code.go 9.7 KB

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