Debian Codegraph @

internal/prnt/printer.go

raw symbols SCIP
1 // Package prnt provides common functionality for code generators.
2 package prnt
3
4 import (
5 "bytes"
6 "fmt"
7 "go/build/constraint"
8 "io"
9 "strings"
10 )
11
12 // Generator provides convenience methods for code generators. In particular it
13 // provides fmt-like methods which print to an internal buffer. It also allows
14 // any errors to be stored so they can be checked at the end, rather than having
15 // error checks obscuring the code generation.
16 type Generator struct {
17 buf bytes.Buffer
18 level int // current indentation level
19 indent string // indentation string
20 pending bool // if there's a pending indentation
21 err error // saved error from printing
22 }
23
24 // Raw provides direct access to the underlying output stream.
25 func (g *Generator) Raw() io.Writer {
26 return &g.buf
27 }
28
29 // SetIndentString sets the string used for one level of indentation. Use
30 // Indent() and Dedent() to control indent level.
31 func (g *Generator) SetIndentString(indent string) {
32 g.indent = indent
33 }
34
35 // Indent increments the indent level.
36 func (g *Generator) Indent() {
37 g.level++
38 }
39
40 // Dedent decrements the indent level.
41 func (g *Generator) Dedent() {
42 g.level--
43 }
44
45 // Linef prints formatted output terminated with a new line.
46 func (g *Generator) Linef(format string, args ...any) {
47 g.Printf(format, args...)
48 g.NL()
49 }
50
51 // Printf prints to the internal buffer.
52 func (g *Generator) Printf(format string, args ...any) {
53 if g.err != nil {
54 return
55 }
56 if g.pending {
57 indent := strings.Repeat(g.indent, g.level)
58 format = indent + format
59 g.pending = false
60 }
61 _, err := fmt.Fprintf(&g.buf, format, args...)
62 g.AddError(err)
63 }
64
65 // NL prints a new line.
66 func (g *Generator) NL() {
67 g.Printf("\n")
68 g.pending = true
69 }
70
71 // Comment writes comment lines prefixed with "// ".
72 func (g *Generator) Comment(lines ...string) {
73 for _, line := range lines {
74 line = strings.TrimSpace("// " + line)
75 g.Printf("%s\n", line)
76 }
77 }
78
79 // BuildConstraint outputs a build constraint.
80 func (g *Generator) BuildConstraint(expr string) {
81 line := fmt.Sprintf("//go:build %s", expr)
82 if _, err := constraint.Parse(line); err != nil {
83 g.AddError(err)
84 }
85 g.Linef(line)
86 }
87
88 // AddError records an error in code generation. The first non-nil error will
89 // prevent printing operations from writing anything else, and the error will be
90 // returned from Result().
91 func (g *Generator) AddError(err error) {
92 if err != nil && g.err == nil {
93 g.err = err
94 }
95 }
96
97 // Result returns the printed bytes. If any error was recorded with AddError
98 // during code generation, the first such error will be returned here.
99 func (g *Generator) Result() ([]byte, error) {
100 return g.buf.Bytes(), g.err
101 }