1
//! The five natives behind a `DEFSTRUCT` instance. Their names contain
2
//! parentheses, which the reader never produces, so a program cannot call them
3
//! or forge an instance: only the lambdas `DEFSTRUCT` defines do. Each takes
4
//! the layout's `StructId` as an integer literal.
5

            
6
mod emit;
7

            
8
use super::NativeSpec;
9
use crate::ast::{Expr, Number, PairElement, StructId, WasmType};
10
use crate::compiler::expr::probe_value;
11
use crate::compiler::join::{Arm, reconcile_arms};
12
use crate::compiler::special::store_arm;
13
use crate::error::{Error, Result};
14
use crate::runtime::{StructLayout, SymbolTable};
15

            
16
pub(in crate::compiler) const NEW: &str = "(STRUCT-NEW)";
17
pub(in crate::compiler) const P: &str = "(STRUCT-P)";
18
pub(in crate::compiler) const REF: &str = "(STRUCT-REF)";
19
pub(in crate::compiler) const SET: &str = "(STRUCT-SET)";
20
pub(in crate::compiler) const COPY: &str = "(STRUCT-COPY)";
21

            
22
pub(super) const NATIVES: &[NativeSpec] = &[
23
    NativeSpec {
24
        name: NEW,
25
        eval: eval_new,
26
        stack: Some(emit::new),
27
        effect: None,
28
    },
29
    NativeSpec {
30
        name: P,
31
        eval: eval_p,
32
        stack: Some(emit::predicate),
33
        effect: None,
34
    },
35
    NativeSpec {
36
        name: REF,
37
        eval: eval_ref,
38
        stack: Some(emit::read),
39
        effect: None,
40
    },
41
    NativeSpec {
42
        name: SET,
43
        eval: eval_set,
44
        stack: Some(emit::write),
45
        effect: None,
46
    },
47
    NativeSpec {
48
        name: COPY,
49
        eval: eval_copy,
50
        stack: Some(emit::copy),
51
        effect: None,
52
    },
53
];
54

            
55
452795
pub(super) fn expect_arity(name: &str, args: &[Expr], expected: usize) -> Result<()> {
56
452795
    match args.len() == expected {
57
452790
        true => Ok(()),
58
5
        false => Err(Error::Arity {
59
5
            name: name.to_string(),
60
5
            expected,
61
5
            actual: args.len(),
62
5
        }),
63
    }
64
452795
}
65

            
66
578169
fn literal_u32(name: &str, arg: &Expr) -> Result<u32> {
67
578169
    match arg {
68
578168
        Expr::Number(Number::Index(i)) => u32::try_from(*i).map_err(|_| ()),
69
1
        _ => Err(()),
70
    }
71
1
    .map_err(|()| Error::Compile(format!("{name}: expected an integer literal")))
72
578169
}
73

            
74
/// The layout `arg` names, with its id.
75
452793
pub(super) fn layout_of(
76
452793
    symbols: &SymbolTable,
77
452793
    name: &str,
78
452793
    arg: &Expr,
79
452793
) -> Result<(StructId, StructLayout)> {
80
452793
    let id = StructId(literal_u32(name, arg)?);
81
452792
    let layout = symbols
82
452792
        .struct_layout(id)
83
452792
        .cloned()
84
1
        .ok_or_else(|| Error::Compile(format!("{name}: no struct layout {}", id.0)))?;
85
452791
    Ok((id, layout))
86
452793
}
87

            
88
/// The slot `arg` names in `layout`.
89
125376
pub(super) fn slot_of(name: &str, arg: &Expr, layout: &StructLayout) -> Result<u16> {
90
125376
    let slot = literal_u32(name, arg)?;
91
125376
    u16::try_from(slot)
92
125376
        .ok()
93
125376
        .filter(|found| usize::from(*found) < layout.fields.len())
94
1
        .ok_or_else(|| Error::Compile(format!("{name}: {} has no field {slot}", layout.name)))
95
125376
}
96

            
97
217610
fn eval_new(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
98
217610
    let first = args.first().ok_or_else(|| Error::Arity {
99
        name: NEW.to_string(),
100
        expected: 1,
101
        actual: 0,
102
    })?;
103
217610
    let (id, layout) = layout_of(symbols, NEW, first)?;
104
217610
    expect_arity(NEW, args, 1 + layout.fields.len())?;
105
217610
    Ok(Expr::WasmRuntime(WasmType::StructRef(id)))
106
217610
}
107

            
108
/// A predicate on a variable whose static type excludes the layout is nil
109
/// at compile time, so a branch it guards is never compiled.
110
5011
fn eval_p(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
111
5011
    expect_arity(P, args, 2)?;
112
5011
    let (id, _) = layout_of(symbols, P, &args[1])?;
113
5011
    match excludes(symbols, &args[0], id) {
114
2916
        true => Ok(Expr::Nil),
115
2095
        false => Ok(Expr::WasmRuntime(WasmType::Bool)),
116
    }
117
5011
}
118

            
119
5011
fn excludes(symbols: &SymbolTable, operand: &Expr, id: StructId) -> bool {
120
5011
    if !matches!(operand, Expr::Symbol(_)) {
121
12
        return false;
122
4999
    }
123
4999
    let Ok(held) = probe_value(&mut symbols.clone(), operand) else {
124
        return false;
125
    };
126
4999
    match held.wasm_type() {
127
        Some(WasmType::AnyRef) => false,
128
2918
        Some(WasmType::StructRef(found)) => found != id,
129
1249
        Some(_) => true,
130
832
        None => !held.is_wasm_runtime(),
131
    }
132
5011
}
133

            
134
46964
fn eval_ref(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
135
46964
    expect_arity(REF, args, 3)?;
136
46964
    let (id, layout) = layout_of(symbols, REF, &args[1])?;
137
46964
    let slot = slot_of(REF, &args[2], &layout)?;
138
46964
    Ok(Expr::WasmRuntime(symbols.field_type(id, slot)))
139
46964
}
140

            
141
17068
fn eval_set(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
142
17068
    expect_arity(SET, args, 4)?;
143
17068
    let (_, layout) = layout_of(symbols, SET, &args[1])?;
144
17068
    slot_of(SET, &args[2], &layout)?;
145
17068
    let probed = probe_value(&mut symbols.clone(), &args[3])?;
146
17068
    Ok(Expr::WasmRuntime(
147
17068
        store_arm(&probed).map_or(WasmType::AnyRef, stored_type),
148
17068
    ))
149
17068
}
150

            
151
/// What a SETF returns: the stored arm's own type when a slot read can unbox
152
/// it, else `AnyRef`.
153
37728
fn stored_type(arm: Arm) -> WasmType {
154
37728
    Some(reconcile_arms(&[arm]))
155
37728
        .filter(|ty| PairElement::from_wasm_type(*ty).is_some())
156
37728
        .unwrap_or(WasmType::AnyRef)
157
37728
}
158

            
159
1669
fn eval_copy(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
160
1669
    expect_arity(COPY, args, 2)?;
161
1669
    let (id, _) = layout_of(symbols, COPY, &args[1])?;
162
1669
    Ok(Expr::WasmRuntime(WasmType::StructRef(id)))
163
1669
}
164

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

            
169
#[cfg(test)]
170
#[path = "field_tests.rs"]
171
mod field_tests;