1
//! Top-level `compile_expr` / `compile_quoted_expr` dispatch + the
2
//! `serialize_stack_to_output` helper they hand off to for runtime
3
//! values.
4

            
5
use scripting_format::ValueType;
6
use tracing::debug;
7

            
8
use crate::ast::{Expr, Number, WasmType};
9
use crate::compiler::context::CompileContext;
10
use crate::compiler::emit::FunctionEmitter;
11
use crate::compiler::expr::format_form;
12
use crate::compiler::layout::{GcLocals, MoneyIds};
13
use crate::error::{Error, Result};
14
use crate::runtime::{SymbolTable, Value, with_sufficient_stack};
15

            
16
use super::atoms::{compile_nil, compile_number, compile_string, compile_symbol, compile_t};
17
use super::call::compile_call;
18
use super::eval::resolve_arg;
19
use super::format::{format_expr, format_runtime_value};
20
use super::local_cell::emit_local_read;
21
use super::quasiquote::quasiquote_form;
22
use super::serialize_struct::serialize_struct_to_output;
23
use super::serialize_value::{
24
    serialize_anyref_to_output, serialize_entity_to_output, serialize_list_to_output,
25
    serialize_symbol_to_output,
26
};
27
use super::stack::{compile_for_stack, index_literal};
28
use super::{LOCAL_GC_ARR, LOCAL_IDX, LOCAL_TEMP_I32, LOCAL_TEMP_RATIO};
29

            
30
2970062
pub(in crate::compiler) fn compile_expr(
31
2970062
    ctx: &mut CompileContext,
32
2970062
    emit: &mut FunctionEmitter,
33
2970062
    symbols: &mut SymbolTable,
34
2970062
    expr: &Expr,
35
2970062
) -> Result<()> {
36
2970062
    with_sufficient_stack(|| {
37
2970062
        symbols.charge_work(1)?;
38
2970062
        if compile_literal_expr(ctx, emit, symbols, expr)? {
39
911151
            return Ok(());
40
2058487
        }
41
2058487
        match expr {
42
            Expr::Symbol(name) => {
43
107080
                debug!(symbol = %name, "resolving symbol");
44
107080
                let resolved = resolve_arg(symbols, expr)?;
45
99795
                compile_expr(ctx, emit, symbols, &resolved)
46
            }
47
1892686
            Expr::List(elems) => compile_call(ctx, emit, symbols, elems),
48
            Expr::Quasiquote(inner) => {
49
1691
                let form = quasiquote_form(inner)?;
50
1691
                compile_expr(ctx, emit, symbols, &form)
51
            }
52
            Expr::Unquote(_) | Expr::UnquoteSplicing(_) => {
53
416
                Err(Error::Compile("unquote outside of quasiquote".to_string()))
54
            }
55
            Expr::Lambda(params, body) => {
56
8
                let sig = crate::compiler::special::try_emit_lambda_for_value(
57
8
                    ctx, emit, symbols, params, body,
58
8
                )?
59
8
                .ok_or_else(crate::compiler::special::non_v1_lambda_error)?;
60
                serialize_stack_to_output(ctx, emit, WasmType::Closure(sig))
61
            }
62
            Expr::RuntimeValue(Value::Commodity { .. }) => {
63
                let ty = compile_for_stack(ctx, emit, symbols, expr)?;
64
                serialize_stack_to_output(ctx, emit, ty)
65
            }
66
            Expr::RuntimeValue(val) => compile_string(ctx, emit, &format_runtime_value(val)),
67
            Expr::WasmRuntime(ty) => serialize_stack_to_output(ctx, emit, *ty),
68
            Expr::WasmLocal(idx, ty) => {
69
39438
                emit_local_read(ctx, emit, *idx);
70
39438
                serialize_stack_to_output(ctx, emit, *ty)
71
            }
72
            Expr::WasmGlobal(idx, ty) => {
73
15918
                ctx.emit_global_read(emit, *idx)?;
74
15918
                serialize_stack_to_output(ctx, emit, *ty)
75
            }
76
            Expr::Instance(_, _) => {
77
1248
                let ty = compile_for_stack(ctx, emit, symbols, expr)?;
78
1248
                serialize_stack_to_output(ctx, emit, ty)
79
            }
80
2
            _ => Err(Error::Compile(format!(
81
2
                "unsupported expression: {}",
82
2
                format_form(expr)
83
2
            ))),
84
        }
85
2970062
    })
86
2970062
}
87

            
88
/// Writes a literal or quoted datum to the output; `false`, having emitted
89
/// nothing, when `expr` is not one. The one emitter of output literals.
90
2970062
pub(in crate::compiler) fn compile_literal_expr(
91
2970062
    ctx: &mut CompileContext,
92
2970062
    emit: &mut FunctionEmitter,
93
2970062
    symbols: &mut SymbolTable,
94
2970062
    expr: &Expr,
95
2970062
) -> Result<bool> {
96
2970062
    match expr {
97
        Expr::Nil => {
98
3985
            debug!("compiling nil");
99
3985
            compile_nil(ctx, emit)?;
100
        }
101
        Expr::T => {
102
1674
            debug!("compiling t");
103
1674
            compile_t(ctx, emit)?;
104
        }
105
        Expr::Number(n) => {
106
72397
            debug!(number = ?n, "compiling number");
107
72397
            if let Number::Index(i) = n {
108
68647
                index_literal(*i)?;
109
3750
            }
110
72391
            compile_number(ctx, emit, *n)?;
111
        }
112
        Expr::String(s) => {
113
10006
            debug!(len = s.len(), "compiling string");
114
10006
            compile_string(ctx, emit, s)?;
115
        }
116
        Expr::Keyword(name) => {
117
420
            debug!(keyword = %name, "compiling keyword");
118
420
            compile_symbol(ctx, emit, &format!(":{name}"))?;
119
        }
120
        Expr::Quote(inner) | Expr::Datum(inner) => {
121
823093
            debug!("compiling quote");
122
823093
            compile_quoted_expr(ctx, emit, symbols, inner)?;
123
        }
124
1892686
        Expr::List(elems) if elems.is_empty() => {
125
            debug!("compiling empty list as nil");
126
            compile_nil(ctx, emit)?;
127
        }
128
2058487
        _ => return Ok(false),
129
    }
130
911151
    Ok(true)
131
2970062
}
132

            
133
/// Writes a quoted datum to the output. A list datum rides the one `$pair`
134
/// chain every list value has and is serialized as a list; a symbol or
135
/// keyword is written as a symbol; a quasiquote form as its printed text.
136
823093
pub(in crate::compiler) fn compile_quoted_expr(
137
823093
    ctx: &mut CompileContext,
138
823093
    emit: &mut FunctionEmitter,
139
823093
    symbols: &mut SymbolTable,
140
823093
    inner: &Expr,
141
823093
) -> Result<()> {
142
823093
    match inner {
143
        Expr::Nil => {
144
            compile_nil(ctx, emit)?;
145
            Ok(())
146
        }
147
        Expr::T => {
148
            compile_t(ctx, emit)?;
149
            Ok(())
150
        }
151
        Expr::Number(n) => {
152
            compile_number(ctx, emit, *n)?;
153
            Ok(())
154
        }
155
        Expr::String(s) => compile_string(ctx, emit, s),
156
806671
        Expr::Symbol(s) => compile_symbol(ctx, emit, s),
157
        Expr::Keyword(s) => compile_symbol(ctx, emit, &format!(":{s}")),
158
        Expr::List(_) | Expr::Cons(_, _) => {
159
16420
            let quoted = Expr::quoted(inner.clone());
160
16420
            let ty = compile_for_stack(ctx, emit, symbols, &quoted)?;
161
16004
            serialize_stack_to_output(ctx, emit, ty)
162
        }
163
        Expr::Quasiquote(_) | Expr::Unquote(_) | Expr::UnquoteSplicing(_) => {
164
            compile_string(ctx, emit, &format_expr(inner))
165
        }
166
        Expr::RuntimeValue(_)
167
        | Expr::WasmRuntime(_)
168
        | Expr::WasmLocal(_, _)
169
        | Expr::WasmGlobal(_, _)
170
        | Expr::Instance(_, _) => Err(Error::Compile(
171
            "runtime values cannot be quoted in WASM".to_string(),
172
        )),
173
2
        _ => Err(Error::Compile(format!(
174
2
            "unsupported quoted expression: {}",
175
2
            format_form(inner)
176
2
        ))),
177
    }
178
823093
}
179

            
180
/// The guest handles the money writer reads from `ctx`.
181
198615
pub(super) fn money_ids(ctx: &CompileContext) -> MoneyIds {
182
198615
    MoneyIds {
183
198615
        ty_commodity: ctx.ids.ty_commodity,
184
198615
        ty_unit_term: ctx.ids.ty_unit_term,
185
198615
        assert_atomic: ctx.ids.commodity_assert_atomic,
186
198615
    }
187
198615
}
188

            
189
395507
pub(in crate::compiler) fn serialize_stack_to_output(
190
395507
    ctx: &mut CompileContext,
191
395507
    emit: &mut FunctionEmitter,
192
395507
    ty: WasmType,
193
395507
) -> Result<()> {
194
395507
    let ratio_idx = ctx.ids.ty_ratio;
195
395507
    match ty {
196
        WasmType::Ratio => {
197
20425
            ctx.serializer()
198
20425
                .write_debug_number_from_stack(emit, ratio_idx, LOCAL_TEMP_RATIO)?;
199
        }
200
        WasmType::I32 => {
201
196226
            ctx.serializer()
202
196226
                .write_debug_i32_from_stack(emit, LOCAL_TEMP_I32)?;
203
        }
204
        WasmType::Bool => {
205
            // A runtime truth value: 0 → Nil, nonzero → T, matching the
206
            // const-fold path (a raw I32 above serializes as Number).
207
28233
            ctx.serializer()
208
28233
                .write_debug_bool_from_stack(emit, LOCAL_TEMP_I32)?;
209
        }
210
80869
        WasmType::PairRef(_) => serialize_list_to_output(ctx, emit)?,
211
        WasmType::StringRef => {
212
15010
            let gc = GcLocals {
213
15010
                type_idx: ctx.ids.ty_i8_array,
214
15010
                arr: LOCAL_GC_ARR,
215
15010
                idx: LOCAL_IDX,
216
15010
            };
217
15010
            ctx.serializer()
218
15010
                .write_debug_string_from_stack(emit, ValueType::String, &gc)?;
219
        }
220
1486
        WasmType::SymbolRef => serialize_symbol_to_output(ctx, emit)?,
221
        WasmType::Commodity => {
222
18
            let local = ctx.alloc_local(WasmType::Commodity)?;
223
18
            let ids = money_ids(ctx);
224
18
            ctx.serializer()
225
18
                .write_debug_commodity_from_stack(emit, ids, local)?;
226
        }
227
1282
        WasmType::EntityRef(kind) => serialize_entity_to_output(ctx, emit, kind)?,
228
        WasmType::Closure(sig) => {
229
6884
            let closure_type_idx = ctx.closure_sig(sig)?.closure_type_idx;
230
6884
            ctx.serializer().write_debug_closure_from_stack(
231
6884
                emit,
232
6884
                closure_type_idx,
233
6884
                LOCAL_TEMP_I32,
234
6884
            )?;
235
        }
236
8747
        WasmType::StructRef(_) => serialize_struct_to_output(ctx, emit)?,
237
36327
        WasmType::AnyRef => serialize_anyref_to_output(ctx, emit)?,
238
    }
239
395507
    Ok(())
240
395507
}