1
//! Numeric-strata bridge natives (ADR-0028): the only sanctioned crossings
2
//! between Index and Scalar for RUNTIME values.
3
//!
4
//! - `(index->scalar n)` widens an Index (count) to a Scalar — the i32 is
5
//!   sign-extended (negatives are real) and lifted to `n/1`.
6
//! - `(scalar->index r)` narrows a Scalar to an Index, truncating toward zero
7
//!   (`7/2 → 3`, `-7/2 → -3`), matching `i32.div_s`.
8
//!
9
//! A bare integer literal still coerces to Scalar implicitly where an operator
10
//! demands it; these natives exist for runtime values, which never coerce.
11

            
12
use super::NativeSpec;
13
use crate::ast::{Expr, Number, WasmType};
14
use crate::compiler::context::CompileContext;
15
use crate::compiler::emit::FunctionEmitter;
16
use crate::compiler::expr::{
17
    compile_for_effect, compile_index_operand, compile_ratio_operand, eval_value, format_expr,
18
    probe_value,
19
};
20
use crate::error::{Error, Result};
21
use crate::runtime::SymbolTable;
22

            
23
pub(in crate::compiler::native) const NATIVES: &[NativeSpec] = &[
24
    NativeSpec {
25
        name: "INDEX->SCALAR",
26
        eval: index_to_scalar_eval,
27
        stack: Some(compile_index_to_scalar),
28
        effect: None,
29
    },
30
    NativeSpec {
31
        name: "SCALAR->INDEX",
32
        eval: scalar_to_index_eval,
33
        stack: Some(compile_scalar_to_index),
34
        effect: None,
35
    },
36
];
37

            
38
41657
pub(super) fn one_arg<'a>(args: &'a [Expr], name: &str) -> Result<&'a Expr> {
39
41657
    match args {
40
41648
        [arg] => Ok(arg),
41
9
        _ => Err(Error::Arity {
42
9
            name: name.to_string(),
43
9
            expected: 1,
44
9
            actual: args.len(),
45
9
        }),
46
    }
47
41657
}
48

            
49
/// `index->scalar` always surfaces a runtime Scalar: a Scalar that equals an
50
/// integer can't be represented as a const `Number` (an integer `Number`
51
/// classifies as Index), so even a constant index is lifted at runtime. A
52
/// constant index must fit `i32` — that is what makes it an Index, and codegen
53
/// (`compile_for_stack_as(.., I32)`) range-checks it identically, so eval
54
/// rejects an out-of-range constant here rather than accept what codegen
55
/// refuses.
56
27317
fn index_to_scalar_eval(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
57
27317
    let resolved = eval_value(symbols, one_arg(args, "INDEX->SCALAR")?)?;
58
27296
    match &resolved {
59
        Expr::Number(Number::Index(i)) => {
60
655
            i32::try_from(*i)
61
                .map_err(|_| Error::Compile("index->scalar: index out of i32 range".to_string()))?;
62
655
            Ok(Expr::WasmRuntime(WasmType::Ratio))
63
        }
64
        Expr::Number(Number::Scalar(_)) => Err(Error::Dimension(
65
            "index->scalar expects an integer index, not a fractional value".to_string(),
66
        )),
67
26641
        _ if resolved.wasm_type() == Some(WasmType::I32) => Ok(Expr::WasmRuntime(WasmType::Ratio)),
68
401
        other => Err(Error::Dimension(format!(
69
401
            "index->scalar expects an index (count), got {}",
70
401
            format_expr(other)
71
401
        ))),
72
    }
73
27317
}
74

            
75
/// `scalar->index` truncates toward zero. A constant scalar folds to an integer
76
/// `Number` (which classifies as Index); a runtime Scalar surfaces a runtime
77
/// Index. A constant whose truncated value overflows `i32` is a compile error
78
/// (eval and codegen agree); a *runtime* one raises `INDEX-OVERFLOW` (ISS-086).
79
236
fn scalar_to_index_eval(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
80
236
    let resolved = eval_value(symbols, one_arg(args, "SCALAR->INDEX")?)?;
81
236
    match &resolved {
82
        Expr::Number(n) => {
83
            let truncated = n.value().trunc().to_integer();
84
            i32::try_from(truncated).map_err(|_| {
85
                Error::Compile("scalar->index: result out of i32 range".to_string())
86
            })?;
87
            Ok(Expr::Number(Number::Index(truncated)))
88
        }
89
236
        _ if resolved.wasm_type() == Some(WasmType::Ratio) => Ok(Expr::WasmRuntime(WasmType::I32)),
90
3
        other => Err(Error::Dimension(format!(
91
3
            "scalar->index expects a scalar (rational), got {}",
92
3
            format_expr(other)
93
3
        ))),
94
    }
95
236
}
96

            
97
11395
fn compile_index_to_scalar(
98
11395
    ctx: &mut CompileContext,
99
11395
    emit: &mut FunctionEmitter,
100
11395
    symbols: &mut SymbolTable,
101
11395
    args: &[Expr],
102
11395
) -> Result<WasmType> {
103
11395
    let arg = one_arg(args, "INDEX->SCALAR")?;
104
11395
    compile_index_operand(ctx, emit, symbols, arg)?;
105
    // SIGNED extend: a count can be negative (e.g. an index delta), so a -1 must
106
    // become -1/1, not 4294967295/1 (the old unsigned-bridge bug).
107
10344
    emit.i64_extend_i32_s();
108
10344
    emit.call(ctx.ids.ratio_from_i64);
109
10344
    Ok(WasmType::Ratio)
110
11395
}
111

            
112
2096
fn compile_scalar_to_index(
113
2096
    ctx: &mut CompileContext,
114
2096
    emit: &mut FunctionEmitter,
115
2096
    symbols: &mut SymbolTable,
116
2096
    args: &[Expr],
117
2096
) -> Result<WasmType> {
118
2096
    let arg = one_arg(args, "SCALAR->INDEX")?;
119
    // A constant operand folds to a range-checked `i32.const` (probed on a
120
    // clone so the live table is untouched). This keeps codegen in lockstep
121
    // with `scalar_to_index_eval`: an out-of-range constant errors on both
122
    // surfaces rather than silently wrapping via the runtime `i32.wrap_i64`,
123
    // which only narrows genuine runtime scalars.
124
2096
    if let Expr::Number(n) = probe_value(&mut symbols.clone(), arg)? {
125
        // A non-literal form that merely *resolves* to a constant (e.g.
126
        // `(progn (debug …) 5)`) still has side effects to emit before the
127
        // folded value — same contract as `compile_ratio_operand` / `compile_index_operand`.
128
838
        if !matches!(arg, Expr::Number(_)) {
129
419
            compile_for_effect(ctx, emit, symbols, arg)?;
130
419
        }
131
838
        let truncated = n.value().trunc().to_integer();
132
838
        let Ok(narrowed) = i32::try_from(truncated) else {
133
208
            return Err(Error::Compile(
134
208
                "scalar->index: result out of i32 range".to_string(),
135
208
            ));
136
        };
137
630
        emit.i32_const(narrowed);
138
630
        return Ok(WasmType::I32);
139
1258
    }
140
1258
    compile_ratio_operand(ctx, emit, symbols, arg)?;
141
633
    emit.call(ctx.ids.ratio_to_i64);
142
633
    emit.call(ctx.ids.index_narrow);
143
633
    Ok(WasmType::I32)
144
2096
}