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
//! Memory-layout planner for every type the backend lays out in
//! linear memory.
//!
//! One planner per type family: [`plan_struct`] for [`IrStruct`],
//! [`plan_enum`] for [`IrEnum`], [`plan_array`] / [`plan_range`] /
//! [`plan_optional`] / [`plan_string`] / [`plan_dictionary`] for the
//! corresponding `ResolvedType` shapes, and [`plan_vtable`] for
//! per-trait vtable blobs. Each planner produces a record describing
//! per-field offsets, total size, and alignment so the lowering
//! emits stable wasm `i32_load` / `i32_store` instructions against
//! known constants.
//!
//! All sizes follow the Component-Model canonical ABI:
//!
//! | type            | size | align |
//! | --------------- | ---: | ----: |
//! | `bool`          | 1    | 1     |
//! | `s32` / `f32`   | 4    | 4     |
//! | `s64` / `f64`   | 8    | 8     |
//!
//! Each field starts at the next offset rounded up to the field's
//! alignment; an aggregate's total size is rounded up to its own
//! alignment (the maximum of its field alignments, or 1 for an empty
//! aggregate). Aggregate-typed fields (nested struct / enum /
//! optional / array headers) lower as 4-byte pointers into the
//! pool of bump-allocated linear-memory regions.

use formalang::ast::{PrimitiveType, Visibility};
use formalang::ir::{IrEnum, IrModule, IrSpan, IrStruct, IrTrait, ResolvedType};
use thiserror::Error;

/// Errors produced by [`plan_struct`].
#[derive(Debug, Error)]
#[non_exhaustive]
pub enum LayoutError {
    /// A field's type is in scope for the backend but not yet wired
    /// into the layout planner. The variant name is carried as a
    /// string so the diagnostic still reads naturally after
    /// `ResolvedType` evolves.
    #[error("type {kind} is not yet supported by the struct-layout planner")]
    NotYetSupported {
        /// Short tag identifying the unsupported type kind
        /// (`"Struct"`, `"Tuple"`, `"Closure"`, …).
        kind: String,
    },

    /// The struct's total size — including alignment padding —
    /// exceeds `u32::MAX`. Linear-memory offsets are `u32` in core
    /// wasm so we cannot represent layouts larger than that.
    #[error("struct '{name}' size exceeds u32::MAX after alignment padding")]
    SizeOverflow {
        /// Source-level struct name.
        name: String,
    },

    /// An enum has more than `u32::MAX` variants. The discriminant tag
    /// is encoded as a 4-byte unsigned integer.
    #[error("enum '{name}' has more than u32::MAX variants")]
    TooManyVariants {
        /// Source-level enum name.
        name: String,
    },

    /// An enum has zero variants. Such an enum is uninhabited (no
    /// value can ever exist) and rejecting it here matches Rust's
    /// treatment of `enum Empty {}`.
    #[error("enum '{name}' is uninhabited (zero variants)")]
    UninhabitedEnum {
        /// Source-level enum name.
        name: String,
    },
}

/// Where a single field lives inside its containing struct.
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FieldLayout {
    /// Byte offset from the start of the struct.
    pub offset: u32,
    /// Field size in bytes (no alignment padding included).
    pub size: u32,
    /// Field alignment in bytes (always a power of two).
    pub align: u32,
}

/// Layout decisions for a whole `IrStruct`.
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct StructLayout {
    /// Total size in bytes, including any trailing alignment padding.
    pub size: u32,
    /// Struct alignment — the maximum of its field alignments, or 1
    /// for an empty struct.
    pub align: u32,
    /// One [`FieldLayout`] per field, in declaration order.
    pub fields: Vec<FieldLayout>,
}

/// Compute the layout of `s`.
///
/// `module` is accepted for API symmetry with the layout planners
/// added in later mcs (which need it to resolve nested struct/enum
/// references); the Phase 1b mc1 implementation only uses primitive
/// fields and therefore ignores it.
pub fn plan_struct(s: &IrStruct, _module: &IrModule) -> Result<StructLayout, LayoutError> {
    let mut offset: u32 = 0;
    let mut max_align: u32 = 1;
    let mut fields = Vec::with_capacity(s.fields.len());

    for f in &s.fields {
        // The `optional: bool` AST flag is redundant with
        // `ty: Optional<...>` (now under `ResolvedType::Generic`).
        // Phase 2 mc7 lifts the
        // outright rejection that came in as a defensive marker
        // before the optional layout existed; aggregate-as-pointer
        // storage handles either form uniformly.
        let (size, align) = type_size_align(&f.ty)?;
        let aligned = align_up(offset, align).ok_or_else(|| LayoutError::SizeOverflow {
            name: s.name.clone(),
        })?;
        let next_offset = aligned
            .checked_add(size)
            .ok_or_else(|| LayoutError::SizeOverflow {
                name: s.name.clone(),
            })?;

        fields.push(FieldLayout {
            offset: aligned,
            size,
            align,
        });
        offset = next_offset;
        if align > max_align {
            max_align = align;
        }
    }

    let total_size = align_up(offset, max_align).ok_or_else(|| LayoutError::SizeOverflow {
        name: s.name.clone(),
    })?;

    Ok(StructLayout {
        size: total_size,
        align: max_align,
        fields,
    })
}

/// Return the `(size, align)` pair for a primitive-typed field.
///
/// String / Path / Regex are stored as 4-byte pointers to their
/// `{ ptr, len }` headers in linear memory; `Never` stays rejected
/// (uninhabited — no instance can ever be laid out).
fn primitive_size_align(p: PrimitiveType) -> Result<(u32, u32), LayoutError> {
    match p {
        PrimitiveType::Boolean => Ok((1, 1)),
        PrimitiveType::I32 | PrimitiveType::F32 => Ok((4, 4)),
        PrimitiveType::I64 | PrimitiveType::F64 => Ok((8, 8)),
        // Strings, paths, and regexes all share the same in-memory
        // representation — a pointer to a heap-allocated header.
        PrimitiveType::String | PrimitiveType::Path | PrimitiveType::Regex => {
            Ok((POINTER_SIZE, POINTER_ALIGN))
        }
        // Never is uninhabited; future #[non_exhaustive] variants
        // ride this arm too.
        PrimitiveType::Never | _ => Err(LayoutError::NotYetSupported {
            kind: format!("{p:?}"),
        }),
    }
}

/// Return the `(size, align)` pair for a [`ResolvedType`] used as a
/// struct field type.
///
/// `Optional<T>` collapses to a 4-byte pointer payload — the
/// underlying tagged cell lives in a separately-allocated linear-
/// memory region. Other aggregate field types (Struct / Enum /
/// Tuple / Array nested directly inside a struct field slot) stay
/// rejected pending the matching nested-aggregate-field mc.
fn type_size_align(ty: &ResolvedType) -> Result<(u32, u32), LayoutError> {
    match ty {
        ResolvedType::Primitive(p) => primitive_size_align(*p),
        // Every aggregate field — struct, enum, tuple, plus the four
        // prelude compounds (Optional / Array / Range / Dictionary,
        // now living under `Generic`) — collapses to a 4-byte heap
        // pointer. The bump allocator owns the storage.
        // Every aggregate field — struct, enum, tuple, the four
        // prelude compounds (Optional / Array / Range / Dictionary)
        // under `Generic`, closure-typed fields (4-byte pointer to
        // an 8-byte `(funcref_idx, env_ptr)` cell — see
        // `lower_closure_ref`; closures crossing the WIT boundary
        // are rejected upstream by `preflight::check`), and
        // trait-typed locals (4-byte pointer to an 8-byte
        // `(vtable_offset, data_ptr)` cell) — collapses to a
        // 4-byte heap pointer. The bump allocator owns the
        // storage.
        ResolvedType::Struct(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Generic { .. }
        | ResolvedType::Closure { .. }
        | ResolvedType::Trait(_) => Ok((POINTER_SIZE, POINTER_ALIGN)),
        ResolvedType::TypeParam(name) => Err(LayoutError::NotYetSupported {
            kind: format!("TypeParam({name})"),
        }),
        ResolvedType::External { name, .. } => Err(LayoutError::NotYetSupported {
            kind: format!(
                "External({name}) — should have been inlined by upstream MonomorphisePass; reaching the backend means an upstream invariant violation"
            ),
        }),
        ResolvedType::Error => Err(LayoutError::NotYetSupported {
            kind: "Error".to_owned(),
        }),
    }
}

/// Round `offset` up to the next multiple of `align`.
///
/// Returns `None` on overflow. `align` is required to be a power of
/// two (all our supported alignments — 1, 4, 8 — satisfy this); the
/// helper silently treats non-power-of-two alignments as a no-op
/// once `align <= 1`, which is the only sentinel callers actually
/// pass.
fn align_up(offset: u32, align: u32) -> Option<u32> {
    if align <= 1 {
        return Some(offset);
    }
    let mask = align.checked_sub(1)?;
    let added = offset.checked_add(mask)?;
    Some(added & !mask)
}

// ── enum layout ──────────────────────────────────────────────────────

/// Discriminant-tag size in bytes. The tag occupies a `u32` slot at
/// offset 0 of every enum value.
pub const ENUM_TAG_SIZE: u32 = 4;

/// Discriminant-tag alignment.
pub const ENUM_TAG_ALIGN: u32 = 4;

/// Layout for one variant inside an [`EnumLayout`].
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct VariantLayout {
    /// Source-level variant name (preserved for diagnostics).
    pub name: String,
    /// Discriminant value stored in the tag slot when this variant is
    /// active. Variants are tagged in declaration order starting at 0.
    pub tag: u32,
    /// Per-payload-field offsets, **absolute** from the enum value's
    /// base pointer (i.e. already past the tag and any post-tag
    /// alignment padding). Empty for unit variants.
    pub fields: Vec<FieldLayout>,
}

/// Layout decisions for a whole [`IrEnum`].
///
/// Uniform-variant policy: every variant occupies exactly the same
/// number of bytes — the maximum across variants — so the constructor
/// site doesn't need to know which variant is being built when
/// computing the allocation size. This trades memory for code-size
/// simplicity, which suits Phase 1b where allocations are infrequent.
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct EnumLayout {
    /// Total bytes one enum value occupies. Includes the tag, post-
    /// tag alignment padding, payload, and trailing alignment padding.
    pub size: u32,
    /// Enum alignment — the maximum of [`ENUM_TAG_ALIGN`] and every
    /// variant payload's alignment.
    pub align: u32,
    /// Offset of the discriminant tag (always 0).
    pub tag_offset: u32,
    /// Offset where every variant's payload starts. `tag_offset +
    /// ENUM_TAG_SIZE`, rounded up to the max payload alignment.
    pub payload_offset: u32,
    /// One [`VariantLayout`] per variant, in declaration order.
    pub variants: Vec<VariantLayout>,
}

/// Compute the layout of `e`.
///
/// Each variant's payload is laid out via the same canonical-ABI
/// rules as a struct (see [`plan_struct`]) — field offsets within a
/// variant payload are then offset by `payload_offset` to become
/// absolute. Unit variants have no fields and therefore no
/// per-variant offsets; their slot is just the tag plus enough
/// padding to match the enum's overall size.
pub fn plan_enum(e: &IrEnum, module: &IrModule) -> Result<EnumLayout, LayoutError> {
    if e.variants.is_empty() {
        return Err(LayoutError::UninhabitedEnum {
            name: e.name.clone(),
        });
    }

    // Step 1: lay out each variant's payload as a sub-struct so we
    // can reuse `plan_struct`. The placeholder enum name is appended
    // for clearer error reporting.
    let mut variant_payloads = Vec::with_capacity(e.variants.len());
    let mut max_payload_align: u32 = 1;
    let mut max_payload_size: u32 = 0;
    for variant in &e.variants {
        let placeholder = IrStruct {
            name: format!("{}::{}", e.name, variant.name),
            visibility: Visibility::Private,
            traits: Vec::new(),
            fields: variant.fields.clone(),
            generic_params: Vec::new(),
            doc: None,
            span: IrSpan::default(),
        };
        let payload = plan_struct(&placeholder, module)?;
        if payload.align > max_payload_align {
            max_payload_align = payload.align;
        }
        if payload.size > max_payload_size {
            max_payload_size = payload.size;
        }
        variant_payloads.push(payload);
    }

    let enum_align = if max_payload_align > ENUM_TAG_ALIGN {
        max_payload_align
    } else {
        ENUM_TAG_ALIGN
    };
    let payload_offset =
        align_up(ENUM_TAG_SIZE, max_payload_align).ok_or_else(|| LayoutError::SizeOverflow {
            name: e.name.clone(),
        })?;
    let raw_size = payload_offset
        .checked_add(max_payload_size)
        .ok_or_else(|| LayoutError::SizeOverflow {
            name: e.name.clone(),
        })?;
    let total_size = align_up(raw_size, enum_align).ok_or_else(|| LayoutError::SizeOverflow {
        name: e.name.clone(),
    })?;

    let mut variants = Vec::with_capacity(e.variants.len());
    for (i, (variant, payload)) in e
        .variants
        .iter()
        .zip(variant_payloads.into_iter())
        .enumerate()
    {
        let tag = u32::try_from(i).map_err(|_| LayoutError::TooManyVariants {
            name: e.name.clone(),
        })?;
        let mut absolute_fields = Vec::with_capacity(payload.fields.len());
        for field in &payload.fields {
            let abs_offset = payload_offset.checked_add(field.offset).ok_or_else(|| {
                LayoutError::SizeOverflow {
                    name: e.name.clone(),
                }
            })?;
            absolute_fields.push(FieldLayout {
                offset: abs_offset,
                size: field.size,
                align: field.align,
            });
        }
        variants.push(VariantLayout {
            name: variant.name.clone(),
            tag,
            fields: absolute_fields,
        });
    }

    Ok(EnumLayout {
        size: total_size,
        align: enum_align,
        tag_offset: 0,
        payload_offset,
        variants,
    })
}

// ── array layout ─────────────────────────────────────────────────────

/// Header size of an array value: `{ ptr: i32, len: i32, cap: i32 }`.
pub const ARRAY_HEADER_SIZE: u32 = 12;

/// Header alignment of an array value (each header field is `i32`).
pub const ARRAY_HEADER_ALIGN: u32 = 4;

/// Byte offset of the buffer pointer field inside an array header.
pub const ARRAY_HEADER_PTR_OFFSET: u32 = 0;

/// Byte offset of the length field inside an array header.
pub const ARRAY_HEADER_LEN_OFFSET: u32 = 4;

/// Byte offset of the capacity field inside an array header.
pub const ARRAY_HEADER_CAP_OFFSET: u32 = 8;

/// Pointer size used for aggregate element types.
pub(crate) const POINTER_SIZE: u32 = 4;

/// Pointer alignment used for aggregate element types.
const POINTER_ALIGN: u32 = 4;

/// Layout decisions for an `Array<T>` value.
///
/// An array splits across two allocations: a fixed-size header
/// (`{ ptr, len, cap }`) and a separately-allocated element buffer
/// pointed to by `ptr`. The header always lives at a 4-byte alignment;
/// the element buffer's stride/alignment depends on `T`.
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ArrayLayout {
    /// Bytes occupied by the header. Always [`ARRAY_HEADER_SIZE`].
    pub header_size: u32,
    /// Header alignment in bytes. Always [`ARRAY_HEADER_ALIGN`].
    pub header_align: u32,
    /// Size in bytes of one element in the buffer. Aggregate elements
    /// are stored as `i32` pointers, so they always occupy 4 bytes
    /// regardless of the underlying type's struct size.
    pub element_size: u32,
    /// Alignment in bytes of one element in the buffer.
    pub element_align: u32,
}

/// Compute the layout of `Array<elem>`.
///
/// `module` is accepted for API symmetry with the struct/enum
/// planners; the current implementation only inspects `elem`.
///
/// Aggregate element types (struct, enum, tuple, …) lower as `i32`
/// pointers into the element buffer — the actual aggregate value lives
/// in a separate bump-allocated region. Primitives are stored inline
/// at their canonical-ABI size and alignment. `Never` and the
/// heap-typed primitives surface as
/// [`LayoutError::NotYetSupported`] just as they do for struct fields.
pub fn plan_array(elem: &ResolvedType, _module: &IrModule) -> Result<ArrayLayout, LayoutError> {
    let (element_size, element_align) = array_element_size_align(elem)?;
    Ok(ArrayLayout {
        header_size: ARRAY_HEADER_SIZE,
        header_align: ARRAY_HEADER_ALIGN,
        element_size,
        element_align,
    })
}

// ── range layout ─────────────────────────────────────────────────────

/// Layout decisions for a `Range<T>` value.
///
/// A range is a two-field struct `{ start: T, end: T }` laid out
/// contiguously in linear memory. Phase 1c restricts `T` to primitive
/// numeric types (the only kinds that have an ordering sensible enough
/// for `..` and the `For`-loop iteration the sieve relies on).
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RangeLayout {
    /// Total bytes one range value occupies, including any trailing
    /// alignment padding.
    pub size: u32,
    /// Range alignment (== bound alignment).
    pub align: u32,
    /// Size of one bound (`start` or `end`) in bytes.
    pub bound_size: u32,
    /// Alignment of one bound in bytes.
    pub bound_align: u32,
    /// Byte offset where `end` lives relative to the range's base.
    /// `start` is always at offset 0.
    pub end_offset: u32,
}

/// Compute the layout of `Range<bound>`.
///
/// `module` is accepted for API symmetry with the struct/enum/array
/// planners; the current implementation only inspects `bound`.
///
/// The bound type must be a primitive — aggregates (and the still-
/// unsupported heap-typed primitives) surface as
/// [`LayoutError::NotYetSupported`]. Boolean is technically permitted
/// because it has a primitive layout, even if `false..true` is
/// semantically odd.
pub fn plan_range(bound: &ResolvedType, _module: &IrModule) -> Result<RangeLayout, LayoutError> {
    let (bound_size, bound_align) = match bound {
        ResolvedType::Primitive(p) => primitive_size_align(*p)?,
        ResolvedType::Struct(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Closure { .. }
        | ResolvedType::Trait(_)
        | ResolvedType::Generic { .. }
        | ResolvedType::TypeParam(_)
        | ResolvedType::External { .. }
        | ResolvedType::Error => {
            return Err(LayoutError::NotYetSupported {
                kind: format!("Range<{bound:?}>"),
            });
        }
    };

    let end_offset =
        align_up(bound_size, bound_align).ok_or_else(|| LayoutError::SizeOverflow {
            name: "<range>".to_owned(),
        })?;
    let raw_size = end_offset
        .checked_add(bound_size)
        .ok_or_else(|| LayoutError::SizeOverflow {
            name: "<range>".to_owned(),
        })?;
    let size = align_up(raw_size, bound_align).ok_or_else(|| LayoutError::SizeOverflow {
        name: "<range>".to_owned(),
    })?;

    Ok(RangeLayout {
        size,
        align: bound_align,
        bound_size,
        bound_align,
        end_offset,
    })
}

// ── dictionary layout ────────────────────────────────────────────────

/// Header size of a dictionary value: `{ ptr: i32, len: i32, cap: i32 }`.
///
/// Phase 2 v1 represents `Dictionary<K, V>` as a sorted-pairs-array
/// — the same shape `Array<Tuple<(K, V)>>` would lower to. Each entry
/// in the buffer is an `i32` pointer to a freshly-allocated `(k: K,
/// v: V)` pair tuple. Lookup walks the buffer linearly comparing
/// keys; insertion order is preserved (Phase 2 doesn't yet sort).
pub const DICTIONARY_HEADER_SIZE: u32 = ARRAY_HEADER_SIZE;

/// Header alignment of a dictionary value (always 4).
pub const DICTIONARY_HEADER_ALIGN: u32 = ARRAY_HEADER_ALIGN;

/// Layout decisions for a `Dictionary<K, V>` value.
///
/// The underlying buffer-of-pair-pointers is identical to the
/// `Array<Tuple<(K, V)>>` storage: each slot is a 4-byte i32 pointer
/// to a per-entry pair tuple in linear memory.
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DictionaryLayout {
    /// Bytes occupied by the header. Always
    /// [`DICTIONARY_HEADER_SIZE`].
    pub header_size: u32,
    /// Header alignment. Always [`DICTIONARY_HEADER_ALIGN`].
    pub header_align: u32,
    /// Per-entry size in the buffer — always `POINTER_SIZE` (4)
    /// since each slot holds an `i32` pointer to the pair tuple.
    pub entry_size: u32,
    /// Per-entry alignment in the buffer.
    pub entry_align: u32,
}

/// Compute the layout of `Dictionary<key, value>`.
///
/// Today the layout is fixed regardless of the key/value types — the
/// per-entry buffer slot is always a pointer. The arguments are
/// accepted for forward compatibility with later layout strategies
/// (small-string-optimization key inlining, etc.).
#[must_use]
pub const fn plan_dictionary(
    _key_ty: &ResolvedType,
    _value_ty: &ResolvedType,
    _module: &IrModule,
) -> DictionaryLayout {
    DictionaryLayout {
        header_size: DICTIONARY_HEADER_SIZE,
        header_align: DICTIONARY_HEADER_ALIGN,
        entry_size: POINTER_SIZE,
        entry_align: POINTER_ALIGN,
    }
}

// ── string layout ────────────────────────────────────────────────────

/// Header size of a string value: `{ ptr: i32, len: i32 }`.
///
/// Strings are immutable in formalang — there is no `cap` slot.
/// Concatenation always allocates a fresh header pointing at a freshly
/// allocated byte buffer; Phase 2's literal-seeding path points the
/// header at a data-section offset.
pub const STRING_HEADER_SIZE: u32 = 8;

/// Header alignment of a string value (each header field is `i32`).
pub const STRING_HEADER_ALIGN: u32 = 4;

/// Byte offset of the buffer pointer inside a string header.
pub const STRING_PTR_OFFSET: u32 = 0;

/// Byte offset of the byte-length field inside a string header.
pub const STRING_LEN_OFFSET: u32 = 4;

/// Layout decisions for a `String` value.
///
/// A string splits across two allocations: a fixed-size header
/// (`{ ptr, len }`) and a separately-stored byte buffer pointed to by
/// `ptr`. Literals seed their bytes into the data section and the
/// header points at the data-section offset; runtime-built strings
/// (concatenation results, host inputs lifted at the boundary) bump-
/// allocate the buffer.
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct StringLayout {
    /// Bytes occupied by the header. Always [`STRING_HEADER_SIZE`].
    pub header_size: u32,
    /// Header alignment in bytes. Always [`STRING_HEADER_ALIGN`].
    pub header_align: u32,
    /// Byte offset of the buffer pointer field (always
    /// [`STRING_PTR_OFFSET`]).
    pub ptr_offset: u32,
    /// Byte offset of the byte-length field (always
    /// [`STRING_LEN_OFFSET`]).
    pub len_offset: u32,
}

/// Compute the layout of a `String` value.
///
/// `module` is accepted for API symmetry with the other layout
/// planners; the current implementation produces the same fixed
/// layout for every string and ignores it.
#[must_use]
pub const fn plan_string(_module: &IrModule) -> StringLayout {
    StringLayout {
        header_size: STRING_HEADER_SIZE,
        header_align: STRING_HEADER_ALIGN,
        ptr_offset: STRING_PTR_OFFSET,
        len_offset: STRING_LEN_OFFSET,
    }
}

// ── optional layout ──────────────────────────────────────────────────

/// Discriminant-tag size in bytes for an `Optional<T>` value. The tag
/// occupies a `u32` slot at offset 0 and uses [`OPTIONAL_TAG_NIL`] /
/// [`OPTIONAL_TAG_SOME`] as its two values.
pub const OPTIONAL_TAG_SIZE: u32 = 4;

/// Discriminant-tag alignment for an `Optional<T>` value.
pub const OPTIONAL_TAG_ALIGN: u32 = 4;

/// Discriminant-tag value for the `nil` payload-absent case.
pub const OPTIONAL_TAG_NIL: u32 = 0;

/// Discriminant-tag value for the payload-present (`Some`) case.
pub const OPTIONAL_TAG_SOME: u32 = 1;

/// Layout decisions for an `Optional<T>` value.
///
/// Optional is laid out as a uniform `{ tag: i32, payload: T }` pair
/// in linear memory. Tag values are [`OPTIONAL_TAG_NIL`] (no payload)
/// and [`OPTIONAL_TAG_SOME`] (payload present); the same byte range is
/// reserved either way so callers don't need to know the discriminant
/// to compute the allocation size. `Optional<Never>` is the type of
/// `nil` itself — it has no payload, so `payload_size == 0` and the
/// total value is just the 4-byte tag.
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct OptionalLayout {
    /// Total bytes one optional value occupies, including tag,
    /// post-tag alignment padding, payload, and trailing alignment
    /// padding.
    pub size: u32,
    /// Optional alignment — the maximum of [`OPTIONAL_TAG_ALIGN`] and
    /// the payload's alignment (or just the tag alignment for
    /// `Optional<Never>`).
    pub align: u32,
    /// Offset of the discriminant tag (always 0).
    pub tag_offset: u32,
    /// Offset where the payload starts. `tag_offset + OPTIONAL_TAG_SIZE`
    /// rounded up to the payload's alignment.
    pub payload_offset: u32,
    /// Payload size in bytes. Aggregate inner types collapse to a
    /// 4-byte pointer; `Optional<Never>` has size 0.
    pub payload_size: u32,
    /// Payload alignment in bytes. `1` when there is no payload
    /// (`Optional<Never>`).
    pub payload_align: u32,
}

/// Compute the layout of `Optional<inner>`.
///
/// `module` is accepted for API symmetry with the struct/enum/array/
/// range planners; the current implementation only inspects `inner`.
///
/// Aggregate inner types (struct, enum, tuple, array) lower as `i32`
/// pointers — the underlying value lives in a separately-allocated
/// region. Primitive inner types are stored inline at their
/// canonical-ABI size and alignment. `Optional<Never>` is the static
/// type of the `nil` literal and lays out as a tag-only value with no
/// payload. The heap-typed primitives (`String` / `Path` / `Regex`)
/// and nested aggregates whose layouts depend on later phases surface
/// as [`LayoutError::NotYetSupported`].
pub fn plan_optional(
    inner: &ResolvedType,
    _module: &IrModule,
) -> Result<OptionalLayout, LayoutError> {
    if matches!(inner, ResolvedType::Primitive(PrimitiveType::Never)) {
        return Ok(OptionalLayout {
            size: OPTIONAL_TAG_SIZE,
            align: OPTIONAL_TAG_ALIGN,
            tag_offset: 0,
            payload_offset: OPTIONAL_TAG_SIZE,
            payload_size: 0,
            payload_align: 1,
        });
    }

    let (payload_size, payload_align) = optional_payload_size_align(inner)?;
    let total_align = if payload_align > OPTIONAL_TAG_ALIGN {
        payload_align
    } else {
        OPTIONAL_TAG_ALIGN
    };
    let payload_offset =
        align_up(OPTIONAL_TAG_SIZE, payload_align).ok_or_else(|| LayoutError::SizeOverflow {
            name: "<optional>".to_owned(),
        })?;
    let raw_size =
        payload_offset
            .checked_add(payload_size)
            .ok_or_else(|| LayoutError::SizeOverflow {
                name: "<optional>".to_owned(),
            })?;
    let size = align_up(raw_size, total_align).ok_or_else(|| LayoutError::SizeOverflow {
        name: "<optional>".to_owned(),
    })?;

    Ok(OptionalLayout {
        size,
        align: total_align,
        tag_offset: 0,
        payload_offset,
        payload_size,
        payload_align,
    })
}

/// Return the inline `(size, align)` pair for an `Optional<T>` payload.
///
/// Aggregate payload types live as `i32` pointers, so they always
/// report `(POINTER_SIZE, POINTER_ALIGN)` regardless of the
/// underlying value's storage size. Primitive payloads report their
/// canonical-ABI size/align via [`primitive_size_align`]. `Never` is
/// handled by the caller — it never reaches this helper.
fn optional_payload_size_align(ty: &ResolvedType) -> Result<(u32, u32), LayoutError> {
    match ty {
        ResolvedType::Primitive(p) => primitive_size_align(*p),
        // Every aggregate payload — struct, enum, tuple, the four
        // prelude compounds living under `Generic`, and trait-typed
        // payloads (4-byte pointer to the fat-pointer cell) —
        // collapses to a 4-byte heap pointer.
        ResolvedType::Struct(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Generic { .. }
        | ResolvedType::Trait(_) => Ok((POINTER_SIZE, POINTER_ALIGN)),
        ResolvedType::Closure { .. } => Err(LayoutError::NotYetSupported {
            kind: "Closure".to_owned(),
        }),
        ResolvedType::TypeParam(name) => Err(LayoutError::NotYetSupported {
            kind: format!("TypeParam({name})"),
        }),
        ResolvedType::External { name, .. } => Err(LayoutError::NotYetSupported {
            kind: format!(
                "External({name}) — should have been inlined by upstream MonomorphisePass; reaching the backend means an upstream invariant violation"
            ),
        }),
        ResolvedType::Error => Err(LayoutError::NotYetSupported {
            kind: "Error".to_owned(),
        }),
    }
}

/// Return the in-buffer `(size, align)` pair for an array element.
///
/// Aggregate element types live as `i32` pointers, so they always
/// report `(POINTER_SIZE, POINTER_ALIGN)` regardless of the
/// underlying value's storage size. Primitive elements report their
/// canonical-ABI size/align via [`primitive_size_align`].
fn array_element_size_align(ty: &ResolvedType) -> Result<(u32, u32), LayoutError> {
    match ty {
        ResolvedType::Primitive(p) => primitive_size_align(*p),
        // Every aggregate element — struct, enum, tuple, the four
        // prelude compounds living under `Generic`, and trait-typed
        // elements (4-byte pointer to the fat-pointer cell) —
        // collapses to a 4-byte heap pointer.
        ResolvedType::Struct(_)
        | ResolvedType::Enum(_)
        | ResolvedType::Tuple(_)
        | ResolvedType::Generic { .. }
        | ResolvedType::Trait(_) => Ok((POINTER_SIZE, POINTER_ALIGN)),
        ResolvedType::Closure { .. } => Err(LayoutError::NotYetSupported {
            kind: "Closure".to_owned(),
        }),
        ResolvedType::TypeParam(name) => Err(LayoutError::NotYetSupported {
            kind: format!("TypeParam({name})"),
        }),
        ResolvedType::External { name, .. } => Err(LayoutError::NotYetSupported {
            kind: format!(
                "External({name}) — should have been inlined by upstream MonomorphisePass; reaching the backend means an upstream invariant violation"
            ),
        }),
        ResolvedType::Error => Err(LayoutError::NotYetSupported {
            kind: "Error".to_owned(),
        }),
    }
}

// ── vtable layout ────────────────────────────────────────────────────

/// Per-slot size in bytes inside a trait vtable. Each slot stores a
/// funcref-table index as an `i32`.
pub const VTABLE_SLOT_SIZE: u32 = 4;

/// Per-slot alignment in bytes inside a trait vtable. Slots are
/// `i32`-sized funcref indices.
pub const VTABLE_SLOT_ALIGN: u32 = 4;

/// Layout decisions for a per-trait vtable.
///
/// One vtable per `(trait, impl_target)` pair. The vtable is a flat
/// array of i32 funcref-table indices — one per method declared on the
/// trait, ordered to match `IrTrait.methods` so a `MethodIdx` indexes
/// directly into it. Virtual call sites compute
/// `vtable_base + method_idx * VTABLE_SLOT_SIZE`, load the funcref,
/// and `call_indirect` against the module's funcref table.
///
/// Traits with zero methods produce a degenerate `size = 0` vtable
/// — the planner accepts them so the per-trait walk has a uniform
/// shape.
#[expect(
    clippy::exhaustive_structs,
    reason = "plain layout record consumed externally; intentionally constructible"
)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VTableLayout {
    /// Total bytes one vtable occupies. Equals `methods * VTABLE_SLOT_SIZE`.
    pub size: u32,
    /// Vtable alignment in bytes — always [`VTABLE_SLOT_ALIGN`].
    pub align: u32,
    /// Number of method slots in the vtable.
    pub method_count: u32,
    /// Per-slot size — always [`VTABLE_SLOT_SIZE`].
    pub slot_size: u32,
}

/// Compute the layout of the vtable for `trait_def`.
///
/// `module` is accepted for API symmetry with the other planners; the
/// current implementation only inspects `trait_def.methods.len()`.
pub fn plan_vtable(trait_def: &IrTrait, _module: &IrModule) -> Result<VTableLayout, LayoutError> {
    let method_count =
        u32::try_from(trait_def.methods.len()).map_err(|_| LayoutError::SizeOverflow {
            name: format!("vtable<{}>", trait_def.name),
        })?;
    let size =
        method_count
            .checked_mul(VTABLE_SLOT_SIZE)
            .ok_or_else(|| LayoutError::SizeOverflow {
                name: format!("vtable<{}>", trait_def.name),
            })?;
    Ok(VTableLayout {
        size,
        align: VTABLE_SLOT_ALIGN,
        method_count,
        slot_size: VTABLE_SLOT_SIZE,
    })
}