1
//! Static inference of the `PairElement` a `$pair` cell rides. Single source
2
//! of truth for CONS, LIST / APPEND chains and the literal-slot mirrors: the
3
//! most specific homogeneous element when every cell agrees, widened to
4
//! `PairElement::AnyRef` (ADR-0025 escape hatch) when they disagree.
5

            
6
use anodized::spec;
7

            
8
use crate::ast::{Expr, Number, PairElement, WasmType};
9
use crate::compiler::expr::{format_expr, index_literal};
10
use crate::error::{Error, Result};
11
use crate::runtime::Value;
12

            
13
/// What one cell contributes to its chain's element.
14
#[derive(Clone, Copy)]
15
enum CellSlot {
16
    Fixed(PairElement),
17
    /// An integer literal an index cell holds exactly: Index by default
18
    /// (ADR-0028), crossing to a `Ratio` neighbor.
19
    IndexLiteral,
20
}
21

            
22
/// Infers the `PairElement` for a runtime CONS. The car's runtime type or
23
/// literal slot unifies with the cdr's cells — a typed `PairRef` cdr's element,
24
/// or each member of a constant quoted-list cdr. A constant car with no literal
25
/// slot adopts a typed cdr's element.
26
642081
pub(super) fn infer_pair_element(car: &Expr, cdr: &Expr) -> Result<PairElement> {
27
642081
    let cdr_slots = cdr_slots(cdr)?;
28
642078
    let mut slots = vec![car_slot(car, &cdr_slots)?];
29
642074
    slots.extend(cdr_slots);
30
642074
    Ok(unify_slots(&slots))
31
642081
}
32

            
33
642078
fn car_slot(car: &Expr, cdr_slots: &[CellSlot]) -> Result<CellSlot> {
34
642078
    if let Some(ty) = car.wasm_type() {
35
297725
        return Ok(CellSlot::Fixed(runtime_cell_slot(ty)));
36
344353
    }
37
344353
    match (checked_literal_slot(car)?, cdr_slots.first()) {
38
336963
        (Some(slot), _) => Ok(slot),
39
7387
        (None, _) if matches!(car, Expr::Lambda(..)) => Ok(CellSlot::Fixed(PairElement::AnyRef)),
40
1
        (None, Some(slot)) => Ok(*slot),
41
1
        (None, None) => Err(Error::Compile(format!(
42
1
            "CONS: cannot infer element type from constant car {} — \
43
1
             supply a typed cdr (a pair) or a typed runtime car",
44
1
            format_expr(car)
45
1
        ))),
46
    }
47
642078
}
48

            
49
642081
fn cdr_slots(cdr: &Expr) -> Result<Vec<CellSlot>> {
50
642081
    match (cdr.wasm_type(), cdr) {
51
604015
        (Some(WasmType::PairRef(elem)), _) => Ok(vec![CellSlot::Fixed(elem)]),
52
3553
        (None, Expr::Datum(inner)) => match inner.as_ref() {
53
3553
            Expr::List(members) => members.iter().map(element_slot).collect(),
54
            _ => Ok(Vec::new()),
55
        },
56
34513
        _ => Ok(Vec::new()),
57
    }
58
642081
}
59

            
60
/// The natural `PairElement` of a literal car: an integer an index cell holds
61
/// exactly is `I32` (ADR-0028), a scalar literal `Ratio`, a
62
/// tagged commodity `Commodity`, `nil` / a bool the `Bool` truth slot, a string
63
/// `StringRef`, a symbol or keyword `Symbol`.
64
#[spec(ensures: |output| [
65
113694
    output != Some(PairElement::AnyRef),
66
113694
    output.is_some() == (matches!(car, Expr::Number(_) | Expr::T | Expr::Nil | Expr::String(_)
67
        | Expr::RuntimeValue(Value::Commodity { .. }))
68
10578
        || is_symbol_literal(car)),
69
])]
70
113694
pub(in crate::compiler) fn literal_pair_element(car: &Expr) -> Option<PairElement> {
71
113694
    literal_cell_slot(car).map(|slot| match slot {
72
3866
        CellSlot::Fixed(elem) => elem,
73
99895
        CellSlot::IndexLiteral => PairElement::I32,
74
103761
    })
75
113694
}
76

            
77
/// Whether a resolved value must ride a `Ratio` car: a scalar literal.
78
2401037
#[spec(ensures: |output| !output || matches!(value, Expr::Number(_)))]
79
2401037
pub(super) fn is_scalar_literal(value: &Expr) -> bool {
80
2401037
    matches!(
81
2401037
        literal_cell_slot(value),
82
        Some(CellSlot::Fixed(PairElement::Ratio))
83
    )
84
2401037
}
85

            
86
4911100
fn literal_cell_slot(expr: &Expr) -> Option<CellSlot> {
87
4911100
    match expr {
88
4260682
        Expr::Number(Number::Index(_)) => Some(CellSlot::IndexLiteral),
89
25505
        Expr::Number(Number::Scalar(_)) => Some(CellSlot::Fixed(PairElement::Ratio)),
90
24830
        Expr::T | Expr::Nil => Some(CellSlot::Fixed(PairElement::Bool)),
91
142169
        Expr::String(_) => Some(CellSlot::Fixed(PairElement::StringRef)),
92
        Expr::RuntimeValue(Value::Commodity { .. }) => {
93
            Some(CellSlot::Fixed(PairElement::Commodity))
94
        }
95
457914
        _ if is_symbol_literal(expr) => Some(CellSlot::Fixed(PairElement::Symbol)),
96
397556
        _ => None,
97
    }
98
4911100
}
99

            
100
/// A symbol or keyword as list data, bare or quoted.
101
468492
fn is_symbol_literal(expr: &Expr) -> bool {
102
468492
    match expr {
103
        Expr::Quote(inner) | Expr::Datum(inner) => {
104
101145
            matches!(inner.as_ref(), Expr::Symbol(_) | Expr::Keyword(_))
105
        }
106
367347
        other => matches!(other, Expr::Symbol(_) | Expr::Keyword(_)),
107
    }
108
468492
}
109

            
110
/// The unified `PairElement` of a chain built from resolved `elems` (LIST
111
/// cells, APPEND members, a FOLD seed). A non-literal constant rides `AnyRef`;
112
/// an empty chain is `AnyRef`.
113
2998975
#[spec(ensures: |ref output| !elems.is_empty() || matches!(output, Ok(PairElement::AnyRef)))]
114
2998975
pub(in crate::compiler) fn chain_pair_element(elems: &[Expr]) -> Result<PairElement> {
115
2998975
    let slots = elems.iter().map(element_slot).collect::<Result<Vec<_>>>()?;
116
2998971
    Ok(unify_slots(&slots))
117
2998975
}
118

            
119
5009351
fn element_slot(elem: &Expr) -> Result<CellSlot> {
120
5009351
    match elem.wasm_type() {
121
2957325
        Some(ty) => Ok(CellSlot::Fixed(runtime_cell_slot(ty))),
122
2052026
        None => Ok(checked_literal_slot(elem)?.unwrap_or(CellSlot::Fixed(PairElement::AnyRef))),
123
    }
124
5009351
}
125

            
126
/// [`literal_cell_slot`], refusing an integer literal no index can hold: a
127
/// list cell takes a literal only within the index range.
128
2396379
fn checked_literal_slot(expr: &Expr) -> Result<Option<CellSlot>> {
129
2396379
    if let Expr::Number(Number::Index(i)) = expr {
130
2178957
        index_literal(*i)?;
131
217422
    }
132
2396369
    Ok(literal_cell_slot(expr))
133
2396379
}
134

            
135
/// The cell a runtime value of `ty` rides: its own slot, or — for a nested
136
/// list, which has no slot of its own — the `AnyRef` escape hatch (ADR-0025),
137
/// so a list of lists is a `pair<any>` whose cars the consumer downcasts.
138
3576682
pub(in crate::compiler) fn runtime_cell_slot(ty: WasmType) -> PairElement {
139
3576682
    PairElement::from_wasm_type(ty).unwrap_or(PairElement::AnyRef)
140
3576682
}
141

            
142
/// Fixed slots widen pairwise; index literals take an `I32` / `Ratio` result
143
/// (and make a literal-only chain `I32`), widening anything else to `AnyRef`.
144
3641045
fn unify_slots(slots: &[CellSlot]) -> PairElement {
145
3641045
    let fixed = slots
146
3641045
        .iter()
147
6255430
        .filter_map(|slot| match slot {
148
4076486
            CellSlot::Fixed(elem) => Some(*elem),
149
2178944
            CellSlot::IndexLiteral => None,
150
6255430
        })
151
3641045
        .reduce(PairElement::widen);
152
3641045
    let index_literal = slots
153
3641045
        .iter()
154
4172266
        .any(|slot| matches!(slot, CellSlot::IndexLiteral));
155
3641045
    match (fixed, index_literal) {
156
102586
        (None, true) => PairElement::I32,
157
1041
        (None, false) => PairElement::AnyRef,
158
3485148
        (Some(elem @ (PairElement::I32 | PairElement::Ratio)), _) | (Some(elem), false) => elem,
159
52270
        (Some(_), true) => PairElement::AnyRef,
160
    }
161
3641045
}