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, Fraction, WasmType};
8
use crate::compiler::context::CompileContext;
9
use crate::compiler::emit::FunctionEmitter;
10
use crate::compiler::expr::{
11
    compile_expr, compile_for_stack, eval_value, format_expr, serialize_stack_to_output,
12
};
13
use crate::error::{Error, Result};
14
use crate::runtime::SymbolTable;
15

            
16
use super::map::extract_list_elements;
17

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

            
36
142
pub(super) fn compile_length(
37
142
    ctx: &mut CompileContext,
38
142
    emit: &mut FunctionEmitter,
39
142
    symbols: &mut SymbolTable,
40
142
    args: &[Expr],
41
142
) -> Result<()> {
42
142
    let folded = length(symbols, args)?;
43
142
    if folded.is_wasm_runtime() {
44
71
        let ty = compile_length_to_stack(ctx, emit, symbols, args)?;
45
71
        return serialize_stack_to_output(ctx, emit, ty);
46
71
    }
47
71
    compile_expr(ctx, emit, symbols, &folded)
48
142
}
49

            
50
781
pub(super) fn compile_length_to_stack(
51
781
    ctx: &mut CompileContext,
52
781
    emit: &mut FunctionEmitter,
53
781
    symbols: &mut SymbolTable,
54
781
    args: &[Expr],
55
781
) -> Result<WasmType> {
56
781
    if args.len() != 1 {
57
        return Err(Error::Arity {
58
            name: "LENGTH".to_string(),
59
            expected: 1,
60
            actual: args.len(),
61
        });
62
781
    }
63
781
    let resolved = eval_value(symbols, &args[0])?;
64
781
    let elem = match resolved.wasm_type() {
65
781
        Some(WasmType::PairRef(e)) => e,
66
        _ => {
67
            // Constant list folds to its count (an Index) straight onto the stack.
68
            let count = extract_list_elements(&resolved).map_err(|_| {
69
                Error::Compile(format!(
70
                    "LENGTH expects a list, got {}",
71
                    format_expr(&resolved)
72
                ))
73
            })?;
74
            let count = i32::try_from(count.len())
75
                .map_err(|_| Error::Compile("LENGTH: list length exceeds i32 range".to_string()))?;
76
            emit.i32_const(count);
77
            return Ok(WasmType::I32);
78
        }
79
    };
80

            
81
781
    let pair_idx = ctx.ids.ty_pair;
82
781
    let pair_local = ctx.alloc_local(WasmType::PairRef(elem))?;
83
781
    let count_local = ctx.alloc_local(WasmType::I32)?;
84

            
85
781
    compile_for_stack(ctx, emit, symbols, &args[0])?;
86
781
    emit.local_set(pair_local);
87
781
    emit.i32_const(0);
88
781
    emit.local_set(count_local);
89

            
90
781
    emit.block_start();
91
781
    emit.loop_start();
92

            
93
781
    emit.local_get(pair_local);
94
781
    emit.ref_is_null();
95
781
    emit.br_if(1);
96

            
97
781
    emit.local_get(count_local);
98
781
    emit.i32_const(1);
99
781
    emit.i32_add();
100
781
    emit.local_set(count_local);
101

            
102
781
    emit.local_get(pair_local);
103
781
    emit.struct_get(pair_idx, 1);
104
781
    emit.local_set(pair_local);
105

            
106
781
    emit.br(0);
107
781
    emit.block_end();
108
781
    emit.block_end();
109

            
110
781
    emit.local_get(count_local);
111
781
    Ok(WasmType::I32)
112
781
}