aver-lang 0.14.2

VM and transpiler for Aver, a statically-typed language designed for AI-assisted development
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
mod calls;
mod classify;
mod expr;
mod patterns;

use std::collections::HashMap;

use crate::ast::{FnBody, FnDef, Stmt, TopLevel, TypeDef};
use crate::nan_value::{Arena, NanValue};
use crate::types::{option, result};
use crate::visibility;

use super::builtin::VmBuiltin;
use super::opcode::*;
use super::symbol::{VmSymbolTable, VmVariantCtor};
use super::types::{CodeStore, FnChunk};

/// Compile a parsed + TCO-transformed + resolved program into bytecode.
/// Also loads dependent modules if a `module` declaration with `depends` is present.
pub fn compile_program(
    items: &[TopLevel],
    arena: &mut Arena,
) -> Result<(CodeStore, Vec<NanValue>), CompileError> {
    compile_program_with_modules(items, arena, None, "")
}

/// Compile with explicit module root for `depends` resolution.
pub fn compile_program_with_modules(
    items: &[TopLevel],
    arena: &mut Arena,
    module_root: Option<&str>,
    source_file: &str,
) -> Result<(CodeStore, Vec<NanValue>), CompileError> {
    compile_program_inner(items, arena, source_file, ModuleSource::Disk(module_root))
}

/// Compile using dependency modules that were already parsed off-disk
/// (or out of a virtual filesystem). The browser playground uses this
/// to run multi-file programs without any real fs access.
pub fn compile_program_with_loaded_modules(
    items: &[TopLevel],
    arena: &mut Arena,
    loaded: Vec<crate::source::LoadedModule>,
    source_file: &str,
) -> Result<(CodeStore, Vec<NanValue>), CompileError> {
    compile_program_inner(items, arena, source_file, ModuleSource::Loaded(loaded))
}

enum ModuleSource<'a> {
    Disk(Option<&'a str>),
    Loaded(Vec<crate::source::LoadedModule>),
}

fn compile_program_inner(
    items: &[TopLevel],
    arena: &mut Arena,
    source_file: &str,
    module_source: ModuleSource<'_>,
) -> Result<(CodeStore, Vec<NanValue>), CompileError> {
    let mut compiler = ProgramCompiler::new();
    compiler.source_file = source_file.to_string();
    compiler.sync_record_field_symbols(arena);
    // Oracle v1: `BranchPath.Root` is a nullary value constructor
    // (like `Option.None`). The VM symbol table needs it as a
    // constant pointing at a pre-allocated arena record; this
    // happens here because bootstrap_core_symbols runs before the
    // arena is available.
    compiler.install_branch_path_root_constant(arena);

    match module_source {
        ModuleSource::Disk(Some(module_root)) => {
            compiler.load_modules(items, module_root, arena)?;
        }
        ModuleSource::Disk(None) => {}
        ModuleSource::Loaded(loaded) => {
            for m in loaded {
                compiler.integrate_module(&m.dep_name, m.items, arena)?;
            }
        }
    }

    for item in items {
        if let TopLevel::Stmt(Stmt::Binding(name, _, _)) = item {
            compiler.ensure_global(name);
        }
    }

    for item in items {
        match item {
            TopLevel::FnDef(fndef) => {
                compiler.ensure_global(&fndef.name);
                let effect_ids: Vec<u32> = fndef
                    .effects
                    .iter()
                    .map(|effect| compiler.symbols.intern_name(&effect.node))
                    .collect();
                let fn_id = compiler.code.add_function(FnChunk {
                    name: fndef.name.clone(),
                    arity: fndef.params.len() as u8,
                    local_count: 0,
                    code: Vec::new(),
                    constants: Vec::new(),
                    effects: effect_ids,
                    thin: false,
                    parent_thin: false,
                    leaf: false,
                    no_alloc: false,
                    source_file: String::new(),
                    line_table: Vec::new(),
                });
                let symbol_id = compiler.symbols.intern_function(
                    &fndef.name,
                    fn_id,
                    &fndef
                        .effects
                        .iter()
                        .map(|e| e.node.clone())
                        .collect::<Vec<_>>(),
                );
                let global_idx = compiler.global_names[&fndef.name];
                compiler.globals[global_idx as usize] = VmSymbolTable::symbol_ref(symbol_id);
            }
            TopLevel::TypeDef(td) => {
                // Current module: register in Arena (no qualified alias needed)
                match td {
                    TypeDef::Product { name, fields, .. } => {
                        let field_names: Vec<String> =
                            fields.iter().map(|(n, _)| n.clone()).collect();
                        arena.register_record_type(name, field_names);
                    }
                    TypeDef::Sum { name, variants, .. } => {
                        let variant_names: Vec<String> =
                            variants.iter().map(|v| v.name.clone()).collect();
                        arena.register_sum_type(name, variant_names);
                    }
                }
                // VM-specific: register type symbols
                compiler.register_type_in_symbols(td, arena);
            }
            _ => {}
        }
    }

    compiler.register_current_module_namespace(items);

    for item in items {
        if let TopLevel::FnDef(fndef) = item {
            let fn_id = compiler.code.find(&fndef.name).unwrap();
            let chunk = compiler.compile_fn(fndef, arena)?;
            compiler.code.functions[fn_id as usize] = chunk;
        }
    }

    compiler.compile_top_level(items, arena)?;
    compiler.code.symbols = compiler.symbols.clone();
    classify::classify_thin_functions(&mut compiler.code, arena)?;

    // Lowering-level no-alloc analysis (shared `ir::compute_alloc_info`).
    // Annotates each chunk so the dispatch loop can skip the runtime
    // length-compare guard inside `finalize_frame_locals_for_tail_call`
    // when the target body is provably alloc-free. The WASM backend uses
    // the same pass to skip boundary framing entirely; here the VM's
    // `TAIL_CALL_KNOWN` site shortcuts a few ops per iteration.
    let user_fn_defs: Vec<&crate::ast::FnDef> = items
        .iter()
        .filter_map(|item| {
            if let TopLevel::FnDef(fd) = item {
                Some(fd)
            } else {
                None
            }
        })
        .collect();
    if !user_fn_defs.is_empty() {
        let policy = super::VmAllocPolicy;
        let alloc_info = crate::ir::compute_alloc_info(&user_fn_defs, &policy);
        for fd in &user_fn_defs {
            let allocates = *alloc_info.get(&fd.name).unwrap_or(&true);
            if !allocates && let Some(fn_id) = compiler.code.find(&fd.name) {
                let chunk = &mut compiler.code.functions[fn_id as usize];
                chunk.no_alloc = true;
                // No-alloc bodies always satisfy `can_fast_return`'s
                // runtime length-equality guards, so promote them into
                // the thin fast-return class. The bytecode classifier
                // rejected them for unrelated reasons (mutual TCO call,
                // body size > MAX_PARENT_THIN, etc.) but for return
                // purposes there's nothing left to do.
                chunk.thin = true;
            }
        }
    }

    Ok((compiler.code, compiler.globals))
}

#[derive(Debug)]
pub struct CompileError {
    pub msg: String,
}

impl std::fmt::Display for CompileError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "Compile error: {}", self.msg)
    }
}

struct ProgramCompiler {
    code: CodeStore,
    symbols: VmSymbolTable,
    globals: Vec<NanValue>,
    global_names: HashMap<String, u16>,
    /// Source file path for the main program (propagated to FnChunks).
    source_file: String,
}

impl ProgramCompiler {
    fn new() -> Self {
        let mut compiler = ProgramCompiler {
            code: CodeStore::new(),
            symbols: VmSymbolTable::default(),
            globals: Vec::new(),
            global_names: HashMap::new(),
            source_file: String::new(),
        };
        compiler.bootstrap_core_symbols();
        compiler
    }

    fn sync_record_field_symbols(&mut self, arena: &Arena) {
        for type_id in 0..arena.type_count() {
            let type_name = arena.get_type_name(type_id);
            self.symbols.intern_namespace_path(type_name);
            let field_names = arena.get_field_names(type_id);
            if field_names.is_empty() {
                continue;
            }
            let field_symbol_ids: Vec<u32> = field_names
                .iter()
                .map(|field_name| self.symbols.intern_name(field_name))
                .collect();
            self.code.register_record_fields(type_id, &field_symbol_ids);
        }
    }

    /// Load all modules from `depends [...]` declarations using the shared loader,
    /// then compile each module's functions and register symbols.
    fn load_modules(
        &mut self,
        items: &[TopLevel],
        module_root: &str,
        arena: &mut Arena,
    ) -> Result<(), CompileError> {
        let module = items.iter().find_map(|i| {
            if let TopLevel::Module(m) = i {
                Some(m)
            } else {
                None
            }
        });
        let module = match module {
            Some(m) => m,
            None => return Ok(()),
        };

        let modules = crate::source::load_module_tree(&module.depends, module_root)
            .map_err(|e| CompileError { msg: e })?;

        for loaded in modules {
            self.integrate_module(&loaded.dep_name, loaded.items, arena)?;
        }
        Ok(())
    }

    /// Integrate a loaded module into the VM: register types, compile functions,
    /// expose symbols.
    fn integrate_module(
        &mut self,
        dep_name: &str,
        mut mod_items: Vec<TopLevel>,
        arena: &mut Arena,
    ) -> Result<(), CompileError> {
        crate::tco::transform_program(&mut mod_items);
        crate::resolver::resolve_program(&mut mod_items);

        // Register types in Arena with qualified aliases.
        for mt in visibility::collect_module_types(&mod_items) {
            let type_id = match &mt.kind {
                visibility::ModuleTypeKind::Record { field_names } => {
                    arena.register_record_type(&mt.bare_name, field_names.clone())
                }
                visibility::ModuleTypeKind::Sum { variant_names } => {
                    arena.register_sum_type(&mt.bare_name, variant_names.clone())
                }
            };
            arena.register_type_alias(
                &visibility::qualified_name(dep_name, &mt.bare_name),
                type_id,
            );
        }
        for item in &mod_items {
            if let TopLevel::TypeDef(td) = item {
                self.register_type_in_symbols(td, arena);
            }
        }

        // Compile ALL functions (not just exposed).
        let mut module_fn_ids: Vec<(String, u32)> = Vec::new();
        for item in &mod_items {
            if let TopLevel::FnDef(fndef) = item {
                let qualified_name = visibility::qualified_name(dep_name, &fndef.name);
                let effect_ids: Vec<u32> = fndef
                    .effects
                    .iter()
                    .map(|effect| self.symbols.intern_name(&effect.node))
                    .collect();
                let fn_id = self.code.add_function(FnChunk {
                    name: qualified_name.clone(),
                    arity: fndef.params.len() as u8,
                    local_count: 0,
                    code: Vec::new(),
                    constants: Vec::new(),
                    effects: effect_ids,
                    thin: false,
                    parent_thin: false,
                    leaf: false,
                    no_alloc: false,
                    source_file: String::new(),
                    line_table: Vec::new(),
                });
                self.symbols.intern_function(
                    &qualified_name,
                    fn_id,
                    &fndef
                        .effects
                        .iter()
                        .map(|e| e.node.clone())
                        .collect::<Vec<_>>(),
                );
                module_fn_ids.push((fndef.name.clone(), fn_id));
            }
        }

        let module_scope: HashMap<String, u32> = module_fn_ids.iter().cloned().collect();
        let mut fn_idx = 0;
        for item in &mod_items {
            if let TopLevel::FnDef(fndef) = item {
                let (fn_name, fn_id) = &module_fn_ids[fn_idx];
                let mut chunk = self.compile_fn_with_scope(fndef, arena, &module_scope)?;
                chunk.name = visibility::qualified_name(dep_name, fn_name);
                self.code.functions[*fn_id as usize] = chunk;
                fn_idx += 1;
            }
        }

        // Expose exported functions and types via globals and namespace members.
        let exports = visibility::collect_module_exports(&mod_items);

        for fd in &exports.functions {
            let qualified = visibility::qualified_name(dep_name, &fd.name);
            let global_idx = self.ensure_global(&qualified);
            let symbol_id = self.symbols.find(&qualified).ok_or_else(|| CompileError {
                msg: format!("missing VM symbol for exposed function {}", qualified),
            })?;
            self.globals[global_idx as usize] = VmSymbolTable::symbol_ref(symbol_id);
        }

        let module_symbol_id = self.symbols.intern_namespace_path(dep_name);
        for et in &exports.types {
            let type_name = match et.def {
                TypeDef::Sum { name, .. } | TypeDef::Product { name, .. } => name,
            };
            if let Some(type_symbol_id) = self.symbols.find(type_name) {
                let member_symbol_id = self.symbols.intern_name(type_name);
                self.symbols.add_namespace_member_by_id(
                    module_symbol_id,
                    member_symbol_id,
                    VmSymbolTable::symbol_ref(type_symbol_id),
                );
            }
        }
        for fd in &exports.functions {
            let qualified = visibility::qualified_name(dep_name, &fd.name);
            if let Some(fn_symbol_id) = self.symbols.find(&qualified) {
                let member_symbol_id = self.symbols.intern_name(&fd.name);
                self.symbols.add_namespace_member_by_id(
                    module_symbol_id,
                    member_symbol_id,
                    VmSymbolTable::symbol_ref(fn_symbol_id),
                );
            }
        }

        Ok(())
    }

    /// Oracle v1: install `BranchPath.Root` as a nullary constant
    /// member of the `BranchPath` namespace. The record is allocated
    /// once in the arena; the symbol table holds a NanValue
    /// referencing it. Follows the same pattern as `Option.None`
    /// which is installed as an immediate constant in
    /// `bootstrap_core_symbols`.
    fn install_branch_path_root_constant(&mut self, arena: &mut Arena) {
        // Guard: micro-benchmarks and unit tests often build a VM
        // without calling `register_service_types` first. When the
        // BranchPath arena type is absent, there's nothing Oracle-
        // related in the program and skipping the install is safe.
        let Some(type_id) = arena.find_type_id(crate::types::branch_path::TYPE_NAME) else {
            return;
        };
        let dewey = crate::nan_value::NanValue::new_string_value("", arena);
        let record_idx = arena.push_record(type_id, vec![dewey]);
        let root_value = crate::nan_value::NanValue::new_record(record_idx);
        self.symbols.intern_constant("BranchPath.Root", root_value);
        let namespace_symbol_id = self.symbols.intern_namespace_path("BranchPath");
        let member_symbol_id = self.symbols.intern_name("Root");
        self.symbols
            .add_namespace_member_by_id(namespace_symbol_id, member_symbol_id, root_value);
    }

    fn ensure_global(&mut self, name: &str) -> u16 {
        if let Some(&idx) = self.global_names.get(name) {
            return idx;
        }
        let idx = self.globals.len() as u16;
        self.global_names.insert(name.to_string(), idx);
        self.globals.push(NanValue::UNIT);
        idx
    }

    /// Register type symbols in VmSymbolTable for namespace resolution.
    /// Arena registration is handled separately via shared `collect_module_types`.
    fn register_type_in_symbols(&mut self, td: &TypeDef, arena: &Arena) {
        match td {
            TypeDef::Product { name, fields, .. } => {
                self.symbols.intern_namespace_path(name);
                let type_id = arena
                    .find_type_id(name)
                    .expect("type already registered in Arena");
                let field_symbol_ids: Vec<u32> = fields
                    .iter()
                    .map(|(field_name, _)| self.symbols.intern_name(field_name))
                    .collect();
                self.code.register_record_fields(type_id, &field_symbol_ids);
            }
            TypeDef::Sum { name, variants, .. } => {
                let type_symbol_id = self.symbols.intern_namespace_path(name);
                let type_id = arena
                    .find_type_id(name)
                    .expect("type already registered in Arena");
                for (variant_id, variant) in variants.iter().enumerate() {
                    let ctor_id = arena
                        .find_ctor_id(type_id, variant_id as u16)
                        .expect("ctor id");
                    let qualified_name = visibility::member_key(name, &variant.name);
                    let ctor_symbol_id = self.symbols.intern_variant_ctor(
                        &qualified_name,
                        VmVariantCtor {
                            type_id,
                            variant_id: variant_id as u16,
                            ctor_id,
                            field_count: variant.fields.len() as u8,
                        },
                    );
                    let member_symbol_id = self.symbols.intern_name(&variant.name);
                    self.symbols.add_namespace_member_by_id(
                        type_symbol_id,
                        member_symbol_id,
                        VmSymbolTable::symbol_ref(ctor_symbol_id),
                    );
                }
            }
        }
    }

    fn bootstrap_core_symbols(&mut self) {
        for builtin in VmBuiltin::ALL.iter().copied() {
            let builtin_symbol_id = self.symbols.intern_builtin(builtin);
            if let Some((namespace, member)) = builtin.name().split_once('.') {
                let namespace_symbol_id = self.symbols.intern_namespace_path(namespace);
                let member_symbol_id = self.symbols.intern_name(member);
                self.symbols.add_namespace_member_by_id(
                    namespace_symbol_id,
                    member_symbol_id,
                    VmSymbolTable::symbol_ref(builtin_symbol_id),
                );
            }
        }

        let result_symbol_id = self.symbols.intern_namespace_path("Result");
        let ok_symbol_id = self.symbols.intern_wrapper("Result.Ok", 0);
        let err_symbol_id = self.symbols.intern_wrapper("Result.Err", 1);
        let ok_member_symbol_id = self.symbols.intern_name("Ok");
        self.symbols.add_namespace_member_by_id(
            result_symbol_id,
            ok_member_symbol_id,
            VmSymbolTable::symbol_ref(ok_symbol_id),
        );
        let err_member_symbol_id = self.symbols.intern_name("Err");
        self.symbols.add_namespace_member_by_id(
            result_symbol_id,
            err_member_symbol_id,
            VmSymbolTable::symbol_ref(err_symbol_id),
        );
        for (member, builtin_name) in result::extra_members() {
            if let Some(symbol_id) = self.symbols.find(&builtin_name) {
                let member_symbol_id = self.symbols.intern_name(member);
                self.symbols.add_namespace_member_by_id(
                    result_symbol_id,
                    member_symbol_id,
                    VmSymbolTable::symbol_ref(symbol_id),
                );
            }
        }

        let option_symbol_id = self.symbols.intern_namespace_path("Option");
        let some_symbol_id = self.symbols.intern_wrapper("Option.Some", 2);
        self.symbols.intern_constant("Option.None", NanValue::NONE);
        let some_member_symbol_id = self.symbols.intern_name("Some");
        self.symbols.add_namespace_member_by_id(
            option_symbol_id,
            some_member_symbol_id,
            VmSymbolTable::symbol_ref(some_symbol_id),
        );
        let none_member_symbol_id = self.symbols.intern_name("None");
        self.symbols.add_namespace_member_by_id(
            option_symbol_id,
            none_member_symbol_id,
            NanValue::NONE,
        );
        for (member, builtin_name) in option::extra_members() {
            if let Some(symbol_id) = self.symbols.find(&builtin_name) {
                let member_symbol_id = self.symbols.intern_name(member);
                self.symbols.add_namespace_member_by_id(
                    option_symbol_id,
                    member_symbol_id,
                    VmSymbolTable::symbol_ref(symbol_id),
                );
            }
        }
    }

    fn compile_fn(&mut self, fndef: &FnDef, arena: &mut Arena) -> Result<FnChunk, CompileError> {
        let empty_scope = HashMap::new();
        self.compile_fn_with_scope(fndef, arena, &empty_scope)
    }

    fn compile_fn_with_scope(
        &mut self,
        fndef: &FnDef,
        arena: &mut Arena,
        module_scope: &HashMap<String, u32>,
    ) -> Result<FnChunk, CompileError> {
        let resolution = fndef.resolution.as_ref();
        let local_count = resolution.map_or(fndef.params.len() as u16, |r| r.local_count);
        let local_slots: HashMap<String, u16> = resolution
            .map(|r| r.local_slots.as_ref().clone())
            .unwrap_or_else(|| {
                fndef
                    .params
                    .iter()
                    .enumerate()
                    .map(|(i, (name, _))| (name.clone(), i as u16))
                    .collect()
            });

        let mut fc = FnCompiler::new(
            &fndef.name,
            fndef.params.len() as u8,
            local_count,
            fndef
                .effects
                .iter()
                .map(|effect| self.symbols.intern_name(&effect.node))
                .collect(),
            local_slots,
            &self.global_names,
            module_scope,
            &self.code,
            &mut self.symbols,
            arena,
        );
        fc.source_file = self.source_file.clone();
        fc.note_line(fndef.line);

        match fndef.body.as_ref() {
            FnBody::Block(stmts) => fc.compile_body(stmts)?,
        }

        Ok(fc.finish())
    }

    fn compile_top_level(
        &mut self,
        items: &[TopLevel],
        arena: &mut Arena,
    ) -> Result<(), CompileError> {
        let has_stmts = items.iter().any(|i| matches!(i, TopLevel::Stmt(_)));
        if !has_stmts {
            return Ok(());
        }

        for item in items {
            if let TopLevel::Stmt(Stmt::Binding(name, _, _)) = item {
                self.ensure_global(name);
            }
        }

        let empty_mod_scope = HashMap::new();
        let mut fc = FnCompiler::new(
            "__top_level__",
            0,
            0,
            Vec::new(),
            HashMap::new(),
            &self.global_names,
            &empty_mod_scope,
            &self.code,
            &mut self.symbols,
            arena,
        );

        for item in items {
            if let TopLevel::Stmt(stmt) = item {
                match stmt {
                    Stmt::Binding(name, _type_ann, expr) => {
                        fc.compile_expr(expr)?;
                        let idx = self.global_names[name.as_str()];
                        fc.emit_op(STORE_GLOBAL);
                        fc.emit_u16(idx);
                    }
                    Stmt::Expr(expr) => {
                        fc.compile_expr(expr)?;
                        fc.emit_op(POP);
                    }
                }
            }
        }

        fc.emit_op(LOAD_UNIT);
        fc.emit_op(RETURN);

        let chunk = fc.finish();
        self.code.add_function(chunk);
        Ok(())
    }

    fn register_current_module_namespace(&mut self, items: &[TopLevel]) {
        let Some(module) = items.iter().find_map(|item| {
            if let TopLevel::Module(module) = item {
                Some(module)
            } else {
                None
            }
        }) else {
            return;
        };

        let module_symbol_id = self.symbols.intern_namespace_path(&module.name);
        let exposes_ref = if module.exposes.is_empty() {
            None
        } else {
            Some(module.exposes.as_slice())
        };

        for item in items {
            match item {
                TopLevel::FnDef(fndef) => {
                    if visibility::is_exposed(&fndef.name, exposes_ref)
                        && let Some(symbol_id) = self.symbols.find(&fndef.name)
                    {
                        let member_symbol_id = self.symbols.intern_name(&fndef.name);
                        self.symbols.add_namespace_member_by_id(
                            module_symbol_id,
                            member_symbol_id,
                            VmSymbolTable::symbol_ref(symbol_id),
                        );
                    }
                }
                TopLevel::TypeDef(TypeDef::Product { name, .. } | TypeDef::Sum { name, .. }) => {
                    if visibility::is_exposed(name, exposes_ref)
                        && let Some(symbol_id) = self.symbols.find(name)
                    {
                        let member_symbol_id = self.symbols.intern_name(name);
                        self.symbols.add_namespace_member_by_id(
                            module_symbol_id,
                            member_symbol_id,
                            VmSymbolTable::symbol_ref(symbol_id),
                        );
                    }
                }
                _ => {}
            }
        }
    }
}

/// What a function expression resolves to at compile time.
enum CallTarget {
    /// Known function id (local or qualified module function).
    KnownFn(u32),
    /// Result.Ok / Result.Err / Option.Some → WRAP opcode. kind: 0=Ok, 1=Err, 2=Some.
    Wrapper(u8),
    /// Option.None → load constant.
    None_,
    /// User-defined variant constructor: Shape.Circle → VARIANT_NEW (or inline nullary at runtime).
    Variant(u32, u16),
    /// Known VM builtin/service resolved by name and interned into the VM symbol table.
    Builtin(VmBuiltin),
    /// Unknown capitalized dotted path that did not resolve to a function, variant, or builtin.
    UnknownQualified(String),
}

struct FnCompiler<'a> {
    name: String,
    arity: u8,
    local_count: u16,
    effects: Vec<u32>,
    local_slots: HashMap<String, u16>,
    global_names: &'a HashMap<String, u16>,
    /// Module-local function scope: simple_name → fn_id.
    /// Used for intra-module calls (e.g. `placeStairs` inside map.av).
    module_scope: &'a HashMap<String, u32>,
    code_store: &'a CodeStore,
    symbols: &'a mut VmSymbolTable,
    arena: &'a mut Arena,
    code: Vec<u8>,
    constants: Vec<NanValue>,
    /// Byte offset of the last emitted opcode (for superinstruction fusion).
    last_op_pos: usize,
    /// Source file path for this function.
    source_file: String,
    /// Run-length encoded line table being built: (bytecode_offset, source_line).
    line_table: Vec<(u16, u16)>,
    /// Last emitted line (for RLE dedup).
    last_noted_line: u16,
}

impl<'a> FnCompiler<'a> {
    #[allow(clippy::too_many_arguments)]
    fn new(
        name: &str,
        arity: u8,
        local_count: u16,
        effects: Vec<u32>,
        local_slots: HashMap<String, u16>,
        global_names: &'a HashMap<String, u16>,
        module_scope: &'a HashMap<String, u32>,
        code_store: &'a CodeStore,
        symbols: &'a mut VmSymbolTable,
        arena: &'a mut Arena,
    ) -> Self {
        FnCompiler {
            name: name.to_string(),
            arity,
            local_count,
            effects,
            local_slots,
            global_names,
            module_scope,
            code_store,
            symbols,
            arena,
            code: Vec::new(),
            constants: Vec::new(),
            last_op_pos: usize::MAX,
            source_file: String::new(),
            line_table: Vec::new(),
            last_noted_line: 0,
        }
    }

    fn finish(self) -> FnChunk {
        FnChunk {
            name: self.name,
            arity: self.arity,
            local_count: self.local_count,
            code: self.code,
            constants: self.constants,
            effects: self.effects,
            thin: false,
            parent_thin: false,
            leaf: false,
            no_alloc: false,
            source_file: self.source_file,
            line_table: self.line_table,
        }
    }

    /// Record that bytecode emitted from this point forward corresponds to
    /// the given source line. RLE-deduplicated: consecutive calls with the
    /// same line produce only one entry.
    fn note_line(&mut self, line: usize) {
        if line == 0 {
            return;
        }
        let line16 = line as u16;
        if line16 == self.last_noted_line {
            return; // RLE dedup
        }
        self.last_noted_line = line16;
        self.line_table.push((self.code.len() as u16, line16));
    }

    fn emit_op(&mut self, op: u8) {
        let prev_pos = self.last_op_pos;
        let prev_op = if prev_pos < self.code.len() {
            self.code[prev_pos]
        } else {
            0xFF
        };

        // LOAD_LOCAL + LOAD_LOCAL → LOAD_LOCAL_2
        if op == LOAD_LOCAL && prev_op == LOAD_LOCAL && prev_pos + 2 == self.code.len() {
            self.code[prev_pos] = LOAD_LOCAL_2;
            // slot_a already at prev_pos+1, slot_b emitted next via emit_u8
            return;
        }
        // LOAD_LOCAL + LOAD_CONST → LOAD_LOCAL_CONST
        if op == LOAD_CONST && prev_op == LOAD_LOCAL && prev_pos + 2 == self.code.len() {
            self.code[prev_pos] = LOAD_LOCAL_CONST;
            // slot at prev_pos+1, const_idx (u16) emitted next via emit_u16
            return;
        }
        // VECTOR_GET + LOAD_CONST(hi,lo) + UNWRAP_OR → VECTOR_GET_OR(hi,lo)
        // Before: [..., VECTOR_GET, LOAD_CONST, hi, lo] + about to emit UNWRAP_OR
        // After:  [..., VECTOR_GET_OR, hi, lo]
        if op == UNWRAP_OR && self.code.len() >= 4 {
            let len = self.code.len();
            if self.code[len - 4] == VECTOR_GET && self.code[len - 3] == LOAD_CONST {
                let hi = self.code[len - 2];
                let lo = self.code[len - 1];
                self.code[len - 4] = VECTOR_GET_OR;
                self.code[len - 3] = hi;
                self.code[len - 2] = lo;
                self.code.pop(); // remove extra byte
                self.last_op_pos = len - 4;
                return;
            }
        }
        self.last_op_pos = self.code.len();
        self.code.push(op);
    }

    fn emit_u8(&mut self, val: u8) {
        self.code.push(val);
    }

    fn emit_u16(&mut self, val: u16) {
        self.code.push((val >> 8) as u8);
        self.code.push((val & 0xFF) as u8);
    }

    fn emit_i16(&mut self, val: i16) {
        self.emit_u16(val as u16);
    }

    fn emit_u32(&mut self, val: u32) {
        self.code.push((val >> 24) as u8);
        self.code.push(((val >> 16) & 0xFF) as u8);
        self.code.push(((val >> 8) & 0xFF) as u8);
        self.code.push((val & 0xFF) as u8);
    }

    fn emit_u64(&mut self, val: u64) {
        self.code.extend_from_slice(&val.to_be_bytes());
    }

    fn add_constant(&mut self, val: NanValue) -> u16 {
        for (i, c) in self.constants.iter().enumerate() {
            if c.bits() == val.bits() {
                return i as u16;
            }
        }
        let idx = self.constants.len() as u16;
        self.constants.push(val);
        idx
    }

    fn offset(&self) -> usize {
        self.code.len()
    }

    fn emit_jump(&mut self, op: u8) -> usize {
        self.emit_op(op);
        let patch_pos = self.code.len();
        self.emit_i16(0);
        patch_pos
    }

    fn patch_jump(&mut self, patch_pos: usize) {
        let target = self.code.len();
        let offset = (target as isize - patch_pos as isize - 2) as i16;
        let bytes = (offset as u16).to_be_bytes();
        self.code[patch_pos] = bytes[0];
        self.code[patch_pos + 1] = bytes[1];
    }

    fn patch_jump_to(&mut self, patch_pos: usize, target: usize) {
        let offset = (target as isize - patch_pos as isize - 2) as i16;
        let bytes = (offset as u16).to_be_bytes();
        self.code[patch_pos] = bytes[0];
        self.code[patch_pos + 1] = bytes[1];
    }

    fn bind_top_to_local(&mut self, name: &str) {
        if let Some(&slot) = self.local_slots.get(name) {
            self.emit_op(STORE_LOCAL);
            self.emit_u8(slot as u8);
        } else {
            self.emit_op(POP);
        }
    }

    fn dup_and_bind_top_to_local(&mut self, name: &str) {
        self.emit_op(DUP);
        self.bind_top_to_local(name);
    }
}

#[cfg(test)]
mod tests {
    use super::compile_program;
    use crate::nan_value::Arena;
    use crate::source::parse_source;
    use crate::vm::opcode::{LT, NOT, VECTOR_GET_OR, VECTOR_SET_OR_KEEP};

    #[test]
    fn vector_get_with_literal_default_lowers_to_vector_get_or() {
        let source = r#"
module Demo

fn cellAt(grid: Vector<Int>, idx: Int) -> Int
    Option.withDefault(Vector.get(grid, idx), 0)
"#;

        let mut items = parse_source(source).expect("source should parse");
        crate::tco::transform_program(&mut items);
        crate::resolver::resolve_program(&mut items);

        let mut arena = Arena::new();
        let (code, _globals) = compile_program(&items, &mut arena).expect("vm compile should pass");
        let fn_id = code.find("cellAt").expect("cellAt should exist");
        let chunk = code.get(fn_id);

        assert!(
            chunk.code.contains(&VECTOR_GET_OR),
            "expected VECTOR_GET_OR in bytecode, got {:?}",
            chunk.code
        );
    }

    #[test]
    fn vector_set_with_same_default_lowers_to_vector_set_or_keep() {
        let source = r#"
module Demo

fn updateOrKeep(vec: Vector<Int>, idx: Int, value: Int) -> Vector<Int>
    Option.withDefault(Vector.set(vec, idx, value), vec)
"#;

        let mut items = parse_source(source).expect("source should parse");
        crate::tco::transform_program(&mut items);
        crate::resolver::resolve_program(&mut items);

        let mut arena = Arena::new();
        let (code, _globals) = compile_program(&items, &mut arena).expect("vm compile should pass");
        let fn_id = code
            .find("updateOrKeep")
            .expect("updateOrKeep should exist");
        let chunk = code.get(fn_id);

        assert!(
            chunk.code.contains(&VECTOR_SET_OR_KEEP),
            "expected VECTOR_SET_OR_KEEP in bytecode, got {:?}",
            chunk.code
        );
    }

    #[test]
    fn bool_match_on_gte_uses_base_compare_without_not() {
        let source = r#"
module Demo

fn bucket(n: Int) -> Int
    match n >= 10
        true -> 7
        false -> 3
"#;

        let mut items = parse_source(source).expect("source should parse");
        crate::tco::transform_program(&mut items);
        crate::resolver::resolve_program(&mut items);

        let mut arena = Arena::new();
        let (code, _globals) = compile_program(&items, &mut arena).expect("vm compile should pass");
        let fn_id = code.find("bucket").expect("bucket should exist");
        let chunk = code.get(fn_id);

        assert!(
            chunk.code.contains(&LT),
            "expected LT in bytecode, got {:?}",
            chunk.code
        );
        assert!(
            !chunk.code.contains(&NOT),
            "did not expect NOT in normalized bool-match bytecode, got {:?}",
            chunk.code
        );
    }

    #[test]
    fn self_host_runtime_http_server_aliases_compile_in_vm() {
        let source = r#"
module Demo

fn listen(handler: Int) -> Unit
    SelfHostRuntime.httpServerListen(8080, handler)

fn listenWith(context: Int, handler: Int) -> Unit
    SelfHostRuntime.httpServerListenWith(8081, context, handler)
"#;

        let mut items = parse_source(source).expect("source should parse");
        crate::tco::transform_program(&mut items);
        crate::resolver::resolve_program(&mut items);

        let mut arena = Arena::new();
        let (code, _globals) = compile_program(&items, &mut arena).expect("vm compile should pass");
        assert!(code.find("listen").is_some(), "listen should compile");
        assert!(
            code.find("listenWith").is_some(),
            "listenWith should compile"
        );
    }
}