-
Notifications
You must be signed in to change notification settings - Fork 4
/
lex.go
107 lines (88 loc) · 1.82 KB
/
lex.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
package tmsh
import (
"bytes"
"strings"
)
type scanner struct {
r *strings.Reader
line int
}
func newScanner(data string) *scanner {
return &scanner{r: strings.NewReader(data)}
}
func isWhitespace(ch rune) bool {
return ch == ' ' || ch == '\t'
}
func isLetter(ch rune) bool {
return (ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z') ||
ch == '.' || ch == ',' || ch == '_' || ch == '-' || ch == ':' || ch == ';' ||
ch == '/' || ch == '\'' || ch == '(' || ch == ')' || ch == '@' ||
ch == '"' || ch == '*' || ch == '!'
}
func isDigit(ch rune) bool {
return (ch >= '0' && ch <= '9')
}
func (s *scanner) read() rune {
ch, _, err := s.r.ReadRune()
if err != nil {
return rune(0)
}
return ch
}
func (s *scanner) unread() { _ = s.r.UnreadRune() }
func (s *scanner) Scan() (tok int, lit string) {
ch := s.read()
if isWhitespace(ch) {
s.unread()
return s.scanWhitespace()
} else if isLetter(ch) || isDigit(ch) {
s.unread()
return s.scanIdent()
}
switch ch {
case rune(0):
return EOF, ""
case '\n':
s.line++
return NEWLINE, string(ch)
case '{':
return L_BRACE, string(ch)
case '}':
return R_BRACE, string(ch)
}
return ILLEGAL, string(ch)
}
func (s *scanner) scanWhitespace() (tok int, lit string) {
var buf bytes.Buffer
buf.WriteRune(s.read())
for {
if ch := s.read(); ch == rune(0) {
break
} else if !isWhitespace(ch) {
s.unread()
break
} else {
buf.WriteRune(ch)
}
}
return WS, buf.String()
}
func (s *scanner) scanIdent() (tok int, lit string) {
var buf bytes.Buffer
buf.WriteRune(s.read())
for {
if ch := s.read(); ch == rune(0) {
break
} else if !isLetter(ch) && !isDigit(ch) && ch != '_' {
s.unread()
break
} else {
_, _ = buf.WriteRune(ch)
}
}
switch buf.String() {
case "ltm":
return LTM, buf.String()
}
return IDENT, buf.String()
}