-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
391 lines (335 loc) · 10.1 KB
/
render.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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
package internal
import (
"bytes"
"fmt"
"io"
"sort"
"strings"
)
type Render struct {
p *Parser
includeDepth int
}
func NewRender(p *Parser) *Render {
return &Render{
p: p,
includeDepth: 0,
}
}
// RenderOutput --
// Writes the parse treee out as a golang file
func (r *Render) RenderOutput(o io.Writer, packageName string, templateName string, langType string, sourcefile string, opt *BlipOptions) {
r.wStr(o, "package ").wStr(o, packageName).wNL(o)
r.wStr(o, "// Do Not Edit\n")
r.wStr(o, fmt.Sprintf("// Generated by Blip\n"))
r.wStr(o, fmt.Sprintf("// source blip: %s\n", sourcefile))
r.outputImports(o, opt)
r.writeFuncts(o)
r.writeMainFunction(o, templateName, langType, opt)
}
func (r *Render) writeMainFunction(o io.Writer, templateName string, langType string, opt *BlipOptions) {
r.wStr(o, "\n\n").
wStr(o, "func ").
wStr(o, r.convertTemplateNameToFunctionName(templateName)).
wStr(o, "( ")
if !r.p.hasErrors() {
r.writeArgVar(o)
}
r.wStr(o, "c context.Context, w io.Writer ) ")
r.wStr(o, `(terror error) {`)
r.wStr(o, "\n start := time.Now()\n")
r.wStr(o, `
var si = blipUtil.Instance()
var escaper = si.GetEscaperFor( "`)
r.wStr(o, langType)
r.wStr(o, `")
defer func() {
if err := recover(); err != nil {
fmt.Printf("Catch panic %s: %s\n", "`)
r.wStr(o, r.convertTemplateNameToFunctionName(templateName))
r.wStr(o, `", err)
terror = fmt.Errorf("%v", err)
}`)
r.wStr(o, `
`)
r.wStr(o, fmt.Sprintf(" si.RenderComplete(escaper, \"%s\", \"%s\", time.Since(start), terror)", templateName, langType))
r.wStr(o, `
}()
`)
if r.p.hasErrors() {
r.wStr(o, "Errors found in transforming the template\n")
for _, err := range r.p.errors {
r.wStr(o, fmt.Sprintf("Error at %d: %s\n", err.lineNum, err.msg))
}
r.wStr(o, "\n")
} else {
r.writeContentVar(o)
r.writeBody(r.p.root, 1, o, opt)
}
r.wStr(o, "\treturn")
r.wStr(o, "\n}")
}
func (r *Render) outputImports(o io.Writer, opt *BlipOptions) {
imports := make(map[string]string)
if !r.p.hasErrors() {
imports["\""+opt.SupportBranch+"\""] = ""
// imports["\"github.com/samlotti/blip/blipUtil\""] = ""
}
imports["\"context\""] = ""
imports["\"io\""] = ""
imports["\"fmt\""] = ""
imports["\"time\""] = ""
if !r.p.hasErrors() {
for _, imp := range r.p.imports {
trimmed := strings.Trim(imp.Literal, "\t")
trimmed = strings.Trim(trimmed, " ")
imports[strings.Trim(trimmed, " ")] = ""
}
}
imports2 := make([]string, 0)
for k, _ := range imports {
imports2 = append(imports2, k)
}
sort.Strings(imports2)
r.wStr(o, "\nimport (")
for _, v := range imports2 {
r.wStr(o, "\n\t").wStr(o, v)
}
r.wStr(o, "\n)\n\n")
}
func (r *Render) writeFuncts(o io.Writer) {
if r.p.hasErrors() {
return
}
for _, fa := range r.p.functions {
for _, ft := range fa.GetChildren() {
r.wStr(o, fmt.Sprintf("// Function block from line: %d\n", ft.GetToken().Line))
r.wStr(o, ft.GetToken().Literal)
}
}
}
func (r *Render) wStr(o io.Writer, msg string) *Render {
o.Write([]byte(msg))
return r
}
func (r *Render) wNL(o io.Writer) *Render {
o.Write([]byte("\n"))
return r
}
func (r *Render) writeArgVar(o io.Writer) {
for idx, c := range r.p.args {
if idx > 0 {
r.wStr(o, ", ")
}
// user := c.Value("user").(manual.User)
split := r.splitString(c.Literal, 2)
r.wStr(o, split[0])
r.wStr(o, " ")
r.wStr(o, split[1])
}
if len(r.p.args) > 0 {
r.wStr(o, ", ")
}
}
func (r *Render) splitString(lit string, max int) []string {
return strings.SplitN(strings.Trim(lit, " "), " ", max)
}
func (r *Render) WriteNodeSimpleCall(o io.Writer, node ast, depth int, contextName string) {
// @include Base @
r.wNL(o)
splits := r.splitString(node.GetToken().Literal, 2)
funName := r.convertTemplateNameToFunctionName(splits[0])
r.wStr(o, r.getTabsDepth(depth))
r.wStr(o, "terror = ")
r.wStr(o, funName).wStr(o, "(")
for idx, s := range splits {
if idx == 0 {
continue
}
if idx > 1 {
r.wStr(o, ", ")
}
r.wStr(o, s)
}
if len(splits) > 1 {
r.wStr(o, ", ")
}
r.wStr(o, fmt.Sprintf("%s, w)\n", contextName))
r.wStr(o, r.getTabsDepth(depth))
r.wStr(o, "if terror != nil { return }\n")
}
// convertTemplateNameToFunctionName
// convert path.path.templateName
// to path.path.TemplateNameRender
func (r *Render) convertTemplateNameToFunctionName(templateName string) string {
sects := strings.Split(templateName, ".")
last := len(sects) - 1
sects[last] = strings.Title(sects[last]) + "Render"
return strings.Join(sects, ".")
}
func (r *Render) getTabsDepth(depth int) string {
var tabs = "\t\t\t\t\t\t\t\t"[0:depth]
return tabs
}
func (r *Render) writeBody(node ast, depth int, o io.Writer, opt *BlipOptions) {
parentbase, ok := node.(*astBase)
inCodeBlock := false
if !ok {
parentbase = nil
} else {
inCodeBlock = parentbase.nodeType == NODE_CODEBLOCK || parentbase.nodeType == NODE_FUNC
}
var cnum = 0
for _, ast := range node.GetChildren() {
base := ast.(*astBase)
var tabs = r.getTabsDepth(depth)
if !inCodeBlock {
if opt.RenderLineNumbers {
// While line numbers look useful, they make a lot of differences in source control compare
r.wStr(o, fmt.Sprintf("%s// Line: %d\n", tabs, base.token.Line))
}
}
switch base.nodeType {
case NODE_TOKEN_RAW:
r.wStr(o, base.token.Literal)
case NODE_TOKEN:
r.wStr(o, fmt.Sprintf("%ssi.Write(w, []byte(\"%s\"))\n", tabs, r.addSlashes(base.token.Literal)))
case NODE_DISPLAY:
// si.WriteStr(w, game.Opponent)
r.wStr(o, fmt.Sprintf("%ssi.WriteStrSafe(w, %s, escaper)\n", tabs, r.addSlashes(base.token.Literal)))
// f.Sp "si.Write(w, indexpage1)")
case NODE_DISPLAY_BOOL:
r.wStr(o, fmt.Sprintf("%ssi.WriteBool(w, %s)\n", tabs, r.addSlashes(base.token.Literal)))
case NODE_DISPLAY_INT:
r.wStr(o, fmt.Sprintf("%ssi.WriteInt(w, %s)\n", tabs, r.addSlashes(base.token.Literal)))
case NODE_DISPLAY_INT64:
r.wStr(o, fmt.Sprintf("%ssi.WriteInt64(w, %s)\n", tabs, r.addSlashes(base.token.Literal)))
case NODE_DISPLAY_RAW:
// si.WriteStr(w, game.Opponent)
r.wStr(o, fmt.Sprintf("%ssi.WriteStr(w, %s)\n", tabs, r.addSlashes(base.token.Literal)))
// f.Sp "si.Write(w, indexpage1)")
case NODE_INCLUDE_SIMPLE:
r.WriteNodeSimpleCall(o, base, depth, "c")
// @include Base @
case NODE_INCLUDE:
r.includeDepth += 1
// var c1 context.Context
r.wStr(o, fmt.Sprintf("%svar %s = context.WithValue(c, \"__Blip__\", 1)\n", tabs, r.contextVarName()))
// Do After
case NODE_CODEBLOCK:
r.wStr(o, fmt.Sprintf("%s// Code block follows\n", tabs))
case NODE_TEXT:
r.wStr(o, fmt.Sprintf("%s// Text block follows\n", tabs))
case NODE_CONTENT:
// var f1 = func() {
cnum += 1
r.wStr(o, fmt.Sprintf("%svar contentF%dS%d = func() (terror error) {\n", tabs, r.includeDepth, cnum))
case NODE_YIELD:
// si.CallCtxFunc(c, "myJavascript")
r.wStr(o, fmt.Sprintf("%sterror = si.CallCtxFunc(c, \"%s\")\n", tabs, r.trimAll(base.token.Literal)))
r.wStr(o, fmt.Sprintf("%sif terror != nil { return }\n", tabs))
case NODE_IF:
r.wStr(o, fmt.Sprintf("%sif %s {\n", tabs, r.trimAll(base.token.Literal)))
case NODE_FOR:
r.WriteNodeForStatement(o, base, depth)
case NODE_ELSE:
r.wStr(o, fmt.Sprintf("%s} else {\n", r.getTabsDepth(depth-1)))
case NODE_ENDIF:
r.wStr(o, fmt.Sprintf("%s}\n", r.getTabsDepth(depth-1)))
case NODE_END:
//if parentbase.nodeType == NODE_CONTENT {
// // We don't actually write the end block when on a content block.
// // due to the way contents are done as lambda functions
//} else {
r.wStr(o, fmt.Sprintf("%s} // end of %s@%d\n", r.getTabsDepth(depth-1), parentbase.token.Type, parentbase.token.Line))
//}
default:
// Force compiler error.. should never happen unless I add new nodes and forget to implement
r.wStr(o, fmt.Sprintf("%s Unsupported Node type: %d: '%s' -> %d\n", tabs, base.nodeType, r.addSlashes(base.token.Literal), len(base.children)))
}
r.writeBody(base, depth+1, o, opt)
switch base.nodeType {
case NODE_INCLUDE:
r.WriteNodeSimpleCall(o, base, depth, r.contextVarName())
r.includeDepth -= 1
case NODE_CONTENT:
// var f1 = func() {
r.wStr(o, fmt.Sprintf("%s// End of content block\n", r.getTabsDepth(depth+1)))
r.wStr(o, fmt.Sprintf("%sreturn\n", r.getTabsDepth(depth+1)))
r.wStr(o, fmt.Sprintf("%s}\n", tabs))
r.wStr(o, fmt.Sprintf("%s%s = context.WithValue(%s, ", tabs, r.contextVarName(), r.contextVarName()))
r.wStr(o, fmt.Sprintf("\"%s\", contentF%dS%d)", r.trimAll(base.token.Literal), r.includeDepth, cnum))
if !opt.RenderLineNumbers {
r.wStr(o, fmt.Sprintf("\n"))
}
}
}
}
func (r *Render) writeContentVar(o io.Writer) {
for _, c := range r.p.context {
eq := " := "
var addNullCheck = false
if strings.Contains(c.Literal, "=") {
eq = " = "
// ex: @context errors []string = make([]string,0)
r.wStr(o, "\tvar ")
r.wStr(o, c.Literal)
r.wStr(o, "\n")
addNullCheck = true
}
// user := c.Value("user").(manual.User)
split := strings.Split(strings.Trim(c.Literal, " "), " ")
if addNullCheck {
// if c.Value("errors") != nil {
r.wStr(o, "\tif c.Value(\"")
r.wStr(o, split[0])
r.wStr(o, "\") != nil {")
r.wNL(o)
r.wStr(o, "\t")
}
r.wStr(o, "\t")
r.wStr(o, split[0])
r.wStr(o, eq)
r.wStr(o, "c.Value(\"")
r.wStr(o, split[0])
r.wStr(o, "\").(")
r.wStr(o, split[1])
r.wStr(o, ")")
r.wNL(o)
if addNullCheck {
// if c.Value("errors") != nil {
r.wStr(o, "\t}")
r.wNL(o)
}
}
}
func (r *Render) contextVarName() string {
return fmt.Sprintf("ctxL%d", r.includeDepth)
}
func (r *Render) trimAll(literal string) string {
return strings.Trim(literal, " ")
}
func (r *Render) WriteNodeForStatement(o io.Writer, base *astBase, depth int) {
sects := r.p.splitFor(base.token)
r.wStr(o, fmt.Sprintf("%sfor idx, %s := range %s { _ = idx\n", r.getTabsDepth(depth), sects[0], sects[2]))
}
func (r *Render) addSlashes(str string) string {
var buf bytes.Buffer
for _, char := range str {
switch char {
case '\n':
buf.WriteString("\\n")
case '\t':
buf.WriteString("\\t")
//case '\'':
// buf.WriteRune('\\')
// buf.WriteRune(char)
case '"':
buf.WriteRune('\\')
buf.WriteRune(char)
default:
buf.WriteRune(char)
}
}
return buf.String()
}