Join GitHub today
GitHub is home to over 50 million developers working together to host and review code, manage projects, and build software together.Sign up
x/tools/go/ast/astutil: ast replace could not handled expression parsed from string #29615
What version of Go are you using (
Looks like the position information is wrong after replacement. I suspect this is because your manually created node has no position info, so go/printer treats it sensibly, whereas the ParseExpr node has position information, which go/printer tries to respect, to no avail.
I’m not sure what the right fix for this is without digging a bit, and realistically that isn’t going to happen soon. My apologies. Is there some form of workaround (aside from creating the AST manually) that I could advise on? Note that one convenient hack is that you can put just about anything in an ast.Ident. I often use them to smuggle in a bunch of pre-formatted code.
cc @griesemer as FYI
@josharian Thanks for you input. From the docs on ParseExpr it mentions that position information is undefined.
Also there is another problem. Even if I replace ast node manually I need to somehow sync token.File which is inside token.FileSet otherwise token.File lines, linesInfo, size may be incorrect. Is there a way of dealing with this in easy way?
@griesemer Maybe it make sense to extend astutil.Apply so it can accept token.FileSet or token.File and do all the handling?
@anjmao If you replace your call of
newCallExpr, err := parser.ParseExpr("log.Println(\"new value\")")
with the newer function
newCallExpr, err := parser.ParseExprFrom(fset, "", `log.Println("new value")`, 0)
then it works (at least for the example you are giving). The problem with
(I haven't looked into why it also inserts a new empty line, both with the hand-crafted and the parsed call replacement.)
There may be other issues still, but at least this seems to fix the problem. We are aware that all of this is suboptimal (the go/ast was probably one of the first if not the first Go package that made it into the std lib and it shows its age). There are (long term) plans to improve the situation significantly by making formatting independent of position information, but unfortunately there are more pressing issues at the moment.
I'm going to close this for now. Feel free to re-open (or file a new issue) if you find other problems.