-
Notifications
You must be signed in to change notification settings - Fork 9
/
compiler.go
437 lines (408 loc) · 12.1 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
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
package bytecode
import (
"fmt"
"evylang.dev/evy/pkg/parser"
)
const (
// JumpPlaceholder is used as a placeholder operand value in OpJump
// and OpJumpOnFalse.
JumpPlaceholder = 9999
)
var (
// ErrUndefinedVar is returned when a variable name cannot
// be resolved in the symbol table.
ErrUndefinedVar = fmt.Errorf("%w: undefined variable", ErrPanic)
// ErrUnknownOperator is returned when an operator cannot
// be resolved.
ErrUnknownOperator = fmt.Errorf("%w: unknown operator", ErrInternal)
// ErrUnsupportedExpression is returned when an expression is not
// supported by the compiler, this indicates an error in the compiler
// itself, as all parseable evy expressions should be supported.
ErrUnsupportedExpression = fmt.Errorf("%w: unsupported expression", ErrInternal)
)
// Compiler is responsible for turning a parsed evy program into
// bytecode.
type Compiler struct {
constants []value
instructions Instructions
globals *SymbolTable
// breaks tracks the positions of break statements in the inner-most loop.
breaks []int
}
// Bytecode represents raw evy bytecode.
type Bytecode struct {
Constants []value
Instructions Instructions
}
// NewCompiler returns a new compiler.
func NewCompiler() *Compiler {
return &Compiler{globals: NewSymbolTable()}
}
// Compile accepts an AST node and renders it to bytecode internally.
func (c *Compiler) Compile(node parser.Node) error {
switch node := node.(type) {
case *parser.Program:
return c.compileProgram(node)
case *parser.IndexExpression:
return c.compileIndexExpression(node)
case *parser.InferredDeclStmt:
return c.compileDecl(node.Decl)
case *parser.AssignmentStmt:
return c.compileAssignment(node)
case *parser.BinaryExpression:
return c.compileBinaryExpression(node)
case *parser.BreakStmt:
return c.compileBreakStatement(node)
case *parser.BlockStatement:
return c.compileBlockStatement(node)
case *parser.IfStmt:
return c.compileIfStatement(node)
case *parser.WhileStmt:
return c.compileWhileStatement(node)
case *parser.SliceExpression:
return c.compileSliceExpression(node)
case *parser.UnaryExpression:
return c.compileUnaryExpression(node)
case *parser.GroupExpression:
return c.Compile(node.Expr)
case *parser.Var:
return c.compileVar(node)
case *parser.NumLiteral:
num := numVal(node.Value)
if err := c.emit(OpConstant, c.addConstant(num)); err != nil {
return err
}
case *parser.BoolLiteral:
opcode := OpFalse
if node.Value {
opcode = OpTrue
}
if err := c.emit(opcode); err != nil {
return err
}
case *parser.StringLiteral:
num := stringVal(node.Value)
if err := c.emit(OpConstant, c.addConstant(num)); err != nil {
return err
}
case *parser.ArrayLiteral:
for _, elem := range node.Elements {
if err := c.Compile(elem); err != nil {
return err
}
}
if err := c.emit(OpArray, len(node.Elements)); err != nil {
return err
}
case *parser.MapLiteral:
for _, k := range node.Order {
str := stringVal(k)
if err := c.emit(OpConstant, c.addConstant(str)); err != nil {
return err
}
if err := c.Compile(node.Pairs[k]); err != nil {
return err
}
}
if err := c.emit(OpMap, len(node.Pairs)*2); err != nil {
return err
}
}
return nil
}
// Bytecode renders the compiler instructions into Bytecode.
func (c *Compiler) Bytecode() *Bytecode {
return &Bytecode{
Instructions: c.instructions,
Constants: c.constants,
}
}
// addConstant appends the provided value to the constants
// and returns the index of that constant.
func (c *Compiler) addConstant(obj value) int {
c.constants = append(c.constants, obj)
return len(c.constants) - 1
}
// addInstruction appends bytes to the instruction set and returns the
// position of the instruction.
func (c *Compiler) addInstruction(ins []byte) int {
posNewInstruction := len(c.instructions)
c.instructions = append(c.instructions, ins...)
return posNewInstruction
}
// emit makes and writes an instruction to the bytecode.
func (c *Compiler) emit(op Opcode, operands ...int) error {
_, err := c.emitPos(op, operands...)
return err
}
// emitPos makes and writes an instruction to the bytecode and returns the
// position of the instruction.
func (c *Compiler) emitPos(op Opcode, operands ...int) (int, error) {
ins, err := Make(op, operands...)
if err != nil {
return 0, err
}
newPos := c.addInstruction(ins)
return newPos, nil
}
func (c *Compiler) compileBinaryExpression(expr *parser.BinaryExpression) error {
if err := c.Compile(expr.Left); err != nil {
return err
}
if err := c.Compile(expr.Right); err != nil {
return err
}
// equality and inequality are type agnostic in the vm, so no type checking
// is required to decide which opcode to output.
switch expr.Op {
case parser.OP_EQ:
return c.emit(OpEqual)
case parser.OP_NOT_EQ:
return c.emit(OpNotEqual)
}
if expr.Left.Type() == parser.NUM_TYPE && expr.Right.Type() == parser.NUM_TYPE {
return c.compileNumBinaryExpression(expr)
}
if expr.Left.Type() == parser.STRING_TYPE && expr.Right.Type() == parser.STRING_TYPE {
return c.compileStringBinaryExpression(expr)
}
if expr.Left.Type().Name == parser.ARRAY && expr.Right.Type().Name == parser.ARRAY && expr.Op == parser.OP_PLUS {
return c.emit(OpArrayConcatenate)
}
if expr.Left.Type().Name == parser.ARRAY && expr.Right.Type() == parser.NUM_TYPE && expr.Op == parser.OP_ASTERISK {
return c.emit(OpArrayRepeat)
}
return fmt.Errorf("%w: %s with types %s %s", ErrUnsupportedExpression,
expr, expr.Left.Type(), expr.Right.Type())
}
func (c *Compiler) compileNumBinaryExpression(expr *parser.BinaryExpression) error {
switch expr.Op {
case parser.OP_PLUS:
return c.emit(OpAdd)
case parser.OP_MINUS:
return c.emit(OpSubtract)
case parser.OP_ASTERISK:
return c.emit(OpMultiply)
case parser.OP_SLASH:
return c.emit(OpDivide)
case parser.OP_PERCENT:
return c.emit(OpModulo)
case parser.OP_LT:
return c.emit(OpNumLessThan)
case parser.OP_LTEQ:
return c.emit(OpNumLessThanEqual)
case parser.OP_GT:
return c.emit(OpNumGreaterThan)
case parser.OP_GTEQ:
return c.emit(OpNumGreaterThanEqual)
default:
return fmt.Errorf("%w %s", ErrUnknownOperator, expr.Op)
}
}
func (c *Compiler) compileStringBinaryExpression(expr *parser.BinaryExpression) error {
switch expr.Op {
case parser.OP_PLUS:
return c.emit(OpStringConcatenate)
case parser.OP_LT:
return c.emit(OpStringLessThan)
case parser.OP_LTEQ:
return c.emit(OpStringLessThanEqual)
case parser.OP_GT:
return c.emit(OpStringGreaterThan)
case parser.OP_GTEQ:
return c.emit(OpStringGreaterThanEqual)
default:
return fmt.Errorf("%w %s", ErrUnknownOperator, expr.Op)
}
}
func (c *Compiler) compileBlockStatement(block *parser.BlockStatement) error {
for _, stmt := range block.Statements {
if err := c.Compile(stmt); err != nil {
return err
}
}
return nil
}
func (c *Compiler) compileIfStatement(stmt *parser.IfStmt) error {
firstJumpPos, err := c.compileConditionalBlock(stmt.IfBlock)
if err != nil {
return err
}
jumpPositions := []int{firstJumpPos}
for _, elseif := range stmt.ElseIfBlocks {
opJumpPos, err := c.compileConditionalBlock(elseif)
if err != nil {
return err
}
jumpPositions = append(jumpPositions, opJumpPos)
}
if stmt.Else != nil {
if err := c.Compile(stmt.Else); err != nil {
return err
}
}
// rewrite all OpJump to jump to the end of the entire if statement,
// optimisation: if the else block is empty then the last jump will
// "jump" to the next instruction
stmtEndPos := len(c.instructions)
for _, jumpPos := range jumpPositions {
c.instructions.changeOperand(jumpPos, stmtEndPos)
}
return nil
}
// compileConditionalBlock will compile the condition and block of a ConditionalBlock, emitting
// an OpJumpOnFalse after the condition and an OpJump after the block. The position of the
// OpJump is returned so that it can be rewritten in the event that this statement is part
// of a larger IfStmt.
func (c *Compiler) compileConditionalBlock(block *parser.ConditionalBlock) (int, error) {
if err := c.Compile(block.Condition); err != nil {
return 0, err
}
jumpOnFalsePos, err := c.emitPos(OpJumpOnFalse, JumpPlaceholder)
if err != nil {
return 0, err
}
if err := c.Compile(block.Block); err != nil {
return 0, err
}
jumpPos, err := c.emitPos(OpJump, JumpPlaceholder)
if err != nil {
return 0, err
}
// rewrite the JumpPlaceholder in the OpJumpOnFalse so that it will jump to the end
// of the statement when the condition is not truthy anymore
afterBlockPos := len(c.instructions)
c.instructions.changeOperand(jumpOnFalsePos, afterBlockPos)
return jumpPos, nil
}
func (c *Compiler) compileWhileStatement(stmt *parser.WhileStmt) error {
startPos := len(c.instructions)
if err := c.Compile(stmt.Condition); err != nil {
return err
}
// Prepare end position of while block, jump to end if condition is false
jumpOnFalsePos, err := c.emitPos(OpJumpOnFalse, JumpPlaceholder)
if err != nil {
return err
}
// take a snapshot of the break list before compiling the body of the loop
outOfScopeBreaks := c.breaks
c.breaks = []int{}
if err := c.Compile(stmt.Block); err != nil {
return err
}
// Jump back to start of while condition
if err := c.emit(OpJump, startPos); err != nil {
return err
}
// rewrite the JumpPlaceholder in the OpJumpOnFalse so that it will
// jump to the end of the statement when the condition is false
afterBlockPos := len(c.instructions)
c.instructions.changeOperand(jumpOnFalsePos, afterBlockPos)
// rewrite the JumpPlaceholder in the break statements to jump
// to the end of the loop
for _, breakPos := range c.breaks {
c.instructions.changeOperand(breakPos, afterBlockPos)
}
// reset the break list
c.breaks = outOfScopeBreaks
return nil
}
func (c *Compiler) compileBreakStatement(_ *parser.BreakStmt) error {
// JumpPlaceholder will be rewritten by the parent loop
pos, err := c.emitPos(OpJump, JumpPlaceholder)
if err != nil {
return err
}
c.breaks = append(c.breaks, pos)
return nil
}
func (c *Compiler) compileSliceExpression(expr *parser.SliceExpression) error {
var err error
if err = c.Compile(expr.Left); err != nil {
return err
}
if err = c.compileOrEmitNone(expr.Start); err != nil {
return err
}
if err = c.compileOrEmitNone(expr.End); err != nil {
return err
}
return c.emit(OpSlice)
}
// compilerOrEmitNone will emit OpNone if the provided parser node is
// nil. If the node is not nil then it will be compiled as normal.
func (c *Compiler) compileOrEmitNone(node parser.Node) error {
if node != nil {
return c.Compile(node)
}
return c.emit(OpNone)
}
func (c *Compiler) compileUnaryExpression(expr *parser.UnaryExpression) error {
if err := c.Compile(expr.Right); err != nil {
return err
}
switch expr.Op {
case parser.OP_MINUS:
return c.emit(OpMinus)
case parser.OP_BANG:
return c.emit(OpNot)
}
return nil
}
func (c *Compiler) compileProgram(prog *parser.Program) error {
for _, s := range prog.Statements {
if err := c.Compile(s); err != nil {
return err
}
}
return nil
}
func (c *Compiler) compileDecl(decl *parser.Decl) error {
if err := c.Compile(decl.Value); err != nil {
return err
}
symbol := c.globals.Define(decl.Var.Name)
return c.emit(OpSetGlobal, symbol.Index)
}
func (c *Compiler) compileAssignment(stmt *parser.AssignmentStmt) error {
if err := c.Compile(stmt.Value); err != nil {
return err
}
switch target := stmt.Target.(type) {
case *parser.Var:
symbol, ok := c.globals.Resolve(target.Name)
if !ok {
return fmt.Errorf("%w %s", ErrUndefinedVar, target.Name)
}
return c.emit(OpSetGlobal, symbol.Index)
case *parser.IndexExpression:
if err := c.Compile(target.Left); err != nil {
return err
}
if err := c.Compile(target.Index); err != nil {
return err
}
return c.emit(OpSetIndex)
}
return c.Compile(stmt.Target)
}
func (c *Compiler) compileVar(variable *parser.Var) error {
symbol, ok := c.globals.Resolve(variable.Name)
if !ok {
return fmt.Errorf("%w %s", ErrUndefinedVar, variable.Name)
}
return c.emit(OpGetGlobal, symbol.Index)
}
func (c *Compiler) compileIndexExpression(expr *parser.IndexExpression) error {
if err := c.Compile(expr.Left); err != nil {
return err
}
if err := c.Compile(expr.Index); err != nil {
return err
}
if err := c.emit(OpIndex); err != nil {
return err
}
return nil
}