splicer 2.4.1

Plan and generate middleware splice operations for WebAssembly component composition graphs.
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
//! Static-memory layout phase: takes the `FuncClassified` list,
//! reserves data + scratch slabs, and returns an immutable
//! `FuncDispatch` list with every offset filled in.

use anyhow::{bail, Result};
use wit_parser::{Function as WitFunction, Type};

use super::super::abi::emit::BlobSlice;
use super::super::mem_layout::StaticLayout;
use super::blob::{resolve, NameInterner, RecordWriter, RelocPlan, Segment, SymRef, SymbolBases};
use super::lift::plan::Cell;
use super::lift::{
    back_fill_record_fields_ptrs, build_char_scratch_map, build_enum_info_blob,
    build_flags_info_maps, build_handle_info_maps, build_record_info_maps,
    build_tuple_indices_blob, build_variant_info_maps, char_scratch_sizes, flags_scratch_sizes,
    fold_cell_side_data, CellFillSources, CellSideData, CharScratch, CharScratchMaps,
    FlagsInfoMaps, FlagsRuntimeFill, HandleInfoMaps, HandleRuntimeFill, InfoCounts, ParamLayout,
    RecordInfoMaps, ResultLayout, ResultLift, ResultSource, ResultSourceLayout, SideTableBlob,
    TupleIndicesBlob, VariantInfoMaps,
};
use super::schema::{
    SchemaLayouts, FIELD_NAME, FIELD_TREE, ON_RET_CALL, ON_RET_RESULT, TREE_CELLS, TREE_ENUM_INFOS,
    TREE_FLAGS_INFOS, TREE_HANDLE_INFOS, TREE_RECORD_INFOS, TREE_ROOT, TREE_VARIANT_INFOS,
};
use super::{AfterSetup, FuncClassified, FuncDispatch, FuncShape};

// ─── ABI-anchored constants (not WIT-schema-derivable) ────────────

/// `waitable-set.wait` event record slot (wit-component runtime ABI).
const EVENT_SLOT_SIZE: u32 = 8;
const EVENT_SLOT_ALIGN: u32 = 4;

// ─── Layout-phase size budget ─────────────────────────────────────
//
// Wasm encodes static-data offsets as `i32.const`, so every offset
// must fit in signed-i32. One pre-check bounds the per-fn/param
// counts; one post-check verifies the final end.

/// Final layout end must fit in signed i32.
const LAYOUT_SIZE_BUDGET: u32 = i32::MAX as u32;

/// Per-fn flat-slot count cap. Reduced under `cfg(test)` to exercise
/// the bail without a WIT at the production limit. Plan-builder
/// pre-bails on `list<T, N>` with `N` over this cap so a hostile
/// integer literal can't overflow `bump_flat_slot`'s u32 counter
/// before layout's post-build check fires.
#[cfg(not(test))]
pub(in crate::adapter::tier2) const MAX_FLAT_SLOTS_PER_FN: u32 = 1 << 16;
#[cfg(test)]
pub(in crate::adapter::tier2) const MAX_FLAT_SLOTS_PER_FN: u32 = 16;

/// Per-param (and per-result) cell-tree cap. Plan-builder pre-bails
/// on oversized `list<T, N>` for the same reason as above.
#[cfg(not(test))]
pub(in crate::adapter::tier2) const MAX_CELLS_PER_PARAM: u32 = 1 << 20;
#[cfg(test)]
pub(in crate::adapter::tier2) const MAX_CELLS_PER_PARAM: u32 = 8;

/// Bound per-fn / per-param counts so downstream `u32` arithmetic fits.
fn check_layout_budget(per_func: &[FuncClassified]) -> Result<()> {
    for (fn_idx, fd) in per_func.iter().enumerate() {
        for (p_idx, p) in fd.params.iter().enumerate() {
            if p.plan.flat_slot_count > MAX_FLAT_SLOTS_PER_FN {
                bail!(
                    "fn[{fn_idx}] param[{p_idx}]: flat-slot count {} exceeds budget {MAX_FLAT_SLOTS_PER_FN}",
                    p.plan.flat_slot_count,
                );
            }
            if p.plan.cell_count() > MAX_CELLS_PER_PARAM {
                bail!(
                    "fn[{fn_idx}] param[{p_idx}]: cell count {} exceeds budget {MAX_CELLS_PER_PARAM}",
                    p.plan.cell_count(),
                );
            }
        }
        if let Some(rl) = fd.result_lift.as_ref() {
            let cells = rl.compound().map_or(1, |c| c.plan.cell_count());
            if cells > MAX_CELLS_PER_PARAM {
                bail!(
                    "fn[{fn_idx}] result: cell count {cells} exceeds budget {MAX_CELLS_PER_PARAM}"
                );
            }
        }
    }
    Ok(())
}

/// Per-fn fills for a Direct (sync flat) result.
struct SingleCellFills<'a> {
    flags_fill: &'a Option<FlagsRuntimeFill>,
    char_scratch: &'a Option<i32>,
    handle_fill: &'a Option<HandleRuntimeFill>,
}

/// Wrap per-fn fills into a `CellSideData` for a Direct result.
/// Compound/un-wired kinds are unreachable — classify_result_lift
/// routes them through Compound.
fn single_cell_side_data(cell: &Cell, fills: &SingleCellFills<'_>) -> CellSideData {
    match cell {
        Cell::Flags { .. } => CellSideData::Flags(Box::new(
            fills
                .flags_fill
                .clone()
                .expect("flags-info fill must exist"),
        )),
        Cell::Char { .. } => CellSideData::Char {
            scratch: CharScratch::Static {
                scratch_addr: fills.char_scratch.expect("char-info scratch must exist"),
            },
        },
        Cell::Handle { .. } => CellSideData::Handle(Box::new(
            fills
                .handle_fill
                .clone()
                .expect("handle-info fill must exist"),
        )),
        Cell::Bool { .. }
        | Cell::IntegerSignExt { .. }
        | Cell::IntegerZeroExt { .. }
        | Cell::Integer64 { .. }
        | Cell::FloatingF32 { .. }
        | Cell::FloatingF64 { .. }
        | Cell::Text { .. }
        | Cell::Bytes { .. }
        | Cell::EnumCase { .. } => CellSideData::None,
        Cell::RecordOf { .. }
        | Cell::TupleOf { .. }
        | Cell::Option { .. }
        | Cell::Result { .. }
        | Cell::Variant { .. }
        | Cell::ListOf { .. } => {
            unreachable!("single_cell_side_data reached unsupported result Cell {cell:?}")
        }
    }
}

/// Output of the static-memory layout phase.
pub(super) struct StaticDataPlan {
    pub(super) bump_start: u32,
    pub(super) event_ptr: i32,
    /// On-call indirect-params scratch; `Some` iff before-hook is wired.
    pub(super) hook_params_ptr: Option<u32>,
    pub(super) data_segments: Vec<(u32, Vec<u8>)>,
}

/// Side-table absolute pointers for one field-tree.
#[derive(Clone, Copy, Default)]
struct FieldSideTables {
    enum_infos: BlobSlice,
    flags_infos: BlobSlice,
    record_infos: BlobSlice,
    variant_infos: BlobSlice,
    handle_infos: BlobSlice,
}

impl FieldSideTables {
    fn write_to_tree(&self, blob: &mut [u8], tree: &RecordWriter) {
        tree.write_slice(blob, TREE_ENUM_INFOS, self.enum_infos);
        tree.write_slice(blob, TREE_FLAGS_INFOS, self.flags_infos);
        tree.write_slice(blob, TREE_RECORD_INFOS, self.record_infos);
        tree.write_slice(blob, TREE_VARIANT_INFOS, self.variant_infos);
        tree.write_slice(blob, TREE_HANDLE_INFOS, self.handle_infos);
    }
}

/// Single-pass build of a `field` record + its embedded
/// `field-tree` for one (function, param) pair. `cells` is
/// `(0, cell-count)` — the wrapper body patches `cells.ptr` per
/// call after `cabi_realloc`. `root` is the cell-array index the
/// field-tree should walk from — sourced from the param's
/// [`super::lift::ParamLift::plan`]'s [`super::lift::plan::LiftPlan::root`].
/// `side_tables` patches the field-tree's per-kind-infos lists for
/// any kinds the param's plan carries.
fn write_field_record(
    blob: &mut Vec<u8>,
    schema: &SchemaLayouts,
    cells: BlobSlice,
    root: u32,
    name: BlobSlice,
    side_tables: FieldSideTables,
) {
    let field = RecordWriter::extend_zero(blob, &schema.field_layout);
    field.write_slice(blob, FIELD_NAME, name);
    let tree = field.nested(FIELD_TREE, &schema.tree_layout);
    tree.write_slice(blob, TREE_CELLS, cells);
    side_tables.write_to_tree(blob, &tree);
    tree.write_i32(blob, TREE_ROOT, root as i32);
}

/// Build the contiguous fields blob: one `field` record per
/// (fn, param). `cells.ptr` is left at `0` — wrapper body patches it
/// per call after `cabi_realloc`.
fn build_fields_blob(
    per_func: &[FuncClassified],
    schema: &SchemaLayouts,
    param_side_tables: &[Vec<FieldSideTables>],
) -> Vec<u8> {
    let mut blob: Vec<u8> = Vec::new();
    for (fn_idx, fd) in per_func.iter().enumerate() {
        for (i, p) in fd.params.iter().enumerate() {
            write_field_record(
                &mut blob,
                schema,
                BlobSlice {
                    off: 0,
                    len: p.plan.cell_count(),
                },
                p.plan.root(),
                p.name,
                param_side_tables[fn_idx][i],
            );
        }
    }
    blob
}

/// On-return params blob: one record per fn. `result` is
/// `some(field-tree)` pre-wired for funcs with a result lift,
/// `none` otherwise. `cells.ptr` patched per call.
fn build_after_params_blob(
    per_func: &[FuncClassified],
    schema: &SchemaLayouts,
    iface_name: BlobSlice,
    result_side_tables: &[FieldSideTables],
) -> Vec<u8> {
    let Some(after_layout) = schema.after_hook.as_ref().map(|h| &h.params_layout) else {
        return Vec::new();
    };
    let mut blob: Vec<u8> = Vec::new();
    for (fn_idx, fd) in per_func.iter().enumerate() {
        let entry = RecordWriter::extend_zero(&mut blob, after_layout);
        schema.callid_layout.store_names_in_blob(
            &mut blob,
            entry.field_offset(ON_RET_CALL),
            iface_name,
            BlobSlice {
                off: fd.fn_name_offset as u32,
                len: fd.fn_name_len as u32,
            },
        );
        if fd.result_lift.is_some() {
            entry.write_option_some(&mut blob, ON_RET_RESULT);
            let tree_base = entry.field_offset(ON_RET_RESULT) + schema.option_payload_off as usize;
            let tree = RecordWriter::at(&schema.tree_layout, tree_base);
            // Compound: cells.len = plan.cell_count, root = plan.root.
            // Direct: len = 1, root = 0.
            let (cells_len, root) = fd
                .result_lift
                .as_ref()
                .and_then(|rl| rl.compound())
                .map_or((1, 0), |c| (c.plan.cell_count(), c.plan.root()));
            tree.write_slice(
                &mut blob,
                TREE_CELLS,
                BlobSlice {
                    off: 0,
                    len: cells_len,
                },
            );
            result_side_tables[fn_idx].write_to_tree(&mut blob, &tree);
            tree.write_i32(&mut blob, TREE_ROOT, root as i32);
        } else {
            entry.write_option_none(&mut blob, ON_RET_RESULT);
        }
    }
    blob
}

/// Place a segment, register its symbol, queue relocs.
fn place_segment(
    layout: &mut StaticLayout,
    symbols: &mut SymbolBases,
    relocs: &mut RelocPlan,
    seg: Segment,
) -> u32 {
    let (base, idx) = layout.place_data(seg.align, &seg.bytes);
    symbols.set(seg.id, base);
    relocs.record_segment(idx, base, seg.relocs);
    base
}

/// Resolve `SymRef` grids to absolute `BlobSlice` grids.
fn resolve_param_result_ranges(
    symbols: &SymbolBases,
    per_param_sym: Vec<Vec<Option<SymRef>>>,
    per_result_sym: Vec<Option<SymRef>>,
) -> (Vec<Vec<BlobSlice>>, Vec<BlobSlice>) {
    let per_param = per_param_sym
        .into_iter()
        .map(|v| v.into_iter().map(|s| resolve(s, symbols)).collect())
        .collect();
    let per_result = per_result_sym
        .into_iter()
        .map(|s| resolve(s, symbols))
        .collect();
    (per_param, per_result)
}

/// Reserve scratch + place data segments, then assemble immutable
/// `FuncDispatch` records. Takes ownership of the classify output and
/// returns a fully-built dispatch list — no back-fill state possible.
pub(super) fn lay_out_static_memory(
    mut per_func: Vec<FuncClassified>,
    funcs: &[&WitFunction],
    schema: &SchemaLayouts,
    names: NameInterner,
    iface_name: BlobSlice,
) -> Result<(Vec<FuncDispatch>, StaticDataPlan)> {
    let n_funcs = per_func.len();
    debug_assert_eq!(
        per_func.len(),
        funcs.len(),
        "FuncClassified list and WitFunction list must be index-aligned",
    );

    check_layout_budget(&per_func)?;

    let mut layout = StaticLayout::new();
    let mut symbols = SymbolBases::new();
    let mut relocs = RelocPlan::new();

    let name_blob = names.into_bytes();
    let _ = layout.place_data(1, &name_blob);

    // Reserve flags scratch before building flags-info so each entry's
    // `set-flags.ptr` lands as an absolute address (no reloc).
    let flags_scratch_addrs: Vec<u32> = flags_scratch_sizes(&per_func)
        .into_iter()
        .map(|n_bytes| layout.reserve_scratch(4, n_bytes))
        .collect();
    // Char scratch: 4 bytes per cell, byte-aligned (i32.store8).
    let char_scratch_addrs: Vec<u32> = char_scratch_sizes(&per_func)
        .into_iter()
        .map(|n_bytes| layout.reserve_scratch(1, n_bytes))
        .collect();
    let CharScratchMaps {
        per_cell: char_scratch_map,
        per_result_single: char_per_result_single,
    } = {
        let mut iter = char_scratch_addrs.iter().copied();
        let maps = build_char_scratch_map(&per_func, &mut iter);
        debug_assert!(iter.next().is_none());
        maps
    };

    // Per-(fn, field) enum-info / record-info side tables. Builders
    // emit `Segment`s with in-segment relocs; placement order is
    // commutative because every cross-segment ptr is a queued reloc.
    let enum_info_id = symbols.alloc();
    let record_tuples_id = symbols.alloc();
    let tuple_indices_id = symbols.alloc();
    let enum_info = build_enum_info_blob(&mut per_func, &schema.enum_info_layout, enum_info_id);
    let SideTableBlob {
        segment: enum_segment,
        per_param: enum_per_param_sym,
        per_result: enum_per_result_sym,
    } = enum_info;
    // Flags-info entries are per-call (wrapper allocates the buffer);
    // only the set-flags scratch slabs are baked statically.
    let mut flags_scratch_iter = flags_scratch_addrs.iter().copied();
    let FlagsInfoMaps {
        per_cell_fill: flags_per_cell_fill,
        per_result_single_fill: flags_per_result_single_fill,
        per_param_count: flags_per_param_count,
        per_result_count: flags_per_result_count,
    } = build_flags_info_maps(&per_func, &mut flags_scratch_iter);
    debug_assert!(
        flags_scratch_iter.next().is_none(),
        "flags scratch reservations must be consumed once per Cell::Flags",
    );
    // Record-info entries are per-call; static records' field-tuples
    // stay baked in `record_tuples_seg` (list-element records get
    // their own per-call tuples buffer).
    let RecordInfoMaps {
        tuples: record_tuples_seg,
        per_cell_fill: mut record_per_cell_fill,
        per_param_count: record_per_param_count,
        per_result_count: record_per_result_count,
    } = build_record_info_maps(
        &per_func,
        &schema.record_field_tuple_layout,
        record_tuples_id,
    );
    let TupleIndicesBlob {
        segment: tuple_indices_seg,
        per_cell_idx: tuple_indices_per_cell,
    } = build_tuple_indices_blob(&per_func, tuple_indices_id);
    // Variant-info entries are per-call.
    let VariantInfoMaps {
        per_cell_fill: variant_per_cell_fill,
        per_param_count: variant_per_param_count,
        per_result_count: variant_per_result_count,
    } = build_variant_info_maps(&per_func);
    // Handle-info entries are per-call.
    let HandleInfoMaps {
        per_cell_fill: handle_per_cell_fill,
        per_result_single_fill: handle_per_result_single_fill,
        per_param_count: handle_per_param_count,
        per_result_count: handle_per_result_count,
    } = build_handle_info_maps(&per_func);

    // Placement order is commutative; each placement assigns a base
    // and relocs land later.
    let record_tuples_base =
        place_segment(&mut layout, &mut symbols, &mut relocs, record_tuples_seg);
    place_segment(&mut layout, &mut symbols, &mut relocs, enum_segment);
    place_segment(&mut layout, &mut symbols, &mut relocs, tuple_indices_seg);

    // Static record fills' `fields_ptr` is segment-relative; rebase now.
    back_fill_record_fields_ptrs(&mut record_per_cell_fill, record_tuples_base);

    let (enum_per_param, enum_per_result) =
        resolve_param_result_ranges(&symbols, enum_per_param_sym, enum_per_result_sym);

    // Bundle every kind's per-(fn, param) and per-(fn, result)
    // pointers into one `FieldSideTables` per field-tree, so the
    // blob writers don't grow another arg per kind.
    let param_side_tables: Vec<Vec<FieldSideTables>> = (0..n_funcs)
        .map(|fn_idx| {
            (0..per_func[fn_idx].params.len())
                .map(|p_idx| FieldSideTables {
                    enum_infos: enum_per_param[fn_idx][p_idx],
                    flags_infos: BlobSlice {
                        off: 0,
                        len: flags_per_param_count[fn_idx][p_idx],
                    },
                    record_infos: BlobSlice {
                        off: 0,
                        len: record_per_param_count[fn_idx][p_idx],
                    },
                    variant_infos: BlobSlice {
                        off: 0,
                        len: variant_per_param_count[fn_idx][p_idx],
                    },
                    handle_infos: BlobSlice {
                        off: 0,
                        len: handle_per_param_count[fn_idx][p_idx],
                    },
                })
                .collect()
        })
        .collect();
    let result_side_tables: Vec<FieldSideTables> = (0..n_funcs)
        .map(|fn_idx| FieldSideTables {
            enum_infos: enum_per_result[fn_idx],
            flags_infos: BlobSlice {
                off: 0,
                len: flags_per_result_count[fn_idx],
            },
            record_infos: BlobSlice {
                off: 0,
                len: record_per_result_count[fn_idx],
            },
            variant_infos: BlobSlice {
                off: 0,
                len: variant_per_result_count[fn_idx],
            },
            handle_infos: BlobSlice {
                off: 0,
                len: handle_per_result_count[fn_idx],
            },
        })
        .collect();

    // `cells.ptr` left zero (patched per call); side-table pointers baked.
    let fields_blob = build_fields_blob(&per_func, schema, &param_side_tables);
    let (fields_base, _) = layout.place_data(schema.field_layout.align, &fields_blob);
    let fields_buf_offsets: Vec<u32> = {
        let mut cursor = fields_base;
        per_func
            .iter()
            .map(|fd| {
                let here = cursor;
                cursor += fd.params.len() as u32 * schema.field_layout.size;
                here
            })
            .collect()
    };

    // On-return params blob (data), only when after-hook is wired.
    let after_blob = build_after_params_blob(&per_func, schema, iface_name, &result_side_tables);
    let after_params_offsets: Vec<Option<i32>> =
        match schema.after_hook.as_ref().map(|h| &h.params_layout) {
            Some(al) => {
                let (after_base, _) = layout.place_data(al.align, &after_blob);
                let mut cursor = after_base;
                (0..n_funcs)
                    .map(|_| {
                        let here = cursor as i32;
                        cursor += al.size;
                        Some(here)
                    })
                    .collect()
            }
            None => vec![None; n_funcs],
        };

    // Scratch slots: event record + on-call indirect-params buffer.
    let event_ptr = layout.reserve_scratch(EVENT_SLOT_ALIGN, EVENT_SLOT_SIZE) as i32;
    let hook_params_ptr = schema
        .before_hook
        .as_ref()
        .map(|h| layout.reserve_scratch(h.params_layout.align, h.params_layout.size));

    // Per-fn retptr scratch (only when sig uses one).
    let retptr_offsets: Vec<Option<i32>> = per_func
        .iter()
        .zip(funcs.iter())
        .map(|(fd, func)| {
            if !(fd.export_sig.retptr || fd.import_sig.retptr) {
                return None;
            }
            let result_ty = func
                .result
                .as_ref()
                .expect("retptr → func.result is_some()");
            let size = schema.size_align.size(result_ty).size_wasm32() as u32;
            let align = schema.size_align.align(result_ty).align_wasm32() as u32;
            Some(layout.reserve_scratch(align, size) as i32)
        })
        .collect();

    // Async indirect-params scratch (canon-lower-async overflowed
    // MAX_FLAT_ASYNC_PARAMS).
    let params_record_offsets: Vec<Option<i32>> = per_func
        .iter()
        .zip(funcs.iter())
        .map(|(fd, func)| {
            if !(matches!(fd.shape, FuncShape::Async(_)) && fd.import_sig.indirect_params) {
                return None;
            }
            let param_types: Vec<Type> = func.params.iter().map(|p| p.ty).collect();
            let info = schema.size_align.record(&param_types);
            let size = info.size.size_wasm32() as u32;
            let align = info.align.align_wasm32() as u32;
            Some(layout.reserve_scratch(align, size) as i32)
        })
        .collect();

    // Bump-allocator start aligned to the schema's max (`cell`).
    let bump_start = layout.end().next_multiple_of(schema.cell_layout.align);
    if bump_start > LAYOUT_SIZE_BUDGET {
        bail!("static-data layout end {bump_start} exceeds i32 budget {LAYOUT_SIZE_BUDGET}");
    }
    let mut data_segments = layout.into_segments();
    // After `into_segments` so segments aren't being mutated.
    relocs.resolve(&symbols, &mut data_segments);

    let dispatches: Vec<FuncDispatch> = per_func
        .into_iter()
        .enumerate()
        .map(|(i, fc)| {
            let params: Vec<ParamLayout> = fc
                .params
                .into_iter()
                .enumerate()
                .map(|(p_idx, lift)| {
                    let tuple_slices = tuple_indices_per_cell.resolve_param(i, p_idx, &symbols);
                    let sources = CellFillSources {
                        record_fill: record_per_cell_fill.for_param(i, p_idx),
                        tuple_indices: &tuple_slices,
                        flags_fill: flags_per_cell_fill.for_param(i, p_idx),
                        variant_fill: variant_per_cell_fill.for_param(i, p_idx),
                        char_scratch: char_scratch_map.for_param(i, p_idx),
                        handle_fill: handle_per_cell_fill.for_param(i, p_idx),
                    };
                    let cell_side = fold_cell_side_data(&lift.plan, &sources);
                    ParamLayout {
                        lift,
                        cell_side,
                        info_counts: InfoCounts {
                            handle: handle_per_param_count[i][p_idx],
                            flags: flags_per_param_count[i][p_idx],
                            record: record_per_param_count[i][p_idx],
                            variant: variant_per_param_count[i][p_idx],
                        },
                    }
                })
                .collect();

            let retptr_offset = retptr_offsets[i];
            let result_lift = fc.result_lift.map(|rl| {
                let ResultLift { source, .. } = rl;
                let layout_source = match source {
                    ResultSource::Direct(cell) => {
                        let fills = SingleCellFills {
                            flags_fill: &flags_per_result_single_fill[i],
                            char_scratch: &char_per_result_single[i],
                            handle_fill: &handle_per_result_single_fill[i],
                        };
                        let side_data = single_cell_side_data(&cell, &fills);
                        ResultSourceLayout::Direct { cell, side_data }
                    }
                    ResultSource::Compound(compound) => {
                        let tuple_slices = tuple_indices_per_cell.resolve_result(i, &symbols);
                        let sources = CellFillSources {
                            record_fill: record_per_cell_fill.for_result(i),
                            tuple_indices: &tuple_slices,
                            flags_fill: flags_per_cell_fill.for_result(i),
                            variant_fill: variant_per_cell_fill.for_result(i),
                            char_scratch: char_scratch_map.for_result(i),
                            handle_fill: handle_per_cell_fill.for_result(i),
                        };
                        let cell_side = fold_cell_side_data(&compound.plan, &sources);
                        // Tie scratch reservation to the same sig
                        // predicate classify saw — else emit reads
                        // from the wrong place.
                        debug_assert_eq!(
                            retptr_offset.is_some(),
                            fc.shape.result_at_retptr(&fc.export_sig, &fc.import_sig),
                            "retptr scratch reservation must match \
                             classify-time result_at_retptr",
                        );
                        ResultSourceLayout::Compound {
                            compound,
                            retptr_offset,
                            cell_side,
                        }
                    }
                };
                ResultLayout {
                    source: layout_source,
                    info_counts: InfoCounts {
                        handle: handle_per_result_count[i],
                        flags: flags_per_result_count[i],
                        record: record_per_result_count[i],
                        variant: variant_per_result_count[i],
                    },
                }
            });

            let after = after_params_offsets[i].map(|params_offset| AfterSetup { params_offset });

            FuncDispatch {
                shape: fc.shape,
                result_ty: fc.result_ty,
                import_module: fc.import_module,
                import_field: fc.import_field,
                export_name: fc.export_name,
                export_sig: fc.export_sig,
                import_sig: fc.import_sig,
                needs_cabi_post: fc.needs_cabi_post,
                fn_name_offset: fc.fn_name_offset,
                fn_name_len: fc.fn_name_len,
                params,
                fields_buf_offset: fields_buf_offsets[i],
                retptr_offset,
                params_record_offset: params_record_offsets[i],
                result_lift,
                after,
                borrow_drops: fc.borrow_drops,
            }
        })
        .collect();

    Ok((
        dispatches,
        StaticDataPlan {
            bump_start,
            event_ptr,
            hook_params_ptr,
            data_segments,
        },
    ))
}