-
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbytecode.go
More file actions
3230 lines (2966 loc) · 76.1 KB
/
bytecode.go
File metadata and controls
3230 lines (2966 loc) · 76.1 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
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"fmt"
"math"
"os"
"strconv"
"strings"
"sync"
)
// ---------------------------------------------------------------------------
// Opcodes — matches the wasm-vm.oak opcode set for consistency
// ---------------------------------------------------------------------------
type opcode byte
const (
opHalt opcode = 0
opNop opcode = 1
opConstNull opcode = 2
opConstEmpty opcode = 3
opConstTrue opcode = 4
opConstFalse opcode = 5
opConstInt opcode = 6 // i32 operand (little-endian)
opConstFloat opcode = 7 // u16 constant pool index
opConstStr opcode = 8 // u16 constant pool index
opConstAtom opcode = 9 // u16 constant pool index
opPop opcode = 10 // discard TOS
opDup opcode = 11 // duplicate TOS
opLoadLocal opcode = 12 // u16 slot
opStoreLocal opcode = 13 // u16 slot
opLoadUpval opcode = 14 // u16 name constant index (name-based scope chain lookup)
opStoreUpval opcode = 15 // u16 name constant index (name-based scope chain lookup)
opAdd opcode = 16
opSub opcode = 17
opMul opcode = 18
opDiv opcode = 19
opMod opcode = 20
opPow opcode = 21
opNeg opcode = 22
opBAnd opcode = 23
opBOr opcode = 24
opBXor opcode = 25
opBRShift opcode = 26
opEq opcode = 27
opNeq opcode = 28
opGt opcode = 29
opLt opcode = 30
opGeq opcode = 31
opLeq opcode = 32
opNot opcode = 33
opConcat opcode = 34 // << (push/append)
opMakeList opcode = 35 // u16 count
opMakeObj opcode = 36 // u16 pair count
opGetProp opcode = 37 // pop key, pop obj, push result
opSetProp opcode = 38 // pop val, pop key, pop obj → set, push val
opJump opcode = 39 // i32 absolute offset
opJumpFalse opcode = 40 // i32 absolute offset (pops condition)
opClosure opcode = 41 // u16 function template index
opCall opcode = 42 // u8 arity
opReturn opcode = 43
opTailCall opcode = 44 // u8 arity
opBuiltin opcode = 45 // u16 builtin index, u8 arity
opImport opcode = 46 // u16 constant pool index (module name)
opImportDyn opcode = 47 // pop string from stack, import that module
opDeepEq opcode = 48
opSwap opcode = 49
opMatchJump opcode = 50 // pop & compare TOS, jump i32 if no match
opScopePush opcode = 51
opScopePop opcode = 52
opCallSpread opcode = 53 // u8 arity — last arg is a list to spread
)
var opcodeNames = [...]string{
"HALT", "NOP", "CONST_NULL", "CONST_EMPTY",
"CONST_TRUE", "CONST_FALSE", "CONST_INT", "CONST_FLOAT",
"CONST_STRING", "CONST_ATOM", "POP", "DUP",
"LOAD_LOCAL", "STORE_LOCAL", "LOAD_UPVAL", "STORE_UPVAL",
"ADD", "SUB", "MUL", "DIV", "MOD", "POW", "NEG",
"BAND", "BOR", "BXOR", "BRSHIFT",
"EQ", "NEQ", "GT", "LT", "GEQ", "LEQ",
"NOT", "CONCAT", "MAKE_LIST", "MAKE_OBJECT",
"GET_PROP", "SET_PROP",
"JUMP", "JUMP_FALSE",
"CLOSURE", "CALL", "RETURN", "TAIL_CALL",
"BUILTIN", "IMPORT", "IMPORT_DYN", "DEEP_EQ",
"SWAP", "MATCH_JUMP",
"SCOPE_PUSH", "SCOPE_POP",
"CALL_SPREAD",
}
// ---------------------------------------------------------------------------
// Constant pool entry
// ---------------------------------------------------------------------------
type constKind byte
const (
constString constKind = 0
constAtom constKind = 1
constFloat constKind = 2
)
type constEntry struct {
kind constKind
str string // for constString and constAtom
f float64 // for constFloat
}
// ---------------------------------------------------------------------------
// Function template (one per fn definition in source)
// ---------------------------------------------------------------------------
type funcTemplate struct {
offset int // bytecode offset where body starts
arity int // number of named parameters
localCount int // total local slots needed
name string // function name (may be empty)
hasRestArg bool
localNames []string // name for each local slot (for scope chain construction)
defn *fnNode // preserved AST for interpreter() engine switching
}
// ---------------------------------------------------------------------------
// Bytecode chunk — output of compilation
// ---------------------------------------------------------------------------
// sourceMapEntry maps a bytecode offset to a source position.
type sourceMapEntry struct {
offset int
pos pos
}
type bytecodeChunk struct {
code []byte
constants []constEntry
functions []funcTemplate
topLevelNames []string // local slot names for top-level code
sourceMap []sourceMapEntry
}
// ---------------------------------------------------------------------------
// .mgb binary format loader
// ---------------------------------------------------------------------------
const mgbMagic = "MGbc"
const mgbVersion = 2
// loadBytecodeChunk deserializes a .mgb binary file into a bytecodeChunk.
// Format: "MGbc" <version:u16LE> <bcSection> <cpSection> <ftSection>
// Each section: <length:u32LE> <data:N bytes>
func loadBytecodeChunk(data []byte) (*bytecodeChunk, error) {
if len(data) < 6 {
return nil, fmt.Errorf("mgb: file too short")
}
if string(data[0:4]) != mgbMagic {
return nil, fmt.Errorf("mgb: invalid magic (expected %q)", mgbMagic)
}
version := uint16(data[4]) | uint16(data[5])<<8
if version != mgbVersion {
return nil, fmt.Errorf("mgb: unsupported version %d", version)
}
off := 6
// --- Bytecode section ---
if off+4 > len(data) {
return nil, fmt.Errorf("mgb: truncated bytecode section header")
}
bcLen := int(u32le(data, off))
off += 4
if off+bcLen > len(data) {
return nil, fmt.Errorf("mgb: truncated bytecode section")
}
code := make([]byte, bcLen)
copy(code, data[off:off+bcLen])
off += bcLen
// --- Constant pool section ---
if off+4 > len(data) {
return nil, fmt.Errorf("mgb: truncated constant pool section header")
}
cpLen := int(u32le(data, off))
off += 4
cpEnd := off + cpLen
if cpEnd > len(data) {
return nil, fmt.Errorf("mgb: truncated constant pool section")
}
constants, err := deserializeConstantPool(data[off:cpEnd])
if err != nil {
return nil, err
}
off = cpEnd
// --- Function table section ---
if off+4 > len(data) {
return nil, fmt.Errorf("mgb: truncated function table section header")
}
ftLen := int(u32le(data, off))
off += 4
ftEnd := off + ftLen
if ftEnd > len(data) {
return nil, fmt.Errorf("mgb: truncated function table section")
}
functions, err := deserializeFunctionTable(data[off:ftEnd])
if err != nil {
return nil, err
}
off = ftEnd
// --- Top-level names section ---
var topLevelNames []string
if off+4 <= len(data) {
tlLen := int(u32le(data, off))
off += 4
tlEnd := off + tlLen
if tlEnd > len(data) {
return nil, fmt.Errorf("mgb: truncated top-level names section")
}
topLevelNames, err = deserializeNameList(data[off:tlEnd])
if err != nil {
return nil, err
}
}
return &bytecodeChunk{
code: code,
constants: constants,
functions: functions,
topLevelNames: topLevelNames,
}, nil
}
func u32le(data []byte, off int) uint32 {
return uint32(data[off]) | uint32(data[off+1])<<8 | uint32(data[off+2])<<16 | uint32(data[off+3])<<24
}
func deserializeConstantPool(data []byte) ([]constEntry, error) {
if len(data) < 4 {
return nil, fmt.Errorf("mgb: constant pool too short")
}
count := int(u32le(data, 0))
off := 4
entries := make([]constEntry, 0, count)
for i := 0; i < count; i++ {
if off >= len(data) {
return nil, fmt.Errorf("mgb: constant pool truncated at entry %d", i)
}
kind := constKind(data[off])
off++
if off+4 > len(data) {
return nil, fmt.Errorf("mgb: constant pool truncated at entry %d length", i)
}
slen := int(u32le(data, off))
off += 4
if off+slen > len(data) {
return nil, fmt.Errorf("mgb: constant pool truncated at entry %d data", i)
}
raw := string(data[off : off+slen])
off += slen
switch kind {
case constString, constAtom:
entries = append(entries, constEntry{kind: kind, str: raw})
case constFloat:
f, err := strconv.ParseFloat(raw, 64)
if err != nil {
return nil, fmt.Errorf("mgb: bad float constant %q: %w", raw, err)
}
entries = append(entries, constEntry{kind: kind, f: f})
default:
return nil, fmt.Errorf("mgb: unknown constant kind %d", kind)
}
}
return entries, nil
}
func deserializeFunctionTable(data []byte) ([]funcTemplate, error) {
if len(data) < 4 {
return nil, fmt.Errorf("mgb: function table too short")
}
count := int(u32le(data, 0))
off := 4
fns := make([]funcTemplate, 0, count)
for i := 0; i < count; i++ {
if off+9 > len(data) {
return nil, fmt.Errorf("mgb: function table truncated at entry %d", i)
}
offset := int(u32le(data, off))
off += 4
arity := int(uint16(data[off]) | uint16(data[off+1])<<8)
off += 2
localCount := int(uint16(data[off]) | uint16(data[off+1])<<8)
off += 2
hasRestArg := data[off] != 0
off++
// Read local names
var localNames []string
if off+2 <= len(data) {
nameCount := int(uint16(data[off]) | uint16(data[off+1])<<8)
off += 2
localNames = make([]string, 0, nameCount)
for j := 0; j < nameCount; j++ {
if off+2 > len(data) {
return nil, fmt.Errorf("mgb: function %d local name %d truncated", i, j)
}
nl := int(uint16(data[off]) | uint16(data[off+1])<<8)
off += 2
if off+nl > len(data) {
return nil, fmt.Errorf("mgb: function %d local name %d data truncated", i, j)
}
localNames = append(localNames, string(data[off:off+nl]))
off += nl
}
}
fns = append(fns, funcTemplate{
offset: offset,
arity: arity,
localCount: localCount,
hasRestArg: hasRestArg,
localNames: localNames,
})
}
return fns, nil
}
func deserializeNameList(data []byte) ([]string, error) {
if len(data) < 4 {
return nil, fmt.Errorf("mgb: name list too short")
}
count := int(u32le(data, 0))
off := 4
names := make([]string, 0, count)
for i := 0; i < count; i++ {
if off+2 > len(data) {
return nil, fmt.Errorf("mgb: name list truncated at entry %d", i)
}
nl := int(uint16(data[off]) | uint16(data[off+1])<<8)
off += 2
if off+nl > len(data) {
return nil, fmt.Errorf("mgb: name list data truncated at entry %d", i)
}
names = append(names, string(data[off:off+nl]))
off += nl
}
return names, nil
}
// ---------------------------------------------------------------------------
// VM scope chain (for upvalue resolution)
// ---------------------------------------------------------------------------
// vmScope maps local variable names to values via shared slices.
// The values slice is shared with the callFrame's locals array, so
// STORE_LOCAL updates are visible through the scope chain.
type vmScope struct {
names []string // name at each slot index
values []Value // value at each slot index (shared with frame locals)
parent *vmScope
}
// get walks the scope chain to find a variable by name.
func (s *vmScope) get(name string) (Value, bool) {
for scope := s; scope != nil; scope = scope.parent {
for i, n := range scope.names {
if n == name && i < len(scope.values) {
return scope.values[i], true
}
}
}
return nil, false
}
// set walks the scope chain to update a variable by name.
func (s *vmScope) set(name string, val Value) bool {
for scope := s; scope != nil; scope = scope.parent {
for i, n := range scope.names {
if n == name && i < len(scope.values) {
scope.values[i] = val
return true
}
}
}
return false
}
// ---------------------------------------------------------------------------
// Compiler
// ---------------------------------------------------------------------------
type compiler struct {
code []byte
constants []constEntry
functions []funcTemplate
locals []string // current scope local names
scopeStack [][]string // saved locals for outer scopes
parentLocals [][]string // stack of parent scope local name lists (for upvalue resolution)
sourceMap []sourceMapEntry
}
func newCompiler() *compiler {
return &compiler{
code: make([]byte, 0, 256),
constants: make([]constEntry, 0, 16),
functions: make([]funcTemplate, 0, 8),
locals: make([]string, 0, 8),
sourceMap: make([]sourceMapEntry, 0, 32),
}
}
// notePos records the source position for the current bytecode offset.
func (co *compiler) notePos(p pos) {
co.sourceMap = append(co.sourceMap, sourceMapEntry{offset: co.offset(), pos: p})
}
// --- Emission helpers ---
func (co *compiler) emit(b byte) {
co.code = append(co.code, b)
}
func (co *compiler) emitOp(op opcode) {
co.code = append(co.code, byte(op))
}
func (co *compiler) emitU16(v int) {
co.code = append(co.code, byte(v&0xFF), byte((v>>8)&0xFF))
}
func (co *compiler) emitI32(v int) {
co.code = append(co.code,
byte(v&0xFF),
byte((v>>8)&0xFF),
byte((v>>16)&0xFF),
byte((v>>24)&0xFF),
)
}
func (co *compiler) patchI32(offset int, v int) {
co.code[offset] = byte(v & 0xFF)
co.code[offset+1] = byte((v >> 8) & 0xFF)
co.code[offset+2] = byte((v >> 16) & 0xFF)
co.code[offset+3] = byte((v >> 24) & 0xFF)
}
func (co *compiler) offset() int {
return len(co.code)
}
// --- Constant pool ---
func (co *compiler) addString(s string) int {
for i, c := range co.constants {
if c.kind == constString && c.str == s {
return i
}
}
idx := len(co.constants)
co.constants = append(co.constants, constEntry{kind: constString, str: s})
return idx
}
func (co *compiler) addAtom(name string) int {
for i, c := range co.constants {
if c.kind == constAtom && c.str == name {
return i
}
}
idx := len(co.constants)
co.constants = append(co.constants, constEntry{kind: constAtom, str: name})
return idx
}
func (co *compiler) addFloat(v float64) int {
for i, c := range co.constants {
if c.kind == constFloat && c.f == v {
return i
}
}
idx := len(co.constants)
co.constants = append(co.constants, constEntry{kind: constFloat, f: v})
return idx
}
// --- Local variable tracking ---
func (co *compiler) resolveLocal(name string) int {
for i := len(co.locals) - 1; i >= 0; i-- {
if co.locals[i] == name {
return i
}
}
return -1
}
func (co *compiler) declareLocal(name string) int {
idx := co.resolveLocal(name)
if idx >= 0 {
return idx
}
idx = len(co.locals)
co.locals = append(co.locals, name)
return idx
}
// pushScope saves the current locals for restoration via popScope.
// Currently unused but retained for future nested-scope compilation.
var _ = (*compiler).pushScope //nolint:unused
func (co *compiler) pushScope() {
saved := make([]string, len(co.locals))
copy(saved, co.locals)
co.scopeStack = append(co.scopeStack, saved)
}
// popScope restores locals saved by pushScope.
var _ = (*compiler).popScope //nolint:unused
func (co *compiler) popScope() {
n := len(co.scopeStack)
if n > 0 {
co.locals = co.scopeStack[n-1]
co.scopeStack = co.scopeStack[:n-1]
}
}
// resolveUpvalue checks if name exists in any parent scope.
func (co *compiler) resolveUpvalue(name string) bool {
for i := len(co.parentLocals) - 1; i >= 0; i-- {
for _, n := range co.parentLocals[i] {
if n == name {
return true
}
}
}
return false
}
// ---------------------------------------------------------------------------
// AST → Bytecode compilation
// ---------------------------------------------------------------------------
func (co *compiler) compileNode(node astNode) {
co.compileNodeTail(node, false)
}
func (co *compiler) compileNodeTail(node astNode, isTail bool) {
if node == nil {
co.emitOp(opConstNull)
return
}
// Record source position for this node's bytecode
co.notePos(node.pos())
switch n := node.(type) {
case nullNode:
co.emitOp(opConstNull)
case emptyNode:
co.emitOp(opConstEmpty)
case boolNode:
if n.payload {
co.emitOp(opConstTrue)
} else {
co.emitOp(opConstFalse)
}
case intNode:
co.emitOp(opConstInt)
co.emitI32(int(n.payload))
case floatNode:
idx := co.addFloat(n.payload)
co.emitOp(opConstFloat)
co.emitU16(idx)
case *stringNode:
idx := co.addString(string(n.payload))
co.emitOp(opConstStr)
co.emitU16(idx)
case stringNode:
idx := co.addString(string(n.payload))
co.emitOp(opConstStr)
co.emitU16(idx)
case atomNode:
idx := co.addAtom(n.payload)
co.emitOp(opConstAtom)
co.emitU16(idx)
case identifierNode:
// First check current locals
localIdx := co.resolveLocal(n.payload)
if localIdx >= 0 {
co.emitOp(opLoadLocal)
co.emitU16(localIdx)
} else if co.resolveUpvalue(n.payload) {
// Found in a parent scope — emit name-based upvalue lookup
nameIdx := co.addString(n.payload)
co.emitOp(opLoadUpval)
co.emitU16(nameIdx)
} else if len(co.parentLocals) > 0 {
// Inside a function body: unknown identifier is an outer variable
// (e.g., forward reference to a sibling function defined later).
// Use runtime scope chain lookup.
nameIdx := co.addString(n.payload)
co.emitOp(opLoadUpval)
co.emitU16(nameIdx)
} else {
// Top-level: forward reference to a local declared later
localIdx = co.declareLocal(n.payload)
co.emitOp(opLoadLocal)
co.emitU16(localIdx)
}
case unaryNode:
co.compileNode(n.right)
switch n.op {
case minus:
co.emitOp(opNeg)
case exclam:
co.emitOp(opNot)
case tilde:
co.emitOp(opConstInt)
co.emitI32(-1)
co.emitOp(opBXor)
}
case binaryNode:
// Pipe operator: x |> f(a, b) desugars to f(x, a, b)
if n.op == pipeArrow {
if call, ok := n.right.(fnCallNode); ok {
// Compile the function reference
co.compileNode(call.fn)
// Compile the piped value as first argument
co.compileNode(n.left)
// Compile additional arguments
for _, arg := range call.args {
co.compileNode(arg)
}
arity := 1 + len(call.args)
if call.restArg != nil {
co.compileNode(call.restArg)
arity++
}
if isTail && len(co.parentLocals) > 0 && call.restArg == nil {
co.emitOp(opTailCall)
} else {
co.emitOp(opCall)
}
co.emit(byte(arity & 0xFF))
} else {
co.compileNode(n.right)
co.compileNode(n.left)
if isTail && len(co.parentLocals) > 0 {
co.emitOp(opTailCall)
} else {
co.emitOp(opCall)
}
co.emit(1)
}
return
}
co.compileNode(n.left)
co.compileNode(n.right)
switch n.op {
case plus:
co.emitOp(opAdd)
case minus:
co.emitOp(opSub)
case times:
co.emitOp(opMul)
case divide:
co.emitOp(opDiv)
case modulus:
co.emitOp(opMod)
case power:
co.emitOp(opPow)
case and:
co.emitOp(opBAnd)
case or:
co.emitOp(opBOr)
case xor:
co.emitOp(opBXor)
case rshift:
co.emitOp(opBRShift)
case eq:
co.emitOp(opEq)
case deepEq:
co.emitOp(opDeepEq)
case neq:
co.emitOp(opNeq)
case greater:
co.emitOp(opGt)
case less:
co.emitOp(opLt)
case geq:
co.emitOp(opGeq)
case leq:
co.emitOp(opLeq)
case pushArrow:
co.emitOp(opConcat)
}
case assignmentNode:
co.compileAssignment(n)
case propertyAccessNode:
co.compileNode(n.left)
if ident, ok := n.right.(identifierNode); ok {
idx := co.addString(ident.payload)
co.emitOp(opConstStr)
co.emitU16(idx)
} else {
co.compileNode(n.right)
}
co.emitOp(opGetProp)
case listNode:
for _, elem := range n.elems {
co.compileNode(elem)
}
co.emitOp(opMakeList)
co.emitU16(len(n.elems))
case objectNode:
for _, entry := range n.entries {
// Object keys: identifiers are string keys, not variable references
if ident, ok := entry.key.(identifierNode); ok {
idx := co.addString(ident.payload)
co.emitOp(opConstStr)
co.emitU16(idx)
} else {
co.compileNode(entry.key)
}
co.compileNode(entry.val)
}
co.emitOp(opMakeObj)
co.emitU16(len(n.entries))
case blockNode:
if len(n.exprs) == 0 {
co.emitOp(opConstNull)
} else {
for i, expr := range n.exprs {
isLast := i == len(n.exprs)-1
if isLast {
co.compileNodeTail(expr, isTail)
} else {
co.compileNode(expr)
co.emitOp(opPop)
}
}
}
case ifExprNode:
co.compileIfTail(n, isTail)
case fnNode:
co.compileFunction(&n)
case *fnNode:
co.compileFunction(n)
case classNode:
co.compileClass(n)
case fnCallNode:
co.compileFnCallTail(n, isTail)
default:
co.emitOp(opConstNull)
}
}
// compileAssignment handles := and <- for identifiers, property access, and destructuring.
func (co *compiler) compileAssignment(n assignmentNode) {
switch left := n.left.(type) {
case identifierNode:
co.compileNode(n.right)
// Check if the target is a local or an upvalue
localIdx := co.resolveLocal(left.payload)
if localIdx >= 0 {
co.emitOp(opDup)
co.emitOp(opStoreLocal)
co.emitU16(localIdx)
} else if co.resolveUpvalue(left.payload) {
// Assignment to an outer variable
nameIdx := co.addString(left.payload)
co.emitOp(opDup)
co.emitOp(opStoreUpval)
co.emitU16(nameIdx)
} else {
// New local variable
localIdx = co.declareLocal(left.payload)
co.emitOp(opDup)
co.emitOp(opStoreLocal)
co.emitU16(localIdx)
}
case propertyAccessNode:
co.compileNode(left.left)
if ident, ok := left.right.(identifierNode); ok {
idx := co.addString(ident.payload)
co.emitOp(opConstStr)
co.emitU16(idx)
} else {
co.compileNode(left.right)
}
co.compileNode(n.right)
co.emitOp(opSetProp)
case listNode:
co.compileNode(n.right)
for i, elem := range left.elems {
if _, isEmpty := elem.(emptyNode); isEmpty {
continue
}
if ident, ok := elem.(identifierNode); ok {
co.emitOp(opDup)
co.emitOp(opConstInt)
co.emitI32(i)
co.emitOp(opGetProp)
idx := co.declareLocal(ident.payload)
co.emitOp(opStoreLocal)
co.emitU16(idx)
}
}
case objectNode:
co.compileNode(n.right)
for _, entry := range left.entries {
co.emitOp(opDup)
// Keys in destructuring patterns are property names, not variable refs
if ident, ok := entry.key.(identifierNode); ok {
idx := co.addString(ident.payload)
co.emitOp(opConstStr)
co.emitU16(idx)
} else {
co.compileNode(entry.key)
}
co.emitOp(opGetProp)
if ident, ok := entry.val.(identifierNode); ok {
idx := co.declareLocal(ident.payload)
co.emitOp(opStoreLocal)
co.emitU16(idx)
} else {
co.emitOp(opPop)
}
}
default:
co.compileNode(n.right)
}
}
// compileIf compiles an if-expression (pattern matching).
// Convenience wrapper; callers use compileIfTail directly.
var _ = (*compiler).compileIf //nolint:unused
func (co *compiler) compileIf(n ifExprNode) {
co.compileIfTail(n, false)
}
func (co *compiler) compileIfTail(n ifExprNode, isTail bool) {
co.compileNode(n.cond)
var endJumps []int
for _, br := range n.branches {
if _, isEmpty := br.target.(emptyNode); isEmpty {
// Default/wildcard branch: pop condition, execute body
co.emitOp(opPop)
co.compileNodeTail(br.body, isTail)
} else {
// Duplicate condition, compile target, compare
co.emitOp(opDup)
co.compileNode(br.target)
co.emitOp(opEq)
// Jump past this branch body if no match
co.emitOp(opJumpFalse)
skipOffset := co.offset()
co.emitI32(0)
// Match: pop condition, execute body, jump to end
co.emitOp(opPop)
co.compileNodeTail(br.body, isTail)
co.emitOp(opJump)
endJumpOffset := co.offset()
co.emitI32(0)
endJumps = append(endJumps, endJumpOffset)
// Patch skip
co.patchI32(skipOffset, co.offset())
}
}
endTarget := co.offset()
for _, off := range endJumps {
co.patchI32(off, endTarget)
}
}
// compileFunction compiles a fn definition.
func (co *compiler) compileFunction(n *fnNode) {
// NOTE: Do NOT capture fnIdx here — inner function compilations
// will register their templates first, shifting the index.
// Pre-declare the function name in the outer scope BEFORE compiling body.
// This ensures the name is in the parent locals so the body can
// reference it as an upvalue for self-recursion.
var nameSlot int
if n.name != "" {
nameSlot = co.declareLocal(n.name)
}
// Save outer locals (now includes the pre-declared function name)
savedLocals := make([]string, len(co.locals))
copy(savedLocals, co.locals)
// Push outer locals onto parentLocals stack for upvalue resolution
co.parentLocals = append(co.parentLocals, savedLocals)
// Jump over inline function body
co.emitOp(opJump)
jumpOverOffset := co.offset()
co.emitI32(0)
fnBodyStart := co.offset()
// Fresh locals for the function body
co.locals = co.locals[:0]
for _, arg := range n.args {
if arg == "" {
// Empty args (_) must each occupy their own slot even though
// they share the same "" name. declareLocal would deduplicate
// them, causing localCount < arity and an index panic.
idx := len(co.locals)
co.locals = append(co.locals, "")
_ = idx
} else {
co.declareLocal(arg)
}
}
if n.restArg != "" {
co.declareLocal(n.restArg)
}
// Compile body (may register inner function templates!)
// Mark body as tail position so recursive calls emit opTailCall
co.compileNodeTail(n.body, true)
co.emitOp(opReturn)
fnBodyEnd := co.offset()
localCount := len(co.locals)
localNamesCopy := make([]string, localCount)
copy(localNamesCopy, co.locals)
// Pop parentLocals stack
co.parentLocals = co.parentLocals[:len(co.parentLocals)-1]
// Restore outer locals
co.locals = savedLocals
// Patch jump-over
co.patchI32(jumpOverOffset, fnBodyEnd)
// Register function template AFTER body compilation (correct index)
fnIdx := len(co.functions)
co.functions = append(co.functions, funcTemplate{
offset: fnBodyStart,
arity: len(n.args),
localCount: localCount,
name: n.name,
hasRestArg: n.restArg != "",
localNames: localNamesCopy,
defn: n,
})
// Emit CLOSURE in outer code
co.emitOp(opClosure)
co.emitU16(fnIdx)
// If named, also bind as local in outer scope
if n.name != "" {
co.emitOp(opDup)
co.emitOp(opStoreLocal)
co.emitU16(nameSlot)
}
}
// compileClass compiles a class node (desugars to fn).
func (co *compiler) compileClass(n classNode) {
fnNode := &fnNode{