Debian Codegraph @

internal/cmd/generator/main.go

raw
1 package main
2
3 import (
4 "bytes"
5 "fmt"
6 "go/ast"
7 "go/format"
8 "go/parser"
9 "go/printer"
10 "go/token"
11 "os"
12 "path/filepath"
13 "runtime"
14 "strings"
15 "text/template"
16 )
17
18 type opType struct {
19 Op string
20 Code string
21 }
22
23 // fieldRunTypes are the kinds of a field which have the opcodes of a run: see internal/encoder.fieldRunOps.
24 var fieldRunTypes = []string{"Int", "Uint", "Float64", "String", "Bool"}
25
26 func createOpType(op, code string) opType {
27 return opType{
28 Op: op,
29 Code: code,
30 }
31 }
32
33 func _main() error {
34 tmpl, err := template.New("").Parse(`// Code generated by internal/cmd/generator. DO NOT EDIT.
35 package encoder
36
37 import (
38 "strings"
39 )
40
41 type CodeType int
42
43 const (
44 {{- range $index, $type := .CodeTypes }}
45 Code{{ $type }} CodeType = {{ $index }}
46 {{- end }}
47 )
48
49 var opTypeStrings = [{{ .OpLen }}]string{
50 {{- range $type := .OpTypes }}
51 "{{ $type.Op }}",
52 {{- end }}
53 }
54
55 type OpType uint16
56
57 const (
58 {{- range $index, $type := .OpTypes }}
59 Op{{ $type.Op }} OpType = {{ $index }}
60 {{- end }}
61 )
62
63 func (t OpType) String() string {
64 if int(t) >= {{ .OpLen }} {
65 return ""
66 }
67 return opTypeStrings[int(t)]
68 }
69
70 func (t OpType) CodeType() CodeType {
71 if strings.Contains(t.String(), "Struct") {
72 if strings.Contains(t.String(), "End") {
73 return CodeStructEnd
74 }
75 return CodeStructField
76 }
77 switch t {
78 case OpArray, OpArrayPtr:
79 return CodeArrayHead
80 case OpArrayElem:
81 return CodeArrayElem
82 case OpSlice, OpSlicePtr:
83 return CodeSliceHead
84 case OpSliceElem:
85 return CodeSliceElem
86 case OpMap, OpMapPtr:
87 return CodeMapHead
88 case OpMapKey:
89 return CodeMapKey
90 case OpMapValue:
91 return CodeMapValue
92 case OpMapEnd:
93 return CodeMapEnd
94 }
95
96 return CodeOp
97 }
98
99 func (t OpType) HeadToPtrHead() OpType {
100 if t == OpStructHead {
101 return OpStructPtrHead
102 }
103 return t
104 }
105
106 func (t OpType) PtrHeadToHead() OpType {
107 if t == OpStructPtrHead {
108 return OpStructHead
109 }
110 return t
111 }
112
113 func (t OpType) FieldToEnd() OpType {
114 idx := strings.Index(t.String(), "Field")
115 if idx == -1 {
116 return t
117 }
118 suffix := t.String()[idx+len("Field"):]
119 if suffix == "" || suffix == "OmitEmpty" {
120 return t
121 }
122 const toEndOffset = 2
123 if strings.Contains(OpType(int(t) + toEndOffset).String(), "End"+suffix) {
124 return OpType(int(t) + toEndOffset)
125 }
126 return t
127 }
128
129 func (t OpType) FieldToOmitEmptyField() OpType {
130 const toOmitEmptyOffset = 1
131 if strings.Contains(OpType(int(t) + toOmitEmptyOffset).String(), "OmitEmpty") {
132 return OpType(int(t) + toOmitEmptyOffset)
133 }
134 return t
135 }
136 `)
137 if err != nil {
138 return err
139 }
140 codeTypes := []string{
141 "Op",
142 "ArrayHead",
143 "ArrayElem",
144 "SliceHead",
145 "SliceElem",
146 "MapHead",
147 "MapKey",
148 "MapValue",
149 "MapEnd",
150 "Recursive",
151 "StructField",
152 "StructEnd",
153 }
154 primitiveTypes := []string{
155 "int", "uint", "float32", "float64", "bool", "string", "bytes", "number",
156 "array", "map", "slice", "struct", "MarshalJSON", "MarshalText",
157 "intString", "uintString", "float32String", "float64String", "boolString", "stringString", "numberString",
158 "intPtr", "uintPtr", "float32Ptr", "float64Ptr", "boolPtr", "stringPtr", "bytesPtr", "numberPtr",
159 "arrayPtr", "mapPtr", "slicePtr", "marshalJSONPtr", "marshalTextPtr", "interfacePtr",
160 "intPtrString", "uintPtrString", "float32PtrString", "float64PtrString", "boolPtrString", "stringPtrString", "numberPtrString",
161 }
162 primitiveTypesUpper := []string{}
163 for _, typ := range primitiveTypes {
164 primitiveTypesUpper = append(primitiveTypesUpper, strings.ToUpper(string(typ[0]))+typ[1:])
165 }
166 opTypes := []opType{
167 createOpType("End", "Op"),
168 createOpType("Interface", "Op"),
169 createOpType("Ptr", "Op"),
170 createOpType("SliceElem", "SliceElem"),
171 createOpType("SliceEnd", "Op"),
172 createOpType("ArrayElem", "ArrayElem"),
173 createOpType("ArrayEnd", "Op"),
174 createOpType("MapKey", "MapKey"),
175 createOpType("MapValue", "MapValue"),
176 createOpType("MapEnd", "Op"),
177 createOpType("Recursive", "Op"),
178 createOpType("RecursivePtr", "Op"),
179 createOpType("RecursiveEnd", "Op"),
180 createOpType("InterfaceEnd", "Op"),
181 }
182 for _, typ := range primitiveTypesUpper {
183 opTypes = append(opTypes, createOpType(typ, "Op"))
184 }
185 // the head of a struct is an opcode of its own: it is followed by the opcode of the first field.
186 opTypes = append(opTypes,
187 opType{Op: "StructHead", Code: "StructField"},
188 opType{Op: "StructPtrHead", Code: "StructField"},
189 )
190 // a field of interface{} has the opcodes of a field of its own, which encode the value as OpInterface does:
191 // the opcode of a value of interface{} is among the first ones, so it is not a primitive type here.
192 for _, typ := range append(primitiveTypesUpper, "Interface", "") {
193 for _, opt := range []string{"", "OmitEmpty"} {
194 op := fmt.Sprintf(
195 "StructField%s%s",
196 opt,
197 typ,
198 )
199 opTypes = append(opTypes, opType{
200 Op: op,
201 Code: "StructField",
202 })
203 }
204 for _, opt := range []string{"", "OmitEmpty"} {
205 op := fmt.Sprintf(
206 "StructEnd%s%s",
207 opt,
208 typ,
209 )
210 opTypes = append(opTypes, opType{
211 Op: op,
212 Code: "StructEnd",
213 })
214 }
215 }
216 // A run of fields of the same kind in a row is encoded by the opcode of the run, which falls through the
217 // cases of the shorter runs: the fields after the first are encoded without a dispatch. The opcodes come
218 // after every other one, so that the offsets between the opcodes of a field, its omitempty and its end
219 // stay as they are.
220 for _, typ := range fieldRunTypes {
221 for _, n := range []string{"3", "2"} {
222 opTypes = append(opTypes, opType{Op: "StructField" + typ + n, Code: "StructField"})
223 }
224 }
225 var b bytes.Buffer
226 if err := tmpl.Execute(&b, struct {
227 CodeTypes []string
228 OpTypes []opType
229 OpLen int
230 }{
231 CodeTypes: codeTypes,
232 OpTypes: opTypes,
233 OpLen: len(opTypes),
234 }); err != nil {
235 return err
236 }
237 path := filepath.Join(repoRoot(), "internal", "encoder", "optype.go")
238 buf, err := format.Source(b.Bytes())
239 if err != nil {
240 return err
241 }
242 return os.WriteFile(path, buf, 0644)
243 }
244
245 // encoderFunctions are the functions of the template which the plain VM has as they are in the encoder
246 // package: the other VMs define them with their indent or their colors.
247 var encoderFunctions = map[string]string{
248 "appendInt": "AppendInt",
249 "appendUint": "AppendUint",
250 "appendFloat64": "AppendFloat64",
251 "appendString": "AppendString",
252 "appendByteSlice": "AppendByteSlice",
253 "appendNumber": "AppendNumber",
254 }
255
256 // callEncoderDirectly makes the calls of encoderFunctions calls of the encoder package: a call through a
257 // function variable is a load and an indirect call, for every value the VM appends.
258 func callEncoderDirectly(f *ast.File) {
259 ast.Inspect(f, func(n ast.Node) bool {
260 call, ok := n.(*ast.CallExpr)
261 if !ok {
262 return true
263 }
264 ident, ok := call.Fun.(*ast.Ident)
265 if !ok {
266 return true
267 }
268 if name, ok := encoderFunctions[ident.Name]; ok {
269 call.Fun = &ast.SelectorExpr{X: ast.NewIdent("encoder"), Sel: ast.NewIdent(name)}
270 }
271 return true
272 })
273 }
274
275 func generateVM() error {
276 file, err := os.ReadFile("vm.go.tmpl")
277 if err != nil {
278 return err
279 }
280 for _, pkg := range []string{"vm", "vm_indent", "vm_color", "vm_color_indent"} {
281 // parsed for each package: the tree of the plain VM is changed.
282 fset := token.NewFileSet()
283 f, err := parser.ParseFile(fset, "", string(file), parser.ParseComments)
284 if err != nil {
285 return err
286 }
287 f.Name.Name = pkg
288 if pkg == "vm" {
289 callEncoderDirectly(f)
290 }
291 var buf bytes.Buffer
292 printer.Fprint(&buf, fset, f)
293 path := filepath.Join(repoRoot(), "internal", "encoder", pkg, "vm.go")
294 source, err := format.Source(buf.Bytes())
295 if err != nil {
296 return err
297 }
298 if err := os.WriteFile(path, source, 0644); err != nil {
299 return err
300 }
301 }
302 return nil
303 }
304
305 func repoRoot() string {
306 _, file, _, _ := runtime.Caller(0)
307 relativePathFromRepoRoot := filepath.Join("internal", "cmd", "generator")
308 return strings.TrimSuffix(filepath.Dir(file), relativePathFromRepoRoot)
309 }
310
311 //go:generate go run main.go
312 func main() {
313 if err := generateVM(); err != nil {
314 panic(err)
315 }
316 if err := _main(); err != nil {
317 panic(err)
318 }
319 }