forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmir_codegen.rs
More file actions
2375 lines (2265 loc) · 95.8 KB
/
Copy pathmir_codegen.rs
File metadata and controls
2375 lines (2265 loc) · 95.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
988
989
990
991
992
993
994
995
996
997
998
999
1000
//! MIR -> Bytecode codegen.
//!
//! Converts the Mid-level IR into the existing `CodeModule` bytecode format,
//! following the same runtime contracts as the stable AST compiler:
//!
//! - call arguments travel in r0..rN, the callee value in r254;
//! - closures are `Closure` objects over function-table entries, with
//! captures stored via `CapStore` and loaded via a `CapLoad` prologue;
//! - records use module-wide field ids (`RecMk`/`RecS`/`RecL`);
//! - effect handlers use `Handle`/`Unwind`/`Resume` with handler tables.
//!
//! Register scheme: r0..r11 are a scratch/staging zone (call and effect
//! arguments, transient values); r12..r14 are spill scratch registers
//! (used round-robin by local_reg to avoid clobbering);
//! each MIR local gets the fixed register `LOCAL_BASE + local_id`.
//! A function whose locals exceed the register file spills excess
//! locals into the frame's spill vector via SpillLoad/SpillStore.
//!
//! Intra-actor reclamation: `compile_function` runs a conservative
//! liveness-based analysis (`plan_drops`) that emits `OpCode::Drop` when a
//! local provably holding the sole counted reference to a heap object dies —
//! overwritten by a new definition, dead after its last use, or dead at the
//! entry of a block its value flows into unused. The VM clears the register
//! on `Drop`, so duplicate drops are harmless no-ops.
use crate::bytecode::{
CodeModule, Constant, ForeignFunctionDef, HandlerBinding, HandlerTable, Instruction, OpCode,
};
use crate::mir;
use crate::types::{NuError, NuResult, PrimitiveType, Span, Type};
use std::collections::HashSet;
type FxHashMap<K, V> =
std::collections::HashMap<K, V, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
const FUNC_VALUE_REG: u8 = 254;
/// First general-purpose local register. r0..(LOCAL_BASE-1) is the call/effect staging zone,
/// r12..r14 are spill scratch registers, and rLOCAL_BASE..253 hold MIR locals that are not spilled.
pub const LOCAL_BASE: u32 = 15;
const MAX_STAGED_ARGS: usize = 12;
const SCRATCH0: u8 = 0;
const SCRATCH1: u8 = 1;
const SPILL_TEMP: u8 = 12;
const SPILL_TEMP2: u8 = 13;
#[allow(dead_code)]
const SPILL_TEMP3: u8 = 14;
fn not_yet_implemented(feature: &str, span: Span) -> NuError {
NuError::NotYetImplemented {
feature: feature.to_string(),
span,
}
}
fn compile_err(msg: impl Into<String>, span: Span) -> NuError {
NuError::VMError {
msg: msg.into(),
span,
}
}
#[derive(Debug, Clone, Copy)]
enum JumpKind {
Jmp,
JmpF,
}
#[derive(Debug, Clone)]
struct JumpPatch {
instr_idx: usize,
target_block: mir::BlockId,
kind: JumpKind,
}
pub struct MirCodegen {
module: CodeModule,
/// Module-wide record field ids, mirroring the stable compiler's layout.
field_map: FxHashMap<String, u8>,
next_field_id: u8,
/// Constant-pool index of each `self.field` name already emitted for
/// `StateGet`/`StateSet`, so repeated access to the same field reuses
/// one constant instead of growing the pool with a fresh duplicate
/// string every time (unlike record fields, `state` is string-keyed at
/// runtime, not a positional slot `field_id` could cover).
state_field_constants: FxHashMap<String, usize>,
/// Per-function float-ness of MIR locals (see `float_locals`), used to
/// pick float opcode variants for arithmetic and comparisons. Rebuilt
/// at the start of every `compile_function`.
float_locals: Vec<bool>,
/// Per-function spill map: local_id → spill slot in frame's spill vector.
/// Built at the start of compile_function. SpillLoad/SpillStore are
/// emitted inline during codegen via local_reg / local_dst / spill_write_done.
spill_map: FxHashMap<u32, u16>,
/// Round-robin counter for spilled-read temp register selection.
/// Cycles through SPILL_TEMP (12), SPILL_TEMP2 (13), SPILL_TEMP3 (14)
/// so that consecutive spilled reads don't clobber each other.
spill_read_cycle: u8,
}
impl MirCodegen {
pub fn new(module_name: impl Into<String>) -> Self {
MirCodegen {
module: CodeModule::new(module_name),
field_map: FxHashMap::default(),
next_field_id: 0,
state_field_constants: FxHashMap::default(),
float_locals: Vec::new(),
spill_map: FxHashMap::default(),
spill_read_cycle: 0,
}
}
/// Whether the given local of the function currently being compiled is
/// known to hold a Float at runtime.
fn is_float_local(&self, id: mir::LocalId) -> bool {
self.float_locals
.get(id.0 as usize)
.copied()
.unwrap_or(false)
}
// -- Inline register spilling -----------------------------------------
// Locals exceeding the register file are spilled into the frame's spill
// vector. These methods emit SpillLoad/SpillStore during codegen so no
// post-processing rewrite is needed — spilled locals never occupy a
// physical register, avoiding u8-wrapping ambiguity.
fn is_spilled(&self, id: mir::LocalId) -> bool {
self.spill_map.contains_key(&id.0)
}
/// Read a local: emits SpillLoad if spilled, returns the register.
/// Uses a round-robin temp register (r12/r13/r14) to avoid clobbering
/// when multiple spilled locals are read for the same instruction.
fn local_reg(&mut self, id: mir::LocalId) -> u8 {
if let Some(&slot) = self.spill_map.get(&id.0) {
let temp = SPILL_TEMP + (self.spill_read_cycle % 3);
self.spill_read_cycle = self.spill_read_cycle.wrapping_add(1);
self.emit(Instruction::new3(
OpCode::SpillLoad,
(slot >> 8) as u8,
(slot & 0xFF) as u8,
temp,
));
temp
} else {
(LOCAL_BASE + id.0) as u8
}
}
/// Destination register for a write. For spilled locals this is
/// SPILL_TEMP; the caller MUST call spill_write_done after emitting
/// the writing instruction.
fn local_dst(&self, id: mir::LocalId) -> u8 {
if self.spill_map.contains_key(&id.0) {
SPILL_TEMP
} else {
(LOCAL_BASE + id.0) as u8
}
}
/// Emit SpillStore to complete a write to a spilled local.
fn spill_write_done(&mut self, id: mir::LocalId) {
if let Some(&slot) = self.spill_map.get(&id.0) {
self.emit(Instruction::new3(
OpCode::SpillStore,
SPILL_TEMP,
(slot >> 8) as u8,
(slot & 0xFF) as u8,
));
}
}
/// For compound rvalues that write to dst then call local_reg: save dst
/// to r11 (safe from local_reg) to prevent clobbering. Returns the
/// register (r11 or dst) to use for subsequent construction operations.
fn protect_dst(&mut self, dst: u8) -> u8 {
// Only needed when dst is in the spill-temp zone (12-14) that
// local_reg may return. r11 is in the staging zone and is never
// returned by local_reg or load_constant during construction loops.
if dst == SPILL_TEMP || dst == SPILL_TEMP2 || dst == SPILL_TEMP3 {
const SAFE_DST: u8 = 11;
self.emit(Instruction::new2(OpCode::Move, dst, SAFE_DST));
SAFE_DST
} else {
dst
}
}
/// Restore dst from the safe register if protection was applied.
fn restore_dst(&mut self, dst: u8, safe: u8) {
if safe != dst {
self.emit(Instruction::new2(OpCode::Move, safe, dst));
}
}
/// Drop a spilled local: load → drop → store nil back.
fn spill_drop(&mut self, id: mir::LocalId) {
if let Some(&slot) = self.spill_map.get(&id.0) {
self.emit(Instruction::new3(
OpCode::SpillLoad,
(slot >> 8) as u8,
(slot & 0xFF) as u8,
SPILL_TEMP2,
));
self.emit(Instruction::new1(OpCode::Drop, SPILL_TEMP2));
self.emit(Instruction::new3(
OpCode::SpillStore,
SPILL_TEMP2,
(slot >> 8) as u8,
(slot & 0xFF) as u8,
));
}
}
/// Constant-pool index for a `self.field` name, reusing an existing
/// entry if this field was already referenced elsewhere in the module.
fn state_field_constant(&mut self, field: &str) -> usize {
if let Some(&idx) = self.state_field_constants.get(field) {
return idx;
}
let idx = self
.module
.add_constant(Constant::String(field.to_string()));
self.state_field_constants.insert(field.to_string(), idx);
idx
}
pub fn compile_module(&mut self, mir: &mir::Module) -> NuResult<&CodeModule> {
// Register foreign functions first so FFICall indices line up.
for ff in &mir.foreign_functions {
let params = ff
.params
.iter()
.map(crate::ffi::marshal::nulang_type_to_ffi_type)
.collect::<Option<Vec<_>>>()
.ok_or_else(|| {
compile_err(
format!(
"unsupported parameter type in extern function {}",
ff.symbol
),
Span::default(),
)
})?;
let ret = crate::ffi::marshal::nulang_type_to_ffi_type(&ff.ret).ok_or_else(|| {
compile_err(
format!("unsupported return type in extern function {}", ff.symbol),
Span::default(),
)
})?;
self.module.foreign_functions.push(ForeignFunctionDef {
library: ff.library.clone(),
symbol: ff.symbol.clone(),
params,
ret,
});
}
// Reserve one function-table slot per MIR function; MIR function
// indices are function-table indices.
self.module.function_table.resize(mir.functions.len(), 0);
let mut main_idx = None;
let mut user_main_idx = None;
for (idx, func) in mir.functions.iter().enumerate() {
let offset = self.compile_function(func)?;
self.module.function_table[idx] = offset;
if func.name == "__main" {
main_idx = Some(idx);
}
if func.name == "main" {
user_main_idx = Some(idx);
}
}
// If no synthetic __main wrapper exists but user declared fn main(),
// treat main as the entry point (matching the legacy compiler).
let effective_main = main_idx.or(user_main_idx);
// Actor behaviors compile through the exact same machinery as
// ordinary functions, but land in CodeModule.behaviors instead of
// function_table — Spawn/Send/Ask reference them by index there,
// and (unlike functions) they are never reachable via Call.
// mir_lower.rs computed ActorMeta.behavior_indices assuming
// behaviors compile in this order, so this loop must not be
// reordered or interleaved with function compilation.
for func in &mir.behaviors {
let offset = self.compile_function(func)?;
let end = self.module.instructions.len();
// Compute BLAKE3 content hash from the compiled bytecode slice +
// param types + return type.
let bytecode_slice = &self.module.instructions[offset..end];
let mut hasher = blake3::Hasher::new();
for instr in bytecode_slice {
hasher.update(&[instr.opcode as u8, instr.op1, instr.op2, instr.op3]);
}
let param_count_bytes = (func.params.len() as u32).to_be_bytes();
hasher.update(¶m_count_bytes);
// Hash return type if present
if let Some(ref ret_ty) = func.ret {
let ty_str = format!("{:?}", ret_ty);
hasher.update(ty_str.as_bytes());
}
let hash_bytes = *hasher.finalize().as_bytes();
self.module
.behaviors
.push(crate::bytecode::BehaviorTableEntry {
name: func.name.clone(),
param_count: func.params.len(),
code_offset: offset,
local_count: LOCAL_BASE as usize + func.locals.len(),
effect_mask: 0,
compensate_offset: None,
content_hash: Some(hash_bytes),
source_location: None,
parallel_branches: None,
});
}
// Saga compensation: patch each step's compensate_offset from its
// already-compiled compensation function's code offset. Both
// indices are into module.behaviors (see mir::Module::compensation_of).
for (behavior_idx, comp_idx) in &mir.compensation_of {
let comp_offset = self
.module
.behaviors
.get(*comp_idx)
.map(|b| b.code_offset)
.ok_or_else(|| {
compile_err(
"internal: compensation behavior index out of range",
Span::default(),
)
})?;
let entry = self
.module
.behaviors
.get_mut(*behavior_idx)
.ok_or_else(|| {
compile_err(
"internal: compensated behavior index out of range",
Span::default(),
)
})?;
entry.compensate_offset = Some(comp_offset);
}
// Parallel-branch metadata: copy branch names onto the matching
// synthesized step's BehaviorTableEntry (see mir::Module::parallel_branches_of).
for (behavior_idx, branches) in &mir.parallel_branches_of {
let entry = self
.module
.behaviors
.get_mut(*behavior_idx)
.ok_or_else(|| {
compile_err(
"internal: parallel-branch behavior index out of range",
Span::default(),
)
})?;
entry.parallel_branches = Some(branches.clone());
}
self.module.actor_metadata = mir.actor_metadata.clone();
// Collect tools from agent actors into module.tools so the runtime
// can resolve @tool-annotated functions for agent LLM requests.
for meta in &self.module.actor_metadata {
if meta.is_agent {
for tool in &meta.tools {
if !self.module.tools.iter().any(|t| t.name == tool.name) {
self.module.tools.push(tool.clone());
}
}
}
}
// Entry prologue: call the effective main function and halt.
if let Some(idx) = effective_main {
let entry = self.module.instructions.len();
self.load_constant(SCRATCH0, &Constant::Int(idx as i64));
self.emit(Instruction::new3(OpCode::Call, SCRATCH0, 0, 0));
self.emit(Instruction::new0(OpCode::Halt));
self.module.entry_point = Some(entry);
} else {
let entry = self.module.instructions.len();
self.emit(Instruction::new0(OpCode::Halt));
self.module.entry_point = Some(entry);
}
Ok(&self.module)
}
fn compile_function(&mut self, func: &mir::Function) -> NuResult<usize> {
// Isolate this function's bytecode so block offsets are relative to
// the function start while still allowing forward jump resolution.
let mut saved_instructions = Vec::new();
std::mem::swap(&mut saved_instructions, &mut self.module.instructions);
let function_start = saved_instructions.len();
// Build the spill map: locals whose id exceeds the register file
// get a slot in the frame's spill vector. Inline spilling via
// local_reg / local_dst / spill_write_done emits SpillLoad/SpillStore
// during codegen — no capacity limit, no wrapping ambiguity.
self.spill_map.clear();
let spilled_threshold = FUNC_VALUE_REG as u32 - LOCAL_BASE;
let mut next_spill_slot: u16 = 0;
for i in 0..func.locals.len() as u32 {
if i >= spilled_threshold {
self.spill_map.insert(i, next_spill_slot);
next_spill_slot += 1;
}
}
if func.params.len() > MAX_STAGED_ARGS {
// Mirrors stage_args's call-site limit: the prologue below reads
// incoming arguments from r0..r11 (the same staging zone callers
// stage into), so a param count above that would alias into
// LOCAL_BASE-mapped registers instead of erroring cleanly.
self.module.instructions = saved_instructions;
return Err(compile_err(format!(
"function '{}' has {} parameters, exceeding the MIR calling convention's limit of {}",
func.name,
func.params.len(),
MAX_STAGED_ARGS
), Span::default()));
}
// Type-directed opcode selection: the VM's integer handlers coerce
// float operands to 0, so float arithmetic/comparisons must be
// emitted as their F* variants.
self.float_locals = float_locals(func);
self.spill_read_cycle = 0;
// Prologue: move incoming arguments into their local registers.
for (i, param) in func.params.iter().enumerate() {
let dst = self.local_dst(*param);
let src = i as u8;
if src != dst {
self.emit(Instruction::new2(OpCode::Move, src, dst));
}
self.spill_write_done(*param);
}
for (i, cap) in func.captures.iter().enumerate() {
let dst = self.local_dst(*cap);
self.emit(Instruction::new3(OpCode::CapLoad, i as u8, dst, 0));
self.spill_write_done(*cap);
}
let mut block_offsets: FxHashMap<mir::BlockId, usize> = FxHashMap::default();
let mut patches: Vec<JumpPatch> = Vec::new();
// Handler-param moves to inject at the start of handler body blocks.
let mut handler_prologues: FxHashMap<mir::BlockId, Vec<mir::LocalId>> =
FxHashMap::default();
for table in &func.handler_tables {
for binding in &table.bindings {
if binding.params.len() > MAX_STAGED_ARGS {
// The VM delivers effect arguments in r0..r11; beyond
// that the prologue moves below would alias into
// LOCAL_BASE-mapped locals — the same corruption the
// function-parameter check above rejects.
self.module.instructions = saved_instructions;
return Err(compile_err(format!(
"handler for effect '{}' in function '{}' has {} parameters, exceeding the MIR staging limit of {}",
binding.effect_name,
func.name,
binding.params.len(),
MAX_STAGED_ARGS
), Span::default()));
}
handler_prologues.insert(binding.body, binding.params.clone());
}
}
// `Handle` instructions awaiting their table index (fn-relative idx).
let mut handle_patches: Vec<(usize, usize)> = Vec::new();
// Conservative liveness-based placement of `Drop` instructions (see
// the module docs and `plan_drops`).
let drop_plan = plan_drops(func);
for (bi, block) in func.blocks.iter().enumerate() {
block_offsets.insert(block.id, self.module.instructions.len());
if let Some(params) = handler_prologues.get(&block.id) {
// The VM delivers effect arguments in r0..rN.
for (i, p) in params.iter().enumerate() {
let dst = self.local_dst(*p);
if i as u8 != dst {
self.emit(Instruction::new2(OpCode::Move, i as u8, dst));
}
self.spill_write_done(*p);
}
}
if let Some(ids) = drop_plan.block_entry.get(&bi) {
for id in ids {
if self.is_spilled(*id) {
self.spill_drop(*id);
} else {
self.emit(Instruction::new1(OpCode::Drop, (LOCAL_BASE + id.0) as u8));
}
}
}
for (si, stmt) in block.stmts.iter().enumerate() {
if let Some(ids) = drop_plan.before_stmt.get(&(bi, si)) {
for id in ids {
if self.is_spilled(*id) {
self.spill_drop(*id);
} else {
self.emit(Instruction::new1(OpCode::Drop, (LOCAL_BASE + id.0) as u8));
}
}
}
self.compile_stmt(stmt, func, &mut handle_patches)?;
if let Some(ids) = drop_plan.after_stmt.get(&(bi, si)) {
for id in ids {
if self.is_spilled(*id) {
self.spill_drop(*id);
} else {
self.emit(Instruction::new1(OpCode::Drop, (LOCAL_BASE + id.0) as u8));
}
}
}
}
self.compile_terminator(&block.terminator, &func.name, &block_offsets, &mut patches)?;
}
// (SpillLoad/SpillStore are emitted inline during codegen via
// local_reg / local_dst / spill_write_done — no post-processing
// rewrite pass is needed.)
// Patch forward jumps now that all block offsets are known.
for patch in &patches {
let target_offset =
block_offsets
.get(&patch.target_block)
.copied()
.ok_or_else(|| {
compile_err("internal: jump to unknown MIR block", Span::default())
})?;
let diff = target_offset as i64 - patch.instr_idx as i64;
let instr = &mut self.module.instructions[patch.instr_idx];
match patch.kind {
JumpKind::Jmp => {
instr.op1 = ((diff as i16 >> 8) & 0xFF) as u8;
instr.op2 = (diff as i16 & 0xFF) as u8;
}
JumpKind::JmpF => {
instr.op2 = ((diff as i16 >> 8) & 0xFF) as u8;
instr.op3 = (diff as i16 & 0xFF) as u8;
}
}
}
// Build handler tables: offsets become module-absolute.
for (instr_idx, table_idx) in handle_patches {
let def = &func.handler_tables[table_idx];
let mut bindings = Vec::with_capacity(def.bindings.len());
for b in &def.bindings {
let rel = block_offsets.get(&b.body).copied().ok_or_else(|| {
compile_err("internal: handler body block missing", Span::default())
})?;
let result_reg = func
.blocks
.get(b.body.0 as usize)
.and_then(|blk| match blk.terminator {
mir::Terminator::Resume(id) => Some(self.local_reg(id)),
_ => None,
})
.unwrap_or(0);
bindings.push(HandlerBinding {
effect_name: b.effect_name.clone(),
handler_offset: function_start + rel,
arg_count: b.params.len() as u8,
result_reg,
single_shot: b.single_shot,
});
}
let global_idx = self.module.add_handler_table(HandlerTable {
bindings,
fallback_offset: None,
});
if global_idx > u8::MAX as usize {
return Err(compile_err(
"too many effect handler tables in module",
Span::default(),
));
}
self.module.instructions[instr_idx].op1 = global_idx as u8;
}
let mut function_code = Vec::new();
std::mem::swap(&mut function_code, &mut self.module.instructions);
self.module.instructions = saved_instructions;
self.module.instructions.extend(function_code);
Ok(function_start)
}
fn compile_stmt(
&mut self,
stmt: &mir::Stmt,
func: &mir::Function,
handle_patches: &mut Vec<(usize, usize)>,
) -> NuResult<()> {
match stmt {
mir::Stmt::Assign { dst, op } => {
let _spill_dst = self.local_dst(*dst);
self.compile_rvalue(_spill_dst, op)?;
self.spill_write_done(*dst);
}
mir::Stmt::StoreFieldNamed { obj, field, src } => {
let fid = self.field_id(field)?;
let _robj = self.local_reg(*obj);
let _rsrc = self.local_reg(*src);
self.emit(Instruction::new3(OpCode::RecS, _robj, fid, _rsrc));
}
mir::Stmt::ArrayStore { arr, idx, src } => {
let _rarr = self.local_reg(*arr);
let _ridx = self.local_reg(*idx);
let _rsrc = self.local_reg(*src);
self.emit(Instruction::new3(OpCode::ArrStore, _rarr, _ridx, _rsrc));
}
mir::Stmt::EnterHandle { table } => {
if *table >= func.handler_tables.len() {
return Err(compile_err(
"internal: EnterHandle references unknown table",
Span::default(),
));
}
let instr_idx = self.module.instructions.len();
self.emit(Instruction::new1(OpCode::Handle, 0));
handle_patches.push((instr_idx, *table));
}
mir::Stmt::PopHandler => {
self.emit(Instruction::new0(OpCode::Unwind));
}
mir::Stmt::StateSet { field, src } => {
let field_idx = self.state_field_constant(field);
let _rsrc = self.local_reg(*src);
self.emit(Instruction::new3(
OpCode::StateSet,
((field_idx >> 8) & 0xFF) as u8,
(field_idx & 0xFF) as u8,
_rsrc,
));
}
mir::Stmt::Emit { event, args } => {
self.stage_args(args)?;
let event_idx = self.module.add_constant(Constant::String(event.clone()));
self.emit(Instruction::new3(
OpCode::Emit,
((event_idx >> 8) & 0xFF) as u8,
(event_idx & 0xFF) as u8,
args.len() as u8,
));
}
}
Ok(())
}
/// Move argument locals into the staging registers r0..rN.
fn stage_args(&mut self, args: &[mir::LocalId]) -> NuResult<()> {
if args.len() > MAX_STAGED_ARGS {
return Err(compile_err(
format!(
"call/effect with {} arguments exceeds the MIR staging limit of {}",
args.len(),
MAX_STAGED_ARGS
),
Span::default(),
));
}
for (i, a) in args.iter().enumerate() {
let src = self.local_reg(*a);
if src != i as u8 {
self.emit(Instruction::new2(OpCode::Move, src, i as u8));
}
}
Ok(())
}
fn compile_rvalue(&mut self, dst: u8, rv: &mir::RValue) -> NuResult<()> {
match rv {
mir::RValue::Const(c) => {
self.load_constant(dst, c);
}
mir::RValue::Load(id) => {
let src = self.local_reg(*id);
if src != dst {
self.emit(Instruction::new2(OpCode::Move, src, dst));
}
}
mir::RValue::LoadFieldNamed { obj, field } => {
let fid = self.field_id(field)?;
let _robj = self.local_reg(*obj);
self.emit(Instruction::new3(OpCode::RecL, _robj, fid, dst));
}
mir::RValue::LoadFieldPos { obj, index } => {
let _robj = self.local_reg(*obj);
self.emit(Instruction::new3(OpCode::FieldL, _robj, *index, dst));
}
mir::RValue::ArrayLoad { arr, idx } => {
let _rarr = self.local_reg(*arr);
let _ridx = self.local_reg(*idx);
self.emit(Instruction::new3(OpCode::ArrLoad, _rarr, _ridx, dst));
}
mir::RValue::ArrayLen(arr) => {
let _rarr = self.local_reg(*arr);
self.emit(Instruction::new2(OpCode::ArrLen, _rarr, dst));
}
mir::RValue::ArrayLit(elems) => {
// Protect dst from local_reg clobbering: save to r11
// (r11 is in the staging zone never returned by local_reg).
self.load_constant(SCRATCH0, &Constant::Int(elems.len() as i64));
self.emit(Instruction::new2(OpCode::ArrAlloc, SCRATCH0, dst));
let safe = self.protect_dst(dst);
for (i, e) in elems.iter().enumerate() {
self.load_constant(SCRATCH1, &Constant::Int(i as i64));
let _re = self.local_reg(*e);
self.emit(Instruction::new3(OpCode::ArrStore, safe, SCRATCH1, _re));
}
self.restore_dst(dst, safe);
}
mir::RValue::Unary(op, id) => {
let src = self.local_reg(*id);
// `Deref`/`Ref` are register copies, same as the stable
// compiler's compile_unary: Nulang's ref cells are locals
// reassigned in place (see lower_place's Var arm), not a
// distinct heap allocation, so `&`/`*` are no-ops at the
// bytecode level — the type checker is what restricts
// reassignment to Ref-typed locals.
let opcode = match op {
crate::ast::UnOp::Neg => {
if self.is_float_local(*id) {
OpCode::FNeg
} else {
OpCode::INeg
}
}
crate::ast::UnOp::Not => OpCode::Not,
crate::ast::UnOp::Deref => OpCode::Load,
crate::ast::UnOp::Ref(_) => OpCode::Move,
};
if opcode == OpCode::FNeg {
// The interpreter reads the source from op1 and writes
// the destination to op3 for FNeg (unlike INeg's op2).
self.emit(Instruction::new3(OpCode::FNeg, src, 0, dst));
} else {
self.emit(Instruction::new2(opcode, src, dst));
}
}
mir::RValue::Binary(op, l, r) => {
let lr = self.local_reg(*l);
let rr = self.local_reg(*r);
// The type checker rejects mixed int/float arithmetic, so
// operands are homogeneous: one float operand means both
// are floats and the F* opcode variants are required (the
// integer handlers coerce float operands to 0).
let is_float = self.is_float_local(*l) || self.is_float_local(*r);
use crate::ast::BinOp;
match (op, is_float) {
(BinOp::Ne, f) => {
let eq = if f { OpCode::FCmpEq } else { OpCode::ICmpEq };
self.emit(Instruction::new3(eq, lr, rr, SCRATCH0));
self.emit(Instruction::new2(OpCode::Not, SCRATCH0, dst));
}
// Float Le/Ge have no dedicated opcodes: expand to the
// negated inverse comparison (a <= b == !(a > b)).
(BinOp::Le, true) => {
self.emit(Instruction::new3(OpCode::FCmpGt, lr, rr, SCRATCH0));
self.emit(Instruction::new2(OpCode::Not, SCRATCH0, dst));
}
(BinOp::Ge, true) => {
self.emit(Instruction::new3(OpCode::FCmpLt, lr, rr, SCRATCH0));
self.emit(Instruction::new2(OpCode::Not, SCRATCH0, dst));
}
_ => {
let opcode = binary_opcode(op, is_float)?;
self.emit(Instruction::new3(opcode, lr, rr, dst));
}
}
}
mir::RValue::StringEq(l, r) => {
let _rl = self.local_reg(*l);
let _rr = self.local_reg(*r);
self.emit(Instruction::new3(OpCode::SCmpEq, _rl, _rr, dst));
}
mir::RValue::StrConcat(l, r) => {
let _rl = self.local_reg(*l);
let _rr = self.local_reg(*r);
self.emit(Instruction::new3(OpCode::SConcat, _rl, _rr, dst));
}
mir::RValue::Call { func, args } => {
// Load the callee value first (it lives above the staging
// zone, so staging cannot clobber it).
match func {
mir::FuncRef::Index(idx) => {
self.load_constant(FUNC_VALUE_REG, &Constant::Int(*idx as i64));
}
mir::FuncRef::Local(id) => {
let _rid = self.local_reg(*id);
self.emit(Instruction::new2(OpCode::Move, _rid, FUNC_VALUE_REG));
}
}
self.stage_args(args)?;
self.emit(Instruction::new3(
OpCode::Call,
FUNC_VALUE_REG,
args.len() as u8,
dst,
));
}
mir::RValue::Closure { func, captures } => {
self.emit(Instruction::new3(
OpCode::Closure,
((*func >> 8) & 0xFF) as u8,
(*func & 0xFF) as u8,
dst,
));
let safe = self.protect_dst(dst);
for (i, cap) in captures.iter().enumerate() {
let _rcap = self.local_reg(*cap);
self.emit(Instruction::new3(OpCode::CapStore, safe, i as u8, _rcap));
}
self.restore_dst(dst, safe);
}
mir::RValue::Tuple(elems) => {
self.emit(Instruction::new2(OpCode::TupleMk, elems.len() as u8, dst));
let safe = self.protect_dst(dst);
for (i, e) in elems.iter().enumerate() {
let _re = self.local_reg(*e);
self.emit(Instruction::new3(OpCode::FieldS, safe, i as u8, _re));
}
self.restore_dst(dst, safe);
}
mir::RValue::Record(fields) => {
let mut max_field_id: u8 = 0;
let mut field_ids = Vec::with_capacity(fields.len());
for (name, _) in fields {
let fid = self.field_id(name)?;
max_field_id = max_field_id.max(fid);
field_ids.push(fid);
}
let slot_count = max_field_id.saturating_add(1);
self.emit(Instruction::new2(OpCode::RecMk, slot_count, dst));
let safe = self.protect_dst(dst);
for ((_, e), fid) in fields.iter().zip(field_ids) {
let _re = self.local_reg(*e);
self.emit(Instruction::new3(OpCode::RecS, safe, fid, _re));
}
self.restore_dst(dst, safe);
}
mir::RValue::RecordUpdate { base, overrides } => {
// Shallow copy the base record, then overwrite each override.
let _rbase = self.local_reg(*base);
self.emit(Instruction::new2(OpCode::RecCopy, _rbase, dst));
let safe = self.protect_dst(dst);
for (name, val_id) in overrides {
let fid = self.field_id(name)?;
let _rval = self.local_reg(*val_id);
self.emit(Instruction::new3(OpCode::RecS, safe, fid, _rval));
}
self.restore_dst(dst, safe);
}
mir::RValue::Perform {
effect,
op,
args,
resolved_handler,
} => {
self.stage_args(args)?;
if let Some(href) = resolved_handler {
// Statically-resolved handler — emit PerformDirect with
// table and binding indices, skipping the string lookup.
self.emit(Instruction::new3(
OpCode::PerformDirect,
href.table_index as u8,
href.binding_index as u8,
dst,
));
} else {
let eff_idx = self
.module
.add_constant(Constant::String(format!("{}.{}", effect, op)));
self.emit(Instruction::new3(
OpCode::Perform,
((eff_idx >> 8) & 0xFF) as u8,
(eff_idx & 0xFF) as u8,
dst,
));
}
}
mir::RValue::PerformAsync {
effect_op,
args,
resolved_handler: _,
} => {
self.stage_args(args)?;
let eff_idx = self
.module
.add_constant(Constant::String(effect_op.clone()));
self.emit(Instruction::new3(
OpCode::PerformAsync,
((eff_idx >> 8) & 0xFF) as u8,
(eff_idx & 0xFF) as u8,
dst,
));
}
mir::RValue::SignalWait { name } => {
let name_idx = self.module.add_constant(Constant::String(name.clone()));
self.emit(Instruction::new3(
OpCode::SignalWait,
((name_idx >> 8) & 0xFF) as u8,
(name_idx & 0xFF) as u8,
dst,
));
}
mir::RValue::Receive => {
// Pops the next mailbox message via ActorVmCallbacks::try_receive;
// writes its first payload value (or nil) to dst.
self.emit(Instruction::new1(OpCode::Receive, dst));
}
mir::RValue::ReceiveMatch {
behavior_ids,
max_params,
} => {
// Selective receive: the spec constant encodes the reserved
// payload-register count and the candidate arm behavior ids
// as "max_params:id1,id2,...". The VM writes the matched arm
// index (or the arm count when nothing matched) to dst and
// payload values into the registers following dst.
let ids = behavior_ids
.iter()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(",");
let spec = format!("{}:{}", max_params, ids);
let spec_idx = self.module.add_constant(Constant::String(spec));
self.emit(Instruction::new3(
OpCode::ReceiveMatch,
((spec_idx >> 8) & 0xFF) as u8,
(spec_idx & 0xFF) as u8,
dst,
));
}
mir::RValue::ReceiveWait {
behavior_ids,
max_params,
timeout,
} => {
// Timed selective receive (receive-after): same spec constant
// and dst contract as ReceiveMatch, plus the timeout in
// milliseconds staged into r0 (fixed-register staging, like
// the pipeline opcodes). See OpCode::ReceiveWait (0xA0) in
// bytecode.rs for the full VM-side contract.
let ids = behavior_ids
.iter()
.map(|id| id.to_string())
.collect::<Vec<_>>()
.join(",");
let spec = format!("{}:{}", max_params, ids);
let spec_idx = self.module.add_constant(Constant::String(spec));
let _rtimeout = self.local_reg(*timeout);
self.emit(Instruction::new2(OpCode::Move, _rtimeout, SCRATCH0));
self.emit(Instruction::new3(
OpCode::ReceiveWait,
((spec_idx >> 8) & 0xFF) as u8,
(spec_idx & 0xFF) as u8,
dst,
));
}
mir::RValue::ReceiveCommit => {
// Commit: removes the matched message from the skip-buffer.
self.emit(Instruction::new0(OpCode::ReceiveCommit));
}
mir::RValue::FFICall { idx, args } => {
self.stage_args(args)?;
self.emit(Instruction::new3(
OpCode::FFICall,
((*idx >> 8) & 0xFF) as u8,
(*idx & 0xFF) as u8,
dst,
));
}
mir::RValue::Migrate { actor, node } => {
let _ractor = self.local_reg(*actor);
let _rnode = self.local_reg(*node);
self.emit(Instruction::new3(OpCode::Migrate, _ractor, _rnode, dst));
}
mir::RValue::SelfRef => {
self.emit(Instruction::new1(OpCode::SelfOp, dst));
}
mir::RValue::CapabilityCheck { val } => {
let _ = val;
self.emit(Instruction::new1(OpCode::Const1, dst)); // true
}
mir::RValue::StateGet { field } => {
let field_idx = self.state_field_constant(field);
self.emit(Instruction::new3(
OpCode::StateGet,
((field_idx >> 8) & 0xFF) as u8,
(field_idx & 0xFF) as u8,
dst,
));
}
mir::RValue::Spawn { behavior_idx, init } => {