submilli-engine 0.3.0

Compiles Submilli programs, a TypeScript subset, to WebAssembly and runs them under capability policy
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
//! Box / unbox helpers — the unified mechanism for moving values
//! between language types and the universal `(ref $Object)` slot
//! type used by arrays, `unknown`, and erased generics.

use wasm_encoder::{BlockType, HeapType, Ieee64, Instruction, RefType, ValType};

use crate::Type;
use crate::codegen::CodegenCtx;
use crate::codegen::classes::VTABLE_PARENT_SLOT;
use crate::codegen::function_emitter::{FunctionEmitter, ReturnTarget};
use crate::codegen::symbol_table::is_nullable_ref;
use crate::typechecker::infer::narrowing::{TruthinessClass, truthiness_class};

/// Emit the nominal class-membership test for the value on top of the stack
/// (any `(ref null $Object)`-compatible ref), leaving an i32 (0/1): walk the
/// value's vtable parent chain, comparing each link by `ref.eq` against the
/// target class's vtable-singleton global. Value identity, not `ref.test` —
/// same-shape sibling classes canonicalize to one WasmGC type, so shape can't
/// carry `instanceof`. Non-class values (strings, boxed primitives, structural
/// objects, closures) exit false at the `$ClassVTable` test — their vtables are
/// plain `$VTable` subtypes.
pub fn emit_nominal_instance_test(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    target_vtable_global_idx: u32,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    let intr = ctx.symbols.intrinsic_type_indices().ok_or_else(|| {
        crate::codegen::internal_failure("intrinsic types declared before body emission")
    })?;
    let ref_null_to = |idx: u32| {
        ValType::Ref(RefType {
            nullable: true,
            heap_type: HeapType::Concrete(idx),
        })
    };
    let obj_local = emitter.add_anonymous_local(ref_null_to(intr.object))?;
    let raw_vt_local = emitter.add_anonymous_local(ref_null_to(intr.vtable))?;
    let vt_local = emitter.add_anonymous_local(ref_null_to(intr.class_vtable))?;

    emitter.instruction(Instruction::LocalSet(obj_local));
    emitter.emit_block(BlockType::Result(ValType::I32)); // $out
    emitter.emit_block(BlockType::Empty); // $false
    emitter.instruction(Instruction::LocalGet(obj_local));
    emitter.instruction(Instruction::BrOnNull(0));
    emitter.instruction(Instruction::StructGet {
        struct_type_index: intr.object,
        field_index: 0,
    });
    emitter.instruction(Instruction::LocalTee(raw_vt_local));
    emitter.instruction(Instruction::RefTestNonNull(HeapType::Concrete(
        intr.class_vtable,
    )));
    emitter.instruction(Instruction::I32Eqz);
    emitter.instruction(Instruction::BrIf(0));
    emitter.instruction(Instruction::LocalGet(raw_vt_local));
    emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(
        intr.class_vtable,
    )));
    emitter.instruction(Instruction::LocalSet(vt_local));
    emitter.emit_loop(BlockType::Empty); // $walk
    emitter.instruction(Instruction::LocalGet(vt_local));
    emitter.instruction(Instruction::GlobalGet(target_vtable_global_idx));
    emitter.instruction(Instruction::RefEq);
    emitter.emit_if(BlockType::Empty);
    emitter.instruction(Instruction::I32Const(1));
    emitter.instruction(Instruction::Br(3)); // -> $out
    emitter.emit_end();
    emitter.instruction(Instruction::LocalGet(vt_local));
    emitter.instruction(Instruction::StructGet {
        struct_type_index: intr.class_vtable,
        field_index: VTABLE_PARENT_SLOT,
    });
    emitter.instruction(Instruction::BrOnNull(1)); // chain root -> $false
    emitter.instruction(Instruction::LocalSet(vt_local));
    emitter.instruction(Instruction::Br(0)); // continue $walk
    emitter.emit_end(); // end $walk
    emitter.emit_end(); // end $false
    emitter.instruction(Instruction::I32Const(0));
    emitter.emit_end(); // end $out

    Ok(())
}

/// Emit Wasm instructions that wrap the value currently on top of
/// the stack (of language type `ty`) into a `(ref $Object)`.
pub fn emit_box(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    ty: &Type,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    let ty = ty.peel();
    match ty {
        Type::Number | Type::NumberLiteral(_) => {
            let boxed_idx = ctx
                .symbols
                .boxed_number_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("boxed_number type registered"))?;
            let vtable_global = ctx
                .symbols
                .prelude_global_idx("boxed_number_vtable")
                .ok_or_else(|| crate::codegen::internal_failure("boxed_number_vtable imported"))?;
            // Stack: [n_f64]. Need [vtable_ref, n_f64] for struct.new.
            // Stash via scratch local.
            let scratch = emitter.add_anonymous_local(wasm_encoder::ValType::F64)?;
            emitter.instruction(Instruction::LocalSet(scratch));
            emitter.instruction(Instruction::GlobalGet(vtable_global));
            emitter.instruction(Instruction::LocalGet(scratch));
            emitter.instruction(Instruction::StructNew(boxed_idx));
        }
        Type::Boolean | Type::BooleanLiteral(_) => {
            let boxed_idx = ctx
                .symbols
                .boxed_boolean_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("boxed_boolean type registered"))?;
            let vtable_global = ctx
                .symbols
                .prelude_global_idx("boxed_boolean_vtable")
                .ok_or_else(|| crate::codegen::internal_failure("boxed_boolean_vtable imported"))?;
            let scratch = emitter.add_anonymous_local(wasm_encoder::ValType::I32)?;
            emitter.instruction(Instruction::LocalSet(scratch));
            emitter.instruction(Instruction::GlobalGet(vtable_global));
            emitter.instruction(Instruction::LocalGet(scratch));
            emitter.instruction(Instruction::StructNew(boxed_idx));
        }
        Type::String
        | Type::StringLiteral(_)
        | Type::BigInt
        | Type::BigIntLiteral(_)
        | Type::Object { .. }
        | Type::Array(_)
        | Type::Tuple(_)
        | Type::Uint8Array
        | Type::Function { .. } => {
            // Already an $Object subtype — upcast is implicit.
        }
        Type::TypeVar(_) | Type::GenericParam { .. } | Type::Unknown | Type::Never => {
            // Never: the call always throws before producing a value, but
            // the wasm sig still has the slot — lowered same as Unknown.
        }
        Type::Null => {
            // null lowers to (ref null none) — the bottom of the WasmGC ref
            // hierarchy — a subtype of every nullable ref; no instruction needed.
        }
        Type::Undefined => {
            let idx = ctx
                .symbols
                .intrinsic_type_indices()
                .ok_or_else(|| {
                    crate::codegen::internal_failure("undefined intrinsic not registered")
                })?
                .undefined;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::Void => {}
        Type::Error => {
            return Err(crate::codegen::internal_failure(
                "invalid type representation during cast lowering",
            ));
        }
        Type::NumberEnum { .. } | Type::StringEnum { .. } => {}
        Type::Union(_) => {
            // value_type is authoritative: literal-only unions can collapse to
            // primitive slots (mirrors emit_cast_to's Union arm); ref-lowered
            // unions are already $Object subtypes.
            match ctx.symbols.value_type(ty)? {
                ValType::F64 => emit_box(emitter, ctx, &Type::Number)?,
                ValType::I32 => emit_box(emitter, ctx, &Type::Boolean)?,
                ValType::Ref(_) => {}
                _ => {
                    return Err(crate::codegen::internal_failure(
                        "invalid type representation during cast lowering",
                    ));
                }
            }
        }
        // A class instance is an `$Object` subtype; the upcast is implicit.
        Type::InterfaceRef { .. } | Type::ClassRef { .. } => {}
        // A recursion back-edge lowers to `(ref null $Object)` — already
        // an `$Object` subtype, so the upcast is implicit. No-op.
        Type::AliasRef { .. } => {}
        Type::Alias { .. } | Type::Refined { .. } | Type::Readonly(_) => {
            return Err(crate::codegen::internal_failure(
                "invalid type representation during cast lowering",
            ));
        }
    };
    Ok(())
}

/// Coerce a `source_ty`-typed value into the Wasm slot type for `target_ty`.
/// Boxes primitives (f64/i32 → ref); WasmGC subtyping handles ref→ref cases.
///
/// Caller guarantees `source_ty` is assignable to `target_ty` (typechecker-proven);
/// narrowing-direction casts use `emit_narrowing_cast` instead.
pub fn emit_coerce_to_slot(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    source_ty: &Type,
    target_ty: &Type,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    let source_val = ctx.symbols.value_type(source_ty)?;
    let target_val = ctx.symbols.value_type(target_ty)?;
    if source_val == target_val {
        return Ok(());
    }
    // Never: the call already threw, but the wasm validator still needs a
    // well-typed cast sequence; emit_cast_to covers this. Traps here are fine.
    if matches!(source_ty.peel(), Type::Never) {
        emit_cast_to(emitter, ctx, target_ty)?;
        return Ok(());
    }
    emit_coerce_to_wasm_slot(emitter, ctx, source_ty, target_val)?;

    Ok(())
}

/// Coerce a `source_ty`-typed value into an already-known Wasm slot type.
///
/// Used where the target's Wasm type was *recorded* when the signature was
/// emitted rather than re-derived from a language type — class-method vtable
/// slots and closure funcref result slots. A vtable signature deliberately
/// erases class types and type variables (see `SymbolTable::slot_value_type`);
/// re-deriving would be unsound because `value_type`'s `ClassRef` lowering
/// changes once the class's struct type is recorded.
pub fn emit_coerce_to_wasm_slot(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    source_ty: &Type,
    target_val: ValType,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    let source_val = ctx.symbols.value_type(source_ty)?;
    if source_val == target_val {
        return Ok(());
    }
    // A `never`-typed argument comes from a call that always throws, so this
    // point is unreachable. The validator still has to see a well-typed stack
    // and the value's slot may be a primitive it can't be cast into, so make
    // the rest of the sequence stack-polymorphic instead.
    if matches!(source_ty.peel(), Type::Never) {
        emitter.instruction(Instruction::Unreachable);
        return Ok(());
    }
    if crate::codegen::closure_coercions::emit_coercion(emitter, ctx, source_ty, target_val)? {
        return Ok(());
    }
    if source_ty == &Type::Unknown && target_val == ctx.symbols.value_type(&Type::String)? {
        let function = ctx
            .symbols
            .prelude_func_idx("__value_to_string")
            .ok_or_else(|| {
                crate::codegen::internal_failure("dynamic string conversion collected")
            })?;
        emitter.instruction(Instruction::Call(function));
        return Ok(());
    }
    match (&source_val, &target_val) {
        (ValType::Ref(_), ValType::F64) if matches!(source_ty, Type::Unknown) => {
            let function = ctx
                .symbols
                .prelude_func_idx("__value_to_number")
                .ok_or_else(|| {
                    crate::codegen::internal_failure("dynamic number conversion collected")
                })?;
            emitter.instruction(Instruction::Call(function));
        }
        (ValType::Ref(_), ValType::I32) if matches!(source_ty, Type::Unknown) => {
            emit_condition_to_i32(emitter, ctx, source_ty)?;
        }
        (ValType::Ref(_), ValType::F64) => {
            emit_cast_to(emitter, ctx, &Type::Number)?;
        }
        // Primitive into a boxed slot.
        (ValType::F64 | ValType::I32, ValType::Ref(_)) => emit_box(emitter, ctx, source_ty)?,
        // Ref subtypes — WasmGC subtyping carries the value; no instruction needed.
        (ValType::Ref(source), ValType::Ref(target))
            if ctx.symbols.ref_fits_slot(*source, *target) => {}
        // Any other ref pairing needs the value pinned to the slot's own heap
        // type: a nullable value into a non-null slot, or a supertype-lowered
        // value (an `InterfaceRef` is `(ref null $Object)`) into a narrower
        // structural slot. The typechecker proved the value fits, so neither
        // trap is reachable.
        (ValType::Ref(_), ValType::Ref(target)) => {
            if target.nullable {
                emitter.instruction(Instruction::RefCastNullable(target.heap_type));
            } else {
                emitter.instruction(Instruction::RefCastNonNull(target.heap_type));
            }
        }
        _ => {
            return Err(crate::codegen::internal_failure(
                "value representation does not fit the recorded slot",
            ));
        }
    };
    Ok(())
}

/// Coerce the returned value on top of the stack (static type `source_ty`) into
/// the enclosing body's [`ReturnTarget`].
///
/// A recorded slot is coerced to as a Wasm type, not through the declaration it
/// came from: coercing `(x: number): number => x + 2` against its declaration
/// would leave a bare f64 in the closure ABI's ref slot.
pub fn emit_coerce_to_return_slot(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    source_ty: &Type,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    match emitter.return_target().clone() {
        ReturnTarget::Slot(slot) => emit_coerce_to_wasm_slot(emitter, ctx, source_ty, slot)?,
        ReturnTarget::Declared(ret) => emit_coerce_to_slot(emitter, ctx, source_ty, &ret)?,
        ReturnTarget::NoResult => {}
    };
    Ok(())
}

/// Consume the condition value (static type `cond_ty`) on the stack and leave
/// an i32 where nonzero = truthy, per JS semantics: `null`, `""`, `0`, `-0`,
/// `NaN`, `false`, and `0n` are falsy; everything else is truthy.
pub fn emit_condition_to_i32(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    cond_ty: &Type,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    let val = ctx.symbols.value_type(cond_ty)?;
    match val {
        // Number slot: `|x| > 0` folds `0`, `-0`, and `NaN` (abs(NaN) > 0 is
        // false) into falsy in three instructions.
        ValType::F64 => {
            emitter.instruction(Instruction::F64Abs);
            emitter.instruction(Instruction::F64Const(Ieee64::from(0.0)));
            emitter.instruction(Instruction::F64Gt);
        }
        ValType::Ref(rt) => emit_ref_truthiness(emitter, ctx, cond_ty, rt.nullable)?,
        // Boolean slot (i32) is already the condition convention.
        _ => {}
    };
    Ok(())
}

/// Ref-slot truthiness. Fast paths: a type whose only falsy value is `null`
/// needs just a null test; a bare `$string` needs just its length. Everything
/// else (falsy-bearing unions, erased generics) takes a `ref.test` dispatch
/// over only the falsy kinds the static type admits, defaulting to truthy —
/// mirrors `emit_typeof_tag`.
fn emit_ref_truthiness(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    cond_ty: &Type,
    nullable: bool,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    use TruthinessClass::*;
    let peeled = cond_ty.peel();
    let members: Vec<&Type> = match peeled {
        Type::Union(members) => members.iter().collect(),
        single => vec![single],
    };
    let classes: Vec<TruthinessClass> = members
        .iter()
        .filter(|m| !matches!(m.peel(), Type::Null))
        .map(|m| match m.peel() {
            Type::Void => Dynamic,
            Type::Undefined => AlwaysFalsy,
            _ => truthiness_class(m),
        })
        .collect();

    if classes.iter().all(|c| *c == AlwaysTruthy) {
        if nullable {
            emitter.instruction(Instruction::RefIsNull);
            emitter.instruction(Instruction::I32Eqz);
        } else {
            emitter.instruction(Instruction::Drop);
            emitter.instruction(Instruction::I32Const(1));
        }
        return Ok(());
    }
    if classes.iter().all(|c| *c == AlwaysFalsy) {
        emitter.instruction(Instruction::Drop);
        emitter.instruction(Instruction::I32Const(0));
        return Ok(());
    }

    let needs = |class: TruthinessClass, literal: fn(&Type) -> bool| {
        classes.contains(&class)
            || classes.contains(&Dynamic)
            || members.iter().any(|m| literal(m.peel()))
    };
    let test_string = needs(StringLike, |m| matches!(m, Type::StringLiteral(_)));
    let test_number = needs(NumberLike, |m| matches!(m, Type::NumberLiteral(_)));
    let test_boolean = needs(BooleanLike, |m| matches!(m, Type::BooleanLiteral(_)));
    let test_bigint = needs(BigIntLike, |_| false);
    let test_undefined = classes.contains(&Dynamic)
        || members
            .iter()
            .any(|member| matches!(member.peel(), Type::Undefined));

    let slot = ctx.symbols.value_type(cond_ty)?;
    let tmp = emitter.add_anonymous_local(slot)?;
    emitter.instruction(Instruction::LocalSet(tmp));

    // Nested if/else chain, innermost default = truthy. Each falsy-capable
    // kind gets a `ref.test` arm that extracts its payload's own truthiness.
    let mut open_blocks = 0u32;
    if nullable {
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefIsNull);
        emitter.emit_if(BlockType::Result(ValType::I32));
        emitter.instruction(Instruction::I32Const(0));
        emitter.emit_else();
        open_blocks += 1;
    }
    if test_undefined {
        emitter.instruction(Instruction::LocalGet(tmp));
        super::expr::emit_is_undefined(emitter, ctx)?;
        emitter.emit_if(BlockType::Result(ValType::I32));
        emitter.instruction(Instruction::I32Const(0));
        emitter.emit_else();
        open_blocks += 1;
    }
    if test_string {
        let idx = ctx
            .symbols
            .string_type_idx()
            .ok_or_else(|| crate::codegen::internal_failure("$string intrinsic type registered"))?;
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefTestNonNull(HeapType::Concrete(idx)));
        emitter.emit_if(BlockType::Result(ValType::I32));
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        emitter.instruction(Instruction::StructGet {
            struct_type_index: idx,
            field_index: 1,
        });
        emitter.instruction(Instruction::ArrayLen);
        emitter.emit_else();
        open_blocks += 1;
    }
    if test_number {
        let idx = ctx.symbols.boxed_number_type_idx().ok_or_else(|| {
            crate::codegen::internal_failure("$BoxedNumber intrinsic type registered")
        })?;
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefTestNonNull(HeapType::Concrete(idx)));
        emitter.emit_if(BlockType::Result(ValType::I32));
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        emitter.instruction(Instruction::StructGet {
            struct_type_index: idx,
            field_index: 1,
        });
        emitter.instruction(Instruction::F64Abs);
        emitter.instruction(Instruction::F64Const(0.0.into()));
        emitter.instruction(Instruction::F64Gt);
        emitter.emit_else();
        open_blocks += 1;
    }
    if test_boolean {
        let idx = ctx.symbols.boxed_boolean_type_idx().ok_or_else(|| {
            crate::codegen::internal_failure("$BoxedBoolean intrinsic type registered")
        })?;
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefTestNonNull(HeapType::Concrete(idx)));
        emitter.emit_if(BlockType::Result(ValType::I32));
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        emitter.instruction(Instruction::StructGet {
            struct_type_index: idx,
            field_index: 1,
        });
        emitter.emit_else();
        open_blocks += 1;
    }
    if test_bigint {
        let idx = ctx
            .symbols
            .bigint_type_idx()
            .ok_or_else(|| crate::codegen::internal_failure("$bigint intrinsic type registered"))?;
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefTestNonNull(HeapType::Concrete(idx)));
        emitter.emit_if(BlockType::Result(ValType::I32));
        emitter.instruction(Instruction::LocalGet(tmp));
        emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        // Field 1 is the sign (−1/0/1) — nonzero iff the bigint is nonzero.
        emitter.instruction(Instruction::StructGet {
            struct_type_index: idx,
            field_index: 1,
        });
        emitter.emit_else();
        open_blocks += 1;
    }
    emitter.instruction(Instruction::I32Const(1));
    for _ in 0..open_blocks {
        emitter.emit_end();
    }
    Ok(())
}

/// Emit the Wasm cast from `cast_info.from_ty` to `cast_info.to_ty`.
/// The cast is **unchecked** — codegen trusts the typechecker's narrowing
/// decision; the Wasm-level cast traps if the predicate's runtime check was unsound.
pub fn emit_narrowing_cast(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    cast_info: &crate::typechecker::infer::narrowing::CastInfo,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    use crate::typechecker::infer::narrowing::CastKind;
    if matches!(cast_info.to_ty.peel(), Type::Never) {
        emitter.instruction(Instruction::Drop);
        emitter.instruction(Instruction::Unreachable);
        return Ok(());
    }
    let from_val = ctx.symbols.value_type(&cast_info.from_ty)?;
    let to_val = ctx.symbols.value_type(&cast_info.to_ty)?;
    // Same Wasm repr → no instructions. Happens when the inferer
    // tightened a multi-member union into another multi-member union
    // (e.g., `number | string | null` → `string | null` after
    // `typeof x === "number"` else-branch) — both lower to
    // `(ref null $Object)`.
    if from_val == to_val {
        return Ok(());
    }
    // Repr changes only in the nullable bit (same heap type, source nullable,
    // target non-null) — e.g. the false-branch of `!== null` on a union like
    // `number | string | null` narrows to a non-null union still lowered to
    // `(ref $Object)`. A bare `ref.as_non_null` covers the repr gap; no
    // `ref.cast` is meaningful since the heap type is unchanged.
    if let (ValType::Ref(s), ValType::Ref(t)) = (&from_val, &to_val)
        && s.heap_type == t.heap_type
        && s.nullable
        && !t.nullable
    {
        emitter.instruction(Instruction::RefAsNonNull);
        return Ok(());
    }
    match cast_info.cast_kind {
        CastKind::NonNull | CastKind::Unbox => {
            // Both reduce to emit_cast_to: source is (ref null $Object),
            // target is the narrowed concrete type.
            emit_cast_to(emitter, ctx, &cast_info.to_ty)?;
        }
        CastKind::RefSubtype => {
            // Same-repr cases were handled above. ref.cast trusts the
            // typechecker — traps only if the narrowing decision was unsound.
            let ValType::Ref(target_ref) = to_val else {
                return Err(crate::codegen::internal_failure(
                    "invalid type representation during cast lowering",
                ));
            };
            let cast = if target_ref.nullable {
                Instruction::RefCastNullable(target_ref.heap_type)
            } else {
                Instruction::RefCastNonNull(target_ref.heap_type)
            };
            emitter.instruction(cast);
        }
    };
    Ok(())
}

/// Recover `ty`'s value type from a slot that stores it erased — a box cell's
/// payload, keyed on `slot_value_type`.
///
/// Skips the cast when the two lowerings already agree — which is not the same
/// as `ty` not being erased. An erased type often lowers to exactly the
/// `(ref null $Object)` the cell holds: a `TypeVar` or `GenericParam` does, and
/// so does a union mixing one with anything else. Gating on erasure instead
/// would cast a value already in its own lowering — and for an unrecorded
/// `ClassRef` that cast is a `ref.as_non_null` plus a `ref.cast` to a class
/// struct this module never recorded.
pub fn emit_unerase(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    ty: &Type,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    if ctx.symbols.slot_value_type(ty)? != ctx.symbols.value_type(ty)? {
        emit_cast_to(emitter, ctx, ty)?;
    };
    Ok(())
}

/// Emit Wasm instructions that pop a `(ref null $Object)` from the
/// stack and produce a `ty`-typed value.
///
/// Never leaves the stack *wider* than `value_type(ty)` — the arms that emit no
/// `ref.cast` narrow with `ref.as_non_null` or nothing at all. Several callers
/// gate on `ValType` equality alone and would emit an ill-typed sequence if a
/// cast target could come back wider than its own lowering.
pub fn emit_cast_to(
    emitter: &mut FunctionEmitter<'_>,
    ctx: &CodegenCtx<'_>,
    ty: &Type,
) -> Result<(), crate::compiler_error::CompilerFailure> {
    // codegen casts on the structural shape — peel through
    // aliases. The alias label is purely a typechecker/display thing.
    let ty = ty.peel();
    // Every per-type cast below assumes non-null input, so lift unless the target
    // admits a null of its own.
    if !target_allows_null(ctx, ty)? {
        emitter.instruction(Instruction::RefAsNonNull);
    }
    match ty {
        Type::Number | Type::NumberLiteral(_) => {
            let boxed_idx = ctx
                .symbols
                .boxed_number_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("boxed_number type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(boxed_idx)));
            emitter.instruction(Instruction::StructGet {
                struct_type_index: boxed_idx,
                field_index: 1,
            });
        }
        Type::Boolean | Type::BooleanLiteral(_) => {
            let boxed_idx = ctx
                .symbols
                .boxed_boolean_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("boxed_boolean type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(boxed_idx)));
            emitter.instruction(Instruction::StructGet {
                struct_type_index: boxed_idx,
                field_index: 1,
            });
        }
        Type::String | Type::StringLiteral(_) => {
            let idx = ctx
                .symbols
                .string_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("string type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::BigInt | Type::BigIntLiteral(_) => {
            let idx = ctx
                .symbols
                .bigint_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("bigint type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::Object { .. } => {
            // `Type::Object` lowers to `(ref $ObjectShape)`,
            // not the arity-specific subtype. The static arity does
            // not pin runtime arity once width subtyping has erased
            // it, so casting to a per-arity subtype here would trap
            // for any widened value. Field reads/writes go through
            // the per-shape getter/setter funcrefs on slots 2/3.
            let idx = ctx
                .symbols
                .object_shape_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("$ObjectShape type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::Array(_) | Type::Tuple(_) => {
            // Tuples and arrays share the `$Array` Wasm representation
            // — the typechecker keeps `Type::Tuple` distinct for
            // positional assignability + per-position `emit_cast_to`
            // at the element level.
            let idx = ctx
                .symbols
                .array_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("array type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::Uint8Array => {
            let idx = ctx
                .symbols
                .uint8_array_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("uint8_array type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::TypeVar(_) | Type::GenericParam { .. } | Type::Unknown | Type::Never => {
            // Never: the call always throws before producing a value; reuses
            // Unknown's (ref null $Object) lowering — see value_type.
        }
        Type::Function { .. } => {
            crate::codegen::closure_coercions::emit_erased_cast(
                emitter,
                ctx,
                crate::codegen::closures::classify(ty)?,
            )?;
        }
        Type::Null => {
            // Null lowers to (ref null $Object) — already a subtype of any nullable ref.
        }
        Type::Undefined => {
            let idx = ctx
                .symbols
                .intrinsic_type_indices()
                .ok_or_else(|| {
                    crate::codegen::internal_failure("undefined intrinsic not registered")
                })?
                .undefined;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::Void => {}
        Type::Error => {
            return Err(crate::codegen::internal_failure(
                "invalid type representation during cast lowering",
            ));
        }
        Type::Union(_) => {
            // value_type is authoritative: literal-only unions can collapse to
            // primitive slots, while object/mixed unions remain references.
            match ctx.symbols.value_type(ty)? {
                ValType::F64 => emit_cast_to(emitter, ctx, &Type::Number)?,
                ValType::I32 => emit_cast_to(emitter, ctx, &Type::Boolean)?,
                ValType::Ref(target_ref) => {
                    let cast = if target_ref.nullable {
                        Instruction::RefCastNullable(target_ref.heap_type)
                    } else {
                        Instruction::RefCastNonNull(target_ref.heap_type)
                    };
                    emitter.instruction(cast);
                }
                _ => {
                    return Err(crate::codegen::internal_failure(
                        "invalid type representation during cast lowering",
                    ));
                }
            }
        }
        Type::NumberEnum { .. } => {
            // Numeric enum values are `$BoxedNumber` instances —
            // cast the universal slot back to that subtype. Unlike
            // `Type::Number`, do NOT unbox to f64: the static type
            // is the boxed form.
            let boxed_idx = ctx
                .symbols
                .boxed_number_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("boxed_number type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(boxed_idx)));
        }
        Type::StringEnum { .. } => {
            let idx = ctx
                .symbols
                .string_type_idx()
                .ok_or_else(|| crate::codegen::internal_failure("string type registered"))?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::InterfaceRef { .. } => {
            // InterfaceRef: RefAsNonNull above is enough — method dispatch uses
            // mangled names, not ref.cast to a per-interface struct.
        }
        Type::ClassRef { mangled, .. } => {
            // Body emission runs after `imported_classes::reconstruct` and the
            // `ClassPlan` reservation, so every class a body can reference has a
            // recorded struct type; a miss here is a dependency-usage collection
            // gap, not the erased pre-recording representation `value_type`
            // tolerates for env/box emission.
            let idx = ctx.symbols.class_struct_type_idx(mangled).ok_or_else(|| {
                crate::codegen::internal_failure("class struct type is not registered")
            })?;
            emitter.instruction(Instruction::RefCastNonNull(HeapType::Concrete(idx)));
        }
        Type::AliasRef { .. } => {
            // A recursion back-edge lowers to `(ref null $Object)` and the
            // `RefAsNonNull` above is skipped for it, so the null the alias body
            // may list flows through. Field reads go through the shape
            // field-name scan, same as `InterfaceRef`; no per-shape cast.
        }
        Type::Alias { .. } | Type::Refined { .. } | Type::Readonly(_) => {
            return Err(crate::codegen::internal_failure(
                "invalid type representation during cast lowering",
            ));
        }
    };
    Ok(())
}

/// Whether [`emit_cast_to`] lets a `null` reach the target rather than lifting to
/// non-null first. True for the targets whose lowering is a nullable
/// `(ref null $Object)`: bare `Null`, nullable unions, and the no-op
/// erased/dynamic types — `unknown`, `never`, an erased generic (which can hold
/// null after instantiation, e.g. `T = string | null`), and a recursion back-edge
/// whose body may list `null`. `emit_cast_to`'s `Union` arm uses `RefCastNullable`
/// for the same reason. A union's nullability is its *lowering*, not whether a
/// member is spelled `null`: `T | number` lowers nullable because `T` does.
///
/// A caller that must not hand [`emit_cast_to`] a `null` has to ask this, not
/// `is_nullable_ref`: the two disagree — an `InterfaceRef` lowers to a nullable
/// slot and is still `ref.as_non_null`ed there, which traps.
pub fn target_allows_null(
    ctx: &CodegenCtx<'_>,
    ty: &Type,
) -> Result<bool, crate::compiler_error::CompilerFailure> {
    let ty = ty.peel();
    Ok(matches!(
        ty,
        Type::Null
            | Type::Void
            | Type::Unknown
            | Type::Never
            | Type::TypeVar(_)
            | Type::GenericParam { .. }
            | Type::AliasRef { .. }
    ) || (matches!(ty, Type::Union(_)) && is_nullable_ref(ctx.symbols.value_type(ty)?)))
}