1
//! `FOLD` — left fold over a list. `(fold f init list)` returns the
2
//! accumulator after applying `f(acc, item)` left-to-right.
3
//!
4
//! Three paths matching MAP / FILTER:
5
//! - **Constant-fold**: function + list both resolve at compile time;
6
//!   walk element-by-element calling `f` via the eval `call` pipeline,
7
//!   threading `init` through.
8
//! - **Runtime closure, literal list**: emit FUNCALL per element,
9
//!   threading the accumulator through a fresh local each iteration.
10
//! - **Runtime closure or runtime `PairRef` list**: walk the input
11
//!   chain at runtime, calling `f` on each car with the accumulator.
12

            
13
use crate::ast::{Expr, PairElement, WasmType};
14
use crate::compiler::context::CompileContext;
15
use crate::compiler::emit::FunctionEmitter;
16
use crate::compiler::expr::{
17
    as_literal_arg, call, compile_expr, compile_for_effect, compile_for_stack,
18
    compile_for_stack_as, emit_nil_default, eval_value, fold_value, format_expr, is_untyped,
19
    pin_hint, probe_value,
20
};
21
use crate::compiler::join::NEVER_RETURNS;
22
use crate::error::{Error, Result};
23
use crate::runtime::SymbolTable;
24

            
25
use super::car_cdr::{coerce_anyref_to_pair, throw_unless_nil};
26
use crate::compiler::native::function_operand::function_operand;
27

            
28
5431
pub(super) fn fold(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
29
5431
    if args.len() != 3 {
30
        return Err(Error::Arity {
31
            name: "FOLD".to_string(),
32
            expected: 3,
33
            actual: args.len(),
34
        });
35
5431
    }
36
5431
    let fn_resolved = eval_value(symbols, &args[0])?;
37
5431
    let init_resolved = eval_value(symbols, &args[1])?;
38
5431
    let list_resolved = eval_value(symbols, &args[2])?;
39
5431
    let runtime_closure = matches!(fn_resolved.wasm_type(), Some(WasmType::Closure(_)));
40
5431
    let runtime_list = matches!(
41
5431
        list_resolved.wasm_type(),
42
        Some(WasmType::PairRef(_) | WasmType::AnyRef)
43
    );
44
5431
    if runtime_closure || runtime_list {
45
3960
        let acc_ty = eval_fold_result_type(
46
3960
            symbols,
47
3960
            &fn_resolved,
48
3960
            &args[0],
49
3960
            &init_resolved,
50
3960
            &list_resolved,
51
3960
        )?;
52
3960
        return Ok(Expr::WasmRuntime(acc_ty));
53
1471
    }
54
    // Static fn + constant list: try to fully reduce. If the body produces a
55
    // runtime value (a side-effecting native like `print`, or any host-fn
56
    // result), the fold ISN'T constant-foldable — surface a runtime placeholder
57
    // so the compile path takes the per-element FUNCALL runtime lowering
58
    // instead of baking a bare `WasmRuntime` placeholder into the result.
59
1471
    let folded = constant_fold_fold(symbols, &args[0], &init_resolved, &list_resolved)?;
60
1055
    if folded.is_wasm_runtime() {
61
12
        let acc_ty = eval_fold_result_type(
62
12
            symbols,
63
12
            &fn_resolved,
64
12
            &args[0],
65
12
            &init_resolved,
66
12
            &list_resolved,
67
12
        )?;
68
        // Depth-guarded teardown: `list_resolved` is a fully materialized
69
        // constant list, potentially deep enough that the default recursive
70
        // drop glue would overflow the native stack (plan 0011 Phase 0).
71
12
        crate::ast_teardown::drop_iteratively(list_resolved);
72
12
        return Ok(Expr::WasmRuntime(acc_ty));
73
1043
    }
74
1043
    crate::ast_teardown::drop_iteratively(list_resolved);
75
1043
    Ok(folded)
76
5431
}
77

            
78
/// Eval-path fold result type, kept in lockstep with `compile_fold_to_stack`:
79
/// a runtime closure's accumulator type IS its signature's result type. The
80
/// eval surface has no `CompileContext`, so it reads the result the closure-emit
81
/// site recorded into the symbol table (`SymbolTable::closure_result`); without
82
/// it (closure not recorded) it falls back to the body/seed probe. This stops
83
/// the eval mirror sizing a fold accumulator from the seed (e.g. `0` → Index)
84
/// while codegen emits the closure's real (e.g. Ratio) result.
85
3972
fn eval_fold_result_type(
86
3972
    symbols: &mut SymbolTable,
87
3972
    fn_resolved: &Expr,
88
3972
    fn_arg: &Expr,
89
3972
    init_resolved: &Expr,
90
3972
    list_resolved: &Expr,
91
3972
) -> Result<WasmType> {
92
3972
    if let Some(sig) = super::sourceless_closure_sig(symbols, fn_resolved)
93
1664
        && let Some(result) = symbols.closure_result(sig)
94
    {
95
1664
        return Ok(result);
96
2308
    }
97
2308
    accumulator_type(symbols, fn_arg, init_resolved, list_resolved)
98
3972
}
99

            
100
/// The accumulator/result `WasmType` of a fold. A concrete (non-nil) init
101
/// fixes it. A `nil` init is POLYMORPHIC — its `Bool` type is just "empty" —
102
/// so the real accumulator type is whatever the fold body returns; probe it by
103
/// classifying one application `f(init, <sample-elem>)` on a clone (no
104
/// live-table mutation). Falls back to the init's own type when the body can't
105
/// be probed. Shared by the eval mirror and the codegen path so they agree.
106
13582
fn accumulator_type(
107
13582
    symbols: &mut SymbolTable,
108
13582
    fn_arg: &Expr,
109
13582
    init_resolved: &Expr,
110
13582
    list_resolved: &Expr,
111
13582
) -> Result<WasmType> {
112
    // A concrete runtime-typed init (a `WasmLocal`/`WasmRuntime`, NOT nil)
113
    // fixes the accumulator type directly.
114
13582
    if let Some(ty) = init_resolved.wasm_type()
115
433
        && !matches!(init_resolved, Expr::Nil)
116
    {
117
433
        return Ok(ty);
118
13149
    }
119
    // Otherwise (a `nil` polymorphic seed, or a literal init like `0` whose
120
    // own classified type may still be refined by the body) the accumulator
121
    // type is what the body returns — probe one application.
122
13149
    if let Some(elem) = sample_element(list_resolved)?
123
12733
        && let Some(ty) = probe_body_type(symbols, fn_arg, init_resolved, &elem)?
124
    {
125
11689
        return widen_with_seed(ty, init_resolved);
126
1457
    }
127
    // Empty list or un-probeable body: fall back to the init's own stack type
128
    // (a literal → its classified type, e.g. `0` → Ratio; nil → Bool).
129
1457
    Ok(crate::compiler::expr::classify_stack_type(init_resolved).unwrap_or(WasmType::Ratio))
130
13582
}
131

            
132
/// A constant-list seed's members share the accumulator chain with the body's
133
/// cells, so they widen a pair accumulator's element: `'(nil)` seeding an
134
/// index chain is heterogeneous, never a zero.
135
11689
fn widen_with_seed(ty: WasmType, init_resolved: &Expr) -> Result<WasmType> {
136
11689
    let (WasmType::PairRef(elem), Expr::Datum(seed)) = (ty, init_resolved) else {
137
10025
        return Ok(ty);
138
    };
139
1664
    let Expr::List(members) = seed.as_ref() else {
140
        return Ok(ty);
141
    };
142
1664
    let mut cells = members.clone();
143
1664
    cells.push(Expr::WasmRuntime(elem.as_wasm_type()));
144
1664
    Ok(WasmType::PairRef(super::infer::chain_pair_element(&cells)?))
145
11689
}
146

            
147
/// A representative element value for probing the fold body's return type:
148
/// the runtime element's placeholder for a `PairRef` list; for a constant
149
/// list, a placeholder typed at the chain's UNIFIED element — not just its
150
/// first member — mirroring the `PairRef` branch and `LIST`'s own
151
/// `chain_pair_element` rule. Probing with only the first element
152
/// under-samples a heterogeneous constant list: `(list 1 nil)` unifies to
153
/// `AnyRef`, but its first element alone (`1`) would probe the body as if it
154
/// only ever saw an `I32`, mis-sizing the accumulator for the OTHER elements.
155
/// `None` for an empty list (nothing to probe).
156
13149
fn sample_element(list_resolved: &Expr) -> Result<Option<Expr>> {
157
13149
    match list_resolved.wasm_type() {
158
7494
        Some(WasmType::PairRef(elem)) => return Ok(Some(Expr::WasmRuntime(elem.as_wasm_type()))),
159
208
        Some(WasmType::AnyRef) => return Ok(Some(Expr::WasmRuntime(WasmType::AnyRef))),
160
5447
        _ => {}
161
    }
162
    // A non-list constant has no element to probe; codegen throws on it.
163
5447
    let Ok(elements) = extract_list_elements(list_resolved) else {
164
208
        return Ok(None);
165
    };
166
5239
    if elements.is_empty() {
167
208
        return Ok(None);
168
5031
    }
169
5031
    let elem = super::infer::chain_pair_element(&elements)?;
170
5031
    Ok(Some(Expr::WasmRuntime(elem.as_wasm_type())))
171
13149
}
172

            
173
/// Classify the type of one fold application `f(acc, elem)` without emitting —
174
/// evaluated on a CLONE so no live-table mutation, then run through the shared
175
/// stack-type classifier so the prediction matches codegen.
176
12733
fn probe_body_type(
177
12733
    symbols: &mut SymbolTable,
178
12733
    fn_arg: &Expr,
179
12733
    acc: &Expr,
180
12733
    elem: &Expr,
181
12733
) -> Result<Option<WasmType>> {
182
12733
    let call_args = vec![
183
12733
        function_operand(symbols, fn_arg)?,
184
12733
        as_literal_arg(acc),
185
12733
        as_literal_arg(elem),
186
    ];
187
12733
    let mut probe = symbols.clone();
188
12733
    let result = match call(&mut probe, &call_args) {
189
11689
        Ok(result) => result,
190
3
        Err(err @ Error::Dimension(_)) => return Err(err),
191
1041
        Err(_) => return Ok(None),
192
    };
193
11689
    Ok(crate::compiler::expr::classify_stack_type(&result))
194
12733
}
195

            
196
2941
fn constant_fold_fold(
197
2941
    symbols: &mut SymbolTable,
198
2941
    fn_arg: &Expr,
199
2941
    init_resolved: &Expr,
200
2941
    list_resolved: &Expr,
201
2941
) -> Result<Expr> {
202
2941
    let elements = extract_list_elements(list_resolved)?;
203
    // Charged upfront, sized by the whole constant list: a fold over a huge
204
    // literal datum is bounded by the shared budget rather than by however
205
    // long the per-element loop below happens to take to run.
206
2941
    symbols.charge_work(elements.len() as u64)?;
207
2941
    let stores = symbols.measurements().cell_stores();
208
2941
    let mut acc = init_resolved.clone();
209
2941
    for elem in elements {
210
111328
        let call_args = vec![
211
111328
            function_operand(symbols, fn_arg)?,
212
111328
            as_literal_arg(&acc),
213
111328
            as_literal_arg(&elem),
214
        ];
215
111328
        let result = call(symbols, &call_args)?;
216
110910
        acc = eval_value(symbols, &result)?;
217
    }
218
2523
    if symbols.measurements().cell_stores() != stores {
219
        return Ok(Expr::WasmRuntime(
220
            crate::compiler::expr::classify_stack_type(&acc).unwrap_or(WasmType::AnyRef),
221
        ));
222
2523
    }
223
2523
    Ok(acc)
224
2941
}
225

            
226
/// Seed the accumulator local from `init`, coercing the init to the resolved
227
/// accumulator type. For a `PairRef` accumulator a constant-list seed (`nil`,
228
/// or a quoted literal list) is materialized into a runtime `$pair` chain —
229
/// `nil` is the empty chain (`ref.null pair`). For any other `acc_ty` the init
230
/// must already match.
231
12106
fn emit_fold_init(
232
12106
    ctx: &mut CompileContext,
233
12106
    emit: &mut FunctionEmitter,
234
12106
    symbols: &mut SymbolTable,
235
12106
    (fn_arg, init_arg): (&Expr, &Expr),
236
12106
    acc_ty: WasmType,
237
12106
) -> Result<()> {
238
    // Probe the seed's resolved value on a CLONE so a seed that mutates the
239
    // table (SETF/DEFVAR) isn't applied here AND again by the emission path.
240
12106
    let resolved = probe_value(&mut symbols.clone(), init_arg)?;
241
12106
    let constant = fold_value(symbols, init_arg)?;
242
    // A nil seed (for ANY accumulator type, including PairRef where it is the
243
    // empty `$pair` chain) must first emit the effects of a non-literal seed
244
    // that merely *resolves* to nil, then push the typed nil default. Checked
245
    // before the PairRef constant-list materialization so a `(progn …effects… nil)`
246
    // seed isn't silently collapsed to `ref.null`.
247
12106
    if matches!(resolved, Expr::Nil) {
248
1872
        if !matches!(init_arg, Expr::Nil) {
249
416
            compile_for_effect(ctx, emit, symbols, init_arg)?;
250
1456
        }
251
1872
        return emit_nil_default(ctx, emit, acc_ty);
252
10234
    }
253
10234
    if let WasmType::PairRef(elem) = acc_ty
254
1664
        && let Some(constant) = constant
255
    {
256
        // A constant-list seed for a runtime pair accumulator: materialize it
257
        // with cells at the accumulator's element, so a fold forced onto the
258
        // runtime path by a side-effecting body can still seed a non-nil
259
        // literal-list accumulator. See `append::push_list_arg`.
260
1664
        let elements = super::map::extract_list_elements(&constant)?;
261
1664
        return super::cons::emit_constant_chain(ctx, emit, symbols, elements, elem);
262
8570
    }
263
    // Scalar / Index / Money / nil seed: coerce to the accumulator type (an
264
    // integer/fractional literal crosses the sanctioned Index↔Scalar boundary).
265
8570
    compile_for_stack_as(ctx, emit, symbols, init_arg, acc_ty).map_err(|e| {
266
3
        let detail = e.to_string().replacen("Compile error: ", "", 1);
267
3
        let hint = probe_value(&mut symbols.clone(), fn_arg)
268
3
            .ok()
269
3
            .and_then(|f| f.place())
270
3
            .map_or_else(String::new, |(place, _)| {
271
3
                pin_hint(symbols, (place, 0), (init_arg, acc_ty))
272
3
            });
273
3
        Error::Compile(format!(
274
3
            "FOLD: init does not match accumulator type {acc_ty}: {detail}{hint}"
275
3
        ))
276
3
    })
277
12106
}
278

            
279
20545
fn extract_list_elements(expr: &Expr) -> Result<Vec<Expr>> {
280
20545
    match expr {
281
        Expr::List(elems) => Ok(elems.clone()),
282
208
        Expr::Nil => Ok(vec![]),
283
19921
        Expr::Datum(inner) => match inner.as_ref() {
284
19921
            Expr::List(elems) => Ok(elems.clone()),
285
            Expr::Nil => Ok(vec![]),
286
            other => Err(Error::Compile(format!(
287
                "FOLD expects a list, got quoted {}",
288
                format_expr(other)
289
            ))),
290
        },
291
416
        other => Err(Error::Compile(format!(
292
416
            "FOLD expects a list, got {}",
293
416
            format_expr(other)
294
416
        ))),
295
    }
296
20545
}
297

            
298
5859
pub(super) fn compile_fold(
299
5859
    ctx: &mut CompileContext,
300
5859
    emit: &mut FunctionEmitter,
301
5859
    symbols: &mut SymbolTable,
302
5859
    args: &[Expr],
303
5859
) -> Result<()> {
304
5859
    let Some(args) = &super::hoist_function_arg(ctx, emit, symbols, args)? else {
305
        return Ok(());
306
    };
307
5857
    if args.len() != 3 {
308
        return Err(Error::Arity {
309
            name: "FOLD".to_string(),
310
            expected: 3,
311
            actual: args.len(),
312
        });
313
5857
    }
314
5857
    let runtime_closure = matches!(
315
5857
        eval_value(symbols, &args[0])?.wasm_type(),
316
        Some(WasmType::Closure(_))
317
    );
318
5647
    if !runtime_closure
319
        && let (Some(init), Some(list)) = (
320
2927
            fold_value(symbols, &args[1])?,
321
2927
            constant_list(symbols, &args[2])?,
322
        )
323
    {
324
1470
        let result = constant_fold_fold(symbols, &args[0], &init, &list)?;
325
1468
        if !result.is_wasm_runtime() {
326
1050
            return compile_expr(ctx, emit, symbols, &result);
327
418
        }
328
3969
    }
329
4387
    let ty = compile_fold_to_stack(ctx, emit, symbols, args)?;
330
3967
    crate::compiler::expr::serialize_stack_to_output(ctx, emit, ty)
331
5859
}
332

            
333
/// The constant list `arg` folds to; `None` when it must be compiled.
334
15033
fn constant_list(symbols: &mut SymbolTable, arg: &Expr) -> Result<Option<Expr>> {
335
15033
    Ok(fold_value(symbols, arg)?.filter(|datum| extract_list_elements(datum).is_ok()))
336
15033
}
337

            
338
12111
pub(super) fn compile_fold_to_stack(
339
12111
    ctx: &mut CompileContext,
340
12111
    emit: &mut FunctionEmitter,
341
12111
    symbols: &mut SymbolTable,
342
12111
    args: &[Expr],
343
12111
) -> Result<WasmType> {
344
12111
    let Some(args) = &super::hoist_function_arg(ctx, emit, symbols, args)? else {
345
        return Ok(NEVER_RETURNS);
346
    };
347
12110
    if args.len() != 3 {
348
        return Err(Error::Compile(
349
            "FOLD: stack-position lowering needs (fn init list)".to_string(),
350
        ));
351
12110
    }
352
12110
    let fn_resolved = eval_value(symbols, &args[0])?;
353
12109
    let (init_arg, init_resolved) = bind_untyped_init(ctx, emit, symbols, &args[1])?;
354
12109
    let list_resolved = probe_value(&mut symbols.clone(), &args[2])?;
355
    // A runtime closure declares its accumulator type in its signature (the
356
    // result type the body returns under its parameter types). Use that rather
357
    // than the eval-side body probe, which sees literal-typed sample args and
358
    // would mis-infer Index where the closure params are Scalar/Money.
359
12109
    let acc_ty = match super::sourceless_closure_sig(symbols, &fn_resolved) {
360
835
        Some(sig) => ctx.closure_sig(sig)?.result,
361
11274
        None => accumulator_type(symbols, &args[0], &init_resolved, &list_resolved)?,
362
    };
363

            
364
    // A let-bound closure has a FIXED signature; applying it via `call_ref` over
365
    // a non-Ratio list mismatches its iteration param. If its source body is
366
    // recoverable, inline it per element instead — `compile_lambda_call` binds
367
    // the iteration param to the actual element type. The accumulator type stays
368
    // the closure's declared result (it threads through unchanged).
369
12106
    let call_fn = super::inline_closure_fn(symbols, &args[0])?;
370

            
371
    // Any callable over a constant list — runtime closure OR a bare lambda /
372
    // defun whose body isn't constant-foldable (const-fold bailed here). Each
373
    // element is applied via FUNCALL, which serves both shapes.
374
12106
    if let Some(list) = constant_list(symbols, &args[2])? {
375
5239
        return compile_fold_literal(ctx, emit, symbols, &call_fn, &init_arg, &list, acc_ty);
376
6867
    }
377
6867
    compile_fold_runtime_list(
378
6867
        ctx,
379
6867
        emit,
380
6867
        symbols,
381
6867
        FoldRuntimeArgs {
382
6867
            fn_arg: &call_fn,
383
6867
            init_arg: &init_arg,
384
6867
            list_expr: &args[2],
385
6867
            acc_ty,
386
6867
        },
387
6867
    )
388
12111
}
389

            
390
/// The init and its probed value. An init the evaluator could not type is
391
/// compiled once into a local, so the accumulator takes the type it pushed.
392
12109
fn bind_untyped_init(
393
12109
    ctx: &mut CompileContext,
394
12109
    emit: &mut FunctionEmitter,
395
12109
    symbols: &mut SymbolTable,
396
12109
    init: &Expr,
397
12109
) -> Result<(Expr, Expr)> {
398
12109
    let probed = probe_value(&mut symbols.clone(), init)?;
399
12109
    if !is_untyped(&probed) {
400
11901
        return Ok((init.clone(), probed));
401
208
    }
402
208
    let ty = compile_for_stack(ctx, emit, symbols, init)?;
403
208
    let local = ctx.alloc_local(ty)?;
404
208
    emit.local_set(local);
405
208
    Ok((Expr::WasmLocal(local, ty), Expr::WasmRuntime(ty)))
406
12109
}
407

            
408
/// Lower `(fold <fn> init '(e0 e1 ...))` element-by-element. Each per-element
409
/// call rides FUNCALL (→ `call_ref` for a closure, inline for a bare lambda)
410
/// and threads the accumulator through a fresh local.
411
5239
fn compile_fold_literal(
412
5239
    ctx: &mut CompileContext,
413
5239
    emit: &mut FunctionEmitter,
414
5239
    symbols: &mut SymbolTable,
415
5239
    fn_arg: &Expr,
416
5239
    init_arg: &Expr,
417
5239
    list_resolved: &Expr,
418
5239
    acc_ty: WasmType,
419
5239
) -> Result<WasmType> {
420
5239
    let elements = extract_list_elements(list_resolved)?;
421
5239
    let acc_local = ctx.alloc_local(acc_ty)?;
422
5239
    emit_fold_init(ctx, emit, symbols, (fn_arg, init_arg), acc_ty)?;
423
5236
    emit.local_set(acc_local);
424

            
425
5236
    for elem_expr in &elements {
426
322067
        let funcall = Expr::List(vec![
427
322067
            Expr::symbol("FUNCALL"),
428
322067
            fn_arg.clone(),
429
322067
            Expr::WasmLocal(acc_local, acc_ty),
430
322067
            as_literal_arg(elem_expr),
431
322067
        ]);
432
322067
        let result_ty = compile_for_stack(ctx, emit, symbols, &funcall)?;
433
322066
        if result_ty != acc_ty {
434
            return Err(Error::Compile(format!(
435
                "FOLD: closure return type {result_ty} doesn't match accumulator type {acc_ty}"
436
            )));
437
322066
        }
438
322066
        emit.local_set(acc_local);
439
    }
440
5235
    emit.local_get(acc_local);
441
5235
    Ok(acc_ty)
442
5239
}
443

            
444
struct FoldRuntimeArgs<'a> {
445
    fn_arg: &'a Expr,
446
    init_arg: &'a Expr,
447
    list_expr: &'a Expr,
448
    acc_ty: WasmType,
449
}
450

            
451
/// Walks a runtime `PairRef(elem)` input. Calls `f(acc, car)` per cell,
452
/// threading the accumulator through a fresh local.
453
6867
fn compile_fold_runtime_list(
454
6867
    ctx: &mut CompileContext,
455
6867
    emit: &mut FunctionEmitter,
456
6867
    symbols: &mut SymbolTable,
457
6867
    args: FoldRuntimeArgs<'_>,
458
6867
) -> Result<WasmType> {
459
    let FoldRuntimeArgs {
460
        fn_arg,
461
        init_arg,
462
        list_expr,
463
        acc_ty,
464
6867
    } = args;
465
6867
    let pair_idx = ctx.ids.ty_pair;
466
6867
    let acc_local = ctx.alloc_local(acc_ty)?;
467

            
468
6867
    emit_fold_init(ctx, emit, symbols, (fn_arg, init_arg), acc_ty)?;
469
6451
    emit.local_set(acc_local);
470

            
471
6451
    let elem = match compile_for_stack(ctx, emit, symbols, list_expr)? {
472
5827
        WasmType::PairRef(elem) => elem,
473
        WasmType::AnyRef => {
474
208
            coerce_anyref_to_pair(ctx, emit)?;
475
208
            PairElement::AnyRef
476
        }
477
        other => {
478
416
            throw_unless_nil(ctx, emit, symbols, "FOLD", list_expr, other)?;
479
208
            emit.local_get(acc_local);
480
208
            return Ok(acc_ty);
481
        }
482
    };
483
6035
    let pair_local = ctx.alloc_local(WasmType::PairRef(elem))?;
484
6035
    let car_local = ctx.alloc_local(elem.as_wasm_type())?;
485
6035
    emit.local_set(pair_local);
486

            
487
6035
    emit.block_start();
488
6035
    emit.loop_start();
489

            
490
6035
    emit.local_get(pair_local);
491
6035
    emit.ref_is_null();
492
6035
    emit.br_if(1);
493

            
494
6035
    emit.local_get(pair_local);
495
6035
    emit.struct_get(pair_idx, 0);
496
6035
    crate::compiler::native::list::emit_pair_car_downcast(ctx, emit, elem)?;
497
6035
    emit.local_set(car_local);
498

            
499
6035
    let funcall = Expr::List(vec![
500
6035
        Expr::symbol("FUNCALL"),
501
6035
        fn_arg.clone(),
502
6035
        Expr::WasmLocal(acc_local, acc_ty),
503
6035
        Expr::WasmLocal(car_local, elem.as_wasm_type()),
504
6035
    ]);
505
6035
    let result_ty = compile_for_stack(ctx, emit, symbols, &funcall)?;
506
5411
    if result_ty != acc_ty {
507
        return Err(Error::Compile(format!(
508
            "FOLD: closure return type {result_ty} doesn't match accumulator type {acc_ty}"
509
        )));
510
5411
    }
511
5411
    emit.local_set(acc_local);
512

            
513
5411
    emit.local_get(pair_local);
514
5411
    emit.struct_get(pair_idx, 1);
515
5411
    emit.local_set(pair_local);
516

            
517
5411
    emit.br(0);
518
5411
    emit.block_end()?;
519
5411
    emit.block_end()?;
520

            
521
5411
    emit.local_get(acc_local);
522
5411
    Ok(acc_ty)
523
6867
}