code.go 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  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 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. // WriteGo appends the buffer with the total size of all created structures and
  55. // writes it as a Go file to the the given writer with the given package name.
  56. func (w *CodeWriter) WriteGo(out io.Writer, pkg string) (n int, err error) {
  57. sz := w.Size
  58. w.WriteComment("Total table size %d bytes (%dKiB); checksum: %X\n", sz, sz/1024, w.Hash.Sum32())
  59. defer w.buf.Reset()
  60. return WriteGo(out, pkg, w.buf.Bytes())
  61. }
  62. func (w *CodeWriter) printf(f string, x ...interface{}) {
  63. fmt.Fprintf(w, f, x...)
  64. }
  65. func (w *CodeWriter) insertSep() {
  66. if w.skipSep {
  67. w.skipSep = false
  68. return
  69. }
  70. // Use at least two newlines to ensure a blank space between the previous
  71. // block. WriteGoFile will remove extraneous newlines.
  72. w.printf("\n\n")
  73. }
  74. // WriteComment writes a comment block. All line starts are prefixed with "//".
  75. // Initial empty lines are gobbled. The indentation for the first line is
  76. // stripped from consecutive lines.
  77. func (w *CodeWriter) WriteComment(comment string, args ...interface{}) {
  78. s := fmt.Sprintf(comment, args...)
  79. s = strings.Trim(s, "\n")
  80. // Use at least two newlines to ensure a blank space between the previous
  81. // block. WriteGoFile will remove extraneous newlines.
  82. w.printf("\n\n// ")
  83. w.skipSep = true
  84. // strip first indent level.
  85. sep := "\n"
  86. for ; len(s) > 0 && (s[0] == '\t' || s[0] == ' '); s = s[1:] {
  87. sep += s[:1]
  88. }
  89. strings.NewReplacer(sep, "\n// ", "\n", "\n// ").WriteString(w, s)
  90. w.printf("\n")
  91. }
  92. func (w *CodeWriter) writeSizeInfo(size int) {
  93. w.printf("// Size: %d bytes\n", size)
  94. }
  95. // WriteConst writes a constant of the given name and value.
  96. func (w *CodeWriter) WriteConst(name string, x interface{}) {
  97. w.insertSep()
  98. v := reflect.ValueOf(x)
  99. switch v.Type().Kind() {
  100. case reflect.String:
  101. w.printf("const %s %s = ", name, typeName(x))
  102. w.WriteString(v.String())
  103. w.printf("\n")
  104. default:
  105. w.printf("const %s = %#v\n", name, x)
  106. }
  107. }
  108. // WriteVar writes a variable of the given name and value.
  109. func (w *CodeWriter) WriteVar(name string, x interface{}) {
  110. w.insertSep()
  111. v := reflect.ValueOf(x)
  112. oldSize := w.Size
  113. sz := int(v.Type().Size())
  114. w.Size += sz
  115. switch v.Type().Kind() {
  116. case reflect.String:
  117. w.printf("var %s %s = ", name, typeName(x))
  118. w.WriteString(v.String())
  119. case reflect.Struct:
  120. w.gob.Encode(x)
  121. fallthrough
  122. case reflect.Slice, reflect.Array:
  123. w.printf("var %s = ", name)
  124. w.writeValue(v)
  125. w.writeSizeInfo(w.Size - oldSize)
  126. default:
  127. w.printf("var %s %s = ", name, typeName(x))
  128. w.gob.Encode(x)
  129. w.writeValue(v)
  130. w.writeSizeInfo(w.Size - oldSize)
  131. }
  132. w.printf("\n")
  133. }
  134. func (w *CodeWriter) writeValue(v reflect.Value) {
  135. x := v.Interface()
  136. switch v.Kind() {
  137. case reflect.String:
  138. w.WriteString(v.String())
  139. case reflect.Array:
  140. // Don't double count: callers of WriteArray count on the size being
  141. // added, so we need to discount it here.
  142. w.Size -= int(v.Type().Size())
  143. w.writeSlice(x, true)
  144. case reflect.Slice:
  145. w.writeSlice(x, false)
  146. case reflect.Struct:
  147. w.printf("%s{\n", typeName(v.Interface()))
  148. t := v.Type()
  149. for i := 0; i < v.NumField(); i++ {
  150. w.printf("%s: ", t.Field(i).Name)
  151. w.writeValue(v.Field(i))
  152. w.printf(",\n")
  153. }
  154. w.printf("}")
  155. default:
  156. w.printf("%#v", x)
  157. }
  158. }
  159. // WriteString writes a string literal.
  160. func (w *CodeWriter) WriteString(s string) {
  161. s = strings.Replace(s, `\`, `\\`, -1)
  162. io.WriteString(w.Hash, s) // content hash
  163. w.Size += len(s)
  164. const maxInline = 40
  165. if len(s) <= maxInline {
  166. w.printf("%q", s)
  167. return
  168. }
  169. // We will render the string as a multi-line string.
  170. const maxWidth = 80 - 4 - len(`"`) - len(`" +`)
  171. // When starting on its own line, go fmt indents line 2+ an extra level.
  172. n, max := maxWidth, maxWidth-4
  173. // As per https://golang.org/issue/18078, the compiler has trouble
  174. // compiling the concatenation of many strings, s0 + s1 + s2 + ... + sN,
  175. // for large N. We insert redundant, explicit parentheses to work around
  176. // that, lowering the N at any given step: (s0 + s1 + ... + s63) + (s64 +
  177. // ... + s127) + etc + (etc + ... + sN).
  178. explicitParens, extraComment := len(s) > 128*1024, ""
  179. if explicitParens {
  180. w.printf(`(`)
  181. extraComment = "; the redundant, explicit parens are for https://golang.org/issue/18078"
  182. }
  183. // Print "" +\n, if a string does not start on its own line.
  184. b := w.buf.Bytes()
  185. if p := len(bytes.TrimRight(b, " \t")); p > 0 && b[p-1] != '\n' {
  186. w.printf("\"\" + // Size: %d bytes%s\n", len(s), extraComment)
  187. n, max = maxWidth, maxWidth
  188. }
  189. w.printf(`"`)
  190. for sz, p, nLines := 0, 0, 0; p < len(s); {
  191. var r rune
  192. r, sz = utf8.DecodeRuneInString(s[p:])
  193. out := s[p : p+sz]
  194. chars := 1
  195. if !unicode.IsPrint(r) || r == utf8.RuneError || r == '"' {
  196. switch sz {
  197. case 1:
  198. out = fmt.Sprintf("\\x%02x", s[p])
  199. case 2, 3:
  200. out = fmt.Sprintf("\\u%04x", r)
  201. case 4:
  202. out = fmt.Sprintf("\\U%08x", r)
  203. }
  204. chars = len(out)
  205. }
  206. if n -= chars; n < 0 {
  207. nLines++
  208. if explicitParens && nLines&63 == 63 {
  209. w.printf("\") + (\"")
  210. }
  211. w.printf("\" +\n\"")
  212. n = max - len(out)
  213. }
  214. w.printf("%s", out)
  215. p += sz
  216. }
  217. w.printf(`"`)
  218. if explicitParens {
  219. w.printf(`)`)
  220. }
  221. }
  222. // WriteSlice writes a slice value.
  223. func (w *CodeWriter) WriteSlice(x interface{}) {
  224. w.writeSlice(x, false)
  225. }
  226. // WriteArray writes an array value.
  227. func (w *CodeWriter) WriteArray(x interface{}) {
  228. w.writeSlice(x, true)
  229. }
  230. func (w *CodeWriter) writeSlice(x interface{}, isArray bool) {
  231. v := reflect.ValueOf(x)
  232. w.gob.Encode(v.Len())
  233. w.Size += v.Len() * int(v.Type().Elem().Size())
  234. name := typeName(x)
  235. if isArray {
  236. name = fmt.Sprintf("[%d]%s", v.Len(), name[strings.Index(name, "]")+1:])
  237. }
  238. if isArray {
  239. w.printf("%s{\n", name)
  240. } else {
  241. w.printf("%s{ // %d elements\n", name, v.Len())
  242. }
  243. switch kind := v.Type().Elem().Kind(); kind {
  244. case reflect.String:
  245. for _, s := range x.([]string) {
  246. w.WriteString(s)
  247. w.printf(",\n")
  248. }
  249. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  250. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  251. // nLine and nBlock are the number of elements per line and block.
  252. nLine, nBlock, format := 8, 64, "%d,"
  253. switch kind {
  254. case reflect.Uint8:
  255. format = "%#02x,"
  256. case reflect.Uint16:
  257. format = "%#04x,"
  258. case reflect.Uint32:
  259. nLine, nBlock, format = 4, 32, "%#08x,"
  260. case reflect.Uint, reflect.Uint64:
  261. nLine, nBlock, format = 4, 32, "%#016x,"
  262. case reflect.Int8:
  263. nLine = 16
  264. }
  265. n := nLine
  266. for i := 0; i < v.Len(); i++ {
  267. if i%nBlock == 0 && v.Len() > nBlock {
  268. w.printf("// Entry %X - %X\n", i, i+nBlock-1)
  269. }
  270. x := v.Index(i).Interface()
  271. w.gob.Encode(x)
  272. w.printf(format, x)
  273. if n--; n == 0 {
  274. n = nLine
  275. w.printf("\n")
  276. }
  277. }
  278. w.printf("\n")
  279. case reflect.Struct:
  280. zero := reflect.Zero(v.Type().Elem()).Interface()
  281. for i := 0; i < v.Len(); i++ {
  282. x := v.Index(i).Interface()
  283. w.gob.EncodeValue(v)
  284. if !reflect.DeepEqual(zero, x) {
  285. line := fmt.Sprintf("%#v,\n", x)
  286. line = line[strings.IndexByte(line, '{'):]
  287. w.printf("%d: ", i)
  288. w.printf(line)
  289. }
  290. }
  291. case reflect.Array:
  292. for i := 0; i < v.Len(); i++ {
  293. w.printf("%d: %#v,\n", i, v.Index(i).Interface())
  294. }
  295. default:
  296. panic("gen: slice elem type not supported")
  297. }
  298. w.printf("}")
  299. }
  300. // WriteType writes a definition of the type of the given value and returns the
  301. // type name.
  302. func (w *CodeWriter) WriteType(x interface{}) string {
  303. t := reflect.TypeOf(x)
  304. w.printf("type %s struct {\n", t.Name())
  305. for i := 0; i < t.NumField(); i++ {
  306. w.printf("\t%s %s\n", t.Field(i).Name, t.Field(i).Type)
  307. }
  308. w.printf("}\n")
  309. return t.Name()
  310. }
  311. // typeName returns the name of the go type of x.
  312. func typeName(x interface{}) string {
  313. t := reflect.ValueOf(x).Type()
  314. return strings.Replace(fmt.Sprint(t), "main.", "", 1)
  315. }