Code generation with go/ast
suggest changeGo has no macros and no annotation processors. When you need repetitive code, like String() methods for enums, marshalling code or mocks, the usual answer is to generate it: write a small Go program that reads your source code and writes more Go source code.
The standard library has everything needed to do that:
- go/token has positions (
token.FileSet,token.Pos) and token kinds (token.ADD,token.CONST, ...) - go/parser parses Go source into a syntax tree
- go/ast defines the syntax tree nodes and has functions to walk them
- go/format formats source code or a syntax tree exactly like
gofmt - go/types is a type checker, for when syntax alone isn't enough
The go generate command ties it together: it runs the generator programs named in //go:generate comments.
Parsing source into an AST
parser.ParseExpr parses a single expression. ast.Print dumps a tree, which is the best way to learn which node types correspond to which syntax:
package main
import (
"go/ast"
"go/parser"
)
func main() {
expr, err := parser.ParseExpr(`a + b*2`)
if err != nil {
panic(err)
}
// nil FileSet: positions are printed as raw offsets
ast.Print(nil, expr)
}
0 *ast.BinaryExpr {
1 . X: *ast.Ident {
2 . . NamePos: 1
3 . . Name: "a"
4 . }
5 . OpPos: 3
6 . Op: +
7 . Y: *ast.BinaryExpr {
8 . . X: *ast.Ident {
9 . . . NamePos: 5
10 . . . Name: "b"
11 . . }
12 . . OpPos: 6
13 . . Op: *
14 . . Y: *ast.BasicLit {
15 . . . ValuePos: 7
16 . . . ValueEnd: 8
17 . . . Kind: INT
18 . . . Value: "2"
19 . . }
20 . }
21 }
Operator precedence is already resolved: b*2 is a nested BinaryExpr. Note that BasicLit.Value is the literal as written in the source ("2", or "\"hello\"" for a string), not a parsed value.
For a whole file use parser.ParseFile. It needs a token.FileSet, which records file names and line starts so that a compact token.Pos can be turned into file:line:column. Useful mode flags:
parser.ParseCommentskeeps comments in the tree. You need it to read doc comments and directives, and to write comments back when you modify and print code.parser.SkipObjectResolutionskips the old, deprecated identifier resolution (ast.Object). It makes parsing faster and you should use it unless you rely onIdent.Obj. Usego/typesfor real name resolution.
Walking the tree with ast.Inspect
ast.Inspect calls a function for every node, depth first. Return true to descend into the node's children, false to skip them. You do a type switch on the node to find what you're looking for:
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
)
const src = `package shop
import "fmt"
type Item struct {
Name string
Price float64
}
func (it *Item) String() string {
return fmt.Sprintf("%s: %.2f", it.Name, it.Price)
}
func Total(items []Item) float64 {
var sum float64
for _, it := range items {
sum += it.Price
}
fmt.Println("computed total")
return sum
}
`
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "shop.go", src, parser.SkipObjectResolution)
if err != nil {
panic(err)
}
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.FuncDecl:
name := x.Name.Name
if x.Recv != nil {
name = "method " + name
} else {
name = "func " + name
}
fmt.Printf("%s: %s\n", fset.Position(x.Pos()), name)
case *ast.TypeSpec:
fmt.Printf("%s: type %s\n", fset.Position(x.Pos()), x.Name.Name)
case *ast.CallExpr:
// Match calls of the form pkg.Func(...).
if sel, ok := x.Fun.(*ast.SelectorExpr); ok {
if pkg, ok := sel.X.(*ast.Ident); ok {
fmt.Printf("%s: call %s.%s\n", fset.Position(x.Pos()), pkg.Name, sel.Sel.Name)
}
}
}
return true // keep descending into children
})
}
shop.go:5:6: type Item
shop.go:10:1: method String
shop.go:11:9: call fmt.Sprintf
shop.go:14:1: func Total
shop.go:19:2: call fmt.Println
The third argument of ParseFile is the source. It can be a string, []byte or io.Reader. Pass nil to read the file named by the second argument.
Since Go 1.23 there is also ast.Preorder(root), an iterator you can use in a for n := range ast.Preorder(f) loop when you don't need to prune subtrees.
Reading struct fields, tags and directives
Most generators are driven by type declarations. A struct declaration is a *ast.GenDecl with Tok == token.TYPE, holding *ast.TypeSpec values whose Type is a *ast.StructType.
Take this file, model/model.go:
package model
// User is a registered user.
//
//gen:validate
type User struct {
ID int64 `json:"id"`
Name string `json:"name" validate:"required"`
Email string `json:"email,omitempty" validate:"required"`
Tags []string `json:"tags"`
Meta map[string]any
*Base
}
type Base struct {
Created int64
}
This program lists the fields of every struct with their types and tags, and checks for a //gen:validate marker comment:
package main
import (
"fmt"
"go/ast"
"go/parser"
"go/token"
"go/types"
"reflect"
"strconv"
"strings"
)
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "model/model.go", nil, parser.ParseComments|parser.SkipObjectResolution)
if err != nil {
panic(err)
}
for _, decl := range f.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.TYPE {
continue
}
for _, spec := range gd.Specs {
ts := spec.(*ast.TypeSpec)
st, ok := ts.Type.(*ast.StructType)
if !ok {
continue
}
// For "type X struct{...}" the doc comment is attached to the GenDecl.
marked := hasDirective(gd.Doc, "gen:validate")
fmt.Printf("struct %s (gen:validate=%v)\n", ts.Name.Name, marked)
for _, field := range st.Fields.List {
typ := types.ExprString(field.Type) // e.g. "map[string]any"
var tag reflect.StructTag
if field.Tag != nil {
// field.Tag.Value is the literal including backquotes.
s, _ := strconv.Unquote(field.Tag.Value)
tag = reflect.StructTag(s)
}
if len(field.Names) == 0 {
fmt.Printf(" (embedded) %s\n", typ)
continue
}
for _, name := range field.Names {
fmt.Printf(" %-7s %-15s json=%q validate=%q\n",
name.Name, typ, tag.Get("json"), tag.Get("validate"))
}
}
}
}
}
func hasDirective(cg *ast.CommentGroup, name string) bool {
if cg == nil {
return false
}
for _, c := range cg.List {
if strings.TrimPrefix(c.Text, "//") == name {
return true
}
}
return false
}
struct User (gen:validate=true)
ID int64 json="id" validate=""
Name string json="name" validate="required"
Email string json="email,omitempty" validate="required"
Tags []string json="tags" validate=""
Meta map[string]any json="" validate=""
(embedded) *Base
struct Base (gen:validate=false)
Created int64 json="" validate=""
Things to know:
- A field like
X, Y intis one*ast.Fieldwith two names. An embedded field has no names. - The doc comment of
type User struct{...}is inGenDecl.Doc. In a groupedtype ( ... )block eachTypeSpec.Docholds its own comment. CommentGroup.Text()returns the comment text but drops directive lines like//gen:validate, so iterate overCommentGroup.Listto find them. Writing directives without a space after//matches the convention of//go:generateand keeps them out of documentation. See Comments and documentation.types.ExprStringturns a type expression back into its source text, which is often exactly what you want to paste into generated code.
Generating code with text/template and go/format
Let's write a real generator. Given an integer enum type, it generates a String() method and a Parse function, similar to the official stringer tool. See Enums for the pattern itself.
Project layout:
paint/
go.mod
color.go
main.go
cmd/enumgen/main.go
color.go declares the enum and the //go:generate line:
package main
//go:generate go run ./cmd/enumgen -type=Color
type Color int
const (
Red Color = iota
Green
Blue
DarkYellow
)
The generator, cmd/enumgen/main.go, finds the constants with go/ast, fills a text/template and formats the result with format.Source:
// enumgen generates String and Parse methods for an integer enum type.
package main
import (
"bytes"
"flag"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"log"
"os"
"path/filepath"
"strings"
"text/template"
"unicode"
)
func main() {
typeName := flag.String("type", "", "name of the enum type")
flag.Parse()
if *typeName == "" {
log.Fatal("-type is required")
}
// go generate runs us in the directory of the file with the
// //go:generate line and sets GOPACKAGE.
pkg := os.Getenv("GOPACKAGE")
names, err := findConsts(".", *typeName)
if err != nil {
log.Fatal(err)
}
if len(names) == 0 {
log.Fatalf("no constants of type %s found", *typeName)
}
var buf bytes.Buffer
err = tmpl.Execute(&buf, map[string]any{
"Pkg": pkg,
"Type": *typeName,
"Names": names,
})
if err != nil {
log.Fatal(err)
}
// Format the output so we don't have to care about whitespace in the
// template. A syntax error here means the template is wrong.
src, err := format.Source(buf.Bytes())
if err != nil {
log.Fatalf("generated invalid Go: %v\n%s", err, buf.Bytes())
}
out := strings.ToLower(*typeName) + "_enum.go"
if err := os.WriteFile(out, src, 0o644); err != nil {
log.Fatal(err)
}
fmt.Printf("enumgen: wrote %s (%d values)\n", out, len(names))
}
// findConsts returns, in declaration order, the names of constants declared
// with the given type in a const block, e.g. "Red Color = iota".
// It assumes values are consecutive iota values starting at 0.
func findConsts(dir, typeName string) ([]string, error) {
files, err := filepath.Glob(filepath.Join(dir, "*.go"))
if err != nil {
return nil, err
}
fset := token.NewFileSet()
var names []string
for _, path := range files {
if strings.HasSuffix(path, "_test.go") || strings.HasSuffix(path, "_enum.go") {
continue
}
f, err := parser.ParseFile(fset, path, nil, parser.SkipObjectResolution)
if err != nil {
return nil, err
}
for _, decl := range f.Decls {
gd, ok := decl.(*ast.GenDecl)
if !ok || gd.Tok != token.CONST {
continue
}
// In "const ( A T = iota; B; C )" only the first spec has a type.
// Later specs repeat the previous type and expression implicitly.
inBlock := false
for _, spec := range gd.Specs {
vs := spec.(*ast.ValueSpec)
if vs.Type != nil {
id, ok := vs.Type.(*ast.Ident)
inBlock = ok && id.Name == typeName
} else if len(vs.Values) > 0 {
inBlock = false // new explicit value without a type
}
if !inBlock {
continue
}
for _, n := range vs.Names {
names = append(names, n.Name)
}
}
}
}
return names, nil
}
// kebab turns "DarkYellow" into "dark-yellow".
func kebab(s string) string {
var b strings.Builder
for i, r := range s {
if unicode.IsUpper(r) {
if i > 0 {
b.WriteByte('-')
}
r = unicode.ToLower(r)
}
b.WriteRune(r)
}
return b.String()
}
var tmpl = template.Must(template.New("enum").Funcs(template.FuncMap{
"kebab": kebab,
}).Parse(`// Code generated by enumgen -type={{.Type}}; DO NOT EDIT.
package {{.Pkg}}
import "fmt"
var _{{.Type}}Names = [...]string{
{{- range $i, $n := .Names}}
{{$n}}: "{{kebab $n}}",
{{- end}}
}
func (v {{.Type}}) String() string {
if v >= 0 && int(v) < len(_{{.Type}}Names) {
return _{{.Type}}Names[v]
}
return fmt.Sprintf("{{.Type}}(%d)", int(v))
}
// Parse{{.Type}} returns the {{.Type}} whose String() is s.
func Parse{{.Type}}(s string) ({{.Type}}, error) {
for i, name := range _{{.Type}}Names {
if name == s {
return {{.Type}}(i), nil
}
}
return 0, fmt.Errorf("invalid {{.Type}} %q", s)
}
`))
Run it with go generate:
$ go generate ./...
enumgen: wrote color_enum.go (4 values)
The generated color_enum.go:
// Code generated by enumgen -type=Color; DO NOT EDIT.
package main
import "fmt"
var _ColorNames = [...]string{
Red: "red",
Green: "green",
Blue: "blue",
DarkYellow: "dark-yellow",
}
func (v Color) String() string {
if v >= 0 && int(v) < len(_ColorNames) {
return _ColorNames[v]
}
return fmt.Sprintf("Color(%d)", int(v))
}
// ParseColor returns the Color whose String() is s.
func ParseColor(s string) (Color, error) {
for i, name := range _ColorNames {
if name == s {
return Color(i), nil
}
}
return 0, fmt.Errorf("invalid Color %q", s)
}
Notice that format.Source aligned the array entries. Without it you'd have to fight text/template whitespace to get readable output. Using the constant names as array indices is a cheap safety net: if two constants ever get the same value, the generated file fails to compile.
Using it from main.go:
package main
import "fmt"
func main() {
fmt.Println(Green, DarkYellow)
fmt.Printf("%v %d\n", Blue, Blue)
c, err := ParseColor("dark-yellow")
fmt.Println(c, err)
_, err = ParseColor("purple")
fmt.Println(err)
fmt.Println(Color(42))
}
$ go run .
green dark-yellow
blue 2
dark-yellow <nil>
invalid Color "purple"
Color(42)
How go generate works
go generate ./...scans.gofiles for lines starting with//go:generateand runs the rest of the line as a command. It isn't run bygo buildorgo test; you run it yourself and commit the generated files.- The command runs in the directory of the file containing the directive, with environment variables
GOFILE,GOLINE,GOPACKAGE,GOARCH,GOOSandDOLLARset. go run ./cmd/enumgenkeeps the generator in the same module, so there's nothing to install. For a third-party tool, declare it withgo get -tool golang.org/x/tools/cmd/stringer(Go 1.24+) and use//go:generate go tool stringer -type=Color. The version is then pinned ingo.mod.go generate -nprints the commands without running them,-xprints and runs them,-run regexplimits which directives run.
The first line of the output, // Code generated ... DO NOT EDIT., is a convention recognized by tools: it must match the regular expression ^// Code generated .* DO NOT EDIT\.$ and appear before the package clause. Linters skip such files, and GitHub collapses them in diffs.
To make sure generated files are never stale, run go generate ./... in CI followed by git diff --exit-code.
Building code from AST nodes
Instead of text templates you can construct the syntax tree directly and print it with format.Node:
package main
import (
"go/ast"
"go/format"
"go/token"
"os"
"strconv"
)
func main() {
// func Clamp(v int) int {
// if v > 100 { return 100 }
// return v
// }
limit := &ast.BasicLit{Kind: token.INT, Value: strconv.Itoa(100)}
fn := &ast.FuncDecl{
Name: ast.NewIdent("Clamp"),
Type: &ast.FuncType{
Params: &ast.FieldList{List: []*ast.Field{{
Names: []*ast.Ident{ast.NewIdent("v")},
Type: ast.NewIdent("int"),
}}},
Results: &ast.FieldList{List: []*ast.Field{{
Type: ast.NewIdent("int"),
}}},
},
Body: &ast.BlockStmt{List: []ast.Stmt{
&ast.IfStmt{
Cond: &ast.BinaryExpr{X: ast.NewIdent("v"), Op: token.GTR, Y: limit},
Body: &ast.BlockStmt{List: []ast.Stmt{
&ast.ReturnStmt{Results: []ast.Expr{limit}},
}},
},
&ast.ReturnStmt{Results: []ast.Expr{ast.NewIdent("v")}},
}},
}
file := &ast.File{
Name: ast.NewIdent("mathx"),
Decls: []ast.Decl{fn},
}
// A fresh FileSet is fine: the nodes have no positions.
if err := format.Node(os.Stdout, token.NewFileSet(), file); err != nil {
panic(err)
}
}
package mathx
func Clamp(v int) int {
if v > 100 {
return 100
}
return v
}
This guarantees syntactically valid output, but it's verbose: seven lines of output took thirty lines of code. A common middle ground is to parse small snippets with parser.ParseExpr and splice the resulting nodes into a tree. In practice, templates plus format.Source are the most popular choice for generating new files, and building AST nodes is mostly used for modifying existing code.
Rewriting existing code
Because the parser keeps positions and comments, you can parse a file, change nodes in place and print it back. This is how tools like gofmt -r and go fix work.
The program below modernizes old.go.txt: it replaces the deprecated ioutil.ReadFile with os.ReadFile and exports loadConfig:
package config
import (
"io/ioutil"
"strings"
)
// loadConfig reads the config file.
func loadConfig(path string) (string, error) {
data, err := ioutil.ReadFile(path) // read it all
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
func Init() {
// Load default config.
s, _ := loadConfig("app.conf")
_ = s
}
package main
import (
"go/ast"
"go/format"
"go/parser"
"go/token"
"os"
"strconv"
)
func main() {
fset := token.NewFileSet()
// ParseComments is needed so the printer can write comments back.
f, err := parser.ParseFile(fset, "old.go.txt", nil, parser.ParseComments)
if err != nil {
panic(err)
}
ast.Inspect(f, func(n ast.Node) bool {
switch x := n.(type) {
case *ast.Ident:
// Rename loadConfig to LoadConfig: both the declaration
// and the call sites are *ast.Ident nodes.
if x.Name == "loadConfig" {
x.Name = "LoadConfig"
}
case *ast.SelectorExpr:
// ioutil.ReadFile(...) -> os.ReadFile(...)
if pkg, ok := x.X.(*ast.Ident); ok && pkg.Name == "ioutil" && x.Sel.Name == "ReadFile" {
pkg.Name = "os"
}
case *ast.ImportSpec:
// Replace the import path. Keep the node, so comments and
// positions stay attached to the right place.
if path, _ := strconv.Unquote(x.Path.Value); path == "io/ioutil" {
x.Path.Value = strconv.Quote("os")
}
}
return true
})
// Imports are no longer sorted; this sorts them in place.
ast.SortImports(fset, f)
if err := format.Node(os.Stdout, fset, f); err != nil {
panic(err)
}
}
package config
import (
"os"
"strings"
)
// loadConfig reads the config file.
func LoadConfig(path string) (string, error) {
data, err := os.ReadFile(path) // read it all
if err != nil {
return "", err
}
return strings.TrimSpace(string(data)), nil
}
func Init() {
// Load default config.
s, _ := LoadConfig("app.conf")
_ = s
}
Comments survived, including the end-of-line one. But the doc comment still says loadConfig: comments are stored separately in File.Comments and are just text, so you have to update them yourself.
Modifying existing nodes works well. Adding or deleting nodes is harder, because the printer places comments based on positions, and new nodes have no positions. Comments can end up in odd places. For heavier refactoring use golang.org/x/tools/go/ast/astutil, which has Apply (a walker that can replace, insert and delete nodes) and AddImport / DeleteImport.
Matching by name, as above, is also naive: it would rename an unrelated local variable called loadConfig and would rewrite ioutil.ReadFile even if ioutil were a local variable. Correct tools resolve names with go/types.
When syntax isn't enough: go/types
The AST only knows what's written. In Delay Duration, it can't tell you that Duration is an alias of time.Duration, and it can't compute the value of Retries * time.Second. The type checker in go/types can:
package main
import (
"fmt"
"go/ast"
"go/importer"
"go/parser"
"go/token"
"go/types"
)
const src = `package demo
import "time"
type Duration = time.Duration
type Event struct {
Name string
At time.Time
Delay Duration
}
const Retries = 3
var timeout = Retries * time.Second
`
func main() {
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, "demo.go", src, 0)
if err != nil {
panic(err)
}
// The "source" importer type-checks imported packages from source,
// so it works without precompiled export data.
conf := types.Config{Importer: importer.ForCompiler(fset, "source", nil)}
info := &types.Info{
Types: map[ast.Expr]types.TypeAndValue{},
}
pkg, err := conf.Check("demo", fset, []*ast.File{f}, info)
if err != nil {
panic(err)
}
// Fields with their resolved types. Syntax alone can't tell that
// Delay is really time.Duration.
ev := pkg.Scope().Lookup("Event").Type().Underlying().(*types.Struct)
for i := range ev.NumFields() {
fld := ev.Field(i)
t := fld.Type()
// types.Unalias follows an alias to the type it stands for.
fmt.Printf("%-5s %-14s -> %s\n", fld.Name(), t, types.Unalias(t))
}
// Values of constant expressions are computed by the type checker.
ast.Inspect(f, func(n ast.Node) bool {
if vs, ok := n.(*ast.ValueSpec); ok {
tv := info.Types[vs.Values[0]]
fmt.Printf("%s: type=%s value=%v\n", vs.Names[0].Name, tv.Type, tv.Value)
}
return true
})
}
Name string -> string
At time.Time -> time.Time
Delay demo.Duration -> time.Duration
Retries: type=untyped int value=3
timeout: type=time.Duration value=3000000000
You fill in only the types.Info maps you need: Types for expressions, Defs and Uses to map identifiers to the objects they declare or refer to (that's what a correct rename needs), Selections for method and field selectors.
For a real generator that has to load a whole package with its dependencies, build tags and modules, use golang.org/x/tools/go/packages. packages.Load runs the go command to find the files and returns parsed and type-checked packages. That's what stringer, mockgen and most serious generators use. With go/types the enum generator above could also handle explicit values, gaps and expressions like 1 << iota, since it gets the computed constant values.
Tips
- Always run generated code through
format.Sourceorformat.Node. It catches template bugs early (a syntax error points at the generated line) and makes output stable, so diffs of generated files stay small. - Start the output with
// Code generated by <tool>; DO NOT EDIT.so that people and tools know not to edit it. - Make output deterministic. Iterating over a Go map gives random order; sort keys first, or every
go generaterun creates a diff. - Give generated files a recognizable suffix (
_enum.go,_string.go,.pb.go) and skip them when your generator parses the package, or a second run reads its own output. - Report errors with positions:
fset.Position(node.Pos())givesfile:line:column, which editors turn into clickable links. - Consider whether you need generation at all. Generics (Go 1.18+) remove much of the need for type-specific copies of code, and reflection is fine when performance isn't critical. Generated code wins when you want compile-time checking and no runtime cost.