splicer 2.2.0

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
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
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
//! WIT-level adapter emission — a thin layer over
//! `wit_component::ComponentEncoder`:
//!
//! 1. Decode the input split's WIT via [`wit_component::decode`].
//! 2. Push the tier1 hook packages + an "adapter" world that
//!    references the target package by name (no type recreation).
//! 3. Emit a dispatch core module whose imports/exports match the
//!    canonical naming contract; all signatures, mangled names, and
//!    result loads come from `wit-parser` / `wit-bindgen-core`.
//! 4. Embed component-type metadata + run [`ComponentEncoder`].
//!
//! Resource-bound functions (constructor / method / static) bail to
//! the legacy emit path; everything else (sync, async-stackful,
//! primitive / string / list / record / variant / option / tuple
//! results) goes through here.

use anyhow::{anyhow, bail, Context, Result};
use std::collections::HashMap;
use wasm_encoder::{
    BlockType, CodeSection, ConstExpr, DataSection, EntityType, ExportKind, ExportSection,
    Function, FunctionSection, GlobalSection, GlobalType, ImportSection, MemorySection, MemoryType,
    Module, TypeSection, ValType,
};
use wit_bindgen_core::abi::lift_from_memory;
use wit_component::{
    decode, embed_component_metadata, ComponentEncoder, DecodedWasm, StringEncoding,
};
use wit_parser::abi::{AbiVariant, FlatTypes, WasmSignature, WasmType};
use wit_parser::{
    Function as WitFunction, Handle, InterfaceId, LiftLowerAbi, Mangling, ManglingAndAbi, Resolve,
    ResourceIntrinsic, SizeAlign, Type, TypeDefKind, TypeId, TypeOwner, WasmExport, WasmExportKind,
    WasmImport, WorldItem, WorldKey,
};

use super::abi::WasmEncoderBindgen;
use super::indices::{DispatchIndices, FunctionIndices};
use super::mem_layout::MemoryLayoutBuilder;

/// Generate the adapter component bytes. `target_interface` is the
/// fully-qualified interface name (`<ns>:<pkg>/<iface>[@<ver>]`);
/// `common_world_wit` is the contents of `wit/common/world.wit`
/// (loaded first as a dependency); `tier1_world_wit` is the contents
/// of `wit/tier1/world.wit` (which references `splicer:common`).
pub(crate) fn build_adapter(
    target_interface: &str,
    has_before: bool,
    has_after: bool,
    has_blocking: bool,
    split_bytes: &[u8],
    common_world_wit: &str,
    tier1_world_wit: &str,
) -> Result<Vec<u8>> {
    let mut resolve = decode_input_resolve(split_bytes)?;
    let target_iface = find_target_interface(&resolve, target_interface)?;

    require_supported_case(&resolve, target_iface, has_blocking)?;

    resolve
        .push_str("splicer-common.wit", common_world_wit)
        .context("parse common WIT")?;
    resolve
        .push_str("splicer-tier1.wit", tier1_world_wit)
        .context("parse tier1 WIT")?;
    let world_pkg = resolve
        .push_str(
            "splicer-adapter.wit",
            &synthesize_adapter_world_wit(target_interface, has_before, has_after, has_blocking),
        )
        .context("parse synthesized adapter world WIT")?;
    let world_id = resolve
        .select_world(&[world_pkg], Some(ADAPTER_WORLD_NAME))
        .context("select adapter world")?;

    let mut core_module = build_dispatch_module(
        &resolve,
        world_id,
        target_iface,
        target_interface,
        has_before,
        has_after,
        has_blocking,
    );
    embed_component_metadata(&mut core_module, &resolve, world_id, StringEncoding::UTF8)
        .context("embed_component_metadata")?;

    ComponentEncoder::default()
        .validate(true)
        .module(&core_module)
        .context("ComponentEncoder::module")?
        .encode()
        .context("ComponentEncoder::encode")
}

/// Decode the input split's WIT into a [`Resolve`]; bail if the bytes
/// decode to a WIT package rather than a component. `wit_component::decode`
/// panics on splits that import + re-export a resource-bearing instance
/// (https://github.com/bytecodealliance/wasm-tools/issues/2506); catch
/// it and surface a structured error so the process doesn't die.
fn decode_input_resolve(split_bytes: &[u8]) -> Result<Resolve> {
    let decoded = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| decode(split_bytes)))
        .map_err(|_| {
            anyhow!(
                "wit-parser panic during component decode — likely the import + re-export \
                 of a resource-bearing instance (upstream issue \
                 https://github.com/bytecodealliance/wasm-tools/issues/2506). The new emit \
                 path can't proceed until that's fixed upstream."
            )
        })?
        .context("wit_component::decode split")?;
    match decoded {
        DecodedWasm::Component(resolve, _world) => Ok(resolve),
        DecodedWasm::WitPackage(_, _) => bail!(
            "split bytes decoded to a WIT package; \
             expected a component"
        ),
    }
}

/// Find the target interface by its fully-qualified name.
fn find_target_interface(resolve: &Resolve, target_interface: &str) -> Result<InterfaceId> {
    resolve
        .interfaces
        .iter()
        .find(|(id, _)| resolve.id_of(*id).as_deref() == Some(target_interface))
        .map(|(id, _)| id)
        .ok_or_else(|| {
            anyhow!(
                "interface `{target_interface}` not found in \
                 the decoded WIT; available: {:?}",
                resolve
                    .interfaces
                    .iter()
                    .filter_map(|(id, _)| resolve.id_of(id))
                    .collect::<Vec<_>>()
            )
        })
}

/// Bail on cases the new path doesn't yet handle. Resource-bound
/// functions need a different dispatch shape; tier-1 blocking on a
/// non-void func is impossible (the adapter can't synthesize a return
/// value when the call is skipped) — same constraint legacy enforces.
fn require_supported_case(
    resolve: &Resolve,
    target_iface: InterfaceId,
    has_blocking: bool,
) -> Result<()> {
    let iface = &resolve.interfaces[target_iface];
    if iface.functions.is_empty() {
        bail!("interface has no functions");
    }
    // Inline-resource interfaces (resources declared in the same
    // interface that uses them) can't survive splicer's wrapper
    // pattern: `wit_component::ComponentEncoder` synthesizes a fresh
    // resource type for the export instance, and runtime handle
    // identity diverges from the import side. Bail with a clear
    // error pointing at the factored-types fix.
    for (ty_name, &tid) in &iface.types {
        let td = &resolve.types[tid];
        if matches!(td.kind, TypeDefKind::Resource)
            && matches!(td.owner, TypeOwner::Interface(owner) if owner == target_iface)
        {
            let iface_name = resolve
                .id_of(target_iface)
                .unwrap_or_else(|| iface.name.clone().unwrap_or_default());
            bail!(
                "interface `{iface_name}` declares resource `{ty_name}` inline. \
                 Splicer's wrapper-component pattern can't preserve resource \
                 type identity for inline resources — runtime handle traffic \
                 between the import side and export side will be rejected. \
                 Move `{ty_name}` into a sibling `types` interface and \
                 reference it via `use types.{{{ty_name}}}` (the wasi-style \
                 factored-types pattern)."
            );
        }
    }
    for (name, func) in &iface.functions {
        if has_blocking && func.result.is_some() {
            bail!(
                "Function '{name}' returns a value but the middleware exports \
                 `should-block`. Tier-1 blocking is only supported for \
                 void-returning functions because the adapter cannot synthesize \
                 a return value when the call is blocked."
            );
        }
        // Async funcs whose params overflow `MAX_FLAT_ASYNC_PARAMS = 4`
        // canon-lower with `indirect_params = true` — the handler takes a
        // single params-pointer instead of flat values. The wrapper export
        // (`GuestExportAsyncStackful`, capped at `MAX_FLAT_PARAMS = 16`)
        // still receives flat, so we'd need to lower-to-memory before the
        // handler call. Driving `wit_bindgen_core::abi::lower_to_memory`
        // requires extending `WasmEncoderBindgen` with the store-side
        // `AbiInst` variants. Not yet implemented.
        if func.kind.is_async() {
            let import_sig = resolve.wasm_signature(AbiVariant::GuestImportAsync, func);
            if import_sig.indirect_params {
                bail!(
                    "async function `{name}` has params that overflow \
                     MAX_FLAT_ASYNC_PARAMS (4) and require lower-to-memory; \
                     not yet implemented"
                );
            }
        }
    }
    Ok(())
}

/// Synthesize the adapter world: import + export the target interface
/// by name (no type recreation), and import the active tier1 hooks.
fn synthesize_adapter_world_wit(
    target_interface: &str,
    has_before: bool,
    has_after: bool,
    has_blocking: bool,
) -> String {
    use crate::contract::{
        versioned_interface, TIER1_AFTER, TIER1_BEFORE, TIER1_BLOCKING, TIER1_VERSION,
    };
    let mut wit = format!("package {ADAPTER_WORLD_PACKAGE};\n\nworld {ADAPTER_WORLD_NAME} {{\n");
    wit.push_str(&format!("    import {target_interface};\n"));
    wit.push_str(&format!("    export {target_interface};\n"));
    let mut import_hook = |iface: &str| {
        wit.push_str(&format!(
            "    import {};\n",
            versioned_interface(iface, TIER1_VERSION)
        ));
    };
    if has_before {
        import_hook(TIER1_BEFORE);
    }
    if has_after {
        import_hook(TIER1_AFTER);
    }
    if has_blocking {
        import_hook(TIER1_BLOCKING);
    }
    wit.push_str("}\n");
    wit
}

// ─── Dispatch core module ──────────────────────────────────────────

/// `(module, name, sig)` from [`WitFunction::task_return_import`].
struct TaskReturnImport {
    module: String,
    name: String,
    sig: WasmSignature,
}

/// Per-function dispatch shape. All sigs and mangled names come from
/// [`Resolve::wasm_signature`] / [`Resolve::wasm_import_name`] /
/// [`Resolve::wasm_export_name`]; offsets come from
/// [`MemoryLayoutBuilder`].
struct FuncDispatch {
    /// Handler import module — the canonical interface name.
    import_module: String,
    /// Handler import field — `<fn>` (sync) or `[async-lower]<fn>` (async).
    import_field: String,
    /// Wrapper export name — `<iface>#<fn>` (sync) or
    /// `[async-lift-stackful]<iface>#<fn>` (async).
    export_name: String,
    is_async: bool,
    /// Wrapper export sig (`GuestExport` / `GuestExportAsyncStackful`).
    export_sig: WasmSignature,
    /// Handler import sig (`GuestImport` / `GuestImportAsync`).
    import_sig: WasmSignature,
    /// WIT result type for [`lift_from_memory`]; `None` for void.
    result_ty: Option<Type>,
    /// `Some` iff async.
    task_return: Option<TaskReturnImport>,
    /// Offset/len of the target interface's fully-qualified name. The
    /// iface name is allocated once and shared across every
    /// `FuncDispatch` for the same target interface — duplicated here
    /// so hook-emission helpers can read it from `fd` without an
    /// extra parameter.
    iface_name_offset: i32,
    iface_name_len: i32,
    /// Offset/len of this function's name (canonical-ABI form, e.g.
    /// `"handle"`, `"[method]request.body"`).
    fn_name_offset: i32,
    fn_name_len: i32,
    /// Offset of the retptr scratch buffer; set iff `import_sig.retptr`.
    retptr_offset: Option<i32>,
    /// `(flat_param_idx, resource_type_id)` for each top-level
    /// `borrow<R>` param. The runtime requires us to drop the borrow
    /// before the wrapper returns; see `emit_wrapper_body`.
    borrow_drops: Vec<(u32, TypeId)>,
}
impl FuncDispatch {
    /// Single flat result for the Direct (non-retptr, non-void) case.
    fn direct_result(&self) -> Option<ValType> {
        if !self.export_sig.retptr && self.export_sig.results.len() == 1 {
            Some(wasm_type_to_val(self.export_sig.results[0]))
        } else {
            None
        }
    }
}

/// wit-parser [`WasmType`]s → wasm-encoder [`ValType`]s.
fn val_types(types: &[WasmType]) -> Vec<ValType> {
    types.iter().copied().map(wasm_type_to_val).collect()
}

/// Top-level `borrow<R>` params, returned as `(flat_idx, resource_id)`.
/// Top-level only — borrows nested inside compound params aren't yet
/// dropped (out of scope until the fuzzer surfaces such shapes).
fn collect_borrow_drops(resolve: &Resolve, func: &WitFunction) -> Vec<(u32, TypeId)> {
    let mut out = Vec::new();
    let mut flat_idx: u32 = 0;
    for param in &func.params {
        if let Type::Id(tid) = param.ty {
            if let TypeDefKind::Handle(Handle::Borrow(rid)) = &resolve.types[tid].kind {
                out.push((flat_idx, resolve_type_alias(resolve, *rid)));
                flat_idx += 1;
                continue;
            }
        }
        let mut storage = vec![WasmType::I32; 32];
        let mut flat = FlatTypes::new(storage.as_mut_slice());
        if !resolve.push_flat(&param.ty, &mut flat) {
            return Vec::new();
        }
        flat_idx += flat.to_vec().len() as u32;
    }
    out
}

/// Follow `TypeDefKind::Type` aliases to the underlying definition
/// (e.g. an `api`-side `use types.{cat}` alias → the `types`-side
/// `resource cat` definition).
fn resolve_type_alias(resolve: &Resolve, mut tid: TypeId) -> TypeId {
    while let TypeDefKind::Type(Type::Id(next)) = &resolve.types[tid].kind {
        tid = *next;
    }
    tid
}

/// The dispatch module has one global — the bump pointer.
const BUMP_POINTER_GLOBAL: u32 = 0;

/// Synthesized adapter world's package + world name. The contents
/// don't matter as long as `select_world` and the WIT we push agree
/// on both.
const ADAPTER_WORLD_PACKAGE: &str = "splicer:adapter";
const ADAPTER_WORLD_NAME: &str = "adapter";

/// Module name + intrinsic field names for the canon-async runtime
/// builtins the dispatch module imports. These are wit-component
/// contract — not exposed via wit-parser's API; the canonical list
/// lives in `wit-component::dummy::push_root_async_intrinsics`.
const ASYNC_INTRINSIC_MODULE: &str = "$root";
const WAITABLE_SET_NEW: &str = "[waitable-set-new]";
const WAITABLE_JOIN: &str = "[waitable-join]";
const WAITABLE_SET_WAIT: &str = "[waitable-set-wait]";
const WAITABLE_SET_DROP: &str = "[waitable-set-drop]";
const SUBTASK_DROP: &str = "[subtask-drop]";

/// Standard wasm exports the dispatch module exposes. Sourced as
/// strings rather than re-derived from `Resolve::wasm_export_name`
/// because they're invariants of `wit_component::ComponentEncoder`'s
/// Legacy mangling, not anything that varies per-resolve.
const EXPORT_MEMORY: &str = "memory";
const EXPORT_CABI_REALLOC: &str = "cabi_realloc";
const EXPORT_INITIALIZE: &str = "_initialize";

/// Type-section indices. `task_return_ty[i]` is `Some` iff func `i` is async.
struct TypeIndices {
    handler_ty: Vec<u32>,
    wrapper_ty: Vec<u32>,
    task_return_ty: Vec<Option<u32>>,
    /// Before/after hook sig: `(ptr, len) -> i32`.
    hook_ty: u32,
    /// Blocking hook sig: `(ptr, len, retptr) -> i32`. `Some` iff
    /// blocking is active.
    block_hook_ty: Option<u32>,
    init_ty: u32,
    cabi_post_ty: u32,
    cabi_realloc_ty: u32,
    async_runtime: Option<AsyncRuntimeTypes>,
    /// `(func (param i32))` for `[resource-drop]<R>` imports. `Some`
    /// iff any per_func has borrow params.
    resource_drop_ty: Option<u32>,
}

/// Canon-async runtime builtin types (`$root/[waitable-*]`,
/// `[subtask-drop]`).
struct AsyncRuntimeTypes {
    /// `() -> i32`.
    waitable_new_ty: u32,
    /// `(i32, i32) -> ()`.
    waitable_join_ty: u32,
    /// `(i32, i32) -> i32`.
    waitable_wait_ty: u32,
    /// `(i32) -> ()` — shared by `[waitable-set-drop]` + `[subtask-drop]`.
    void_i32_ty: u32,
}

/// Imports come first (handlers, hooks, async-runtime, task.return),
/// then defined functions starting at `wrapper_base`. `imp_task_return[i]`
/// and `cabi_post[i]` are `Some` only for the per-func cases that need them.
struct FuncIndices {
    imp_handler: Vec<u32>,
    imp_before: Option<u32>,
    imp_after: Option<u32>,
    /// `should-block` import; `Some` iff blocking is active.
    imp_block: Option<u32>,
    imp_task_return: Vec<Option<u32>>,
    wrapper_base: u32,
    init: u32,
    /// `Some` iff sync + retptr (async-stackful has no post-return).
    cabi_post: Vec<Option<u32>>,
    /// Always `Some` — `cabi_realloc` is unconditionally exported.
    cabi_realloc: Option<u32>,
    /// Memory offset of the bool slot `should-block` writes its
    /// retptr into. `Some` iff blocking is active.
    block_result_ptr: Option<i32>,
    async_runtime: Option<AsyncRuntimeFuncs>,
    /// `[resource-drop]<R>` import per resource referenced by a borrow
    /// param across `per_func`.
    resource_drop: HashMap<TypeId, u32>,
}

/// Canon-async runtime builtin indices + the wait-event scratch
/// offset. Populated whenever any hook is active or any target func
/// is async.
struct AsyncRuntimeFuncs {
    waitable_new: u32,
    waitable_join: u32,
    waitable_wait: u32,
    waitable_drop: u32,
    subtask_drop: u32,
    event_ptr: i32,
}

/// Build the dispatch core module — phase orchestrator. `cabi_realloc` + the bump global
/// are emitted unconditionally (matches `wit_component::dummy_module`);
/// the ~30-byte cost is cheaper than a "does any type transitively contain a string/list?" walker.
fn build_dispatch_module(
    resolve: &Resolve,
    world_id: wit_parser::WorldId,
    target_iface: InterfaceId,
    target_interface_name: &str,
    has_before: bool,
    has_after: bool,
    has_blocking: bool,
) -> Vec<u8> {
    let funcs: Vec<&WitFunction> = resolve.interfaces[target_iface]
        .functions
        .values()
        .collect();
    // Any hook OR any async target needs the canon-async builtins
    // to await its subtask handle.
    let any_async_target = funcs.iter().any(|f| f.kind.is_async());
    let needs_async_runtime = has_before || has_after || has_blocking || any_async_target;
    let mut sizes = SizeAlign::default();
    sizes.fill(resolve);
    let (per_func, name_blob, event_ptr, block_result_ptr, bump_start) = compute_func_dispatches(
        resolve,
        &sizes,
        target_iface,
        target_interface_name,
        &funcs,
        needs_async_runtime,
        has_blocking,
    );
    let hook_imports = collect_hook_imports(resolve, world_id, has_before, has_after, has_blocking);
    let mut idx = DispatchIndices::new();

    let mut module = Module::new();
    let type_idx = emit_type_section(&mut module, &mut idx, &per_func, &hook_imports);
    let func_idx = emit_imports_section(
        &mut module,
        &mut idx,
        &per_func,
        &type_idx,
        &hook_imports,
        event_ptr,
        block_result_ptr,
        resolve,
    );
    let func_idx = emit_function_section(&mut module, &mut idx, &per_func, &type_idx, func_idx);
    emit_memory_and_globals(&mut module, bump_start);
    emit_export_section(&mut module, &per_func, &func_idx);
    emit_code_section(&mut module, resolve, &sizes, &per_func, &func_idx);
    emit_data_section(&mut module, &name_blob);

    module.finish()
}

/// Phase 1 — derive per-func dispatch shapes, collect name bytes, and
/// reserve memory slots for retptr scratch + the async-event record.
/// Hooks receive a `call-id { interface-name, function-name }` record:
/// the interface name is allocated once at the head of memory and
/// shared by every `FuncDispatch`; each function name is allocated
/// per-func right after.
/// `event_ptr` is `Some` iff `needs_async_runtime`.
#[allow(clippy::too_many_arguments)]
fn compute_func_dispatches(
    resolve: &Resolve,
    sizes: &SizeAlign,
    target_iface: InterfaceId,
    target_interface_name: &str,
    funcs: &[&WitFunction],
    needs_async_runtime: bool,
    has_blocking: bool,
) -> (Vec<FuncDispatch>, Vec<u8>, Option<i32>, Option<i32>, u32) {
    let iface_name_bytes = target_interface_name.len() as u32;
    let total_fn_name_bytes: u32 = funcs.iter().map(|f| f.name.len() as u32).sum();
    let total_name_bytes = iface_name_bytes + total_fn_name_bytes;
    let mut layout = MemoryLayoutBuilder::new(total_name_bytes);
    let mut name_blob: Vec<u8> = Vec::with_capacity(total_name_bytes as usize);
    let mut per_func: Vec<FuncDispatch> = Vec::with_capacity(funcs.len());

    // Iface name allocated once and reused across all FuncDispatches.
    let iface_name_offset = layout.alloc_name(iface_name_bytes) as i32;
    name_blob.extend_from_slice(target_interface_name.as_bytes());

    let target_world_key = WorldKey::Interface(target_iface);

    for func in funcs.iter() {
        let is_async = func.kind.is_async();
        let (import_variant, export_variant) = if is_async {
            (
                AbiVariant::GuestImportAsync,
                AbiVariant::GuestExportAsyncStackful,
            )
        } else {
            (AbiVariant::GuestImport, AbiVariant::GuestExport)
        };
        // Same mangling on both sides → matched `[async-lower]<fn>` /
        // `[async-lift-stackful]<iface>#<fn>` pair (or no prefix for sync).
        let mangling = ManglingAndAbi::Legacy(if is_async {
            LiftLowerAbi::AsyncStackful
        } else {
            LiftLowerAbi::Sync
        });
        let (import_module, import_field) = resolve.wasm_import_name(
            mangling,
            WasmImport::Func {
                interface: Some(&target_world_key),
                func,
            },
        );
        let export_name = resolve.wasm_export_name(
            mangling,
            WasmExport::Func {
                interface: Some(&target_world_key),
                func,
                kind: WasmExportKind::Normal,
            },
        );
        let export_sig = resolve.wasm_signature(export_variant, func);
        let import_sig = resolve.wasm_signature(import_variant, func);
        let fn_name_offset = layout.alloc_name(func.name.len() as u32) as i32;
        name_blob.extend_from_slice(func.name.as_bytes());
        // Sync: retptr iff the export sig says so. Async: canon-lower-async
        // always retptr's a non-void result.
        let retptr_needed = if is_async {
            import_sig.retptr
        } else {
            export_sig.retptr
        };
        let retptr_offset = retptr_needed.then(|| {
            // Exact canonical-ABI size + alignment of the result type
            // — anything smaller than the type's natural alignment
            // (e.g. 4-byte buffer for an i64-bearing variant) traps
            // with "unaligned pointer" inside `lift_from_memory` /
            // wit-bindgen's async runtime.
            let result_ty = func
                .result
                .as_ref()
                .expect("retptr_needed → func.result is_some()");
            let size = sizes.size(result_ty).size_wasm32() as u32;
            let align = sizes.align(result_ty).align_wasm32() as u32;
            layout.alloc_retptr_scratch(size, align) as i32
        });
        let task_return = is_async.then(|| {
            let (module, name, sig) =
                func.task_return_import(resolve, Some(&target_world_key), Mangling::Legacy);
            TaskReturnImport { module, name, sig }
        });
        let borrow_drops = collect_borrow_drops(resolve, func);
        per_func.push(FuncDispatch {
            import_module,
            import_field,
            export_name,
            is_async,
            export_sig,
            import_sig,
            result_ty: func.result,
            task_return,
            iface_name_offset,
            iface_name_len: iface_name_bytes as i32,
            fn_name_offset,
            fn_name_len: func.name.len() as i32,
            retptr_offset,
            borrow_drops,
        });
    }
    // [`MemoryLayoutBuilder`] is single-cursor — fixed slots land
    // AFTER per-func name + retptr allocations, in the same order
    // the legacy path uses.
    let event_ptr = needs_async_runtime.then(|| layout.alloc_event_slot() as i32);
    let block_result_ptr = has_blocking.then(|| layout.alloc_block_result() as i32);
    let bump_start = layout.finish_as_bump_start();
    (per_func, name_blob, event_ptr, block_result_ptr, bump_start)
}

/// wit-parser [`WasmType`] → wasm-encoder [`ValType`] (wasm32:
/// `Pointer`/`Length` → i32, `PointerOrI64` → i64).
fn wasm_type_to_val(wt: WasmType) -> ValType {
    match wt {
        WasmType::I32 | WasmType::Pointer | WasmType::Length => ValType::I32,
        WasmType::I64 | WasmType::PointerOrI64 => ValType::I64,
        WasmType::F32 => ValType::F32,
        WasmType::F64 => ValType::F64,
    }
}

/// One tier-1 hook import — `(module, name)` from
/// [`Resolve::wasm_import_name`] + sig from [`Resolve::wasm_signature`].
struct HookImport {
    module: String,
    name: String,
    sig: WasmSignature,
}

/// Active tier-1 hook imports. `before` / `after` share a common sig
/// (`(ptr, len) -> i32`); `blocking` has a retptr param for the bool
/// result (`(ptr, len, retptr) -> i32`).
struct HookImports {
    before: Option<HookImport>,
    after: Option<HookImport>,
    blocking: Option<HookImport>,
}

impl HookImports {
    fn any(&self) -> bool {
        self.before.is_some() || self.after.is_some() || self.blocking.is_some()
    }
}

/// Resolve tier-1 hook imports through wit-parser so a contract bump
/// (or a `wit/tier1/world.wit` signature change) can't silently
/// desync the dispatch module.
fn collect_hook_imports(
    resolve: &Resolve,
    world_id: wit_parser::WorldId,
    has_before: bool,
    has_after: bool,
    has_blocking: bool,
) -> HookImports {
    use crate::contract::{
        versioned_interface, TIER1_AFTER, TIER1_BEFORE, TIER1_BLOCKING, TIER1_VERSION,
    };
    let world = &resolve.worlds[world_id];
    let resolve_one = |iface_name: &str| -> Option<HookImport> {
        world.imports.iter().find_map(|(key, item)| {
            let WorldItem::Interface { id, .. } = item else {
                return None;
            };
            if resolve.id_of(*id).as_deref() != Some(iface_name) {
                return None;
            }
            // Tier-1 interfaces have exactly one function each.
            let func = resolve.interfaces[*id].functions.values().next()?;
            let (module, name) = resolve.wasm_import_name(
                ManglingAndAbi::Legacy(LiftLowerAbi::AsyncCallback),
                WasmImport::Func {
                    interface: Some(key),
                    func,
                },
            );
            let sig = resolve.wasm_signature(AbiVariant::GuestImportAsync, func);
            Some(HookImport { module, name, sig })
        })
    };
    let pick = |active: bool, iface: &str| -> Option<HookImport> {
        if !active {
            return None;
        }
        resolve_one(&versioned_interface(iface, TIER1_VERSION))
    };
    HookImports {
        before: pick(has_before, TIER1_BEFORE),
        after: pick(has_after, TIER1_AFTER),
        blocking: pick(has_blocking, TIER1_BLOCKING),
    }
}

/// Phase 2 — type section: per-func handler + wrapper (+ per-async-func
/// task.return), then the four singletons (hook, init, cabi_post,
/// cabi_realloc), then the async-runtime builtin types when needed.
fn emit_type_section(
    module: &mut Module,
    idx: &mut DispatchIndices,
    per_func: &[FuncDispatch],
    hook_imports: &HookImports,
) -> TypeIndices {
    let mut types = TypeSection::new();
    let mut handler_ty: Vec<u32> = Vec::with_capacity(per_func.len());
    let mut wrapper_ty: Vec<u32> = Vec::with_capacity(per_func.len());
    let mut task_return_ty: Vec<Option<u32>> = vec![None; per_func.len()];

    for (i, fd) in per_func.iter().enumerate() {
        types.ty().function(
            val_types(&fd.import_sig.params),
            val_types(&fd.import_sig.results),
        );
        handler_ty.push(idx.alloc_ty());
        types.ty().function(
            val_types(&fd.export_sig.params),
            val_types(&fd.export_sig.results),
        );
        wrapper_ty.push(idx.alloc_ty());
        if let Some(tr) = &fd.task_return {
            types
                .ty()
                .function(val_types(&tr.sig.params), val_types(&tr.sig.results));
            task_return_ty[i] = Some(idx.alloc_ty());
        }
    }

    // Both hooks share the same `async func(name: string)` shape; pick
    // whichever's active. With neither active the slot is unreferenced
    // and falls back to `() -> ()`.
    let hook_sig = hook_imports
        .before
        .as_ref()
        .or(hook_imports.after.as_ref())
        .map(|h| (val_types(&h.sig.params), val_types(&h.sig.results)))
        .unwrap_or_else(|| (vec![], vec![]));
    types.ty().function(hook_sig.0, hook_sig.1);
    let hook_ty = idx.alloc_ty();
    types.ty().function([], []);
    let init_ty = idx.alloc_ty();
    types.ty().function([ValType::I32], []);
    let cabi_post_ty = idx.alloc_ty();
    types.ty().function(
        [ValType::I32, ValType::I32, ValType::I32, ValType::I32],
        [ValType::I32],
    );
    let cabi_realloc_ty = idx.alloc_ty();

    // Blocking hook sig — sourced from the WIT (`should-block:
    // async func(name: string) -> bool` lowered → `(ptr, len, retptr) -> i32`).
    let block_hook_ty = hook_imports.blocking.as_ref().map(|h| {
        types
            .ty()
            .function(val_types(&h.sig.params), val_types(&h.sig.results));
        idx.alloc_ty()
    });

    // Async-runtime types are needed when a hook is active OR any
    // target func is async — both fire the wait loop in the wrapper
    // body. Gating only on hooks would leave a hook-less async-target
    // module unable to await its handler subtask.
    let needs_async_runtime = hook_imports.any() || per_func.iter().any(|f| f.is_async);
    let async_runtime = needs_async_runtime.then(|| {
        types.ty().function([], [ValType::I32]);
        let waitable_new_ty = idx.alloc_ty();
        types.ty().function([ValType::I32, ValType::I32], []);
        let waitable_join_ty = idx.alloc_ty();
        types
            .ty()
            .function([ValType::I32, ValType::I32], [ValType::I32]);
        let waitable_wait_ty = idx.alloc_ty();
        types.ty().function([ValType::I32], []);
        let void_i32_ty = idx.alloc_ty();
        AsyncRuntimeTypes {
            waitable_new_ty,
            waitable_join_ty,
            waitable_wait_ty,
            void_i32_ty,
        }
    });

    // `[resource-drop]<R>`: `(func (param i32))`. Reuse async runtime's
    // void-i32 slot when available; otherwise allocate fresh.
    let needs_resource_drop = per_func.iter().any(|f| !f.borrow_drops.is_empty());
    let resource_drop_ty = needs_resource_drop.then(|| {
        if let Some(art) = &async_runtime {
            art.void_i32_ty
        } else {
            types.ty().function([ValType::I32], []);
            idx.alloc_ty()
        }
    });

    module.section(&types);
    TypeIndices {
        handler_ty,
        wrapper_ty,
        task_return_ty,
        hook_ty,
        block_hook_ty,
        init_ty,
        cabi_post_ty,
        cabi_realloc_ty,
        async_runtime,
        resource_drop_ty,
    }
}

/// Phase 3 — import section: per-func handlers + hooks + async-runtime
/// builtins + per-async-func task.return. Hook + handler names come
/// from [`Resolve::wasm_import_name`]; the `$root/[waitable-*]` /
/// `[subtask-drop]` builtins are wit-component intrinsics not exposed
/// via wit-parser (mirrors `dummy_module::push_root_async_intrinsics`).
#[allow(clippy::too_many_arguments)]
fn emit_imports_section(
    module: &mut Module,
    idx: &mut DispatchIndices,
    per_func: &[FuncDispatch],
    type_idx: &TypeIndices,
    hook_imports: &HookImports,
    event_ptr: Option<i32>,
    block_result_ptr: Option<i32>,
    resolve: &Resolve,
) -> FuncIndices {
    let mut imports = ImportSection::new();
    let mut imp_handler: Vec<u32> = Vec::with_capacity(per_func.len());
    for (i, fd) in per_func.iter().enumerate() {
        imports.import(
            &fd.import_module,
            &fd.import_field,
            EntityType::Function(type_idx.handler_ty[i]),
        );
        imp_handler.push(idx.alloc_func());
    }
    // `[resource-drop]<R>` imports for each unique resource referenced
    // by a borrow param. Imported from the owning interface (factored
    // types: resource lives in `<pkg>/types`, not the using interface).
    let mut resource_drop: HashMap<TypeId, u32> = HashMap::new();
    if let Some(drop_ty) = type_idx.resource_drop_ty {
        let mut unique: Vec<TypeId> = per_func
            .iter()
            .flat_map(|f| f.borrow_drops.iter().map(|(_, rid)| *rid))
            .collect();
        unique.sort();
        unique.dedup();
        for rid in unique {
            // Drop is imported from the resource's owning interface
            // (e.g. `<pkg>/types`), not from the using interface.
            // `wasm_import_name` then returns the canonical
            // `<owner-iface>` / `[resource-drop]<R>` pair.
            let owner_iface = match resolve.types[rid].owner {
                TypeOwner::Interface(iid) => iid,
                _ => continue,
            };
            let owner_key = WorldKey::Interface(owner_iface);
            let imp = WasmImport::ResourceIntrinsic {
                interface: Some(&owner_key),
                resource: rid,
                intrinsic: ResourceIntrinsic::ImportedDrop,
            };
            let (module_name, field_name) =
                resolve.wasm_import_name(ManglingAndAbi::Legacy(LiftLowerAbi::Sync), imp);
            imports.import(&module_name, &field_name, EntityType::Function(drop_ty));
            resource_drop.insert(rid, idx.alloc_func());
        }
    }
    let mut import_hook = |hook: &HookImport| {
        imports.import(
            &hook.module,
            &hook.name,
            EntityType::Function(type_idx.hook_ty),
        );
        idx.alloc_func()
    };
    let imp_before = hook_imports.before.as_ref().map(&mut import_hook);
    let imp_after = hook_imports.after.as_ref().map(&mut import_hook);
    let imp_block = hook_imports.blocking.as_ref().map(|hook| {
        let ty = type_idx
            .block_hook_ty
            .expect("block_hook_ty allocated when blocking is active");
        imports.import(&hook.module, &hook.name, EntityType::Function(ty));
        idx.alloc_func()
    });

    let async_runtime = type_idx.async_runtime.as_ref().map(|art| {
        let event_ptr = event_ptr.expect("event_ptr must be set when async_runtime is");
        let mut import_intrinsic = |name: &str, ty: u32| {
            imports.import(ASYNC_INTRINSIC_MODULE, name, EntityType::Function(ty));
            idx.alloc_func()
        };
        let waitable_new = import_intrinsic(WAITABLE_SET_NEW, art.waitable_new_ty);
        let waitable_join = import_intrinsic(WAITABLE_JOIN, art.waitable_join_ty);
        let waitable_wait = import_intrinsic(WAITABLE_SET_WAIT, art.waitable_wait_ty);
        let waitable_drop = import_intrinsic(WAITABLE_SET_DROP, art.void_i32_ty);
        let subtask_drop = import_intrinsic(SUBTASK_DROP, art.void_i32_ty);
        AsyncRuntimeFuncs {
            waitable_new,
            waitable_join,
            waitable_wait,
            waitable_drop,
            subtask_drop,
            event_ptr,
        }
    });

    // task.return: `[export]<iface>` / `[task-return]<fn>` per
    // `Function::task_return_import` (already in `fd.task_return`).
    let mut imp_task_return: Vec<Option<u32>> = vec![None; per_func.len()];
    for (i, fd) in per_func.iter().enumerate() {
        if let Some(tr) = &fd.task_return {
            let ty_idx = type_idx.task_return_ty[i].expect("task_return_ty allocated for async");
            imports.import(&tr.module, &tr.name, EntityType::Function(ty_idx));
            imp_task_return[i] = Some(idx.alloc_func());
        }
    }

    module.section(&imports);

    FuncIndices {
        imp_handler,
        imp_before,
        imp_after,
        imp_block,
        imp_task_return,
        wrapper_base: 0,
        init: 0,
        cabi_post: vec![None; per_func.len()],
        cabi_realloc: None,
        block_result_ptr,
        async_runtime,
        resource_drop,
    }
}

/// Phase 4 — function section. `cabi_realloc` is always declared.
fn emit_function_section(
    module: &mut Module,
    idx: &mut DispatchIndices,
    per_func: &[FuncDispatch],
    type_idx: &TypeIndices,
    mut func_idx: FuncIndices,
) -> FuncIndices {
    let mut fsec = FunctionSection::new();

    let wrapper_base = idx.func;
    for &t in &type_idx.wrapper_ty {
        fsec.function(t);
    }
    for _ in per_func {
        idx.alloc_func();
    }
    func_idx.wrapper_base = wrapper_base;

    fsec.function(type_idx.init_ty);
    func_idx.init = idx.alloc_func();

    // `cabi_post_*` only for sync retptr — async-stackful has no
    // post-return contract.
    for (i, fd) in per_func.iter().enumerate() {
        if fd.export_sig.retptr && !fd.is_async {
            fsec.function(type_idx.cabi_post_ty);
            func_idx.cabi_post[i] = Some(idx.alloc_func());
        }
    }

    fsec.function(type_idx.cabi_realloc_ty);
    func_idx.cabi_realloc = Some(idx.alloc_func());

    module.section(&fsec);
    func_idx
}

/// Phase 5 — memory + bump-pointer global (paired with `cabi_realloc`).
fn emit_memory_and_globals(module: &mut Module, bump_start: u32) {
    let mut memory = MemorySection::new();
    memory.memory(MemoryType {
        minimum: 1,
        maximum: None,
        memory64: false,
        shared: false,
        page_size_log2: None,
    });
    module.section(&memory);

    let mut globals = GlobalSection::new();
    globals.global(
        GlobalType {
            val_type: ValType::I32,
            mutable: true,
            shared: false,
        },
        &ConstExpr::i32_const(bump_start as i32),
    );
    module.section(&globals);
}

/// Phase 6 — export section. Wrapper names come from
/// [`Resolve::wasm_export_name`] via [`FuncDispatch::export_name`].
fn emit_export_section(module: &mut Module, per_func: &[FuncDispatch], func_idx: &FuncIndices) {
    let mut exports = ExportSection::new();
    for (i, fd) in per_func.iter().enumerate() {
        exports.export(
            &fd.export_name,
            ExportKind::Func,
            func_idx.wrapper_base + i as u32,
        );
        if let Some(post_idx) = func_idx.cabi_post[i] {
            let post_name = format!("cabi_post_{}", fd.export_name);
            exports.export(&post_name, ExportKind::Func, post_idx);
        }
    }
    exports.export(EXPORT_MEMORY, ExportKind::Memory, 0);
    let realloc_idx = func_idx
        .cabi_realloc
        .expect("cabi_realloc is always emitted");
    exports.export(EXPORT_CABI_REALLOC, ExportKind::Func, realloc_idx);
    exports.export(EXPORT_INITIALIZE, ExportKind::Func, func_idx.init);
    module.section(&exports);
}

/// Phase 7 — code section, declaration order matches phase 4.
fn emit_code_section(
    module: &mut Module,
    resolve: &Resolve,
    sizes: &SizeAlign,
    per_func: &[FuncDispatch],
    func_idx: &FuncIndices,
) {
    let blocking =
        func_idx
            .imp_block
            .zip(func_idx.block_result_ptr)
            .map(|(import_fn, result_ptr)| BlockingConfig {
                import_fn,
                result_ptr,
            });
    let mut code = CodeSection::new();
    for (i, fd) in per_func.iter().enumerate() {
        if fd.is_async {
            emit_async_wrapper_body(
                &mut code,
                resolve,
                sizes,
                fd,
                func_idx.imp_handler[i],
                func_idx.imp_before,
                func_idx.imp_after,
                blocking.as_ref(),
                func_idx.imp_task_return[i].expect("async func must have task.return import"),
                func_idx
                    .async_runtime
                    .as_ref()
                    .expect("async runtime imports active when any func is async"),
                &func_idx.resource_drop,
            );
        } else {
            emit_wrapper_body(
                &mut code,
                fd,
                func_idx.imp_handler[i],
                func_idx.imp_before,
                func_idx.imp_after,
                blocking.as_ref(),
                func_idx.async_runtime.as_ref(),
                &func_idx.resource_drop,
            );
        }
    }
    code.function(&empty_function());
    for fd in per_func {
        if fd.export_sig.retptr && !fd.is_async {
            code.function(&empty_function());
        }
    }
    emit_cabi_realloc(&mut code);
    module.section(&code);
}

/// Phase 8 — active data segment with the concatenated `<iface>#<fn>`
/// names the hooks see.
fn emit_data_section(module: &mut Module, name_blob: &[u8]) {
    if name_blob.is_empty() {
        return;
    }
    let mut data = DataSection::new();
    data.active(0, &ConstExpr::i32_const(0), name_blob.iter().copied());
    module.section(&data);
}

/// `should-block` runtime bundle — the import fn index plus the
/// memory offset its retptr writes the bool result into.
struct BlockingConfig {
    import_fn: u32,
    result_ptr: i32,
}

/// Emit one sync wrapper body. Shape is read off
/// [`FuncDispatch::export_sig`]: `retptr` ⇒ multi-flat / compound,
/// else `results.len() == 1` ⇒ Direct, else Void.
#[allow(clippy::too_many_arguments)]
fn emit_wrapper_body(
    code: &mut CodeSection,
    fd: &FuncDispatch,
    imp_handler: u32,
    imp_before: Option<u32>,
    imp_after: Option<u32>,
    blocking: Option<&BlockingConfig>,
    async_runtime: Option<&AsyncRuntimeFuncs>,
    resource_drop: &HashMap<TypeId, u32>,
) {
    let nparams = fd.export_sig.params.len() as u32;
    let mut locals = FunctionIndices::new(nparams);
    let result_local = fd.direct_result().map(|t| locals.alloc_local(t));
    // Wait-loop scratch (subtask + waitable-set handles); shared
    // across on-call / on-return / blocking awaits.
    let wait_locals = async_runtime.map(|_| {
        let st = locals.alloc_local(ValType::I32);
        let ws = locals.alloc_local(ValType::I32);
        (st, ws)
    });
    let mut f = Function::new_with_locals_types(locals.into_locals());

    if let Some(idx) = imp_before {
        emit_hook_call(&mut f, fd, idx, async_runtime, wait_locals);
    }
    if let Some(blk) = blocking {
        // Sync void early-return: matches legacy `emit_blocking_phase`.
        // `require_supported_case` already rejects sync + non-void
        // when blocking is active, so we don't need the
        // local-restoration song-and-dance here.
        emit_blocking_phase(&mut f, fd, blk, async_runtime, wait_locals, None);
    }
    for p in 0..nparams {
        f.instructions().local_get(p);
    }
    if fd.export_sig.retptr {
        f.instructions()
            .i32_const(fd.retptr_offset.expect("retptr_offset set"));
    }
    f.instructions().call(imp_handler);
    if let Some(local) = result_local {
        f.instructions().local_set(local);
    }
    if let Some(idx) = imp_after {
        emit_hook_call(&mut f, fd, idx, async_runtime, wait_locals);
    }
    // Drop borrow handles before returning — the runtime requires
    // every borrow lifted on entry to be dropped before exit.
    for (flat_idx, rid) in &fd.borrow_drops {
        let drop_fn = resource_drop[rid];
        f.instructions().local_get(*flat_idx);
        f.instructions().call(drop_fn);
    }
    if let Some(local) = result_local {
        f.instructions().local_get(local);
    } else if fd.export_sig.retptr {
        f.instructions()
            .i32_const(fd.retptr_offset.expect("retptr_offset set"));
    }
    f.instructions().end();
    code.function(&f);
}

/// Phase 2 (between on-call and the handler call): call
/// `should-block(call, retptr)` with the canonical-ABI-lowered
/// `(iface_ptr, iface_len, fn_ptr, fn_len, retptr)` shape, await the
/// subtask, load the bool, and `return` early if it's true. For async
/// wrappers a `task.return` import index is supplied and called with
/// no args before the return (async-stackful must call task.return
/// before `End`); sync void wrappers just return.
///
/// Mirrors legacy `dispatch::emit_blocking_phase`.
/// `require_supported_case` already rejects non-void blocking, so
/// neither branch needs to fabricate a return value.
fn emit_blocking_phase(
    f: &mut Function,
    fd: &FuncDispatch,
    blk: &BlockingConfig,
    async_runtime: Option<&AsyncRuntimeFuncs>,
    wait_locals: Option<(u32, u32)>,
    task_return_for_async: Option<u32>,
) {
    f.instructions().i32_const(fd.iface_name_offset);
    f.instructions().i32_const(fd.iface_name_len);
    f.instructions().i32_const(fd.fn_name_offset);
    f.instructions().i32_const(fd.fn_name_len);
    f.instructions().i32_const(blk.result_ptr);
    f.instructions().call(blk.import_fn);
    let art = async_runtime.expect("async_runtime active when blocking is");
    let (st, ws) = wait_locals.expect("wait_locals allocated alongside async_runtime");
    f.instructions().local_set(st);
    emit_wait_loop(f, st, ws, art);
    f.instructions().i32_const(blk.result_ptr);
    f.instructions().i32_load(wasm_encoder::MemArg {
        offset: 0,
        align: 0,
        memory_index: 0,
    });
    f.instructions().if_(BlockType::Empty);
    if let Some(tr_fn) = task_return_for_async {
        f.instructions().call(tr_fn);
    }
    f.instructions().return_();
    f.instructions().end();
}

/// Emit one async-stackful wrapper body. Result is delivered via
/// `task.return` (not the wrapper's return); arg loads come from
/// [`lift_from_memory`] driven by [`WasmEncoderBindgen`].
#[allow(clippy::too_many_arguments)]
fn emit_async_wrapper_body(
    code: &mut CodeSection,
    resolve: &Resolve,
    sizes: &SizeAlign,
    fd: &FuncDispatch,
    imp_handler: u32,
    imp_before: Option<u32>,
    imp_after: Option<u32>,
    blocking: Option<&BlockingConfig>,
    imp_task_return: u32,
    async_runtime: &AsyncRuntimeFuncs,
    resource_drop: &HashMap<TypeId, u32>,
) {
    let nparams = fd.export_sig.params.len() as u32;
    let mut locals = FunctionIndices::new(nparams);
    // Wait-loop scratch, shared across hook awaits + the handler await.
    let st = locals.alloc_local(ValType::I32);
    let ws = locals.alloc_local(ValType::I32);
    let wait_locals = Some((st, ws));
    // task.return is `wasm_signature(GuestImport, fake_func_with_result_as_param)`:
    // small results flatten into params; large results overflow into a
    // single retptr param (`indirect_params=true`). The `retptr` flag is
    // only set for actual *results* and is always false for task.return
    // (whose fake_func has no result), so use `indirect_params` to pick
    // the path.
    let tr_sig = &fd.task_return.as_ref().expect("async has task_return").sig;
    let tr_uses_flat_loads = !tr_sig.indirect_params && fd.result_ty.is_some();
    let tr_addr_local = tr_uses_flat_loads.then(|| locals.alloc_local(ValType::I32));

    // Build the load sequence BEFORE freezing locals — `lift_from_memory`
    // allocates additional scratch (variant disc, joined-payload slots, …).
    let task_return_loads: Option<Vec<wasm_encoder::Instruction<'static>>> =
        tr_addr_local.map(|addr_local| {
            let result_ty = fd.result_ty.as_ref().expect("flat loads → result_ty");
            let mut bindgen = WasmEncoderBindgen::new(sizes, addr_local, &mut locals);
            lift_from_memory(resolve, &mut bindgen, (), result_ty);
            bindgen.into_instructions()
        });

    let mut f = Function::new_with_locals_types(locals.into_locals());

    if let Some(idx) = imp_before {
        emit_hook_call(&mut f, fd, idx, Some(async_runtime), wait_locals);
    }
    if let Some(blk) = blocking {
        // Async-with-result + blocking is rejected in `require_supported_case`
        // (no way to fabricate the result), so reaching here means the
        // wrapper is async-void — we still need a `task.return` call
        // before returning early.
        emit_blocking_phase(
            &mut f,
            fd,
            blk,
            Some(async_runtime),
            wait_locals,
            Some(imp_task_return),
        );
    }

    // Handler call → packed status → wait.
    for p in 0..nparams {
        f.instructions().local_get(p);
    }
    if fd.import_sig.retptr {
        f.instructions()
            .i32_const(fd.retptr_offset.expect("retptr_offset for async retptr"));
    }
    f.instructions().call(imp_handler);
    f.instructions().local_set(st);
    emit_wait_loop(&mut f, st, ws, async_runtime);

    if let Some(idx) = imp_after {
        emit_hook_call(&mut f, fd, idx, Some(async_runtime), wait_locals);
    }

    // Drop borrow handles before returning.
    for (flat_idx, rid) in &fd.borrow_drops {
        let drop_fn = resource_drop[rid];
        f.instructions().local_get(*flat_idx);
        f.instructions().call(drop_fn);
    }

    // task.return shape: void (no args), retptr (pass the buffer
    // through — large compound result), or flat (lift each slot via
    // `lift_from_memory`).
    if fd.result_ty.is_none() {
        f.instructions().call(imp_task_return);
    } else if tr_sig.indirect_params {
        f.instructions()
            .i32_const(fd.retptr_offset.expect("retptr_offset for async retptr"));
        f.instructions().call(imp_task_return);
    } else {
        let addr_local = tr_addr_local.expect("flat loads → tr_addr_local");
        f.instructions()
            .i32_const(fd.retptr_offset.expect("retptr_offset for async retptr"));
        f.instructions().local_set(addr_local);
        for inst in task_return_loads
            .as_ref()
            .expect("task_return_loads built for flat loads")
        {
            f.instruction(inst);
        }
        f.instructions().call(imp_task_return);
    }
    f.instructions().end();
    code.function(&f);
}

/// Call hook with `(iface_ptr, iface_len, fn_ptr, fn_len)` — the
/// canonical-ABI lowering of `call: call-id { interface-name: string,
/// function-name: string }` — and await its packed subtask handle.
/// `async_runtime` + `wait_locals` are `Some` whenever a hook is
/// active.
fn emit_hook_call(
    f: &mut Function,
    fd: &FuncDispatch,
    hook_idx: u32,
    async_runtime: Option<&AsyncRuntimeFuncs>,
    wait_locals: Option<(u32, u32)>,
) {
    f.instructions().i32_const(fd.iface_name_offset);
    f.instructions().i32_const(fd.iface_name_len);
    f.instructions().i32_const(fd.fn_name_offset);
    f.instructions().i32_const(fd.fn_name_len);
    f.instructions().call(hook_idx);
    let art = async_runtime.expect("async_runtime must be set when a hook is imported");
    let (st, ws) = wait_locals.expect("wait_locals allocated alongside async_runtime");
    f.instructions().local_set(st);
    emit_wait_loop(f, st, ws, art);
}

/// Await a packed `canon lower async` status in local `st`. The packed
/// i32 is `(handle << 4) | status_tag` (tag: 1=Started, 2=Returned);
/// after this helper `st` holds the raw handle, and if it was nonzero
/// the subtask has been joined into a fresh waitable-set, waited on,
/// and both handles dropped.
fn emit_wait_loop(f: &mut Function, st: u32, ws: u32, art: &AsyncRuntimeFuncs) {
    f.instructions().local_get(st);
    f.instructions().i32_const(4);
    f.instructions().i32_shr_u();
    f.instructions().local_set(st);
    f.instructions().local_get(st);
    f.instructions().if_(BlockType::Empty);
    f.instructions().call(art.waitable_new);
    f.instructions().local_set(ws);
    f.instructions().local_get(st);
    f.instructions().local_get(ws);
    f.instructions().call(art.waitable_join);
    f.instructions().local_get(ws);
    f.instructions().i32_const(art.event_ptr);
    f.instructions().call(art.waitable_wait);
    f.instructions().drop();
    f.instructions().local_get(st);
    f.instructions().call(art.subtask_drop);
    f.instructions().local_get(ws);
    f.instructions().call(art.waitable_drop);
    f.instructions().end();
}

/// No-op function body — used for `_initialize` and `cabi_post_*`.
fn empty_function() -> Function {
    let mut f = Function::new_with_locals_types([]);
    f.instructions().end();
    f
}

/// Bump-allocator `cabi_realloc(old_ptr, old_size, align, new_size)`.
/// Every call is a fresh alloc — `old_ptr`/`old_size` are ignored.
fn emit_cabi_realloc(code: &mut CodeSection) {
    const PARAM_COUNT: u32 = 4;
    const ALIGN_LOCAL: u32 = 2;
    const NEW_SIZE_LOCAL: u32 = 3;
    let mut locals = FunctionIndices::new(PARAM_COUNT);
    let scratch = locals.alloc_local(ValType::I32);
    let mut f = Function::new_with_locals_types(locals.into_locals());

    // scratch = (global.bump + (align - 1)) & ~(align - 1)
    f.instructions().global_get(BUMP_POINTER_GLOBAL);
    f.instructions().local_get(ALIGN_LOCAL);
    f.instructions().i32_const(1);
    f.instructions().i32_sub();
    f.instructions().i32_add();
    f.instructions().local_get(ALIGN_LOCAL);
    f.instructions().i32_const(1);
    f.instructions().i32_sub();
    f.instructions().i32_const(-1);
    f.instructions().i32_xor();
    f.instructions().i32_and();
    f.instructions().local_set(scratch);

    // global.bump = scratch + new_size
    f.instructions().local_get(scratch);
    f.instructions().local_get(NEW_SIZE_LOCAL);
    f.instructions().i32_add();
    f.instructions().global_set(BUMP_POINTER_GLOBAL);

    // return scratch
    f.instructions().local_get(scratch);
    f.instructions().end();
    code.function(&f);
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Parse `wit`, find `<pkg_name>/<iface_name>`, return its
    /// `InterfaceId`. Drives `require_supported_case` directly from a
    /// WIT source string.
    fn iface_from_wit(wit: &str, pkg_name: &str, iface_name: &str) -> (Resolve, InterfaceId) {
        let mut resolve = Resolve::default();
        resolve.push_str("test.wit", wit).expect("parse test WIT");
        let target = format!("{pkg_name}/{iface_name}");
        let iface_id = resolve
            .interfaces
            .iter()
            .find(|(id, _)| resolve.id_of(*id).as_deref() == Some(&target))
            .map(|(id, _)| id)
            .expect("target interface present");
        (resolve, iface_id)
    }

    /// Inline-resource interface (`resource cat` declared inside the
    /// same interface that uses it) bails with a clear error pointing
    /// at the factored-types fix.
    #[test]
    fn require_supported_case_bails_on_inline_resource() {
        let (resolve, iface_id) = iface_from_wit(
            r#"
            package my:shape@1.0.0;
            interface api {
                resource cat { constructor(); }
                foo: func(x: cat) -> cat;
            }
            "#,
            "my:shape",
            "api@1.0.0",
        );
        let err = require_supported_case(&resolve, iface_id, false)
            .expect_err("inline resource should bail");
        let msg = err.to_string();
        assert!(
            msg.contains("declares resource `cat` inline"),
            "error should call out the inline declaration; got: {msg}"
        );
        assert!(
            msg.contains("factored-types pattern"),
            "error should point at the factored-types fix; got: {msg}"
        );
    }

    /// Factored-types: resource in a sibling `types` interface,
    /// referenced via `use types.{{cat}}` in `api`. Accepted.
    #[test]
    fn require_supported_case_accepts_factored_types() {
        let (resolve, iface_id) = iface_from_wit(
            r#"
            package my:shape@1.0.0;
            interface types {
                resource cat { constructor(); }
            }
            interface api {
                use types.{cat};
                foo: func(x: cat) -> cat;
            }
            "#,
            "my:shape",
            "api@1.0.0",
        );
        require_supported_case(&resolve, iface_id, false)
            .expect("factored-types should be accepted");
    }

    /// Sanity: value-type-only interfaces (no resources at all) pass.
    #[test]
    fn require_supported_case_accepts_value_types() {
        let (resolve, iface_id) = iface_from_wit(
            r#"
            package my:shape@1.0.0;
            interface api {
                foo: func(x: u32) -> u32;
            }
            "#,
            "my:shape",
            "api@1.0.0",
        );
        require_supported_case(&resolve, iface_id, false)
            .expect("value-type interfaces should be accepted");
    }
}