walrus 0.26.0

A library for performing WebAssembly transformations
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
//! WebAssembly function and value types.

use crate::error::Result;
use crate::tombstone_arena::Tombstone;
use anyhow::bail;
use id_arena::Id;
use std::cmp::Ordering;
use std::convert::TryFrom;
use std::fmt;
use std::hash;

/// An identifier for types.
pub type TypeId = Id<Type>;

/// An identifier for recursive type groups.
pub type RecGroupId = Id<RecGroup>;

/// A recursive type group.
///
/// In the GC proposal, types can be grouped into recursive type groups that
/// allow mutual references between types. Each type in a module belongs to
/// exactly one recursive group (singleton groups for non-recursive types).
#[derive(Debug, Clone)]
pub struct RecGroup {
    /// The types in this recursive group, in definition order.
    pub types: Vec<TypeId>,
    /// Whether this rec group was declared with an explicit `(rec ...)` wrapper.
    ///
    /// Explicit singleton rec groups are semantically distinct from implicit
    /// singletons in the GC spec (they affect type identity). This flag is
    /// preserved so that emission can reproduce the original encoding.
    pub is_explicit: bool,
}

// ---------------------------------------------------------------------------
// GC type definitions: storage types, field types, aggregate types
// ---------------------------------------------------------------------------

/// A packed storage type for struct and array fields.
///
/// Packed types allow storing smaller integers in fields for memory efficiency.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum StorageType {
    /// A standard value type.
    Val(ValType),
    /// An 8-bit integer (packed).
    I8,
    /// A 16-bit integer (packed).
    I16,
}

impl StorageType {
    /// Unpack a storage type to its corresponding value type.
    ///
    /// Packed integer types (`I8`, `I16`) unpack to `I32`.
    pub fn unpack(&self) -> ValType {
        match self {
            StorageType::Val(v) => *v,
            StorageType::I8 | StorageType::I16 => ValType::I32,
        }
    }

    /// Convert to wasm_encoder StorageType, resolving concrete type indices
    /// via `IdsToIndices`.
    pub(crate) fn to_wasmencoder_type(
        &self,
        indices: &crate::emit::IdsToIndices,
    ) -> wasm_encoder::StorageType {
        match self {
            StorageType::I8 => wasm_encoder::StorageType::I8,
            StorageType::I16 => wasm_encoder::StorageType::I16,
            StorageType::Val(vt) => wasm_encoder::StorageType::Val(vt.to_wasmencoder_type(indices)),
        }
    }

    /// Convert a wasmparser StorageType to a walrus StorageType, resolving
    /// concrete type indices via `IndicesToIds`.
    pub(crate) fn from_wasmparser(
        st: wasmparser::StorageType,
        ids: &crate::parse::IndicesToIds,
        rec_group_start: u32,
    ) -> Result<StorageType> {
        match st {
            wasmparser::StorageType::I8 => Ok(StorageType::I8),
            wasmparser::StorageType::I16 => Ok(StorageType::I16),
            wasmparser::StorageType::Val(vt) => Ok(StorageType::Val(ValType::from_wasmparser(
                &vt,
                ids,
                rec_group_start,
            )?)),
        }
    }
}

impl fmt::Display for StorageType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            StorageType::Val(v) => write!(f, "{v}"),
            StorageType::I8 => write!(f, "i8"),
            StorageType::I16 => write!(f, "i16"),
        }
    }
}

/// A field type for struct and array fields.
///
/// Combines a storage type with a mutability flag.
///
/// # Example
///
/// ```
/// use walrus::{FieldType, StorageType, ValType};
///
/// // A mutable i32 field (unpacked)
/// let int_field = FieldType {
///     element_type: StorageType::Val(ValType::I32),
///     mutable: true,
/// };
///
/// // An immutable packed i8 field (uses struct.get_s / struct.get_u)
/// let byte_field = FieldType {
///     element_type: StorageType::I8,
///     mutable: false,
/// };
///
/// assert_eq!(byte_field.element_type.unpack(), ValType::I32);
/// ```
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FieldType {
    /// The storage type of this field.
    pub element_type: StorageType,
    /// Whether this field is mutable.
    pub mutable: bool,
}

impl FieldType {
    /// Convert to wasm_encoder FieldType, resolving concrete type indices
    /// via `IdsToIndices`.
    pub(crate) fn to_wasmencoder_type(
        &self,
        indices: &crate::emit::IdsToIndices,
    ) -> wasm_encoder::FieldType {
        wasm_encoder::FieldType {
            element_type: self.element_type.to_wasmencoder_type(indices),
            mutable: self.mutable,
        }
    }

    /// Convert a wasmparser FieldType to a walrus FieldType, resolving
    /// concrete type indices via `IndicesToIds`.
    pub(crate) fn from_wasmparser(
        ft: wasmparser::FieldType,
        ids: &crate::parse::IndicesToIds,
        rec_group_start: u32,
    ) -> Result<FieldType> {
        Ok(FieldType {
            element_type: StorageType::from_wasmparser(ft.element_type, ids, rec_group_start)?,
            mutable: ft.mutable,
        })
    }
}

impl fmt::Display for FieldType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.mutable {
            write!(f, "(mut {})", self.element_type)
        } else {
            write!(f, "{}", self.element_type)
        }
    }
}

/// A function type, consisting of parameter and result types.
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct FunctionType {
    /// The parameter types.
    params: Box<[ValType]>,
    /// The result types.
    results: Box<[ValType]>,
}

impl FunctionType {
    /// Create a new function type.
    pub fn new(params: Box<[ValType]>, results: Box<[ValType]>) -> Self {
        FunctionType { params, results }
    }

    /// Get the parameter types.
    #[inline]
    pub fn params(&self) -> &[ValType] {
        &self.params
    }

    /// Get the result types.
    #[inline]
    pub fn results(&self) -> &[ValType] {
        &self.results
    }
}

impl fmt::Display for FunctionType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "(func")?;
        if !self.params.is_empty() {
            let params = self
                .params
                .iter()
                .map(|p| format!("{p}"))
                .collect::<Vec<_>>()
                .join(" ");
            write!(f, " (param {params})")?;
        }
        if !self.results.is_empty() {
            let results = self
                .results
                .iter()
                .map(|r| format!("{r}"))
                .collect::<Vec<_>>()
                .join(" ");
            write!(f, " (result {results})")?;
        }
        write!(f, ")")
    }
}

/// A struct type, consisting of a sequence of field types.
#[derive(Clone, Debug, Default, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct StructType {
    /// The fields of this struct type.
    pub fields: Box<[FieldType]>,
}

impl fmt::Display for StructType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let fields = self
            .fields
            .iter()
            .map(|field| format!("(field {field})"))
            .collect::<Vec<_>>()
            .join(" ");
        if fields.is_empty() {
            write!(f, "(struct)")
        } else {
            write!(f, "(struct {fields})")
        }
    }
}

/// An array type, consisting of a single field type for all elements.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct ArrayType {
    /// The element type of this array.
    pub field: FieldType,
}

impl fmt::Display for ArrayType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "(array {})", self.field)
    }
}

/// A composite type that can be a function, struct, or array.
///
/// This corresponds to the `comptype` production in the WebAssembly GC spec.
///
/// # Example
///
/// ```
/// use walrus::*;
///
/// // A struct composite type
/// let struct_comp = CompositeType::Struct(StructType {
///     fields: vec![
///         FieldType { element_type: StorageType::Val(ValType::I32), mutable: true },
///         FieldType { element_type: StorageType::Val(ValType::F64), mutable: false },
///     ].into_boxed_slice(),
/// });
/// assert!(struct_comp.is_struct());
///
/// // A function composite type
/// let func_comp = CompositeType::Function(FunctionType::new(
///     vec![ValType::I32].into_boxed_slice(),
///     vec![ValType::I64].into_boxed_slice(),
/// ));
/// assert!(func_comp.is_function());
/// ```
#[derive(Clone, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum CompositeType {
    /// A function type.
    Function(FunctionType),
    /// A struct type (GC proposal).
    Struct(StructType),
    /// An array type (GC proposal).
    Array(ArrayType),
}

impl CompositeType {
    /// Returns `Some` if this is a function type.
    pub fn as_function(&self) -> Option<&FunctionType> {
        match self {
            CompositeType::Function(f) => Some(f),
            _ => None,
        }
    }

    /// Returns a mutable reference if this is a function type.
    pub fn as_function_mut(&mut self) -> Option<&mut FunctionType> {
        match self {
            CompositeType::Function(f) => Some(f),
            _ => None,
        }
    }

    /// Returns `Some` if this is a struct type.
    pub fn as_struct(&self) -> Option<&StructType> {
        match self {
            CompositeType::Struct(s) => Some(s),
            _ => None,
        }
    }

    /// Returns `Some` if this is an array type.
    pub fn as_array(&self) -> Option<&ArrayType> {
        match self {
            CompositeType::Array(a) => Some(a),
            _ => None,
        }
    }

    /// Unwrap as a function type, panicking if it's not one.
    pub fn unwrap_function(&self) -> &FunctionType {
        self.as_function().expect("expected a function type")
    }

    /// Unwrap as a struct type, panicking if it's not one.
    pub fn unwrap_struct(&self) -> &StructType {
        self.as_struct().expect("expected a struct type")
    }

    /// Unwrap as an array type, panicking if it's not one.
    pub fn unwrap_array(&self) -> &ArrayType {
        self.as_array().expect("expected an array type")
    }

    /// Returns `true` if this is a function type.
    pub fn is_function(&self) -> bool {
        matches!(self, CompositeType::Function(_))
    }

    /// Returns `true` if this is a struct type.
    pub fn is_struct(&self) -> bool {
        matches!(self, CompositeType::Struct(_))
    }

    /// Returns `true` if this is an array type.
    pub fn is_array(&self) -> bool {
        matches!(self, CompositeType::Array(_))
    }
}

impl fmt::Display for CompositeType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            CompositeType::Function(ft) => write!(f, "{ft}"),
            CompositeType::Struct(st) => write!(f, "{st}"),
            CompositeType::Array(at) => write!(f, "{at}"),
        }
    }
}

// ---------------------------------------------------------------------------
// Type: the top-level type definition (subtype wrapper)
// ---------------------------------------------------------------------------

/// A WebAssembly type definition.
///
/// With the GC proposal, types can be function types, struct types, or array
/// types, and can participate in subtyping and recursive type groups.
#[derive(Debug, Clone)]
pub struct Type {
    id: TypeId,
    /// The composite type definition (function, struct, or array).
    comp: CompositeType,
    /// Whether this type is final (cannot be further subtyped).
    /// Defaults to `true` for types without explicit subtype declarations.
    pub is_final: bool,
    /// Optional supertype that this type extends.
    pub supertype: Option<TypeId>,

    // Whether or not this type is for a multi-value function entry block, and
    // therefore is for internal use only and shouldn't be emitted when we
    // serialize the Type section.
    is_for_function_entry: bool,

    /// An optional name for debugging.
    ///
    /// This is not really used by anything currently, but a theoretical WAT to
    /// walrus parser could keep track of the original name in the WAT.
    pub name: Option<String>,
}

impl PartialEq for Type {
    #[inline]
    fn eq(&self, rhs: &Type) -> bool {
        // NB: do not compare id or name.
        self.comp == rhs.comp
            && self.is_final == rhs.is_final
            && self.supertype == rhs.supertype
            && self.is_for_function_entry == rhs.is_for_function_entry
    }
}

impl Eq for Type {}

impl PartialOrd for Type {
    fn partial_cmp(&self, rhs: &Type) -> Option<Ordering> {
        Some(self.cmp(rhs))
    }
}

impl Ord for Type {
    fn cmp(&self, rhs: &Type) -> Ordering {
        self.comp
            .cmp(&rhs.comp)
            .then_with(|| self.is_final.cmp(&rhs.is_final))
            .then_with(|| self.supertype.cmp(&rhs.supertype))
            .then_with(|| self.is_for_function_entry.cmp(&rhs.is_for_function_entry))
    }
}

impl hash::Hash for Type {
    #[inline]
    fn hash<H: hash::Hasher>(&self, h: &mut H) {
        // Do not hash id or name.
        self.comp.hash(h);
        self.is_final.hash(h);
        self.supertype.hash(h);
        self.is_for_function_entry.hash(h);
    }
}

impl Tombstone for Type {
    fn on_delete(&mut self) {
        self.comp = CompositeType::Function(FunctionType {
            params: Box::new([]),
            results: Box::new([]),
        });
    }
}

impl Type {
    /// Construct a placeholder type for pre-allocation during parsing.
    ///
    /// The placeholder will be overwritten with the real type once all
    /// forward references within a rec group can be resolved.
    #[inline]
    pub(crate) fn placeholder(id: TypeId) -> Type {
        Type {
            id,
            comp: CompositeType::Struct(Default::default()),
            is_final: true,
            supertype: None,
            is_for_function_entry: false,
            name: None,
        }
    }

    /// Construct a new function type.
    #[inline]
    pub(crate) fn new(id: TypeId, params: Box<[ValType]>, results: Box<[ValType]>) -> Type {
        Type {
            id,
            comp: CompositeType::Function(FunctionType { params, results }),
            is_final: true,
            supertype: None,
            is_for_function_entry: false,
            name: None,
        }
    }

    /// Construct a new type for function entry blocks.
    #[inline]
    pub(crate) fn for_function_entry(id: TypeId, results: Box<[ValType]>) -> Type {
        let params = vec![].into();
        Type {
            id,
            comp: CompositeType::Function(FunctionType { params, results }),
            is_final: true,
            supertype: None,
            is_for_function_entry: true,
            name: None,
        }
    }

    /// Construct a new type with a given composite type.
    pub(crate) fn new_composite(
        id: TypeId,
        comp: CompositeType,
        is_final: bool,
        supertype: Option<TypeId>,
    ) -> Type {
        Type {
            id,
            comp,
            is_final,
            supertype,
            is_for_function_entry: false,
            name: None,
        }
    }

    /// Get the id of this type.
    #[inline]
    pub fn id(&self) -> TypeId {
        self.id
    }

    /// Get a reference to the composite type.
    #[inline]
    pub fn kind(&self) -> &CompositeType {
        &self.comp
    }

    /// Get a mutable reference to the composite type.
    #[inline]
    pub fn kind_mut(&mut self) -> &mut CompositeType {
        &mut self.comp
    }

    /// Get the parameters to this function type.
    ///
    /// # Panics
    ///
    /// Panics if this type is not a function type.
    #[inline]
    pub fn params(&self) -> &[ValType] {
        self.comp.unwrap_function().params()
    }

    /// Get the results of this function type.
    ///
    /// # Panics
    ///
    /// Panics if this type is not a function type.
    #[inline]
    pub fn results(&self) -> &[ValType] {
        self.comp.unwrap_function().results()
    }

    /// Returns this type's composite type as a function type, if it is one.
    #[inline]
    pub fn as_function(&self) -> Option<&FunctionType> {
        self.comp.as_function()
    }

    /// Returns this type's composite type as a struct type, if it is one.
    #[inline]
    pub fn as_struct(&self) -> Option<&StructType> {
        self.comp.as_struct()
    }

    /// Returns this type's composite type as an array type, if it is one.
    #[inline]
    pub fn as_array(&self) -> Option<&ArrayType> {
        self.comp.as_array()
    }

    /// Whether this type is a function type.
    #[inline]
    pub fn is_function(&self) -> bool {
        self.comp.is_function()
    }

    /// Whether this type is a struct type.
    #[inline]
    pub fn is_struct(&self) -> bool {
        self.comp.is_struct()
    }

    /// Whether this type is an array type.
    #[inline]
    pub fn is_array(&self) -> bool {
        self.comp.is_array()
    }

    pub(crate) fn is_for_function_entry(&self) -> bool {
        self.is_for_function_entry
    }

    /// Collect all `TypeId`s that this type directly references.
    ///
    /// This includes concrete heap types in parameters/results/fields and the
    /// supertype, if any. Used by the GC pass to transitively keep types alive.
    pub fn referenced_types(&self, out: &mut Vec<TypeId>) {
        // Supertype reference
        if let Some(sup) = self.supertype {
            out.push(sup);
        }
        // Composite type references
        match &self.comp {
            CompositeType::Function(ft) => {
                collect_val_type_refs(ft.params(), out);
                collect_val_type_refs(ft.results(), out);
            }
            CompositeType::Struct(st) => {
                for field in st.fields.iter() {
                    collect_storage_type_refs(&field.element_type, out);
                }
            }
            CompositeType::Array(at) => {
                collect_storage_type_refs(&at.field.element_type, out);
            }
        }
    }
}

/// Collect `TypeId` references from a slice of value types.
fn collect_val_type_refs(val_types: &[ValType], out: &mut Vec<TypeId>) {
    for vt in val_types {
        if let ValType::Ref(rt) = vt {
            if let HeapType::Concrete(id) | HeapType::Exact(id) = rt.heap_type {
                out.push(id);
            }
        }
    }
}

/// Collect `TypeId` references from a storage type.
fn collect_storage_type_refs(st: &StorageType, out: &mut Vec<TypeId>) {
    if let StorageType::Val(ValType::Ref(rt)) = st {
        if let HeapType::Concrete(id) | HeapType::Exact(id) = rt.heap_type {
            out.push(id);
        }
    }
}

// ---------------------------------------------------------------------------
// Value types
// ---------------------------------------------------------------------------

/// A value type.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub enum ValType {
    /// 32-bit integer.
    I32,
    /// 64-bit integer.
    I64,
    /// 32-bit float.
    F32,
    /// 64-bit float.
    F64,
    /// 128-bit vector.
    V128,
    /// Reference.
    Ref(RefType),
}

// ---------------------------------------------------------------------------
// Heap types
// ---------------------------------------------------------------------------

/// A heap type for GC reference types.
///
/// This represents the kind of heap object a reference points to.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum HeapType {
    /// Abstract heap type (abstract types like func, extern, any, etc.)
    Abstract(AbstractHeapType),
    /// Concrete (indexed) heap type, referencing a defined type by its id.
    ///
    /// `(ref $t)` — matches the type and all its subtypes.
    Concrete(TypeId),
    /// Exact heap type, referencing a defined type by its id.
    ///
    /// `(ref exact $t)` — matches exactly the named type, excluding subtypes.
    ///
    /// This corresponds to the custom-descriptors proposal, which is not yet
    /// part of the standard GC proposal and is not enabled by default.
    #[doc(hidden)]
    Exact(TypeId),
}

impl HeapType {
    /// Convert to wasm_encoder HeapType, resolving concrete type indices via
    /// `IdsToIndices`.
    pub fn to_wasmencoder_heap_type(
        self,
        indices: &crate::emit::IdsToIndices,
    ) -> wasm_encoder::HeapType {
        match self {
            HeapType::Abstract(ab_heap_type) => wasm_encoder::HeapType::Abstract {
                shared: false,
                ty: ab_heap_type.into(),
            },
            HeapType::Concrete(id) => wasm_encoder::HeapType::Concrete(indices.get_type_index(id)),
            HeapType::Exact(id) => wasm_encoder::HeapType::Exact(indices.get_type_index(id)),
        }
    }
}

impl TryFrom<wasmparser::HeapType> for HeapType {
    type Error = anyhow::Error;

    fn try_from(heap_type: wasmparser::HeapType) -> Result<HeapType> {
        match heap_type {
            wasmparser::HeapType::Abstract { shared: _, ty } => {
                Ok(HeapType::Abstract(ty.try_into()?))
            }
            wasmparser::HeapType::Concrete(_) | wasmparser::HeapType::Exact(_) => {
                bail!("concrete/exact (indexed) heap types require IndicesToIds for resolution; use HeapType::from_wasmparser")
            }
        }
    }
}

impl HeapType {
    /// Convert a wasmparser HeapType to a walrus HeapType, resolving concrete
    /// type indices via `IndicesToIds`.
    ///
    /// `rec_group_start` is the module-level type index of the first type in
    /// the current rec group, used to resolve `RecGroup`-relative indices.
    pub(crate) fn from_wasmparser(
        heap_type: wasmparser::HeapType,
        ids: &crate::parse::IndicesToIds,
        rec_group_start: u32,
    ) -> Result<HeapType> {
        match heap_type {
            wasmparser::HeapType::Abstract { shared: _, ty } => {
                Ok(HeapType::Abstract(ty.try_into()?))
            }
            wasmparser::HeapType::Concrete(unpacked) => {
                let type_id = resolve_heap_type_index(unpacked, ids, rec_group_start)?;
                Ok(HeapType::Concrete(type_id))
            }
            wasmparser::HeapType::Exact(unpacked) => {
                let type_id = resolve_heap_type_index(unpacked, ids, rec_group_start)?;
                Ok(HeapType::Exact(type_id))
            }
        }
    }
}

/// Resolve a wasmparser `UnpackedIndex` to a walrus `TypeId`.
fn resolve_heap_type_index(
    unpacked: wasmparser::UnpackedIndex,
    ids: &crate::parse::IndicesToIds,
    rec_group_start: u32,
) -> Result<TypeId> {
    match unpacked {
        wasmparser::UnpackedIndex::Module(idx) => ids.get_type(idx),
        wasmparser::UnpackedIndex::RecGroup(idx) => ids.get_type(rec_group_start + idx),
        #[allow(unreachable_patterns)]
        _ => bail!("unsupported type index variant"),
    }
}

impl fmt::Display for HeapType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            HeapType::Abstract(ab_heap_type) => write!(
                f,
                "{}",
                match ab_heap_type {
                    AbstractHeapType::Func => "func",
                    AbstractHeapType::Extern => "extern",
                    AbstractHeapType::Any => "any",
                    AbstractHeapType::None => "none",
                    AbstractHeapType::NoExtern => "noextern",
                    AbstractHeapType::NoFunc => "nofunc",
                    AbstractHeapType::Eq => "eq",
                    AbstractHeapType::Struct => "struct",
                    AbstractHeapType::Array => "array",
                    AbstractHeapType::I31 => "i31",
                    AbstractHeapType::Exn => "exn",
                    AbstractHeapType::NoExn => "noexn",
                }
            ),
            HeapType::Concrete(id) => write!(f, "{}", id.index()),
            HeapType::Exact(id) => write!(f, "exact {}", id.index()),
        }
    }
}

// ---------------------------------------------------------------------------
// Abstract heap types
// ---------------------------------------------------------------------------

/// Abstract heap types for GC reference types.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
#[non_exhaustive]
pub enum AbstractHeapType {
    /// The abstract `func` heap type (any function).
    Func,
    /// The abstract `extern` heap type (external/host references).
    Extern,
    /// The abstract `any` heap type (any internal reference).
    Any,
    /// The abstract `none` heap type (bottom type for internal refs).
    None,
    /// The abstract `noextern` heap type (bottom type for external refs).
    NoExtern,
    /// The abstract `nofunc` heap type (bottom type for function refs).
    NoFunc,
    /// The abstract `eq` heap type (comparable references: i31, struct, array).
    Eq,
    /// The abstract `struct` heap type.
    Struct,
    /// The abstract `array` heap type.
    Array,
    /// The abstract `i31` heap type (31-bit integers).
    I31,
    /// The abstract `exn` heap type (exceptions).
    Exn,
    /// The abstract `noexn` heap type (bottom type for exception refs).
    NoExn,
}

#[allow(clippy::from_over_into)]
impl Into<wasm_encoder::AbstractHeapType> for AbstractHeapType {
    fn into(self) -> wasm_encoder::AbstractHeapType {
        match self {
            AbstractHeapType::Func => wasm_encoder::AbstractHeapType::Func,
            AbstractHeapType::Extern => wasm_encoder::AbstractHeapType::Extern,
            AbstractHeapType::Any => wasm_encoder::AbstractHeapType::Any,
            AbstractHeapType::None => wasm_encoder::AbstractHeapType::None,
            AbstractHeapType::NoExtern => wasm_encoder::AbstractHeapType::NoExtern,
            AbstractHeapType::NoFunc => wasm_encoder::AbstractHeapType::NoFunc,
            AbstractHeapType::Eq => wasm_encoder::AbstractHeapType::Eq,
            AbstractHeapType::Struct => wasm_encoder::AbstractHeapType::Struct,
            AbstractHeapType::Array => wasm_encoder::AbstractHeapType::Array,
            AbstractHeapType::I31 => wasm_encoder::AbstractHeapType::I31,
            AbstractHeapType::Exn => wasm_encoder::AbstractHeapType::Exn,
            AbstractHeapType::NoExn => wasm_encoder::AbstractHeapType::NoExn,
        }
    }
}

impl TryFrom<wasmparser::AbstractHeapType> for AbstractHeapType {
    type Error = anyhow::Error;

    fn try_from(
        ab_heap_type: wasmparser::AbstractHeapType,
    ) -> std::result::Result<Self, Self::Error> {
        Ok(match ab_heap_type {
            wasmparser::AbstractHeapType::Func => AbstractHeapType::Func,
            wasmparser::AbstractHeapType::Extern => AbstractHeapType::Extern,
            wasmparser::AbstractHeapType::Any => AbstractHeapType::Any,
            wasmparser::AbstractHeapType::None => AbstractHeapType::None,
            wasmparser::AbstractHeapType::NoExtern => AbstractHeapType::NoExtern,
            wasmparser::AbstractHeapType::NoFunc => AbstractHeapType::NoFunc,
            wasmparser::AbstractHeapType::Eq => AbstractHeapType::Eq,
            wasmparser::AbstractHeapType::Struct => AbstractHeapType::Struct,
            wasmparser::AbstractHeapType::Array => AbstractHeapType::Array,
            wasmparser::AbstractHeapType::I31 => AbstractHeapType::I31,
            wasmparser::AbstractHeapType::Exn => AbstractHeapType::Exn,
            wasmparser::AbstractHeapType::NoExn => AbstractHeapType::NoExn,
            wasmparser::AbstractHeapType::Cont | wasmparser::AbstractHeapType::NoCont => {
                bail!("Stack switching proposal is not supported")
            }
        })
    }
}

// ---------------------------------------------------------------------------
// Reference types
// ---------------------------------------------------------------------------

/// A reference type.
///
/// Reference types include function references, external references, and
/// the GC proposal types (anyref, eqref, i31ref, etc.).
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct RefType {
    /// Whether this reference type is nullable.
    pub nullable: bool,
    /// The heap type that this reference points to.
    pub heap_type: HeapType,
}

impl RefType {
    /// Alias for the `anyref` type in WebAssembly.
    pub const ANYREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::Any),
    };

    /// Alias for the `eqref` type in WebAssembly.
    pub const EQREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::Eq),
    };

    /// Alias for the `funcref` type in WebAssembly.
    pub const FUNCREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::Func),
    };

    /// Alias for the `externref` type in WebAssembly.
    pub const EXTERNREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::Extern),
    };

    /// Alias for the `i31ref` type in WebAssembly.
    pub const I31REF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::I31),
    };

    /// Alias for the `arrayref` type in WebAssembly.
    pub const ARRAYREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::Array),
    };

    /// Alias for the `structref` type in WebAssembly.
    pub const STRUCTREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::Struct),
    };

    /// Alias for the `exnref` type in WebAssembly.
    pub const EXNREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::Exn),
    };

    /// Alias for the `nullref` type in WebAssembly.
    pub const NULLREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::None),
    };

    /// Alias for the `nullexternref` type in WebAssembly.
    pub const NULLEXTERNREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::NoExtern),
    };

    /// Alias for the `nullfuncref` type in WebAssembly.
    pub const NULLFUNCREF: RefType = RefType {
        nullable: true,
        heap_type: HeapType::Abstract(AbstractHeapType::NoFunc),
    };

    /// Returns whether this reference type is nullable.
    pub fn is_nullable(&self) -> bool {
        self.nullable
    }

    /// Convert to wasm_encoder RefType, resolving concrete type indices via
    /// `IdsToIndices`.
    pub fn to_wasmencoder_ref_type(
        self,
        indices: &crate::emit::IdsToIndices,
    ) -> wasm_encoder::RefType {
        wasm_encoder::RefType {
            nullable: self.nullable,
            heap_type: self.heap_type.to_wasmencoder_heap_type(indices),
        }
    }
}

impl TryFrom<wasmparser::RefType> for RefType {
    type Error = anyhow::Error;

    fn try_from(ref_type: wasmparser::RefType) -> Result<RefType> {
        Ok(RefType {
            nullable: ref_type.is_nullable(),
            heap_type: ref_type.heap_type().try_into()?,
        })
    }
}

impl RefType {
    /// Convert a wasmparser RefType to a walrus RefType, resolving concrete
    /// type indices via `IndicesToIds`.
    pub(crate) fn from_wasmparser(
        ref_type: wasmparser::RefType,
        ids: &crate::parse::IndicesToIds,
        rec_group_start: u32,
    ) -> Result<RefType> {
        Ok(RefType {
            nullable: ref_type.is_nullable(),
            heap_type: HeapType::from_wasmparser(ref_type.heap_type(), ids, rec_group_start)?,
        })
    }
}

impl fmt::Display for RefType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.nullable {
            // Use shorthand names for common nullable types
            match self.heap_type {
                HeapType::Abstract(AbstractHeapType::Func) => write!(f, "funcref"),
                HeapType::Abstract(AbstractHeapType::Extern) => write!(f, "externref"),
                HeapType::Abstract(AbstractHeapType::Exn) => write!(f, "exnref"),
                HeapType::Abstract(AbstractHeapType::Any) => write!(f, "anyref"),
                HeapType::Abstract(AbstractHeapType::Eq) => write!(f, "eqref"),
                HeapType::Abstract(AbstractHeapType::I31) => write!(f, "i31ref"),
                HeapType::Abstract(AbstractHeapType::Struct) => write!(f, "structref"),
                HeapType::Abstract(AbstractHeapType::Array) => write!(f, "arrayref"),
                HeapType::Abstract(AbstractHeapType::None) => write!(f, "nullref"),
                HeapType::Abstract(AbstractHeapType::NoExtern) => write!(f, "nullexternref"),
                HeapType::Abstract(AbstractHeapType::NoFunc) => write!(f, "nullfuncref"),
                HeapType::Abstract(AbstractHeapType::NoExn) => write!(f, "nullexnref"),
                HeapType::Concrete(id) => write!(f, "(ref null {})", id.index()),
                HeapType::Exact(id) => write!(f, "(ref null exact {})", id.index()),
            }
        } else {
            write!(f, "(ref {})", self.heap_type)
        }
    }
}

// ---------------------------------------------------------------------------
// ValType conversion impls
// ---------------------------------------------------------------------------

impl ValType {
    pub(crate) fn from_wasmparser_type(
        ty: wasmparser::ValType,
        ids: &crate::parse::IndicesToIds,
    ) -> Result<Box<[ValType]>> {
        let v = vec![ValType::from_wasmparser(&ty, ids, 0)?];
        Ok(v.into_boxed_slice())
    }

    #[allow(clippy::wrong_self_convention)]
    pub(crate) fn to_wasmencoder_type(
        &self,
        indices: &crate::emit::IdsToIndices,
    ) -> wasm_encoder::ValType {
        match self {
            ValType::I32 => wasm_encoder::ValType::I32,
            ValType::I64 => wasm_encoder::ValType::I64,
            ValType::F32 => wasm_encoder::ValType::F32,
            ValType::F64 => wasm_encoder::ValType::F64,
            ValType::V128 => wasm_encoder::ValType::V128,
            ValType::Ref(ref_type) => {
                wasm_encoder::ValType::Ref(ref_type.to_wasmencoder_ref_type(indices))
            }
        }
    }

    /// Convert a wasmparser ValType to a walrus ValType, resolving concrete
    /// type indices via `IndicesToIds`.
    pub(crate) fn from_wasmparser(
        input: &wasmparser::ValType,
        ids: &crate::parse::IndicesToIds,
        rec_group_start: u32,
    ) -> Result<ValType> {
        match input {
            wasmparser::ValType::I32 => Ok(ValType::I32),
            wasmparser::ValType::I64 => Ok(ValType::I64),
            wasmparser::ValType::F32 => Ok(ValType::F32),
            wasmparser::ValType::F64 => Ok(ValType::F64),
            wasmparser::ValType::V128 => Ok(ValType::V128),
            wasmparser::ValType::Ref(wasmparser::RefType::CONT)
            | wasmparser::ValType::Ref(wasmparser::RefType::CONTREF)
            | wasmparser::ValType::Ref(wasmparser::RefType::NULLCONTREF)
            | wasmparser::ValType::Ref(wasmparser::RefType::NOCONT) => {
                bail!("The stack switching proposal is not supported")
            }
            wasmparser::ValType::Ref(ref_type) => Ok(ValType::Ref(RefType::from_wasmparser(
                *ref_type,
                ids,
                rec_group_start,
            )?)),
        }
    }
}

impl fmt::Display for ValType {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ValType::I32 => write!(f, "i32"),
            ValType::I64 => write!(f, "i64"),
            ValType::F32 => write!(f, "f32"),
            ValType::F64 => write!(f, "f64"),
            ValType::V128 => write!(f, "v128"),
            ValType::Ref(r) => write!(f, "{}", r),
        }
    }
}