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.
22 // This file contains utilities for generating code.
24 // TODO: other write methods like:
25 // - slices, maps, types, etc.
27 // CodeWriter is a utility for writing structured code. It computes the content
28 // hash and size of written content. It ensures there are newlines between
29 // written code blocks.
30 type CodeWriter struct {
33 Hash hash.Hash32 // content hash
35 // For comments we skip the usual one-line separator if they are followed by
40 func (w *CodeWriter) Write(p []byte) (n int, err error) {
44 // NewCodeWriter returns a new CodeWriter.
45 func NewCodeWriter() *CodeWriter {
47 return &CodeWriter{Hash: h, gob: gob.NewEncoder(h)}
50 // WriteGoFile appends the buffer with the total size of all created structures
51 // and writes it as a Go file to the given file with the given package name.
52 func (w *CodeWriter) WriteGoFile(filename, pkg string) {
53 f, err := os.Create(filename)
55 log.Fatalf("Could not create file %s: %v", filename, err)
58 if _, err = w.WriteGo(f, pkg, ""); err != nil {
59 log.Fatalf("Error writing file %s: %v", filename, err)
63 // WriteVersionedGoFile appends the buffer with the total size of all created
64 // structures and writes it as a Go file to the given file with the given
65 // package name and build tags for the current Unicode version,
66 func (w *CodeWriter) WriteVersionedGoFile(filename, pkg string) {
69 pattern := fileToPattern(filename)
70 updateBuildTags(pattern)
71 filename = fmt.Sprintf(pattern, UnicodeVersion())
73 f, err := os.Create(filename)
75 log.Fatalf("Could not create file %s: %v", filename, err)
78 if _, err = w.WriteGo(f, pkg, tags); err != nil {
79 log.Fatalf("Error writing file %s: %v", filename, err)
83 // WriteGo appends the buffer with the total size of all created structures and
84 // writes it as a Go file to the given writer with the given package name.
85 func (w *CodeWriter) WriteGo(out io.Writer, pkg, tags string) (n int, err error) {
88 w.WriteComment("Total table size %d bytes (%dKiB); checksum: %X\n", sz, sz/1024, w.Hash.Sum32())
91 return WriteGo(out, pkg, tags, w.buf.Bytes())
94 func (w *CodeWriter) printf(f string, x ...interface{}) {
95 fmt.Fprintf(w, f, x...)
98 func (w *CodeWriter) insertSep() {
103 // Use at least two newlines to ensure a blank space between the previous
104 // block. WriteGoFile will remove extraneous newlines.
108 // WriteComment writes a comment block. All line starts are prefixed with "//".
109 // Initial empty lines are gobbled. The indentation for the first line is
110 // stripped from consecutive lines.
111 func (w *CodeWriter) WriteComment(comment string, args ...interface{}) {
112 s := fmt.Sprintf(comment, args...)
113 s = strings.Trim(s, "\n")
115 // Use at least two newlines to ensure a blank space between the previous
116 // block. WriteGoFile will remove extraneous newlines.
120 // strip first indent level.
122 for ; len(s) > 0 && (s[0] == '\t' || s[0] == ' '); s = s[1:] {
126 strings.NewReplacer(sep, "\n// ", "\n", "\n// ").WriteString(w, s)
131 func (w *CodeWriter) writeSizeInfo(size int) {
132 w.printf("// Size: %d bytes\n", size)
135 // WriteConst writes a constant of the given name and value.
136 func (w *CodeWriter) WriteConst(name string, x interface{}) {
138 v := reflect.ValueOf(x)
140 switch v.Type().Kind() {
142 w.printf("const %s %s = ", name, typeName(x))
143 w.WriteString(v.String())
146 w.printf("const %s = %#v\n", name, x)
150 // WriteVar writes a variable of the given name and value.
151 func (w *CodeWriter) WriteVar(name string, x interface{}) {
153 v := reflect.ValueOf(x)
155 sz := int(v.Type().Size())
158 switch v.Type().Kind() {
160 w.printf("var %s %s = ", name, typeName(x))
161 w.WriteString(v.String())
165 case reflect.Slice, reflect.Array:
166 w.printf("var %s = ", name)
168 w.writeSizeInfo(w.Size - oldSize)
170 w.printf("var %s %s = ", name, typeName(x))
173 w.writeSizeInfo(w.Size - oldSize)
178 func (w *CodeWriter) writeValue(v reflect.Value) {
182 w.WriteString(v.String())
184 // Don't double count: callers of WriteArray count on the size being
185 // added, so we need to discount it here.
186 w.Size -= int(v.Type().Size())
187 w.writeSlice(x, true)
189 w.writeSlice(x, false)
191 w.printf("%s{\n", typeName(v.Interface()))
193 for i := 0; i < v.NumField(); i++ {
194 w.printf("%s: ", t.Field(i).Name)
195 w.writeValue(v.Field(i))
204 // WriteString writes a string literal.
205 func (w *CodeWriter) WriteString(s string) {
206 io.WriteString(w.Hash, s) // content hash
210 if len(s) <= maxInline {
215 // We will render the string as a multi-line string.
216 const maxWidth = 80 - 4 - len(`"`) - len(`" +`)
218 // When starting on its own line, go fmt indents line 2+ an extra level.
219 n, max := maxWidth, maxWidth-4
221 // As per https://golang.org/issue/18078, the compiler has trouble
222 // compiling the concatenation of many strings, s0 + s1 + s2 + ... + sN,
223 // for large N. We insert redundant, explicit parentheses to work around
224 // that, lowering the N at any given step: (s0 + s1 + ... + s63) + (s64 +
225 // ... + s127) + etc + (etc + ... + sN).
226 explicitParens, extraComment := len(s) > 128*1024, ""
229 extraComment = "; the redundant, explicit parens are for https://golang.org/issue/18078"
232 // Print "" +\n, if a string does not start on its own line.
234 if p := len(bytes.TrimRight(b, " \t")); p > 0 && b[p-1] != '\n' {
235 w.printf("\"\" + // Size: %d bytes%s\n", len(s), extraComment)
236 n, max = maxWidth, maxWidth
241 for sz, p, nLines := 0, 0, 0; p < len(s); {
243 r, sz = utf8.DecodeRuneInString(s[p:])
246 if !unicode.IsPrint(r) || r == utf8.RuneError || r == '"' {
249 out = fmt.Sprintf("\\x%02x", s[p])
251 out = fmt.Sprintf("\\u%04x", r)
253 out = fmt.Sprintf("\\U%08x", r)
256 } else if r == '\\' {
257 out = "\\" + string(r)
260 if n -= chars; n < 0 {
262 if explicitParens && nLines&63 == 63 {
263 w.printf("\") + (\"")
277 // WriteSlice writes a slice value.
278 func (w *CodeWriter) WriteSlice(x interface{}) {
279 w.writeSlice(x, false)
282 // WriteArray writes an array value.
283 func (w *CodeWriter) WriteArray(x interface{}) {
284 w.writeSlice(x, true)
287 func (w *CodeWriter) writeSlice(x interface{}, isArray bool) {
288 v := reflect.ValueOf(x)
289 w.gob.Encode(v.Len())
290 w.Size += v.Len() * int(v.Type().Elem().Size())
293 name = fmt.Sprintf("[%d]%s", v.Len(), name[strings.Index(name, "]")+1:])
296 w.printf("%s{\n", name)
298 w.printf("%s{ // %d elements\n", name, v.Len())
301 switch kind := v.Type().Elem().Kind(); kind {
303 for _, s := range x.([]string) {
307 case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64,
308 reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
309 // nLine and nBlock are the number of elements per line and block.
310 nLine, nBlock, format := 8, 64, "%d,"
317 nLine, nBlock, format = 4, 32, "%#08x,"
318 case reflect.Uint, reflect.Uint64:
319 nLine, nBlock, format = 4, 32, "%#016x,"
324 for i := 0; i < v.Len(); i++ {
325 if i%nBlock == 0 && v.Len() > nBlock {
326 w.printf("// Entry %X - %X\n", i, i+nBlock-1)
328 x := v.Index(i).Interface()
338 zero := reflect.Zero(v.Type().Elem()).Interface()
339 for i := 0; i < v.Len(); i++ {
340 x := v.Index(i).Interface()
342 if !reflect.DeepEqual(zero, x) {
343 line := fmt.Sprintf("%#v,\n", x)
344 line = line[strings.IndexByte(line, '{'):]
350 for i := 0; i < v.Len(); i++ {
351 w.printf("%d: %#v,\n", i, v.Index(i).Interface())
354 panic("gen: slice elem type not supported")
359 // WriteType writes a definition of the type of the given value and returns the
361 func (w *CodeWriter) WriteType(x interface{}) string {
362 t := reflect.TypeOf(x)
363 w.printf("type %s struct {\n", t.Name())
364 for i := 0; i < t.NumField(); i++ {
365 w.printf("\t%s %s\n", t.Field(i).Name, t.Field(i).Type)
371 // typeName returns the name of the go type of x.
372 func typeName(x interface{}) string {
373 t := reflect.ValueOf(x).Type()
374 return strings.Replace(fmt.Sprint(t), "main.", "", 1)