-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.go
144 lines (121 loc) · 2.07 KB
/
lexer.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
package main
import (
"fmt"
"strings"
"unicode/utf8"
)
// completely ripping off Rob Pike's talk. :)
var EOF = rune(0)
var MetaDelim = "---"
func New(filename, input string) *Lexer {
return &Lexer{
name: filename,
input: input,
Items: make(chan Item, 2),
}
}
type ItemType int
type Item struct {
Type ItemType
Value string
}
type Lexer struct {
name string
input string
start int
pos int
width int
Items chan Item
}
func (l *Lexer) Emit(t ItemType) {
l.Items <- Item{t, l.input[l.start:l.pos]}
l.start = l.pos
}
func (l *Lexer) HasPrefix(prefix string) bool {
return strings.HasPrefix(l.input[l.start:l.pos], prefix)
}
func (l *Lexer) Next() (ch rune) {
if l.pos >= len(l.input) {
l.width = 0
return EOF
}
ch, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += l.width
return ch
}
func (l *Lexer) Ignore() {
l.start = l.pos
}
func (l *Lexer) backup() {
l.pos -= l.width
}
func (l *Lexer) Peek() rune {
ch := l.Next()
l.backup()
return ch
}
func (l *Lexer) Pos() int {
return l.pos
}
func (l *Lexer) Accept(valid string) bool {
if strings.IndexRune(valid, l.Next()) >= 0 {
return true
}
l.backup()
return false
}
func (l *Lexer) AcceptRun(valid string) {
for strings.IndexRune(valid, l.Next()) >= 0 {
}
l.backup()
}
func (l *Lexer) Run() {
for fn := LexMetaKey; fn != nil; {
fn = fn(l)
}
close(l.Items)
}
func (l *Lexer) AcceptClasses(cl ...AcceptFn) {
for {
r := l.Next()
if r == EOF {
break
}
accept := false
for _, c := range cl {
if c(r) {
accept = true
break
}
}
if !accept {
break
}
}
l.backup()
}
func (l *Lexer) AcceptUntil(stop string) {
for {
r := l.Next()
if r == EOF {
break
} else if strings.IndexRune(stop, r) >= 0 {
break
}
}
l.backup()
}
func (l *Lexer) Errorf(format string, args ...interface{}) StateFn {
l.Items <- Item{
ItemError,
fmt.Sprintf(format, args...),
}
return nil
}
func RuneSet(set string) AcceptFn {
return func(r rune) bool {
return (strings.IndexRune(set, r) >= 0)
}
}
type StateFn func(*Lexer) StateFn
type AcceptFn func(rune) bool