Abstract
Go code generation was traditionally still a difficult topic. Armed with Gomacro REPL, we will see how creating and manipulating abstract syntax trees (go/ast.Node) becomes as easy as adding few keystrokes to a statement or declaration. And you can do it interactively: much more fun and productive. Go code generation, while easier than in many other languages, is still mostly considered an advanced topic. Borrowing ideas from code generation languages, we propose an alternative approach that is easy, interactive and fun. Using Go interactive interpreter Gomacro, we show how creating and manipulating abstract syntax trees of go/ast.Node becomes a matter of adding few keystrokes to an expression, statement or declaration. A quick example: x + y is a Go expression that could be saved, compiled and executed. ~"{x + y} is another Go expression that, when typed at Gomacro prompt, gets executed immediately and returns an ast.Node containing the parsed abstract syntax tree &ast.BinaryExpr{X: &ast.Ident{Name: "x"}, Op: token.ADD, Y: &ast.Ident{Name: "y"}} which can be inspected and manipulated directly at the prompt. Compare it to the traditional approach to generate such ast.BinaryExpr: save the string "x + y" somewhere (in a file, or as a string in source code…), write code that invokes one of the functions go/parser.Parse*, compile and execute it. By combining two additional Lisp code generation techniques supported by Gomacro, namely quasiquoting and macros, a full code-generating program often consists of the skeleton code to generate, wrapped inside ~"{}, intermixed with normal Go code that loops and sets the non-constant parts. For reference, more than 75% of Gomacro ‘fast’ interpreter source code is generated with this mechanism. In the author’s opinion, using a traditional approach to generate the same code would have been simply too onerous. And much less fun.