Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GoLang ast: generating and printing a tree without position information

I'm looking to make a tool which generates method stubs from some given input. I've seen the ast package, but it seems to represent an already parsed AST, which has information about where in the source file everything is. Importantly, you need to provide source information

I'm looking at generating a source file programatically, so I have no idea where in the final file my AST nodes will end up.

I'm wondering:

  • Is there a better AST tool which lets you generate code without giving source file position information?
  • If I give dummy information for positions in the ast package, will it pretty-print properly (i.e. ignore the position information)?

I realize I could do this all with text generation, but that seems type-unsafe and harder to deal with.

like image 418
jmite Avatar asked Nov 01 '16 17:11

jmite


1 Answers

Consider https://github.com/lu4p/astextract which has a nicer AST to work with that can be printed into go code.

I know you've thought about this, but using text/template and goimports on the resulting string is actually quite reasonable. It's way easier to write and it translates much better to writing normal go code. As you note, it's not type-safe (which is fine because running goimports on it later enforces that). The biggest con is actually that it's hard to test (we ended up writing a set of generated tests and manual written tests).

(EDIT: just realized how old of a question this is - going to leave my answer up for others as I'm sure you've found some way to solve this for yourself by now)

like image 124
Liyan Chang Avatar answered Oct 17 '22 03:10

Liyan Chang