1
//! `REVERSE` — produce the input list in reversed order. Constant-folds
2
//! when the input is a compile-time list literal; for runtime
3
//! `PairRef(elem)` chains, walks the input cell-by-cell building a fresh
4
//! reversed chain via the `pair_new` helper.
5

            
6
use crate::ast::{Expr, PairElement, WasmType};
7
use crate::compiler::context::CompileContext;
8
use crate::compiler::emit::FunctionEmitter;
9
use crate::compiler::expr::{
10
    compile_for_stack, eval_value, fold_call, format_expr, serialize_stack_to_output,
11
};
12
use crate::error::{Error, Result};
13
use crate::runtime::SymbolTable;
14

            
15
use super::car_cdr::{coerce_anyref_to_pair, reject_non_list};
16
use super::datum::{compile_folded_to_stack, emit_folded_output};
17

            
18
2303
pub(super) fn reverse(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
19
2303
    if args.len() != 1 {
20
1
        return Err(Error::Arity {
21
1
            name: "REVERSE".to_string(),
22
1
            expected: 1,
23
1
            actual: args.len(),
24
1
        });
25
2302
    }
26
2302
    let arg = eval_value(symbols, &args[0])?;
27
2302
    match arg.wasm_type() {
28
9
        Some(WasmType::PairRef(elem)) => return Ok(Expr::WasmRuntime(WasmType::PairRef(elem))),
29
        Some(WasmType::AnyRef) => {
30
            return Ok(Expr::WasmRuntime(WasmType::PairRef(PairElement::AnyRef)));
31
        }
32
2293
        _ => {}
33
    }
34
2293
    let elements = match arg {
35
417
        Expr::Nil => return Ok(Expr::Nil),
36
        Expr::List(elems) => elems,
37
1458
        Expr::Datum(inner) => match *inner {
38
1458
            Expr::List(elems) => elems,
39
            Expr::Nil => return Ok(Expr::Nil),
40
            other => {
41
                return Err(Error::Compile(format!(
42
                    "REVERSE expects a list, got {}",
43
                    format_expr(&other)
44
                )));
45
            }
46
        },
47
        other => {
48
418
            return Err(Error::Compile(format!(
49
418
                "REVERSE expects a list, got {}",
50
418
                format_expr(&other)
51
418
            )));
52
        }
53
    };
54
1458
    let reversed: Vec<Expr> = elements.into_iter().rev().collect();
55
1458
    Ok(Expr::quoted_list(reversed))
56
2303
}
57

            
58
1248
pub(super) fn compile_reverse(
59
1248
    ctx: &mut CompileContext,
60
1248
    emit: &mut FunctionEmitter,
61
1248
    symbols: &mut SymbolTable,
62
1248
    args: &[Expr],
63
1248
) -> Result<()> {
64
1248
    check_arity(args)?;
65
1248
    if let Some(folded) = fold_call(symbols, "REVERSE", args)? {
66
832
        return emit_folded_output(ctx, emit, symbols, folded);
67
416
    }
68
416
    let ty = compile_reverse_runtime(ctx, emit, symbols, &args[0])?;
69
416
    serialize_stack_to_output(ctx, emit, ty)
70
1248
}
71

            
72
2707
fn check_arity(args: &[Expr]) -> Result<()> {
73
2707
    if args.len() == 1 {
74
2707
        return Ok(());
75
    }
76
    Err(Error::Arity {
77
        name: "REVERSE".to_string(),
78
        expected: 1,
79
        actual: args.len(),
80
    })
81
2707
}
82

            
83
1459
pub(super) fn compile_reverse_to_stack(
84
1459
    ctx: &mut CompileContext,
85
1459
    emit: &mut FunctionEmitter,
86
1459
    symbols: &mut SymbolTable,
87
1459
    args: &[Expr],
88
1459
) -> Result<WasmType> {
89
1459
    check_arity(args)?;
90
1459
    if let Some(folded) = fold_call(symbols, "REVERSE", args)? {
91
832
        return compile_folded_to_stack(ctx, emit, symbols, folded);
92
627
    }
93
627
    compile_reverse_runtime(ctx, emit, symbols, &args[0])
94
1459
}
95

            
96
1043
fn compile_reverse_runtime(
97
1043
    ctx: &mut CompileContext,
98
1043
    emit: &mut FunctionEmitter,
99
1043
    symbols: &mut SymbolTable,
100
1043
    arg: &Expr,
101
1043
) -> Result<WasmType> {
102
1043
    let elem = match compile_for_stack(ctx, emit, symbols, arg)? {
103
419
        WasmType::PairRef(e) => e,
104
        WasmType::AnyRef => {
105
208
            coerce_anyref_to_pair(ctx, emit)?;
106
208
            PairElement::AnyRef
107
        }
108
416
        other => return reject_non_list(ctx, emit, symbols, "REVERSE", arg, other),
109
    };
110
627
    emit_reverse_from_stack(ctx, emit, elem)?;
111
627
    Ok(WasmType::PairRef(elem))
112
1043
}
113

            
114
/// Walks `list_expr` cell by cell, prepending each car onto a fresh
115
/// accumulator chain, and leaves the reversed chain on the wasm stack.
116
7098
pub(in crate::compiler::native::list) fn emit_reverse_loop(
117
7098
    ctx: &mut CompileContext,
118
7098
    emit: &mut FunctionEmitter,
119
7098
    symbols: &mut SymbolTable,
120
7098
    list_expr: &Expr,
121
7098
    elem: PairElement,
122
7098
) -> Result<()> {
123
7098
    let arg_ty = compile_for_stack(ctx, emit, symbols, list_expr)?;
124
7098
    if matches!(arg_ty, WasmType::AnyRef) {
125
        coerce_anyref_to_pair(ctx, emit)?;
126
7098
    }
127
7098
    emit_reverse_from_stack(ctx, emit, elem)
128
7098
}
129

            
130
/// Reverses the `$pair` chain on top of the stack. The accumulator starts
131
/// as a null `$pair` ref and is rebuilt every iteration via
132
/// `pair_new(car, acc)`.
133
7725
fn emit_reverse_from_stack(
134
7725
    ctx: &mut CompileContext,
135
7725
    emit: &mut FunctionEmitter,
136
7725
    elem: PairElement,
137
7725
) -> Result<()> {
138
7725
    let pair_idx = ctx.ids.ty_pair;
139
7725
    let pair_local = ctx.alloc_local(WasmType::PairRef(elem))?;
140
7725
    let acc_local = ctx.alloc_local(WasmType::PairRef(elem))?;
141
7725
    emit.local_set(pair_local);
142

            
143
7725
    emit.ref_null(pair_idx);
144
7725
    emit.local_set(acc_local);
145

            
146
7725
    emit.block_start();
147
7725
    emit.loop_start();
148

            
149
7725
    emit.local_get(pair_local);
150
7725
    emit.ref_is_null();
151
7725
    emit.br_if(1);
152

            
153
    // pair_new expects (anyref car, ref null $pair cdr). The car comes
154
    // straight off the input pair as anyref — no downcast needed since
155
    // we're rebuilding into a fresh pair of the same element type.
156
7725
    emit.local_get(pair_local);
157
7725
    emit.struct_get(pair_idx, 0);
158
7725
    emit.local_get(acc_local);
159
7725
    emit.call(ctx.ids.pair_new);
160
7725
    emit.local_set(acc_local);
161

            
162
7725
    emit.local_get(pair_local);
163
7725
    emit.struct_get(pair_idx, 1);
164
7725
    emit.local_set(pair_local);
165

            
166
7725
    emit.br(0);
167
7725
    emit.block_end()?;
168
7725
    emit.block_end()?;
169

            
170
7725
    emit.local_get(acc_local);
171
7725
    Ok(())
172
7725
}