forked from alecthomas/participle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
struct.go
71 lines (62 loc) · 1.43 KB
/
struct.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
package participle
import (
"reflect"
"github.com/alecthomas/participle/lexer"
)
// A structLexer lexes over the tags of struct fields while tracking the current field.
type structLexer struct {
s reflect.Type
field int
lexer lexer.Lexer
}
func lexStruct(s reflect.Type) *structLexer {
return &structLexer{
s: s,
lexer: lexer.LexString(fieldLexerTag(s.Field(0))),
}
}
// NumField returns the number of fields in the struct associated with this structLexer.
func (s *structLexer) NumField() int {
return s.s.NumField()
}
// Field returns the field associated with the current token.
func (s *structLexer) Field() reflect.StructField {
return s.s.Field(s.field)
}
func (s *structLexer) Peek() lexer.Token {
field := s.field
lex := s.lexer
for {
token := lex.Peek()
if !token.EOF() {
token.Pos.Line = field + 1
return token
}
field++
if field >= s.s.NumField() {
return lexer.EOFToken
}
tag := fieldLexerTag(s.s.Field(field))
lex = lexer.LexString(tag)
}
}
func (s *structLexer) Next() lexer.Token {
token := s.lexer.Next()
if !token.EOF() {
token.Pos.Line = s.field + 1
return token
}
if s.field+1 >= s.s.NumField() {
return lexer.EOFToken
}
s.field++
tag := fieldLexerTag(s.s.Field(s.field))
s.lexer = lexer.LexString(tag)
return s.Next()
}
func fieldLexerTag(field reflect.StructField) string {
if tag := field.Tag.Get("parser"); tag != "" {
return tag
}
return string(field.Tag)
}