Debian Codegraph @

syntax/gen_token_parse.go

raw
1 // Copyright (c) 2026, Daniel Martí <[email protected]>
2 // See LICENSE for licensing information
3
4 //go:build ignore
5
6 // gen_token_parse emits tokens_parse.go with an [encoding.TextUnmarshaler]
7 // implementation per exported operator type declared in tokens.go.
8 package main
9
10 import (
11 "bytes"
12 "go/ast"
13 "go/format"
14 "go/parser"
15 "go/token"
16 "log"
17 "os"
18 "strings"
19 "text/template"
20 )
21
22 func main() {
23 fset := token.NewFileSet()
24 file, err := parser.ParseFile(fset, "tokens.go", nil, parser.ParseComments)
25 if err != nil {
26 log.Fatal(err)
27 }
28
29 operatorTypes := map[string]bool{}
30 for _, decl := range file.Decls {
31 gd, ok := decl.(*ast.GenDecl)
32 if !ok || gd.Tok != token.TYPE {
33 continue
34 }
35 for _, spec := range gd.Specs {
36 ts := spec.(*ast.TypeSpec)
37 id, ok := ts.Type.(*ast.Ident)
38 if ok && id.Name == "token" && ts.Name.IsExported() {
39 operatorTypes[ts.Name.Name] = true
40 }
41 }
42 }
43
44 type entry struct {
45 Name string
46 Str string
47 }
48 type group struct {
49 Name string
50 Entries []entry
51 }
52 var groups []group
53
54 for _, decl := range file.Decls {
55 gd, ok := decl.(*ast.GenDecl)
56 if !ok || gd.Tok != token.CONST {
57 continue
58 }
59 first := gd.Specs[0].(*ast.ValueSpec)
60 if len(first.Values) == 0 {
61 continue
62 }
63 typeName := operatorExprType(first.Values[0])
64 if !operatorTypes[typeName] {
65 continue
66 }
67
68 g := group{Name: typeName}
69 for _, spec := range gd.Specs {
70 vs := spec.(*ast.ValueSpec)
71 if vs.Doc != nil && strings.Contains(vs.Doc.Text(), "Deprecated:") {
72 continue
73 }
74 str := lineComment(vs)
75 if str == "" {
76 log.Fatalf("no line comment for %s", vs.Names[0].Name)
77 }
78 for _, name := range vs.Names {
79 g.Entries = append(g.Entries, entry{Name: name.Name, Str: str})
80 }
81 }
82 if len(g.Entries) > 0 {
83 groups = append(groups, g)
84 }
85 }
86
87 var buf bytes.Buffer
88 if err := outputTmpl.Execute(&buf, groups); err != nil {
89 log.Fatal(err)
90 }
91 out, err := format.Source(buf.Bytes())
92 if err != nil {
93 log.Fatalf("format: %v\n%s", err, buf.Bytes())
94 }
95 if err := os.WriteFile("tokens_parse.go", out, 0o644); err != nil {
96 log.Fatal(err)
97 }
98 }
99
100 // operatorExprType returns the operator type name in expressions of the form
101 // `Type(name)` or `Type(name) + iota`, or "" otherwise (e.g. plain aliases).
102 func operatorExprType(expr ast.Expr) string {
103 if be, ok := expr.(*ast.BinaryExpr); ok {
104 return operatorExprType(be.X)
105 }
106 if ce, ok := expr.(*ast.CallExpr); ok {
107 if id, ok := ce.Fun.(*ast.Ident); ok {
108 return id.Name
109 }
110 }
111 return ""
112 }
113
114 // lineComment returns the first whitespace-separated word of the trailing
115 // line comment of vs, which is the operator's source form. Some comments
116 // have trailing documentation like "// :# with [LangZsh]"; we want ":#".
117 func lineComment(vs *ast.ValueSpec) string {
118 if vs.Comment == nil {
119 return ""
120 }
121 fields := strings.Fields(vs.Comment.Text())
122 if len(fields) == 0 {
123 return ""
124 }
125 return fields[0]
126 }
127
128 var outputTmpl = template.Must(template.New("").Parse(`
129 // Code generated by gen_token_parse.go; DO NOT EDIT.
130
131 package syntax
132
133 import "fmt"
134 {{range .}}
135 func (o *{{.Name}}) UnmarshalText(text []byte) error {
136 switch string(text) {
137 {{- range .Entries}}
138 case {{printf "%q" .Str}}:
139 *o = {{.Name}}
140 {{- end}}
141 default:
142 return fmt.Errorf("invalid {{.Name}}: %q", text)
143 }
144 return nil
145 }
146 {{end}}
147 `[1:]))