-
Notifications
You must be signed in to change notification settings - Fork 0
/
compiler.go
272 lines (237 loc) · 6.5 KB
/
compiler.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
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
package main
import (
"fmt"
"os"
"strconv"
)
func compile(source string, chunk *Chunk) bool {
initScanner(source)
compilingChunk = chunk
advanceParser()
expression()
consume(TOKEN_EOF, "Expect end of expression.")
endCompiler()
return !parser.HadError
}
type Parser struct {
Current Token
Previous Token
HadError bool
PanicMode bool
}
type Precedence uint8
const (
PREC_NONE Precedence = iota
PREC_ASSIGNMENT
PREC_OR
PREC_AND
PREC_EQUALITY
PREC_COMPARISON
PREC_TERM
PREC_FACTOR
PREC_UNARY
PREC_CALL
PREC_PRIMARY
)
type ParseRule struct {
Prefix ParseFn
Infix ParseFn
Precedence Precedence
}
type ParseFn = func()
var parser Parser
func consume(tokenType TokenType, msg string) {
if parser.Current.Type == tokenType {
advanceParser()
return
}
errorAtCurrent(msg)
}
func advanceParser() {
parser.Previous = parser.Current
for {
parser.Current = scanToken()
if parser.Current.Type != TOKEN_ERROR {
break
}
errorAtCurrent(*parser.Current.Source)
}
}
func errorAtCurrent(msg string) {
errorAt(&parser.Current, msg)
}
func errorRpt(msg string) {
errorAt(&parser.Previous, msg)
}
func errorAt(token *Token, msg string) {
if parser.PanicMode {
return
}
parser.PanicMode = true
fmt.Fprintf(os.Stderr, "[line %d] Error", token.Line)
if token.Type == TOKEN_EOF {
fmt.Fprintf(os.Stderr, " at end")
} else if token.Type == TOKEN_ERROR {
// nothing
} else {
fmt.Fprintf(os.Stderr, " at '%s'", (*token.Source)[token.Start:token.Start+token.Length])
}
fmt.Fprintf(os.Stderr, ": %s\n", msg)
parser.HadError = true
}
func expression() {
parsePrecedence(PREC_ASSIGNMENT)
}
func parsePrecedence(precedence Precedence) {
advanceParser()
prefixRule := rules[parser.Previous.Type].Prefix
if prefixRule == nil {
errorRpt("expect expression.")
return
}
prefixRule()
for precedence <= rules[parser.Current.Type].Precedence {
advanceParser()
infixRule := rules[parser.Previous.Type].Infix
infixRule()
}
}
func emitConstant(value Value) {
emitBytes(OP_CONSTANT, makeConstant(value))
}
func makeConstant(value Value) byte {
constant := currentChunk().AddConstant(value)
if constant > 256 {
errorRpt("too many constants in one chunk.")
return 0
}
return byte(constant)
}
var compilingChunk *Chunk
func currentChunk() *Chunk {
return compilingChunk
}
func emitByte(b byte) {
currentChunk().Write(b, parser.Previous.Line)
}
func emitReturn() {
emitByte(OP_RETURN)
}
func emitBytes(b1, b2 byte) {
emitByte(b1)
emitByte(b2)
}
func endCompiler() {
emitReturn()
if DEBUG_PRINT_CODE {
if !parser.HadError {
DisassembleChunk(currentChunk(), "code")
}
}
}
func compileBinary() {
operatorType := parser.Previous.Type
rule := rules[operatorType]
parsePrecedence(Precedence(rule.Precedence + 1))
switch operatorType {
case TOKEN_BANG_EQUAL:
emitBytes(OP_EQUAL, OP_NOT)
case TOKEN_EQUAL_EQUAL:
emitByte(OP_EQUAL)
case TOKEN_GREATER:
emitByte(OP_GREATER)
case TOKEN_GREATER_EQUAL:
emitBytes(OP_LESS, OP_NOT)
case TOKEN_LESS:
emitByte(OP_LESS)
case TOKEN_LESS_EQUAL:
emitBytes(OP_GREATER, OP_NOT)
case TOKEN_PLUS:
emitByte(OP_ADD)
case TOKEN_MINUS:
emitByte(OP_SUBTRACT)
case TOKEN_STAR:
emitByte(OP_MULTIPLY)
case TOKEN_SLASH:
emitByte(OP_DIVIDE)
}
}
func compileGrouping() {
expression()
consume(TOKEN_RIGHT_PAREN, "Expect ')' after expression.")
}
func compileNumber() {
// N.B. error from ParseFlot is safely ignored because our scanner correctly identifies valid input
value, _ := strconv.ParseFloat((*parser.Previous.Source)[parser.Previous.Start:parser.Previous.Start+parser.Previous.Length], 64)
emitConstant(NumberVal(value))
}
func compileString() {
emitConstant(NewObjString((*parser.Previous.Source)[parser.Previous.Start+1 : parser.Previous.Start+1+parser.Previous.Length-2]))
}
func compileUnary() {
operatorType := parser.Previous.Type
parsePrecedence(PREC_UNARY)
switch operatorType {
case TOKEN_BANG:
emitByte(OP_NOT)
case TOKEN_MINUS:
emitByte(OP_NEGATE)
default:
return
}
}
func compileLiteral() {
switch parser.Previous.Type {
case TOKEN_FALSE:
emitByte(OP_FALSE)
case TOKEN_NIL:
emitByte(OP_NIL)
case TOKEN_TRUE:
emitByte(OP_TRUE)
}
}
var rules map[TokenType]ParseRule
func init() {
rules = map[TokenType]ParseRule{
TOKEN_LEFT_PAREN: {compileGrouping, nil, PREC_NONE},
TOKEN_RIGHT_PAREN: {nil, nil, PREC_NONE},
TOKEN_LEFT_BRACE: {nil, nil, PREC_NONE},
TOKEN_RIGHT_BRACE: {nil, nil, PREC_NONE},
TOKEN_COMMA: {nil, nil, PREC_NONE},
TOKEN_DOT: {nil, nil, PREC_NONE},
TOKEN_MINUS: {compileUnary, compileBinary, PREC_TERM},
TOKEN_PLUS: {nil, compileBinary, PREC_TERM},
TOKEN_SEMICOLON: {nil, nil, PREC_NONE},
TOKEN_SLASH: {nil, compileBinary, PREC_FACTOR},
TOKEN_STAR: {nil, compileBinary, PREC_FACTOR},
TOKEN_BANG: {compileUnary, nil, PREC_NONE},
TOKEN_BANG_EQUAL: {nil, compileBinary, PREC_EQUALITY},
TOKEN_EQUAL: {nil, nil, PREC_NONE},
TOKEN_EQUAL_EQUAL: {nil, compileBinary, PREC_EQUALITY},
TOKEN_GREATER: {nil, compileBinary, PREC_COMPARISON},
TOKEN_GREATER_EQUAL: {nil, compileBinary, PREC_COMPARISON},
TOKEN_LESS: {nil, compileBinary, PREC_COMPARISON},
TOKEN_LESS_EQUAL: {nil, compileBinary, PREC_COMPARISON},
TOKEN_IDENTIFIER: {nil, nil, PREC_NONE},
TOKEN_STRING: {compileString, nil, PREC_NONE},
TOKEN_NUMBER: {compileNumber, nil, PREC_NONE},
TOKEN_AND: {nil, nil, PREC_NONE},
TOKEN_CLASS: {nil, nil, PREC_NONE},
TOKEN_ELSE: {nil, nil, PREC_NONE},
TOKEN_FALSE: {compileLiteral, nil, PREC_NONE},
TOKEN_FOR: {nil, nil, PREC_NONE},
TOKEN_FUN: {nil, nil, PREC_NONE},
TOKEN_IF: {nil, nil, PREC_NONE},
TOKEN_NIL: {compileLiteral, nil, PREC_NONE},
TOKEN_OR: {nil, nil, PREC_NONE},
TOKEN_PRINT: {nil, nil, PREC_NONE},
TOKEN_RETURN: {nil, nil, PREC_NONE},
TOKEN_SUPER: {nil, nil, PREC_NONE},
TOKEN_THIS: {nil, nil, PREC_NONE},
TOKEN_TRUE: {compileLiteral, nil, PREC_NONE},
TOKEN_VAR: {nil, nil, PREC_NONE},
TOKEN_WHILE: {nil, nil, PREC_NONE},
TOKEN_ERROR: {nil, nil, PREC_NONE},
TOKEN_EOF: {nil, nil, PREC_NONE},
}
}