1
//! `(the TYPE form)`: the checked narrowing of an `any` value (CL `THE`).
2
//! TYPE is `index`, `scalar`, `money` or `string`. A statically typed form
3
//! must already be of that type — `THE` narrows, it never converts; a runtime
4
//! `AnyRef` is tested and throws a catchable `TYPE-ERROR` on a mismatch.
5

            
6
use super::NativeSpec;
7
use super::list::emit_pair_car_downcast;
8
use crate::ast::{Expr, Number, PairElement, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::{
12
    compile_for_stack, compile_index_operand, compile_ratio_operand, eval_value, format_expr,
13
    probe_value,
14
};
15
use crate::error::{Error, Result, with_article};
16
use crate::runtime::{DOTIMES_COUNT, SymbolTable};
17
use wasm_encoder::{BlockType, HeapType};
18

            
19
pub(super) const NATIVES: &[NativeSpec] = &[NativeSpec {
20
    name: "THE",
21
    eval: the_eval,
22
    stack: Some(compile_the_to_stack),
23
    effect: None,
24
}];
25

            
26
/// Who asked for the narrowing, so a refusal names what the user wrote.
27
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
28
enum Subject {
29
    The,
30
    DotimesCount,
31
}
32

            
33
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34
pub(in crate::compiler) enum Target {
35
    Index,
36
    Scalar,
37
    Money,
38
    String,
39
}
40

            
41
impl Target {
42
34868
    fn parse(name: &str) -> Result<(Self, Subject)> {
43
34868
        match name.to_ascii_lowercase().as_str() {
44
14436
            "index" => Ok((Self::Index, Subject::The)),
45
190
            "scalar" => Ok((Self::Scalar, Subject::The)),
46
33
            "money" => Ok((Self::Money, Subject::The)),
47
25
            "string" => Ok((Self::String, Subject::The)),
48
20184
            _ if name.eq_ignore_ascii_case(DOTIMES_COUNT) => {
49
20179
                Ok((Self::Index, Subject::DotimesCount))
50
            }
51
5
            _ => Err(Error::Compile(format!(
52
5
                "THE type must be one of index, scalar, money, string, got {name}"
53
5
            ))),
54
        }
55
34868
    }
56

            
57
    /// The target whose narrowed value has type `ty`.
58
211
    pub(in crate::compiler) fn from_wasm(ty: WasmType) -> Option<Self> {
59
211
        match ty {
60
209
            WasmType::I32 => Some(Self::Index),
61
            WasmType::Ratio => Some(Self::Scalar),
62
            WasmType::Commodity => Some(Self::Money),
63
1
            WasmType::StringRef => Some(Self::String),
64
1
            _ => None,
65
        }
66
211
    }
67

            
68
37499
    fn wasm(self) -> WasmType {
69
37499
        match self {
70
37200
            Self::Index => WasmType::I32,
71
219
            Self::Scalar => WasmType::Ratio,
72
45
            Self::Money => WasmType::Commodity,
73
35
            Self::String => WasmType::StringRef,
74
        }
75
37499
    }
76

            
77
2653
    fn element(self) -> PairElement {
78
2653
        match self {
79
2598
            Self::Index => PairElement::I32,
80
30
            Self::Scalar => PairElement::Ratio,
81
15
            Self::Money => PairElement::Commodity,
82
10
            Self::String => PairElement::StringRef,
83
        }
84
2653
    }
85

            
86
134
    fn word(self) -> &'static str {
87
134
        match self {
88
112
            Self::Index => "index",
89
10
            Self::Scalar => "scalar",
90
2
            Self::Money => "money",
91
10
            Self::String => "string",
92
        }
93
134
    }
94

            
95
84
    fn mismatch(self, subject: Subject, got: &str) -> Error {
96
84
        let article = with_article(self.word());
97
84
        let message = match subject {
98
50
            Subject::The => format!(
99
50
                "THE {} expects {article} value, got {got}; THE narrows, it never converts",
100
50
                self.word()
101
            ),
102
34
            Subject::DotimesCount => format!("DOTIMES count expects {article} value, got {got}"),
103
        };
104
84
        match self {
105
5
            Self::String => Error::Compile(message),
106
79
            _ => Error::Dimension(message),
107
        }
108
84
    }
109
}
110

            
111
/// The type a `(the TYPE form)` call lowers to, for the stack-type classifier.
112
574627
pub(in crate::compiler) fn the_result_type(elems: &[Expr]) -> Option<WasmType> {
113
574627
    match elems {
114
538680
        [Expr::Symbol(head), Expr::Symbol(name), _] if head.eq_ignore_ascii_case("THE") => {
115
57
            Target::parse(name).ok().map(|(target, _)| target.wasm())
116
        }
117
574570
        _ => None,
118
    }
119
574627
}
120

            
121
34816
fn parse_args(args: &[Expr]) -> Result<(Target, Subject, &Expr)> {
122
34816
    match args {
123
        [Expr::Symbol(name), form] => {
124
34811
            let (target, subject) = Target::parse(name)?;
125
34807
            Ok((target, subject, form))
126
        }
127
1
        [_, _] => Err(Error::Compile(
128
1
            "THE type must be one of index, scalar, money, string".to_string(),
129
1
        )),
130
4
        _ => Err(Error::Arity {
131
4
            name: "THE".to_string(),
132
4
            expected: 2,
133
4
            actual: args.len(),
134
4
        }),
135
    }
136
34816
}
137

            
138
30107
fn the_eval(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
139
30107
    let (target, subject, form) = parse_args(args)?;
140
30104
    let value = eval_value(symbols, form)?;
141
30088
    let want = target.wasm();
142
30088
    match (&value, target) {
143
        (Expr::Number(Number::Index(_)), Target::Index)
144
20043
        | (Expr::Number(Number::Scalar(_)), Target::Scalar) => Ok(value),
145
1
        (Expr::Number(Number::Index(_)), Target::Scalar) => Ok(Expr::WasmRuntime(want)),
146
        (Expr::Number(Number::Scalar(_)), Target::Index) => {
147
43
            Err(target.mismatch(subject, &WasmType::Ratio.to_string()))
148
        }
149
1
        (Expr::String(_), Target::String) => Ok(value),
150
10000
        _ => match value.wasm_type() {
151
9996
            Some(ty) if ty == want => Ok(value),
152
9894
            Some(WasmType::AnyRef) => Ok(Expr::WasmRuntime(want)),
153
6
            Some(ty) => Err(target.mismatch(subject, &ty.to_string())),
154
4
            None => Err(target.mismatch(subject, &format_expr(&value))),
155
        },
156
    }
157
30107
}
158

            
159
4709
fn compile_the_to_stack(
160
4709
    ctx: &mut CompileContext,
161
4709
    emit: &mut FunctionEmitter,
162
4709
    symbols: &mut SymbolTable,
163
4709
    args: &[Expr],
164
4709
) -> Result<WasmType> {
165
4709
    let (target, subject, form) = parse_args(args)?;
166
4703
    let want = target.wasm();
167
4703
    if let Expr::Number(n) = probe_value(&mut symbols.clone(), form)? {
168
2195
        match target {
169
2186
            Target::Index if matches!(n, Number::Scalar(_)) => {
170
19
                emit.reject_if_live(target.mismatch(subject, &WasmType::Ratio.to_string()))?;
171
            }
172
2167
            Target::Index => compile_index_operand(ctx, emit, symbols, form)?,
173
6
            Target::Scalar => compile_ratio_operand(ctx, emit, symbols, form)?,
174
            Target::Money | Target::String => {
175
3
                emit.reject_if_live(target.mismatch(subject, "a number literal"))?;
176
            }
177
        }
178
2173
        return Ok(want);
179
2508
    }
180
2508
    match compile_for_stack(ctx, emit, symbols, form)? {
181
2502
        ty if ty == want => {}
182
2440
        WasmType::AnyRef => emit_narrow(ctx, emit, target)?,
183
9
        ty => emit.reject_if_live(target.mismatch(subject, &ty.to_string()))?,
184
    }
185
2493
    Ok(want)
186
4709
}
187

            
188
/// Tests the `AnyRef` on the stack for `target` (a non-null instance) and
189
/// casts it, throwing the target's `TYPE-ERROR` otherwise.
190
2648
pub(in crate::compiler) fn emit_narrow(
191
2648
    ctx: &mut CompileContext,
192
2648
    emit: &mut FunctionEmitter,
193
2648
    target: Target,
194
2648
) -> Result<()> {
195
2648
    let local = ctx.alloc_local(WasmType::AnyRef)?;
196
2648
    emit.local_tee(local);
197
2648
    let (heap, throw) = match target {
198
2596
        Target::Index => (HeapType::I31, ctx.ids.not_an_index),
199
29
        Target::Scalar => (HeapType::Concrete(ctx.ids.ty_ratio), ctx.ids.not_a_scalar),
200
14
        Target::Money => (HeapType::Concrete(ctx.ids.ty_commodity), ctx.ids.not_money),
201
9
        Target::String => (
202
9
            HeapType::Concrete(ctx.ids.ty_i8_array),
203
9
            ctx.ids.not_a_string,
204
9
        ),
205
    };
206
2648
    emit.ref_test_non_null(heap);
207
2648
    emit.if_block(BlockType::Result(ctx.wasm_val_type(target.wasm())?));
208
2648
    emit.local_get(local);
209
2648
    emit_pair_car_downcast(ctx, emit, target.element())?;
210
2648
    emit.else_block();
211
2648
    emit.call(throw);
212
2648
    emit.unreachable();
213
2648
    emit.block_end()
214
2648
}
215

            
216
#[cfg(test)]
217
#[path = "the_tests.rs"]
218
mod tests;