-
Notifications
You must be signed in to change notification settings - Fork 0
/
match.go
118 lines (90 loc) · 1.98 KB
/
match.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
package tpl
import (
"errors"
"go/token"
)
var (
ErrNoGrammar = errors.New("no grammar")
)
// -----------------------------------------------------------------------------
type Matcher struct {
Grammar Grammar
Scanner Tokener
ScanMode ScanMode
Init func()
}
type TokenizeError struct {
Pos token.Position
Msg string
}
func (p *TokenizeError) Error() string {
return p.Msg
}
func (p *Matcher) Code() string {
return Code(p.Grammar, p.requireScanner())
}
func (p *Matcher) Tokenize(src []byte, fname string) (tokens []Token, err error) {
fset := token.NewFileSet()
file := fset.AddFile(fname, -1, len(src))
s := p.requireScanner()
var errTok *TokenizeError
onError := func(pos token.Position, msg string) {
errTok = &TokenizeError{pos, msg}
}
s.Init(file, src, onError, p.ScanMode)
for {
token := s.Scan()
if errTok != nil {
return tokens, errTok
}
tokens = append(tokens, token)
if token.Kind == EOF { // 尽管 tokens 里面不包含 EOF,但我们希望有 EOF 过尾值(为了 Source 函数)
tokens = tokens[:len(tokens)-1]
break
}
}
return
}
func (p *Matcher) requireScanner() Tokener {
s := p.Scanner
if s == nil {
s = new(Scanner)
p.Scanner = s
}
return s
}
func (p *Matcher) Tokener() Tokener {
return p.requireScanner()
}
func (p *Matcher) Match(src []byte, fname string) (next []Token, err error) {
g := p.Grammar
if g == nil {
return nil, ErrNoGrammar
}
tokens, err := p.Tokenize(src, fname)
if err != nil {
return
}
if p.Init != nil {
p.Init()
}
n, err := g.Match(tokens, p)
if err != nil {
return
}
return tokens[n:], nil
}
func (p *Matcher) MatchExactly(src []byte, fname string) (err error) {
next, err := p.Match(src, fname)
if err != nil {
return
}
if len(next) != 0 {
return &MatchError{GrEOF, p, next, nil, 0}
}
return
}
func (p *Matcher) Eval(src string) (err error) {
return p.MatchExactly([]byte(src), "")
}
// -----------------------------------------------------------------------------