gen.go 11 KB

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