gen.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359
  1. // Copyright (c) 2012-2018 Ugorji Nwoke. All rights reserved.
  2. // Use of this source code is governed by a MIT license found in the LICENSE file.
  3. // codecgen generates codec.Selfer implementations for a set of types.
  4. package main
  5. import (
  6. "bufio"
  7. "bytes"
  8. "errors"
  9. "flag"
  10. "fmt"
  11. "go/ast"
  12. "go/parser"
  13. "go/token"
  14. "math/rand"
  15. "os"
  16. "os/exec"
  17. "path/filepath"
  18. "regexp"
  19. "strconv"
  20. "strings"
  21. "text/template"
  22. "time"
  23. )
  24. const genCodecPkg = "codec1978" // keep this in sync with codec.genCodecPkg
  25. const genFrunMainTmpl = `//+build ignore
  26. // Code generated - temporary main package for codecgen - DO NOT EDIT.
  27. package main
  28. {{ if .Types }}import "{{ .ImportPath }}"{{ end }}
  29. func main() {
  30. {{ $.PackageName }}.CodecGenTempWrite{{ .RandString }}()
  31. }
  32. `
  33. // const genFrunPkgTmpl = `//+build codecgen
  34. const genFrunPkgTmpl = `
  35. // Code generated - temporary package for codecgen - DO NOT EDIT.
  36. package {{ $.PackageName }}
  37. import (
  38. {{ if not .CodecPkgFiles }}{{ .CodecPkgName }} "{{ .CodecImportPath }}"{{ end }}
  39. "os"
  40. "reflect"
  41. "bytes"
  42. "strings"
  43. "go/format"
  44. )
  45. func CodecGenTempWrite{{ .RandString }}() {
  46. os.Remove("{{ .OutFile }}")
  47. fout, err := os.Create("{{ .OutFile }}")
  48. if err != nil {
  49. panic(err)
  50. }
  51. defer fout.Close()
  52. var typs []reflect.Type
  53. var typ reflect.Type
  54. var numfields int
  55. {{ range $index, $element := .Types }}
  56. var t{{ $index }} {{ . }}
  57. typ = reflect.TypeOf(t{{ $index }})
  58. typs = append(typs, typ)
  59. if typ.Kind() == reflect.Struct { numfields += typ.NumField() } else { numfields += 1 }
  60. {{ end }}
  61. // println("initializing {{ .OutFile }}, buf size: {{ .AllFilesSize }}*16",
  62. // {{ .AllFilesSize }}*16, "num fields: ", numfields)
  63. var out = bytes.NewBuffer(make([]byte, 0, numfields*1024)) // {{ .AllFilesSize }}*16
  64. {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}Gen(out,
  65. "{{ .BuildTag }}", "{{ .PackageName }}", "{{ .RandString }}", {{ .NoExtensions }},
  66. {{ if not .CodecPkgFiles }}{{ .CodecPkgName }}.{{ end }}NewTypeInfos(strings.Split("{{ .StructTags }}", ",")),
  67. typs...)
  68. bout, err := format.Source(out.Bytes())
  69. // println("... lengths: before formatting: ", len(out.Bytes()), ", after formatting", len(bout))
  70. if err != nil {
  71. fout.Write(out.Bytes())
  72. panic(err)
  73. }
  74. fout.Write(bout)
  75. }
  76. `
  77. // Generate is given a list of *.go files to parse, and an output file (fout).
  78. //
  79. // It finds all types T in the files, and it creates 2 tmp files (frun).
  80. // - main package file passed to 'go run'
  81. // - package level file which calls *genRunner.Selfer to write Selfer impls for each T.
  82. // We use a package level file so that it can reference unexported types in the package being worked on.
  83. // Tool then executes: "go run __frun__" which creates fout.
  84. // fout contains Codec(En|De)codeSelf implementations for every type T.
  85. //
  86. func Generate(outfile, buildTag, codecPkgPath string,
  87. uid int64,
  88. goRunTag string, st string,
  89. regexName, notRegexName *regexp.Regexp,
  90. deleteTempFile, noExtensions bool,
  91. infiles ...string) (err error) {
  92. // For each file, grab AST, find each type, and write a call to it.
  93. if len(infiles) == 0 {
  94. return
  95. }
  96. if outfile == "" || codecPkgPath == "" {
  97. err = errors.New("outfile and codec package path cannot be blank")
  98. return
  99. }
  100. if uid < 0 {
  101. uid = -uid
  102. } else if uid == 0 {
  103. rr := rand.New(rand.NewSource(time.Now().UnixNano()))
  104. uid = 101 + rr.Int63n(9777)
  105. }
  106. // We have to parse dir for package, before opening the temp file for writing (else ImportDir fails).
  107. // Also, ImportDir(...) must take an absolute path.
  108. lastdir := filepath.Dir(outfile)
  109. absdir, err := filepath.Abs(lastdir)
  110. if err != nil {
  111. return
  112. }
  113. importPath, err := pkgPath(absdir)
  114. if err != nil {
  115. return
  116. }
  117. type tmplT struct {
  118. CodecPkgName string
  119. CodecImportPath string
  120. ImportPath string
  121. OutFile string
  122. PackageName string
  123. RandString string
  124. BuildTag string
  125. StructTags string
  126. Types []string
  127. AllFilesSize int64
  128. CodecPkgFiles bool
  129. NoExtensions bool
  130. }
  131. tv := tmplT{
  132. CodecPkgName: genCodecPkg,
  133. OutFile: outfile,
  134. CodecImportPath: codecPkgPath,
  135. BuildTag: buildTag,
  136. RandString: strconv.FormatInt(uid, 10),
  137. StructTags: st,
  138. NoExtensions: noExtensions,
  139. }
  140. tv.ImportPath = importPath
  141. if tv.ImportPath == tv.CodecImportPath {
  142. tv.CodecPkgFiles = true
  143. tv.CodecPkgName = "codec"
  144. } else {
  145. // HACK: always handle vendoring. It should be typically on in go 1.6, 1.7
  146. tv.ImportPath = stripVendor(tv.ImportPath)
  147. }
  148. astfiles := make([]*ast.File, len(infiles))
  149. var fi os.FileInfo
  150. for i, infile := range infiles {
  151. if filepath.Dir(infile) != lastdir {
  152. err = errors.New("in files must all be in same directory as outfile")
  153. return
  154. }
  155. if fi, err = os.Stat(infile); err != nil {
  156. return
  157. }
  158. tv.AllFilesSize += fi.Size()
  159. fset := token.NewFileSet()
  160. astfiles[i], err = parser.ParseFile(fset, infile, nil, 0)
  161. if err != nil {
  162. return
  163. }
  164. if i == 0 {
  165. tv.PackageName = astfiles[i].Name.Name
  166. if tv.PackageName == "main" {
  167. // codecgen cannot be run on types in the 'main' package.
  168. // A temporary 'main' package must be created, and should reference the fully built
  169. // package containing the types.
  170. // Also, the temporary main package will conflict with the main package which already has a main method.
  171. err = errors.New("codecgen cannot be run on types in the 'main' package")
  172. return
  173. }
  174. }
  175. }
  176. // keep track of types with selfer methods
  177. // selferMethods := []string{"CodecEncodeSelf", "CodecDecodeSelf"}
  178. selferEncTyps := make(map[string]bool)
  179. selferDecTyps := make(map[string]bool)
  180. for _, f := range astfiles {
  181. for _, d := range f.Decls {
  182. // if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && fd.Recv.NumFields() == 1 {
  183. if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && len(fd.Recv.List) == 1 {
  184. recvType := fd.Recv.List[0].Type
  185. if ptr, ok := recvType.(*ast.StarExpr); ok {
  186. recvType = ptr.X
  187. }
  188. if id, ok := recvType.(*ast.Ident); ok {
  189. switch fd.Name.Name {
  190. case "CodecEncodeSelf":
  191. selferEncTyps[id.Name] = true
  192. case "CodecDecodeSelf":
  193. selferDecTyps[id.Name] = true
  194. }
  195. }
  196. }
  197. }
  198. }
  199. // now find types
  200. for _, f := range astfiles {
  201. for _, d := range f.Decls {
  202. if gd, ok := d.(*ast.GenDecl); ok {
  203. for _, dd := range gd.Specs {
  204. if td, ok := dd.(*ast.TypeSpec); ok {
  205. // if len(td.Name.Name) == 0 || td.Name.Name[0] > 'Z' || td.Name.Name[0] < 'A' {
  206. if len(td.Name.Name) == 0 {
  207. continue
  208. }
  209. // only generate for:
  210. // struct: StructType
  211. // primitives (numbers, bool, string): Ident
  212. // map: MapType
  213. // slice, array: ArrayType
  214. // chan: ChanType
  215. // do not generate:
  216. // FuncType, InterfaceType, StarExpr (ptr), etc
  217. //
  218. // We generate for all these types (not just structs), because they may be a field
  219. // in another struct which doesn't have codecgen run on it, and it will be nice
  220. // to take advantage of the fact that the type is a Selfer.
  221. switch td.Type.(type) {
  222. case *ast.StructType, *ast.Ident, *ast.MapType, *ast.ArrayType, *ast.ChanType:
  223. // only add to tv.Types iff
  224. // - it matches per the -r parameter
  225. // - it doesn't match per the -nr parameter
  226. // - it doesn't have any of the Selfer methods in the file
  227. if regexName.FindStringIndex(td.Name.Name) != nil &&
  228. notRegexName.FindStringIndex(td.Name.Name) == nil &&
  229. !selferEncTyps[td.Name.Name] &&
  230. !selferDecTyps[td.Name.Name] {
  231. tv.Types = append(tv.Types, td.Name.Name)
  232. }
  233. }
  234. }
  235. }
  236. }
  237. }
  238. }
  239. if len(tv.Types) == 0 {
  240. return
  241. }
  242. // we cannot use ioutil.TempFile, because we cannot guarantee the file suffix (.go).
  243. // Also, we cannot create file in temp directory,
  244. // because go run will not work (as it needs to see the types here).
  245. // Consequently, create the temp file in the current directory, and remove when done.
  246. // frun, err = ioutil.TempFile("", "codecgen-")
  247. // frunName := filepath.Join(os.TempDir(), "codecgen-"+strconv.FormatInt(time.Now().UnixNano(), 10)+".go")
  248. frunMainName := "codecgen-main-" + tv.RandString + ".generated.go"
  249. frunPkgName := "codecgen-pkg-" + tv.RandString + ".generated.go"
  250. if deleteTempFile {
  251. defer os.Remove(frunMainName)
  252. defer os.Remove(frunPkgName)
  253. }
  254. // var frunMain, frunPkg *os.File
  255. if _, err = gen1(frunMainName, genFrunMainTmpl, &tv); err != nil {
  256. return
  257. }
  258. if _, err = gen1(frunPkgName, genFrunPkgTmpl, &tv); err != nil {
  259. return
  260. }
  261. // remove outfile, so "go run ..." will not think that types in outfile already exist.
  262. os.Remove(outfile)
  263. // execute go run frun
  264. cmd := exec.Command("go", "run", "-tags", "codecgen.exec safe "+goRunTag, frunMainName) //, frunPkg.Name())
  265. var buf bytes.Buffer
  266. cmd.Stdout = &buf
  267. cmd.Stderr = &buf
  268. if err = cmd.Run(); err != nil {
  269. err = fmt.Errorf("error running 'go run %s': %v, console: %s",
  270. frunMainName, err, buf.Bytes())
  271. return
  272. }
  273. os.Stdout.Write(buf.Bytes())
  274. return
  275. }
  276. func gen1(frunName, tmplStr string, tv interface{}) (frun *os.File, err error) {
  277. os.Remove(frunName)
  278. if frun, err = os.Create(frunName); err != nil {
  279. return
  280. }
  281. defer frun.Close()
  282. t := template.New("")
  283. if t, err = t.Parse(tmplStr); err != nil {
  284. return
  285. }
  286. bw := bufio.NewWriter(frun)
  287. if err = t.Execute(bw, tv); err != nil {
  288. bw.Flush()
  289. return
  290. }
  291. if err = bw.Flush(); err != nil {
  292. return
  293. }
  294. return
  295. }
  296. // copied from ../gen.go (keep in sync).
  297. func stripVendor(s string) string {
  298. // HACK: Misbehaviour occurs in go 1.5. May have to re-visit this later.
  299. // if s contains /vendor/ OR startsWith vendor/, then return everything after it.
  300. const vendorStart = "vendor/"
  301. const vendorInline = "/vendor/"
  302. if i := strings.LastIndex(s, vendorInline); i >= 0 {
  303. s = s[i+len(vendorInline):]
  304. } else if strings.HasPrefix(s, vendorStart) {
  305. s = s[len(vendorStart):]
  306. }
  307. return s
  308. }
  309. func main() {
  310. o := flag.String("o", "", "out file")
  311. c := flag.String("c", genCodecPath, "codec path")
  312. t := flag.String("t", "", "build tag to put in file")
  313. r := flag.String("r", ".*", "regex for type name to match")
  314. nr := flag.String("nr", "^$", "regex for type name to exclude")
  315. rt := flag.String("rt", "", "tags for go run")
  316. st := flag.String("st", "codec,json", "struct tag keys to introspect")
  317. x := flag.Bool("x", false, "keep temp file")
  318. _ = flag.Bool("u", false, "Allow unsafe use. ***IGNORED*** - kept for backwards compatibility: ")
  319. d := flag.Int64("d", 0, "random identifier for use in generated code")
  320. nx := flag.Bool("nx", false, "do not support extensions - support of extensions may cause extra allocation")
  321. flag.Parse()
  322. err := Generate(*o, *t, *c, *d, *rt, *st,
  323. regexp.MustCompile(*r), regexp.MustCompile(*nr), !*x, *nx, flag.Args()...)
  324. if err != nil {
  325. fmt.Fprintf(os.Stderr, "codecgen error: %v\n", err)
  326. os.Exit(1)
  327. }
  328. }