Go code generators that are easy to write and read.

Writing a Go code generator often means stitching code together from Printf calls and string concatenation. Instead, qudy turns readable templates written in Go into generator source code.

Template

for _, name := range names {
    //`case ~name:
    //`    return "~name"
}

Generator (_gen.go)

for _, name := range names {
    fmt.Printf(`case %v:
    return "%v"
`, name, name)
}

Output, for Red, Green, Blue

case Red:
    return "Red"
case Green:
    return "Green"
case Blue:
    return "Blue"

Trouble with generators

stringer

writes String methods for enum constants · source

g.Printf("func (i %s) String() string {\n", typeName)
g.Printf("\tswitch {\n")
for i, values := range runs {
	if len(values) == 1 {
		g.Printf("\tcase i == %s:\n", &values[0])
		g.Printf("\t\treturn _%s_name_%d\n", typeName, i)
		continue
	}
	// ...
}
g.Printf("\tdefault:\n")
g.Printf("\t\treturn \"%s(\" + strconv.FormatInt(int64(i), 10) + \")\"\n", typeName)
g.Printf("\t}\n")
g.Printf("}\n")

easyjson

writes fast JSON encoders and decoders without reflection · source

if !assumeNonEmpty {
	fmt.Fprintln(g.out, ws+"if "+in+" == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {")
	fmt.Fprintln(g.out, ws+"  out.RawString(`null`)")
	fmt.Fprintln(g.out, ws+"} else {")
} else {
	fmt.Fprintln(g.out, ws+"{")
}
fmt.Fprintln(g.out, ws+"  out.RawByte('{')")
fmt.Fprintln(g.out, ws+"  "+tmpVar+"First := true")
fmt.Fprintln(g.out, ws+"  for "+tmpVar+"Name, "+tmpVar+"Value := range "+in+" {")
fmt.Fprintln(g.out, ws+"    if "+tmpVar+"First { "+tmpVar+"First = false } else { out.RawByte(',') }")

mksyscall

writes system call wrappers for golang.org/x/sys/unix · source

if p.Type == "string" && errvar != "" {
	text += fmt.Sprintf("\tvar _p%d *byte\n", n)
	text += fmt.Sprintf("\t_p%d, %s = BytePtrFromString(%s)\n", n, errvar, p.Name)
	text += fmt.Sprintf("\tif %s != nil {\n\t\treturn\n\t}\n", errvar)
	args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n))
	n++
} else if regexpSlice.FindStringSubmatch(p.Type) != nil {
	text += fmt.Sprintf("\tvar _p%d unsafe.Pointer\n", n)
	text += fmt.Sprintf("\tif len(%s) > 0 {\n\t\t_p%d = unsafe.Pointer(&%s[0])\n\t}", p.Name, n, p.Name)
	text += fmt.Sprintf(" else {\n\t\t_p%d = unsafe.Pointer(&_zero)\n\t}\n", n)
	args = append(args, fmt.Sprintf("uintptr(_p%d)", n), fmt.Sprintf("uintptr(len(%s))", p.Name))
	n++
}

How qudy works

qudy is a command-line tool and a Go library. It reads a template and writes a generator. In a template, comments that start with //`, called output lines, describe the output. The ordinary Go code around them holds the generation logic.

Three nesting dolls show qudy producing a stringer generator, which produces colors_gen.go.
1

Write a template

A Go file that starts with //go:build qudy, so normal builds skip it.

stringer/stringer.go

2

Compile it

qudy turns the template into a generator.

qudy -o stringer/stringer_gen.go stringer/stringer.go
3

Run the generator

go run ./stringer colors Color Red Green Blue > color_string_gen.go

Simple syntax

~name

Inserts the value of a Go variable or field.

~{expr}

Inserts the result of any Go expression.

~"name

Inserts a value as a Go string literal, in quotes.

~@xs

Inserts the elements of a slice, separated by commas, for parameter and argument lists.

v#

Writes a generated name, such as v_qd1, for an identifier less likely to clash with names in the surrounding code.

~//

Starts a note for readers of the template. qudy leaves it out of the output.

Literal text is copied, ~typ inserts Color, and both occurrences of value# become value_qd1.

Get started

qudy needs Go 1.25 or later. Install the command, then follow the tutorial in the README. It builds a complete String generator in one file.

go install github.com/bilus/qudy/cmd/qudy@latest