formawasm 0.0.1-beta

Backend that compiles a typed FormaLang IR module into a WebAssembly component.
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
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
//! Lowering for aggregate constructors and field access.
//!
//! Phase 1b mc3b lands [`lower_struct_inst`]; the matching
//! `FieldAccess` and `Tuple` lowerings ride the next two mcs but
//! reuse the helpers in this file.
//!
//! Aggregates live in linear memory. A constructor:
//!
//! 1. Calls the bump-allocator helper to reserve the struct's size.
//! 2. Stores the returned base pointer in a fresh scratch local.
//! 3. Stores each field at `base + offset` using the right primitive
//!    store opcode for the field's type.
//! 4. Reloads the base pointer as the constructor's value.

use formalang::ast::PrimitiveType;
use formalang::ir::{IrEnum, IrEnumVariant, IrExpr, IrField, IrModule, IrStruct, ResolvedType};
use wasm_encoder::{InstructionSink, MemArg, ValType};

use super::{LowerContext, LowerError, lower_expr};
use crate::layout::{
    ARRAY_HEADER_ALIGN, ARRAY_HEADER_CAP_OFFSET, ARRAY_HEADER_LEN_OFFSET, ARRAY_HEADER_PTR_OFFSET,
    ArrayLayout, ENUM_TAG_ALIGN, FieldLayout, LayoutError, RangeLayout, StructLayout,
    VariantLayout, plan_array, plan_enum, plan_range, plan_struct,
};
use crate::module::MEMORY_INDEX;

/// Lower [`IrExpr::StructInst`].
///
/// Pushes the base pointer of the freshly-allocated struct onto the
/// stack. Field initializers are evaluated in source order — each
/// one is stored at `base + field_offset` via the appropriate
/// primitive `store` opcode for its type.
pub fn lower_struct_inst(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::StructInst {
        struct_id,
        fields,
        ty,
        ..
    } = expr
    else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_struct_inst called with non-StructInst expression".to_owned(),
        });
    };

    // Prefer `ty`'s carried StructId — passes (DeadCodeElimination)
    // can renumber `module.structs` and leave the IR's `struct_id`
    // field pointing at the pre-renumbering slot. The post-pass
    // type-checker keeps `ty` in sync, so `compound::struct_id_of`
    // resolves to the live id.
    let id = crate::compound::struct_id_of(ty)
        .or(*struct_id)
        .ok_or(LowerError::ExternalStructInst)?;
    let module = ctx.module()?;
    let s = module
        .structs
        .get(id.0 as usize)
        .ok_or(LowerError::UnknownStruct(id))?;
    let layout = plan_struct(s, module)?;

    let base_local = allocate_aggregate(layout.size, sink, ctx)?;

    for (name, _idx, value_expr) in fields {
        let (field_layout, field_def) = lookup_field_by_name(s, &layout.fields, name)?;
        sink.local_get(base_local);
        store_aggregate_field(value_expr, &field_def.ty, *field_layout, sink, ctx)?;
    }

    sink.local_get(base_local);
    Ok(())
}

/// Lower `value_expr` into a position on the wasm operand stack
/// suitable for the field-store opcode that matches `field_ty`, then
/// emit that store at `field_layout`.
///
/// Primitive fields go through [`store_primitive`]; `Optional<T>`
/// fields store the value as an i32 pointer (the optional cell
/// itself lives elsewhere in linear memory). Other aggregate field
/// types stay rejected pending the matching nested-aggregate-field
/// mc — the layout planner already enforces that gate, so the arm
/// here is defensive only.
pub(super) fn store_aggregate_field(
    value_expr: &IrExpr,
    field_ty: &ResolvedType,
    field_layout: FieldLayout,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let module = ctx.module()?;
    if matches!(
        crate::compound::Compound::of(field_ty, module),
        crate::compound::Compound::Optional(_)
    ) {
        super::optional::lower_coerced(value_expr, field_ty, sink, ctx)?;
        sink.i32_store(field_mem_arg(field_layout));
        return Ok(());
    }
    match field_ty {
        ResolvedType::Primitive(p) => {
            super::optional::lower_coerced(value_expr, field_ty, sink, ctx)?;
            store_primitive(*p, field_layout, sink);
            Ok(())
        }
        // Aggregate field types (nested struct, enum, tuple, the
        // four prelude compounds, closure, trait fat pointer) all
        // live in linear memory and are referenced by an `i32`
        // pointer at the field offset. The pointer comes back on
        // the wasm value stack from `lower_expr`; we just need an
        // `i32_store` at the right offset.
        ResolvedType::Struct(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Closure { .. }
        | ResolvedType::Trait(_)
        | ResolvedType::Generic { .. } => {
            super::optional::lower_coerced(value_expr, field_ty, sink, ctx)?;
            sink.i32_store(field_mem_arg(field_layout));
            Ok(())
        }
        ResolvedType::TypeParam(_) | ResolvedType::External { .. } | ResolvedType::Error => {
            Err(LowerError::FieldAccessOnNonAggregate {
                ty: field_ty.clone(),
            })
        }
    }
}

/// Reserve `size` bytes via the bump-allocator helper, store the
/// returned pointer in a fresh scratch local, and return that
/// local's index.
pub(super) fn allocate_aggregate(
    size: u32,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<u32, LowerError> {
    let alloc_idx = ctx.bump_allocator()?;
    let size_i32 = i32::try_from(size).map_err(|_| {
        LowerError::Layout(crate::layout::LayoutError::SizeOverflow {
            name: "<aggregate>".to_owned(),
        })
    })?;
    let base_local = ctx.next_scratch_local(ValType::I32)?;
    sink.i32_const(size_i32);
    sink.call(alloc_idx);
    sink.local_set(base_local);
    Ok(base_local)
}

/// Pick the right `xN.store` opcode for `p`. `bool` uses
/// `i32.store8` since the field occupies a single byte;
/// `String` / `Path` / `Regex` store the i32 header pointer; the
/// numeric primitives store at their full native width.
pub(super) fn store_primitive(
    p: PrimitiveType,
    layout: FieldLayout,
    sink: &mut InstructionSink<'_>,
) {
    let mem_arg = field_mem_arg(layout);
    match p {
        PrimitiveType::Boolean => {
            sink.i32_store8(mem_arg);
        }
        PrimitiveType::I32 | PrimitiveType::String | PrimitiveType::Path | PrimitiveType::Regex => {
            sink.i32_store(mem_arg);
        }
        PrimitiveType::I64 => {
            sink.i64_store(mem_arg);
        }
        PrimitiveType::F32 => {
            sink.f32_store(mem_arg);
        }
        PrimitiveType::F64 => {
            sink.f64_store(mem_arg);
        }
        // `Never` is uninhabited so this arm is defensive only;
        // future #[non_exhaustive] variants ride the same path.
        PrimitiveType::Never | _ => {
            sink.unreachable();
        }
    }
}

/// Pick the right `xN.load` opcode for `p`. `bool` uses
/// `i32.load8_u` to zero-extend the byte into the i32 value type;
/// `String` / `Path` / `Regex` load the i32 header pointer.
pub(super) fn load_primitive(
    p: PrimitiveType,
    layout: FieldLayout,
    sink: &mut InstructionSink<'_>,
) {
    let mem_arg = field_mem_arg(layout);
    match p {
        PrimitiveType::Boolean => {
            sink.i32_load8_u(mem_arg);
        }
        PrimitiveType::I32 | PrimitiveType::String | PrimitiveType::Path | PrimitiveType::Regex => {
            sink.i32_load(mem_arg);
        }
        PrimitiveType::I64 => {
            sink.i64_load(mem_arg);
        }
        PrimitiveType::F32 => {
            sink.f32_load(mem_arg);
        }
        PrimitiveType::F64 => {
            sink.f64_load(mem_arg);
        }
        PrimitiveType::Never | _ => {
            sink.unreachable();
        }
    }
}

/// Lower [`IrExpr::ClosureRef`].
///
/// Materializes the closure as an `(i32 funcref, i32 env_ptr)` pair
/// in linear memory:
///
/// 1. Look up the lifted top-level function by name (last segment of
///    `funcref`) in `module.functions` and record its wasm function
///    index.
/// 2. Lower `env_struct` — typically an `IrExpr::StructInst` whose
///    fields hold the captured values; the result is the env's base
///    pointer.
/// 3. Allocate `CLOSURE_VALUE_SIZE` bytes through the bump allocator,
///    store the funcref index at offset 0 and the env pointer at
///    offset 4, and leave the closure value's base pointer on the
///    stack.
///
/// Indirect invocation (calling the closure) is not yet wired — that
/// needs a wasm `Table` of funcrefs plus `call_indirect`, which lands
/// later. Today's job is just to produce a valid closure VALUE.
pub fn lower_closure_ref(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::ClosureRef {
        funcref,
        env_struct,
        ..
    } = expr
    else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_closure_ref called with non-ClosureRef expression".to_owned(),
        });
    };

    let module = ctx.module()?;
    let last = funcref
        .last()
        .ok_or_else(|| LowerError::NotYetImplemented {
            what: "ClosureRef carries an empty funcref path".to_owned(),
        })?;
    let func_idx_u32 = module
        .functions
        .iter()
        .enumerate()
        .find(|(_, f)| &f.name == last)
        .map(|(i, _)| i)
        .ok_or_else(|| LowerError::NotYetImplemented {
            what: format!("ClosureRef target function '{last}' is not in module.functions"),
        })?;
    let func_idx_raw = u32::try_from(func_idx_u32).map_err(|_| LowerError::NotYetImplemented {
        what: "ClosureRef target index exceeds u32::MAX".to_owned(),
    })?;
    // Closure values store the *table element index* (not the wasm
    // function index) in the funcref slot, so `call_indirect` at the
    // call site can index the closure funcref table directly.
    let funcref_table_idx = ctx.closure_funcref_index(formalang::ir::FunctionId(func_idx_raw))?;
    let funcref_signed =
        i32::try_from(funcref_table_idx).map_err(|_| LowerError::NotYetImplemented {
            what: "ClosureRef target table index exceeds i32::MAX".to_owned(),
        })?;

    let base_local = allocate_aggregate(crate::types::CLOSURE_VALUE_SIZE, sink, ctx)?;

    // Funcref slot at offset 0.
    sink.local_get(base_local);
    sink.i32_const(funcref_signed);
    sink.i32_store(MemArg {
        offset: u64::from(crate::types::CLOSURE_FUNCREF_OFFSET),
        align: 2, // log2(4)
        memory_index: MEMORY_INDEX,
    });

    // Env pointer slot at offset 4.
    sink.local_get(base_local);
    lower_expr(env_struct, sink, ctx)?;
    sink.i32_store(MemArg {
        offset: u64::from(crate::types::CLOSURE_ENV_OFFSET),
        align: 2,
        memory_index: MEMORY_INDEX,
    });

    sink.local_get(base_local);
    Ok(())
}

/// Lower [`IrExpr::EnumInst`].
///
/// Allocates `enum_layout.size` bytes through the bump allocator,
/// stores the variant's discriminant tag at `tag_offset`, then writes
/// each provided field at the variant's absolute field offset. The
/// base pointer is left on the stack as the constructor's value.
///
/// The `variant_idx` stored on the IR node is the source of truth
/// when in range; we fall back to a name lookup so older IR shapes
/// emitted with the placeholder `VariantIdx(0)` still resolve.
pub fn lower_enum_inst(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::EnumInst {
        enum_id,
        variant,
        variant_idx,
        fields,
        ty,
        ..
    } = expr
    else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_enum_inst called with non-EnumInst expression".to_owned(),
        });
    };

    let id = enum_id.ok_or(LowerError::ExternalEnumInst)?;
    let module = ctx.module()?;
    let e_decl = module
        .enums
        .get(id.0 as usize)
        .ok_or(LowerError::UnknownEnum(id))?;
    // Substitute generic args: when this EnumInst's type is
    // `Generic { Enum(id), [...] }` (the post-0.0.4-beta shape for
    // Optional<T> / user-generic enums), each variant field's
    // declared `TypeParam(name)` becomes the matching concrete
    // arg. For non-generic enums the helper returns the
    // declaration unchanged.
    let type_args = crate::compound::generic_args_for_enum(ty, id);
    let e_owned = crate::compound::substitute_enum(e_decl, &e_decl.generic_params, type_args);
    let e = &e_owned;
    let layout = plan_enum(e, module)?;

    let (variant_layout, variant_def) =
        resolve_variant(e, &layout.variants, variant_idx.0, variant)?;

    let base_local = allocate_aggregate(layout.size, sink, ctx)?;

    // Tag store: i32_const tag, then i32_store at tag_offset.
    sink.local_get(base_local);
    let tag_signed = i32::try_from(variant_layout.tag).unwrap_or(i32::MAX);
    sink.i32_const(tag_signed);
    sink.i32_store(MemArg {
        offset: u64::from(layout.tag_offset),
        align: align_to_log2(ENUM_TAG_ALIGN),
        memory_index: MEMORY_INDEX,
    });

    // Field stores. Match by name so we're robust to a placeholder
    // FieldIdx(0) on the IR node.
    for (field_name, _idx, value_expr) in fields {
        let (field_layout, field_def) =
            lookup_variant_field_by_name(variant_def, &variant_layout.fields, field_name)?;
        sink.local_get(base_local);
        store_aggregate_field(value_expr, &field_def.ty, *field_layout, sink, ctx)?;
    }

    sink.local_get(base_local);
    Ok(())
}

/// Resolve the variant identified by `idx` (with name fallback) on
/// `e`, returning both the layout-side and IR-side metadata.
fn resolve_variant<'a>(
    e: &'a IrEnum,
    variants: &'a [VariantLayout],
    idx: u32,
    name: &str,
) -> Result<(&'a VariantLayout, &'a IrEnumVariant), LowerError> {
    let i = idx as usize;
    if let Some(vl) = variants.get(i)
        && let Some(vd) = e.variants.get(i)
        && vl.name == vd.name
    {
        return Ok((vl, vd));
    }
    for (vl, vd) in variants.iter().zip(e.variants.iter()) {
        if vd.name == name {
            return Ok((vl, vd));
        }
    }
    Err(LowerError::UnknownVariant {
        enum_name: e.name.clone(),
        variant: name.to_owned(),
    })
}

fn lookup_variant_field_by_name<'a>(
    variant_def: &'a IrEnumVariant,
    field_layouts: &'a [FieldLayout],
    name: &str,
) -> Result<(&'a FieldLayout, &'a IrField), LowerError> {
    for (i, f) in variant_def.fields.iter().enumerate() {
        if f.name == name {
            let fl = field_layouts
                .get(i)
                .ok_or_else(|| LowerError::FieldIndexOutOfRange {
                    struct_name: variant_def.name.clone(),
                    field_count: variant_def.fields.len(),
                    field_idx: u32::try_from(i).unwrap_or(u32::MAX),
                })?;
            return Ok((fl, f));
        }
    }
    Err(LowerError::FieldIndexOutOfRange {
        struct_name: variant_def.name.clone(),
        field_count: variant_def.fields.len(),
        field_idx: u32::MAX,
    })
}

/// Lower [`IrExpr::Tuple`].
///
/// Treats the tuple as an anonymous struct synthesized from the
/// carried `ResolvedType::Tuple(...)`. Layout planning, allocation,
/// and per-field stores reuse the same path as
/// [`lower_struct_inst`]; the only difference is the field-meta
/// source.
pub fn lower_tuple(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::Tuple { fields, ty, .. } = expr else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_tuple called with non-Tuple expression".to_owned(),
        });
    };

    let module = ctx.module()?;
    let synthetic = synthetic_struct_for_tuple(ty)?;
    let layout = plan_struct(&synthetic, module)?;

    let base_local = allocate_aggregate(layout.size, sink, ctx)?;

    for (name, value_expr) in fields {
        let (field_layout, field_def) =
            lookup_field_by_name_with_meta(&synthetic.fields, &layout.fields, name, "__tuple")?;
        sink.local_get(base_local);
        store_aggregate_field(value_expr, &field_def.ty, *field_layout, sink, ctx)?;
    }

    sink.local_get(base_local);
    Ok(())
}

/// Lower [`IrExpr::Array`].
///
/// Materializes an array literal as a 12-byte header
/// (`{ ptr, len, cap }`) plus a separately-allocated element buffer:
///
/// 1. Allocate `len * element_size` bytes for the element buffer
///    through the bump allocator and stash the base pointer in a
///    scratch local.
/// 2. Walk each element expression in source order; for each one,
///    leave the buffer pointer + element value on the stack and emit
///    the right primitive `store` opcode at offset
///    `i * element_size`. Aggregate elements are stored as `i32`
///    pointers since aggregates already live elsewhere in linear
///    memory.
/// 3. Allocate the 12-byte header through the bump allocator and
///    stash that pointer in a second scratch local. Store the buffer
///    base at offset 0 (`ptr`), the length at offset 4 (`len`), and
///    the length again at offset 8 (`cap` — capacity equals length
///    for literals; growable arrays are a later feature).
/// 4. Leave the header pointer on the stack as the array value.
///
/// Empty arrays still take both allocations; the buffer alloc with
/// size 0 returns the current heap pointer without advancing it, so
/// the header's `ptr` slot may coincide with the header itself —
/// benign since nothing reads through `ptr` when `len == 0`.
pub fn lower_array(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::Array { elements, ty, .. } = expr else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_array called with non-Array expression".to_owned(),
        });
    };

    let module = ctx.module()?;
    let elem_ty =
        crate::compound::array_elem(ty, module).ok_or_else(|| LowerError::NotYetImplemented {
            what: format!("Array literal carrying non-Array type {ty:?}"),
        })?;
    let layout = plan_array(elem_ty, module)?;

    let len_u32 = u32::try_from(elements.len()).map_err(|_| LowerError::NotYetImplemented {
        what: "array literal with more than u32::MAX elements".to_owned(),
    })?;
    let len_signed = i32::try_from(len_u32).map_err(|_| LowerError::NotYetImplemented {
        what: "array literal length exceeds i32::MAX".to_owned(),
    })?;
    let buffer_size =
        layout
            .element_size
            .checked_mul(len_u32)
            .ok_or_else(|| LayoutError::SizeOverflow {
                name: "<array buffer>".to_owned(),
            })?;

    let buf_local = allocate_aggregate(buffer_size, sink, ctx)?;

    for (i, element) in elements.iter().enumerate() {
        let i_u32 = u32::try_from(i).unwrap_or(u32::MAX);
        let offset =
            layout
                .element_size
                .checked_mul(i_u32)
                .ok_or_else(|| LayoutError::SizeOverflow {
                    name: "<array element offset>".to_owned(),
                })?;
        sink.local_get(buf_local);
        super::optional::lower_coerced(element, elem_ty, sink, ctx)?;
        store_array_element(elem_ty, layout, offset, sink)?;
    }

    let header_local = allocate_aggregate(layout.header_size, sink, ctx)?;
    finalize_array_header(header_local, buf_local, HeaderLen::Const(len_signed), sink);
    Ok(())
}

/// Source of the `len` / `cap` values used by
/// [`finalize_array_header`].
///
/// Array literals know their length statically (the IR carries the
/// element vector), so they pass [`HeaderLen::Const`]. The For-loop
/// comprehension computes its length at runtime as `end - start`,
/// stashes it in a wasm local, and passes [`HeaderLen::Local`].
#[derive(Debug, Clone, Copy)]
pub(super) enum HeaderLen {
    /// Statically-known length — emitted as `i32.const`.
    Const(i32),
    /// Length lives in the wasm local at this index — emitted as
    /// `local.get`.
    Local(u32),
}

/// Write the `{ ptr, len, cap }` triple into a freshly-allocated
/// 12-byte array header.
///
/// `header_local` holds the header's base pointer; `buf_local` holds
/// the element-buffer pointer that goes into the `ptr` slot. `len`
/// drives both the `len` and `cap` slots — capacity equals length
/// since growable arrays aren't a Phase 1c feature. Leaves the header
/// pointer on the wasm stack as the array value.
pub(super) fn finalize_array_header(
    header_local: u32,
    buf_local: u32,
    len: HeaderLen,
    sink: &mut InstructionSink<'_>,
) {
    let mem_arg = |offset: u64| MemArg {
        offset,
        align: align_to_log2(ARRAY_HEADER_ALIGN),
        memory_index: MEMORY_INDEX,
    };
    let push_len = |sink: &mut InstructionSink<'_>| match len {
        HeaderLen::Const(c) => {
            sink.i32_const(c);
        }
        HeaderLen::Local(idx) => {
            sink.local_get(idx);
        }
    };

    // ptr field
    sink.local_get(header_local);
    sink.local_get(buf_local);
    sink.i32_store(mem_arg(u64::from(ARRAY_HEADER_PTR_OFFSET)));

    // len field
    sink.local_get(header_local);
    push_len(sink);
    sink.i32_store(mem_arg(u64::from(ARRAY_HEADER_LEN_OFFSET)));

    // cap field (= len; growable arrays land later)
    sink.local_get(header_local);
    push_len(sink);
    sink.i32_store(mem_arg(u64::from(ARRAY_HEADER_CAP_OFFSET)));

    // Leave the header pointer on the stack as the array value.
    sink.local_get(header_local);
}

/// Emit the `store` opcode that writes one array element to `buf +
/// offset`, given the element's resolved type and the array's layout.
fn store_array_element(
    elem_ty: &ResolvedType,
    layout: ArrayLayout,
    offset: u32,
    sink: &mut InstructionSink<'_>,
) -> Result<(), LowerError> {
    let field_layout = FieldLayout {
        offset,
        size: layout.element_size,
        align: layout.element_align,
    };
    // After 0.0.4-beta, `Array<T>` and `Optional<T>` both flow
    // through `Generic { .. }`. `plan_array` already rejects element
    // types that can't lower as i32 pointers, so the dispatch here
    // is correct for any aggregate (struct / enum / tuple /
    // generic) — they all collapse to a single `i32_store`.
    match elem_ty {
        ResolvedType::Primitive(p) => {
            store_primitive(*p, field_layout, sink);
            Ok(())
        }
        ResolvedType::Struct(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Generic { .. } => {
            sink.i32_store(field_mem_arg(field_layout));
            Ok(())
        }
        ResolvedType::Closure { .. }
        | ResolvedType::Trait(_)
        | ResolvedType::TypeParam(_)
        | ResolvedType::External { .. }
        | ResolvedType::Error => Err(LowerError::NotYetImplemented {
            what: format!("array element of type {elem_ty:?}"),
        }),
    }
}

/// Lower [`IrExpr::DictLiteral`] as a `{ ptr, len, cap }` header
/// pointing at a buffer of pointers, each pointing to a freshly-
/// allocated `(k, v)` pair tuple.
///
/// Phase 2 v1 keeps insertion order and does no sorting / dedup;
/// later mcs may swap in a sorted layout for log-n lookup.
pub fn lower_dict_literal(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::DictLiteral { entries, ty, .. } = expr else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_dict_literal called with non-DictLiteral expression".to_owned(),
        });
    };
    let module = ctx.module()?;
    let (key_ty, value_ty) = crate::compound::dictionary_kv(ty, module).ok_or_else(|| {
        LowerError::NotYetImplemented {
            what: format!("DictLiteral carrying non-Dictionary type {ty:?}"),
        }
    })?;
    let pair_struct = dict_pair_struct(key_ty, value_ty);
    let pair_layout = plan_struct(&pair_struct, module)?;
    let key_field_layout =
        pair_layout
            .fields
            .first()
            .copied()
            .ok_or_else(|| LowerError::NotYetImplemented {
                what: "dict pair tuple has no fields".to_owned(),
            })?;
    let value_field_layout =
        pair_layout
            .fields
            .get(1)
            .copied()
            .ok_or_else(|| LowerError::NotYetImplemented {
                what: "dict pair tuple has fewer than two fields".to_owned(),
            })?;

    let len_u32 = u32::try_from(entries.len()).map_err(|_| LowerError::NotYetImplemented {
        what: "dict literal with more than u32::MAX entries".to_owned(),
    })?;
    let len_signed = i32::try_from(len_u32).map_err(|_| LowerError::NotYetImplemented {
        what: "dict literal length exceeds i32::MAX".to_owned(),
    })?;
    let buffer_size =
        len_u32
            .checked_mul(POINTER_SIZE_CONST)
            .ok_or_else(|| LayoutError::SizeOverflow {
                name: "<dict buffer>".to_owned(),
            })?;

    let buf_local = allocate_aggregate(buffer_size, sink, ctx)?;

    for (i, (k_expr, v_expr)) in entries.iter().enumerate() {
        let i_u32 = u32::try_from(i).unwrap_or(u32::MAX);
        let slot_offset =
            i_u32
                .checked_mul(POINTER_SIZE_CONST)
                .ok_or_else(|| LayoutError::SizeOverflow {
                    name: "<dict slot offset>".to_owned(),
                })?;

        // Allocate a pair tuple, store (k, v) into it.
        let pair_local = allocate_aggregate(pair_layout.size, sink, ctx)?;
        let key_prim = primitive_of(key_ty)?;
        sink.local_get(pair_local);
        super::optional::lower_coerced(k_expr, key_ty, sink, ctx)?;
        store_primitive(key_prim, key_field_layout, sink);

        let value_prim = primitive_of(value_ty)?;
        sink.local_get(pair_local);
        super::optional::lower_coerced(v_expr, value_ty, sink, ctx)?;
        store_primitive(value_prim, value_field_layout, sink);

        // Store the pair pointer in the buffer at slot_offset.
        sink.local_get(buf_local);
        sink.local_get(pair_local);
        sink.i32_store(MemArg {
            offset: u64::from(slot_offset),
            align: 2,
            memory_index: MEMORY_INDEX,
        });
    }

    let header_local = allocate_aggregate(crate::layout::DICTIONARY_HEADER_SIZE, sink, ctx)?;
    finalize_array_header(header_local, buf_local, HeaderLen::Const(len_signed), sink);
    Ok(())
}

/// Pointer size used for dictionary buffer slots and similar
/// aggregate-as-pointer contexts.
const POINTER_SIZE_CONST: u32 = 4;

/// Lower [`IrExpr::DictAccess`] for either an array indexing (`arr[i]`)
/// or a dictionary lookup (`dict[key]`).
///
/// The two collection shapes share the variant in the IR; the
/// dispatch here switches on `dict.ty()`:
///
/// * `Array<T>`: read the buffer pointer from the array header at
///   offset 0, then leave `buf_ptr + idx * element_size` on the
///   stack and emit the element type's `load` opcode (or `i32_load`
///   for aggregate elements stored as pointers).
/// * `Dictionary<K, V>`: walk the buffer of pair pointers comparing
///   each entry's key against the lookup key. Returns the matching
///   value's bytes; traps via `unreachable` when no entry matches.
///
/// Bounds checking on array indexing is intentionally absent for
/// Phase 1c — out-of-range reads land wherever the multiply takes
/// them. A trapping bounds check rides a later phase once the
/// language has a panicking-runtime story.
pub fn lower_dict_access(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::DictAccess { dict, key, .. } = expr else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_dict_access called with non-DictAccess expression".to_owned(),
        });
    };

    let coll_ty = dict.ty();
    let module = ctx.module()?;
    if let Some(elem_ty) = crate::compound::array_elem(coll_ty, module) {
        return lower_array_index(dict, key, elem_ty, sink, ctx);
    }
    if let Some((key_ty, value_ty)) = crate::compound::dictionary_kv(coll_ty, module) {
        return lower_dict_lookup(dict, key, key_ty, value_ty, sink, ctx);
    }
    match coll_ty {
        ResolvedType::Primitive(_)
        | ResolvedType::Struct(_)
        | ResolvedType::Trait(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Generic { .. }
        | ResolvedType::TypeParam(_)
        | ResolvedType::External { .. }
        | ResolvedType::Closure { .. }
        | ResolvedType::Error => Err(LowerError::NotYetImplemented {
            what: format!("DictAccess on collection type {coll_ty:?}"),
        }),
    }
}

/// Synthesize a 2-tuple struct for a dictionary's `(key, value)`
/// pair — consumed by `plan_struct` to compute per-field offsets.
fn dict_pair_struct(key_ty: &ResolvedType, value_ty: &ResolvedType) -> IrStruct {
    use formalang::ast::ParamConvention;
    use formalang::ast::Visibility;
    use formalang::ir::IrSpan;
    let field = |name: &str, ty: ResolvedType| IrField {
        name: name.to_owned(),
        ty,
        mutable: false,
        optional: false,
        default: None,
        doc: None,
        convention: ParamConvention::Let,
        span: IrSpan::default(),
    };
    IrStruct {
        name: "__dict_pair".to_owned(),
        visibility: Visibility::Private,
        traits: Vec::new(),
        fields: vec![field("k", key_ty.clone()), field("v", value_ty.clone())],
        generic_params: Vec::new(),
        doc: None,
        span: IrSpan::default(),
    }
}

/// Lower a `Dictionary<K, V>` lookup as a linear scan.
///
/// Phase 2 v1 represents the dictionary as `{ ptr, len, cap }` plus a
/// buffer of pointers, each pointing to a heap-allocated `(k: K,
/// v: V)` pair tuple. The lookup walks the buffer comparing every
/// pair's key against the lookup key and returns the matching value.
/// A miss traps via `unreachable` — Phase 2 has no panic-runtime story
/// yet, so absent keys aren't recoverable.
///
/// String keys compare via `__str_eq`. Other key types stay
/// unimplemented for v1 — formalang's typical dictionary literals
/// use string keys so this covers the milestone case.
#[expect(
    clippy::too_many_lines,
    reason = "single self-contained linear-scan loop; splitting hides the block / loop / br_if structure"
)]
fn lower_dict_lookup(
    dict: &IrExpr,
    key: &IrExpr,
    key_ty: &ResolvedType,
    value_ty: &ResolvedType,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    use formalang::ast::PrimitiveType;
    use wasm_encoder::BlockType;

    if !matches!(key_ty, ResolvedType::Primitive(PrimitiveType::String)) {
        return Err(LowerError::NotYetImplemented {
            what: format!("Dictionary lookup with key type {key_ty:?} (Phase 2 v1: String only)"),
        });
    }
    let value_prim = primitive_of(value_ty).map_err(|_| LowerError::NotYetImplemented {
        what: format!("Dictionary value type {value_ty:?} (Phase 2 v1: primitive only)"),
    })?;
    if matches!(value_prim, PrimitiveType::Never) {
        return Err(LowerError::NotYetImplemented {
            what: "Dictionary value type Never".to_owned(),
        });
    }
    let module = ctx.module()?;
    let pair_struct = dict_pair_struct(key_ty, value_ty);
    let pair_layout = plan_struct(&pair_struct, module)?;
    let value_field_layout =
        pair_layout
            .fields
            .get(1)
            .copied()
            .ok_or_else(|| LowerError::NotYetImplemented {
                what: "dict pair tuple has fewer than two fields".to_owned(),
            })?;
    let value_block_ty = match value_prim {
        // Strings / paths / regexes ride the same i32-pointer
        // representation as the numeric primitives that fit in i32,
        // so they share the BlockType::Result(I32) branch.
        PrimitiveType::Boolean
        | PrimitiveType::I32
        | PrimitiveType::String
        | PrimitiveType::Path
        | PrimitiveType::Regex => BlockType::Result(ValType::I32),
        PrimitiveType::I64 => BlockType::Result(ValType::I64),
        PrimitiveType::F32 => BlockType::Result(ValType::F32),
        PrimitiveType::F64 => BlockType::Result(ValType::F64),
        PrimitiveType::Never | _ => {
            return Err(LowerError::NotYetImplemented {
                what: format!("Dictionary value primitive {value_prim:?}"),
            });
        }
    };

    let str_eq_idx = ctx.str_eq_index()?;

    // Reserve scratch locals: dict header ptr, buffer ptr, len,
    // loop counter, target key, current pair pointer.
    let dict_local = ctx.next_scratch_local(ValType::I32)?;
    let buf_local = ctx.next_scratch_local(ValType::I32)?;
    let len_local = ctx.next_scratch_local(ValType::I32)?;
    let i_local = ctx.next_scratch_local(ValType::I32)?;
    let target_local = ctx.next_scratch_local(ValType::I32)?;
    let pair_local = ctx.next_scratch_local(ValType::I32)?;

    lower_expr(dict, sink, ctx)?;
    sink.local_set(dict_local);

    sink.local_get(dict_local);
    sink.i32_load(MemArg {
        offset: u64::from(ARRAY_HEADER_PTR_OFFSET),
        align: align_to_log2(ARRAY_HEADER_ALIGN),
        memory_index: MEMORY_INDEX,
    });
    sink.local_set(buf_local);

    sink.local_get(dict_local);
    sink.i32_load(MemArg {
        offset: u64::from(ARRAY_HEADER_LEN_OFFSET),
        align: align_to_log2(ARRAY_HEADER_ALIGN),
        memory_index: MEMORY_INDEX,
    });
    sink.local_set(len_local);

    lower_expr(key, sink, ctx)?;
    sink.local_set(target_local);

    sink.i32_const(0);
    sink.local_set(i_local);

    // block $found (result: V's value type)
    //   loop $scan
    //     if i >= len { unreachable }   ;; not-found path traps
    //     pair = buf[i]
    //     if __str_eq(pair.k, target) {
    //       <load pair.v>
    //       br $found
    //     }
    //     i += 1
    //     br $scan
    //   end
    // end
    sink.block(value_block_ty);
    sink.loop_(BlockType::Empty);

    // Termination check — falling off `len` traps.
    sink.local_get(i_local);
    sink.local_get(len_local);
    sink.i32_ge_u();
    sink.if_(BlockType::Empty);
    sink.unreachable();
    sink.end();

    // Load pair pointer at buf + i*4.
    sink.local_get(buf_local);
    sink.local_get(i_local);
    sink.i32_const(4);
    sink.i32_mul();
    sink.i32_add();
    sink.i32_load(MemArg {
        offset: 0,
        align: 2,
        memory_index: MEMORY_INDEX,
    });
    sink.local_set(pair_local);

    // Compare keys: __str_eq(pair.k, target).
    sink.local_get(pair_local);
    sink.i32_load(MemArg {
        offset: 0, // k at pair offset 0 (first field of pair tuple)
        align: 2,
        memory_index: MEMORY_INDEX,
    });
    sink.local_get(target_local);
    sink.call(str_eq_idx);
    sink.if_(BlockType::Empty);
    // Match: leave value on stack, br to $found (depth 2: out of `if`,
    // out of `loop`, into `block`).
    sink.local_get(pair_local);
    load_primitive(value_prim, value_field_layout, sink);
    sink.br(2);
    sink.end();

    // i += 1; br loop
    sink.local_get(i_local);
    sink.i32_const(1);
    sink.i32_add();
    sink.local_set(i_local);
    sink.br(0);

    sink.end(); // close loop
    // Falling off the loop's end is statically unreachable (the body
    // always ends in `br 0`), but wasm's validator doesn't perform
    // that dataflow analysis. Emit `unreachable` after the loop so
    // the outer block's `i32` result-type is satisfied via the
    // validator's polymorphic-after-unreachable rule.
    sink.unreachable();
    sink.end(); // close block (value already pushed via br on match)
    Ok(())
}

fn lower_array_index(
    dict: &IrExpr,
    key: &IrExpr,
    elem_ty: &ResolvedType,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let module = ctx.module()?;
    let layout = plan_array(elem_ty, module)?;
    let elem_size_signed =
        i32::try_from(layout.element_size).map_err(|_| LayoutError::SizeOverflow {
            name: "<array element>".to_owned(),
        })?;

    lower_expr(dict, sink, ctx)?;
    sink.i32_load(MemArg {
        offset: u64::from(ARRAY_HEADER_PTR_OFFSET),
        align: align_to_log2(ARRAY_HEADER_ALIGN),
        memory_index: MEMORY_INDEX,
    });

    lower_expr(key, sink, ctx)?;
    sink.i32_const(elem_size_signed);
    sink.i32_mul();
    sink.i32_add();

    let field_layout = FieldLayout {
        offset: 0,
        size: layout.element_size,
        align: layout.element_align,
    };
    load_array_element(elem_ty, field_layout, sink)
}

/// Emit the `load` opcode that reads one array element at the address
/// already on the stack, given the element's resolved type. Mirrors
/// [`store_array_element`].
fn load_array_element(
    elem_ty: &ResolvedType,
    field_layout: FieldLayout,
    sink: &mut InstructionSink<'_>,
) -> Result<(), LowerError> {
    match elem_ty {
        ResolvedType::Primitive(p) => {
            load_primitive(*p, field_layout, sink);
            Ok(())
        }
        // After 0.0.4-beta, the four prelude compounds collapse into
        // `Generic { .. }`. Every aggregate element loads as an i32
        // pointer.
        ResolvedType::Struct(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Generic { .. } => {
            sink.i32_load(field_mem_arg(field_layout));
            Ok(())
        }
        ResolvedType::Closure { .. }
        | ResolvedType::Trait(_)
        | ResolvedType::TypeParam(_)
        | ResolvedType::External { .. }
        | ResolvedType::Error => Err(LowerError::NotYetImplemented {
            what: format!("array element of type {elem_ty:?}"),
        }),
    }
}

/// Lower a `BinaryOp { op: Range, left, right }` expression.
///
/// Allocates a `Range<T>` value as a two-field aggregate
/// `{ start: T, end: T }` in linear memory:
///
/// 1. Plan the range layout via [`plan_range`] from the expression's
///    declared element type.
/// 2. Allocate `layout.size` bytes through the bump allocator and
///    park the base pointer in a fresh scratch local.
/// 3. Lower `left`, store at `start_offset = 0`. Lower `right`, store
///    at `layout.end_offset`. Both stores use the primitive width
///    appropriate to the bound type.
/// 4. Leave the base pointer on the stack as the range value.
///
/// The element type must be a primitive (validated upstream by
/// [`plan_range`]); aggregate-bound ranges surface as
/// [`LayoutError::NotYetSupported`].
pub fn lower_range(
    elem_ty: &ResolvedType,
    left: &IrExpr,
    right: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let module = ctx.module()?;
    let layout = plan_range(elem_ty, module)?;
    let primitive = primitive_of(elem_ty)?;

    let base_local = allocate_aggregate(layout.size, sink, ctx)?;

    // start at offset 0
    sink.local_get(base_local);
    lower_expr(left, sink, ctx)?;
    store_primitive(primitive, range_field_layout(layout, 0), sink);

    // end at offset `layout.end_offset`
    sink.local_get(base_local);
    lower_expr(right, sink, ctx)?;
    store_primitive(
        primitive,
        range_field_layout(layout, layout.end_offset),
        sink,
    );

    sink.local_get(base_local);
    Ok(())
}

/// Build the synthetic [`FieldLayout`] for `start` / `end` slots given
/// a [`RangeLayout`] and the bound's offset.
const fn range_field_layout(layout: RangeLayout, offset: u32) -> FieldLayout {
    FieldLayout {
        offset,
        size: layout.bound_size,
        align: layout.bound_align,
    }
}

/// Lower [`IrExpr::SelfFieldRef`].
///
/// Reads the field at the resolved offset through `self`, which lives
/// at wasm-local 0 (the implicit first parameter on every method).
/// The enclosing impl's struct id comes from
/// [`LowerContext::self_struct_id`]; the field's primitive type comes
/// from the carried `ty`.
pub fn lower_self_field_ref(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::SelfFieldRef { field, .. } = expr else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_self_field_ref called with non-SelfFieldRef expression".to_owned(),
        });
    };

    let struct_id = ctx.self_struct_id.ok_or(LowerError::MissingSelfStruct)?;
    let module = ctx.module()?;
    let s = module
        .structs
        .get(struct_id.0 as usize)
        .ok_or(LowerError::UnknownStruct(struct_id))?;
    let layout = plan_struct(s, module)?;

    // The frontend emits `FieldIdx(0)` as a placeholder on every
    // `SelfFieldRef`, so resolving by index would silently pick the
    // first field. The carried `field` name is authoritative.
    let (field_layout, field_def) = lookup_field_by_name(s, &layout.fields, field)?;

    let primitive = primitive_of(&field_def.ty)?;
    // `self` is the first wasm parameter — local index 0.
    sink.local_get(0);
    load_primitive(primitive, *field_layout, sink);
    Ok(())
}

/// Lower [`IrExpr::FieldAccess`].
///
/// Evaluates `object` to leave its base pointer on the stack, then
/// emits the primitive load at the resolved field's offset. Works
/// for both struct objects (`ResolvedType::Struct(_)`) and tuple
/// objects (`ResolvedType::Tuple(_)`).
pub fn lower_field_access(
    expr: &IrExpr,
    sink: &mut InstructionSink<'_>,
    ctx: &LowerContext<'_>,
) -> Result<(), LowerError> {
    let IrExpr::FieldAccess { object, field, .. } = expr else {
        return Err(LowerError::NotYetImplemented {
            what: "lower_field_access called with non-FieldAccess expression".to_owned(),
        });
    };

    let module = ctx.module()?;
    let (layout, fields_meta) = layout_for_aggregate(object.ty(), module)?;

    // The frontend often leaves `field_idx` as a `FieldIdx(0)`
    // placeholder, so resolving by index would silently pick the
    // first field. The carried `field` name is authoritative for
    // both structs and tuples (tuple synthetic fields use the
    // positional names "0"/"1"/...).
    let (field_layout, field_def) = lookup_field_by_name_with_meta(
        &fields_meta,
        &layout.fields,
        field,
        &type_tag(object.ty()),
    )?;

    // Aggregate field types (Optional<T>, Struct, Tuple, …) live as
    // a heap-pointer cell at the field's offset; primitive fields
    // load through `load_primitive` at the matching width. Choose
    // by classifying `field_def.ty`: anything that lowers to an
    // `i32` body-value is a pointer cell.
    lower_expr(object, sink, ctx)?;
    if let Ok(prim) = primitive_of(&field_def.ty) {
        load_primitive(prim, *field_layout, sink);
    } else {
        // Pointer-typed field (Optional, Array, Range, Dictionary,
        // Struct, Enum, Tuple, Closure, Trait). The store path
        // wrote an `i32` here via `i32_store(field_mem_arg(...))`,
        // so the load mirrors that.
        sink.i32_load(field_mem_arg(*field_layout));
    }
    Ok(())
}

/// Plan the layout for an aggregate object expression and return its
/// field metadata. Tuple objects are mapped to a synthetic struct so
/// `plan_struct` can reused.
pub(super) fn layout_for_aggregate(
    ty: &ResolvedType,
    module: &IrModule,
) -> Result<(StructLayout, Vec<IrField>), LowerError> {
    // Resolve the struct id transparently through
    // `Generic { base: Struct(_) }` so user generics
    // monomorphised to a concrete struct keep working when the IR
    // surfaces them in the post-0.0.4-beta `Generic` shape rather
    // than the bare `Struct(id)` form.
    if let Some(id) = crate::compound::struct_id_of(ty) {
        let s = module
            .structs
            .get(id.0 as usize)
            .ok_or(LowerError::UnknownStruct(id))?;
        let layout = plan_struct(s, module)?;
        return Ok((layout, s.fields.clone()));
    }
    match ty {
        ResolvedType::Tuple(_) => {
            let synthetic = synthetic_struct_for_tuple(ty)?;
            let layout = plan_struct(&synthetic, module)?;
            Ok((layout, synthetic.fields))
        }
        ResolvedType::Primitive(_)
        | ResolvedType::Trait(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Struct(_)
        | ResolvedType::Generic { .. }
        | ResolvedType::TypeParam(_)
        | ResolvedType::External { .. }
        | ResolvedType::Closure { .. }
        | ResolvedType::Error => Err(LowerError::FieldAccessOnNonAggregate { ty: ty.clone() }),
    }
}

/// Build a synthetic [`IrStruct`] from a `ResolvedType::Tuple(...)`.
/// Lets the layout planner be reused for tuples without duplicating
/// its alignment logic.
pub(crate) fn synthetic_struct_for_tuple(ty: &ResolvedType) -> Result<IrStruct, LowerError> {
    let ResolvedType::Tuple(fields) = ty else {
        return Err(LowerError::FieldAccessOnNonAggregate { ty: ty.clone() });
    };
    Ok(IrStruct {
        name: "__tuple".to_owned(),
        visibility: formalang::ast::Visibility::Private,
        traits: Vec::new(),
        fields: fields
            .iter()
            .map(|(field_name, field_ty)| IrField {
                name: field_name.clone(),
                ty: field_ty.clone(),
                mutable: false,
                optional: false,
                default: None,
                doc: None,
                convention: formalang::ast::ParamConvention::Let,
                span: formalang::ir::IrSpan::default(),
            })
            .collect(),
        generic_params: Vec::new(),
        doc: None,
        span: formalang::ir::IrSpan::default(),
    })
}

/// Resolve a field by name once we already have the field-meta and
/// layout vectors. Used as a fallback when `FieldIdx` is out of
/// range — kept robust to placeholder IDs that older IR emitters
/// produce.
pub(super) fn lookup_field_by_name_with_meta<'a>(
    fields_meta: &'a [IrField],
    field_layouts: &'a [FieldLayout],
    name: &str,
    aggregate_tag: &str,
) -> Result<(&'a FieldLayout, &'a IrField), LowerError> {
    for (i, f) in fields_meta.iter().enumerate() {
        if f.name == name {
            let fl = field_layouts
                .get(i)
                .ok_or_else(|| LowerError::FieldIndexOutOfRange {
                    struct_name: aggregate_tag.to_owned(),
                    field_count: fields_meta.len(),
                    field_idx: u32::try_from(i).unwrap_or(u32::MAX),
                })?;
            return Ok((fl, f));
        }
    }
    Err(LowerError::FieldIndexOutOfRange {
        struct_name: aggregate_tag.to_owned(),
        field_count: fields_meta.len(),
        field_idx: u32::MAX,
    })
}

fn type_tag(ty: &ResolvedType) -> String {
    match ty {
        ResolvedType::Struct(_) => "<struct>".to_owned(),
        ResolvedType::Tuple(_) => "__tuple".to_owned(),
        ResolvedType::Primitive(_)
        | ResolvedType::Trait(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Generic { .. }
        | ResolvedType::TypeParam(_)
        | ResolvedType::External { .. }
        | ResolvedType::Closure { .. }
        | ResolvedType::Error => "<non-aggregate>".to_owned(),
    }
}

/// Translate a [`FieldLayout`] into a wasm `MemArg`. The `align`
/// field encodes the *log2* of the alignment hint (0 for 1-byte, 2
/// for 4-byte, 3 for 8-byte). `MemArg::offset` is the byte offset
/// added to the base pointer at runtime.
pub(super) fn field_mem_arg(layout: FieldLayout) -> MemArg {
    MemArg {
        offset: u64::from(layout.offset),
        align: align_to_log2(layout.align),
        memory_index: MEMORY_INDEX,
    }
}

const fn align_to_log2(align: u32) -> u32 {
    match align {
        2 => 1,
        4 => 2,
        8 => 3,
        // 1 (and any non-power-of-two value, which our layout planner
        // never produces) gets the byte-alignment hint.
        _ => 0,
    }
}

/// Extract the primitive type of a field. Aggregate field types
/// surface as `LayoutError::NotYetSupported` through `plan_struct`
/// long before reaching this helper, so anything non-primitive here
/// indicates an upstream invariant break.
pub(super) fn primitive_of(ty: &ResolvedType) -> Result<PrimitiveType, LowerError> {
    match ty {
        ResolvedType::Primitive(p) => Ok(*p),
        ResolvedType::Struct(_)
        | ResolvedType::Trait(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Generic { .. }
        | ResolvedType::TypeParam(_)
        | ResolvedType::External { .. }
        | ResolvedType::Closure { .. }
        | ResolvedType::Error => Err(LowerError::FieldAccessOnNonAggregate { ty: ty.clone() }),
    }
}

/// Resolve a field by name in a struct that has already been laid
/// out. `StructInst.fields` carries `(name, FieldIdx, value)`
/// triples; the name lookup is robust to a `FieldIdx(0)` placeholder
/// from older IR-emitting code paths.
pub(super) fn lookup_field_by_name<'a>(
    s: &'a IrStruct,
    field_layouts: &'a [FieldLayout],
    name: &str,
) -> Result<(&'a FieldLayout, &'a formalang::ir::IrField), LowerError> {
    for (i, f) in s.fields.iter().enumerate() {
        if f.name == name {
            let fl = field_layouts
                .get(i)
                .ok_or_else(|| LowerError::FieldIndexOutOfRange {
                    struct_name: s.name.clone(),
                    field_count: s.fields.len(),
                    field_idx: u32::try_from(i).unwrap_or(u32::MAX),
                })?;
            return Ok((fl, f));
        }
    }
    Err(LowerError::FieldIndexOutOfRange {
        struct_name: s.name.clone(),
        field_count: s.fields.len(),
        field_idx: u32::MAX,
    })
}