-
Notifications
You must be signed in to change notification settings - Fork 3
/
ast.go
315 lines (275 loc) · 7.9 KB
/
ast.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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
package got
import (
"fmt"
"html"
"io"
"os"
"strings"
)
type astType struct {
topItem tokenItem
}
type astWalker struct {
w io.Writer
textMode bool
escapeText bool
htmlBreaks bool
translate bool
// previousOutputEndedInNewline help us concatenate multiple blocks so they don't get extra lines
previousOutputEndedInNewline bool
}
// buildAst creates an symbol tree for the given file.
//
// named blocks are previously named blocks to use, and that are added to during the process
func buildAst(fileName string, namedBlocks map[string]namedBlockEntry) (ret astType, err error) {
var inFile *os.File
inFile, err = os.Open(fileName)
if err != nil {
return
}
defer func() {
_ = inFile.Close()
}()
l := lexFile(fileName, inFile, namedBlocks)
ret.topItem = parse(l)
if ret.topItem.typ == itemError {
err = fmt.Errorf(ret.topItem.FormatError())
}
return
}
func outputAsts(outPath string, asts ...astType) error {
outFile, err := os.Create(outPath)
if err != nil {
return fmt.Errorf("Could not open output file " + outPath + " error: " + err.Error())
}
defer func() {
_ = outFile.Close()
}()
_, err = io.WriteString(outFile, "//** This file was code generated by GoT. DO NOT EDIT. ***\n\n\n")
if err != nil {
return fmt.Errorf("Could not write to output file " + outPath + " error: " + err.Error())
}
for _, ast := range asts {
walker := astWalker{w: outFile, previousOutputEndedInNewline: true}
err = walker.walk(ast.topItem)
if err != nil {
break
}
}
return err
}
func (a *astWalker) walk(item tokenItem) error {
switch item.typ {
case itemGo:
defer a.setTextMode(a.textMode, a.escapeText, a.htmlBreaks, a.translate)
a.setTextMode(false, false, false, false)
return a.walkItems(item.childItems)
case itemText:
defer a.setTextMode(a.textMode, a.escapeText, a.htmlBreaks, a.translate)
a.setTextMode(true, item.escaped, item.htmlBreaks, item.translate)
if len(item.childItems) == 0 {
return nil
}
return a.walkItems(item.childItems)
case itemStrictBlock:
defer a.setTextMode(a.textMode, a.escapeText, a.htmlBreaks, a.translate)
a.setTextMode(true, item.escaped, item.htmlBreaks, item.translate)
return a.outputText(item.val)
case itemRun:
return a.outputRun(item)
case itemString:
fallthrough
case itemBool:
fallthrough
case itemInt:
fallthrough
case itemUInt:
fallthrough
case itemFloat:
fallthrough
case itemInterface:
fallthrough
case itemBytes:
return a.outputValue(item)
case itemGoErr:
return a.outputGoErr(item)
case itemIf:
return a.outputIf(item)
case itemFor:
return a.outputFor(item)
case itemJoin:
return a.outputJoin(item)
default:
panic("unexpected token while walking ast")
}
}
func (a *astWalker) walkItems(items []tokenItem) (err error) {
for _, i := range items {
err = a.walk(i)
if err != nil {
break
}
}
return
}
func (a *astWalker) setTextMode(textMode, escapeText, htmlBreaks bool, translate bool) {
a.textMode = textMode
a.escapeText = escapeText
a.htmlBreaks = htmlBreaks
a.translate = translate
}
// outputText sends plain text to the template. There are some nuances here.
// The val includes the space character that comes after the opening tag. We may
// or may not use that character, depending on the circumstances.
func (a *astWalker) outputText(val string) (err error) {
if val == "" {
return
}
if a.previousOutputEndedInNewline && (val[0] == '\n' || val[0] == '\r') {
if len(val) >= 2 && val[:2] == "\r\n" {
val = val[2:]
} else {
val = val[1:]
}
if val == "" {
return
}
}
a.previousOutputEndedInNewline = val[len(val)-1] == '\n'
if a.escapeText {
val = html.EscapeString(val)
if a.htmlBreaks {
val = strings.Replace(val, "\r\n", "\n", -1)
val = strings.Replace(val, "\n\n", "</p><p>", -1)
val = strings.Replace(val, "\n", "<br>\n", -1)
val = strings.Replace(val, "</p><p>", "</p>\n<p>", -1) // pretty print it so its inspectable
val = "<p>" + val + "</p>\n"
}
}
if a.translate {
// Yes, we may be translating html encoded text here.
_, err = io.WriteString(a.w, "\nif _,err = io.WriteString(_w, t.Translate("+quoteText(val)+")); err != nil {return}\n")
} else {
_, err = io.WriteString(a.w, "\nif _,err = io.WriteString(_w, "+quoteText(val)+"); err != nil {return}\n")
}
return
}
func (a *astWalker) outputRun(item tokenItem) error {
if !a.textMode {
return a.outputGo(item.val)
} else {
return a.outputText(item.val)
}
}
func (a *astWalker) outputGo(code string) (err error) {
_, err = io.WriteString(a.w, code)
return
}
// outputValue sends a particular value to output
// outputValue overrides the current text environment, but does not change it
func (a *astWalker) outputValue(item tokenItem) (err error) {
writer := `io.WriteString(_w, %s)`
if item.htmlBreaks { // assume escaped too
writer = `io.WriteString(_w, strings.Replace(html.EscapeString(%s), "\n", "<br>\n", -1))`
} else if item.escaped {
writer = `io.WriteString(_w, html.EscapeString(%s))`
}
var formatter string
switch item.typ {
case itemBool:
formatter = `strconv.FormatBool(%s)`
case itemInt:
formatter = `strconv.Itoa(%s)`
case itemUInt:
formatter = `strconv.FormatUint(uint64(%s), 10)`
case itemInterface:
formatter = `fmt.Sprint(%s)`
case itemFloat:
formatter = `strconv.FormatFloat(float64(%s), 'g', -1, 64)`
case itemBytes:
formatter = `string(%s[:])`
default:
formatter = `%s`
}
var out string
if item.withError {
out = fmt.Sprintf(`
{
_v,_err2 := %s
if _,err = %s; err != nil {return}
if _err2 != nil {return err}
}
`, item.val,
fmt.Sprintf(writer, fmt.Sprintf(formatter, "_v")))
} else {
out = fmt.Sprintf("\n if _,err = %s; err != nil {return}\n", fmt.Sprintf(writer, fmt.Sprintf(formatter, item.val)))
}
_, err = io.WriteString(a.w, out)
a.previousOutputEndedInNewline = false
return
}
func (a *astWalker) outputGoErr(item tokenItem) (err error) {
_,err = fmt.Fprintf(a.w, "\nif err = %s; err != nil {return}\n", item.val)
return
}
// Generally speaking, text is quoted with a backtick character. However, there is a special case. If the text actually
// contains a backtick character, we cannot use backticks to quote them, but rather double-quotes. This function prepares
// text, looking for these backticks, and then returns a golang quoted text that can be suitably used in all situations.
func quoteText(val string) string {
return "`" + strings.Replace(val, "`", "` + \"`\" + `", -1) + "`"
}
func (a *astWalker) outputIf(topItem tokenItem) (err error) {
for _, ifItem := range topItem.childItems {
switch ifItem.typ {
case itemIf:
_, err = fmt.Fprintf(a.w, "\nif %s {\n", ifItem.val)
case itemElseIf:
_, err = fmt.Fprintf(a.w, "\n} else if %s {\n", ifItem.val)
case itemElse:
_, err = fmt.Fprintf(a.w, "\n} else {\n")
}
if err != nil {
return err
}
defer a.setTextMode(a.textMode, a.escapeText, a.htmlBreaks, a.translate)
a.setTextMode(true, false, false, false)
if err = a.walkItems(ifItem.childItems); err != nil {
return err
}
}
if _, err = fmt.Fprintf(a.w, "\n}\n"); err != nil {
return err
}
return
}
func (a *astWalker) outputFor(item tokenItem) (err error) {
_, err = fmt.Fprintf(a.w, "\nfor %s {\n", item.val)
defer a.setTextMode(a.textMode, a.escapeText, a.htmlBreaks, a.translate)
a.setTextMode(true, false, false, false)
if err = a.walkItems(item.childItems); err != nil {
return err
}
if _, err = fmt.Fprintf(a.w, "\n}\n"); err != nil {
return err
}
return
}
func (a *astWalker) outputJoin(item tokenItem) (err error) {
_, err = fmt.Fprintf(a.w, `
for _i,_j := range %s {
_ = _j
`, item.params["slice"].val)
{
defer a.setTextMode(a.textMode, a.escapeText, a.htmlBreaks, a.translate)
a.setTextMode(true, false, false, false)
if err = a.walkItems(item.childItems); err != nil {
return err
}
}
_, err = fmt.Fprintf(a.w, `
if _i < len(%s) - 1 {
if _, err = io.WriteString(_w, %q); err != nil {return}
}
}`, item.params["slice"].val, item.params["joinString"].val)
return
}