-
Notifications
You must be signed in to change notification settings - Fork 58
/
compiler.go
96 lines (89 loc) · 2.23 KB
/
compiler.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
package render
import (
"fmt"
"github.com/osteele/liquid/parser"
)
// Compile parses a source template. It returns an AST root, that can be evaluated.
func (c Config) Compile(source string, loc parser.SourceLoc) (Node, parser.Error) {
root, err := c.Parse(source, loc)
if err != nil {
return nil, err
}
return c.compileNode(root)
}
// nolint: gocyclo
func (c Config) compileNode(n parser.ASTNode) (Node, parser.Error) {
switch n := n.(type) {
case *parser.ASTBlock:
body, err := c.compileNodes(n.Body)
if err != nil {
return nil, err
}
branches, err := c.compileBlocks(n.Clauses)
if err != nil {
return nil, err
}
cd, ok := c.findBlockDef(n.Name)
if !ok {
return nil, parser.Errorf(n, "undefined tag %q", n.Name)
}
node := BlockNode{
Token: n.Token,
Body: body,
Clauses: branches,
}
if cd.parser != nil {
r, err := cd.parser(node)
if err != nil {
return nil, parser.WrapError(err, n)
}
node.renderer = r
}
return &node, nil
case *parser.ASTRaw:
return &RawNode{n.Slices, sourcelessNode{}}, nil
case *parser.ASTSeq:
children, err := c.compileNodes(n.Children)
if err != nil {
return nil, err
}
return &SeqNode{children, sourcelessNode{}}, nil
case *parser.ASTTag:
if td, ok := c.FindTagDefinition(n.Name); ok {
f, err := td(n.Args)
if err != nil {
return nil, parser.Errorf(n, "%s", err)
}
return &TagNode{n.Token, f}, nil
}
return nil, parser.Errorf(n, "undefined tag %q", n.Name)
case *parser.ASTText:
return &TextNode{n.Token}, nil
case *parser.ASTObject:
return &ObjectNode{n.Token, n.Expr}, nil
default:
panic(fmt.Errorf("un-compilable node type %T", n))
}
}
func (c Config) compileBlocks(blocks []*parser.ASTBlock) ([]*BlockNode, parser.Error) {
out := make([]*BlockNode, 0, len(blocks))
for _, child := range blocks {
compiled, err := c.compileNode(child)
if err != nil {
return nil, err
}
out = append(out, compiled.(*BlockNode))
}
return out, nil
}
func (c Config) compileNodes(nodes []parser.ASTNode) ([]Node, parser.Error) {
out := make([]Node, 0, len(nodes))
for _, child := range nodes {
compiled, err := c.compileNode(child)
if err != nil {
return nil, err
}
out = append(out, compiled)
}
return out, nil
}