forked from alecthomas/participle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
grammar.go
235 lines (219 loc) · 5.67 KB
/
grammar.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
package participle
import (
"fmt"
"reflect"
"text/scanner"
"github.com/alecthomas/participle/lexer"
)
type generatorContext struct {
lexer.Definition
typeNodes map[reflect.Type]node
symbolsToIDs map[rune]string
}
func newGeneratorContext(lex lexer.Definition) *generatorContext {
return &generatorContext{
Definition: lex,
typeNodes: map[reflect.Type]node{},
symbolsToIDs: lexer.SymbolsByRune(lex),
}
}
// Takes a type and builds a tree of nodes out of it.
func (g *generatorContext) parseType(t reflect.Type) node {
rt := t
t = indirectType(t)
if n, ok := g.typeNodes[t]; ok {
return n
}
if rt.Implements(parseableType) {
return &parseable{rt.Elem()}
}
if reflect.PtrTo(rt).Implements(parseableType) {
return &parseable{rt}
}
switch t.Kind() {
case reflect.Slice, reflect.Ptr:
t = indirectType(t.Elem())
if t.Kind() != reflect.Struct {
panic(fmt.Sprintf("expected a struct but got %T", t))
}
fallthrough
case reflect.Struct:
slexer := lexStruct(t)
out := &strct{typ: t}
g.typeNodes[t] = out // Ensure we avoid infinite recursion.
if slexer.NumField() == 0 {
panicf("can not parse into empty struct %s", t)
}
defer decorate(func() string { return slexer.Field().Name })
e := g.parseDisjunction(slexer)
if e == nil {
panicf("no grammar found in %s", t)
}
if !slexer.Peek().EOF() {
panicf("unexpected input %q", slexer.Peek().Value)
}
out.expr = e
return out
}
panicf("%s should be a struct or should implement the Parseable interface", t)
return nil
}
func (g *generatorContext) parseDisjunction(slexer *structLexer) node {
out := &disjunction{}
for {
out.nodes = append(out.nodes, g.parseSequence(slexer))
if slexer.Peek().Type != '|' {
break
}
slexer.Next() // |
}
if len(out.nodes) == 1 {
return out.nodes[0]
}
return out
}
func (g *generatorContext) parseSequence(slexer *structLexer) node {
head := &sequence{}
cursor := head
loop:
for {
if slexer.Peek().Type == lexer.EOF {
break loop
}
term := g.parseTerm(slexer)
if term == nil {
break loop
}
if cursor.node == nil {
cursor.head = true
cursor.node = term
} else {
cursor.next = &sequence{node: term}
cursor = cursor.next
}
// An optional or repetition result in some magic.
switch node := term.(type) {
case *optional:
node.next = g.parseSequence(slexer)
break loop
case *repetition:
node.next = g.parseSequence(slexer)
break loop
}
}
if head.node == nil {
return nil
}
if head.next == nil {
return head.node
}
return head
}
func (g *generatorContext) parseTerm(slexer *structLexer) node {
r := slexer.Peek()
switch r.Type {
case '@':
return g.parseCapture(slexer)
case scanner.String, scanner.RawString, scanner.Char:
return g.parseLiteral(slexer)
case '[':
return g.parseOptional(slexer)
case '{':
return g.parseRepetition(slexer)
case '(':
return g.parseGroup(slexer)
case scanner.Ident:
return g.parseReference(slexer)
case lexer.EOF:
slexer.Next()
return nil
default:
return nil
}
}
// @<expression> captures <expression> into the current field.
func (g *generatorContext) parseCapture(slexer *structLexer) node {
slexer.Next()
token := slexer.Peek()
field := slexer.Field()
if token.Type == '@' {
slexer.Next()
return &capture{field, g.parseType(field.Type)}
}
if indirectType(field.Type).Kind() == reflect.Struct && !field.Type.Implements(captureType) {
panicf("structs can only be parsed with @@ or by implementing the Capture interface")
}
return &capture{field, g.parseTerm(slexer)}
}
// A reference in the form <identifier> refers to a named token from the lexer.
func (g *generatorContext) parseReference(slexer *structLexer) node {
token := slexer.Next()
if token.Type != scanner.Ident {
panicf("expected identifier")
}
typ, ok := g.Symbols()[token.Value]
if !ok {
panicf("unknown token type %q", token)
}
return &reference{typ: typ, identifier: token.Value}
}
// [ <expression> ] optionally matches <expression>.
func (g *generatorContext) parseOptional(slexer *structLexer) node {
slexer.Next() // [
optional := &optional{node: g.parseDisjunction(slexer)}
next := slexer.Peek()
if next.Type != ']' {
panicf("expected ] but got %q", next)
}
slexer.Next()
return optional
}
// { <expression> } matches 0 or more repititions of <expression>
func (g *generatorContext) parseRepetition(slexer *structLexer) node {
slexer.Next() // {
n := &repetition{
node: g.parseDisjunction(slexer),
}
next := slexer.Next()
if next.Type != '}' {
panicf("expected } but got %q", next)
}
return n
}
// ( <expression> ) groups a sub-expression
func (g *generatorContext) parseGroup(slexer *structLexer) node {
slexer.Next() // (
n := g.parseDisjunction(slexer)
next := slexer.Peek() // )
if next.Type != ')' {
panicf("expected ) but got %q", next)
}
slexer.Next() // )
return n
}
// A literal string.
//
// Note that for this to match, the tokeniser must be able to produce this string. For example,
// if the tokeniser only produces individual characters but the literal is "hello", or vice versa.
func (g *generatorContext) parseLiteral(lex *structLexer) node { // nolint: interfacer
token := lex.Next()
if token.Type != scanner.String && token.Type != scanner.RawString && token.Type != scanner.Char {
panicf("expected quoted string but got %q", token)
}
s := token.Value
t := rune(-1)
token = lex.Peek()
if token.Value == ":" {
lex.Next()
token = lex.Next()
if token.Type != scanner.Ident {
panicf("expected identifier for literal type constraint but got %q", token)
}
var ok bool
t, ok = g.Symbols()[token.Value]
if !ok {
panicf("unknown token type %q in literal type constraint", token)
}
}
return &literal{s: s, t: t, tt: g.symbolsToIDs[t]}
}