1
//! Shared lowering for a const-folded list-native result at value position.
2
//!
3
//! CAR/CDR/REVERSE/CONS/APPEND all const-fold a constant (or quoted) list
4
//! argument on the eval path; the folded result may be a self-evaluating atom, a
5
//! quoted tail, or a bare datum (`Symbol` / `List` / `Cons`) extracted from a
6
//! quoted source. A bare datum is DATA, not code, so it is re-quoted and lowered
7
//! by `compile_for_stack`'s quoted-datum arm: a list as its `$pair` chain, a
8
//! symbol as its printed `StringRef`.
9

            
10
use crate::ast::{Expr, WasmType};
11
use crate::compiler::context::CompileContext;
12
use crate::compiler::emit::FunctionEmitter;
13
use crate::compiler::expr::{compile_expr, compile_for_stack, serialize_stack_to_output};
14
use crate::error::Result;
15
use crate::runtime::SymbolTable;
16

            
17
/// Whether a const-folded result is quoted DATA (must lower as a datum)
18
/// rather than code/an atom: a bare `Symbol` / `List` / `Cons` extracted from a
19
/// quoted source, or a `Datum` value.
20
#[must_use]
21
7946
pub(super) fn is_datum_result(result: &Expr) -> bool {
22
7946
    matches!(
23
7946
        result,
24
        Expr::Symbol(_) | Expr::List(_) | Expr::Cons(_, _) | Expr::Datum(_)
25
    )
26
7946
}
27

            
28
/// Lowers a const-folded list-native result to a single clean stack value.
29
15984
pub(super) fn compile_folded_to_stack(
30
15984
    ctx: &mut CompileContext,
31
15984
    emit: &mut FunctionEmitter,
32
15984
    symbols: &mut SymbolTable,
33
15984
    folded: Expr,
34
15984
) -> Result<WasmType> {
35
15984
    match folded {
36
        datum @ (Expr::Symbol(_) | Expr::List(_) | Expr::Cons(_, _)) => {
37
            compile_for_stack(ctx, emit, symbols, &Expr::quoted(datum))
38
        }
39
15984
        other => compile_for_stack(ctx, emit, symbols, &other),
40
    }
41
15984
}
42

            
43
/// Emits a const-folded list-native result to the output: a datum renders as
44
/// DATA, an atom lowers as itself.
45
4180
pub(super) fn emit_folded_output(
46
4180
    ctx: &mut CompileContext,
47
4180
    emit: &mut FunctionEmitter,
48
4180
    symbols: &mut SymbolTable,
49
4180
    folded: Expr,
50
4180
) -> Result<()> {
51
4180
    if is_datum_result(&folded) {
52
2094
        let ty = compile_folded_to_stack(ctx, emit, symbols, folded)?;
53
2094
        return serialize_stack_to_output(ctx, emit, ty);
54
2086
    }
55
2086
    compile_expr(ctx, emit, symbols, &folded)
56
4180
}