1
//! Arm reconciliation and the single nil classifier (ADR-0033), shared by the
2
//! multi-arm forms.
3

            
4
use crate::ast::{PairElement, WasmType};
5

            
6
/// Whether — and how — a value of static type `ty` can be `nil` (ADR-0033).
7
/// The single source of truth every nil-facing consumer routes through. One
8
/// row per [`WasmType`] variant, so a new variant without a row is a Rust
9
/// compile error.
10
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11
pub(crate) enum NilRepr {
12
    /// `nil` is the unboxed i32 zero (`t` is one) — only `Bool`.
13
    I32Zero,
14
    /// This type has no valid `nil`; a nil arm beside it widens to `AnyRef`
15
    /// (or is a compile error, at the call site's discretion).
16
    Never,
17
    /// `nil` is `ref.null` in this type's reference slot.
18
    Null,
19
}
20

            
21
#[must_use]
22
6683358
pub(crate) fn nil_repr(ty: &WasmType) -> NilRepr {
23
6683358
    match ty {
24
6093425
        WasmType::Bool => NilRepr::I32Zero,
25
        WasmType::I32 | WasmType::Ratio | WasmType::Commodity | WasmType::Closure(_) => {
26
70953
            NilRepr::Never
27
        }
28
        WasmType::PairRef(_)
29
        | WasmType::StringRef
30
        | WasmType::SymbolRef
31
        | WasmType::EntityRef(_)
32
        | WasmType::StructRef(_)
33
518980
        | WasmType::AnyRef => NilRepr::Null,
34
    }
35
6683358
}
36

            
37
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
38
pub(crate) enum Arm {
39
    /// Compiled: a value of this type is already on the arm's stack.
40
    Value(WasmType),
41
    /// A numeric literal of this default stratum, not yet emitted.
42
    NumberLiteral(WasmType),
43
    /// A form resolving to `nil`, not yet emitted.
44
    Nil,
45
    /// A form resolving to a constant list of this chain element, materialized
46
    /// at the reconciled element once the result is known.
47
    ConstantList(PairElement),
48
}
49

            
50
/// A BLOCK exit or tail as one pass compiled it: its own arm, the same in
51
/// every pass, and the type its bytes left on the stack.
52
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
53
pub(crate) struct Exit {
54
    pub(crate) arm: Arm,
55
    pub(crate) emitted: WasmType,
56
}
57

            
58
/// The type a form that never returns reports, as `(error …)` does: its
59
/// bytes end `unreachable`, so the type is never observed at runtime.
60
pub(crate) const NEVER_RETURNS: WasmType = WasmType::I32;
61

            
62
/// Unifies reachable arms: compiled values join (pair elements widen), a
63
/// numeric literal adopts an Index/Scalar value's stratum, `nil` rides a
64
/// list / anyref / bool result, and anything else widens to `AnyRef`. With no
65
/// reachable arm the form never returns.
66
#[must_use]
67
3449858
pub(crate) fn reconcile_arms(arms: &[Arm]) -> WasmType {
68
3449858
    let mut value: Option<WasmType> = None;
69
3449858
    let mut literal: Option<WasmType> = None;
70
3449858
    let mut nil = false;
71
3449858
    for arm in arms {
72
10406867
        match *arm {
73
5224044
            Arm::Value(ty) => value = Some(joined(value, ty)),
74
15884
            Arm::ConstantList(elem) => value = Some(joined(value, WasmType::PairRef(elem))),
75
            Arm::NumberLiteral(ty) => {
76
4484875
                literal = Some(match literal {
77
2830957
                    Some(prev) if prev != ty => WasmType::Ratio,
78
4469984
                    _ => ty,
79
                });
80
            }
81
682064
            Arm::Nil => nil = true,
82
        }
83
    }
84
3449858
    let typed = match (value, literal) {
85
1795940
        (base, None) => base,
86
883749
        (None, lit) => lit,
87
770169
        (Some(base), Some(lit)) if literal_fits(base, lit) => Some(base),
88
71840
        (Some(base), Some(lit)) => Some(join_types(base, lit)),
89
    };
90
3449858
    match (typed, nil) {
91
15458
        (None, false) => NEVER_RETURNS,
92
37756
        (None, true) => WasmType::Bool,
93
2763515
        (Some(ty), false) => ty,
94
633129
        (Some(ty), true) => match nil_repr(&ty) {
95
587160
            NilRepr::I32Zero | NilRepr::Null => ty,
96
45969
            NilRepr::Never => WasmType::AnyRef,
97
        },
98
    }
99
3449858
}
100

            
101
/// [`reconcile_arms`] for a consumer that expects `expected`: when every
102
/// reachable arm is a numeric literal fitting it (or none is reachable),
103
/// nothing else fixes the type, so the consumer's does.
104
#[must_use]
105
236076
pub(crate) fn reconcile_arms_expecting(arms: &[Arm], expected: Option<WasmType>) -> WasmType {
106
123
    let adopts = |ty: &WasmType| {
107
123
        arms.iter()
108
128
            .all(|arm| matches!(arm, Arm::NumberLiteral(lit) if literal_fits(*ty, *lit)))
109
123
    };
110
236076
    match expected.filter(adopts) {
111
6
        Some(ty) => ty,
112
236070
        None => reconcile_arms(arms),
113
    }
114
236076
}
115

            
116
/// Whether a value of `ty` already stands as `result` with no instruction: the
117
/// same type, a pair under a widened element, or a reference read as
118
/// `AnyRef`. Only an i32-repr value needs boxing (`emit_box_anyref`).
119
#[must_use]
120
78183
pub(crate) fn rides(ty: WasmType, result: WasmType) -> bool {
121
78183
    match (ty, result) {
122
78183
        _ if ty == result => true,
123
1
        (WasmType::PairRef(_), WasmType::PairRef(_)) => true,
124
6593
        (WasmType::I32 | WasmType::Bool, _) => false,
125
2732
        (_, result) => result == WasmType::AnyRef,
126
    }
127
78183
}
128

            
129
2798873
fn join_types(a: WasmType, b: WasmType) -> WasmType {
130
2798873
    match (a, b) {
131
2798873
        _ if a == b => a,
132
32242
        (WasmType::PairRef(x), WasmType::PairRef(y)) => WasmType::PairRef(x.widen(y)),
133
351147
        _ => WasmType::AnyRef,
134
    }
135
2798873
}
136

            
137
5239928
fn joined(prev: Option<WasmType>, ty: WasmType) -> WasmType {
138
5239928
    match prev {
139
2727033
        Some(prev) => join_types(prev, ty),
140
2512895
        None => ty,
141
    }
142
5239928
}
143

            
144
/// Whether a literal of stratum `lit` can adopt `base`: an integer literal
145
/// becomes an index or a scalar, a fractional one only a scalar, and no literal
146
/// becomes Money (it has no currency).
147
#[must_use]
148
3068386
pub(crate) fn literal_fits(base: WasmType, lit: WasmType) -> bool {
149
3068386
    matches!(
150
3068386
        (base, lit),
151
        (WasmType::I32 | WasmType::Ratio, WasmType::I32) | (WasmType::Ratio, WasmType::Ratio)
152
    )
153
3068386
}
154

            
155
/// A fact never holds a closure type, so no signature id outlives its attempt.
156
#[must_use]
157
246811
pub(crate) fn fact(ty: WasmType) -> WasmType {
158
246811
    match ty {
159
2336
        WasmType::Closure(_) => WasmType::AnyRef,
160
10845
        WasmType::PairRef(PairElement::Closure(_)) => WasmType::PairRef(PairElement::AnyRef),
161
233630
        _ => ty,
162
    }
163
246811
}
164

            
165
#[cfg(test)]
166
#[path = "join_tests.rs"]
167
mod tests;