1
//! `LENGTH` — count the cells of a list. Constant-folds over a list
2
//! literal; for a runtime `PairRef` chain, walks the cells with an i32
3
//! counter. ADR-0028: a length is a count, so the result is an **Index**
4
//! (`I32`) — it composes with Index arithmetic / comparison, and crosses to
5
//! Scalar only via an explicit `(index->scalar …)`.
6

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

            
16
use super::car_cdr::{coerce_anyref_to_pair, throw_unless_nil};
17
use super::map::extract_list_elements;
18

            
19
44485
pub(super) fn length(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
20
44485
    if args.len() != 1 {
21
        return Err(Error::Arity {
22
            name: "LENGTH".to_string(),
23
            expected: 1,
24
            actual: args.len(),
25
        });
26
44485
    }
27
44485
    let arg = eval_value(symbols, &args[0])?;
28
43225
    if matches!(
29
43225
        arg.wasm_type(),
30
        Some(WasmType::PairRef(_) | WasmType::AnyRef)
31
    ) {
32
14240
        return Ok(Expr::WasmRuntime(WasmType::I32));
33
28985
    }
34
28985
    let count = extract_list_elements(&arg)
35
3791
        .map_err(|_| Error::Compile(format!("LENGTH expects a list, got {}", format_expr(&arg))))?
36
        .len();
37
25194
    Ok(Expr::Number(Number::Index(count as i64)))
38
44485
}
39

            
40
5466
pub(super) fn compile_length(
41
5466
    ctx: &mut CompileContext,
42
5466
    emit: &mut FunctionEmitter,
43
5466
    symbols: &mut SymbolTable,
44
5466
    args: &[Expr],
45
5466
) -> Result<()> {
46
5466
    let ty = compile_length_to_stack(ctx, emit, symbols, args)?;
47
5246
    serialize_stack_to_output(ctx, emit, ty)
48
5466
}
49

            
50
/// The count a fold-safe `(length …)` form folds to; `None` when the form
51
/// is compiled — including when LENGTH's own eval errs on a constant that is
52
/// not a list, so the `TYPE-ERROR` is raised at runtime where a handler can
53
/// catch it (0014 obligation (a)).
54
28067
fn fold_length(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Option<i32>> {
55
28067
    match fold_call(symbols, "LENGTH", args)? {
56
10662
        Some(Expr::Number(Number::Index(n))) => i32::try_from(n)
57
10662
            .map(Some)
58
            .map_err(|_| Error::Compile("LENGTH: list length exceeds i32 range".to_string())),
59
17405
        _ => Ok(None),
60
    }
61
28067
}
62

            
63
28067
pub(super) fn compile_length_to_stack(
64
28067
    ctx: &mut CompileContext,
65
28067
    emit: &mut FunctionEmitter,
66
28067
    symbols: &mut SymbolTable,
67
28067
    args: &[Expr],
68
28067
) -> Result<WasmType> {
69
28067
    if args.len() != 1 {
70
        return Err(Error::Arity {
71
            name: "LENGTH".to_string(),
72
            expected: 1,
73
            actual: args.len(),
74
        });
75
28067
    }
76
28067
    if let Some(count) = fold_length(symbols, args)? {
77
10662
        emit.i32_const(count);
78
10662
        return Ok(WasmType::I32);
79
17405
    }
80
17405
    let arg_ty = compile_for_stack(ctx, emit, symbols, &args[0])?;
81
15937
    let elem = match arg_ty {
82
12178
        WasmType::PairRef(elem) => elem,
83
        WasmType::AnyRef => {
84
2291
            coerce_anyref_to_pair(ctx, emit)?;
85
2291
            PairElement::AnyRef
86
        }
87
        other => {
88
1468
            throw_unless_nil(ctx, emit, symbols, "LENGTH", &args[0], other)?;
89
            emit.i32_const(0);
90
            return Ok(WasmType::I32);
91
        }
92
    };
93

            
94
14469
    let pair_idx = ctx.ids.ty_pair;
95
14469
    let pair_local = ctx.alloc_local(WasmType::PairRef(elem))?;
96
14469
    let count_local = ctx.alloc_local(WasmType::I32)?;
97
14469
    emit.local_set(pair_local);
98
14469
    emit.i32_const(0);
99
14469
    emit.local_set(count_local);
100

            
101
14469
    emit.block_start();
102
14469
    emit.loop_start();
103

            
104
14469
    emit.local_get(pair_local);
105
14469
    emit.ref_is_null();
106
14469
    emit.br_if(1);
107

            
108
14469
    emit.local_get(count_local);
109
14469
    emit.i32_const(1);
110
14469
    emit.i32_add();
111
14469
    emit.local_set(count_local);
112

            
113
14469
    emit.local_get(pair_local);
114
14469
    emit.struct_get(pair_idx, 1);
115
14469
    emit.local_set(pair_local);
116

            
117
14469
    emit.br(0);
118
14469
    emit.block_end()?;
119
14469
    emit.block_end()?;
120

            
121
14469
    emit.local_get(count_local);
122
14469
    Ok(WasmType::I32)
123
28067
}