Debian Codegraph @

codec/codecgen/gen.go

raw symbols SCIP
1 // Copyright (c) 2012-2020 Ugorji Nwoke. All rights reserved.
2 // Use of this source code is governed by a MIT license found in the LICENSE file.
3
4 // codecgen generates static implementations of the encoder and decoder functions
5 // for a given type, bypassing reflection, and giving some performance benefits in terms of
6 // wall and cpu time, and memory usage.
7 //
8 // Benchmarks (as of Dec 2018) show that codecgen gives about
9 //
10 // - for binary formats (cbor, etc): 25% on encoding and 30% on decoding to/from []byte
11 // - for text formats (json, etc): 15% on encoding and 25% on decoding to/from []byte
12 //
13 // Note that (as of Dec 2018) codecgen completely ignores
14 //
15 // - MissingFielder interface
16 // (if you types implements it, codecgen ignores that)
17 // - decode option PreferArrayOverSlice
18 // (we cannot dynamically create non-static arrays without reflection)
19 //
20 // In explicit package terms: codecgen generates codec.Selfer implementations for a set of types.
21 package main
22
23 import (
24 "bufio"
25 "bytes"
26 "errors"
27 "flag"
28 "fmt"
29 "go/ast"
30 "go/parser"
31 "go/token"
32 "math/rand"
33 "os"
34 "os/exec"
35 "path/filepath"
36 "regexp"
37 "runtime/debug"
38 "strconv"
39 "strings"
40 "text/template"
41 "time"
42 )
43
44 // MARKER: keep in sync with ../gen.go (genVersion) and ../go.mod (module version)
45 const (
46 codecgenModuleVersion = `1.2.7` // default version - overridden if available via go.mod
47 minimumCodecVersion = `1.2.7`
48 genVersion = 25
49 )
50
51 const genCodecPkg = "codec1978" // MARKER: keep in sync with ../gen.go
52
53 const genFrunMainTmpl = `// +build ignore
54
55 // Code generated - temporary main package for codecgen - DO NOT EDIT.
56
57 package main
58 {{ if .Types }}import "{{ .ImportPath }}"{{ end }}
59 func main() {
60 {{ $.PackageName }}.CodecGenTempWrite{{ .RandString }}()
61 }
62 `
63
64 // const genFrunPkgTmpl = `// +build codecgen
65 const genFrunPkgTmpl = `
66
67 // Code generated - temporary package for codecgen - DO NOT EDIT.
68
69 package {{ $.PackageName }}
70
71 import (
72 {{ if not .CodecPkgFiles }}{{ .CodecPkgName }} "{{ .CodecImportPath }}"{{ end }}
73 "os"
74 "reflect"
75 "bytes"
76 "strings"
77 "go/format"
78 "fmt"
79 )
80
81 func codecGenBoolPtr(b bool) *bool {
82 return &b
83 }
84
85 func CodecGenTempWrite{{ .RandString }}() {
86 os.Remove("{{ .OutFile }}")
87 fout, err := os.Create("{{ .OutFile }}")
88 if err != nil {
89 panic(err)
90 }
91 defer fout.Close()
92
93 var bJO, bS2A, bOE *bool
94 _, _, _ = bJO, bS2A, bOE
95 {{ if .JsonOnly }}bJO = codecGenBoolPtr({{ boolvar .JsonOnly }}){{end}}
96 {{ if .StructToArrayAlways }}bS2A = codecGenBoolPtr({{ boolvar .StructToArrayAlways }}){{end}}
97 {{ if .OmitEmptyAlways }}bOE = codecGenBoolPtr({{ boolvar .OmitEmptyAlways }}){{end}}
98
99 var typs []reflect.Type
100 var typ reflect.Type
101 var numfields int
102 {{ range $index, $element := .Types }}
103 var t{{ $index }} {{ . }}
104 typ = reflect.TypeOf(t{{ $index }})
105 typs = append(typs, typ)
106 if typ.Kind() == reflect.Struct { numfields += typ.NumField() } else { numfields += 1 }
107 {{ end }}
108
109 // println("initializing {{ .OutFile }}, buf size: {{ .AllFilesSize }}*16",
110 // {{ .AllFilesSize }}*16, "num fields: ", numfields)
111 var out = bytes.NewBuffer(make([]byte, 0, numfields*1024)) // {{ .AllFilesSize }}*16
112 var warnings = {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}Gen(out,
113 "{{ .BuildTag }}", "{{ .PackageName }}", "{{ .RandString }}", {{ .NoExtensions }},
114 bJO, bS2A, bOE,
115 {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}NewTypeInfos(strings.Split("{{ .StructTags }}", ",")),
116 typs...)
117
118 for _, warning := range warnings {
119 fmt.Fprintf(os.Stderr, "warning: %s\n", warning)
120 }
121
122 bout, err := format.Source(out.Bytes())
123 // println("... lengths: before formatting: ", len(out.Bytes()), ", after formatting", len(bout))
124 if err != nil {
125 fout.Write(out.Bytes())
126 panic(err)
127 }
128 fout.Write(bout)
129 }
130
131 `
132
133 var genFuncs template.FuncMap
134
135 func init() {
136 genFuncs = make(template.FuncMap)
137 genFuncs["boolvar"] = func(x *bool) bool { return *x }
138 }
139
140 type regexFlagValue struct {
141 v *regexp.Regexp
142 }
143
144 func (v *regexFlagValue) Set(s string) (err error) {
145 // fmt.Printf("calling regexFlagValue.Set with %s\n", s)
146 v.v, err = regexp.Compile(s)
147 return
148 }
149 func (v *regexFlagValue) Get() interface{} { return v.v }
150 func (v *regexFlagValue) String() string { return fmt.Sprintf("%v", v.v) }
151
152 // boolFlagValue can be set to true or false, or unset as nil (default)
153 type boolFlagValue struct {
154 v *bool
155 }
156
157 func (v *boolFlagValue) Set(s string) (err error) {
158 // fmt.Printf("calling boolFlagValue.Set with %s\n", s)
159 b, err := strconv.ParseBool(s)
160 if err == nil {
161 v.v = &b
162 }
163 return
164 }
165 func (v *boolFlagValue) Get() interface{} { return v.v }
166 func (v *boolFlagValue) String() string { return fmt.Sprintf("%#v", v.v) }
167
168 type mainCfg struct {
169 CodecPkgName string
170 CodecImportPath string
171 ImportPath string
172 OutFile string
173 PackageName string
174 RandString string
175 BuildTag string
176 StructTags string
177 Types []string
178 AllFilesSize int64
179 CodecPkgFiles bool
180 NoExtensions bool
181
182 JsonOnly *bool
183 StructToArrayAlways *bool
184 OmitEmptyAlways *bool
185
186 uid int64
187 goRunTags string
188 regexName *regexp.Regexp
189 notRegexName *regexp.Regexp
190
191 keepTempFile bool // !deleteTempFile
192 }
193
194 // mainGen is given a list of *.go files to parse, and an output file (fout).
195 //
196 // It finds all types T in the files, and it creates 2 tmp files (frun).
197 // - main package file passed to 'go run'
198 // - package level file which calls *genRunner.Selfer to write Selfer impls for each T.
199 //
200 // We use a package level file so that it can reference unexported types in the package being worked on.
201 // Tool then executes: "go run __frun__" which creates fout.
202 // fout contains Codec(En|De)codeSelf implementations for every type T.
203 func mainGen(tv *mainCfg, infiles ...string) (err error) {
204 // For each file, grab AST, find each type, and write a call to it.
205 if len(infiles) == 0 {
206 return
207 }
208 if tv.CodecImportPath == "" {
209 return errors.New("codec package path cannot be blank")
210 }
211 if tv.OutFile == "" {
212 return errors.New("outfile cannot be blank")
213 }
214 if tv.regexName == nil {
215 tv.regexName = regexp.MustCompile(".*")
216 }
217 if tv.notRegexName == nil {
218 tv.notRegexName = regexp.MustCompile("^$")
219 }
220 if tv.uid < 0 {
221 tv.uid = -tv.uid
222 } else if tv.uid == 0 {
223 rr := rand.New(rand.NewSource(time.Now().UnixNano()))
224 tv.uid = 101 + rr.Int63n(9777)
225 }
226
227 // We have to parse dir for package, before opening the temp file for writing (else ImportDir fails).
228 // Also, ImportDir(...) must take an absolute path.
229 lastdir := filepath.Dir(tv.OutFile)
230 absdir, err := filepath.Abs(lastdir)
231 if err != nil {
232 return
233 }
234 importPath, err := pkgPath(absdir)
235 if err != nil {
236 return
237 }
238
239 tv.CodecPkgName = genCodecPkg
240 tv.RandString = strconv.FormatInt(tv.uid, 10)
241
242 tv.ImportPath = importPath
243 if tv.ImportPath == tv.CodecImportPath {
244 tv.CodecPkgFiles = true
245 tv.CodecPkgName = "codec"
246 } else {
247 // HACK: always handle vendoring. It should be typically on in go 1.6, 1.7
248 tv.ImportPath = genStripVendor(tv.ImportPath)
249 }
250 astfiles := make([]*ast.File, len(infiles))
251 var fi os.FileInfo
252 for i, infile := range infiles {
253 if filepath.Dir(infile) != lastdir {
254 err = errors.New("all input files must all be in same directory as output file")
255 return
256 }
257 if fi, err = os.Stat(infile); err != nil {
258 return
259 }
260 tv.AllFilesSize += fi.Size()
261
262 fset := token.NewFileSet()
263 astfiles[i], err = parser.ParseFile(fset, infile, nil, 0)
264 if err != nil {
265 return
266 }
267 if i == 0 {
268 tv.PackageName = astfiles[i].Name.Name
269 if tv.PackageName == "main" {
270 // codecgen cannot be run on types in the 'main' package.
271 // A temporary 'main' package must be created, and should reference the fully built
272 // package containing the types.
273 // Also, the temporary main package will conflict with the main package which already has a main method.
274 err = errors.New("codecgen cannot be run on types in the 'main' package")
275 return
276 }
277 }
278 }
279
280 // keep track of types with selfer methods
281 // selferMethods := []string{"CodecEncodeSelf", "CodecDecodeSelf"}
282 selferEncTyps := make(map[string]bool)
283 selferDecTyps := make(map[string]bool)
284 for _, f := range astfiles {
285 for _, d := range f.Decls {
286 // if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && fd.Recv.NumFields() == 1 {
287 if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && len(fd.Recv.List) == 1 {
288 recvType := fd.Recv.List[0].Type
289 if ptr, ok := recvType.(*ast.StarExpr); ok {
290 recvType = ptr.X
291 }
292 if id, ok := recvType.(*ast.Ident); ok {
293 switch fd.Name.Name {
294 case "CodecEncodeSelf":
295 selferEncTyps[id.Name] = true
296 case "CodecDecodeSelf":
297 selferDecTyps[id.Name] = true
298 }
299 }
300 }
301 }
302 }
303
304 // now find types
305 for _, f := range astfiles {
306 for _, d := range f.Decls {
307 if gd, ok := d.(*ast.GenDecl); ok {
308 for _, dd := range gd.Specs {
309 if td, ok := dd.(*ast.TypeSpec); ok {
310 // if len(td.Name.Name) == 0 || td.Name.Name[0] > 'Z' || td.Name.Name[0] < 'A' {
311 if len(td.Name.Name) == 0 {
312 continue
313 }
314
315 // only generate for:
316 // struct: StructType
317 // primitives (numbers, bool, string): Ident
318 // map: MapType
319 // slice, array: ArrayType
320 // chan: ChanType
321 // do not generate:
322 // FuncType, InterfaceType, StarExpr (ptr), etc
323 //
324 // We generate for all these types (not just structs), because they may be a field
325 // in another struct which doesn't have codecgen run on it, and it will be nice
326 // to take advantage of the fact that the type is a Selfer.
327 switch td.Type.(type) {
328 case *ast.StructType, *ast.Ident, *ast.MapType, *ast.ArrayType, *ast.ChanType:
329 // only add to tv.Types iff
330 // - it matches per the -r parameter
331 // - it doesn't match per the -nr parameter
332 // - it doesn't have any of the Selfer methods in the file
333 if tv.regexName.FindStringIndex(td.Name.Name) != nil &&
334 tv.notRegexName.FindStringIndex(td.Name.Name) == nil &&
335 !td.Assign.IsValid() && // skip type aliases e.g. type A = B
336 !selferEncTyps[td.Name.Name] &&
337 !selferDecTyps[td.Name.Name] {
338 tv.Types = append(tv.Types, td.Name.Name)
339 }
340 }
341 }
342 }
343 }
344 }
345 }
346
347 if len(tv.Types) == 0 {
348 return
349 }
350
351 // we cannot use ioutil.TempFile, because we cannot guarantee the file suffix (.go).
352 // Also, we cannot create file in temp directory,
353 // because go run will not work (as it needs to see the types here).
354 // Consequently, create the temp file in the current directory, and remove when done.
355
356 // frun, err = ioutil.TempFile("", "codecgen-")
357 // frunName := filepath.Join(os.TempDir(), "codecgen-"+strconv.FormatInt(time.Now().UnixNano(), 10)+".go")
358
359 frunMainName := filepath.Join(lastdir, "codecgen-main-"+tv.RandString+".generated.go")
360 frunPkgName := filepath.Join(lastdir, "codecgen-pkg-"+tv.RandString+".generated.go")
361
362 // var frunMain, frunPkg *os.File
363 if _, err = gen1(frunMainName, genFrunMainTmpl, &tv); err != nil {
364 return
365 }
366 if _, err = gen1(frunPkgName, genFrunPkgTmpl, &tv); err != nil {
367 return
368 }
369
370 // remove outfile, so "go run ..." will not think that types in outfile already exist.
371 os.Remove(tv.OutFile)
372
373 // execute go run
374 // MARKER: it must be run with codec.safe tag, so that we don't use wrong optimizations that only make sense at runtime.
375 // e.g. compositeUnderlyingType will cause generated code to have bad conversions for defined composite types.
376 cmd := exec.Command("go", "run", "-tags", "codecgen.exec codec.safe "+tv.goRunTags, frunMainName) //, frunPkg.Name())
377 cmd.Dir = lastdir
378 var buf bytes.Buffer
379 cmd.Stdout = &buf
380 cmd.Stderr = &buf
381 if err = cmd.Run(); err != nil {
382 err = fmt.Errorf("error running 'go run %s': %v, console: %s", frunMainName, err, buf.Bytes())
383 return
384 }
385 os.Stdout.Write(buf.Bytes())
386
387 // only delete these files if codecgen ran successfully.
388 // if unsuccessful, these files are here for diagnosis.
389 if !tv.keepTempFile {
390 os.Remove(frunMainName)
391 os.Remove(frunPkgName)
392 }
393
394 return
395 }
396
397 func gen1(frunName, tmplStr string, tv interface{}) (frun *os.File, err error) {
398 os.Remove(frunName)
399 if frun, err = os.Create(frunName); err != nil {
400 return
401 }
402 defer frun.Close()
403
404 t := template.New("").Funcs(genFuncs)
405 if t, err = t.Parse(tmplStr); err != nil {
406 return
407 }
408 bw := bufio.NewWriter(frun)
409 if err = t.Execute(bw, tv); err != nil {
410 bw.Flush()
411 return
412 }
413 if err = bw.Flush(); err != nil {
414 return
415 }
416 return
417 }
418
419 // MARKER: keep in sync with ../gen.go
420 func genStripVendor(s string) string {
421 // HACK: Misbehaviour occurs in go 1.5. May have to re-visit this later.
422 // if s contains /vendor/ OR startsWith vendor/, then return everything after it.
423 const vendorStart = "vendor/"
424 const vendorInline = "/vendor/"
425 if i := strings.LastIndex(s, vendorInline); i >= 0 {
426 s = s[i+len(vendorInline):]
427 } else if strings.HasPrefix(s, vendorStart) {
428 s = s[len(vendorStart):]
429 }
430 return s
431 }
432
433 func main() {
434 var unusedBool bool
435 var printVersion bool
436 var g mainCfg
437 var r1, r2 regexFlagValue
438 var b1, b2, b3 boolFlagValue
439
440 flag.BoolVar(&printVersion, "version", false, "show version information")
441 flag.StringVar(&g.OutFile, "o", "", "`output file` that contains generated type")
442 flag.StringVar(&g.CodecImportPath, "c", genCodecPath, "`codec import path` useful when building against a mirror or fork")
443 flag.StringVar(&g.BuildTag, "t", "", "`build tag` to put into generated file")
444
445 flag.Var(&r1, "r", "`regex` for type names to match - defaults to '.*' (all)")
446 flag.Var(&r2, "nr", "`regex` for type names to exclude - defaults to the '^$' (none)")
447
448 flag.Var(&b1, "j", "if set to `true or false`, generated file supports 'json only' or omits json specific optimizations")
449 flag.Var(&b2, "ta", "if set to `true or false`, support 'to_array' always or never, regardless of Handle or struct tags")
450 flag.Var(&b3, "oe", "if set to `true or false`, 'omit empty' always or never, regardless of struct tags")
451
452 flag.StringVar(&g.goRunTags, "rt", "", "`runtime tags` for go run to select which files to use during codecgen execution")
453 flag.StringVar(&g.StructTags, "st", "codec,json", "`struct tag keys` to introspect")
454 flag.BoolVar(&g.keepTempFile, "x", false, "set to `true or false` to 'keep' temp file created during codecgen execution - for debugging sessions")
455 flag.BoolVar(&unusedBool, "u", false, "set to `true or false` to 'allow unsafe' use. **Deprecated and Ignored: kept for backwards compatibility**")
456 flag.Int64Var(&g.uid, "d", 0, "`random integer identifier` for use in generated code, to prevent excessive churn")
457 flag.BoolVar(&g.NoExtensions, "nx", false, "set to `true or false` to elide/ignore checking for extensions (if you do not use extensions)")
458
459 flag.Parse()
460
461 if printVersion {
462 var modVersion string = codecgenModuleVersion
463 if bi, ok := debug.ReadBuildInfo(); ok {
464 if modVersion = bi.Main.Version; len(modVersion) > 0 && modVersion[0] == 'v' {
465 modVersion = modVersion[1:]
466 }
467 }
468 fmt.Printf("codecgen v%s (internal version %d) works with %s library v%s +\n",
469 modVersion, genVersion, genCodecPath, minimumCodecVersion)
470 return
471 }
472
473 g.JsonOnly = b1.v
474 g.StructToArrayAlways = b2.v
475 g.OmitEmptyAlways = b3.v
476
477 g.regexName = r1.v
478 g.notRegexName = r2.v
479
480 // fmt.Printf("jsonOnly: %v, StructToArrayAlways: %v, OmitEmptyAlways: %v\n", g.JsonOnly, g.StructToArrayAlways, g.OmitEmptyAlways)
481 err := mainGen(&g, flag.Args()...)
482 // err := mainGen(*o, *t, *c, *d, *rt, *st,
483 // regexp.MustCompile(*r), regexp.MustCompile(*nr), !*x, *nx, flag.Args()...)
484 if err != nil {
485 fmt.Fprintf(os.Stderr, "codecgen error: %v\n", err)
486 os.Exit(1)
487 }
488 }