Could anyone steer me to some good examples of generating and printing Go code from scratch using go/ast and go/printer? I've played around a bit with generating some files from built-from-scratch ASTs, and it seems like I can basically count on the printer to handle formatting by setting positions to the default...as long as there aren't any comments in the file. Once those come into play, it seems like there needs to be position data in the AST or else the printer just sticks the comments in unexpected places. The documentation seems to mostly assume that you're modifying parser output and doesn't get a lot into generating files from scratch, so I'd love to look over some existing examples if there are any good ones out there
评论:
mewkiz:
bradfitz:Probably not the best place to start, but if you would like to see an example of an application using go/ast to generate Go code from scratch, have a look at ll2go (https://github.com/decomp/ll2go). It decompiles LLVM IR (a platform independent assembly) to Go source code.
The ll2go tool is unfortunately not yet go-getable (this work is tracked by the issue https://github.com/decomp/decompilation/issues/167). However, you may look at the code and get an idea for how ast.File's containing ast.FuncDecl's may be created and printed.
robertbieber:It's really painful and go/ast isn't really designed for code generation. Don't be ashamed to just use print statements to write out your code. You can then format it with go/format. That's what the google-api-go-generator does.
bradfitz:Ugh, the lost potential is so sad though :(
natefinch:Robert Griesemer (author of existing go/ packages) has plans or is working on a new go/ set of packages with a nicer API which would permit many more things like this easily.
robertbieber:That would be amazing. I have at least a couple projects percolating in my head that revolve around generating code from scratch.
daveddev:That would be so great. Is there perchance an issue out there somewhere I could follow to get updates on the progress?
klaaax:https://github.com/campoy/jsonenums
https://www.youtube.com/watch?v=YgnD27GFcyA http://talks.golang.org/2015/json.slide#1
would really like to see a good tutorial about code generation, ast/token/parser packages in Go. It's often hard to tell what is what and how to generate go files the proper way.
