-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparser.go
More file actions
142 lines (117 loc) · 2.35 KB
/
parser.go
File metadata and controls
142 lines (117 loc) · 2.35 KB
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
package whtml
import (
"fmt"
"io"
)
// Error represenns a syntax error.
type Error struct {
Message string
Pos Pos
}
// Error returns the formatted string error message.
func (e *Error) Error() string {
return sfmt("%v:%v: %v", e.Pos.Line+1, e.Pos.Char, e.Message)
}
// ErrorList represenns a list of syntax errors.
type ErrorList []error
// Error returns the formatted string error message.
func (a ErrorList) Error() string {
switch len(a) {
case 0:
return "no errors"
case 1:
return a[0].Error()
}
return fmt.Sprintf("%s (and %d more errors)", a[0], len(a)-1)
}
type Parser struct {
s *Scanner
ns *nodeStack
root *Node
}
func (z *Parser) newNode(tok *Token) *Node {
switch tok.Type {
case StartTagToken, SelfClosingTagToken:
return &Node{
Type: ElementNode,
Data: tok.Data,
Attrs: tok.Attrs,
Pos: tok.Pos,
}
case TextToken:
return &Node{
Type: TextNode,
Data: tok.Data,
Pos: tok.Pos,
}
case MustacheToken:
return &Node{
Type: MustacheNode,
Data: tok.Data,
Pos: tok.Pos,
}
default:
panic("This token type cannot be used for node creation")
}
return nil
}
func (z *Parser) addChildNode(node *Node) {
parent := z.ns.top()
if parent == nil {
parent = z.root
}
parent.AppendChild(node)
}
func (z *Parser) parse() error {
for {
tok := z.s.Scan()
switch tok.Type {
case ErrorToken:
return z.s.Errors[0]
case EOFToken:
opening := z.ns.top()
if opening != nil {
return &Error{
Message: sfmt("Unexpected end-of-file. "+
"Expecting closing tag for %v", opening.Data),
Pos: tok.Pos,
}
}
return nil
case StartTagToken:
node := z.newNode(tok)
z.addChildNode(node)
z.ns.push(node)
case SelfClosingTagToken, TextToken, MustacheToken:
node := z.newNode(tok)
z.addChildNode(node)
case EndTagToken:
opening := z.ns.top()
if opening == nil || opening.Data != tok.Data {
return &Error{
Message: sfmt("Closing '%v' tag not matching an opening one", tok.Data),
Pos: tok.Pos,
}
}
z.ns.pop()
}
}
return nil
}
func Parse(rd io.Reader) ([]*Node, error) {
s := NewScanner(rd)
p := &Parser{
ns: &nodeStack{},
s: s,
root: &Node{},
}
err := p.parse()
if err != nil {
return nil, err
}
var l []*Node
for c := p.root.FirstChild; c != nil; c = c.NextSibling {
l = append(l, c)
}
return l, nil
}