1
//! Pair element types and struct layout ids.
2

            
3
use core::fmt;
4

            
5
use crate::ast::{ClosureSigId, EntityKind, WasmType};
6

            
7
/// Element type of a homogeneous `$pair` chain. Tracked at compile time so
8
/// CAR/CDR emit the right downcast and CONS refuses heterogeneous mixing
9
/// with a structured type error. Kept as a `Copy` enum so `WasmType` stays
10
/// `Copy` — and so adding a new element type stays a one-line variant
11
/// addition. Nesting (pairs-of-pairs) waits for a follow-up sub-slice
12
/// once flat lists are stable across the consumers.
13
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
14
pub enum PairElement {
15
    I32,
16
    /// Truth-value cell: shares `I32`'s i31-boxed car representation (CAR/CDR
17
    /// emit the same i31 downcast), but distinct so a bool extracted from a
18
    /// list serializes as `Nil` / `Bool`, not `Number` — the list-element
19
    /// analogue of [`WasmType::Bool`] vs `I32`.
20
    Bool,
21
    Ratio,
22
    Commodity,
23
    StringRef,
24
    /// Runtime symbol or keyword: a `$symbol` struct carrying its printed name.
25
    Symbol,
26
    Entity(EntityKind),
27
    /// A `DEFSTRUCT` instance of this layout: a `$struct` reference.
28
    Struct(StructId),
29
    /// A closure of this signature: a closure struct reference.
30
    Closure(ClosureSigId),
31
    /// Heterogeneous escape hatch (ADR-0025). Cars stay as raw
32
    /// `anyref`; CAR returns `WasmType::AnyRef` and the script must
33
    /// downcast at the use site (or consume via type-test natives like
34
    /// `ok?` / `err-code`). CONS widens to this variant when the two
35
    /// arms disagree on element type, and host fns that produce
36
    /// fundamentally heterogeneous lists (e.g. =catch-each= result
37
    /// cells) construct directly into `PairRef(AnyRef)`.
38
    AnyRef,
39
}
40

            
41
impl fmt::Display for PairElement {
42
1714
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
43
1714
        match self {
44
653
            Self::I32 => write!(f, "i32"),
45
            Self::Bool => write!(f, "bool"),
46
634
            Self::Ratio => write!(f, "ratio"),
47
            Self::Commodity => write!(f, "commodity"),
48
212
            Self::StringRef => write!(f, "string"),
49
            Self::Symbol => write!(f, "symbol"),
50
            Self::Entity(kind) => write!(f, "{kind}"),
51
1
            Self::Struct(id) => write!(f, "{id}"),
52
212
            Self::Closure(sig) => write!(f, "{}", WasmType::Closure(*sig)),
53
2
            Self::AnyRef => write!(f, "any"),
54
        }
55
1714
    }
56
}
57

            
58
impl PairElement {
59
    /// The matching `WasmType` for a pair's car when extracted.
60
    #[must_use]
61
2161550
    pub fn as_wasm_type(self) -> WasmType {
62
2161550
        match self {
63
1930048
            Self::I32 => WasmType::I32,
64
17276
            Self::Bool => WasmType::Bool,
65
62351
            Self::Ratio => WasmType::Ratio,
66
2289
            Self::Commodity => WasmType::Commodity,
67
10430
            Self::StringRef => WasmType::StringRef,
68
2232
            Self::Symbol => WasmType::SymbolRef,
69
7698
            Self::Entity(kind) => WasmType::EntityRef(kind),
70
6467
            Self::Struct(id) => WasmType::StructRef(id),
71
36077
            Self::Closure(sig) => WasmType::Closure(sig),
72
86682
            Self::AnyRef => WasmType::AnyRef,
73
        }
74
2161550
    }
75

            
76
    /// Inverse of `as_wasm_type`: `None` for a nested list, which has no
77
    /// slot of its own. `WasmType::AnyRef` round-trips to `PairElement::AnyRef`.
78
    #[must_use]
79
3823844
    pub fn from_wasm_type(ty: WasmType) -> Option<Self> {
80
3823844
        match ty {
81
860666
            WasmType::I32 => Some(Self::I32),
82
            // `Bool` keeps its own slot — it shares `I32`'s i31-boxed car
83
            // representation (the CAR/CDR downcast is identical) but stays
84
            // distinct so a bool extracted from a list serializes as Nil/Bool,
85
            // not Number.
86
13333
            WasmType::Bool => Some(Self::Bool),
87
62212
            WasmType::Ratio => Some(Self::Ratio),
88
15532
            WasmType::Commodity => Some(Self::Commodity),
89
97437
            WasmType::StringRef => Some(Self::StringRef),
90
16477
            WasmType::SymbolRef => Some(Self::Symbol),
91
82392
            WasmType::EntityRef(kind) => Some(Self::Entity(kind)),
92
67310
            WasmType::StructRef(id) => Some(Self::Struct(id)),
93
132422
            WasmType::Closure(sig) => Some(Self::Closure(sig)),
94
48705
            WasmType::AnyRef => Some(Self::AnyRef),
95
2427358
            WasmType::PairRef(_) => None,
96
        }
97
3823844
    }
98

            
99
    /// Widen `self` against `other` to the most-specific common
100
    /// element. Identical types stay; everything else widens to
101
    /// `AnyRef` so heterogeneous CONS no longer errors. Symmetric.
102
    #[must_use]
103
571316
    pub fn widen(self, other: Self) -> Self {
104
571316
        if self == other { self } else { Self::AnyRef }
105
571316
    }
106
}
107

            
108
/// Index of a `DEFSTRUCT` layout in the session's struct registry. Rides
109
/// inside `WasmType` like `ClosureSigId`, so it stays small and `Copy`.
110
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
111
pub struct StructId(pub u32);
112

            
113
impl fmt::Display for StructId {
114
1460
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
115
1460
        write!(f, "struct#{}", self.0)
116
1460
    }
117
}