1
//! `MAP` eval + compile.
2
//!
3
//! Three paths:
4
//! - **Constant-fold**: when the function and every list arg resolves
5
//!   at compile time, `map_fn` walks element-by-element via the eval
6
//!   `call` pipeline and returns the resulting list literal.
7
//! - **Runtime closure, literal list**: emit a per-element FUNCALL,
8
//!   stash each result in a fresh local, then walk the locals in
9
//!   reverse and prepend each car onto the accumulator via `pair_new`.
10
//! - **Runtime closure or runtime `PairRef` list**: walk the input
11
//!   chain at runtime, calling the function on each car, prepend onto
12
//!   a reversed accumulator, and run `emit_reverse_loop` once at the
13
//!   end so the output preserves input order.
14

            
15
use crate::ast::{Expr, PairElement, WasmType};
16
use crate::compiler::context::CompileContext;
17
use crate::compiler::emit::FunctionEmitter;
18
use crate::compiler::expr::{
19
    as_literal_arg, call, classify_stack_type, compile_expr, compile_for_stack,
20
    compile_for_stack_as, eval_value, fold_value, format_expr,
21
};
22
use crate::compiler::join::{Arm, NEVER_RETURNS, reconcile_arms};
23
use crate::error::{Error, Result};
24
use crate::runtime::SymbolTable;
25

            
26
use super::car_cdr::{coerce_anyref_to_pair, reject_non_list};
27
use super::infer::{chain_pair_element, literal_pair_element};
28
use super::map_runtime::{compile_map_runtime_list, predict_map_result_element};
29
use crate::compiler::expr::emit_box_cell;
30
use crate::compiler::native::function_operand::function_operand;
31

            
32
32749
pub(super) fn map_fn(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
33
32749
    if args.len() < 2 {
34
208
        return Err(Error::Arity {
35
208
            name: "MAP".to_string(),
36
208
            expected: 2,
37
208
            actual: args.len(),
38
208
        });
39
32541
    }
40
32541
    let fn_resolved = eval_value(symbols, &args[0])?;
41
32327
    if matches!(fn_resolved.wasm_type(), Some(WasmType::Closure(_))) {
42
        // MAP's OUTPUT element is the closure's RESULT type (it transforms each
43
        // element) — NOT the input element. The closure-emit site records the
44
        // result so this eval prediction agrees with codegen (`compile_map_*`
45
        // uses the per-row closure result). When the result isn't recorded
46
        // (or isn't a pair-cell type), fall back to `predict_map_result_element`
47
        // — the SAME predictor `compile_map_runtime_list` uses — instead of
48
        // silently keeping the INPUT element, which would drift from whatever
49
        // the closure body actually returns.
50
642
        let elem = match super::sourceless_closure_sig(symbols, &fn_resolved)
51
            .and_then(|sig| symbols.closure_result(sig))
52
642
            .and_then(PairElement::from_wasm_type)
53
        {
54
            Some(result_elem) => result_elem,
55
            None => {
56
                let input_elem =
57
642
                    runtime_pair_input_element(symbols, &args[1..])?.unwrap_or(PairElement::Ratio);
58
642
                predict_map_result_element(symbols, &args[0], input_elem)?
59
            }
60
        };
61
642
        return Ok(Expr::WasmRuntime(WasmType::PairRef(elem)));
62
31685
    }
63
31685
    if list_args_have_runtime_pair(symbols, &args[1..])? {
64
        // Same fix for a runtime input list mapped by an INLINE lambda or
65
        // bare defun (no recorded closure signature at all): the input
66
        // element is only a probing SAMPLE, never the answer.
67
        // `predict_map_result_element` applies the function to a
68
        // representative element and classifies what comes back — the
69
        // single path `compile_map_runtime_list` already used, so this
70
        // eval-side prediction can no longer drift from what codegen
71
        // actually lowers each row to (a `(> x 5)` predicate over a runtime
72
        // I32 list is Bool, not I32).
73
2925
        let input_elem = runtime_pair_input_element(symbols, &args[1..])?
74
            .ok_or_else(|| Error::Compile("MAP: runtime list element type unknown".to_string()))?;
75
2925
        let result_elem = predict_map_result_element(symbols, &args[0], input_elem)?;
76
2093
        return Ok(Expr::WasmRuntime(WasmType::PairRef(result_elem)));
77
28760
    }
78
    // Static fn + constant list(s): try to fully reduce. If the body produces
79
    // a runtime value per element (a side-effecting native, or a runtime
80
    // result), MAP ISN'T constant-foldable — surface a runtime placeholder
81
    // typed by the body's per-element result so the compile path lowers each
82
    // element call at runtime instead of baking placeholders into a list.
83
28760
    let folded = constant_fold_map(symbols, &args[0], &args[1..])?;
84
28345
    if let Some(elem) = mapped_runtime_element(&folded) {
85
24
        return Ok(Expr::WasmRuntime(WasmType::PairRef(elem)));
86
28321
    }
87
28321
    Ok(folded)
88
32749
}
89

            
90
/// If a folded MAP result is a list whose elements are runtime placeholders
91
/// (the body produced runtime values), returns the unified `PairElement` of
92
/// those results — the signal that MAP must lower at runtime. `None` when the
93
/// fold produced a genuine constant list.
94
34011
fn mapped_runtime_element(folded: &Expr) -> Option<PairElement> {
95
34011
    let elems = match folded {
96
33803
        Expr::Datum(inner) => match inner.as_ref() {
97
33803
            Expr::List(elems) => elems,
98
            _ => return None,
99
        },
100
        Expr::List(elems) => elems,
101
208
        _ => return None,
102
    };
103
33803
    if !elems.iter().any(Expr::is_wasm_runtime) {
104
31273
        return None;
105
2530
    }
106
2530
    Some(chain_pair_element(elems).unwrap_or(PairElement::AnyRef))
107
34011
}
108

            
109
35272
fn constant_fold_map(
110
35272
    symbols: &mut SymbolTable,
111
35272
    function_arg: &Expr,
112
35272
    list_args: &[Expr],
113
35272
) -> Result<Expr> {
114
35272
    let lists: Vec<Vec<Expr>> = list_args
115
35272
        .iter()
116
36312
        .map(|arg| {
117
36312
            let resolved = eval_value(symbols, arg)?;
118
36312
            extract_list_elements(&resolved)
119
36312
        })
120
208
        .collect::<Result<_>>()?;
121

            
122
35064
    let min_len = lists.iter().map(std::vec::Vec::len).min().unwrap_or(0);
123
35064
    let stores = symbols.measurements().cell_stores();
124

            
125
35064
    let mut results = Vec::with_capacity(min_len);
126
35064
    for i in 0..min_len {
127
45358
        let mut call_args = vec![function_operand(symbols, function_arg)?];
128
45358
        for list in &lists {
129
47646
            call_args.push(as_literal_arg(&list[i]));
130
        }
131
45358
        let result = call(symbols, &call_args)?;
132
44305
        let resolved_result = eval_value(symbols, &result)?;
133
44305
        results.push(resolved_result);
134
    }
135
34011
    if symbols.measurements().cell_stores() != stores {
136
1049
        results = results.iter().map(as_runtime_result).collect();
137
32962
    }
138
34011
    crate::compiler::datum::bounded(symbols, Expr::quoted_list(results))
139
35272
}
140

            
141
/// A result of a mapped body that stored to a cell: a fold cannot keep the
142
/// store, so the row is a runtime value of its type.
143
2921
fn as_runtime_result(result: &Expr) -> Expr {
144
2921
    Expr::WasmRuntime(classify_stack_type(result).unwrap_or(WasmType::AnyRef))
145
2921
}
146

            
147
31685
fn list_args_have_runtime_pair(symbols: &mut SymbolTable, list_args: &[Expr]) -> Result<bool> {
148
31685
    for arg in list_args {
149
32309
        let resolved = eval_value(symbols, arg)?;
150
32309
        if matches!(
151
32309
            resolved.wasm_type(),
152
            Some(WasmType::PairRef(_) | WasmType::AnyRef)
153
        ) {
154
2925
            return Ok(true);
155
29384
        }
156
    }
157
28760
    Ok(false)
158
31685
}
159

            
160
3567
fn runtime_pair_input_element(
161
3567
    symbols: &mut SymbolTable,
162
3567
    list_args: &[Expr],
163
3567
) -> Result<Option<PairElement>> {
164
3567
    for arg in list_args {
165
3567
        match eval_value(symbols, arg)?.wasm_type() {
166
2925
            Some(WasmType::PairRef(elem)) => return Ok(Some(elem)),
167
            Some(WasmType::AnyRef) => return Ok(Some(PairElement::AnyRef)),
168
642
            _ => {}
169
        }
170
    }
171
642
    Ok(None)
172
3567
}
173

            
174
115994
pub(super) fn extract_list_elements(expr: &Expr) -> Result<Vec<Expr>> {
175
115994
    match expr {
176
        Expr::List(elems) => Ok(elems.clone()),
177
10129
        Expr::Nil => Ok(vec![]),
178
103352
        Expr::Datum(inner) => match inner.as_ref() {
179
99563
            Expr::List(elems) => Ok(elems.clone()),
180
            Expr::Nil => Ok(vec![]),
181
3789
            other => Err(Error::Compile(format!(
182
3789
                "MAP expects list arguments, got quoted {}",
183
3789
                format_expr(other)
184
3789
            ))),
185
        },
186
2513
        other => Err(Error::Compile(format!(
187
2513
            "MAP expects list arguments, got {}",
188
2513
            format_expr(other)
189
2513
        ))),
190
    }
191
115994
}
192

            
193
11134
pub(super) fn compile_map(
194
11134
    ctx: &mut CompileContext,
195
11134
    emit: &mut FunctionEmitter,
196
11134
    symbols: &mut SymbolTable,
197
11134
    args: &[Expr],
198
11134
) -> Result<()> {
199
11134
    let Some(args) = &super::hoist_function_arg(ctx, emit, symbols, args)? else {
200
        return Ok(());
201
    };
202
10706
    if args.len() < 2 {
203
        return Err(Error::Arity {
204
            name: "MAP".to_string(),
205
            expected: 2,
206
            actual: args.len(),
207
        });
208
10706
    }
209
10706
    let fn_resolved = eval_value(symbols, &args[0])?;
210
9872
    let runtime_closure = matches!(fn_resolved.wasm_type(), Some(WasmType::Closure(_)));
211
9872
    if !runtime_closure && constant_lists(symbols, &args[1..])?.is_some() {
212
6512
        let result = constant_fold_map(symbols, &args[0], &args[1..])?;
213
5666
        if mapped_runtime_element(&result).is_none() {
214
3160
            return compile_expr(ctx, emit, symbols, &result);
215
2506
        }
216
3360
    }
217
5866
    let ty = compile_map_to_stack(ctx, emit, symbols, args)?;
218
5448
    crate::compiler::expr::serialize_stack_to_output(ctx, emit, ty)
219
11134
}
220

            
221
/// The element lists of `list_args` when every one folds to a constant list;
222
/// `None` when any must be compiled (it runs, or raises, at runtime).
223
24787
fn constant_lists(symbols: &mut SymbolTable, list_args: &[Expr]) -> Result<Option<Vec<Vec<Expr>>>> {
224
24787
    let mut lists = Vec::with_capacity(list_args.len());
225
24787
    for arg in list_args {
226
25415
        match fold_value(symbols, arg)?.map(|datum| extract_list_elements(&datum)) {
227
16445
            Some(Ok(elements)) => lists.push(elements),
228
8970
            _ => return Ok(None),
229
        }
230
    }
231
15817
    Ok(Some(lists))
232
24787
}
233

            
234
16620
pub(super) fn compile_map_to_stack(
235
16620
    ctx: &mut CompileContext,
236
16620
    emit: &mut FunctionEmitter,
237
16620
    symbols: &mut SymbolTable,
238
16620
    args: &[Expr],
239
16620
) -> Result<WasmType> {
240
16620
    let Some(args) = &super::hoist_function_arg(ctx, emit, symbols, args)? else {
241
3
        return Ok(NEVER_RETURNS);
242
    };
243
16607
    if args.len() < 2 {
244
        return Err(Error::Compile(
245
            "MAP: stack-position lowering requires a function and at least one list".to_string(),
246
        ));
247
16607
    }
248
16607
    if let Some(lists) = constant_lists(symbols, &args[1..])? {
249
9305
        return compile_map_literal(ctx, emit, symbols, &args[0], &lists);
250
7302
    }
251
    // A list that does not fold is compiled and dispatched on its stack type.
252
    // (A multi-list MAP over runtime pair chains is not supported — only the
253
    // single-list runtime chain is.)
254
7302
    if args.len() != 2 {
255
416
        return Err(Error::Compile(
256
416
            "MAP: a multi-list mapping requires constant lists; a runtime list \
257
416
             is only supported as the sole list argument"
258
416
                .to_string(),
259
416
        ));
260
6886
    }
261
6886
    let elem = match compile_for_stack(ctx, emit, symbols, &args[1])? {
262
6261
        WasmType::PairRef(elem) => elem,
263
        WasmType::AnyRef => {
264
416
            coerce_anyref_to_pair(ctx, emit)?;
265
416
            PairElement::AnyRef
266
        }
267
208
        other => return reject_non_list(ctx, emit, symbols, "MAP", &args[1], other),
268
    };
269
6677
    compile_map_runtime_list(ctx, emit, symbols, &args[0], elem)
270
16620
}
271

            
272
/// Lower `(map <fn> '(a0 a1 ...) '(b0 b1 ...) ...)` row-by-row over one or more
273
/// constant lists (zipped to the shortest). Each per-row call rides FUNCALL (→
274
/// `call_ref` for a closure, inline for a bare lambda); results land in fresh
275
/// per-row locals. We then walk the locals in reverse and prepend each car onto
276
/// the accumulator via `pair_new` so the output keeps input order without an
277
/// extra reverse pass.
278
9305
fn compile_map_literal(
279
9305
    ctx: &mut CompileContext,
280
9305
    emit: &mut FunctionEmitter,
281
9305
    symbols: &mut SymbolTable,
282
9305
    fn_arg: &Expr,
283
9305
    lists: &[Vec<Expr>],
284
9305
) -> Result<WasmType> {
285
9305
    let rows = lists.iter().map(Vec::len).min().unwrap_or(0);
286
9305
    if rows == 0 {
287
212
        emit.ref_null(ctx.ids.ty_pair);
288
212
        return Ok(WasmType::PairRef(PairElement::Ratio));
289
9093
    }
290
19643
    let calls: Vec<Expr> = (0..rows).map(|row| row_call(fn_arg, lists, row)).collect();
291
    // The rows' resolved values decide the chain by the LIST rule — the same
292
    // values the eval mirror `mapped_runtime_element` unifies.
293
9093
    let closure = eval_value(&mut symbols.clone(), fn_arg)?;
294
9092
    let closure_result = match super::sourceless_closure_sig(symbols, &closure) {
295
633
        Some(sig) => Some(ctx.closure_sig(sig)?.result),
296
8459
        None => None,
297
    };
298
9092
    let values = calls
299
9092
        .iter()
300
19427
        .map(|call| row_value(symbols, call, closure_result))
301
222
        .collect::<Result<Vec<_>>>()?;
302
8870
    let predicted = chain_pair_element(&values).map_err(|_| unpairable_row_error())?;
303
8870
    let mut element_locals: Vec<(u32, PairElement)> = Vec::with_capacity(rows);
304
8870
    for (call, value) in calls.iter().zip(&values) {
305
18997
        let elem = compile_map_row(ctx, emit, symbols, call, value, predicted)?;
306
18789
        let local = ctx.alloc_local(elem.as_wasm_type())?;
307
18789
        emit.local_set(local);
308
18789
        element_locals.push((local, elem));
309
    }
310
8662
    let chain_elem = joined_row_element(predicted, &element_locals)?;
311
8662
    let pair_idx = ctx.ids.ty_pair;
312
8662
    let acc_local = ctx.alloc_local(WasmType::PairRef(chain_elem))?;
313
8662
    emit.ref_null(pair_idx);
314
8662
    emit.local_set(acc_local);
315
8662
    for (local, elem_ty) in element_locals.iter().rev() {
316
18789
        emit.local_get(*local);
317
        // Box each car for the CHAIN's element slot: an AnyRef chain needs
318
        // every car widened to anyref (i31 for i32/bool); a homogeneous chain
319
        // boxes per the element's own type.
320
18789
        emit_box_cell(ctx, emit, *elem_ty, chain_elem);
321
18789
        emit.local_get(acc_local);
322
18789
        emit.call(ctx.ids.pair_new);
323
18789
        emit.local_set(acc_local);
324
    }
325
8662
    emit.local_get(acc_local);
326
8662
    Ok(WasmType::PairRef(chain_elem))
327
9305
}
328

            
329
/// A row's value as the chain rule sees it: a closure call yields its
330
/// signature's result (the eval `call` cannot apply a closure local), any
331
/// other callable resolves on a clone.
332
19427
fn row_value(symbols: &SymbolTable, call: &Expr, closure_result: Option<WasmType>) -> Result<Expr> {
333
19427
    match closure_result {
334
1266
        Some(result) => Ok(Expr::WasmRuntime(result)),
335
18161
        None => eval_value(&mut symbols.clone(), call),
336
    }
337
19427
}
338

            
339
19643
fn row_call(fn_arg: &Expr, lists: &[Vec<Expr>], row: usize) -> Expr {
340
19643
    let mut call = vec![Expr::symbol("FUNCALL"), fn_arg.clone()];
341
20071
    call.extend(lists.iter().map(|list| as_literal_arg(&list[row])));
342
19643
    Expr::List(call)
343
19643
}
344

            
345
/// The chain element the prediction and the compiled rows join to: a row the
346
/// prediction missed widens it, and its car is boxed as it is consed.
347
8662
fn joined_row_element(predicted: PairElement, rows: &[(u32, PairElement)]) -> Result<PairElement> {
348
8662
    let arms: Vec<Arm> = std::iter::once(predicted)
349
18789
        .chain(rows.iter().map(|(_, elem)| *elem))
350
27451
        .map(|elem| Arm::Value(elem.as_wasm_type()))
351
        .collect();
352
8662
    PairElement::from_wasm_type(reconcile_arms(&arms)).ok_or_else(unpairable_row_error)
353
8662
}
354

            
355
/// Compiles one row's call: a literal result takes the predicted chain's cell
356
/// type (its own slot in an `AnyRef` chain); a runtime result keeps its own.
357
18997
fn compile_map_row(
358
18997
    ctx: &mut CompileContext,
359
18997
    emit: &mut FunctionEmitter,
360
18997
    symbols: &mut SymbolTable,
361
18997
    call: &Expr,
362
18997
    value: &Expr,
363
18997
    chain_elem: PairElement,
364
18997
) -> Result<PairElement> {
365
18997
    let cell = match (literal_pair_element(value), chain_elem) {
366
416
        (Some(slot), PairElement::AnyRef) => Some(slot),
367
9480
        (Some(_), chain) => Some(chain),
368
9101
        (None, _) => None,
369
    };
370
18997
    let ty = match cell {
371
        Some(elem) => {
372
9896
            compile_for_stack_as(ctx, emit, symbols, call, elem.as_wasm_type())?;
373
9896
            elem.as_wasm_type()
374
        }
375
9101
        None => compile_for_stack(ctx, emit, symbols, call)?,
376
    };
377
18789
    PairElement::from_wasm_type(ty).ok_or_else(unpairable_row_error)
378
18997
}
379

            
380
fn unpairable_row_error() -> Error {
381
    Error::Compile(
382
        "MAP: closure result type can't ride a typed pair; flatten via let-bind first".to_string(),
383
    )
384
}