-
Notifications
You must be signed in to change notification settings - Fork 0
/
lexer.go
139 lines (122 loc) · 2.3 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
package json
import (
"unicode"
)
type Type string
const (
LEFT_BRACE Type = "{"
RIGHT_BRACE Type = "}"
LEFT_BRACKET Type = "["
RIGHT_BRACKET Type = "]"
COLON Type = ":"
COMMA Type = ","
STRING Type = "STRING"
NUMBER Type = "NUMBER"
TRUE Type = "true"
FALSE Type = "false"
NULL Type = "null"
EOF Type = "EOF"
)
func NewLexer(input string) *Lexer {
l := &Lexer{input: input}
l.readChar()
return l
}
func (l *Lexer) readChar() {
if l.readPosition >= len(l.input) {
l.ch = 0
} else {
l.ch = l.input[l.readPosition]
}
l.position = l.readPosition
l.readPosition++
}
func (l *Lexer) NextToken() Token {
var tok Token
l.skip()
switch l.ch {
case '{':
tok = set(LEFT_BRACE, l.ch)
case '}':
tok = set(RIGHT_BRACE, l.ch)
case '[':
tok = set(LEFT_BRACKET, l.ch)
case ']':
tok = set(RIGHT_BRACKET, l.ch)
case ':':
tok = set(COLON, l.ch)
case ',':
tok = set(COMMA, l.ch)
case '"':
tok.Type = STRING
tok.Literal = l.readString()
case 0:
tok.Literal = ""
tok.Type = EOF
default:
if isNum(l.ch) {
tok.Type = NUMBER
tok.Literal = l.readNumber()
return tok
} else if isLetter(l.ch) {
literal := l.readIdentifier()
tok.Type = lookupIdent(literal)
tok.Literal = literal
return tok
} else {
tok = set(EOF, l.ch)
}
}
l.readChar()
return tok
}
func set(Type Type, ch byte) Token {
return Token{Type: Type, Literal: string(ch)}
}
func (l *Lexer) readString() string {
position := l.position + 1
for {
l.readChar()
if l.ch == '"' || l.ch == 0 {
break
}
}
return l.input[position:l.position]
}
func (l *Lexer) readNumber() string {
position := l.position
for isNum(l.ch) {
l.readChar()
}
return l.input[position:l.position]
}
func (l *Lexer) readIdentifier() string {
position := l.position
for isLetter(l.ch) {
l.readChar()
}
return l.input[position:l.position]
}
func (l *Lexer) skip() {
for l.ch == ' ' || l.ch == '\t' || l.ch == '\n' || l.ch == '\r' {
l.readChar()
}
}
func isNum(ch byte) bool {
return '0' <= ch && ch <= '9'
}
func isLetter(ch byte) bool {
return unicode.IsLetter(rune(ch))
}
func lookupIdent(ident string) Type {
switch ident {
case "true":
return TRUE
case "false":
return FALSE
case "null":
return NULL
default:
return STRING
}
}