code.go 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375
  1. // Copyright 2015 The Go Authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package gen
  5. import (
  6. "bytes"
  7. "encoding/gob"
  8. "fmt"
  9. "hash"
  10. "hash/fnv"
  11. "io"
  12. "log"
  13. "os"
  14. "reflect"
  15. "strings"
  16. "unicode"
  17. "unicode/utf8"
  18. )
  19. // This file contains utilities for generating code.
  20. // TODO: other write methods like:
  21. // - slices, maps, types, etc.
  22. // CodeWriter is a utility for writing structured code. It computes the content
  23. // hash and size of written content. It ensures there are newlines between
  24. // written code blocks.
  25. type CodeWriter struct {
  26. buf bytes.Buffer
  27. Size int
  28. Hash hash.Hash32 // content hash
  29. gob *gob.Encoder
  30. // For comments we skip the usual one-line separator if they are followed by
  31. // a code block.
  32. skipSep bool
  33. }
  34. func (w *CodeWriter) Write(p []byte) (n int, err error) {
  35. return w.buf.Write(p)
  36. }
  37. // NewCodeWriter returns a new CodeWriter.
  38. func NewCodeWriter() *CodeWriter {
  39. h := fnv.New32()
  40. return &CodeWriter{Hash: h, gob: gob.NewEncoder(h)}
  41. }
  42. // WriteGoFile appends the buffer with the total size of all created structures
  43. // and writes it as a Go file to the given file with the given package name.
  44. func (w *CodeWriter) WriteGoFile(filename, pkg string) {
  45. f, err := os.Create(filename)
  46. if err != nil {
  47. log.Fatalf("Could not create file %s: %v", filename, err)
  48. }
  49. defer f.Close()
  50. if _, err = w.WriteGo(f, pkg, ""); err != nil {
  51. log.Fatalf("Error writing file %s: %v", filename, err)
  52. }
  53. }
  54. // WriteVersionedGoFile appends the buffer with the total size of all created
  55. // structures and writes it as a Go file to the given file with the given
  56. // package name and build tags for the current Unicode version,
  57. func (w *CodeWriter) WriteVersionedGoFile(filename, pkg string) {
  58. tags := buildTags()
  59. if tags != "" {
  60. pattern := fileToPattern(filename)
  61. updateBuildTags(pattern)
  62. filename = fmt.Sprintf(pattern, UnicodeVersion())
  63. }
  64. f, err := os.Create(filename)
  65. if err != nil {
  66. log.Fatalf("Could not create file %s: %v", filename, err)
  67. }
  68. defer f.Close()
  69. if _, err = w.WriteGo(f, pkg, tags); err != nil {
  70. log.Fatalf("Error writing file %s: %v", filename, err)
  71. }
  72. }
  73. // WriteGo appends the buffer with the total size of all created structures and
  74. // writes it as a Go file to the given writer with the given package name.
  75. func (w *CodeWriter) WriteGo(out io.Writer, pkg, tags string) (n int, err error) {
  76. sz := w.Size
  77. if sz > 0 {
  78. w.WriteComment("Total table size %d bytes (%dKiB); checksum: %X\n", sz, sz/1024, w.Hash.Sum32())
  79. }
  80. defer w.buf.Reset()
  81. return WriteGo(out, pkg, tags, w.buf.Bytes())
  82. }
  83. func (w *CodeWriter) printf(f string, x ...interface{}) {
  84. fmt.Fprintf(w, f, x...)
  85. }
  86. func (w *CodeWriter) insertSep() {
  87. if w.skipSep {
  88. w.skipSep = false
  89. return
  90. }
  91. // Use at least two newlines to ensure a blank space between the previous
  92. // block. WriteGoFile will remove extraneous newlines.
  93. w.printf("\n\n")
  94. }
  95. // WriteComment writes a comment block. All line starts are prefixed with "//".
  96. // Initial empty lines are gobbled. The indentation for the first line is
  97. // stripped from consecutive lines.
  98. func (w *CodeWriter) WriteComment(comment string, args ...interface{}) {
  99. s := fmt.Sprintf(comment, args...)
  100. s = strings.Trim(s, "\n")
  101. // Use at least two newlines to ensure a blank space between the previous
  102. // block. WriteGoFile will remove extraneous newlines.
  103. w.printf("\n\n// ")
  104. w.skipSep = true
  105. // strip first indent level.
  106. sep := "\n"
  107. for ; len(s) > 0 && (s[0] == '\t' || s[0] == ' '); s = s[1:] {
  108. sep += s[:1]
  109. }
  110. strings.NewReplacer(sep, "\n// ", "\n", "\n// ").WriteString(w, s)
  111. w.printf("\n")
  112. }
  113. func (w *CodeWriter) writeSizeInfo(size int) {
  114. w.printf("// Size: %d bytes\n", size)
  115. }
  116. // WriteConst writes a constant of the given name and value.
  117. func (w *CodeWriter) WriteConst(name string, x interface{}) {
  118. w.insertSep()
  119. v := reflect.ValueOf(x)
  120. switch v.Type().Kind() {
  121. case reflect.String:
  122. w.printf("const %s %s = ", name, typeName(x))
  123. w.WriteString(v.String())
  124. w.printf("\n")
  125. default:
  126. w.printf("const %s = %#v\n", name, x)
  127. }
  128. }
  129. // WriteVar writes a variable of the given name and value.
  130. func (w *CodeWriter) WriteVar(name string, x interface{}) {
  131. w.insertSep()
  132. v := reflect.ValueOf(x)
  133. oldSize := w.Size
  134. sz := int(v.Type().Size())
  135. w.Size += sz
  136. switch v.Type().Kind() {
  137. case reflect.String:
  138. w.printf("var %s %s = ", name, typeName(x))
  139. w.WriteString(v.String())
  140. case reflect.Struct:
  141. w.gob.Encode(x)
  142. fallthrough
  143. case reflect.Slice, reflect.Array:
  144. w.printf("var %s = ", name)
  145. w.writeValue(v)
  146. w.writeSizeInfo(w.Size - oldSize)
  147. default:
  148. w.printf("var %s %s = ", name, typeName(x))
  149. w.gob.Encode(x)
  150. w.writeValue(v)
  151. w.writeSizeInfo(w.Size - oldSize)
  152. }
  153. w.printf("\n")
  154. }
  155. func (w *CodeWriter) writeValue(v reflect.Value) {
  156. x := v.Interface()
  157. switch v.Kind() {
  158. case reflect.String:
  159. w.WriteString(v.String())
  160. case reflect.Array:
  161. // Don't double count: callers of WriteArray count on the size being
  162. // added, so we need to discount it here.
  163. w.Size -= int(v.Type().Size())
  164. w.writeSlice(x, true)
  165. case reflect.Slice:
  166. w.writeSlice(x, false)
  167. case reflect.Struct:
  168. w.printf("%s{\n", typeName(v.Interface()))
  169. t := v.Type()
  170. for i := 0; i < v.NumField(); i++ {
  171. w.printf("%s: ", t.Field(i).Name)
  172. w.writeValue(v.Field(i))
  173. w.printf(",\n")
  174. }
  175. w.printf("}")
  176. default:
  177. w.printf("%#v", x)
  178. }
  179. }
  180. // WriteString writes a string literal.
  181. func (w *CodeWriter) WriteString(s string) {
  182. io.WriteString(w.Hash, s) // content hash
  183. w.Size += len(s)
  184. const maxInline = 40
  185. if len(s) <= maxInline {
  186. w.printf("%q", s)
  187. return
  188. }
  189. // We will render the string as a multi-line string.
  190. const maxWidth = 80 - 4 - len(`"`) - len(`" +`)
  191. // When starting on its own line, go fmt indents line 2+ an extra level.
  192. n, max := maxWidth, maxWidth-4
  193. // As per https://golang.org/issue/18078, the compiler has trouble
  194. // compiling the concatenation of many strings, s0 + s1 + s2 + ... + sN,
  195. // for large N. We insert redundant, explicit parentheses to work around
  196. // that, lowering the N at any given step: (s0 + s1 + ... + s63) + (s64 +
  197. // ... + s127) + etc + (etc + ... + sN).
  198. explicitParens, extraComment := len(s) > 128*1024, ""
  199. if explicitParens {
  200. w.printf(`(`)
  201. extraComment = "; the redundant, explicit parens are for https://golang.org/issue/18078"
  202. }
  203. // Print "" +\n, if a string does not start on its own line.
  204. b := w.buf.Bytes()
  205. if p := len(bytes.TrimRight(b, " \t")); p > 0 && b[p-1] != '\n' {
  206. w.printf("\"\" + // Size: %d bytes%s\n", len(s), extraComment)
  207. n, max = maxWidth, maxWidth
  208. }
  209. w.printf(`"`)
  210. for sz, p, nLines := 0, 0, 0; p < len(s); {
  211. var r rune
  212. r, sz = utf8.DecodeRuneInString(s[p:])
  213. out := s[p : p+sz]
  214. chars := 1
  215. if !unicode.IsPrint(r) || r == utf8.RuneError || r == '"' {
  216. switch sz {
  217. case 1:
  218. out = fmt.Sprintf("\\x%02x", s[p])
  219. case 2, 3:
  220. out = fmt.Sprintf("\\u%04x", r)
  221. case 4:
  222. out = fmt.Sprintf("\\U%08x", r)
  223. }
  224. chars = len(out)
  225. } else if r == '\\' {
  226. out = "\\" + string(r)
  227. chars = 2
  228. }
  229. if n -= chars; n < 0 {
  230. nLines++
  231. if explicitParens && nLines&63 == 63 {
  232. w.printf("\") + (\"")
  233. }
  234. w.printf("\" +\n\"")
  235. n = max - len(out)
  236. }
  237. w.printf("%s", out)
  238. p += sz
  239. }
  240. w.printf(`"`)
  241. if explicitParens {
  242. w.printf(`)`)
  243. }
  244. }
  245. // WriteSlice writes a slice value.
  246. func (w *CodeWriter) WriteSlice(x interface{}) {
  247. w.writeSlice(x, false)
  248. }
  249. // WriteArray writes an array value.
  250. func (w *CodeWriter) WriteArray(x interface{}) {
  251. w.writeSlice(x, true)
  252. }
  253. func (w *CodeWriter) writeSlice(x interface{}, isArray bool) {
  254. v := reflect.ValueOf(x)
  255. w.gob.Encode(v.Len())
  256. w.Size += v.Len() * int(v.Type().Elem().Size())
  257. name := typeName(x)
  258. if isArray {
  259. name = fmt.Sprintf("[%d]%s", v.Len(), name[strings.Index(name, "]")+1:])
  260. }
  261. if isArray {
  262. w.printf("%s{\n", name)
  263. } else {
  264. w.printf("%s{ // %d elements\n", name, v.Len())
  265. }
  266. switch kind := v.Type().Elem().Kind(); kind {
  267. case reflect.String:
  268. for _, s := range x.([]string) {
  269. w.WriteString(s)
  270. w.printf(",\n")
  271. }
  272. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  273. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  274. // nLine and nBlock are the number of elements per line and block.
  275. nLine, nBlock, format := 8, 64, "%d,"
  276. switch kind {
  277. case reflect.Uint8:
  278. format = "%#02x,"
  279. case reflect.Uint16:
  280. format = "%#04x,"
  281. case reflect.Uint32:
  282. nLine, nBlock, format = 4, 32, "%#08x,"
  283. case reflect.Uint, reflect.Uint64:
  284. nLine, nBlock, format = 4, 32, "%#016x,"
  285. case reflect.Int8:
  286. nLine = 16
  287. }
  288. n := nLine
  289. for i := 0; i < v.Len(); i++ {
  290. if i%nBlock == 0 && v.Len() > nBlock {
  291. w.printf("// Entry %X - %X\n", i, i+nBlock-1)
  292. }
  293. x := v.Index(i).Interface()
  294. w.gob.Encode(x)
  295. w.printf(format, x)
  296. if n--; n == 0 {
  297. n = nLine
  298. w.printf("\n")
  299. }
  300. }
  301. w.printf("\n")
  302. case reflect.Struct:
  303. zero := reflect.Zero(v.Type().Elem()).Interface()
  304. for i := 0; i < v.Len(); i++ {
  305. x := v.Index(i).Interface()
  306. w.gob.EncodeValue(v)
  307. if !reflect.DeepEqual(zero, x) {
  308. line := fmt.Sprintf("%#v,\n", x)
  309. line = line[strings.IndexByte(line, '{'):]
  310. w.printf("%d: ", i)
  311. w.printf(line)
  312. }
  313. }
  314. case reflect.Array:
  315. for i := 0; i < v.Len(); i++ {
  316. w.printf("%d: %#v,\n", i, v.Index(i).Interface())
  317. }
  318. default:
  319. panic("gen: slice elem type not supported")
  320. }
  321. w.printf("}")
  322. }
  323. // WriteType writes a definition of the type of the given value and returns the
  324. // type name.
  325. func (w *CodeWriter) WriteType(x interface{}) string {
  326. t := reflect.TypeOf(x)
  327. w.printf("type %s struct {\n", t.Name())
  328. for i := 0; i < t.NumField(); i++ {
  329. w.printf("\t%s %s\n", t.Field(i).Name, t.Field(i).Type)
  330. }
  331. w.printf("}\n")
  332. return t.Name()
  333. }
  334. // typeName returns the name of the go type of x.
  335. func typeName(x interface{}) string {
  336. t := reflect.ValueOf(x).Type()
  337. return strings.Replace(fmt.Sprint(t), "main.", "", 1)
  338. }