-
Notifications
You must be signed in to change notification settings - Fork 245
/
generator_impl.go
78 lines (65 loc) · 2.09 KB
/
generator_impl.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package generator
import (
"strings"
)
type sourceGenerator struct {
buf strings.Builder // The buffer for the new source code.
indentationLevel int // The current indentation level.
hasNewline bool // Whether there is a newline at the end of the buffer.
hasBlankline bool // Whether there is a blank line at the end of the buffer.
hasIssue bool // Whether there is a translation issue.
hasNewScope bool // Whether there is a new scope at the end of the buffer.
existingLineLength int // Length of the existing line.
}
// ensureBlankLineOrNewScope ensures that there is a blank line or new scope at the tail of the buffer. If not,
// a new line is added.
func (sg *sourceGenerator) ensureBlankLineOrNewScope() {
if !sg.hasBlankline && !sg.hasNewScope {
sg.appendLine()
}
}
// indent increases the current indentation.
func (sg *sourceGenerator) indent() {
sg.indentationLevel = sg.indentationLevel + 1
}
// dedent decreases the current indentation.
func (sg *sourceGenerator) dedent() {
sg.indentationLevel = sg.indentationLevel - 1
}
// appendIssue adds an issue found in generation.
func (sg *sourceGenerator) appendIssue(description string) {
sg.append("/* ")
sg.append(description)
sg.append(" */")
sg.hasIssue = true
}
// append adds the given value to the buffer, indenting as necessary.
func (sg *sourceGenerator) append(value string) {
for _, currentRune := range value {
if currentRune == '\n' {
if sg.hasNewline {
sg.hasBlankline = true
}
sg.buf.WriteRune('\n')
sg.hasNewline = true
sg.existingLineLength = 0
continue
}
sg.hasBlankline = false
sg.hasNewScope = false
if sg.hasNewline {
sg.buf.WriteString(strings.Repeat("\t", sg.indentationLevel))
sg.hasNewline = false
sg.existingLineLength += sg.indentationLevel
}
sg.existingLineLength++
sg.buf.WriteRune(currentRune)
}
}
// appendLine adds a newline.
func (sg *sourceGenerator) appendLine() {
sg.append("\n")
}
func (sg *sourceGenerator) markNewScope() {
sg.hasNewScope = true
}