1
//! Guest-side i32-repr value helpers: range-checked i31 boxing of an index,
2
//! nil-as-null boxing of a bool, and index arithmetic / car-of-nil that throw
3
//! catchable `$nomi_error` conditions (ADR-0026) instead of silently wrapping
4
//! or trapping the engine.
5

            
6
use super::CompileContext;
7
use super::exception::ConditionTrap;
8
use crate::error::Result;
9
use wasm_encoder::{BlockType, Function, HeapType, Instruction, ValType};
10

            
11
impl CompileContext {
12
2352712
    pub(super) fn declare_index_helpers(&mut self) -> Result<()> {
13
2352712
        let anyref = self.anyref();
14
2352712
        let index = ValType::I32;
15
2352712
        self.register_function("box_index", &[index], &[anyref])?;
16
2352712
        self.register_function("box_bool", &[index], &[anyref])?;
17
2352712
        self.register_function("index_div", &[index, index], &[index])?;
18
2352712
        self.register_function("index_rem", &[index, index], &[index])?;
19
2352712
        self.register_function("index_add", &[index, index], &[index])?;
20
2352712
        self.register_function("index_sub", &[index, index], &[index])?;
21
2352712
        self.register_function("index_mul", &[index, index], &[index])?;
22
2352712
        self.register_function("index_narrow", &[ValType::I64], &[index])?;
23
2352712
        self.register_function("car_of_nil", &[], &[])?;
24
2352712
        self.register_function("not_a_list", &[], &[])?;
25
2352712
        self.register_function("nil_string", &[], &[])?;
26
2352712
        self.register_function("nil_entity", &[], &[])?;
27
2352712
        self.register_function("output_overflow", &[], &[])?;
28
2352712
        self.register_function("not_a_symbol", &[], &[])?;
29
2352712
        for name in [
30
2352712
            "not_an_index",
31
2352712
            "not_a_scalar",
32
2352712
            "not_money",
33
2352712
            "not_a_string",
34
2352712
            "not_printable",
35
2352712
            "not_a_function",
36
2352712
            "wrong_function_arguments",
37
2352712
            "symbol_not_callable",
38
2352712
        ] {
39
18821696
            self.register_function(name, &[], &[])?;
40
        }
41
2352712
        Ok(())
42
2352712
    }
43

            
44
    /// Emits the helper bodies in [`Self::declare_index_helpers`] order.
45
2352712
    pub(super) fn build_index_helpers(&mut self) -> Result<()> {
46
2352712
        let beyond_i31 = self.register_condition_trap(
47
2352712
            "INDEX-OVERFLOW",
48
2352712
            "index value outside the 31-bit range -1073741824..1073741823",
49
2352712
        )?;
50
2352712
        let quotient_overflow = self.register_condition_trap(
51
2352712
            "INDEX-OVERFLOW",
52
2352712
            "index quotient -2147483648 / -1 overflows 32 bits",
53
2352712
        )?;
54
2352712
        let beyond_i32 = self.register_condition_trap(
55
2352712
            "INDEX-OVERFLOW",
56
2352712
            "index arithmetic result outside the 32-bit range",
57
2352712
        )?;
58
2352712
        let div_by_zero = self.register_condition_trap("DIVISION-BY-ZERO", "division by zero")?;
59
        let car_of_nil =
60
2352712
            self.register_condition_trap("TYPE-ERROR", "car of an empty list has no value")?;
61
2352712
        let not_a_list = self.register_condition_trap("TYPE-ERROR", "not a list")?;
62
2352712
        let nil_string = self.register_condition_trap("TYPE-ERROR", "nil is not a string")?;
63
2352712
        let nil_entity = self.register_condition_trap("TYPE-ERROR", "nil is not an entity")?;
64
2352712
        let not_a_symbol = self.register_condition_trap("TYPE-ERROR", "not a symbol")?;
65
2352712
        let narrowing_traps = [
66
2352712
            "not an index",
67
2352712
            "not a scalar",
68
2352712
            "not money",
69
2352712
            "not a string",
70
2352712
            "not printable",
71
2352712
            "not a function",
72
2352712
            "the function does not take these arguments",
73
2352712
            "a built-in function designator is not callable as an any value yet",
74
2352712
        ]
75
18821696
        .map(|message| self.register_condition_trap("TYPE-ERROR", message))
76
        .into_iter()
77
        .collect::<Result<Vec<_>>>()?;
78
2352712
        let output_overflow = self.register_condition_trap(
79
2352712
            "OUTPUT-OVERFLOW",
80
2352712
            "the script's output does not fit in its output buffer",
81
2352712
        )?;
82
2352712
        self.pending_helpers.push(box_index_body(&beyond_i31));
83
2352712
        self.pending_helpers
84
2352712
            .push(box_bool_body(self.anyref(), self.ids.global_t));
85
2352712
        self.pending_helpers
86
2352712
            .push(index_div_body(&div_by_zero, &quotient_overflow));
87
2352712
        self.pending_helpers.push(index_rem_body(&div_by_zero));
88
2352712
        for op in [
89
2352712
            Instruction::I64Add,
90
2352712
            Instruction::I64Sub,
91
2352712
            Instruction::I64Mul,
92
2352712
        ] {
93
7058136
            self.pending_helpers.push(index_wide_body(&op, &beyond_i32));
94
        }
95
2352712
        self.pending_helpers.push(index_narrow_body(&beyond_i32));
96
2352712
        self.pending_helpers.push(throw_body(&car_of_nil));
97
2352712
        self.pending_helpers.push(throw_body(&not_a_list));
98
2352712
        self.pending_helpers.push(throw_body(&nil_string));
99
2352712
        self.pending_helpers.push(throw_body(&nil_entity));
100
2352712
        self.pending_helpers.push(throw_body(&output_overflow));
101
2352712
        self.pending_helpers.push(throw_body(&not_a_symbol));
102
2352712
        for trap in &narrowing_traps {
103
18821696
            self.pending_helpers.push(throw_body(trap));
104
        }
105
2352712
        Ok(())
106
2352712
    }
107
}
108

            
109
/// `box_bool(i32) -> anyref` (ADR-0033): in an anyref slot `nil` is `ref.null`
110
/// and `t` is the `$t` singleton global — the same representation whether the
111
/// slot is typed `Bool` or `AnyRef`, so a bool car never needs rebuilding when
112
/// its chain widens.
113
2352712
fn box_bool_body(anyref: ValType, t_global: u32) -> Function {
114
2352712
    let mut f = Function::new([]);
115
2352712
    f.instruction(&Instruction::LocalGet(0));
116
2352712
    f.instruction(&Instruction::If(BlockType::Result(anyref)));
117
2352712
    f.instruction(&Instruction::GlobalGet(t_global));
118
2352712
    f.instruction(&Instruction::Else);
119
2352712
    f.instruction(&Instruction::RefNull(HeapType::ANY));
120
2352712
    f.instruction(&Instruction::End);
121
2352712
    f.instruction(&Instruction::End);
122
2352712
    f
123
2352712
}
124

            
125
/// A no-result helper that only throws `trap` (e.g. `car_of_nil`); callers
126
/// follow the call with `unreachable`.
127
32937968
fn throw_body(trap: &ConditionTrap) -> Function {
128
32937968
    let mut f = Function::new([]);
129
32937968
    trap.emit_throw(&mut f);
130
32937968
    f.instruction(&Instruction::End);
131
32937968
    f
132
32937968
}
133

            
134
/// `box_index(i32) -> anyref`: `ref.i31` keeps only 31 bits, so a value outside
135
/// [-2^30, 2^30-1] throws rather than wrapping.
136
2352712
fn box_index_body(beyond_i31: &ConditionTrap) -> Function {
137
2352712
    let mut f = Function::new([]);
138
    // v + 2^30 lands in [0, 2^31) exactly when v is in the i31 range.
139
2352712
    f.instruction(&Instruction::LocalGet(0));
140
2352712
    f.instruction(&Instruction::I32Const(1 << 30));
141
2352712
    f.instruction(&Instruction::I32Add);
142
2352712
    f.instruction(&Instruction::I32Const(i32::MIN));
143
2352712
    f.instruction(&Instruction::I32GeU);
144
2352712
    throw_if(&mut f, beyond_i31);
145
2352712
    f.instruction(&Instruction::LocalGet(0));
146
2352712
    f.instruction(&Instruction::RefI31);
147
2352712
    f.instruction(&Instruction::End);
148
2352712
    f
149
2352712
}
150

            
151
/// `index_div(a, b) -> i32`: truncating division that throws on a zero divisor
152
/// and on `i32::MIN / -1`, the one quotient that overflows.
153
2352712
fn index_div_body(div_by_zero: &ConditionTrap, overflow: &ConditionTrap) -> Function {
154
2352712
    let mut f = Function::new([]);
155
2352712
    throw_on_zero_divisor(&mut f, div_by_zero);
156
2352712
    f.instruction(&Instruction::LocalGet(0));
157
2352712
    f.instruction(&Instruction::I32Const(i32::MIN));
158
2352712
    f.instruction(&Instruction::I32Eq);
159
2352712
    f.instruction(&Instruction::LocalGet(1));
160
2352712
    f.instruction(&Instruction::I32Const(-1));
161
2352712
    f.instruction(&Instruction::I32Eq);
162
2352712
    f.instruction(&Instruction::I32And);
163
2352712
    throw_if(&mut f, overflow);
164
2352712
    finish_binop(f, &Instruction::I32DivS)
165
2352712
}
166

            
167
/// `index_rem(a, b) -> i32`: floored modulo, the result taking the divisor's
168
/// sign as CL's `MOD` does. Throws on a zero divisor (`i32.rem_s` defines
169
/// `i32::MIN rem -1` as 0, so no overflow check is needed).
170
2352712
fn index_rem_body(div_by_zero: &ConditionTrap) -> Function {
171
2352712
    let mut f = Function::new([(1, ValType::I32)]);
172
2352712
    throw_on_zero_divisor(&mut f, div_by_zero);
173
2352712
    f.instruction(&Instruction::LocalGet(0));
174
2352712
    f.instruction(&Instruction::LocalGet(1));
175
2352712
    f.instruction(&Instruction::I32RemS);
176
2352712
    f.instruction(&Instruction::LocalSet(2));
177
    // r != 0 and r, b of opposite signs: step r into the divisor's sign.
178
2352712
    f.instruction(&Instruction::LocalGet(2));
179
2352712
    f.instruction(&Instruction::LocalGet(1));
180
2352712
    f.instruction(&Instruction::I32Xor);
181
2352712
    f.instruction(&Instruction::I32Const(0));
182
2352712
    f.instruction(&Instruction::I32LtS);
183
2352712
    f.instruction(&Instruction::LocalGet(2));
184
2352712
    f.instruction(&Instruction::I32Const(0));
185
2352712
    f.instruction(&Instruction::I32Ne);
186
2352712
    f.instruction(&Instruction::I32And);
187
2352712
    f.instruction(&Instruction::If(BlockType::Result(ValType::I32)));
188
2352712
    f.instruction(&Instruction::LocalGet(2));
189
2352712
    f.instruction(&Instruction::LocalGet(1));
190
2352712
    f.instruction(&Instruction::I32Add);
191
2352712
    f.instruction(&Instruction::Else);
192
2352712
    f.instruction(&Instruction::LocalGet(2));
193
2352712
    f.instruction(&Instruction::End);
194
2352712
    f.instruction(&Instruction::End);
195
2352712
    f
196
2352712
}
197

            
198
/// `index_add` / `index_sub` / `index_mul(a, b) -> i32`: the operation in 64
199
/// bits, where no i32 operands overflow, throwing when the result leaves the
200
/// i32 range instead of wrapping.
201
7058136
fn index_wide_body(op: &Instruction<'_>, beyond_i32: &ConditionTrap) -> Function {
202
7058136
    let mut f = Function::new([(1, ValType::I64)]);
203
7058136
    f.instruction(&Instruction::LocalGet(0));
204
7058136
    f.instruction(&Instruction::I64ExtendI32S);
205
7058136
    f.instruction(&Instruction::LocalGet(1));
206
7058136
    f.instruction(&Instruction::I64ExtendI32S);
207
7058136
    f.instruction(op);
208
7058136
    f.instruction(&Instruction::LocalSet(2));
209
7058136
    narrow_local(&mut f, 2, beyond_i32);
210
7058136
    f.instruction(&Instruction::End);
211
7058136
    f
212
7058136
}
213

            
214
/// `index_narrow(n: i64) -> i32`: a scalar truncated to an index, throwing
215
/// when it leaves the i32 range instead of wrapping.
216
2352712
fn index_narrow_body(beyond_i32: &ConditionTrap) -> Function {
217
2352712
    let mut f = Function::new([]);
218
2352712
    narrow_local(&mut f, 0, beyond_i32);
219
2352712
    f.instruction(&Instruction::End);
220
2352712
    f
221
2352712
}
222

            
223
/// Pushes i64 local `n` as an i32, throwing when it is outside the i32 range.
224
9410848
fn narrow_local(f: &mut Function, n: u32, beyond_i32: &ConditionTrap) {
225
    // n + 2^31 lands in [0, 2^32) exactly when n is in the i32 range.
226
9410848
    f.instruction(&Instruction::LocalGet(n));
227
9410848
    f.instruction(&Instruction::I64Const(1 << 31));
228
9410848
    f.instruction(&Instruction::I64Add);
229
9410848
    f.instruction(&Instruction::I64Const(1 << 32));
230
9410848
    f.instruction(&Instruction::I64GeU);
231
9410848
    throw_if(f, beyond_i32);
232
9410848
    f.instruction(&Instruction::LocalGet(n));
233
9410848
    f.instruction(&Instruction::I32WrapI64);
234
9410848
}
235

            
236
4705424
fn throw_on_zero_divisor(f: &mut Function, div_by_zero: &ConditionTrap) {
237
4705424
    f.instruction(&Instruction::LocalGet(1));
238
4705424
    f.instruction(&Instruction::I32Eqz);
239
4705424
    throw_if(f, div_by_zero);
240
4705424
}
241

            
242
/// Consumes the i32 condition on the stack, throwing `trap` when it is set.
243
18821696
fn throw_if(f: &mut Function, trap: &ConditionTrap) {
244
18821696
    f.instruction(&Instruction::If(BlockType::Empty));
245
18821696
    trap.emit_throw(f);
246
18821696
    f.instruction(&Instruction::End);
247
18821696
}
248

            
249
2352712
fn finish_binop(mut f: Function, op: &Instruction<'_>) -> Function {
250
2352712
    f.instruction(&Instruction::LocalGet(0));
251
2352712
    f.instruction(&Instruction::LocalGet(1));
252
2352712
    f.instruction(op);
253
2352712
    f.instruction(&Instruction::End);
254
2352712
    f
255
2352712
}