forked from nulang-org/nulang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmir_lower.rs
More file actions
3303 lines (3191 loc) · 130 KB
/
Copy pathmir_lower.rs
File metadata and controls
3303 lines (3191 loc) · 130 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
//! HIR -> MIR lowering.
//!
//! Converts the typed High-level IR into the 3-address-code Mid-level IR.
//!
//! Guarantees:
//! - Everything this pass emits compiles to *correct* bytecode; any
//! construct that cannot be lowered faithfully yet returns an honest
//! `NotYetImplemented` error instead of emitting placeholder code.
//! - Lexical scoping (with shadowing) is respected via a scope stack.
//! - Lambdas and recursive let-bindings are lifted to top-level MIR
//! functions; closures capture enclosing locals by value.
//! - `actor` declarations are supported: behaviors compile through the
//! same machinery as ordinary functions (see `lower_behavior_def`), with
//! `self` bound as a local and `spawn`/`send`/`ask`/`self.field` lowered
//! to their dedicated MIR constructs. `workflow` (including `parallel`
//! blocks and saga compensation) and `agent` (including `@tool`-backed
//! tools) desugar to actors at the HIR layer (see
//! `hir_lower::desugar_workflow`/`desugar_agent`) and are supported the
//! same way.
use crate::ast::Pattern;
use crate::hir;
use crate::mir;
use crate::types::{NuError, NuResult, Span, Type};
use std::collections::HashSet;
type FxHashMap<K, V> =
std::collections::HashMap<K, V, std::hash::BuildHasherDefault<rustc_hash::FxHasher>>;
fn compile_err(msg: impl Into<String>, span: Span) -> NuError {
NuError::VMError {
msg: msg.into(),
span,
}
}
pub fn lower_module(hir: &hir::Module) -> NuResult<mir::Module> {
let mut ctx = ModuleCtx::new(&hir.name);
// Pass 1: reserve function/behavior slots and build actor metadata up
// front, so forward references and mutual recursion between functions,
// and between actors' send/ask sites, all resolve regardless of source
// order. (The stable compiler only supports actors declared before use;
// this pass is strictly more permissive, which cannot make any
// currently-valid program disagree between the two backends.)
for decl in &hir.decls {
reserve_decl(&mut ctx, decl)?;
}
// Pass 2: lower function and behavior bodies into their reserved slots.
for decl in &hir.decls {
lower_decl_bodies(&mut ctx, decl)?;
}
let mut module = ctx.finish()?;
crate::mir_inline::inline_local_closures(&mut module);
Ok(module)
}
/// Nested modules are purely a namespacing construct: the stable compiler's
/// `compile_decl` flattens `Decl::Module { decls, .. }` by recursing over
/// `decls` in place, so this pass does the same instead of erroring.
fn reserve_decl(ctx: &mut ModuleCtx, decl: &hir::Decl) -> NuResult<()> {
match decl {
hir::Decl::CrdtDecl { name, .. } => {
// CRDT declaration - reserve a placeholder
let _ = ctx.reserve_function(name); // placeholder
}
hir::Decl::Function(f) => {
if ctx.func_map.contains_key(&f.name) {
return Err(compile_err(
format!(
"duplicate function '{}': a function with this name is already \
declared in this module (top-level and `module {{ .. }}` blocks \
share one flat namespace, so nested modules can't disambiguate \
same-named functions -- rename one of them)",
f.name
),
f.span,
));
}
let idx = ctx.reserve_function(&f.name);
ctx.func_map.insert(f.name.clone(), idx);
}
hir::Decl::ExternBlock { library, funcs, .. } => {
for f in funcs {
let idx = ctx.foreign.len();
ctx.foreign.push(mir::ForeignFunction {
library: library.clone(),
symbol: f.name.clone(),
params: f.params.iter().map(|(_, t)| t.clone()).collect(),
ret: f.ret.clone(),
});
ctx.extern_map.insert(f.name.clone(), idx);
}
}
hir::Decl::Actor(a) => {
let first_idx = ctx.behaviors.len();
for b in &a.behaviors {
ctx.reserve_behavior(format!("{}.{}", a.name, b.name));
}
let behavior_indices: Vec<usize> = (first_idx..ctx.behaviors.len()).collect();
// Compensation slots are reserved AFTER all of this actor's
// real behaviors, so they never fall inside behavior_indices
// (compensations are invoked directly by offset, never
// dispatched by name via send/ask).
for (b, &abs_idx) in a.behaviors.iter().zip(behavior_indices.iter()) {
if b.compensate.is_some() {
let comp_idx =
ctx.reserve_behavior(format!("{}.{}__compensate", a.name, b.name));
// The step's ABSOLUTE (whole-module) behavior index —
// not a per-actor relative index. The codegen resolves
// compensations against each actor's own
// `behavior_indices`; a relative index would let an
// actor declared before the workflow hijack its first
// compensation (SPEC2 §10 known-issue #2).
ctx.compensation_of.push((abs_idx, comp_idx));
}
if let Some(branches) = &b.parallel_branches {
ctx.parallel_branches_of.push((abs_idx, branches.clone()));
}
}
let state_models = a
.state_fields
.iter()
.map(|(name, model, _ty, _default)| (name.clone(), *model))
.collect();
let state_defaults = a
.state_fields
.iter()
.filter_map(|(name, _model, _ty, default)| match default {
hir::Operand::Literal(lit, _) => Some((name.clone(), literal_to_constant(lit))),
_ => None,
})
.collect();
ctx.actor_metas.push(crate::bytecode::ActorMeta {
name: a.name.clone(),
persistent: a.persistent,
state_models,
state_defaults,
behavior_indices,
is_workflow: a.is_workflow,
is_agent: a.is_agent,
is_organization: a.is_organization,
tools: a.tools.clone(),
semantic_memory_dimensions: a.semantic_memory_dimensions,
procedural_memory_namespace: a.procedural_memory_namespace.clone(),
backend: crate::ast::ActorBackendKind::Native,
fallback_config: a.fallback_config.clone(),
retry_config: a.retry_config.clone(),
type_hash: None,
version: a.version,
migrations: String::new(),
});
}
hir::Decl::Workflow { name, .. } => {
unreachable!(
"workflow '{}' should be desugared to an actor by HIR lowering (desugar_workflow)",
name
);
}
hir::Decl::Agent { name, .. } => {
unreachable!(
"agent '{}' should be desugared to an actor by HIR lowering (desugar_agent)",
name
);
}
hir::Decl::Module { decls, .. } => {
for d in decls {
reserve_decl(ctx, d)?;
}
}
hir::Decl::VariantType { variants, .. } => {
// Variant declarations produce no code, but construction sites
// need the constructor table: a payload constructor call
// `Some(x)` builds a `{ ctor, payload }` record and a nullary
// constructor reference `None` is the bare tag string (see
// pattern_test for the matching destructuring side). On a name
// collision between two variant declarations the later one
// wins, mirroring the typechecker's ctx.bind.
for (ctor_name, payload) in variants {
ctx.ctor_map.insert(ctor_name.clone(), payload.is_some());
}
}
hir::Decl::Constant { name, .. } => {
let idx = ctx.reserve_function(name);
ctx.func_map.insert(name.clone(), idx);
}
// Type-level declarations produce no code.
hir::Decl::TypeAlias { .. }
| hir::Decl::RecordType { .. }
| hir::Decl::EffectDecl { .. }
| hir::Decl::Import { .. }
| hir::Decl::Database { .. } => {}
}
Ok(())
}
fn lower_decl_bodies(ctx: &mut ModuleCtx, decl: &hir::Decl) -> NuResult<()> {
match decl {
hir::Decl::Function(f) => {
let idx = ctx.func_map[&f.name];
let func = lower_function_def(ctx, f)?;
ctx.fill_function(idx, func);
}
hir::Decl::Actor(a) => {
let indices = ctx
.actor_metas
.iter()
.find(|m| m.name == a.name)
.expect("actor registered in pass 1")
.behavior_indices
.clone();
for (b, &idx) in a.behaviors.iter().zip(indices.iter()) {
let full_name = format!("{}.{}", a.name, b.name);
let func = lower_behavior_def(ctx, &full_name, b)?;
ctx.fill_behavior(idx, func);
if let Some(comp_body) = &b.compensate {
let comp_idx = ctx
.compensation_of
.iter()
.find(|(behavior_idx, _)| *behavior_idx == idx)
.map(|(_, comp_idx)| *comp_idx)
.expect("compensation slot reserved in pass 1");
let comp_def = hir::BehaviorDef {
name: format!("{}__compensate", b.name),
params: Vec::new(),
ret: b.ret.clone(),
effect: b.effect.clone(),
cap: b.cap,
body: comp_body.clone(),
compensate: None,
parallel_branches: None,
span: b.span,
};
let comp_full_name = format!("{}.{}__compensate", a.name, b.name);
let comp_func = lower_behavior_def(ctx, &comp_full_name, &comp_def)?;
ctx.fill_behavior(comp_idx, comp_func);
}
}
}
hir::Decl::Module { decls, .. } => {
for d in decls {
lower_decl_bodies(ctx, d)?;
}
}
hir::Decl::Constant { name, body, .. } => {
let idx = ctx.func_map[name];
let mut lowerer = FnLowerer::new(ctx, name, None);
lowerer.lower_body_top(body)?;
let func = lowerer.b.build();
ctx.fill_function(idx, func);
}
_ => {}
}
Ok(())
}
// ---------------------------------------------------------------------------
// Module context
// ---------------------------------------------------------------------------
struct ModuleCtx {
name: String,
functions: Vec<Option<mir::Function>>,
func_map: FxHashMap<String, usize>,
extern_map: FxHashMap<String, usize>,
foreign: Vec<mir::ForeignFunction>,
/// Actor behaviors, reserved (with their fully-qualified "Actor.behavior"
/// name) in pass 1 and filled in pass 2 — mirrors `functions`, but never
/// registered in `func_map` so they stay un-`Call`-able.
behaviors: Vec<Option<mir::Function>>,
behavior_names: Vec<String>,
actor_metas: Vec<crate::bytecode::ActorMeta>,
/// `(step_behavior_idx, compensation_behavior_idx)` pairs; see `mir::Module`.
compensation_of: Vec<(usize, usize)>,
/// `(behavior_idx, branch_names)` pairs; see `mir::Module`.
parallel_branches_of: Vec<(usize, Vec<String>)>,
/// Declared variant constructors: ctor name -> has_payload. Populated in
/// pass 1 from `Decl::VariantType` so construction sites (`Some(41)`,
/// `None`) resolve regardless of source order; see `reserve_decl`.
ctor_map: FxHashMap<String, bool>,
next_lambda: u32,
}
impl ModuleCtx {
fn new(name: &str) -> Self {
ModuleCtx {
name: name.to_string(),
functions: Vec::new(),
func_map: FxHashMap::default(),
extern_map: FxHashMap::default(),
foreign: Vec::new(),
behaviors: Vec::new(),
behavior_names: Vec::new(),
actor_metas: Vec::new(),
compensation_of: Vec::new(),
parallel_branches_of: Vec::new(),
ctor_map: FxHashMap::default(),
next_lambda: 0,
}
}
fn reserve_function(&mut self, _name: &str) -> usize {
self.functions.push(None);
self.functions.len() - 1
}
fn fill_function(&mut self, idx: usize, func: mir::Function) {
self.functions[idx] = Some(func);
}
fn reserve_behavior(&mut self, full_name: String) -> usize {
self.behaviors.push(None);
self.behavior_names.push(full_name);
self.behaviors.len() - 1
}
fn fill_behavior(&mut self, idx: usize, func: mir::Function) {
self.behaviors[idx] = Some(func);
}
/// Resolve `spawn ActorName { ... }` to the behavior-table index the VM
/// uses to look up the actor's metadata (its first behavior's index).
/// Mirrors the stable compiler's `compile_spawn`.
fn spawn_behavior_idx(&self, actor_name: &str) -> usize {
self.actor_metas
.iter()
.find(|m| m.name == actor_name)
.and_then(|m| m.behavior_indices.first().copied())
.unwrap_or(self.behaviors.len())
}
/// Resolve `send`/`ask actor behavior(...)` to a behavior-table index by
/// name. Mirrors the stable compiler's `behavior_table_index`: an exact
/// "ActorName.behavior" match first, falling back to any behavior with a
/// matching suffix if the receiver expression isn't a bare actor-typed
/// variable name (a known ambiguity inherited from the stable compiler,
/// not introduced here).
fn send_behavior_idx(&self, actor_name_hint: &str, behavior: &str) -> usize {
let full_name = format!("{}.{}", actor_name_hint, behavior);
if let Some(idx) = self.behavior_names.iter().position(|n| *n == full_name) {
return idx;
}
let suffix = format!(".{}", behavior);
self.behavior_names
.iter()
.position(|n| n.ends_with(&suffix))
.unwrap_or(self.behaviors.len())
}
fn fresh_lambda_name(&mut self) -> String {
let n = self.next_lambda;
self.next_lambda += 1;
format!("__lambda_{}", n)
}
fn finish(self) -> NuResult<mir::Module> {
let mut module = mir::Module::new(&self.name);
for (i, f) in self.functions.into_iter().enumerate() {
let mut f = f.ok_or_else(|| {
compile_err(
format!("internal: MIR function slot {} left unfilled", i),
Span::default(),
)
})?;
fuse_single_use_temps(&mut f);
module.functions.push(f);
}
for (i, f) in self.behaviors.into_iter().enumerate() {
let mut f = f.ok_or_else(|| {
compile_err(
format!("internal: MIR behavior slot {} left unfilled", i),
Span::default(),
)
})?;
fuse_single_use_temps(&mut f);
module.behaviors.push(f);
}
module.actor_metadata = self.actor_metas;
module.compensation_of = self.compensation_of;
module.parallel_branches_of = self.parallel_branches_of;
module.foreign_functions = self.foreign;
Ok(module)
}
}
fn lower_function_def(ctx: &mut ModuleCtx, f: &hir::FunctionDef) -> NuResult<mir::Function> {
let mut lowerer = FnLowerer::new(ctx, &f.name, Some(f.ret.clone()));
for (name, ty) in &f.params {
let id = lowerer.b.add_param(name.clone(), ty.clone());
lowerer.bind(name, id);
}
lowerer.lower_body_top(&f.body)?;
Ok(lowerer.b.build())
}
/// Lower a lifted lambda/recursive-function body into a standalone MIR
/// function. `captures` are bound from closure capture slots (in order);
/// `rec` binds a name to the function's own index for recursive calls.
fn lower_lifted(
ctx: &mut ModuleCtx,
name: &str,
params: &[(String, Type)],
captures: &[String],
rec: Option<(&str, usize)>,
body: &hir::Body,
) -> NuResult<mir::Function> {
let mut lowerer = FnLowerer::new(ctx, name, None);
for (pname, ty) in params {
let id = lowerer.b.add_param(pname.clone(), ty.clone());
lowerer.bind(pname, id);
}
for cname in captures {
let id = lowerer.b.add_capture(cname.clone(), Type::unit());
lowerer.bind(cname, id);
}
if let Some((rec_name, rec_idx)) = rec {
// The function refers to itself by name. Without captures a raw
// function-table index suffices (callable like any function value);
// with captures the self-reference must be a closure carrying the
// same environment, otherwise recursive calls would lose the
// captured values (CapLoad would fail outside a closure call).
let id = lowerer.b.add_local(rec_name, Type::unit());
if captures.is_empty() {
lowerer.b.assign(
id,
mir::RValue::Const(crate::bytecode::Constant::Int(rec_idx as i64)),
);
} else {
let cap_ids: Vec<mir::LocalId> = captures
.iter()
.map(|n| lowerer.lookup(n).expect("capture just bound"))
.collect();
lowerer.b.assign(
id,
mir::RValue::Closure {
func: rec_idx,
captures: cap_ids,
},
);
}
lowerer.bind(rec_name, id);
}
lowerer.lower_body_top(body)?;
Ok(lowerer.b.build())
}
/// Lower an actor behavior body into a standalone MIR function. Identical to
/// an ordinary function except for the prologue statement binding `self` to
/// the current actor reference, mirroring the stable compiler's
/// `compile_behavior`.
fn lower_behavior_def(
ctx: &mut ModuleCtx,
full_name: &str,
bh: &hir::BehaviorDef,
) -> NuResult<mir::Function> {
let mut lowerer = FnLowerer::new(ctx, full_name, Some(bh.ret.clone()));
for (name, ty) in &bh.params {
let id = lowerer.b.add_param(name.clone(), ty.clone());
lowerer.bind(name, id);
}
let self_id = lowerer.b.add_local("self", Type::unit());
lowerer.b.assign(self_id, mir::RValue::SelfRef);
lowerer.bind("self", self_id);
lowerer.lower_body_top(&bh.body)?;
Ok(lowerer.b.build())
}
// ---------------------------------------------------------------------------
// Function lowering
// ---------------------------------------------------------------------------
struct FnLowerer<'c> {
ctx: &'c mut ModuleCtx,
b: mir::FunctionBuilder,
scopes: Vec<Vec<(String, mir::LocalId)>>,
loop_exits: Vec<mir::BlockId>,
loop_results: Vec<mir::LocalId>,
/// Number of `handle` bodies currently being lowered. Each one pushed a
/// handler frame at runtime, so an explicit `return` emitted while this
/// is > 0 must unwind that many frames first (the VM does not unwind
/// `handler_stack` on `Ret`).
handle_depth: usize,
/// Stack of active handler scopes. Each entry is `(table_index, [(binding_index, effect_qualified_name)])`.
/// Pushed when lowering a `handle` block (after `EnterHandle`) and
/// popped when the `handle`'s join block is reached. Used to resolve
/// `Perform` operations to a statically-known `HandlerRef`.
handler_scope: Vec<(usize, Vec<(usize, String)>)>,
}
impl<'c> FnLowerer<'c> {
fn new(ctx: &'c mut ModuleCtx, name: &str, ret: Option<Type>) -> Self {
FnLowerer {
ctx,
b: mir::FunctionBuilder::new(name, ret),
scopes: vec![Vec::new()],
loop_exits: Vec::new(),
loop_results: Vec::new(),
handle_depth: 0,
handler_scope: Vec::new(),
}
}
fn push_scope(&mut self) {
self.scopes.push(Vec::new());
}
fn pop_scope(&mut self) {
self.scopes.pop();
}
fn bind(&mut self, name: &str, id: mir::LocalId) {
self.scopes
.last_mut()
.expect("scope stack never empty")
.push((name.to_string(), id));
}
fn lookup(&self, name: &str) -> Option<mir::LocalId> {
for scope in self.scopes.iter().rev() {
for (n, id) in scope.iter().rev() {
if n == name {
return Some(*id);
}
}
}
None
}
// -- Body lowering ------------------------------------------------------
/// Terminate the current block with a function return, first unwinding
/// any handler frames installed by enclosing `handle` bodies (and by the
/// handler body itself, when the return sits inside one — the VM keeps
/// the frame on `handler_stack` while the handler runs). Without this
/// the frame would outlive the function on the VM's `handler_stack`,
/// and a later unhandled perform of the same effect would dispatch
/// into the dead function's handler code.
fn emit_return(&mut self, id: mir::LocalId) {
for _ in 0..self.handle_depth {
self.b.emit(mir::Stmt::PopHandler);
// Pop the corresponding handler scope entry so a `return`
// inside a handle block correctly unwinds the scope stack.
self.handler_scope.pop();
}
self.b.terminate(mir::Terminator::Return(Some(id)));
}
/// Lower a body in function-return position.
fn lower_body_top(&mut self, body: &hir::Body) -> NuResult<()> {
for stmt in &body.stmts {
self.lower_stmt(stmt)?;
}
if self.b.is_terminated() {
return Ok(());
}
match &body.terminator {
hir::Terminator::Yield(op) | hir::Terminator::FnReturn(Some(op)) => {
let id = self.lower_operand(op)?;
self.b.terminate(mir::Terminator::Return(Some(id)));
}
hir::Terminator::FnReturn(None) => {
let id = self.unit_temp();
self.b.terminate(mir::Terminator::Return(Some(id)));
}
hir::Terminator::Break(_) => {
return Err(compile_err("break outside of a loop", Span::default()));
}
}
Ok(())
}
/// Lower a body in expression position: its yielded value is assigned to
/// `dst` and control joins `join`. Explicit returns still return from the
/// function; breaks target the innermost loop.
fn lower_body_into(
&mut self,
body: &hir::Body,
dst: mir::LocalId,
join: mir::BlockId,
) -> NuResult<()> {
use crate::bytecode::Constant;
for stmt in &body.stmts {
self.lower_stmt(stmt)?;
}
if self.b.is_terminated() {
return Ok(());
}
match &body.terminator {
hir::Terminator::Yield(op) => {
let id = self.lower_operand(op)?;
self.b.assign(dst, mir::RValue::Load(id));
self.b.terminate(mir::Terminator::Jump(join));
}
hir::Terminator::FnReturn(op) => {
let id = match op {
Some(op) => self.lower_operand(op)?,
None => self.unit_temp(),
};
self.emit_return(id);
}
hir::Terminator::Break(op) => {
let exit = self
.loop_exits
.last()
.copied()
.ok_or_else(|| compile_err("break outside of a loop", Span::default()))?;
let result = self
.loop_results
.last()
.copied()
.ok_or_else(|| compile_err("break outside of a loop", Span::default()))?;
match op {
Some(op) => {
let val = self.lower_operand(op)?;
self.b.assign(result, mir::RValue::Load(val));
}
None => {
self.b.assign(result, mir::RValue::Const(Constant::Unit));
}
}
self.b.terminate(mir::Terminator::Jump(exit));
}
}
Ok(())
}
// -- Statements ----------------------------------------------------------
fn lower_stmt(&mut self, stmt: &hir::Stmt) -> NuResult<()> {
if self.b.is_terminated() {
// Unreachable code after return/break: skip.
return Ok(());
}
// Attach the HIR statement's source line to every MIR statement it
// emits (drives the debugger's PC<->line table).
let line = match stmt {
hir::Stmt::Let { span, .. }
| hir::Stmt::Assign { span, .. }
| hir::Stmt::StateSet { span, .. }
| hir::Stmt::Emit { span, .. } => span.line(),
} as u32;
if line != 0 {
self.b.set_line(line);
}
match stmt {
hir::Stmt::Let {
name, ty, value, ..
} => {
let dst = self.b.add_local(name.clone(), ty.clone());
self.lower_rvalue(dst, value)?;
self.bind(name, dst);
Ok(())
}
hir::Stmt::Assign { target, value, .. } => self.lower_assign(target, value),
hir::Stmt::StateSet { field, value, .. } => {
let src = self.lower_operand(value)?;
self.b.emit(mir::Stmt::StateSet {
field: field.clone(),
src,
});
Ok(())
}
hir::Stmt::Emit { event, args, .. } => {
let mut ids = Vec::with_capacity(args.len());
for a in args {
ids.push(self.lower_operand(a)?);
}
self.b.emit(mir::Stmt::Emit {
event: event.clone(),
args: ids,
});
Ok(())
}
}
}
fn lower_assign(&mut self, target: &hir::Place, value: &hir::RValue) -> NuResult<()> {
match target {
hir::Place::Var(name, _) => {
// "self" is bound as an ordinary local in behavior bodies
// (see lower_behavior_def), so reassigning it needs no
// special case — it just overwrites that local, same as the
// stable compiler.
let dst = self.lookup(name).ok_or_else(|| {
compile_err(
format!("assignment to undefined variable '{}'", name),
Span::default(),
)
})?;
self.lower_rvalue(dst, value)
}
hir::Place::Field { base, field, .. } if place_is_self(base) => {
let src = self.b.add_temp(Type::unit());
self.lower_rvalue(src, value)?;
self.b.emit(mir::Stmt::StateSet {
field: field.clone(),
src,
});
Ok(())
}
hir::Place::Field { base, field, .. } => {
let obj = self.read_place(base)?;
let src = self.b.add_temp(Type::unit());
self.lower_rvalue(src, value)?;
self.b.emit(mir::Stmt::StoreFieldNamed {
obj,
field: field.clone(),
src,
});
Ok(())
}
hir::Place::Index { base, idx, .. } => {
let arr = self.read_place(base)?;
let idx_id = self.lower_operand(idx)?;
let src = self.b.add_temp(Type::unit());
self.lower_rvalue(src, value)?;
self.b.emit(mir::Stmt::ArrayStore {
arr,
idx: idx_id,
src,
});
Ok(())
}
}
}
fn read_place(&mut self, place: &hir::Place) -> NuResult<mir::LocalId> {
match place {
hir::Place::Var(name, _) => self.lookup(name).ok_or_else(|| {
compile_err(format!("undefined variable '{}'", name), Span::default())
}),
hir::Place::Field { base, field, .. } => {
let obj = self.read_place(base)?;
let dst = self.b.add_temp(Type::unit());
self.b.assign(
dst,
mir::RValue::LoadFieldNamed {
obj,
field: field.clone(),
},
);
Ok(dst)
}
hir::Place::Index { base, idx, .. } => {
let arr = self.read_place(base)?;
let idx_id = self.lower_operand(idx)?;
let dst = self.b.add_temp(Type::unit());
self.b
.assign(dst, mir::RValue::ArrayLoad { arr, idx: idx_id });
Ok(dst)
}
}
}
// -- Operands ------------------------------------------------------------
fn lower_operand(&mut self, op: &hir::Operand) -> NuResult<mir::LocalId> {
match op {
hir::Operand::Var(name, _) => {
if let Some(id) = self.lookup(name) {
return Ok(id);
}
if let Some(&idx) = self.ctx.func_map.get(name) {
// Reference to a top-level function used as a value.
let id = self.b.add_temp(Type::unit());
self.b.assign(
id,
mir::RValue::Const(crate::bytecode::Constant::Int(idx as i64)),
);
return Ok(id);
}
if name == "self" {
let id = self.b.add_temp(Type::unit());
self.b.assign(id, mir::RValue::SelfRef);
return Ok(id);
}
if let Some(&has_payload) = self.ctx.ctor_map.get(name) {
// Declared variant constructor used as a value. Locals
// and top-level functions shadow constructors (resolved
// above), so a user `let Some = ...` or `fn Some(...)`
// always wins over the ctor.
return self.lower_ctor_value(name, has_payload);
}
Err(compile_err(
format!("undefined variable '{}' in MIR lowering", name),
Span::default(),
))
}
hir::Operand::Literal(lit, ty) => {
let id = self.b.add_temp(ty.clone());
self.b
.assign(id, mir::RValue::Const(literal_to_constant(lit)));
Ok(id)
}
hir::Operand::Unit => Ok(self.unit_temp()),
}
}
fn unit_temp(&mut self) -> mir::LocalId {
let id = self.b.add_temp(Type::unit());
self.b
.assign(id, mir::RValue::Const(crate::bytecode::Constant::Unit));
id
}
/// Lower a declared variant constructor *call* `Some(x)` to the record
/// `{ ctor: "Some", payload: x }` — the representation pattern_test and
/// bind_pattern destructure (`ctor` rather than `tag` because `tag` is a
/// lexer keyword). Field names resolve to module-wide field ids in
/// codegen, so both sides agree on the layout automatically.
fn lower_ctor_call(
&mut self,
dst: mir::LocalId,
name: &str,
has_payload: bool,
args: Vec<mir::LocalId>,
) -> NuResult<()> {
if !has_payload {
return Err(compile_err(
format!(
"constructor '{}' takes no payload; use it as a plain value, not a call",
name
),
Span::default(),
));
}
let payload = if args.len() == 1 {
args[0]
} else {
// Pack multiple args into a tuple to match the typechecker's
// convention: a constructor with payload (T, U) expects two
// separate arguments at the call site, not a single tuple.
let tup = self.b.add_temp(Type::unit());
self.b.assign(tup, mir::RValue::Tuple(args.to_vec()));
tup
};
let tag = self.b.add_temp(Type::string());
self.b.assign(
tag,
mir::RValue::Const(crate::bytecode::Constant::String(name.to_string())),
);
self.b.assign(
dst,
mir::RValue::Record(vec![
("ctor".to_string(), tag),
("payload".to_string(), payload),
]),
);
Ok(())
}
/// Lower a declared variant constructor used as a *value* (not a call).
/// A nullary constructor is the bare tag string — the payload-less
/// variant pattern test string-compares the whole scrutinee against the
/// tag, so the value must be exactly that representation. A payload
/// constructor eta-expands to a lifted `fn(x) { { ctor, payload: x } }`
/// so `let f = Some in f(1)` works like any other function value.
fn lower_ctor_value(&mut self, name: &str, has_payload: bool) -> NuResult<mir::LocalId> {
if !has_payload {
let id = self.b.add_temp(Type::string());
self.b.assign(
id,
mir::RValue::Const(crate::bytecode::Constant::String(name.to_string())),
);
return Ok(id);
}
let lname = self.ctx.fresh_lambda_name();
let idx = self.ctx.reserve_function(&lname);
let mut body = hir::Body::new();
body.stmts.push(hir::Stmt::Let {
name: "__ctor".to_string(),
ty: Type::unit(),
value: hir::RValue::Record(
vec![
(
"ctor".to_string(),
hir::Operand::Literal(
crate::ast::Literal::String(name.to_string()),
Type::string(),
),
),
(
"payload".to_string(),
hir::Operand::Var("__payload".to_string(), Type::unit()),
),
],
Type::unit(),
),
span: Span::default(),
});
body.terminator =
hir::Terminator::Yield(hir::Operand::Var("__ctor".to_string(), Type::unit()));
let lifted = lower_lifted(
self.ctx,
&lname,
&[("__payload".to_string(), Type::unit())],
&[],
None,
&body,
)?;
self.ctx.fill_function(idx, lifted);
// No captures: the function-table index is the value (callable like
// any top-level function reference — see lower_lifted).
let id = self.b.add_temp(Type::unit());
self.b.assign(
id,
mir::RValue::Const(crate::bytecode::Constant::Int(idx as i64)),
);
Ok(id)
}
// -- RValues (dst-directed) -----------------------------------------------
fn lower_rvalue(&mut self, dst: mir::LocalId, rv: &hir::RValue) -> NuResult<()> {
use crate::bytecode::Constant;
match rv {
hir::RValue::Use(op) => {
let id = self.lower_operand(op)?;
self.b.assign(dst, mir::RValue::Load(id));
Ok(())
}
hir::RValue::Literal(lit, _) => {
self.b
.assign(dst, mir::RValue::Const(literal_to_constant(lit)));
Ok(())
}
hir::RValue::Binary(op, l, r, _) => {
let lid = self.lower_operand(l)?;
let rid = self.lower_operand(r)?;
// String equality/inequality must use SCmpEq (content
// comparison), not ICmpEq (raw-bit comparison), because
// a string value may be a constant-pool id or a heap
// pointer depending on how it was constructed.
// HIR Operand::Var always carries Type::unit(), so we must
// also consult the MIR local types (which are populated from
// Stmt::Let type annotations) to detect string-typed variables.
let l_mir_ty = self.b.local_ty(lid);
let r_mir_ty = self.b.local_ty(rid);
let is_string = l.ty() == Type::string()
|| r.ty() == Type::string()
|| *l_mir_ty == Type::string()
|| *r_mir_ty == Type::string();
match (op, is_string) {
(crate::ast::BinOp::Eq, true) => {
self.b.assign(dst, mir::RValue::StringEq(lid, rid));
}
(crate::ast::BinOp::Ne, true) => {
let eq_dst = self.b.add_temp(Type::bool());
self.b.assign(eq_dst, mir::RValue::StringEq(lid, rid));
self.b
.assign(dst, mir::RValue::Unary(crate::ast::UnOp::Not, eq_dst));
}
(crate::ast::BinOp::Add, true) => {
self.b.assign(dst, mir::RValue::StrConcat(lid, rid));
// A concatenation result is always a String. The dst
// local may have been created with a placeholder type
// (hir_lower's `binary_type` cannot see through a
// variable operand that lowers to Type::unit()), so
// record the precise type here — otherwise a chained
// `s + 2 + 3` lowers the second add as `Binary(Add)`
// instead of `StrConcat`, and the native/AOT backends
// mis-tag the pointer as an int.
self.b.set_local_ty(dst, Type::string());
}
_ => {
self.b.assign(dst, mir::RValue::Binary(*op, lid, rid));
// The dst local was created by `hir_lower::binary_type`,
// which cannot see through variable operands (HIR vars
// carry `Type::unit()`). Consult the MIR operand locals
// (which hold the real types) so a float arithmetic
// result is typed Float — otherwise downstream unary
// ops (e.g. `-(x + y)` for float x,y) mis-compile the
// float bits as an int.
let lt = self.b.local_ty(lid);
let rt = self.b.local_ty(rid);
if *lt == Type::float() || *rt == Type::float() {
self.b.set_local_ty(dst, Type::float());
}
}
}
Ok(())
}
hir::RValue::Unary(op, e, _) => {
let id = self.lower_operand(e)?;
self.b.assign(dst, mir::RValue::Unary(*op, id));
Ok(())
}
hir::RValue::Call { func, args, .. } => {
let mut aids = Vec::with_capacity(args.len());
for a in args {
aids.push(self.lower_operand(a)?);
}
let func_ref = match func {
hir::Operand::Var(name, _) => {
if let Some(id) = self.lookup(name) {
mir::FuncRef::Local(id)
} else if let Some(&idx) = self.ctx.func_map.get(name) {