1
//! List-shaped natives: `LIST`, `CONS`, `CAR`, `CDR`, `MAP`, `FILTER`,
2
//! `FOLD`, `REVERSE`.
3
//!
4
//! Split by form:
5
//! - [`infer`] — `infer_pair_element` (static element-type inference
6
//!   for CONS) + per-shape unit tests.
7
//! - [`list_fn`] — `LIST` eval + compile paths.
8
//! - [`cons`] — `CONS` eval + compile + the car/cdr push helpers.
9
//! - [`car_cdr`] — `CAR` / `CDR` eval + compile + the shared
10
//!   `emit_pair_car_downcast` helper reused by `DOLIST`.
11
//! - [`map`] — `MAP` eval + compile + `extract_list_elements`.
12
//! - [`map_runtime`] — `MAP` over a runtime `PairRef` list.
13
//! - [`filter`] — `FILTER` eval + compile, predicate-truthy keeps.
14
//! - [`fold`] — `FOLD` eval + compile, left fold threading accumulator.
15
//! - [`reverse`] — `REVERSE` eval + compile, runtime path emits a
16
//!   prepend-loop using `pair_new` as the cell allocator.
17

            
18
mod append;
19
mod car_cdr;
20
mod cons;
21
mod datum;
22
mod filter;
23
mod fold;
24
mod infer;
25
mod length;
26
mod list_fn;
27
mod map;
28
mod map_runtime;
29
mod pair_p;
30
mod reverse;
31
mod search;
32
mod spill;
33

            
34
#[cfg(test)]
35
mod member_datum_tests;
36
#[cfg(test)]
37
mod spill_tests;
38
#[cfg(test)]
39
mod tests;
40

            
41
use super::NativeSpec;
42
use super::function_operand::hoist_function_arg;
43
use crate::ast::{ClosureSigId, Expr, PairElement, WasmType};
44
use crate::compiler::context::CompileContext;
45
use crate::compiler::emit::FunctionEmitter;
46
use crate::compiler::expr::eval_value;
47
use crate::error::Result;
48
use crate::runtime::SymbolTable;
49

            
50
pub(in crate::compiler) use car_cdr::{coerce_anyref_to_pair, emit_pair_car_downcast};
51
pub(in crate::compiler) use cons::{
52
    compile_pair_chain, push_anyref_arm, push_anyref_car, push_constant_arm,
53
};
54
pub(in crate::compiler) use infer::{chain_pair_element, literal_pair_element, runtime_cell_slot};
55
pub(in crate::compiler::native) use search::NATIVES as SEARCH_NATIVES;
56

            
57
/// The function expression FOLD should apply per element. If `fn_arg` resolves
58
/// to a let-bound closure whose source body was recorded, returns that
59
/// `(lambda …)` so FOLD INLINES it — binding each parameter to the actual
60
/// element/accumulator type — instead of `call_ref`ing the closure's fixed
61
/// (Ratio-default) signature, which mismatches a non-Ratio element list.
62
/// Otherwise returns `fn_arg` unchanged (an inline lambda already types from its
63
/// args; a non-recoverable runtime closure keeps `call_ref`).
64
///
65
/// FOLD-only on purpose: MAP / FILTER build a fresh result list whose element
66
/// type the eval surface sizes from the closure SIG, so inlining there (which
67
/// re-types per the actual element) drifts the eval-vs-codegen element type.
68
/// They keep the `call_ref` path, relying on `param_infer` to pin non-Ratio
69
/// params (a non-pinnable non-Ratio closure surfaces a clean type error there).
70
///
71
/// The body was vetted capture-free against its CREATION scope; inlining
72
/// recompiles it under THIS (fold-site) symbol table, so a global the body uses
73
/// (`+`, `cons`, …) that an inner binder has since shadowed would resolve to the
74
/// shadow instead of the creation-site definition the emitted closure used. Re-
75
/// run the capture-free check against the fold-site table: a now-shadowed global
76
/// resolves to a `Variable` here and fails it, so we keep `call_ref` (which calls
77
/// the closure value compiled at creation) — correct, not inlined-wrong.
78
12106
fn inline_closure_fn(symbols: &mut SymbolTable, fn_arg: &Expr) -> Result<Expr> {
79
12106
    if let Some((place, WasmType::Closure(_))) = eval_value(symbols, fn_arg)?.place()
80
4185
        && let Some((params, body)) = symbols.closure_body(place)
81
3350
        && crate::compiler::special::is_capture_free(symbols, params, body)
82
    {
83
3350
        return Ok(Expr::Lambda(params.clone(), Box::new(body.clone())));
84
8756
    }
85
8756
    Ok(fn_arg.clone())
86
12106
}
87

            
88
/// The signature of the closure `closure` evaluated to, unless a source is
89
/// recorded for it: a closure with a source is typed as that source, on both
90
/// surfaces, and only a sourceless one by its signature.
91
44813
pub(super) fn sourceless_closure_sig(
92
44813
    symbols: &SymbolTable,
93
44813
    closure: &Expr,
94
44813
) -> Option<ClosureSigId> {
95
44813
    let WasmType::Closure(sig) = closure.wasm_type()? else {
96
624
        return None;
97
    };
98
14688
    let sourced = closure
99
14688
        .place()
100
14688
        .is_some_and(|(place, _)| symbols.closure_body(place).is_some());
101
14688
    (!sourced).then_some(sig)
102
44813
}
103

            
104
/// Materializes a resolved constant list's `members` as a `$pair` chain with
105
/// cells of `elem`, for a consumer whose source form (e.g. a let-bound list
106
/// symbol) does not itself lower to a chain.
107
44145
pub(in crate::compiler) fn compile_constant_list(
108
44145
    ctx: &mut CompileContext,
109
44145
    emit: &mut FunctionEmitter,
110
44145
    symbols: &mut SymbolTable,
111
44145
    members: Vec<Expr>,
112
44145
    elem: PairElement,
113
44145
) -> Result<WasmType> {
114
44145
    cons::emit_constant_chain(ctx, emit, symbols, members, elem)?;
115
43937
    Ok(WasmType::PairRef(elem))
116
44145
}
117

            
118
pub(in crate::compiler::native) const NATIVES: &[NativeSpec] = &[
119
    NativeSpec {
120
        name: "LIST",
121
        eval: list_fn::list,
122
        stack: Some(list_fn::compile_list_to_stack),
123
        effect: Some(list_fn::compile_list),
124
    },
125
    NativeSpec {
126
        name: "CONS",
127
        eval: cons::cons,
128
        stack: Some(cons::compile_cons_to_stack),
129
        effect: Some(cons::compile_cons),
130
    },
131
    NativeSpec {
132
        name: "CAR",
133
        eval: car_cdr::car,
134
        stack: Some(car_cdr::compile_car_to_stack),
135
        effect: Some(car_cdr::compile_car),
136
    },
137
    NativeSpec {
138
        name: "CDR",
139
        eval: car_cdr::cdr,
140
        stack: Some(car_cdr::compile_cdr_to_stack),
141
        effect: Some(car_cdr::compile_cdr),
142
    },
143
    NativeSpec {
144
        name: "MAP",
145
        eval: map::map_fn,
146
        stack: Some(map::compile_map_to_stack),
147
        effect: Some(map::compile_map),
148
    },
149
    NativeSpec {
150
        name: "FILTER",
151
        eval: filter::filter,
152
        stack: Some(filter::compile_filter_to_stack),
153
        effect: Some(filter::compile_filter),
154
    },
155
    NativeSpec {
156
        name: "FOLD",
157
        eval: fold::fold,
158
        stack: Some(fold::compile_fold_to_stack),
159
        effect: Some(fold::compile_fold),
160
    },
161
    NativeSpec {
162
        name: "REVERSE",
163
        eval: reverse::reverse,
164
        stack: Some(reverse::compile_reverse_to_stack),
165
        effect: Some(reverse::compile_reverse),
166
    },
167
    NativeSpec {
168
        name: "LENGTH",
169
        eval: length::length,
170
        stack: Some(length::compile_length_to_stack),
171
        effect: Some(length::compile_length),
172
    },
173
    NativeSpec {
174
        name: "APPEND",
175
        eval: append::append,
176
        stack: Some(append::compile_append_to_stack),
177
        effect: Some(append::compile_append),
178
    },
179
    NativeSpec {
180
        name: "PAIR?",
181
        eval: pair_p::pair_p,
182
        stack: Some(pair_p::compile_pair_p_to_stack),
183
        effect: Some(pair_p::compile_pair_p),
184
    },
185
];