-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.go
98 lines (90 loc) · 1.48 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
package main
import (
"strings"
"unicode"
)
type Lexer struct {
text string
pos int
currentToken *Token
}
func (it *Lexer) Advance() {
if !it.Done() {
it.pos++
}
}
func (it *Lexer) Done() bool {
return it.pos >= len(it.text)
}
func (it *Lexer) SkipWhitespace() {
for {
if it.Done() || !unicode.IsSpace(rune(it.text[it.pos])) {
return
}
it.Advance()
}
}
func (it *Lexer) GetInteger() *Token {
var sb strings.Builder
for {
if it.Done() || !unicode.IsDigit(rune(it.text[it.pos])) {
break
}
sb.WriteString(string(it.text[it.pos]))
it.Advance()
}
return &Token{
label: INTEGER,
literal: sb.String(),
}
}
func (it *Lexer) GetNextToken() {
it.SkipWhitespace()
// when Done() = true, return nil for currentToken
if it.Done() {
return
}
currentChar := it.text[it.pos]
switch currentChar {
case '+':
it.Advance()
it.currentToken = &Token{
label: PLUS,
literal: "+",
}
case '-':
it.Advance()
it.currentToken = &Token{
label: MINUS,
literal: "-",
}
case '*':
it.Advance()
it.currentToken = &Token{
label: MULT,
literal: "*",
}
case '/':
it.Advance()
it.currentToken = &Token{
label: DIV,
literal: "/",
}
case '(':
it.Advance()
it.currentToken = &Token{
label: LPAREN,
literal: "(",
}
case ')':
it.Advance()
it.currentToken = &Token{
label: RPAREN,
literal: ")",
}
default:
if unicode.IsDigit(rune(currentChar)) {
it.currentToken = it.GetInteger()
}
}
}