Gomacro: code generation made easy and fun

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.

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.

Video

Stay connected

You can subscribe to our newsletter to stay updated on the latest news and announcements. Follow us on social media to join our community and engage with other attendees, speakers, and staff. We're on Twitter, Mastodon, Youtube and Facebook. Don't forget to use our official hashtag #GoLab2023 to share your experience and connect with other attendees on social media.

Subscribe to our newsletter

We hate spam just as much as you do, which is why we promise to only send you relevant communications. We respect your privacy and will never share your information with third parties.
©2023 GoLab | The international conference on Go in Florence-Design & devCantiere Creativo-Made withDatoCMS