forked from alecthomas/participle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodes.go
435 lines (377 loc) · 10.2 KB
/
nodes.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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
package participle
import (
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/alecthomas/participle/lexer"
)
var (
positionType = reflect.TypeOf(lexer.Position{})
captureType = reflect.TypeOf((*Capture)(nil)).Elem()
parseableType = reflect.TypeOf((*Parseable)(nil)).Elem()
// NextMatch should be returned by Parseable.Parse() method implementations to indicate
// that the node did not match and that other matches should be attempted, if appropriate.
NextMatch = errors.New("no match") // nolint: golint
)
// A node in the grammar.
type node interface {
// Parse from scanner into value.
// Nodes should panic if parsing fails.
Parse(lex lexer.PeekingLexer, parent reflect.Value) []reflect.Value
String() string
}
func decorate(name func() string) {
if msg := recover(); msg != nil {
switch msg := msg.(type) {
case Error:
panicf("%s: %s", name(), msg)
case *lexer.Error:
panic(&lexer.Error{Message: name() + ": " + msg.Message, Pos: msg.Pos})
default:
panic(msg)
}
}
}
func recoverToError(err *error) {
if msg := recover(); msg != nil {
switch msg := msg.(type) {
case Error:
*err = msg
case *lexer.Error:
*err = msg
default:
panic(msg)
}
}
}
// A node that proxies to an implementation that implements the Parseable interface.
type parseable struct {
t reflect.Type
}
func (p *parseable) String() string { return stringer(p) }
func (p *parseable) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
rv := reflect.New(p.t)
v := rv.Interface().(Parseable)
err := v.Parse(lex)
if err != nil {
if err == NextMatch {
return nil
}
panic(err)
}
return []reflect.Value{rv.Elem()}
}
type strct struct {
typ reflect.Type
expr node
}
func (s *strct) String() string { return stringer(s) }
func (s *strct) maybeInjectPos(pos lexer.Position, v reflect.Value) {
if f := v.FieldByName("Pos"); f.IsValid() && f.Type() == positionType {
f.Set(reflect.ValueOf(pos))
}
}
func (s *strct) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
sv := reflect.New(s.typ).Elem()
s.maybeInjectPos(lex.Peek(0).Pos, sv)
if s.expr.Parse(lex, sv) == nil {
return nil
}
return []reflect.Value{sv}
}
// <expr> {"|" <expr>}
type disjunction struct {
nodes []node
lookahead lookaheadTable
}
func (d *disjunction) String() string { return stringer(d) }
func (d *disjunction) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
if selected := d.lookahead.Select(lex, parent); selected != -2 {
if selected == -1 {
return nil
}
return d.nodes[selected].Parse(lex, parent)
}
// Same logic without lookahead.
for _, a := range d.nodes {
if value := a.Parse(lex, parent); value != nil {
return value
}
}
return nil
}
// <node> ...
type sequence struct {
head bool
node node
next *sequence
}
func (s *sequence) String() string { return stringer(s) }
func (s *sequence) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
for n := s; n != nil; n = n.next {
child := n.node.Parse(lex, parent)
if child == nil {
// Early exit if first value doesn't match, otherwise all values must match.
if n == s {
return nil
}
lexer.Panicf(lex.Peek(0).Pos, "unexpected %q (expected %s)", lex.Peek(0), n)
}
out = append(out, child...)
}
return out
}
// @<expr>
type capture struct {
field structLexerField
node node
}
func (c *capture) String() string { return stringer(c) }
func (c *capture) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
pos := lex.Peek(0).Pos
v := c.node.Parse(lex, parent)
if v == nil {
return nil
}
setField(pos, parent, c.field, v)
return []reflect.Value{parent}
}
// <identifier> - named lexer token reference
type reference struct {
typ rune
identifier string // Used for informational purposes.
}
func (r *reference) String() string { return stringer(r) }
func (r *reference) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
token := lex.Peek(0)
if token.Type != r.typ {
return nil
}
return []reflect.Value{reflect.ValueOf(lex.Next().Value)}
}
// [ <expr> ] <sequence>
type optional struct {
node node
next node
lookahead lookaheadTable
}
func (o *optional) String() string { return stringer(o) }
func (o *optional) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
switch o.lookahead.Select(lex, parent) {
case -2: // No lookahead table
fallthrough
case 0:
out = o.node.Parse(lex, parent)
if out == nil {
out = []reflect.Value{}
}
fallthrough
case 1:
if o.next != nil {
next := o.next.Parse(lex, parent)
if next == nil {
return nil
}
out = append(out, next...)
}
return out
case -1:
// We have a next node but neither it or the optional matched the lookahead, so it's a complete mismatch.
if o.next != nil {
return nil
}
return []reflect.Value{}
default:
panic("unexpected selection")
}
}
// { <expr> } <sequence>
type repetition struct {
node node
next node
lookahead lookaheadTable
}
func (r *repetition) String() string { return stringer(r) }
// Parse a repetition. Once a repetition is encountered it will always match, so grammars
// should ensure that branches are differentiated prior to the repetition.
func (r *repetition) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
switch r.lookahead.Select(lex, parent) {
case -2: // No lookahead table
fallthrough
case 0:
for {
v := r.node.Parse(lex, parent)
if v == nil {
break
}
out = append(out, v...)
}
if out == nil {
out = []reflect.Value{}
}
fallthrough
case 1:
if r.next != nil {
next := r.next.Parse(lex, parent)
if next == nil {
return nil
}
out = append(out, next...)
}
return out
case -1:
// We have a next node but neither it or the optional matched the lookahead, so it's a complete mismatch.
if r.next != nil {
return nil
}
return []reflect.Value{}
default:
panic("unexpected selection")
}
}
// Match a token literal exactly "..."[:<type>].
type literal struct {
s string
t rune
tt string // Used for display purposes - symbolic name of t.
}
func (l *literal) String() string { return stringer(l) }
func (l *literal) Parse(lex lexer.PeekingLexer, parent reflect.Value) (out []reflect.Value) {
token := lex.Peek(0)
if token.Value == l.s && (l.t == -1 || l.t == token.Type) {
return []reflect.Value{reflect.ValueOf(lex.Next().Value)}
}
return nil
}
// Attempt to transform values to given type.
//
// This will dereference pointers, and attempt to parse strings into integer values, floats, etc.
func conform(t reflect.Type, values []reflect.Value) (out []reflect.Value) {
for _, v := range values {
for t != v.Type() && t.Kind() == reflect.Ptr && v.Kind() != reflect.Ptr {
v = v.Addr()
}
switch t.Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(v.String(), 0, 64)
if err == nil {
v = reflect.New(t).Elem()
v.SetInt(n)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
n, err := strconv.ParseUint(v.String(), 0, 64)
if err == nil {
v = reflect.New(t).Elem()
v.SetUint(n)
}
case reflect.Bool:
v = reflect.ValueOf(true)
case reflect.Float32, reflect.Float64:
n, err := strconv.ParseFloat(v.String(), 64)
if err == nil {
v = reflect.New(t).Elem()
v.SetFloat(n)
}
}
out = append(out, v)
}
return out
}
// Set field.
//
// If field is a pointer the pointer will be set to the value. If field is a string, value will be
// appended. If field is a slice, value will be appended to slice.
//
// For all other types, an attempt will be made to convert the string to the corresponding
// type (int, float32, etc.).
func setField(pos lexer.Position, strct reflect.Value, field structLexerField, fieldValue []reflect.Value) { // nolint: gocyclo
defer decorate(func() string { return strct.Type().String() + "." + field.Name })
f := strct.FieldByIndex(field.Index)
switch f.Kind() {
case reflect.Slice:
fieldValue = conform(f.Type().Elem(), fieldValue)
f.Set(reflect.Append(f, fieldValue...))
return
case reflect.Ptr:
if f.IsNil() {
fv := reflect.New(f.Type().Elem()).Elem()
f.Set(fv.Addr())
f = fv
} else {
f = f.Elem()
}
}
if f.CanAddr() {
if d, ok := f.Addr().Interface().(Capture); ok {
ifv := []string{}
for _, v := range fieldValue {
ifv = append(ifv, v.Interface().(string))
}
err := d.Capture(ifv)
if err != nil {
lexer.Panic(pos, err.Error())
}
return
}
}
// Strings concatenate all captured tokens.
if f.Kind() == reflect.String {
fieldValue = conform(f.Type(), fieldValue)
for _, v := range fieldValue {
f.Set(reflect.ValueOf(f.String() + v.String()).Convert(f.Type()))
}
return
}
// Coalesce multiple tokens into one. This allow eg. ["-", "10"] to be captured as separate tokens but
// parsed as a single string "-10".
if len(fieldValue) > 1 {
out := []string{}
for _, v := range fieldValue {
out = append(out, v.String())
}
fieldValue = []reflect.Value{reflect.ValueOf(strings.Join(out, ""))}
}
fieldValue = conform(f.Type(), fieldValue)
fv := fieldValue[0]
switch f.Kind() {
// Numeric types will increment if the token can not be coerced.
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if fv.Type() != f.Type() {
f.SetInt(f.Int() + 1)
} else {
f.Set(fv)
}
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if fv.Type() != f.Type() {
f.SetUint(f.Uint() + 1)
} else {
f.Set(fv)
}
case reflect.Float32, reflect.Float64:
if fv.Type() != f.Type() {
f.SetFloat(f.Float() + 1)
} else {
f.Set(fv)
}
case reflect.Bool, reflect.Struct:
if fv.Type() != f.Type() {
panicf("value %q is not correct type %s", fv, f.Type())
}
f.Set(fv)
default:
panicf("unsupported field type %s for field %s", f.Type(), field.Name)
}
}
func indirectType(t reflect.Type) reflect.Type {
if t.Kind() == reflect.Ptr || t.Kind() == reflect.Slice {
return indirectType(t.Elem())
}
return t
}
func panicf(f string, args ...interface{}) {
panic(Error(fmt.Sprintf(f, args...)))
}
type Error string
func (e Error) Error() string { return string(e) }