1
//! `APPEND` — concatenate lists left to right. Constant-folds when every
2
//! argument is a compile-time list; otherwise lowers the two-list runtime
3
//! case by reversing the prefix onto an accumulator seeded with the
4
//! suffix chain (so the suffix is shared, not copied).
5

            
6
use wasm_encoder::BlockType;
7

            
8
use crate::ast::{Expr, PairElement, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::datum::bounded;
11
use crate::compiler::emit::FunctionEmitter;
12
use crate::compiler::expr::{
13
    compile_expr, compile_for_stack, describe_operand, eval_value, fold_call, fold_value,
14
    format_expr, probe_value, serialize_stack_to_output,
15
};
16
use crate::error::{Error, Result};
17
use crate::runtime::SymbolTable;
18

            
19
use super::car_cdr::coerce_anyref_to_pair;
20
use super::datum::compile_folded_to_stack;
21
use super::infer::chain_pair_element;
22
use super::map::extract_list_elements;
23

            
24
12629
pub(super) fn append(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
25
25208
    if args.iter().any(|a| {
26
25208
        eval_value(symbols, a)
27
25208
            .map(|r| matches!(r.wasm_type(), Some(WasmType::PairRef(_) | WasmType::AnyRef)))
28
25208
            .unwrap_or(false)
29
25208
    }) {
30
4025
        return Ok(Expr::WasmRuntime(WasmType::PairRef(result_element(
31
4025
            symbols, args,
32
4025
        )?)));
33
8604
    }
34
8604
    let mut out = Vec::new();
35
8604
    for arg in args {
36
17202
        let resolved = eval_value(symbols, arg)?;
37
17202
        out.extend(extract_list_elements(&resolved).map_err(|_| {
38
214
            Error::Compile(format!(
39
214
                "APPEND expects lists, got {}",
40
214
                format_expr(&resolved)
41
214
            ))
42
214
        })?);
43
    }
44
8390
    bounded(symbols, Expr::quoted_list(out))
45
12629
}
46

            
47
/// The element type of a runtime APPEND result: [`chain_pair_element`] over
48
/// every constant list's members plus one placeholder per runtime `PairRef`
49
/// chain, so a constant list is typed exactly as LIST types its cells. An
50
/// empty constant list / nil doesn't constrain the result, and a non-list
51
/// operand contributes nothing: it throws at runtime.
52
9606
fn result_element(symbols: &SymbolTable, args: &[Expr]) -> Result<PairElement> {
53
9606
    let mut members = Vec::new();
54
9606
    let mut probe = symbols.clone();
55
9606
    for arg in args {
56
19212
        let resolved = probe_value(&mut probe, arg)?;
57
19212
        match resolved.wasm_type() {
58
3426
            Some(WasmType::PairRef(e)) => members.push(Expr::WasmRuntime(e.as_wasm_type())),
59
5996
            Some(WasmType::AnyRef) => members.push(Expr::WasmRuntime(WasmType::AnyRef)),
60
9790
            _ => members.extend(extract_list_elements(&resolved).unwrap_or_default()),
61
        }
62
    }
63
9606
    chain_pair_element(&members)
64
9606
}
65

            
66
2295
pub(super) fn compile_append(
67
2295
    ctx: &mut CompileContext,
68
2295
    emit: &mut FunctionEmitter,
69
2295
    symbols: &mut SymbolTable,
70
2295
    args: &[Expr],
71
2295
) -> Result<()> {
72
2295
    if let Some(folded) = fold_call(symbols, "APPEND", args)? {
73
1044
        return compile_expr(ctx, emit, symbols, &folded);
74
1251
    }
75
1251
    let ty = compile_append_runtime(ctx, emit, symbols, args)?;
76
1251
    serialize_stack_to_output(ctx, emit, ty)
77
2295
}
78

            
79
5581
pub(super) fn compile_append_to_stack(
80
5581
    ctx: &mut CompileContext,
81
5581
    emit: &mut FunctionEmitter,
82
5581
    symbols: &mut SymbolTable,
83
5581
    args: &[Expr],
84
5581
) -> Result<WasmType> {
85
5581
    if let Some(folded) = fold_call(symbols, "APPEND", args)? {
86
835
        return compile_folded_to_stack(ctx, emit, symbols, folded);
87
4746
    }
88
4746
    compile_append_runtime(ctx, emit, symbols, args)
89
5581
}
90

            
91
5997
fn compile_append_runtime(
92
5997
    ctx: &mut CompileContext,
93
5997
    emit: &mut FunctionEmitter,
94
5997
    symbols: &mut SymbolTable,
95
5997
    args: &[Expr],
96
5997
) -> Result<WasmType> {
97
5997
    if args.len() != 2 {
98
        // Runtime n-ary APPEND is ISS-082 (WONTFIX).
99
416
        return Err(Error::Compile(
100
416
            "APPEND with a runtime list argument requires exactly 2 lists".to_string(),
101
416
        ));
102
5581
    }
103
5581
    let elem = result_element(symbols, args)?;
104
5581
    let pair_idx = ctx.ids.ty_pair;
105
5581
    let prefix_local = ctx.alloc_local(WasmType::PairRef(elem))?;
106
5581
    let acc_local = ctx.alloc_local(WasmType::PairRef(elem))?;
107

            
108
    // Both operands run, left to right, before either is checked as a list;
109
    // the suffix is the shared tail, and the prefix is prepended onto it in
110
    // reverse.
111
5581
    let first = evaluate_list_arg(ctx, emit, symbols, &args[0], elem)?;
112
5373
    let second = evaluate_list_arg(ctx, emit, symbols, &args[1], elem)?;
113
4749
    validate_list_arg(ctx, emit, first, prefix_local)?;
114
4749
    validate_list_arg(ctx, emit, second, acc_local)?;
115

            
116
4749
    let reversed_local = ctx.alloc_local(WasmType::PairRef(elem))?;
117
4749
    reverse_into(ctx, emit, pair_idx, prefix_local, reversed_local)?;
118
4749
    prepend_reversed(ctx, emit, pair_idx, reversed_local, acc_local)?;
119
4749
    emit.local_get(acc_local);
120
4749
    Ok(WasmType::PairRef(elem))
121
5997
}
122

            
123
/// Walks the reversed prefix, prepending each car onto `acc_local`.
124
4749
fn prepend_reversed(
125
4749
    ctx: &mut CompileContext,
126
4749
    emit: &mut FunctionEmitter,
127
4749
    pair_idx: u32,
128
4749
    reversed_local: u32,
129
4749
    acc_local: u32,
130
4749
) -> Result<()> {
131
4749
    emit.block_start();
132
4749
    emit.loop_start();
133
4749
    emit.local_get(reversed_local);
134
4749
    emit.ref_is_null();
135
4749
    emit.br_if(1);
136
4749
    emit.local_get(reversed_local);
137
4749
    emit.struct_get(pair_idx, 0);
138
4749
    emit.local_get(acc_local);
139
4749
    emit.call(ctx.ids.pair_new);
140
4749
    emit.local_set(acc_local);
141
4749
    emit.local_get(reversed_local);
142
4749
    emit.struct_get(pair_idx, 1);
143
4749
    emit.local_set(reversed_local);
144
4749
    emit.br(0);
145
4749
    emit.block_end()?;
146
4749
    emit.block_end()
147
4749
}
148

            
149
/// An evaluated APPEND operand: its local and, unless it is already a `$pair`
150
/// chain of the result element, the list-like type it was compiled to.
151
struct ListOperand {
152
    local: u32,
153
    ty: Option<WasmType>,
154
}
155

            
156
/// Evaluates an APPEND argument into a local. A constant list is materialized
157
/// into a fresh `$pair` chain whose cells ride the result element `elem` (so a
158
/// concrete result label never covers mismatched cells); anything else is
159
/// compiled, so its effects run. Nothing is checked here.
160
10954
fn evaluate_list_arg(
161
10954
    ctx: &mut CompileContext,
162
10954
    emit: &mut FunctionEmitter,
163
10954
    symbols: &mut SymbolTable,
164
10954
    arg: &Expr,
165
10954
    elem: PairElement,
166
10954
) -> Result<ListOperand> {
167
10954
    if let Some(elements) = fold_value(symbols, arg)?.and_then(|c| extract_list_elements(&c).ok()) {
168
4535
        super::cons::emit_constant_chain(ctx, emit, symbols, elements, elem)?;
169
4535
        let local = ctx.alloc_local(WasmType::PairRef(elem))?;
170
4535
        emit.local_set(local);
171
4535
        return Ok(ListOperand { local, ty: None });
172
6419
    }
173
6419
    let ty = compile_for_stack(ctx, emit, symbols, arg)?;
174
6419
    if !matches!(ty, WasmType::PairRef(_) | WasmType::AnyRef | WasmType::Bool) {
175
835
        emit.drop_value();
176
835
        let got = describe_operand(symbols, arg, ty);
177
835
        emit.reject_if_live(Error::Compile(format!("APPEND expects a list, got {got}")))?;
178
3
        let local = ctx.alloc_local(WasmType::PairRef(elem))?;
179
3
        return Ok(ListOperand { local, ty: None });
180
5584
    }
181
5584
    let local = ctx.alloc_local(ty)?;
182
5584
    emit.local_set(local);
183
5584
    Ok(ListOperand {
184
5584
        local,
185
5584
        ty: Some(ty),
186
5584
    })
187
10954
}
188

            
189
/// Stores an evaluated operand's `$pair` chain in `target`: a nil is the null
190
/// pair, and a runtime `AnyRef` or `Bool` that is no list throws `TYPE-ERROR`.
191
9498
fn validate_list_arg(
192
9498
    ctx: &mut CompileContext,
193
9498
    emit: &mut FunctionEmitter,
194
9498
    operand: ListOperand,
195
9498
    target: u32,
196
9498
) -> Result<()> {
197
9498
    emit.local_get(operand.local);
198
9498
    match operand.ty {
199
7479
        None | Some(WasmType::PairRef(_)) => {}
200
1811
        Some(WasmType::AnyRef) => coerce_anyref_to_pair(ctx, emit)?,
201
208
        Some(WasmType::Bool) => emit_nil_pair_operand(ctx, emit)?,
202
        _ => {}
203
    }
204
9498
    emit.local_set(target);
205
9498
    Ok(())
206
9498
}
207

            
208
/// A bool APPEND operand is the empty list when zero, a `TYPE-ERROR` otherwise.
209
1701
pub(super) fn emit_nil_pair_operand(
210
1701
    ctx: &mut CompileContext,
211
1701
    emit: &mut FunctionEmitter,
212
1701
) -> Result<()> {
213
1701
    let pair_ty = ctx.wasm_val_type(WasmType::PairRef(PairElement::AnyRef))?;
214
1701
    emit.if_block(BlockType::Result(pair_ty));
215
1701
    emit.call(ctx.ids.not_a_list);
216
1701
    emit.unreachable();
217
1701
    emit.else_block();
218
1701
    emit.ref_null(ctx.ids.ty_pair);
219
1701
    emit.block_end()
220
1701
}
221

            
222
/// Reverses the chain in `src_local` into `dst_local` (a fresh null-seeded
223
/// accumulator), consuming `src_local`. Used so APPEND can prepend the
224
/// prefix onto the shared suffix in original order.
225
4749
fn reverse_into(
226
4749
    ctx: &mut CompileContext,
227
4749
    emit: &mut FunctionEmitter,
228
4749
    pair_idx: u32,
229
4749
    src_local: u32,
230
4749
    dst_local: u32,
231
4749
) -> Result<()> {
232
4749
    emit.ref_null(pair_idx);
233
4749
    emit.local_set(dst_local);
234
4749
    emit.block_start();
235
4749
    emit.loop_start();
236
4749
    emit.local_get(src_local);
237
4749
    emit.ref_is_null();
238
4749
    emit.br_if(1);
239
4749
    emit.local_get(src_local);
240
4749
    emit.struct_get(pair_idx, 0);
241
4749
    emit.local_get(dst_local);
242
4749
    emit.call(ctx.ids.pair_new);
243
4749
    emit.local_set(dst_local);
244
4749
    emit.local_get(src_local);
245
4749
    emit.struct_get(pair_idx, 1);
246
4749
    emit.local_set(src_local);
247
4749
    emit.br(0);
248
4749
    emit.block_end()?;
249
4749
    emit.block_end()
250
4749
}