1
//! The arithmetic emitter over compiled operands: the ADR-0028 dimension
2
//! rules (index / scalar / money) and the instructions each operator emits,
3
//! once its operands are compiled into [`Slot`]s.
4

            
5
use super::ArithOp;
6
use crate::ast::{Expr, Number, WasmType};
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::compiler::expr::{always_raises, push_number, push_ratio};
10
use crate::error::{Error, Result, with_article};
11
use crate::runtime::SymbolTable;
12

            
13
#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Debug)]
14
pub(in crate::compiler::native) enum Dim {
15
    Index,
16
    Scalar,
17
    Money,
18
}
19

            
20
impl Dim {
21
7093602
    pub(in crate::compiler::native) fn wasm_type(self) -> WasmType {
22
7093602
        match self {
23
6976129
            Dim::Index => WasmType::I32,
24
97356
            Dim::Scalar => WasmType::Ratio,
25
20117
            Dim::Money => WasmType::Commodity,
26
        }
27
7093602
    }
28

            
29
194280
    fn describe(self) -> &'static str {
30
194280
        match self {
31
84779
            Dim::Index => "an index (count)",
32
67155
            Dim::Scalar => "a scalar",
33
42346
            Dim::Money => "a money value",
34
        }
35
194280
    }
36

            
37
65970753
    pub(in crate::compiler::native) fn of_number(n: Number) -> Dim {
38
65970753
        match n {
39
65791892
            Number::Index(_) => Dim::Index,
40
178861
            Number::Scalar(_) => Dim::Scalar,
41
        }
42
65970753
    }
43

            
44
7985129
    fn of_type(ty: WasmType) -> Option<Dim> {
45
7985129
        match ty {
46
7659291
            WasmType::I32 => Some(Dim::Index),
47
191187
            WasmType::Ratio => Some(Dim::Scalar),
48
100936
            WasmType::Commodity => Some(Dim::Money),
49
33715
            _ => None,
50
        }
51
7985129
    }
52

            
53
1150865
    pub(in crate::compiler::native) fn of(ty: WasmType, op: &str) -> Result<Dim> {
54
1150865
        Dim::of_type(ty).ok_or_else(|| non_numeric_operand(op, ty))
55
1150865
    }
56

            
57
    /// The dimension of a resolved operand: a constant's own kind, or a runtime
58
    /// value's type; `None` for anything else.
59
13254861
    pub(in crate::compiler::native) fn of_value(value: &Expr) -> Option<Dim> {
60
13254861
        match value {
61
6377898
            Expr::Number(n) => Some(Dim::of_number(*n)),
62
6876963
            _ => value.wasm_type().and_then(Dim::of_type),
63
        }
64
13254861
    }
65
}
66

            
67
/// The error for a runtime operand of type `ty` that the numeric `op` refuses.
68
7594
pub(in crate::compiler::native) fn non_numeric_operand(op: &str, ty: WasmType) -> Error {
69
7594
    match ty {
70
4457
        WasmType::AnyRef => Error::Compile(format!(
71
4457
            "{op} expects numeric arguments, got an any value; \
72
4457
             narrow it with THE (index, scalar or money)"
73
4457
        )),
74
3137
        other => Error::Compile(format!(
75
3137
            "{op} expects numeric arguments, got {} value",
76
3137
            with_article(other)
77
3137
        )),
78
    }
79
7594
}
80

            
81
/// A compiled operand: a numeric constant (not yet emitted) with the one
82
/// dimension its kind fixes, a runtime value already evaluated into `local`
83
/// with its wasm type, or an operand that always raises and has no dimension.
84
pub(in crate::compiler) enum Slot {
85
    Literal(Number),
86
    Runtime(u32, WasmType),
87
    Raises,
88
}
89

            
90
impl Slot {
91
    /// The fixed dimension of the slot, or `None` for an operand that raises.
92
1319703
    fn dim(&self, op: &str) -> Result<Option<Dim>> {
93
1319703
        match self {
94
722367
            Slot::Literal(n) => Ok(Some(Dim::of_number(*n))),
95
590325
            Slot::Runtime(_, ty) => Dim::of(*ty, op).map(Some),
96
7011
            Slot::Raises => Ok(None),
97
        }
98
1319703
    }
99
}
100

            
101
/// Emit a single slot at `dim`; a slot of another dimension is a mix.
102
1229512
fn emit_slot(
103
1229512
    ctx: &CompileContext,
104
1229512
    emit: &mut FunctionEmitter,
105
1229512
    slot: &Slot,
106
1229512
    dim: Dim,
107
1229512
    op: &str,
108
1229512
) -> Result<()> {
109
1229512
    match slot {
110
6591
        Slot::Raises => emit.unreachable(),
111
        Slot::Literal(n) => {
112
662381
            require_dim(Dim::of_number(*n), dim, op)?;
113
662381
            push_number(ctx, emit, *n)?;
114
        }
115
        Slot::Runtime(local, ty) => {
116
560540
            require_dim(Dim::of(*ty, op)?, dim, op)?;
117
560540
            emit.local_get(*local);
118
        }
119
    }
120
1229512
    Ok(())
121
1229512
}
122

            
123
1222921
fn require_dim(found: Dim, dim: Dim, op: &str) -> Result<()> {
124
1222921
    match found == dim {
125
1222921
        true => Ok(()),
126
        false => Err(mix_error(op, found, dim)),
127
    }
128
1222921
}
129

            
130
/// The one dimension every operand shares, `None` when no operand has one;
131
/// a differing dimension is a mix.
132
36148478
pub(in crate::compiler::native) fn shared_dim(
133
36148478
    dims: impl IntoIterator<Item = Dim>,
134
36148478
    op: &str,
135
36148478
) -> Result<Option<Dim>> {
136
36148478
    let mut dims = dims.into_iter();
137
36148478
    let Some(first) = dims.next() else {
138
840
        return Ok(None);
139
    };
140
36152606
    match dims.find(|d| *d != first) {
141
68693
        Some(other) => Err(mix_error(op, first, other)),
142
36078945
        None => Ok(Some(first)),
143
    }
144
36148478
}
145

            
146
/// Two operands whose dimensions are both known must share one.
147
43980
pub(in crate::compiler::native) fn refuse_dim_mix(a: &Expr, b: &Expr, op: &str) -> Result<()> {
148
43980
    if let (Some(left), Some(right)) = (Dim::of_value(a), Dim::of_value(b)) {
149
16602
        shared_dim([left, right], op)?;
150
27378
    }
151
43874
    Ok(())
152
43980
}
153

            
154
/// `decide` over the operands' dimensions. Only when that fails are the
155
/// operands that always raise taken out as dimension-less, since the walk that
156
/// finds them is costly.
157
3954755
pub(in crate::compiler::native) fn decided_over_dims<T>(
158
3954755
    symbols: &SymbolTable,
159
3954755
    (args, resolved): (&[Expr], &[Expr]),
160
3954755
    dim_of: impl Fn(&Expr) -> Result<Dim>,
161
3954755
    decide: impl Fn(&[Option<Dim>]) -> Result<T>,
162
3954755
) -> Result<T> {
163
3954755
    let typed = resolved.iter().map(&dim_of).collect::<Result<Vec<_>>>();
164
3954755
    if let Ok(dims) = typed {
165
3946750
        let dims: Vec<_> = dims.into_iter().map(Some).collect();
166
3946750
        if let Ok(decided) = decide(&dims) {
167
3905279
            return Ok(decided);
168
41471
        }
169
8005
    }
170
49476
    let mut dims = Vec::with_capacity(args.len());
171
49476
    for (arg, value) in args.iter().zip(resolved) {
172
96854
        dims.push(match value {
173
24504
            Expr::Number(_) => Some(dim_of(value)?),
174
72350
            _ if always_raises(symbols, arg)? => None,
175
71726
            _ => Some(dim_of(value)?),
176
        });
177
    }
178
42095
    decide(&dims)
179
3954755
}
180

            
181
/// The dimension of an additive op (`+`/`-`/`MOD`): the one its operands
182
/// share; operands that raise decide nothing, and all-raising is an index.
183
555763
fn additive_dim(slots: &[Slot], op: &str) -> Result<Dim> {
184
555763
    let dims = slots
185
555763
        .iter()
186
1110461
        .map(|s| s.dim(op))
187
6507
        .collect::<Result<Vec<_>>>()?;
188
549256
    Ok(shared_dim(dims.into_iter().flatten(), op)?.unwrap_or(Dim::Index))
189
555763
}
190

            
191
/// The arity each operator refuses before anything is folded or emitted.
192
712504
pub(in crate::compiler) fn check_arity(op: ArithOp, count: usize) -> Result<()> {
193
712504
    match op {
194
23823
        ArithOp::Sub | ArithOp::Div if count == 0 => Err(Error::Compile(format!(
195
420
            "{} requires at least 1 argument",
196
420
            op_name(op)
197
420
        ))),
198
5059
        ArithOp::Mod if count != 2 => Err(Error::Arity {
199
420
            name: "MOD".to_string(),
200
420
            expected: 2,
201
420
            actual: count,
202
420
        }),
203
711664
        _ => Ok(()),
204
    }
205
712504
}
206

            
207
18805030
pub(in crate::compiler::native) fn op_name(op: ArithOp) -> &'static str {
208
18805030
    match op {
209
18223278
        ArithOp::Add => "+",
210
271193
        ArithOp::Sub => "-",
211
187706
        ArithOp::Mul => "*",
212
115896
        ArithOp::Div => "/",
213
6957
        ArithOp::Mod => "MOD",
214
    }
215
18805030
}
216

            
217
/// Emits a non-constant arithmetic call over its compiled operands: the
218
/// operation's dimension picks raw `i32` ops, `ratio_*` or `commodity_*`.
219
/// The one implementation of these rules.
220
625791
pub(in crate::compiler) fn emit_slots(
221
625791
    ctx: &mut CompileContext,
222
625791
    emit: &mut FunctionEmitter,
223
625791
    op: ArithOp,
224
625791
    slots: &[Slot],
225
625791
) -> Result<WasmType> {
226
625791
    let name = op_name(op);
227
625791
    let Some((first, rest)) = slots.split_first() else {
228
        return Err(Error::Compile(format!("{name} has no operands to emit")));
229
    };
230
625791
    match op {
231
        ArithOp::Add | ArithOp::Sub => {
232
552606
            let dim = additive_dim(slots, name)?;
233
542210
            if op == ArithOp::Sub && rest.is_empty() {
234
453
                return emit_unary_neg(ctx, emit, first, dim);
235
541757
            }
236
541757
            let binop = if op == ArithOp::Sub {
237
19163
                BinOp::Sub
238
            } else {
239
522594
                BinOp::Add
240
            };
241
541757
            emit_slot(ctx, emit, first, dim, name)?;
242
541757
            for slot in rest {
243
544516
                emit_slot(ctx, emit, slot, dim, name)?;
244
544516
                emit_combine(ctx, emit, dim, binop);
245
            }
246
541757
            Ok(dim.wasm_type())
247
        }
248
        ArithOp::Mul | ArithOp::Div => {
249
70028
            let seed = scaling_seed(&slot_dims(slots, name)?);
250
70028
            if op == ArithOp::Div && rest.is_empty() {
251
423
                return emit_reciprocal(ctx, emit, first, seed);
252
69605
            }
253
69605
            emit_slot(ctx, emit, first, seed, name)?;
254
69605
            let mut acc = seed;
255
69605
            for slot in rest {
256
69607
                acc = combine_scaling(ctx, emit, (op, acc), slot)?;
257
            }
258
68945
            Ok(acc.wasm_type())
259
        }
260
3157
        ArithOp::Mod => match additive_dim(slots, name)? {
261
            Dim::Index => {
262
1907
                for slot in slots {
263
3814
                    emit_slot(ctx, emit, slot, Dim::Index, name)?;
264
                }
265
1907
                emit.call(ctx.ids.index_rem);
266
1907
                Ok(WasmType::I32)
267
            }
268
208
            Dim::Scalar | Dim::Money => Err(Error::Compile(
269
208
                "MOD with runtime non-integer arguments is not yet supported".to_string(),
270
208
            )),
271
        },
272
    }
273
625791
}
274

            
275
#[derive(Clone, Copy)]
276
enum BinOp {
277
    Add,
278
    Sub,
279
}
280

            
281
544516
fn emit_combine(ctx: &CompileContext, emit: &mut FunctionEmitter, dim: Dim, op: BinOp) {
282
544516
    match (dim, op) {
283
507582
        (Dim::Index, BinOp::Add) => emit.call(ctx.ids.index_add),
284
15587
        (Dim::Index, BinOp::Sub) => emit.call(ctx.ids.index_sub),
285
14229
        (Dim::Scalar, BinOp::Add) => emit.call(ctx.ids.ratio_add),
286
3986
        (Dim::Scalar, BinOp::Sub) => emit.call(ctx.ids.ratio_sub),
287
3120
        (Dim::Money, BinOp::Add) => emit.call(ctx.ids.commodity_add),
288
12
        (Dim::Money, BinOp::Sub) => emit.call(ctx.ids.commodity_sub),
289
    }
290
544516
}
291

            
292
453
fn emit_unary_neg(
293
453
    ctx: &mut CompileContext,
294
453
    emit: &mut FunctionEmitter,
295
453
    slot: &Slot,
296
453
    dim: Dim,
297
453
) -> Result<WasmType> {
298
453
    match dim {
299
        Dim::Index => {
300
216
            emit.i32_const(0);
301
216
            emit_slot(ctx, emit, slot, Dim::Index, "-")?;
302
216
            emit.call(ctx.ids.index_sub);
303
216
            Ok(WasmType::I32)
304
        }
305
        Dim::Scalar => {
306
222
            let r_local = ctx.alloc_local(WasmType::Ratio)?;
307
222
            emit_slot(ctx, emit, slot, Dim::Scalar, "-")?;
308
222
            emit.local_set(r_local);
309
222
            push_ratio(ctx, emit, 0, 1);
310
222
            emit.local_get(r_local);
311
222
            emit.call(ctx.ids.ratio_sub);
312
222
            Ok(WasmType::Ratio)
313
        }
314
        Dim::Money => {
315
15
            emit_slot(ctx, emit, slot, Dim::Money, "-")?;
316
15
            emit.call(ctx.ids.commodity_neg);
317
15
            Ok(WasmType::Commodity)
318
        }
319
    }
320
453
}
321

            
322
/// The dimension of `acc op operand` for `*` / `/`, `None` being an operand
323
/// that raises: index with index, scalar with scalar, and money scaled by a
324
/// scalar or combined with money; anything else is a mix.
325
155970
fn scaled_dim(op: ArithOp, acc: Dim, operand: Option<Dim>) -> Result<Dim> {
326
155970
    match (op, acc, operand) {
327
208
        (_, acc, None) => Ok(acc),
328
96128
        (_, Dim::Index, Some(Dim::Index)) => Ok(Dim::Index),
329
5
        (ArithOp::Div, Dim::Scalar, Some(Dim::Money)) => Err(Error::Dimension(
330
5
            "dividing a pure rational by a commodity-bearing value has no \
331
5
             dimensional meaning; reverse operands or convert-commodity first"
332
5
                .to_string(),
333
5
        )),
334
648
        (_, Dim::Scalar, Some(Dim::Money)) => Ok(Dim::Money),
335
18496
        (_, Dim::Scalar, Some(Dim::Scalar)) => Ok(Dim::Scalar),
336
12038
        (_, Dim::Money, Some(Dim::Money | Dim::Scalar)) => Ok(Dim::Money),
337
28447
        (_, acc, Some(found)) => Err(mix_error(op_name(op), acc, found)),
338
    }
339
155970
}
340

            
341
/// The dimension of `*` / `/` over `dims`: the first operand's own (else the
342
/// first that does not raise) scaled by each following operand.
343
86365
pub(in crate::compiler::native) fn scaling_dim(op: ArithOp, dims: &[Option<Dim>]) -> Result<Dim> {
344
86365
    let seed = scaling_seed(dims);
345
86365
    if op == ArithOp::Div && dims.len() == 1 && seed == Dim::Money {
346
2
        return Err(reciprocal_of_money());
347
86363
    }
348
86363
    dims.iter()
349
86363
        .skip(1)
350
86363
        .try_fold(seed, |acc, dim| scaled_dim(op, acc, *dim))
351
86365
}
352

            
353
156393
fn scaling_seed(dims: &[Option<Dim>]) -> Dim {
354
156393
    dims.iter().flatten().next().copied().unwrap_or(Dim::Index)
355
156393
}
356

            
357
70028
fn slot_dims(slots: &[Slot], op: &str) -> Result<Vec<Option<Dim>>> {
358
139635
    slots.iter().map(|slot| slot.dim(op)).collect()
359
70028
}
360

            
361
69607
fn combine_scaling(
362
69607
    ctx: &mut CompileContext,
363
69607
    emit: &mut FunctionEmitter,
364
69607
    (op, acc): (ArithOp, Dim),
365
69607
    slot: &Slot,
366
69607
) -> Result<Dim> {
367
69607
    let name = op_name(op);
368
69607
    let found = slot.dim(name)?;
369
69607
    let result = scaled_dim(op, acc, found)?;
370
68947
    if let (Dim::Scalar, Some(Dim::Money)) = (acc, found) {
371
        // scalar × money → money: stash the scalar, push the money, restore.
372
        let scalar_local = ctx.alloc_local(WasmType::Ratio)?;
373
        emit.local_set(scalar_local);
374
        emit_slot(ctx, emit, slot, Dim::Money, name)?;
375
        emit.local_get(scalar_local);
376
        emit.call(ctx.ids.commodity_mul_by_ratio);
377
        return Ok(result);
378
68947
    }
379
68947
    let operand = match (acc, found) {
380
3973
        (Dim::Money, Some(Dim::Money)) => Dim::Money,
381
229
        (Dim::Money, _) => Dim::Scalar,
382
64745
        _ => acc,
383
    };
384
68947
    emit_slot(ctx, emit, slot, operand, name)?;
385
68947
    emit.call(scaling_helper(ctx, op, (acc, found)));
386
68947
    Ok(result)
387
69607
}
388

            
389
/// The runtime helper for `acc op operand`; money × money and money ÷ money
390
/// combine the unit terms (ADR-0028 E2), money with a scalar scales.
391
68947
fn scaling_helper(ctx: &CompileContext, op: ArithOp, (acc, found): (Dim, Option<Dim>)) -> u32 {
392
68947
    let ids = &ctx.ids;
393
68947
    let mul = op == ArithOp::Mul;
394
68947
    match (acc, found) {
395
55847
        (Dim::Index, _) if mul => ids.index_mul,
396
17952
        (Dim::Index, _) => ids.index_div,
397
8898
        (Dim::Scalar, _) if mul => ids.ratio_mul,
398
1305
        (Dim::Scalar, _) => ids.ratio_div,
399
3973
        (Dim::Money, Some(Dim::Money)) if mul => ids.commodity_mul,
400
832
        (Dim::Money, Some(Dim::Money)) => ids.commodity_div,
401
229
        (Dim::Money, _) if mul => ids.commodity_mul_by_ratio,
402
6
        (Dim::Money, _) => ids.commodity_div_by_ratio,
403
    }
404
68947
}
405

            
406
5
fn reciprocal_of_money() -> Error {
407
5
    Error::Dimension(
408
5
        "reciprocal of a commodity-bearing value has no dimensional meaning; \
409
5
         divide a commodity by a Ratio scalar instead"
410
5
            .to_string(),
411
5
    )
412
5
}
413

            
414
423
fn emit_reciprocal(
415
423
    ctx: &mut CompileContext,
416
423
    emit: &mut FunctionEmitter,
417
423
    slot: &Slot,
418
423
    dim: Dim,
419
423
) -> Result<WasmType> {
420
423
    match dim {
421
3
        Dim::Money => Err(reciprocal_of_money()),
422
        Dim::Index => {
423
418
            emit.i32_const(1);
424
418
            emit_slot(ctx, emit, slot, Dim::Index, "/")?;
425
418
            emit.call(ctx.ids.index_div);
426
418
            Ok(WasmType::I32)
427
        }
428
        Dim::Scalar => {
429
2
            let r_local = ctx.alloc_local(WasmType::Ratio)?;
430
2
            emit_slot(ctx, emit, slot, Dim::Scalar, "/")?;
431
2
            emit.local_set(r_local);
432
2
            push_ratio(ctx, emit, 1, 1);
433
2
            emit.local_get(r_local);
434
2
            emit.call(ctx.ids.ratio_div);
435
2
            Ok(WasmType::Ratio)
436
        }
437
    }
438
423
}
439

            
440
/// The one refusal for two dimensions in a single operation; the kinds read
441
/// in lattice order (index, scalar, money) whichever operand came first.
442
97140
pub(in crate::compiler::native) fn mix_error(op: &str, left: Dim, right: Dim) -> Error {
443
97140
    let (low, high) = (left.min(right), left.max(right));
444
97140
    Error::Dimension(format!(
445
97140
        "{op} cannot mix {} with {}; bridge explicitly with `(index->scalar ...)`, \
446
97140
         `(scalar->index ...)`, or `(convert-commodity ...)`",
447
97140
        low.describe(),
448
97140
        high.describe()
449
97140
    ))
450
97140
}