1
//! `MAP` over a runtime `PairRef` list.
2

            
3
use crate::ast::{Expr, PairElement, WasmType};
4
use crate::compiler::context::CompileContext;
5
use crate::compiler::emit::FunctionEmitter;
6
use crate::compiler::expr::{
7
    as_literal_arg, call, classify_stack_type, compile_for_stack, emit_box_cell, eval_value,
8
};
9
use crate::error::{Error, Result};
10
use crate::runtime::SymbolTable;
11

            
12
use super::reverse::emit_reverse_loop;
13

            
14
/// MAP's output element for a runtime chain input: a let-bound closure's
15
/// recorded signature result (same rule `map_fn`'s eval mirror and
16
/// `compile_map_literal` use); otherwise (an inline lambda or bare
17
/// defun with no signature yet) probe one application against a
18
/// representative element of the input chain, mirroring FOLD's
19
/// `probe_body_type`. Falls back to the input element when the probe
20
/// itself can't classify (the per-row FUNCALL still runs the real check
21
/// below, so an actual mismatch still surfaces as a compile error there).
22
10246
pub(super) fn predict_map_result_element(
23
10246
    symbols: &SymbolTable,
24
10246
    fn_arg: &Expr,
25
10246
    elem: PairElement,
26
10246
) -> Result<PairElement> {
27
10246
    if let Some(sig) = eval_value(&mut symbols.clone(), fn_arg)
28
10246
        .ok()
29
10246
        .and_then(|v| super::sourceless_closure_sig(symbols, &v))
30
3
        && let Some(result_elem) = symbols
31
3
            .closure_result(sig)
32
3
            .and_then(PairElement::from_wasm_type)
33
    {
34
3
        return Ok(result_elem);
35
10243
    }
36
10243
    let sample = as_literal_arg(&Expr::WasmRuntime(elem.as_wasm_type()));
37
10243
    let mut probe = symbols.clone();
38
10243
    let result = match call(&mut probe, &[fn_arg.clone(), sample]) {
39
6064
        Ok(result) => result,
40
1249
        Err(err @ Error::Dimension(_)) => return Err(err),
41
2930
        Err(_) => return Ok(elem),
42
    };
43
6064
    Ok(classify_stack_type(&result)
44
6064
        .and_then(PairElement::from_wasm_type)
45
6064
        .unwrap_or(elem))
46
10246
}
47

            
48
/// Walks the runtime `PairRef(elem)` input already on the stack. Builds the result reversed
49
/// (one prepend per car) by calling the function on each car, then
50
/// reverses once at the end so the output preserves input order.
51
6677
pub(super) fn compile_map_runtime_list(
52
6677
    ctx: &mut CompileContext,
53
6677
    emit: &mut FunctionEmitter,
54
6677
    symbols: &mut SymbolTable,
55
6677
    fn_arg: &Expr,
56
6677
    elem: PairElement,
57
6677
) -> Result<WasmType> {
58
    // MAP's OUTPUT element is the closure's RESULT type (it transforms each
59
    // element), NOT the input element — same rule `map_fn`'s eval mirror uses.
60
6677
    let result_elem = predict_map_result_element(symbols, fn_arg, elem)?;
61
6261
    let pair_idx = ctx.ids.ty_pair;
62
6261
    let pair_local = ctx.alloc_local(WasmType::PairRef(result_elem))?;
63
6261
    let acc_local = ctx.alloc_local(WasmType::PairRef(result_elem))?;
64
6261
    let car_local = ctx.alloc_local(elem.as_wasm_type())?;
65

            
66
6261
    emit.local_set(pair_local);
67

            
68
6261
    emit.ref_null(pair_idx);
69
6261
    emit.local_set(acc_local);
70

            
71
6261
    emit.block_start();
72
6261
    emit.loop_start();
73

            
74
6261
    emit.local_get(pair_local);
75
6261
    emit.ref_is_null();
76
6261
    emit.br_if(1);
77

            
78
6261
    emit.local_get(pair_local);
79
6261
    emit.struct_get(pair_idx, 0);
80
6261
    crate::compiler::native::list::emit_pair_car_downcast(ctx, emit, elem)?;
81
6053
    emit.local_set(car_local);
82

            
83
6053
    let mapped_ty = compile_map_call_with_local(ctx, emit, symbols, fn_arg, car_local, elem)?;
84
5221
    let actual_elem = PairElement::from_wasm_type(mapped_ty).ok_or_else(|| {
85
        Error::Compile(format!(
86
            "MAP: closure result type {mapped_ty} can't ride a typed pair; \
87
             flatten via let-bind first"
88
        ))
89
    })?;
90
5221
    if actual_elem != result_elem {
91
        return Err(Error::Compile(format!(
92
            "MAP: closure result element {actual_elem} doesn't match input element {result_elem}; \
93
             heterogeneous mapping isn't supported yet"
94
        )));
95
5221
    }
96
5221
    emit_box_cell(ctx, emit, actual_elem, result_elem);
97
5221
    emit.local_get(acc_local);
98
5221
    emit.call(ctx.ids.pair_new);
99
5221
    emit.local_set(acc_local);
100

            
101
5221
    emit.local_get(pair_local);
102
5221
    emit.struct_get(pair_idx, 1);
103
5221
    emit.local_set(pair_local);
104

            
105
5221
    emit.br(0);
106
5221
    emit.block_end()?;
107
5221
    emit.block_end()?;
108

            
109
    // The accumulator is in reverse order — walk it once more through
110
    // the standard reverse loop so the output preserves input order.
111
5221
    let acc_expr = Expr::WasmLocal(acc_local, WasmType::PairRef(result_elem));
112
5221
    emit_reverse_loop(ctx, emit, symbols, &acc_expr, result_elem)?;
113
5221
    Ok(WasmType::PairRef(result_elem))
114
6677
}
115

            
116
/// Emit a per-iteration call of `fn_arg` against the value held in
117
/// `car_local`. A quoted function name (`'g2`) designates that function, so it
118
/// is called by name; any other callable rides FUNCALL.
119
6053
fn compile_map_call_with_local(
120
6053
    ctx: &mut CompileContext,
121
6053
    emit: &mut FunctionEmitter,
122
6053
    symbols: &mut SymbolTable,
123
6053
    fn_arg: &Expr,
124
6053
    car_local: u32,
125
6053
    elem: PairElement,
126
6053
) -> Result<WasmType> {
127
6053
    let car_expr = Expr::WasmLocal(car_local, elem.as_wasm_type());
128
6053
    let call = match fn_arg {
129
        Expr::Quote(designator) | Expr::Datum(designator)
130
416
            if matches!(designator.as_ref(), Expr::Symbol(_)) =>
131
        {
132
416
            vec![designator.as_ref().clone(), car_expr]
133
        }
134
5637
        _ => vec![Expr::symbol("FUNCALL"), fn_arg.clone(), car_expr],
135
    };
136
6053
    compile_for_stack(ctx, emit, symbols, &Expr::List(call))
137
6053
}