wirm 4.0.2

A lightweight WebAssembly Transformation Library for the Component Model
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
use crate::ir::component::idx_spaces::{IndexSpaceOf, Space, SpaceSubtype};
use crate::ir::component::refs::{RefKind, ReferencedIndices};
use crate::ir::component::scopes::GetScopeKind;
use crate::ir::component::section::ComponentSection;
use crate::ir::component::visitor::driver::VisitEvent;
use crate::ir::component::visitor::VisitCtx;
use crate::ir::types::CustomSection;
use crate::{Component, Module};
use std::collections::HashSet;
use wasmparser::{
    CanonicalFunction, ComponentAlias, ComponentExport, ComponentImport, ComponentInstance,
    ComponentStartFunction, ComponentType, ComponentTypeDeclaration, CoreType, Instance,
    InstanceTypeDeclaration, ModuleTypeDeclaration,
};

pub(crate) fn get_topological_events<'ir>(
    component: &'ir Component<'ir>,
    ctx: &mut VisitCtx<'ir>,
    out: &mut Vec<VisitEvent<'ir>>,
) {
    let mut topo = TopoCtx::default();

    ctx.inner.push_component(component);
    out.push(VisitEvent::enter_root_comp(component));

    // The root component is not declared in any enclosing section, so its own enter/exit
    // events have no parent section_idx. Collected items inherit their actual section
    // ordinals from the root's own section list, threaded through `collect_component`.
    topo.collect_component(component, None, None, ctx);
    out.extend(topo.events);

    out.push(VisitEvent::exit_root_comp(component));
    ctx.inner.pop_component();
}

#[derive(Default)]
struct TopoCtx<'ir> {
    seen: HashSet<NodeKey>,
    events: Vec<VisitEvent<'ir>>,
}
impl<'ir> TopoCtx<'ir> {
    /// `parent_section_idx` is the section ordinal in the *enclosing* component where this
    /// nested component was declared (used only for the EnterComp/ExitComp events). For the
    /// root component it is `None`. Items collected from `comp`'s own sections are tagged
    /// with section ordinals from `comp.sections`.
    fn collect_component(
        &mut self,
        comp: &'ir Component<'ir>,
        idx: Option<usize>,
        parent_section_idx: Option<usize>,
        ctx: &mut VisitCtx<'ir>,
    ) {
        let key = NodeKey::Component(id(comp));
        if !self.visit_once(key) {
            return;
        }

        if let Some(idx) = idx {
            // A nested component is always declared inside some Component section of the
            // parent, so `parent_section_idx` must be set when `idx` is set.
            let parent_section_idx =
                parent_section_idx.expect("nested component must have a parent section_idx");
            ctx.inner.push_component(comp);
            self.events
                .push(VisitEvent::enter_comp(parent_section_idx, idx, comp));
        }

        for (section_idx, (count, section)) in comp.sections.iter().enumerate() {
            let start_idx = ctx.inner.visit_section(section, *count as usize);
            self.collect_section_items(comp, section, section_idx, start_idx, *count as usize, ctx);
        }

        if let Some(idx) = idx {
            let parent_section_idx =
                parent_section_idx.expect("nested component must have a parent section_idx");
            ctx.inner.pop_component();
            self.events
                .push(VisitEvent::exit_comp(parent_section_idx, idx, comp));
        }
    }
    fn collect_module(
        &mut self,
        section_idx: usize,
        module: &'ir Module<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            module,
            NodeKey::Module(id(module)),
            ctx,
            None,
            VisitEvent::module(section_idx, module.index_space_of().into(), idx, module),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }
    fn collect_component_type(
        &mut self,
        section_idx: usize,
        node: &'ir ComponentType<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        let key = NodeKey::ComponentType(id(node));

        self.collect_node(
            node,
            key,
            ctx,
            Some(VisitEvent::enter_comp_type(
                section_idx,
                node.index_space_of().into(),
                idx,
                node,
            )),
            VisitEvent::exit_comp_type(section_idx, node.index_space_of().into(), idx, node),
            |this, node, ctx| {
                match node {
                    ComponentType::Component(decls) => {
                        for (i, item) in decls.iter().enumerate() {
                            this.collect_subitem(
                                decls,
                                item,
                                i,
                                NodeKey::component_type_decl,
                                |inner_this, item, i, cx| {
                                    inner_this.collect_component_type_decl(
                                        section_idx,
                                        node,
                                        item,
                                        i,
                                        cx,
                                    );
                                },
                                ctx,
                            );
                        }
                    }

                    ComponentType::Instance(decls) => {
                        for (i, item) in decls.iter().enumerate() {
                            this.collect_subitem(
                                decls,
                                item,
                                i,
                                NodeKey::inst_type_decl,
                                |inner_this, item, i, cx| {
                                    inner_this.collect_instance_type_decl(
                                        section_idx,
                                        node,
                                        item,
                                        i,
                                        cx,
                                    );
                                },
                                ctx,
                            );
                        }
                    }

                    // no sub-scoping for the below variants
                    ComponentType::Defined(_)
                    | ComponentType::Func(_)
                    | ComponentType::Resource { .. } => {}
                }
            },
        );
    }
    fn collect_component_type_decl(
        &mut self,
        section_idx: usize,
        parent: &'ir ComponentType<'ir>,
        decl: &'ir ComponentTypeDeclaration<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.events
            .push(VisitEvent::comp_type_decl(section_idx, parent, idx, decl));
        match decl {
            ComponentTypeDeclaration::Type(ty) => {
                self.collect_component_type(section_idx, ty, idx, ctx)
            }
            ComponentTypeDeclaration::CoreType(ty) => {
                self.collect_core_type(section_idx, ty, idx, ctx)
            }
            ComponentTypeDeclaration::Alias(_)
            | ComponentTypeDeclaration::Export { .. }
            | ComponentTypeDeclaration::Import(_) => {}
        }
    }
    fn collect_instance_type_decl(
        &mut self,
        section_idx: usize,
        parent: &'ir ComponentType<'ir>,
        decl: &'ir InstanceTypeDeclaration<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.events
            .push(VisitEvent::inst_type_decl(section_idx, parent, idx, decl));
        match decl {
            InstanceTypeDeclaration::Type(ty) => {
                self.collect_component_type(section_idx, ty, idx, ctx)
            }
            InstanceTypeDeclaration::CoreType(ty) => {
                self.collect_core_type(section_idx, ty, idx, ctx)
            }
            InstanceTypeDeclaration::Alias(_) | InstanceTypeDeclaration::Export { .. } => {}
        }
    }
    fn collect_comp_inst(
        &mut self,
        section_idx: usize,
        inst: &'ir ComponentInstance<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            inst,
            NodeKey::ComponentInstance(id(inst)),
            ctx,
            None,
            VisitEvent::comp_inst(section_idx, inst.index_space_of().into(), idx, inst),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }
    fn collect_core_inst(
        &mut self,
        section_idx: usize,
        inst: &'ir Instance<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            inst,
            NodeKey::CoreInst(id(inst)),
            ctx,
            None,
            VisitEvent::core_inst(section_idx, inst.index_space_of().into(), idx, inst),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }

    fn collect_core_type(
        &mut self,
        section_idx: usize,
        node: &'ir CoreType<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        let key = NodeKey::CoreType(id(node));

        let (enter_evt, exit_evt) = if let CoreType::Rec(group) = node {
            (
                VisitEvent::enter_rec_group(section_idx, group.types().len(), node),
                VisitEvent::exit_rec_group(section_idx),
            )
        } else {
            (
                VisitEvent::enter_core_type(section_idx, node.index_space_of().into(), idx, node),
                VisitEvent::exit_core_type(section_idx, node.index_space_of().into(), idx, node),
            )
        };

        self.collect_node(
            node,
            key,
            ctx,
            Some(enter_evt),
            exit_evt,
            |this, node, ctx| {
                match node {
                    CoreType::Module(decls) => {
                        for (i, item) in decls.iter().enumerate() {
                            this.collect_subitem(
                                decls,
                                item,
                                i,
                                NodeKey::module_type_decl,
                                |inner_this, item, i, cx| {
                                    inner_this.collect_module_type_decl(
                                        section_idx,
                                        node,
                                        item,
                                        i,
                                        cx,
                                    );
                                },
                                ctx,
                            );
                        }
                    }

                    // no sub-scoping for the below variant
                    CoreType::Rec(group) => {
                        for (subvec_idx, item) in group.types().enumerate() {
                            this.events.push(VisitEvent::core_subtype(
                                section_idx,
                                idx,
                                subvec_idx,
                                item,
                            ));
                        }
                    }
                }
            },
        );
    }
    fn collect_module_type_decl(
        &mut self,
        section_idx: usize,
        parent: &'ir CoreType<'ir>,
        decl: &'ir ModuleTypeDeclaration<'ir>,
        idx: usize,
        _: &mut VisitCtx<'ir>,
    ) {
        self.events
            .push(VisitEvent::mod_type_decl(section_idx, parent, idx, decl))
    }
    fn collect_canon(
        &mut self,
        section_idx: usize,
        canon: &'ir CanonicalFunction,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            canon,
            NodeKey::Canon(id(canon)),
            ctx,
            None,
            VisitEvent::canon(section_idx, canon.index_space_of().into(), idx, canon),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }
    fn collect_export(
        &mut self,
        section_idx: usize,
        export: &'ir ComponentExport<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            export,
            NodeKey::Export(id(export)),
            ctx,
            None,
            VisitEvent::export(section_idx, export.index_space_of().into(), idx, export),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }
    fn collect_import(
        &mut self,
        section_idx: usize,
        import: &'ir ComponentImport<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            import,
            NodeKey::Import(id(import)),
            ctx,
            None,
            VisitEvent::import(section_idx, import.index_space_of().into(), idx, import),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }
    fn collect_alias(
        &mut self,
        section_idx: usize,
        alias: &'ir ComponentAlias<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            alias,
            NodeKey::Alias(id(alias)),
            ctx,
            None,
            VisitEvent::alias(section_idx, alias.index_space_of().into(), idx, alias),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }
    fn collect_custom_section(
        &mut self,
        section_idx: usize,
        sect: &'ir CustomSection<'ir>,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            sect,
            NodeKey::Custom(id(sect)),
            ctx,
            None,
            VisitEvent::custom_sect(section_idx, sect.index_space_of().into(), idx, sect),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }
    fn collect_start_section(
        &mut self,
        section_idx: usize,
        func: &'ir ComponentStartFunction,
        idx: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        self.collect_node(
            func,
            NodeKey::Start(id(func)),
            ctx,
            None,
            VisitEvent::start_func(section_idx, func.index_space_of().into(), idx, func),
            |this, node, cx| {
                this.collect_deps(node, cx);
            },
        );
    }

    fn collect_section_items(
        &mut self,
        comp: &'ir Component<'ir>,
        section: &ComponentSection,
        section_idx: usize,
        start_idx: usize,
        count: usize,
        ctx: &mut VisitCtx<'ir>,
    ) {
        for i in 0..count {
            let idx = start_idx + i;

            match section {
                ComponentSection::Component => {
                    self.collect_component(&comp.components[idx], Some(idx), Some(section_idx), ctx)
                }

                ComponentSection::Module => {
                    self.collect_module(section_idx, &comp.modules[idx], idx, ctx)
                }

                ComponentSection::ComponentType => self.collect_component_type(
                    section_idx,
                    &comp.component_types.items[idx],
                    idx,
                    ctx,
                ),

                ComponentSection::ComponentInstance => {
                    self.collect_comp_inst(section_idx, &comp.component_instance[idx], idx, ctx)
                }

                ComponentSection::Canon => {
                    self.collect_canon(section_idx, &comp.canons.items[idx], idx, ctx)
                }

                ComponentSection::Alias => {
                    self.collect_alias(section_idx, &comp.alias.items[idx], idx, ctx)
                }

                ComponentSection::ComponentImport => {
                    self.collect_import(section_idx, &comp.imports[idx], idx, ctx)
                }

                ComponentSection::ComponentExport => {
                    self.collect_export(section_idx, &comp.exports[idx], idx, ctx)
                }

                ComponentSection::CoreType => {
                    self.collect_core_type(section_idx, &comp.core_types[idx], idx, ctx)
                }

                ComponentSection::CoreInstance => {
                    self.collect_core_inst(section_idx, &comp.instances[idx], idx, ctx)
                }

                ComponentSection::CustomSection => self.collect_custom_section(
                    section_idx,
                    &comp.custom_sections.custom_sections[idx],
                    idx,
                    ctx,
                ),

                ComponentSection::ComponentStartSection => {
                    self.collect_start_section(section_idx, &comp.start_section[idx], idx, ctx)
                }
            }
        }
    }

    fn collect_node<T>(
        &mut self,
        node: &'ir T,
        key: NodeKey,
        ctx: &mut VisitCtx<'ir>,
        enter_event: Option<VisitEvent<'ir>>,
        exit_event: VisitEvent<'ir>,
        walk: impl FnOnce(&mut Self, &'ir T, &mut VisitCtx<'ir>),
    ) where
        T: GetScopeKind + ReferencedIndices + 'ir,
    {
        if !self.visit_once(key) {
            return;
        }

        if let Some(evt) = enter_event {
            self.events.push(evt)
        }

        // walk inner declarations
        ctx.inner.maybe_enter_scope(node);
        walk(self, node, ctx);
        ctx.inner.maybe_exit_scope(node);

        self.events.push(exit_event);
    }
    /// Walks an item's outgoing references and topologically collects each dependency.
    /// Each dep lives in its own section in `referenced_comp` — we look that up via
    /// [`section_idx_for_main_vec`] and [`section_idx_of_kth_item`] so the queued event
    /// carries the correct ordinal even when the dep crosses an outer-component boundary.
    fn collect_deps<T: ReferencedIndices + 'ir>(&mut self, item: &'ir T, ctx: &mut VisitCtx<'ir>) {
        let refs = item.referenced_indices();
        for RefKind { ref_, .. } in refs.iter() {
            let (vec, idx, subidx) = ctx.inner.index_from_assumed_id(ref_);
            if ref_.space != Space::CoreType {
                assert!(
                    subidx.is_none(),
                    "only core types (with rec groups) should ever have subvec indices!"
                );
            }

            let comp_id = ctx.inner.comp_at(ref_.depth);
            let referenced_comp = ctx.inner.comp_store.get(comp_id);

            let space = ref_.space;
            match vec {
                SpaceSubtype::Main => match space {
                    Space::Comp => {
                        let dep_section = section_idx_for_main_vec(referenced_comp, space, idx);
                        self.collect_component(
                            &referenced_comp.components[idx],
                            Some(idx),
                            Some(dep_section),
                            ctx,
                        )
                    }
                    Space::CompType => {
                        let dep_section = section_idx_for_main_vec(referenced_comp, space, idx);
                        self.collect_component_type(
                            dep_section,
                            &referenced_comp.component_types.items[idx],
                            idx,
                            ctx,
                        )
                    }
                    Space::CompInst => {
                        let dep_section = section_idx_for_main_vec(referenced_comp, space, idx);
                        self.collect_comp_inst(
                            dep_section,
                            &referenced_comp.component_instance[idx],
                            idx,
                            ctx,
                        )
                    }
                    Space::CoreInst => {
                        let dep_section = section_idx_for_main_vec(referenced_comp, space, idx);
                        self.collect_core_inst(
                            dep_section,
                            &referenced_comp.instances[idx],
                            idx,
                            ctx,
                        )
                    }
                    Space::CoreModule => {
                        let dep_section = section_idx_for_main_vec(referenced_comp, space, idx);
                        self.collect_module(dep_section, &referenced_comp.modules[idx], idx, ctx)
                    }
                    Space::CoreType => {
                        let dep_section = section_idx_for_main_vec(referenced_comp, space, idx);
                        self.collect_core_type(
                            dep_section,
                            &referenced_comp.core_types[idx],
                            idx,
                            ctx,
                        )
                    }
                    Space::CompFunc | Space::CoreFunc => {
                        let dep_section = section_idx_for_main_vec(referenced_comp, space, idx);
                        self.collect_canon(
                            dep_section,
                            &referenced_comp.canons.items[idx],
                            idx,
                            ctx,
                        )
                    }
                    Space::CompVal
                    | Space::CoreMemory
                    | Space::CoreTable
                    | Space::CoreGlobal
                    | Space::CoreTag
                    | Space::NA => unreachable!(
                        "This spaces don't exist in a main vector on the component IR: {vec:?}"
                    ),
                },
                SpaceSubtype::Export => {
                    let dep_section = section_idx_of_kth_item(
                        referenced_comp,
                        ComponentSection::ComponentExport,
                        idx,
                    );
                    self.collect_export(dep_section, &referenced_comp.exports[idx], idx, ctx)
                }
                SpaceSubtype::Import => {
                    let dep_section = section_idx_of_kth_item(
                        referenced_comp,
                        ComponentSection::ComponentImport,
                        idx,
                    );
                    self.collect_import(dep_section, &referenced_comp.imports[idx], idx, ctx)
                }
                SpaceSubtype::Alias => {
                    let dep_section =
                        section_idx_of_kth_item(referenced_comp, ComponentSection::Alias, idx);
                    self.collect_alias(dep_section, &referenced_comp.alias.items[idx], idx, ctx)
                }
            }
        }
    }

    /// Walk the deps of a sub-decl item and emit it. The enclosing section_idx for the
    /// queued events is captured by the `emit_item` closure at the call site, so it isn't
    /// passed as a parameter here.
    fn collect_subitem<T: ReferencedIndices + GetScopeKind + 'ir>(
        &mut self,
        all: &'ir [T],
        item: &'ir T,
        item_idx: usize,
        gen_key: fn(&T, usize) -> NodeKey,
        mut emit_item: impl FnMut(&mut Self, &'ir T, usize, &mut VisitCtx<'ir>),
        ctx: &mut VisitCtx<'ir>,
    ) {
        if !self.visit_once(gen_key(item, item_idx)) {
            return;
        }

        // collect the dependencies of this guy
        ctx.inner.maybe_enter_scope(item);
        let refs = item.referenced_indices();
        for RefKind { ref_, .. } in refs.iter() {
            if !ref_.depth.is_curr() {
                continue;
            }
            let (vec, idx, ..) = ctx.inner.index_from_assumed_id(ref_);
            assert_eq!(vec, SpaceSubtype::Main);
            let dep_item = &all[idx];

            if !self.visit_once(gen_key(dep_item, idx)) {
                continue;
            }

            // collect subitem
            emit_item(self, dep_item, idx, ctx);
        }

        ctx.inner.maybe_exit_scope(item);

        // collect item
        emit_item(self, item, item_idx, ctx);
    }
    fn visit_once(&mut self, key: NodeKey) -> bool {
        self.seen.insert(key)
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
enum NodeKey {
    Component(*const ()),
    Module(*const ()),
    ComponentType(*const ()),
    ComponentTypeDecl(*const (), usize), // decl ptr + index
    InstanceTypeDecl(*const (), usize),  // decl ptr + index
    CoreType(*const ()),
    ModuleTypeDecl(*const (), usize), // decl ptr + index
    ComponentInstance(*const ()),
    CoreInst(*const ()),
    Alias(*const ()),
    Import(*const ()),
    Export(*const ()),
    Canon(*const ()),
    Custom(*const ()),
    Start(*const ()),
}
impl NodeKey {
    fn inst_type_decl(decl: &InstanceTypeDeclaration, idx: usize) -> Self {
        Self::InstanceTypeDecl(id(decl), idx)
    }
    fn component_type_decl(decl: &ComponentTypeDeclaration, idx: usize) -> Self {
        Self::ComponentTypeDecl(id(decl), idx)
    }
    fn module_type_decl(decl: &ModuleTypeDeclaration, idx: usize) -> Self {
        Self::ModuleTypeDecl(id(decl), idx)
    }
}

fn id<T>(ptr: &T) -> *const () {
    ptr as *const T as *const ()
}

/// Map a `(space, vec_idx)` pair into the section ordinal where that item was declared.
///
/// The wirm IR stores items from each kind of section in a single per-kind vector
/// (e.g. all `ComponentType` section items end up in `comp.component_types.items`),
/// and `vec_idx` is the position within that vector. To find which section produced
/// a given item, we walk `comp.sections` in order, accumulating the per-section item
/// counts for the matching section kind, and return the section ordinal where the
/// running count first exceeds `vec_idx`.
///
/// This is only valid for spaces that have a single corresponding section kind in the
/// IR's main vectors. Spaces produced by imports / aliases / exports are looked up via
/// [`section_idx_of_kth_item`] directly.
fn section_idx_for_main_vec(comp: &Component, space: Space, vec_idx: usize) -> usize {
    let target = match space {
        Space::Comp => ComponentSection::Component,
        Space::CompType => ComponentSection::ComponentType,
        Space::CompInst => ComponentSection::ComponentInstance,
        Space::CoreInst => ComponentSection::CoreInstance,
        Space::CoreModule => ComponentSection::Module,
        Space::CoreType => ComponentSection::CoreType,
        Space::CompFunc | Space::CoreFunc => ComponentSection::Canon,
        Space::CompVal
        | Space::CoreMemory
        | Space::CoreTable
        | Space::CoreGlobal
        | Space::CoreTag
        | Space::NA => {
            panic!("section_idx_for_main_vec: space {space:?} has no main vector in the IR")
        }
    };
    section_idx_of_kth_item(comp, target, vec_idx)
}

/// Walk `comp.sections` in order and return the section ordinal of the section that
/// holds the `vec_idx`-th item among all sections of the given kind. Panics if the
/// component has fewer than `vec_idx + 1` items of that kind, since that indicates a
/// bug in the caller's index resolution.
fn section_idx_of_kth_item(comp: &Component, target: ComponentSection, vec_idx: usize) -> usize {
    let mut cumulative = 0usize;
    for (section_idx, (num, section)) in comp.sections.iter().enumerate() {
        if std::mem::discriminant(section) == std::mem::discriminant(&target) {
            let new_cum = cumulative + (*num as usize);
            if vec_idx < new_cum {
                return section_idx;
            }
            cumulative = new_cum;
        }
    }
    panic!(
        "section_idx_of_kth_item: vec_idx {vec_idx} not found in any {target:?} section \
         (component has only {cumulative} items of that kind)"
    );
}