-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.go
142 lines (122 loc) Β· 2.15 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
// the lexer is based on rob pike's "lexical scanning in go" talk
// from 2011: https://talks.golang.org/2011/lex.slide#1
// i think he's said at this point its out dated and would do things
// differently. need to research this.
package cooklang
import (
"strings"
"unicode/utf8"
)
type stateFn func(*lexer) stateFn
type itemType int
const (
itemError itemType = iota
itemEOF
itemText
itemComment
itemMetadata
itemStep
itemIngredient
//
itemCookware
//
itemTimer
//
)
const (
//
itemCategory itemType = iota
)
type item struct {
typ itemType
val string
}
func (i item) String() string {
switch i.typ {
case itemEOF:
return "EOF"
case itemError:
return i.val
}
return i.val
}
type lexer struct {
name string
input string
stepsInput []string
start int
lineStart int
pos int
width int
items chan item
}
func lex(name, input string) (*lexer, chan item) {
l := &lexer{
name: name,
input: input,
stepsInput: strings.Split(input, "\n"),
items: make(chan item),
}
go l.run()
return l, l.items
}
func (l *lexer) run() {
for state := lexText; state != nil; {
state = state(l)
}
close(l.items)
}
func (l *lexer) next() (r rune) {
if l.pos >= len(l.input) {
l.width = 0
return eof
}
r, l.width = utf8.DecodeRuneInString(l.input[l.pos:])
l.pos += l.width
return r
}
func (l *lexer) ignore() {
l.start = l.pos
}
func (l *lexer) backup() {
l.pos -= l.width
}
func (l *lexer) rewind() {
l.pos = l.start
}
func (l *lexer) peek() rune {
r := l.next()
l.backup()
return r
}
func (l *lexer) peekSpecial() rune {
p := l.pos
for {
r := l.next()
if strings.ContainsRune(special, r) {
l.pos = p
return r
}
}
}
func (l *lexer) accept(valid string) bool {
if strings.ContainsRune(valid, l.next()) {
return true
}
l.backup()
return false
}
func (l *lexer) acceptRun(valid string) {
for strings.IndexRune(valid, l.next()) >= 0 {
}
l.backup()
}
func (l *lexer) acceptUntil(valid string) {
for !strings.ContainsRune(valid, l.next()) && l.peek() != eof {
}
l.backup()
}
func (l *lexer) emit(t itemType) {
l.items <- item{t, l.input[l.start:l.pos]}
l.start = l.pos
}