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"
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")
//`func (i ~typeName) String() string { //` switch { for i, values := range runs { if len(values) == 1 { //` case i == ~{&values[0]}: //` return _~{typeName}_name_~i continue } // ... } //` default: //` return "~typeName(" + strconv.FormatInt(int64(i), 10) + ")" //` } //`}
fmt.Printf(`func (i %v) String() string { switch { `, typeName) for i, values := range runs { if len(values) == 1 { fmt.Printf(` case i == %v: return _%v_name_%v `, &values[0], typeName, i) continue } // ... } fmt.Printf(` default: return "%v(" + strconv.FormatInt(int64(i), 10) + ")" } } `, typeName)
func (i Color) String() string {
switch {
case i == Red:
return _Color_name_0
case i == Blue:
return _Color_name_2
default:
return "Color(" + strconv.FormatInt(int64(i), 10) + ")"
}
}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(',') }")
if !assumeNonEmpty { //`~{ws}if ~in == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 { //`~{ws} out.RawString(`null`) //`~{ws}} else { } else { //`~{ws}{ } //`~{ws} out.RawByte('{') //`~{ws} ~{tmpVar}First := true //`~{ws} for ~{tmpVar}Name, ~{tmpVar}Value := range ~in { //`~{ws} if ~{tmpVar}First { ~{tmpVar}First = false } else { out.RawByte(',') }
if !assumeNonEmpty { fmt.Printf("%vif %v == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {\n%v out.RawString(`null`)\n%v} else {\n", ws, in, ws, ws) } else { fmt.Printf(`%v{ `, ws) } fmt.Printf(`%v out.RawByte('{') %v %vFirst := true %v for %vName, %vValue := range %v { %v if %vFirst { %vFirst = false } else { out.RawByte(',') } `, ws, ws, tmpVar, ws, tmpVar, tmpVar, in, ws, tmpVar, tmpVar)
if in.M == nil && (out.Flags & jwriter.NilMapAsEmpty) == 0 {
out.RawString(`null`)
} else {
out.RawByte('{')
v3First := true
for v3Name, v3Value := range in.M {
if v3First { v3First = false } else { out.RawByte(',') }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++ }
if p.Type == "string" && errvar != "" { //` var _p~n *byte //` _p~n, ~errvar = BytePtrFromString(~p.Name) //` if ~errvar != nil { //` return //` } args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) n++ } else if regexpSlice.FindStringSubmatch(p.Type) != nil { //` var _p~n unsafe.Pointer //` if len(~p.Name) > 0 { //` _p~n = unsafe.Pointer(&~p.Name[0]) //` } else { //` _p~n = unsafe.Pointer(&_zero) //` } args = append(args, fmt.Sprintf("uintptr(_p%d)", n), fmt.Sprintf("uintptr(len(%s))", p.Name)) n++ }
if p.Type == "string" && errvar != "" { fmt.Printf(` var _p%v *byte _p%v, %v = BytePtrFromString(%v) if %v != nil { return } `, n, n, errvar, p.Name, errvar) args = append(args, fmt.Sprintf("uintptr(unsafe.Pointer(_p%d))", n)) n++ } else if regexpSlice.FindStringSubmatch(p.Type) != nil { fmt.Printf(` var _p%v unsafe.Pointer if len(%v) > 0 { _p%v = unsafe.Pointer(&%v[0]) } else { _p%v = unsafe.Pointer(&_zero) } `, n, p.Name, n, p.Name, n) args = append(args, fmt.Sprintf("uintptr(_p%d)", n), fmt.Sprintf("uintptr(len(%s))", p.Name)) n++ }
var _p0 *byte
_p0, err = BytePtrFromString(path)
if err != nil {
return
}
var _p1 unsafe.Pointer
if len(buf) > 0 {
_p1 = unsafe.Pointer(&buf[0])
} else {
_p1 = unsafe.Pointer(&_zero)
}
var _p2 *byte
_p2, err = BytePtrFromString(name)
if err != nil {
return
}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.
A Go file that starts with //go:build qudy, so normal builds skip it.
stringer/stringer.go
qudy turns the template into a generator.
qudy -o stringer/stringer_gen.go stringer/stringer.go
go run ./stringer colors Color Red Green Blue > color_string_gen.go
//go:generate sh -c "go run ./stringer colors Color Red Green Blue > color_string_gen.go"
~nameInserts the value of a Go variable or field.
~{expr}Inserts the result of any Go expression.
~"nameInserts a value as a Go string literal, in quotes.
~@xsInserts 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.
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