You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

372 lines
9.7 KiB

  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. 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 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. io.WriteString(w.Hash, s) // content hash
  179. w.Size += len(s)
  180. const maxInline = 40
  181. if len(s) <= maxInline {
  182. w.printf("%q", s)
  183. return
  184. }
  185. // We will render the string as a multi-line string.
  186. const maxWidth = 80 - 4 - len(`"`) - len(`" +`)
  187. // When starting on its own line, go fmt indents line 2+ an extra level.
  188. n, max := maxWidth, maxWidth-4
  189. // As per https://golang.org/issue/18078, the compiler has trouble
  190. // compiling the concatenation of many strings, s0 + s1 + s2 + ... + sN,
  191. // for large N. We insert redundant, explicit parentheses to work around
  192. // that, lowering the N at any given step: (s0 + s1 + ... + s63) + (s64 +
  193. // ... + s127) + etc + (etc + ... + sN).
  194. explicitParens, extraComment := len(s) > 128*1024, ""
  195. if explicitParens {
  196. w.printf(`(`)
  197. extraComment = "; the redundant, explicit parens are for https://golang.org/issue/18078"
  198. }
  199. // Print "" +\n, if a string does not start on its own line.
  200. b := w.buf.Bytes()
  201. if p := len(bytes.TrimRight(b, " \t")); p > 0 && b[p-1] != '\n' {
  202. w.printf("\"\" + // Size: %d bytes%s\n", len(s), extraComment)
  203. n, max = maxWidth, maxWidth
  204. }
  205. w.printf(`"`)
  206. for sz, p, nLines := 0, 0, 0; p < len(s); {
  207. var r rune
  208. r, sz = utf8.DecodeRuneInString(s[p:])
  209. out := s[p : p+sz]
  210. chars := 1
  211. if !unicode.IsPrint(r) || r == utf8.RuneError || r == '"' {
  212. switch sz {
  213. case 1:
  214. out = fmt.Sprintf("\\x%02x", s[p])
  215. case 2, 3:
  216. out = fmt.Sprintf("\\u%04x", r)
  217. case 4:
  218. out = fmt.Sprintf("\\U%08x", r)
  219. }
  220. chars = len(out)
  221. } else if r == '\\' {
  222. out = "\\" + string(r)
  223. chars = 2
  224. }
  225. if n -= chars; n < 0 {
  226. nLines++
  227. if explicitParens && nLines&63 == 63 {
  228. w.printf("\") + (\"")
  229. }
  230. w.printf("\" +\n\"")
  231. n = max - len(out)
  232. }
  233. w.printf("%s", out)
  234. p += sz
  235. }
  236. w.printf(`"`)
  237. if explicitParens {
  238. w.printf(`)`)
  239. }
  240. }
  241. // WriteSlice writes a slice value.
  242. func (w *CodeWriter) WriteSlice(x interface{}) {
  243. w.writeSlice(x, false)
  244. }
  245. // WriteArray writes an array value.
  246. func (w *CodeWriter) WriteArray(x interface{}) {
  247. w.writeSlice(x, true)
  248. }
  249. func (w *CodeWriter) writeSlice(x interface{}, isArray bool) {
  250. v := reflect.ValueOf(x)
  251. w.gob.Encode(v.Len())
  252. w.Size += v.Len() * int(v.Type().Elem().Size())
  253. name := typeName(x)
  254. if isArray {
  255. name = fmt.Sprintf("[%d]%s", v.Len(), name[strings.Index(name, "]")+1:])
  256. }
  257. if isArray {
  258. w.printf("%s{\n", name)
  259. } else {
  260. w.printf("%s{ // %d elements\n", name, v.Len())
  261. }
  262. switch kind := v.Type().Elem().Kind(); kind {
  263. case reflect.String:
  264. for _, s := range x.([]string) {
  265. w.WriteString(s)
  266. w.printf(",\n")
  267. }
  268. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  269. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  270. // nLine and nBlock are the number of elements per line and block.
  271. nLine, nBlock, format := 8, 64, "%d,"
  272. switch kind {
  273. case reflect.Uint8:
  274. format = "%#02x,"
  275. case reflect.Uint16:
  276. format = "%#04x,"
  277. case reflect.Uint32:
  278. nLine, nBlock, format = 4, 32, "%#08x,"
  279. case reflect.Uint, reflect.Uint64:
  280. nLine, nBlock, format = 4, 32, "%#016x,"
  281. case reflect.Int8:
  282. nLine = 16
  283. }
  284. n := nLine
  285. for i := 0; i < v.Len(); i++ {
  286. if i%nBlock == 0 && v.Len() > nBlock {
  287. w.printf("// Entry %X - %X\n", i, i+nBlock-1)
  288. }
  289. x := v.Index(i).Interface()
  290. w.gob.Encode(x)
  291. w.printf(format, x)
  292. if n--; n == 0 {
  293. n = nLine
  294. w.printf("\n")
  295. }
  296. }
  297. w.printf("\n")
  298. case reflect.Struct:
  299. zero := reflect.Zero(v.Type().Elem()).Interface()
  300. for i := 0; i < v.Len(); i++ {
  301. x := v.Index(i).Interface()
  302. w.gob.EncodeValue(v)
  303. if !reflect.DeepEqual(zero, x) {
  304. line := fmt.Sprintf("%#v,\n", x)
  305. line = line[strings.IndexByte(line, '{'):]
  306. w.printf("%d: ", i)
  307. w.printf(line)
  308. }
  309. }
  310. case reflect.Array:
  311. for i := 0; i < v.Len(); i++ {
  312. w.printf("%d: %#v,\n", i, v.Index(i).Interface())
  313. }
  314. default:
  315. panic("gen: slice elem type not supported")
  316. }
  317. w.printf("}")
  318. }
  319. // WriteType writes a definition of the type of the given value and returns the
  320. // type name.
  321. func (w *CodeWriter) WriteType(x interface{}) string {
  322. t := reflect.TypeOf(x)
  323. w.printf("type %s struct {\n", t.Name())
  324. for i := 0; i < t.NumField(); i++ {
  325. w.printf("\t%s %s\n", t.Field(i).Name, t.Field(i).Type)
  326. }
  327. w.printf("}\n")
  328. return t.Name()
  329. }
  330. // typeName returns the name of the go type of x.
  331. func typeName(x interface{}) string {
  332. t := reflect.ValueOf(x).Type()
  333. return strings.Replace(fmt.Sprint(t), "main.", "", 1)
  334. }