/
pug_parser.go
302 lines (248 loc) · 6.78 KB
/
pug_parser.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
package pugjs
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"log"
"path"
"strings"
"github.com/pkg/errors"
)
type (
// Attr is a simple key-value pair
Attr struct {
Name string
Val interface{}
MustEscape bool
}
// Fileref is used by include/extends
Fileref struct {
Type, Path string
Line int
}
// Token defines the basic token read by the tokenizer
// Tokens form a tree, where the beginning root node starts the document
Token struct {
// default
Type, Name string
Mode, Val string
Line int
// subblock
Block *Token
// subblock childs
Nodes []*Token
// specific information
AttributeBlocks []*Token
Attrs []*Attr
MustEscape bool
File *Fileref
Filename string
SelfClosing bool
IsInline *bool
Obj string
Key string
// mixin
Call bool // mixin call?
Args string // call args
// if
Test string // if
Consequent, Alternate *Token // if result
// Interpolated
Expr string
}
)
// Parse parses a filename into a Token-tree
func (p *renderState) Parse(file string) (*Token, error) {
b, err := ioutil.ReadFile(path.Join(p.path, file) + ".ast.json")
if err != nil {
return nil, errors.Errorf("Cannot read %q", file)
}
return p.ParseJSON(b, file)
}
// ParseJSON parses a json into a Token-tree
func (p *renderState) ParseJSON(bytes []byte, file string) (*Token, error) {
token := new(Token)
err := json.Unmarshal(bytes, token)
if err != nil {
return nil, errors.WithStack(err)
}
return token, nil
}
// TokenToTemplate gets named Template from Token
func (p *renderState) TokenToTemplate(name string, t *Token) (*Template, string, error) {
//writeTranslations, _ = os.Create("/tmp/en-nz.page-" + strings.Replace(name, "/", "-", -1) + ".json")
//fmt.Fprintf(writeTranslations, "[\n")
//defer func() {
// fmt.Fprintf(writeTranslations, "{}]\n")
// writeTranslations.(*os.File).Close()
//}()
template := New(name).
Funcs(funcmap).
Funcs(p.funcs)
nodes := p.build(t)
wr := new(bytes.Buffer)
for _, b := range nodes {
b.Render(p, wr)
}
for _, b := range p.mixinblocks {
wr.WriteString("\n" + b)
}
for _, b := range p.mixinorder {
wr.WriteString("\n" + p.mixin[b])
}
template, err := template.Parse(wr.String())
if err != nil {
e := err.Error() + "\n"
for i, l := range strings.Split(wr.String(), "\n") {
e += fmt.Sprintf("%03d: %s\n", i+1, strings.TrimSpace(strings.TrimSuffix(l, `{{- "" -}}`)))
}
return nil, "", errors.New(e)
}
for call := range p.mixincalls {
if _, ok := p.mixin[call]; !ok {
if p.debug {
return nil, "", fmt.Errorf("mixin %q called but not found", call)
} else {
p.logger.Warn(fmt.Sprintf("mixin %q called but not found", call))
}
}
}
return template, wr.String(), nil
}
func (p *renderState) build(parent *Token) (res []Node) {
if parent == nil {
return
}
for _, t := range parent.Nodes {
node := p.buildNode(t)
if node != nil {
res = append(res, node)
}
}
return
}
var selfclosing = map[string]bool{
"area": true,
"base": true,
"br": true,
"col": true,
"command": true,
"embed": true,
"hr": true,
"img": true,
"input": true,
"keygen": true,
"link": true,
"meta": true,
"param": true,
"source": true,
"track": true,
"wbr": true,
}
func (p *renderState) buildNode(t *Token) (res Node) {
switch t.Type {
case "Tag":
tag := new(Tag)
tag.Name = t.Name
tag.IsInline = t.IsInline
tag.SelfClosing = t.SelfClosing
for _, a := range t.AttributeBlocks {
tag.AttributeBlocks = append(tag.AttributeBlocks, JavaScriptExpression(a.Val))
}
tag.Block = Block{Nodes: p.build(t.Block)}
for _, a := range t.Attrs {
tag.Attrs = append(tag.Attrs, Attribute{Name: a.Name, Val: JavaScriptExpression(fmt.Sprintf("%v", a.Val)), MustEscape: a.MustEscape})
}
tag.SelfClosing = selfclosing[tag.Name]
return tag
case "Mixin":
mixin := new(Mixin)
mixin.Block = Block{Nodes: p.build(t.Block)}
for _, a := range t.AttributeBlocks {
mixin.AttributeBlocks = append(mixin.AttributeBlocks, JavaScriptExpression(a.Val))
}
mixin.Name = JavaScriptIdentifier(t.Name)
mixin.Args = JavaScriptExpression(`[` + t.Args + `]`)
for _, a := range t.Attrs {
mixin.Attrs = append(mixin.Attrs, Attribute{Name: a.Name, Val: JavaScriptExpression(fmt.Sprintf("%v", a.Val)), MustEscape: a.MustEscape})
}
mixin.Call = t.Call
return mixin
case "Text":
text := new(Text)
t.Val = strings.Replace(t.Val, "{{", `--{{--`, -1)
t.Val = strings.Replace(t.Val, "}}", `--}}--`, -1)
t.Val = strings.Replace(t.Val, "--{{--", `{{"{{"}}`, -1)
t.Val = strings.Replace(t.Val, "--}}--", `{{"}}"}}`, -1)
text.Val = t.Val
return text
case "Code":
code := new(Code)
code.Val = t.Val
code.Block = Block{Nodes: p.build(t.Block)}
code.IsInline = t.IsInline
code.MustEscape = t.MustEscape
return code
case "Conditional":
cond := new(Conditional)
cond.Test = JavaScriptExpression(t.Test)
cond.Consequent = p.buildNode(t.Consequent)
if t.Alternate != nil {
cond.Alternate = p.buildNode(t.Alternate)
}
return cond
case "Each":
each := new(Each)
each.Val = JavaScriptIdentifier(t.Val)
each.Key = JavaScriptIdentifier(t.Key)
each.Obj = JavaScriptExpression(t.Obj)
each.Block = Block{Nodes: p.build(t.Block)}
return each
case "While":
while := new(While)
while.Test = JavaScriptExpression(t.Test)
while.Block = Block{Nodes: p.build(t.Block)}
return while
case "Doctype":
doctype := new(Doctype)
doctype.Val = t.Val
return doctype
case "NamedBlock", "Block":
return &Block{Nodes: p.build(t)}
case "Comment":
return nil
case "BlockComment":
return nil
case "Case":
cas := new(Case)
cas.Expr = JavaScriptExpression(t.Expr)
cas.Block = Block{Nodes: p.build(t.Block)}
return cas
case "When":
when := new(When)
when.Expr = JavaScriptExpression(t.Expr)
when.Block = Block{Nodes: p.build(t.Block)}
return when
case "MixinBlock":
return new(MixinBlock)
case "InterpolatedTag":
interpolatedTag := new(InterpolatedTag)
interpolatedTag.IsInline = t.IsInline
interpolatedTag.Expr = JavaScriptExpression(t.Expr)
interpolatedTag.SelfClosing = t.SelfClosing
for _, a := range t.AttributeBlocks {
interpolatedTag.AttributeBlocks = append(interpolatedTag.AttributeBlocks, JavaScriptExpression(a.Val))
}
interpolatedTag.Block = Block{Nodes: p.build(t.Block)}
for _, a := range t.Attrs {
interpolatedTag.Attrs = append(interpolatedTag.Attrs, Attribute{Name: a.Name, Val: JavaScriptExpression(fmt.Sprintf("%v", a.Val)), MustEscape: a.MustEscape})
}
// todo how?
// interpolatedTag.SelfClosing = selfclosing[interpolatedTag.Name]
return interpolatedTag
default:
log.Printf("%#v\n", t)
panic(errors.Errorf("Cannot parse Pug block %#v", t))
}
}