gen.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360
  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. } else if uid == 0 {
  104. rr := rand.New(rand.NewSource(time.Now().UnixNano()))
  105. uid = 101 + rr.Int63n(9777)
  106. }
  107. // We have to parse dir for package, before opening the temp file for writing (else ImportDir fails).
  108. // Also, ImportDir(...) must take an absolute path.
  109. lastdir := filepath.Dir(outfile)
  110. absdir, err := filepath.Abs(lastdir)
  111. if err != nil {
  112. return
  113. }
  114. pkg, err := build.Default.ImportDir(absdir, build.AllowBinary)
  115. if err != nil {
  116. return
  117. }
  118. type tmplT struct {
  119. CodecPkgName string
  120. CodecImportPath string
  121. ImportPath string
  122. OutFile string
  123. PackageName string
  124. RandString string
  125. BuildTag string
  126. StructTags string
  127. Types []string
  128. AllFilesSize int64
  129. CodecPkgFiles bool
  130. NoExtensions bool
  131. }
  132. tv := tmplT{
  133. CodecPkgName: genCodecPkg,
  134. OutFile: outfile,
  135. CodecImportPath: codecPkgPath,
  136. BuildTag: buildTag,
  137. RandString: strconv.FormatInt(uid, 10),
  138. StructTags: st,
  139. NoExtensions: noExtensions,
  140. }
  141. tv.ImportPath = pkg.ImportPath
  142. if tv.ImportPath == tv.CodecImportPath {
  143. tv.CodecPkgFiles = true
  144. tv.CodecPkgName = "codec"
  145. } else {
  146. // HACK: always handle vendoring. It should be typically on in go 1.6, 1.7
  147. tv.ImportPath = stripVendor(tv.ImportPath)
  148. }
  149. astfiles := make([]*ast.File, len(infiles))
  150. var fi os.FileInfo
  151. for i, infile := range infiles {
  152. if filepath.Dir(infile) != lastdir {
  153. err = errors.New("in files must all be in same directory as outfile")
  154. return
  155. }
  156. if fi, err = os.Stat(infile); err != nil {
  157. return
  158. }
  159. tv.AllFilesSize += fi.Size()
  160. fset := token.NewFileSet()
  161. astfiles[i], err = parser.ParseFile(fset, infile, nil, 0)
  162. if err != nil {
  163. return
  164. }
  165. if i == 0 {
  166. tv.PackageName = astfiles[i].Name.Name
  167. if tv.PackageName == "main" {
  168. // codecgen cannot be run on types in the 'main' package.
  169. // A temporary 'main' package must be created, and should reference the fully built
  170. // package containing the types.
  171. // Also, the temporary main package will conflict with the main package which already has a main method.
  172. err = errors.New("codecgen cannot be run on types in the 'main' package")
  173. return
  174. }
  175. }
  176. }
  177. // keep track of types with selfer methods
  178. // selferMethods := []string{"CodecEncodeSelf", "CodecDecodeSelf"}
  179. selferEncTyps := make(map[string]bool)
  180. selferDecTyps := make(map[string]bool)
  181. for _, f := range astfiles {
  182. for _, d := range f.Decls {
  183. // if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && fd.Recv.NumFields() == 1 {
  184. if fd, ok := d.(*ast.FuncDecl); ok && fd.Recv != nil && len(fd.Recv.List) == 1 {
  185. recvType := fd.Recv.List[0].Type
  186. if ptr, ok := recvType.(*ast.StarExpr); ok {
  187. recvType = ptr.X
  188. }
  189. if id, ok := recvType.(*ast.Ident); ok {
  190. switch fd.Name.Name {
  191. case "CodecEncodeSelf":
  192. selferEncTyps[id.Name] = true
  193. case "CodecDecodeSelf":
  194. selferDecTyps[id.Name] = true
  195. }
  196. }
  197. }
  198. }
  199. }
  200. // now find types
  201. for _, f := range astfiles {
  202. for _, d := range f.Decls {
  203. if gd, ok := d.(*ast.GenDecl); ok {
  204. for _, dd := range gd.Specs {
  205. if td, ok := dd.(*ast.TypeSpec); ok {
  206. // if len(td.Name.Name) == 0 || td.Name.Name[0] > 'Z' || td.Name.Name[0] < 'A' {
  207. if len(td.Name.Name) == 0 {
  208. continue
  209. }
  210. // only generate for:
  211. // struct: StructType
  212. // primitives (numbers, bool, string): Ident
  213. // map: MapType
  214. // slice, array: ArrayType
  215. // chan: ChanType
  216. // do not generate:
  217. // FuncType, InterfaceType, StarExpr (ptr), etc
  218. //
  219. // We generate for all these types (not just structs), because they may be a field
  220. // in another struct which doesn't have codecgen run on it, and it will be nice
  221. // to take advantage of the fact that the type is a Selfer.
  222. switch td.Type.(type) {
  223. case *ast.StructType, *ast.Ident, *ast.MapType, *ast.ArrayType, *ast.ChanType:
  224. // only add to tv.Types iff
  225. // - it matches per the -r parameter
  226. // - it doesn't match per the -nr parameter
  227. // - it doesn't have any of the Selfer methods in the file
  228. if regexName.FindStringIndex(td.Name.Name) != nil &&
  229. notRegexName.FindStringIndex(td.Name.Name) == nil &&
  230. !selferEncTyps[td.Name.Name] &&
  231. !selferDecTyps[td.Name.Name] {
  232. tv.Types = append(tv.Types, td.Name.Name)
  233. }
  234. }
  235. }
  236. }
  237. }
  238. }
  239. }
  240. if len(tv.Types) == 0 {
  241. return
  242. }
  243. // we cannot use ioutil.TempFile, because we cannot guarantee the file suffix (.go).
  244. // Also, we cannot create file in temp directory,
  245. // because go run will not work (as it needs to see the types here).
  246. // Consequently, create the temp file in the current directory, and remove when done.
  247. // frun, err = ioutil.TempFile("", "codecgen-")
  248. // frunName := filepath.Join(os.TempDir(), "codecgen-"+strconv.FormatInt(time.Now().UnixNano(), 10)+".go")
  249. frunMainName := "codecgen-main-" + tv.RandString + ".generated.go"
  250. frunPkgName := "codecgen-pkg-" + tv.RandString + ".generated.go"
  251. if deleteTempFile {
  252. defer os.Remove(frunMainName)
  253. defer os.Remove(frunPkgName)
  254. }
  255. // var frunMain, frunPkg *os.File
  256. if _, err = gen1(frunMainName, genFrunMainTmpl, &tv); err != nil {
  257. return
  258. }
  259. if _, err = gen1(frunPkgName, genFrunPkgTmpl, &tv); err != nil {
  260. return
  261. }
  262. // remove outfile, so "go run ..." will not think that types in outfile already exist.
  263. os.Remove(outfile)
  264. // execute go run frun
  265. cmd := exec.Command("go", "run", "-tags", "codecgen.exec safe "+goRunTag, frunMainName) //, frunPkg.Name())
  266. var buf bytes.Buffer
  267. cmd.Stdout = &buf
  268. cmd.Stderr = &buf
  269. if err = cmd.Run(); err != nil {
  270. err = fmt.Errorf("error running 'go run %s': %v, console: %s",
  271. frunMainName, err, buf.Bytes())
  272. return
  273. }
  274. os.Stdout.Write(buf.Bytes())
  275. return
  276. }
  277. func gen1(frunName, tmplStr string, tv interface{}) (frun *os.File, err error) {
  278. os.Remove(frunName)
  279. if frun, err = os.Create(frunName); err != nil {
  280. return
  281. }
  282. defer frun.Close()
  283. t := template.New("")
  284. if t, err = t.Parse(tmplStr); err != nil {
  285. return
  286. }
  287. bw := bufio.NewWriter(frun)
  288. if err = t.Execute(bw, tv); err != nil {
  289. bw.Flush()
  290. return
  291. }
  292. if err = bw.Flush(); err != nil {
  293. return
  294. }
  295. return
  296. }
  297. // copied from ../gen.go (keep in sync).
  298. func stripVendor(s string) string {
  299. // HACK: Misbehaviour occurs in go 1.5. May have to re-visit this later.
  300. // if s contains /vendor/ OR startsWith vendor/, then return everything after it.
  301. const vendorStart = "vendor/"
  302. const vendorInline = "/vendor/"
  303. if i := strings.LastIndex(s, vendorInline); i >= 0 {
  304. s = s[i+len(vendorInline):]
  305. } else if strings.HasPrefix(s, vendorStart) {
  306. s = s[len(vendorStart):]
  307. }
  308. return s
  309. }
  310. func main() {
  311. o := flag.String("o", "", "out file")
  312. c := flag.String("c", genCodecPath, "codec path")
  313. t := flag.String("t", "", "build tag to put in file")
  314. r := flag.String("r", ".*", "regex for type name to match")
  315. nr := flag.String("nr", "^$", "regex for type name to exclude")
  316. rt := flag.String("rt", "", "tags for go run")
  317. st := flag.String("st", "codec,json", "struct tag keys to introspect")
  318. x := flag.Bool("x", false, "keep temp file")
  319. _ = flag.Bool("u", false, "Allow unsafe use. ***IGNORED*** - kept for backwards compatibility: ")
  320. d := flag.Int64("d", 0, "random identifier for use in generated code")
  321. nx := flag.Bool("nx", false, "do not support extensions - support of extensions may cause extra allocation")
  322. flag.Parse()
  323. err := Generate(*o, *t, *c, *d, *rt, *st,
  324. regexp.MustCompile(*r), regexp.MustCompile(*nr), !*x, *nx, flag.Args()...)
  325. if err != nil {
  326. fmt.Fprintf(os.Stderr, "codecgen error: %v\n", err)
  327. os.Exit(1)
  328. }
  329. }