-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcompiler.go
More file actions
987 lines (856 loc) · 27.8 KB
/
compiler.go
File metadata and controls
987 lines (856 loc) · 27.8 KB
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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
package runevm
import (
"fmt"
"strconv"
"strings"
)
// ValueType represents the type of a value at compile time
type ValueType int
const (
TypeUnknown ValueType = iota
TypeInt
TypeFloat
TypeString
TypeBool
)
// Compiler compiles AST nodes to bytecode
type Compiler struct {
chunk *Chunk
locals []string // Local variable names
localDepth int // Current local scope depth
globalNames map[string]int // Global variable name to index mapping
functionChunks map[string]*Chunk // Function name to chunk mapping
loopStarts []int // Stack of loop start positions for break/continue
loopEnds [][]int // Stack of loop end positions for break/continue
isInFunction bool // Track if we're inside a function
// Type inference system
localTypes map[string]ValueType // Track types of local variables
stackTypes []ValueType // Track types on expression stack
}
// NewCompiler creates a new compiler
func NewCompiler() *Compiler {
return &Compiler{
chunk: NewChunk(),
locals: make([]string, 0),
localDepth: 0,
globalNames: make(map[string]int),
functionChunks: make(map[string]*Chunk),
loopStarts: make([]int, 0),
loopEnds: make([][]int, 0),
isInFunction: false,
localTypes: make(map[string]ValueType),
stackTypes: make([]ValueType, 0),
}
}
// Compile compiles an AST expression to bytecode
func (c *Compiler) Compile(expr *expression) error {
if expr == nil {
return nil
}
switch expr.Type {
case numExpr:
return c.compileNumber(expr)
case strExpr:
return c.compileString(expr)
case boolExpr:
return c.compileBool(expr)
case varExpr:
return c.compileVariable(expr)
case assignExpr:
return c.compileAssignment(expr)
case binaryExpr:
return c.compileBinary(expr)
case unaryExpr:
return c.compileUnary(expr)
case blockExpr:
return c.compileBlock(expr)
case ifExpr:
return c.compileIf(expr)
case whileExpr:
return c.compileWhile(expr)
case funExpr:
return c.compileFunction(expr)
case callExpr:
return c.compileCall(expr)
case returnExpr:
return c.compileReturn(expr)
case breakExpr:
return c.compileBreak(expr)
case continueExpr:
return c.compileContinue(expr)
case arrayExpr:
return c.compileArray(expr)
case tableExpr:
return c.compileTable(expr)
case indexExpr:
return c.compileIndex(expr)
case importExpr:
return c.compileImport(expr)
default:
return fmt.Errorf("unknown expression type: %v", expr.Type)
}
}
func (c *Compiler) compileNumber(expr *expression) error {
// Convert string number to actual numeric type
numStr := expr.Value.(string)
var value interface{}
// Check if it contains a decimal point
if strings.Contains(numStr, ".") {
if f, err := strconv.ParseFloat(numStr, 64); err != nil {
return fmt.Errorf("invalid float: %s", numStr)
} else {
value = f
}
} else {
if i, err := strconv.Atoi(numStr); err != nil {
return fmt.Errorf("invalid integer: %s", numStr)
} else {
value = i
// Optimize common small integers
switch i {
case 0:
c.chunk.AddInstruction(OP_CONST_0, expr.Line, expr.File)
return nil
case 1:
c.chunk.AddInstruction(OP_CONST_1, expr.Line, expr.File)
return nil
case 2:
c.chunk.AddInstruction(OP_CONST_2, expr.Line, expr.File)
return nil
}
}
}
constIndex := c.chunk.AddConstant(value)
c.chunk.AddInstructionWithOperand(OP_CONSTANT, constIndex, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileString(expr *expression) error {
constIndex := c.chunk.AddConstant(expr.Value)
c.chunk.AddInstructionWithOperand(OP_CONSTANT, constIndex, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileBool(expr *expression) error {
constIndex := c.chunk.AddConstant(expr.Value)
c.chunk.AddInstructionWithOperand(OP_CONSTANT, constIndex, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileVariable(expr *expression) error {
varName := expr.Value.(string)
// Check for field access (e.g., obj.field)
if expr.Left != nil {
if err := c.Compile(expr.Left); err != nil {
return err
}
fieldIndex := c.chunk.AddConstant(varName)
c.chunk.AddInstructionWithOperand(OP_CONSTANT, fieldIndex, expr.Line, expr.File)
c.chunk.AddInstruction(OP_INDEX, expr.Line, expr.File)
return nil
}
// Check if it's a local variable
for i := len(c.locals) - 1; i >= 0; i-- {
if c.locals[i] == varName {
c.chunk.AddInstructionWithOperand(OP_GET_LOCAL, i, expr.Line, expr.File)
return nil
}
}
// It's a global variable
globalIndex, exists := c.globalNames[varName]
if !exists {
globalIndex = len(c.globalNames)
c.globalNames[varName] = globalIndex
}
c.chunk.AddInstructionWithOperand(OP_GET_GLOBAL, globalIndex, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileAssignment(expr *expression) error {
// First compile the right side (the value to assign)
if err := c.Compile(expr.Right); err != nil {
return err
}
// Infer the type of the assigned value for optimization
assignedType := c.inferType(expr.Right)
if expr.Left.Type == varExpr {
varName := expr.Left.Value.(string)
// Check for field assignment (e.g., obj.field = value)
if expr.Left.Left != nil {
if err := c.Compile(expr.Left.Left); err != nil {
return err
}
fieldIndex := c.chunk.AddConstant(varName)
c.chunk.AddInstructionWithOperand(OP_CONSTANT, fieldIndex, expr.Line, expr.File)
c.chunk.AddInstruction(OP_INDEX_SET, expr.Line, expr.File)
return nil
}
// Check if it's a local variable
for i := len(c.locals) - 1; i >= 0; i-- {
if c.locals[i] == varName {
// Track the type of this local variable for future optimizations
c.localTypes[varName] = assignedType
c.chunk.AddInstructionWithOperand(OP_SET_LOCAL, i, expr.Line, expr.File)
return nil
}
}
// It's a global variable
globalIndex, exists := c.globalNames[varName]
if !exists {
globalIndex = len(c.globalNames)
c.globalNames[varName] = globalIndex
}
c.chunk.AddInstructionWithOperand(OP_SET_GLOBAL, globalIndex, expr.Line, expr.File)
return nil
}
if expr.Left.Type == indexExpr {
// Array/table index assignment
if err := c.Compile(expr.Left.Left); err != nil {
return err
}
if err := c.Compile(expr.Left.Index); err != nil {
return err
}
c.chunk.AddInstruction(OP_INDEX_SET, expr.Line, expr.File)
return nil
}
return fmt.Errorf("invalid assignment target")
}
func (c *Compiler) compileBinary(expr *expression) error {
// Handle short-circuit evaluation for && and ||
if expr.Operator == "&&" {
if err := c.Compile(expr.Left); err != nil {
return err
}
c.chunk.AddInstruction(OP_DUP, expr.Line, expr.File)
jumpFalse := c.chunk.AddInstructionWithOperand(OP_JUMP_FALSE, 0, expr.Line, expr.File)
c.chunk.AddInstruction(OP_POP, expr.Line, expr.File)
if err := c.Compile(expr.Right); err != nil {
return err
}
c.chunk.PatchJump(jumpFalse, len(c.chunk.Instructions))
return nil
}
if expr.Operator == "||" {
if err := c.Compile(expr.Left); err != nil {
return err
}
c.chunk.AddInstruction(OP_DUP, expr.Line, expr.File)
jumpTrue := c.chunk.AddInstructionWithOperand(OP_JUMP_TRUE, 0, expr.Line, expr.File)
c.chunk.AddInstruction(OP_POP, expr.Line, expr.File)
if err := c.Compile(expr.Right); err != nil {
return err
}
c.chunk.PatchJump(jumpTrue, len(c.chunk.Instructions))
return nil
}
// Regular binary operations - with pattern optimization and type inference
// Pattern optimization for common cases like n-1, n-2
if expr.Operator == "-" && expr.Right.Type == numExpr {
if rightVal, err := strconv.Atoi(expr.Right.Value.(string)); err == nil && rightVal >= 0 && rightVal <= 255 {
// Compile left operand only
if err := c.Compile(expr.Left); err != nil {
return err
}
// Use optimized subtract constant instruction
c.chunk.AddInstructionWithOperand(OP_SUB_CONST, rightVal, expr.Line, expr.File)
return nil
}
}
// Pattern optimization for addition with small constants
if expr.Operator == "+" && expr.Right.Type == numExpr {
if rightVal, err := strconv.Atoi(expr.Right.Value.(string)); err == nil && rightVal >= 0 && rightVal <= 255 {
if err := c.Compile(expr.Left); err != nil {
return err
}
c.chunk.AddInstructionWithOperand(OP_ADD_CONST, rightVal, expr.Line, expr.File)
return nil
}
}
// Regular path for other operations
if err := c.Compile(expr.Left); err != nil {
return err
}
leftType := c.inferType(expr.Left)
c.pushType(leftType)
if err := c.Compile(expr.Right); err != nil {
return err
}
rightType := c.inferType(expr.Right)
c.pushType(rightType)
// Pop the operand types (we know them already)
c.popType() // right
c.popType() // left
// Emit the most efficient instruction based on operand types
return c.emitTypedBinaryOp(expr.Operator, leftType, rightType, expr.Line, expr.File)
}
// Helper function to infer the type of an expression
func (c *Compiler) inferType(expr *expression) ValueType {
switch expr.Type {
case numExpr:
numStr := expr.Value.(string)
if strings.Contains(numStr, ".") {
return TypeFloat
}
return TypeInt
case strExpr:
return TypeString
case boolExpr:
return TypeBool
case varExpr:
varName := expr.Value.(string)
if varType, exists := c.localTypes[varName]; exists {
return varType
}
return TypeUnknown
case binaryExpr:
leftType := c.inferType(expr.Left)
rightType := c.inferType(expr.Right)
switch expr.Operator {
case "+", "-", "*", "/":
// Arithmetic operations
if leftType == TypeInt && rightType == TypeInt {
return TypeInt
}
if (leftType == TypeInt || leftType == TypeFloat) &&
(rightType == TypeInt || rightType == TypeFloat) {
return TypeFloat
}
case "==", "!=", "<", "<=", ">", ">=":
// Comparison operations always return bool
return TypeBool
case "&&", "||":
// Logical operations always return bool
return TypeBool
}
case callExpr:
// For recursive functions like fibonacci, assume int return type
if expr.Func.Type == varExpr && expr.Func.Value == "fibonacci" {
return TypeInt
}
return TypeUnknown
}
return TypeUnknown
}
// Push a type onto the stack type tracker
func (c *Compiler) pushType(t ValueType) {
c.stackTypes = append(c.stackTypes, t)
}
// Pop a type from the stack type tracker
func (c *Compiler) popType() ValueType {
if len(c.stackTypes) == 0 {
return TypeUnknown
}
t := c.stackTypes[len(c.stackTypes)-1]
c.stackTypes = c.stackTypes[:len(c.stackTypes)-1]
return t
}
// Emit the most efficient binary operation instruction based on types
func (c *Compiler) emitTypedBinaryOp(operator string, leftType, rightType ValueType, line int, file string) error {
switch operator {
case "+":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_ADD_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_ADD_FLOAT, line, file)
} else if leftType == TypeInt && rightType == TypeFloat {
c.chunk.AddInstruction(OP_ADD_INT_FLOAT, line, file)
} else if leftType == TypeFloat && rightType == TypeInt {
c.chunk.AddInstruction(OP_ADD_FLOAT_INT, line, file)
} else {
c.chunk.AddInstruction(OP_ADD, line, file)
}
case "-":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_SUB_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_SUB_FLOAT, line, file)
} else if leftType == TypeInt && rightType == TypeFloat {
c.chunk.AddInstruction(OP_SUB_INT_FLOAT, line, file)
} else if leftType == TypeFloat && rightType == TypeInt {
c.chunk.AddInstruction(OP_SUB_FLOAT_INT, line, file)
} else {
c.chunk.AddInstruction(OP_SUB, line, file)
}
case "*":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_MUL_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_MUL_FLOAT, line, file)
} else if leftType == TypeInt && rightType == TypeFloat {
c.chunk.AddInstruction(OP_MUL_INT_FLOAT, line, file)
} else if leftType == TypeFloat && rightType == TypeInt {
c.chunk.AddInstruction(OP_MUL_FLOAT_INT, line, file)
} else {
c.chunk.AddInstruction(OP_MUL, line, file)
}
case "/":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_DIV_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_DIV_FLOAT, line, file)
} else if leftType == TypeInt && rightType == TypeFloat {
c.chunk.AddInstruction(OP_DIV_INT_FLOAT, line, file)
} else if leftType == TypeFloat && rightType == TypeInt {
c.chunk.AddInstruction(OP_DIV_FLOAT_INT, line, file)
} else {
c.chunk.AddInstruction(OP_DIV, line, file)
}
case "%":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_MOD_INT, line, file)
} else {
c.chunk.AddInstruction(OP_MOD, line, file)
}
case "==":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_EQ_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_EQ_FLOAT, line, file)
} else {
c.chunk.AddInstruction(OP_EQ, line, file)
}
case "<":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_LT_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_LT_FLOAT, line, file)
} else {
c.chunk.AddInstruction(OP_LT, line, file)
}
case "<=":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_LE_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_LE_FLOAT, line, file)
} else {
c.chunk.AddInstruction(OP_LE, line, file)
}
case ">":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_GT_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_GT_FLOAT, line, file)
} else {
c.chunk.AddInstruction(OP_GT, line, file)
}
case ">=":
if leftType == TypeInt && rightType == TypeInt {
c.chunk.AddInstruction(OP_GE_INT, line, file)
} else if leftType == TypeFloat && rightType == TypeFloat {
c.chunk.AddInstruction(OP_GE_FLOAT, line, file)
} else {
c.chunk.AddInstruction(OP_GE, line, file)
}
default:
return c.emitGeneralBinaryOp(operator, line, file)
}
return nil
}
// Helper function to emit general binary operations
func (c *Compiler) emitGeneralBinaryOp(operator string, line int, file string) error {
switch operator {
case "+":
c.chunk.AddInstruction(OP_ADD, line, file)
case "-":
c.chunk.AddInstruction(OP_SUB, line, file)
case "*":
c.chunk.AddInstruction(OP_MUL, line, file)
case "/":
c.chunk.AddInstruction(OP_DIV, line, file)
case "%":
c.chunk.AddInstruction(OP_MOD, line, file)
case "==":
c.chunk.AddInstruction(OP_EQ, line, file)
case "!=":
c.chunk.AddInstruction(OP_NE, line, file)
case "<":
c.chunk.AddInstruction(OP_LT, line, file)
case "<=":
c.chunk.AddInstruction(OP_LE, line, file)
case ">":
c.chunk.AddInstruction(OP_GT, line, file)
case ">=":
c.chunk.AddInstruction(OP_GE, line, file)
default:
return fmt.Errorf("unknown binary operator: %s", operator)
}
return nil
}
func (c *Compiler) compileUnary(expr *expression) error {
if err := c.Compile(expr.Left); err != nil {
return err
}
switch expr.Operator {
case "-":
c.chunk.AddInstruction(OP_NEG, expr.Line, expr.File)
case "not":
c.chunk.AddInstruction(OP_NOT, expr.Line, expr.File)
default:
return fmt.Errorf("unknown unary operator: %s", expr.Operator)
}
return nil
}
func (c *Compiler) compileBlock(expr *expression) error {
for _, stmt := range expr.Block {
if err := c.Compile(stmt); err != nil {
return err
}
// Pop the result of expression statements (except the last one)
if stmt != expr.Block[len(expr.Block)-1] {
c.chunk.AddInstruction(OP_POP, stmt.Line, stmt.File)
}
}
return nil
}
func (c *Compiler) compileIf(expr *expression) error {
// Try to optimize common patterns like "n <= 1"
if c.tryOptimizeIfPattern(expr) {
return nil
}
// Regular if compilation
if err := c.Compile(expr.Cond); err != nil {
return err
}
// Jump to else branch if condition is false
jumpFalse := c.chunk.AddInstructionWithOperand(OP_JUMP_FALSE, 0, expr.Line, expr.File)
// Compile then branch
if err := c.Compile(expr.Then); err != nil {
return err
}
// Jump over else branch
jumpEnd := c.chunk.AddInstructionWithOperand(OP_JUMP, 0, expr.Line, expr.File)
// Patch the false jump to point to else branch
c.chunk.PatchJump(jumpFalse, len(c.chunk.Instructions))
// Compile else branch if it exists
if expr.Else != nil {
if err := c.Compile(expr.Else); err != nil {
return err
}
} else {
// Push nil if no else branch
nilIndex := c.chunk.AddConstant(nil)
c.chunk.AddInstructionWithOperand(OP_CONSTANT, nilIndex, expr.Line, expr.File)
}
// Patch the end jump
c.chunk.PatchJump(jumpEnd, len(c.chunk.Instructions))
return nil
}
func (c *Compiler) compileWhile(expr *expression) error {
loopStart := len(c.chunk.Instructions)
c.loopStarts = append(c.loopStarts, loopStart)
c.loopEnds = append(c.loopEnds, make([]int, 0))
// Compile condition
if err := c.Compile(expr.Cond); err != nil {
return err
}
// Jump out of loop if condition is false
jumpFalse := c.chunk.AddInstructionWithOperand(OP_JUMP_FALSE, 0, expr.Line, expr.File)
// Compile loop body
if err := c.Compile(expr.Body); err != nil {
return err
}
c.chunk.AddInstruction(OP_POP, expr.Line, expr.File) // Pop body result
// Jump back to condition
c.chunk.AddInstructionWithOperand(OP_LOOP, loopStart, expr.Line, expr.File)
// Patch the false jump
c.chunk.PatchJump(jumpFalse, len(c.chunk.Instructions))
// Patch all break statements in this loop
for _, breakPos := range c.loopEnds[len(c.loopEnds)-1] {
c.chunk.PatchJump(breakPos, len(c.chunk.Instructions))
}
// Pop loop tracking
c.loopStarts = c.loopStarts[:len(c.loopStarts)-1]
c.loopEnds = c.loopEnds[:len(c.loopEnds)-1]
// Push nil as while loop result
nilIndex := c.chunk.AddConstant(nil)
c.chunk.AddInstructionWithOperand(OP_CONSTANT, nilIndex, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileFunction(expr *expression) error {
// Functions are compiled as closures
funcChunk := NewChunk()
oldChunk := c.chunk
c.chunk = funcChunk
oldLocals := c.locals
c.locals = make([]string, 0)
oldLocalTypes := c.localTypes
c.localTypes = make(map[string]ValueType)
oldIsInFunction := c.isInFunction
c.isInFunction = true
// Add parameters as local variables
c.locals = append(c.locals, expr.Params...)
// For mathematical functions, try to infer parameter types
for _, param := range expr.Params {
// For common mathematical parameter names, assume integer
if param == "n" || param == "x" || param == "i" || param == "count" {
c.localTypes[param] = TypeInt
} else {
c.localTypes[param] = TypeUnknown
}
}
// Compile function body
if err := c.Compile(expr.Body); err != nil {
return err
}
// Add implicit return if function doesn't end with return
if len(funcChunk.Instructions) == 0 || funcChunk.Instructions[len(funcChunk.Instructions)-1].Op != OP_RETURN {
// If no explicit return, return the last expression value
funcChunk.AddInstruction(OP_RETURN, expr.Line, expr.File)
}
// Restore compiler state
c.chunk = oldChunk
c.locals = oldLocals
c.localTypes = oldLocalTypes
c.isInFunction = oldIsInFunction
// Create closure instruction
funcIndex := c.chunk.AddConstant(funcChunk)
c.chunk.AddInstructionWithOperand(OP_CLOSURE, funcIndex, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileCall(expr *expression) error {
// Compile function expression
if err := c.Compile(expr.Func); err != nil {
return err
}
// Compile arguments with compound instruction optimization
if err := c.compileArguments(expr.Args, expr.Line, expr.File); err != nil {
return err
}
// Call instruction with argument count
c.chunk.AddInstructionWithOperand(OP_CALL, len(expr.Args), expr.Line, expr.File)
return nil
}
func (c *Compiler) compileReturn(expr *expression) error {
if expr.Right != nil {
if err := c.Compile(expr.Right); err != nil {
return err
}
} else {
nilIndex := c.chunk.AddConstant(nil)
c.chunk.AddInstructionWithOperand(OP_CONSTANT, nilIndex, expr.Line, expr.File)
}
c.chunk.AddInstruction(OP_RETURN, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileBreak(expr *expression) error {
if len(c.loopEnds) == 0 {
return fmt.Errorf("break statement outside of loop")
}
breakJump := c.chunk.AddInstructionWithOperand(OP_JUMP, 0, expr.Line, expr.File)
c.loopEnds[len(c.loopEnds)-1] = append(c.loopEnds[len(c.loopEnds)-1], breakJump)
return nil
}
func (c *Compiler) compileContinue(expr *expression) error {
if len(c.loopStarts) == 0 {
return fmt.Errorf("continue statement outside of loop")
}
loopStart := c.loopStarts[len(c.loopStarts)-1]
c.chunk.AddInstructionWithOperand(OP_LOOP, loopStart, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileArray(expr *expression) error {
// Compile array elements
for _, elem := range expr.Args {
if err := c.Compile(elem); err != nil {
return err
}
}
// Create array with the specified number of elements
c.chunk.AddInstructionWithOperand(OP_ARRAY, len(expr.Args), expr.Line, expr.File)
return nil
}
func (c *Compiler) compileTable(expr *expression) error {
count := 0
// Compile key-value pairs
for _, pair := range expr.Args {
if pair.Type == pairExpr {
if err := c.Compile(pair.Left); err != nil { // key
return err
}
if err := c.Compile(pair.Right); err != nil { // value
return err
}
count++
}
}
// Create table with the specified number of pairs
c.chunk.AddInstructionWithOperand(OP_TABLE, count, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileIndex(expr *expression) error {
// Compile the object being indexed
if err := c.Compile(expr.Left); err != nil {
return err
}
// Compile the index
if err := c.Compile(expr.Index); err != nil {
return err
}
c.chunk.AddInstruction(OP_INDEX, expr.Line, expr.File)
return nil
}
func (c *Compiler) compileImport(expr *expression) error {
// For now, imports are handled at runtime
if err := c.Compile(expr.Left); err != nil {
return err
}
c.chunk.AddInstruction(OP_IMPORT, expr.Line, expr.File)
return nil
}
// Helper function to check if a variable is local
func (c *Compiler) isLocalVariable(varName string) bool {
for _, local := range c.locals {
if local == varName {
return true
}
}
return false
}
// Helper function to get local variable index
func (c *Compiler) getLocalIndex(varName string) int {
for i := len(c.locals) - 1; i >= 0; i-- {
if c.locals[i] == varName {
return i
}
}
return -1
}
// Helper function to add constant and return index
func (c *Compiler) addConstantValue(expr *expression) int {
var value interface{}
switch expr.Type {
case numExpr:
if i, err := strconv.Atoi(expr.Value.(string)); err == nil {
value = i
} else if f, err := strconv.ParseFloat(expr.Value.(string), 64); err == nil {
value = f
}
case strExpr:
value = expr.Value
case boolExpr:
value = expr.Value
default:
return -1
}
return c.chunk.AddConstant(value)
}
// compileArguments optimizes argument compilation with compound instructions
func (c *Compiler) compileArguments(args []*expression, line int, file string) error {
i := 0
for i < len(args) {
// Try to compile pairs of arguments with compound instructions
if i+1 < len(args) {
if c.tryCompileArgumentPair(args[i], args[i+1], line, file) {
i += 2 // Skip both arguments, they were compiled together
continue
}
}
// Regular compilation for single argument
if err := c.Compile(args[i]); err != nil {
return err
}
i++
}
return nil
}
// tryCompileArgumentPair attempts to compile two arguments with a compound instruction
func (c *Compiler) tryCompileArgumentPair(arg1, arg2 *expression, line int, file string) bool {
// Check if both arguments are constants
if (arg1.Type == numExpr || arg1.Type == strExpr || arg1.Type == boolExpr) &&
(arg2.Type == numExpr || arg2.Type == strExpr || arg2.Type == boolExpr) {
constIndex1 := c.addConstantValue(arg1)
constIndex2 := c.addConstantValue(arg2)
c.chunk.AddInstructionWithTwoOperands(OP_CONST_CONST, constIndex1, constIndex2, line, file)
return true
}
// Check if first is constant, second is local variable
if (arg1.Type == numExpr || arg1.Type == strExpr || arg1.Type == boolExpr) &&
arg2.Type == varExpr && c.isLocalVariable(arg2.Value.(string)) {
constIndex := c.addConstantValue(arg1)
localIndex := c.getLocalIndex(arg2.Value.(string))
c.chunk.AddInstructionWithTwoOperands(OP_CONST_LOCAL, constIndex, localIndex, line, file)
return true
}
// Check if first is local variable, second is constant
if arg1.Type == varExpr && c.isLocalVariable(arg1.Value.(string)) &&
(arg2.Type == numExpr || arg2.Type == strExpr || arg2.Type == boolExpr) {
localIndex := c.getLocalIndex(arg1.Value.(string))
constIndex := c.addConstantValue(arg2)
c.chunk.AddInstructionWithTwoOperands(OP_LOCAL_CONST, localIndex, constIndex, line, file)
return true
}
// Check if both are local variables
if arg1.Type == varExpr && c.isLocalVariable(arg1.Value.(string)) &&
arg2.Type == varExpr && c.isLocalVariable(arg2.Value.(string)) {
localIndex1 := c.getLocalIndex(arg1.Value.(string))
localIndex2 := c.getLocalIndex(arg2.Value.(string))
c.chunk.AddInstructionWithTwoOperands(OP_LOCAL_LOCAL, localIndex1, localIndex2, line, file)
return true
}
return false
}
// tryOptimizeIfPattern attempts to optimize common if patterns like "n <= 1"
func (c *Compiler) tryOptimizeIfPattern(expr *expression) bool {
cond := expr.Cond
// Check if condition is a comparison with a small constant
if cond != nil && cond.Type == binaryExpr {
// Look for patterns like "variable <= small_constant"
if cond.Operator == "<=" && cond.Right != nil && cond.Right.Type == numExpr {
if rightVal, err := strconv.Atoi(cond.Right.Value.(string)); err == nil && rightVal >= 0 && rightVal <= 255 {
// This is "variable <= small_constant"
// Compile the variable (left side)
if err := c.Compile(cond.Left); err != nil {
return false
}
// Reserve space for the jump instruction
jumpElse := len(c.chunk.Instructions)
c.chunk.AddInstructionWithTwoOperands(OP_JUMP_LE_CONST, rightVal, 0, expr.Line, expr.File)
// Compile then branch
if err := c.Compile(expr.Then); err != nil {
return false
}
// Jump over else branch
jumpEnd := c.chunk.AddInstructionWithOperand(OP_JUMP, 0, expr.Line, expr.File)
// Patch the conditional jump to point to else branch
c.chunk.Instructions[jumpElse].Operand2 = len(c.chunk.Instructions)
// Compile else branch if it exists
if expr.Else != nil {
if err := c.Compile(expr.Else); err != nil {
return false
}
}
// Patch the end jump
c.chunk.PatchJump(jumpEnd, len(c.chunk.Instructions))
return true
}
}
// Similar optimization for ">" operator
if cond.Operator == ">" && cond.Right != nil && cond.Right.Type == numExpr {
if rightVal, err := strconv.Atoi(cond.Right.Value.(string)); err == nil && rightVal >= 0 && rightVal <= 255 {
if err := c.Compile(cond.Left); err != nil {
return false
}
jumpElse := len(c.chunk.Instructions)
c.chunk.AddInstructionWithTwoOperands(OP_JUMP_GT_CONST, rightVal, 0, expr.Line, expr.File)
if err := c.Compile(expr.Then); err != nil {
return false
}
jumpEnd := c.chunk.AddInstructionWithOperand(OP_JUMP, 0, expr.Line, expr.File)
c.chunk.Instructions[jumpElse].Operand2 = len(c.chunk.Instructions)
if expr.Else != nil {
if err := c.Compile(expr.Else); err != nil {
return false
}
}
c.chunk.PatchJump(jumpEnd, len(c.chunk.Instructions))
return true
}
}
}
return false
}
// GetChunk returns the compiled chunk
func (c *Compiler) GetChunk() *Chunk {
return c.chunk
}
// GetGlobalNames returns the global variable names mapping
func (c *Compiler) GetGlobalNames() map[string]int {
return c.globalNames
}