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.
 
 
 

339 lines
8.5 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 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. // See golang.org/issue/13145.
  102. const arbitraryCutoff = 16
  103. if v.Len() > arbitraryCutoff {
  104. w.printf("var %s %s = ", name, typeName(x))
  105. } else {
  106. w.printf("const %s %s = ", name, typeName(x))
  107. }
  108. w.WriteString(v.String())
  109. w.printf("\n")
  110. default:
  111. w.printf("const %s = %#v\n", name, x)
  112. }
  113. }
  114. // WriteVar writes a variable of the given name and value.
  115. func (w *CodeWriter) WriteVar(name string, x interface{}) {
  116. w.insertSep()
  117. v := reflect.ValueOf(x)
  118. oldSize := w.Size
  119. sz := int(v.Type().Size())
  120. w.Size += sz
  121. switch v.Type().Kind() {
  122. case reflect.String:
  123. w.printf("var %s %s = ", name, typeName(x))
  124. w.WriteString(v.String())
  125. case reflect.Struct:
  126. w.gob.Encode(x)
  127. fallthrough
  128. case reflect.Slice, reflect.Array:
  129. w.printf("var %s = ", name)
  130. w.writeValue(v)
  131. w.writeSizeInfo(w.Size - oldSize)
  132. default:
  133. w.printf("var %s %s = ", name, typeName(x))
  134. w.gob.Encode(x)
  135. w.writeValue(v)
  136. w.writeSizeInfo(w.Size - oldSize)
  137. }
  138. w.printf("\n")
  139. }
  140. func (w *CodeWriter) writeValue(v reflect.Value) {
  141. x := v.Interface()
  142. switch v.Kind() {
  143. case reflect.String:
  144. w.WriteString(v.String())
  145. case reflect.Array:
  146. // Don't double count: callers of WriteArray count on the size being
  147. // added, so we need to discount it here.
  148. w.Size -= int(v.Type().Size())
  149. w.writeSlice(x, true)
  150. case reflect.Slice:
  151. w.writeSlice(x, false)
  152. case reflect.Struct:
  153. w.printf("%s{\n", typeName(v.Interface()))
  154. t := v.Type()
  155. for i := 0; i < v.NumField(); i++ {
  156. w.printf("%s: ", t.Field(i).Name)
  157. w.writeValue(v.Field(i))
  158. w.printf(",\n")
  159. }
  160. w.printf("}")
  161. default:
  162. w.printf("%#v", x)
  163. }
  164. }
  165. // WriteString writes a string literal.
  166. func (w *CodeWriter) WriteString(s string) {
  167. io.WriteString(w.Hash, s) // content hash
  168. w.Size += len(s)
  169. const maxInline = 40
  170. if len(s) <= maxInline {
  171. w.printf("%q", s)
  172. return
  173. }
  174. // We will render the string as a multi-line string.
  175. const maxWidth = 80 - 4 - len(`"`) - len(`" +`)
  176. // When starting on its own line, go fmt indents line 2+ an extra level.
  177. n, max := maxWidth, maxWidth-4
  178. // Print "" +\n, if a string does not start on its own line.
  179. b := w.buf.Bytes()
  180. if p := len(bytes.TrimRight(b, " \t")); p > 0 && b[p-1] != '\n' {
  181. w.printf("\"\" + // Size: %d bytes\n", len(s))
  182. n, max = maxWidth, maxWidth
  183. }
  184. w.printf(`"`)
  185. for sz, p := 0, 0; p < len(s); {
  186. var r rune
  187. r, sz = utf8.DecodeRuneInString(s[p:])
  188. out := s[p : p+sz]
  189. chars := 1
  190. if !unicode.IsPrint(r) || r == utf8.RuneError || r == '"' {
  191. switch sz {
  192. case 1:
  193. out = fmt.Sprintf("\\x%02x", s[p])
  194. case 2, 3:
  195. out = fmt.Sprintf("\\u%04x", r)
  196. case 4:
  197. out = fmt.Sprintf("\\U%08x", r)
  198. }
  199. chars = len(out)
  200. }
  201. if n -= chars; n < 0 {
  202. w.printf("\" +\n\"")
  203. n = max - len(out)
  204. }
  205. w.printf("%s", out)
  206. p += sz
  207. }
  208. w.printf(`"`)
  209. }
  210. // WriteSlice writes a slice value.
  211. func (w *CodeWriter) WriteSlice(x interface{}) {
  212. w.writeSlice(x, false)
  213. }
  214. // WriteArray writes an array value.
  215. func (w *CodeWriter) WriteArray(x interface{}) {
  216. w.writeSlice(x, true)
  217. }
  218. func (w *CodeWriter) writeSlice(x interface{}, isArray bool) {
  219. v := reflect.ValueOf(x)
  220. w.gob.Encode(v.Len())
  221. w.Size += v.Len() * int(v.Type().Elem().Size())
  222. name := typeName(x)
  223. if isArray {
  224. name = fmt.Sprintf("[%d]%s", v.Len(), name[strings.Index(name, "]")+1:])
  225. }
  226. if isArray {
  227. w.printf("%s{\n", name)
  228. } else {
  229. w.printf("%s{ // %d elements\n", name, v.Len())
  230. }
  231. switch kind := v.Type().Elem().Kind(); kind {
  232. case reflect.String:
  233. for _, s := range x.([]string) {
  234. w.WriteString(s)
  235. w.printf(",\n")
  236. }
  237. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
  238. reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
  239. // nLine and nBlock are the number of elements per line and block.
  240. nLine, nBlock, format := 8, 64, "%d,"
  241. switch kind {
  242. case reflect.Uint8:
  243. format = "%#02x,"
  244. case reflect.Uint16:
  245. format = "%#04x,"
  246. case reflect.Uint32:
  247. nLine, nBlock, format = 4, 32, "%#08x,"
  248. case reflect.Uint, reflect.Uint64:
  249. nLine, nBlock, format = 4, 32, "%#016x,"
  250. case reflect.Int8:
  251. nLine = 16
  252. }
  253. n := nLine
  254. for i := 0; i < v.Len(); i++ {
  255. if i%nBlock == 0 && v.Len() > nBlock {
  256. w.printf("// Entry %X - %X\n", i, i+nBlock-1)
  257. }
  258. x := v.Index(i).Interface()
  259. w.gob.Encode(x)
  260. w.printf(format, x)
  261. if n--; n == 0 {
  262. n = nLine
  263. w.printf("\n")
  264. }
  265. }
  266. w.printf("\n")
  267. case reflect.Struct:
  268. zero := reflect.Zero(v.Type().Elem()).Interface()
  269. for i := 0; i < v.Len(); i++ {
  270. x := v.Index(i).Interface()
  271. w.gob.EncodeValue(v)
  272. if !reflect.DeepEqual(zero, x) {
  273. line := fmt.Sprintf("%#v,\n", x)
  274. line = line[strings.IndexByte(line, '{'):]
  275. w.printf("%d: ", i)
  276. w.printf(line)
  277. }
  278. }
  279. case reflect.Array:
  280. for i := 0; i < v.Len(); i++ {
  281. w.printf("%d: %#v,\n", i, v.Index(i).Interface())
  282. }
  283. default:
  284. panic("gen: slice elem type not supported")
  285. }
  286. w.printf("}")
  287. }
  288. // WriteType writes a definition of the type of the given value and returns the
  289. // type name.
  290. func (w *CodeWriter) WriteType(x interface{}) string {
  291. t := reflect.TypeOf(x)
  292. w.printf("type %s struct {\n", t.Name())
  293. for i := 0; i < t.NumField(); i++ {
  294. w.printf("\t%s %s\n", t.Field(i).Name, t.Field(i).Type)
  295. }
  296. w.printf("}\n")
  297. return t.Name()
  298. }
  299. // typeName returns the name of the go type of x.
  300. func typeName(x interface{}) string {
  301. t := reflect.ValueOf(x).Type()
  302. return strings.Replace(fmt.Sprint(t), "main.", "", 1)
  303. }