1
//! Operands compiled to one numeric dimension (ADR-0028): a literal coerces
2
//! across the Index/Scalar boundary, a runtime value must already have it.
3

            
4
use crate::ast::{Expr, Number, WasmType};
5
use crate::compiler::context::CompileContext;
6
use crate::compiler::emit::FunctionEmitter;
7
use crate::error::{Error, Result};
8
use crate::runtime::SymbolTable;
9

            
10
use super::effect::compile_for_effect;
11
use super::fold::{probe_value, raises_division};
12
use super::stack::{compile_for_stack, push_number_as};
13
use crate::compiler::special::form_diverges_scratch;
14

            
15
const PROGN: &str = "progn";
16

            
17
/// Emits `expr` when it always raises (a constant division by zero, an
18
/// `ERROR`, a `PROGN` with either in its body) and answers `true`; its value
19
/// is never produced, so the caller gives it no dimension (ISS-087 keeps
20
/// program conditions at runtime).
21
3454379
pub(in crate::compiler) fn compile_raising(
22
3454379
    ctx: &mut CompileContext,
23
3454379
    emit: &mut FunctionEmitter,
24
3454379
    symbols: &mut SymbolTable,
25
3454379
    expr: &Expr,
26
3454379
) -> Result<bool> {
27
3454379
    if !always_raises(symbols, expr)? {
28
3441539
        return Ok(false);
29
12629
    }
30
12629
    compile_for_stack(ctx, emit, symbols, expr)?;
31
12629
    emit.drop_value();
32
12629
    Ok(true)
33
3454379
}
34

            
35
/// [`compile_raising`] that also seals the dead code after the raise, so the
36
/// caller compiles nothing further.
37
1126639
pub(in crate::compiler) fn compile_raising_to_end(
38
1126639
    ctx: &mut CompileContext,
39
1126639
    emit: &mut FunctionEmitter,
40
1126639
    symbols: &mut SymbolTable,
41
1126639
    expr: &Expr,
42
1126639
) -> Result<bool> {
43
1126639
    compile_diverging_to_end(ctx, emit, symbols, expr, always_raises)
44
1126639
}
45

            
46
/// Emits `expr` and seals the dead code after it when `diverges` holds.
47
2055099
pub(in crate::compiler) fn compile_diverging_to_end(
48
2055099
    ctx: &mut CompileContext,
49
2055099
    emit: &mut FunctionEmitter,
50
2055099
    symbols: &mut SymbolTable,
51
2055099
    expr: &Expr,
52
2055099
    diverges: fn(&SymbolTable, &Expr) -> Result<bool>,
53
2055099
) -> Result<bool> {
54
2055099
    if !diverges(symbols, expr)? {
55
2051030
        return Ok(false);
56
4069
    }
57
4069
    compile_for_stack(ctx, emit, symbols, expr)?;
58
4069
    emit.drop_value();
59
4069
    emit.unreachable();
60
4069
    Ok(true)
61
2055099
}
62

            
63
/// Compiles `expr` into a fresh local and answers the local with its type;
64
/// `None` when it never returns. In dead code the operand is compiled once on
65
/// a live scratch, since the dead emitter yields a placeholder: the scratch
66
/// reports what it pushes when reached and whether it returns.
67
596235
pub(in crate::compiler) fn compile_to_local(
68
596235
    ctx: &mut CompileContext,
69
596235
    emit: &mut FunctionEmitter,
70
596235
    symbols: &mut SymbolTable,
71
596235
    expr: &Expr,
72
596235
) -> Result<Option<(u32, WasmType)>> {
73
596235
    let (ty, returns) = match emit.is_reachable() {
74
        true => {
75
595474
            let ty = compile_for_stack(ctx, emit, symbols, expr)?;
76
593814
            (ty, emit.is_reachable())
77
        }
78
761
        false => emit.on_live_scratch(|scratch| compile_for_stack(ctx, scratch, symbols, expr))?,
79
    };
80
594570
    if !returns {
81
130
        return Ok(None);
82
594440
    }
83
594440
    let local = ctx.alloc_local(ty)?;
84
594440
    emit.local_set(local);
85
594440
    Ok(Some((local, ty)))
86
596235
}
87

            
88
/// [`compile_raising`] for a boundary that needs an integer placeholder for the
89
/// never-observed value, which adopts the dimension the boundary demands.
90
2846155
pub(in crate::compiler) fn compile_raising_constant(
91
2846155
    ctx: &mut CompileContext,
92
2846155
    emit: &mut FunctionEmitter,
93
2846155
    symbols: &mut SymbolTable,
94
2846155
    expr: &Expr,
95
2846155
) -> Result<Option<Number>> {
96
2846155
    Ok(compile_raising(ctx, emit, symbols, expr)?.then_some(Number::Index(1)))
97
2846155
}
98

            
99
/// True when evaluating `expr` always raises, so its value is never produced.
100
9982235
pub(in crate::compiler) fn always_raises(symbols: &SymbolTable, expr: &Expr) -> Result<bool> {
101
9982235
    Ok(progn_divides(symbols, expr) || form_diverges_scratch(symbols, expr)?)
102
9982235
}
103

            
104
/// A constant division by zero in `expr` or, recursively, in a `PROGN` body;
105
/// the other raising forms are `form_diverges`' walk.
106
10041131
fn progn_divides(symbols: &SymbolTable, expr: &Expr) -> bool {
107
10041131
    if raises_division(symbols, expr) {
108
10879
        return true;
109
10030252
    }
110
10030252
    match expr {
111
3363125
        Expr::List(items) => match items.as_slice() {
112
3362899
            [Expr::Symbol(head), body @ ..] if head.eq_ignore_ascii_case(PROGN) => {
113
58896
                body.iter().any(|form| progn_divides(symbols, form))
114
            }
115
3333890
            _ => false,
116
        },
117
6667127
        _ => false,
118
    }
119
10041131
}
120

            
121
/// Compiles `expr` as a Scalar operand.
122
///
123
/// ADR-0028: a numeric literal is a dimension-flexible token — coerce it to
124
/// Scalar (the sanctioned Index↔Scalar crossing). A RUNTIME index never
125
/// coerces; it must bridge explicitly via `(index->scalar …)`. A non-literal
126
/// operand that *resolves* to a number still emits its effects on the live
127
/// table first (the probe runs on a clone, so it applies none).
128
144340
pub(in crate::compiler) fn compile_ratio_operand(
129
144340
    ctx: &mut CompileContext,
130
144340
    emit: &mut FunctionEmitter,
131
144340
    symbols: &mut SymbolTable,
132
144340
    expr: &Expr,
133
144340
) -> Result<()> {
134
144340
    if let Expr::Number(n) = probe_value(&mut symbols.clone(), expr)? {
135
100970
        if !matches!(expr, Expr::Number(_)) {
136
4245
            compile_for_effect(ctx, emit, symbols, expr)?;
137
96725
        }
138
100970
        return push_number_as(ctx, emit, n, WasmType::Ratio);
139
43370
    }
140
43370
    if let Some(n) = compile_raising_constant(ctx, emit, symbols, expr)? {
141
208
        return push_number_as(ctx, emit, n, WasmType::Ratio);
142
43162
    }
143
43162
    let ty = compile_for_stack(ctx, emit, symbols, expr)?;
144
42310
    match ty {
145
41673
        WasmType::Ratio => Ok(()),
146
1
        WasmType::Commodity => Err(Error::Dimension(
147
1
            "commodity-bearing values cannot mix with pure-rational arithmetic; \
148
1
             use `(convert-commodity ...)` to bridge"
149
1
                .to_string(),
150
1
        )),
151
2
        WasmType::I32 => Err(Error::Dimension(
152
2
            "a runtime index (count) cannot be used as a scalar; \
153
2
             bridge explicitly with `(index->scalar ...)`"
154
2
                .to_string(),
155
2
        )),
156
        WasmType::Bool
157
        | WasmType::PairRef(_)
158
        | WasmType::StringRef
159
        | WasmType::SymbolRef
160
        | WasmType::EntityRef(_)
161
        | WasmType::StructRef(_)
162
        | WasmType::Closure(_)
163
634
        | WasmType::AnyRef => Err(Error::Compile(format!(
164
634
            "arithmetic requires ratio values, got {ty}"
165
634
        ))),
166
    }
167
637
    .or_else(|err| emit.reject_if_live(err))
168
144340
}
169

            
170
/// Compiles `expr` as a raw i32 Index value: a runtime `I32` (a count/length/
171
/// index) or an integer literal. A fractional literal is a Scalar, and a
172
/// runtime Ratio/Commodity/ref is not an Index — all rejected (ADR-0028:
173
/// Index combines only with Index + integer literals). See
174
/// [`compile_ratio_operand`].
175
9853760
pub(in crate::compiler) fn compile_index_operand(
176
9853760
    ctx: &mut CompileContext,
177
9853760
    emit: &mut FunctionEmitter,
178
9853760
    symbols: &mut SymbolTable,
179
9853760
    expr: &Expr,
180
9853760
) -> Result<()> {
181
9853760
    if let Expr::Number(n) = probe_value(&mut symbols.clone(), expr)? {
182
7050975
        if !matches!(expr, Expr::Number(_)) {
183
494765
            compile_for_effect(ctx, emit, symbols, expr)?;
184
6556210
        }
185
7050559
        return push_number_as(ctx, emit, n, WasmType::I32);
186
2802785
    }
187
2802785
    if let Some(n) = compile_raising_constant(ctx, emit, symbols, expr)? {
188
643
        return push_number_as(ctx, emit, n, WasmType::I32);
189
2802142
    }
190
2802142
    let ty = compile_for_stack(ctx, emit, symbols, expr)?;
191
2800964
    match ty {
192
2800117
        WasmType::I32 => Ok(()),
193
421
        WasmType::Ratio | WasmType::Commodity => Err(Error::Dimension(
194
421
            "a scalar/money value cannot be used as an index; \
195
421
             bridge explicitly with `(scalar->index ...)`"
196
421
                .to_string(),
197
421
        )),
198
        WasmType::Bool
199
        | WasmType::PairRef(_)
200
        | WasmType::StringRef
201
        | WasmType::SymbolRef
202
        | WasmType::EntityRef(_)
203
        | WasmType::StructRef(_)
204
        | WasmType::Closure(_)
205
426
        | WasmType::AnyRef => Err(Error::Compile(format!(
206
426
            "index arithmetic requires an integer count, got {ty}"
207
426
        ))),
208
    }
209
847
    .or_else(|err| emit.reject_if_live(err))
210
9853760
}