-
-
Notifications
You must be signed in to change notification settings - Fork 186
/
nodes.go
782 lines (700 loc) · 20.7 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
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
package participle
import (
"encoding"
"errors"
"fmt"
"reflect"
"strconv"
"strings"
"github.com/alecthomas/participle/v2/lexer"
)
var (
// MaxIterations limits the number of elements capturable by {}.
MaxIterations = 1000000
positionType = reflect.TypeOf(lexer.Position{})
tokenType = reflect.TypeOf(lexer.Token{})
tokensType = reflect.TypeOf([]lexer.Token{})
captureType = reflect.TypeOf((*Capture)(nil)).Elem()
textUnmarshalerType = reflect.TypeOf((*encoding.TextUnmarshaler)(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.
//
// Returned slice will be nil if the node does not match.
Parse(ctx *parseContext, parent reflect.Value) ([]reflect.Value, error)
// Return a decent string representation of the Node.
fmt.Stringer
fmt.GoStringer
}
func decorate(err *error, name func() string) {
if *err == nil {
return
}
if perr, ok := (*err).(Error); ok {
*err = Errorf(perr.Position(), "%s: %s", name(), perr.Message())
} else {
*err = &ParseError{Msg: fmt.Sprintf("%s: %s", name(), *err)}
}
}
// A node that proxies to an implementation that implements the Parseable interface.
type parseable struct {
t reflect.Type
}
func (p *parseable) String() string { return ebnf(p) }
func (p *parseable) GoString() string { return p.t.String() }
func (p *parseable) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(p)()
rv := reflect.New(p.t)
v := rv.Interface().(Parseable)
err = v.Parse(ctx.PeekingLexer)
if err != nil {
if err == NextMatch {
return nil, nil
}
return nil, err
}
return []reflect.Value{rv.Elem()}, nil
}
// @@ (but for a custom production)
type custom struct {
typ reflect.Type
parseFn reflect.Value
}
func (c *custom) String() string { return ebnf(c) }
func (c *custom) GoString() string { return c.typ.Name() }
func (c *custom) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(c)()
results := c.parseFn.Call([]reflect.Value{reflect.ValueOf(ctx.PeekingLexer)})
if err, _ := results[1].Interface().(error); err != nil {
if err == NextMatch {
return nil, nil
}
return nil, err
}
return []reflect.Value{results[0]}, nil
}
// @@ (for a union)
type union struct {
typ reflect.Type
members []node
}
func (u *union) String() string { return ebnf(u) }
func (u *union) GoString() string { return u.typ.Name() }
func (u *union) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(u)()
temp := disjunction{u.members}
vals, err := temp.Parse(ctx, parent)
if err != nil {
return nil, err
}
for i := range vals {
vals[i] = vals[i].Convert(u.typ)
}
return vals, nil
}
// @@
type strct struct {
typ reflect.Type
expr node
tokensFieldIndex []int
posFieldIndex []int
endPosFieldIndex []int
}
func newStrct(typ reflect.Type) *strct {
s := &strct{
typ: typ,
}
field, ok := typ.FieldByName("Pos")
if ok && field.Type == positionType {
s.posFieldIndex = field.Index
}
field, ok = typ.FieldByName("EndPos")
if ok && field.Type == positionType {
s.endPosFieldIndex = field.Index
}
field, ok = typ.FieldByName("Tokens")
if ok && field.Type == tokensType {
s.tokensFieldIndex = field.Index
}
return s
}
func (s *strct) String() string { return ebnf(s) }
func (s *strct) GoString() string { return s.typ.Name() }
func (s *strct) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(s)()
sv := reflect.New(s.typ).Elem()
start := ctx.RawCursor()
t := ctx.Peek()
s.maybeInjectStartToken(t, sv)
if out, err = s.expr.Parse(ctx, sv); err != nil {
_ = ctx.Apply() // Best effort to give partial AST.
ctx.MaybeUpdateError(err)
return []reflect.Value{sv}, err
} else if out == nil {
return nil, nil
}
end := ctx.RawCursor()
t = ctx.RawPeek()
s.maybeInjectEndToken(t, sv)
s.maybeInjectTokens(ctx.Range(start, end), sv)
return []reflect.Value{sv}, ctx.Apply()
}
func (s *strct) maybeInjectStartToken(token lexer.Token, v reflect.Value) {
if s.posFieldIndex == nil {
return
}
v.FieldByIndex(s.posFieldIndex).Set(reflect.ValueOf(token.Pos))
}
func (s *strct) maybeInjectEndToken(token lexer.Token, v reflect.Value) {
if s.endPosFieldIndex == nil {
return
}
v.FieldByIndex(s.endPosFieldIndex).Set(reflect.ValueOf(token.Pos))
}
func (s *strct) maybeInjectTokens(tokens []lexer.Token, v reflect.Value) {
if s.tokensFieldIndex == nil {
return
}
v.FieldByIndex(s.tokensFieldIndex).Set(reflect.ValueOf(tokens))
}
type groupMatchMode int
func (g groupMatchMode) String() string {
switch g {
case groupMatchOnce:
return "n"
case groupMatchZeroOrOne:
return "n?"
case groupMatchZeroOrMore:
return "n*"
case groupMatchOneOrMore:
return "n+"
case groupMatchNonEmpty:
return "n!"
}
panic("??")
}
const (
groupMatchOnce groupMatchMode = iota
groupMatchZeroOrOne = iota
groupMatchZeroOrMore = iota
groupMatchOneOrMore = iota
groupMatchNonEmpty = iota
)
// ( <expr> ) - match once
// ( <expr> )* - match zero or more times
// ( <expr> )+ - match one or more times
// ( <expr> )? - match zero or once
// ( <expr> )! - must be a non-empty match
//
// The additional modifier "!" forces the content of the group to be non-empty if it does match.
type group struct {
expr node
mode groupMatchMode
}
func (g *group) String() string { return ebnf(g) }
func (g *group) GoString() string { return fmt.Sprintf("group{%s}", g.mode) }
func (g *group) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(g)()
// Configure min/max matches.
min := 1
max := 1
switch g.mode {
case groupMatchNonEmpty:
out, err = g.expr.Parse(ctx, parent)
if err != nil {
return out, err
}
if len(out) == 0 {
t := ctx.Peek()
return out, Errorf(t.Pos, "sub-expression %s cannot be empty", g)
}
return out, nil
case groupMatchOnce:
return g.expr.Parse(ctx, parent)
case groupMatchZeroOrOne:
min = 0
case groupMatchZeroOrMore:
min = 0
max = MaxIterations
case groupMatchOneOrMore:
min = 1
max = MaxIterations
}
matches := 0
for ; matches < max; matches++ {
branch := ctx.Branch()
v, err := g.expr.Parse(branch, parent)
if err != nil {
ctx.MaybeUpdateError(err)
// Optional part failed to match.
if ctx.Stop(err, branch) {
out = append(out, v...) // Try to return as much of the parse tree as possible
return out, err
}
break
}
out = append(out, v...)
ctx.Accept(branch)
if v == nil {
break
}
}
// fmt.Printf("%d < %d < %d: out == nil? %v\n", min, matches, max, out == nil)
t := ctx.Peek()
if matches >= MaxIterations {
return nil, Errorf(t.Pos, "too many iterations of %s (> %d)", g, MaxIterations)
}
if matches < min {
return out, Errorf(t.Pos, "sub-expression %s must match at least once", g)
}
// The idea here is that something like "a"? is a successful match and that parsing should proceed.
if min == 0 && out == nil {
out = []reflect.Value{}
}
return out, nil
}
// (?= <expr> ) for positive lookahead, (?! <expr> ) for negative lookahead; neither consumes input
type lookaheadGroup struct {
expr node
negative bool
}
func (n *lookaheadGroup) String() string { return ebnf(n) }
func (n *lookaheadGroup) GoString() string { return "lookaheadGroup{}" }
func (n *lookaheadGroup) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(n)()
// Create a branch to avoid advancing the parser as any match will be discarded
branch := ctx.Branch()
out, err = n.expr.Parse(branch, parent)
matchedLookahead := err == nil && out != nil
expectingMatch := !n.negative
if matchedLookahead != expectingMatch {
peek := ctx.Peek()
return nil, Errorf(peek.Pos, "unexpected '%s'", peek.Value)
}
return []reflect.Value{}, nil // Empty match slice means a match, unlike nil
}
// <expr> {"|" <expr>}
type disjunction struct {
nodes []node
}
func (d *disjunction) String() string { return ebnf(d) }
func (d *disjunction) GoString() string { return "disjunction{}" }
func (d *disjunction) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(d)()
var (
deepestError = 0
firstError error
firstValues []reflect.Value
)
for _, a := range d.nodes {
branch := ctx.Branch()
if value, err := a.Parse(branch, parent); err != nil {
// If this branch progressed too far and still didn't match, error out.
if ctx.Stop(err, branch) {
return value, err
}
// Show the closest error returned. The idea here is that the further the parser progresses
// without error, the more difficult it is to trace the error back to its root.
if branch.Cursor() >= deepestError {
firstError = err
firstValues = value
deepestError = branch.Cursor()
}
} else if value != nil {
bt := branch.RawPeek()
ct := ctx.RawPeek()
if bt == ct && bt.Type != lexer.EOF {
panic(Errorf(bt.Pos, "branch %s was accepted but did not progress the lexer at %s (%q)", a, bt.Pos, bt.Value))
}
ctx.Accept(branch)
return value, nil
}
}
if firstError != nil {
ctx.MaybeUpdateError(firstError)
return firstValues, firstError
}
return nil, nil
}
// <node> ...
type sequence struct {
head bool // True if this is the head node.
node node
next *sequence
}
func (s *sequence) String() string { return ebnf(s) }
func (s *sequence) GoString() string { return "sequence{}" }
func (s *sequence) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(s)()
for n := s; n != nil; n = n.next {
child, err := n.node.Parse(ctx, parent)
out = append(out, child...)
if err != nil {
return out, err
}
if child == nil {
// Early exit if first value doesn't match, otherwise all values must match.
if n == s {
return nil, nil
}
token := ctx.Peek()
return out, &UnexpectedTokenError{Unexpected: token, at: n}
}
// Special-case for when children return an empty match.
// Appending an empty, non-nil slice to a nil slice returns a nil slice.
// https://go.dev/play/p/lV1Xk-IP6Ta
if out == nil {
out = []reflect.Value{}
}
}
return out, nil
}
// @<expr>
type capture struct {
field structLexerField
node node
}
func (c *capture) String() string { return ebnf(c) }
func (c *capture) GoString() string { return "capture{}" }
func (c *capture) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(c)()
start := ctx.RawCursor()
v, err := c.node.Parse(ctx, parent)
if v != nil {
ctx.Defer(ctx.Range(start, ctx.RawCursor()), parent, c.field, v)
}
if err != nil {
return []reflect.Value{parent}, err
}
if v == nil {
return nil, nil
}
return []reflect.Value{parent}, nil
}
// <identifier> - named lexer token reference
type reference struct {
typ lexer.TokenType
identifier string // Used for informational purposes.
}
func (r *reference) String() string { return ebnf(r) }
func (r *reference) GoString() string { return fmt.Sprintf("reference{%s}", r.identifier) }
func (r *reference) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(r)()
token, cursor := ctx.PeekAny(func(t lexer.Token) bool {
return t.Type == r.typ
})
if token.Type != r.typ {
return nil, nil
}
ctx.FastForward(cursor)
return []reflect.Value{reflect.ValueOf(token.Value)}, nil
}
// [ <expr> ] <sequence>
type optional struct {
node node
}
func (o *optional) String() string { return ebnf(o) }
func (o *optional) GoString() string { return "optional{}" }
func (o *optional) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(o)()
branch := ctx.Branch()
out, err = o.node.Parse(branch, parent)
if err != nil {
// Optional part failed to match.
if ctx.Stop(err, branch) {
return out, err
}
} else {
ctx.Accept(branch)
}
if out == nil {
out = []reflect.Value{}
}
return out, nil
}
// { <expr> } <sequence>
type repetition struct {
node node
}
func (r *repetition) String() string { return ebnf(r) }
func (r *repetition) GoString() string { return "repetition{}" }
// 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(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(r)()
i := 0
for ; i < MaxIterations; i++ {
branch := ctx.Branch()
v, err := r.node.Parse(branch, parent)
out = append(out, v...)
if err != nil {
// Optional part failed to match.
if ctx.Stop(err, branch) {
return out, err
}
break
} else {
ctx.Accept(branch)
}
if v == nil {
break
}
}
if i >= MaxIterations {
t := ctx.Peek()
return nil, Errorf(t.Pos, "too many iterations of %s (> %d)", r, MaxIterations)
}
if out == nil {
out = []reflect.Value{}
}
return out, nil
}
// Match a token literal exactly "..."[:<type>].
type literal struct {
s string
t lexer.TokenType
tt string // Used for display purposes - symbolic name of t.
}
func (l *literal) String() string { return ebnf(l) }
func (l *literal) GoString() string { return fmt.Sprintf("literal{%q, %q}", l.s, l.tt) }
func (l *literal) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(l)()
match := func(t lexer.Token) bool {
var equal bool
if ctx.caseInsensitive[t.Type] {
equal = l.s == "" || strings.EqualFold(t.Value, l.s)
} else {
equal = l.s == "" || t.Value == l.s
}
return (l.t == lexer.EOF || l.t == t.Type) && equal
}
token, cursor := ctx.PeekAny(match)
if match(token) {
ctx.FastForward(cursor)
return []reflect.Value{reflect.ValueOf(token.Value)}, nil
}
return nil, nil
}
type negation struct {
node node
}
func (n *negation) String() string { return ebnf(n) }
func (n *negation) GoString() string { return "negation{}" }
func (n *negation) Parse(ctx *parseContext, parent reflect.Value) (out []reflect.Value, err error) {
defer ctx.printTrace(n)()
// Create a branch to avoid advancing the parser, but call neither Stop nor Accept on it
// since we will discard a match.
branch := ctx.Branch()
notEOF := ctx.Peek()
if notEOF.EOF() {
// EOF cannot match a negation, which expects something
return nil, nil
}
out, err = n.node.Parse(branch, parent)
if out != nil && err == nil {
// out being non-nil means that what we don't want is actually here, so we report nomatch
return nil, Errorf(notEOF.Pos, "unexpected '%s'", notEOF.Value)
}
// Just give the next token
next := ctx.Next()
return []reflect.Value{reflect.ValueOf(next.Value)}, 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, err error) {
for _, v := range values {
for t != v.Type() && t.Kind() == reflect.Ptr && v.Kind() != reflect.Ptr {
// This can occur during partial failure.
if !v.CanAddr() {
return
}
v = v.Addr()
}
// Already of the right kind, don't bother converting.
if v.Kind() == t.Kind() {
if v.Type() != t {
v = v.Convert(t)
}
out = append(out, v)
continue
}
kind := t.Kind()
switch kind { // nolint: exhaustive
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
n, err := strconv.ParseInt(v.String(), 0, sizeOfKind(kind))
if err != nil {
return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err)
}
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, sizeOfKind(kind))
if err != nil {
return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err)
}
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(), sizeOfKind(kind))
if err != nil {
return nil, fmt.Errorf("invalid integer %q: %s", v.String(), err)
}
v = reflect.New(t).Elem()
v.SetFloat(n)
}
out = append(out, v)
}
return out, nil
}
func sizeOfKind(kind reflect.Kind) int {
switch kind { // nolint: exhaustive
case reflect.Int8, reflect.Uint8:
return 8
case reflect.Int16, reflect.Uint16:
return 16
case reflect.Int32, reflect.Uint32, reflect.Float32:
return 32
case reflect.Int64, reflect.Uint64, reflect.Float64:
return 64
case reflect.Int, reflect.Uint:
return strconv.IntSize
}
panic("unsupported kind " + kind.String())
}
// 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(tokens []lexer.Token, strct reflect.Value, field structLexerField, fieldValue []reflect.Value) (err error) { // nolint: gocognit
defer decorate(&err, func() string { return strct.Type().Name() + "." + field.Name })
f := strct.FieldByIndex(field.Index)
// Any kind of pointer, hydrate it first.
if f.Kind() == reflect.Ptr {
if f.IsNil() {
fv := reflect.New(f.Type().Elem()).Elem()
f.Set(fv.Addr())
f = fv
} else {
f = f.Elem()
}
}
if f.Type() == tokenType {
f.Set(reflect.ValueOf(tokens[0]))
return nil
}
if f.Type() == tokensType {
f.Set(reflect.ValueOf(tokens))
return nil
}
if f.CanAddr() {
if d, ok := f.Addr().Interface().(Capture); ok {
ifv := make([]string, 0, len(fieldValue))
for _, v := range fieldValue {
ifv = append(ifv, v.Interface().(string))
}
return d.Capture(ifv)
} else if d, ok := f.Addr().Interface().(encoding.TextUnmarshaler); ok {
for _, v := range fieldValue {
if err := d.UnmarshalText([]byte(v.Interface().(string))); err != nil {
return err
}
}
return nil
}
}
if f.Kind() == reflect.Slice {
sliceElemType := f.Type().Elem()
if sliceElemType.Implements(captureType) || reflect.PtrTo(sliceElemType).Implements(captureType) {
if sliceElemType.Kind() == reflect.Ptr {
sliceElemType = sliceElemType.Elem()
}
for _, v := range fieldValue {
d := reflect.New(sliceElemType).Interface().(Capture)
if err := d.Capture([]string{v.Interface().(string)}); err != nil {
return err
}
eltValue := reflect.ValueOf(d)
if f.Type().Elem().Kind() != reflect.Ptr {
eltValue = eltValue.Elem()
}
f.Set(reflect.Append(f, eltValue))
}
} else {
fieldValue, err = conform(sliceElemType, fieldValue)
if err != nil {
return err
}
f.Set(reflect.Append(f, fieldValue...))
}
return nil
}
// Strings concatenate all captured tokens.
if f.Kind() == reflect.String {
fieldValue, err = conform(f.Type(), fieldValue)
if err != nil {
return err
}
for _, v := range fieldValue {
f.Set(reflect.ValueOf(f.String() + v.String()).Convert(f.Type()))
}
return nil
}
// Coalesce multiple tokens into one. This allows 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, err = conform(f.Type(), fieldValue)
if err != nil {
return err
}
fv := fieldValue[0]
switch f.Kind() { // nolint: exhaustive
// 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, reflect.Interface:
if f.Kind() == reflect.Bool && fv.Kind() == reflect.Bool {
f.SetBool(fv.Bool())
break
}
if fv.Type() != f.Type() {
return fmt.Errorf("value %q is not correct type %s", fv, f.Type())
}
f.Set(fv)
default:
return fmt.Errorf("unsupported field type %s for field %s", f.Type(), field.Name)
}
return nil
}