1
//! Stack-position codegen.
2
//!
3
//! `compile_for_stack` is the entry — it emits an expression as a
4
//! single wasm stack value and returns the `WasmType` that landed on
5
//! the stack. The two numeric refinements (`compile_ratio_operand`,
6
//! `compile_index_operand`) wrap it for the Scalar / Index dispatch
7
//! in `compiler::native`. Function calls in value position
8
//! route through `compile_call_for_stack` and the symbol-call
9
//! dispatcher below.
10

            
11
use anodized::spec;
12

            
13
use crate::ast::{Expr, Number, WasmType};
14
use crate::compiler::context::CompileContext;
15
use crate::compiler::emit::FunctionEmitter;
16
pub(in crate::compiler) use crate::compiler::join::{NilRepr, nil_repr};
17
use crate::compiler::native::designator_class::is_function_form;
18
use crate::compiler::native::nullable::require_non_null;
19
use crate::compiler::native::{chain_pair_element, compile_constant_list, the_result_type};
20
use crate::compiler::special::{ExpectingForm, is_special_form, reject_non_v1_lambda};
21
use crate::error::{Error, Result, with_article};
22
use crate::runtime::{Head, SymbolTable, Value, with_sufficient_stack};
23

            
24
use super::any_call::compile_any_call;
25
use super::atoms::{emit_nil_default, push_money, push_ratio, push_symbol};
26
use super::call::{
27
    CallTarget, applying_lambda, call_target, compile_lambda_call_for_stack, lift_function_args,
28
};
29
use super::call_runtime::try_compile_runtime_call;
30
use super::effect::compile_for_effect;
31
use super::eval::{call, expand_macro_then, resolve_arg};
32
use super::fold::probe_value;
33
use super::format::{format_expr, not_callable};
34
use super::local_cell::emit_local_read;
35
use super::operand::{compile_index_operand, compile_ratio_operand};
36
use super::printed_datum::{is_printed_datum, render_datum_string};
37
use super::quasiquote::quasiquote_form;
38
use super::respecialise::compile_closure_call_for_stack;
39

            
40
18950389
pub(in crate::compiler) fn compile_for_stack(
41
18950389
    ctx: &mut CompileContext,
42
18950389
    emit: &mut FunctionEmitter,
43
18950389
    symbols: &mut SymbolTable,
44
18950389
    expr: &Expr,
45
18950389
) -> Result<WasmType> {
46
18950389
    with_sufficient_stack(|| {
47
18950389
        symbols.charge_work(1)?;
48
18950388
        ctx.compile_stats_mut().note_stack_compile();
49
18950388
        if let Some(ty) = compile_literal_for_stack(ctx, emit, symbols, expr)? {
50
3187282
            return Ok(ty);
51
15761228
        }
52
15761228
        match expr {
53
            Expr::WasmRuntime(_) => Err(Error::Compile(
54
                "internal: compile_for_stack saw an Expr::WasmRuntime placeholder. \
55
                 A binder failed to promote the runtime value into a WasmLocal \
56
                 (allocate a wasm local, emit the producer expression, local.set) \
57
                 before the symbol was referenced. Check the let / let* / dolist \
58
                 / do / lambda-arg / defvar / defparameter call sites."
59
                    .to_string(),
60
            )),
61
            Expr::WasmLocal(idx, ty) => {
62
3330170
                emit_local_read(ctx, emit, *idx);
63
3330170
                Ok(*ty)
64
            }
65
            Expr::WasmGlobal(idx, ty) => {
66
321916
                ctx.emit_global_read(emit, *idx)?;
67
321916
                Ok(*ty)
68
            }
69
            Expr::Instance(serial, id) => {
70
173890
                let global = ctx.instance_global(*serial)?;
71
173890
                emit.global_get(global);
72
173890
                Ok(WasmType::StructRef(*id))
73
            }
74
            Expr::Symbol(_) => {
75
3387078
                let resolved = resolve_arg(symbols, expr)?;
76
3381856
                compile_for_stack(ctx, emit, symbols, &resolved)
77
            }
78
8547263
            Expr::List(elems) => compile_call_for_stack(ctx, emit, symbols, elems),
79
            Expr::Quasiquote(inner) => {
80
281
                let form = quasiquote_form(inner)?;
81
281
                compile_for_stack(ctx, emit, symbols, &form)
82
            }
83
            _ => {
84
630
                reject_non_v1_lambda(expr)?;
85
418
                Err(Error::Compile(format!(
86
418
                    "cannot compile to WASM stack value: {}",
87
418
                    format_expr(expr)
88
418
                )))
89
            }
90
        }
91
18950389
    })
92
18950389
}
93

            
94
/// [`compile_for_stack`] for a consumer that expects `expected`: a BLOCK or
95
/// IF takes it for the arms still free to adopt it; any other form compiles
96
/// as usual.
97
316084
pub(in crate::compiler) fn compile_for_stack_expecting(
98
316084
    ctx: &mut CompileContext,
99
316084
    emit: &mut FunctionEmitter,
100
316084
    symbols: &mut SymbolTable,
101
316084
    expr: &Expr,
102
316084
    expected: Option<WasmType>,
103
316084
) -> Result<WasmType> {
104
316084
    if let (Some(expected), Some((form, args))) = (expected, ExpectingForm::of(expr)) {
105
118
        return with_sufficient_stack(|| {
106
118
            ctx.compile_stats_mut().note_stack_compile();
107
118
            form.compile(ctx, emit, symbols, args, expected)
108
118
        });
109
315966
    }
110
315966
    compile_for_stack(ctx, emit, symbols, expr)
111
316084
}
112

            
113
/// Pushes a literal or quoted datum and returns its type; `None`, having
114
/// emitted nothing, when `expr` is not one. The one emitter of literals in
115
/// value position.
116
18950604
pub(in crate::compiler) fn compile_literal_for_stack(
117
18950604
    ctx: &mut CompileContext,
118
18950604
    emit: &mut FunctionEmitter,
119
18950604
    symbols: &mut SymbolTable,
120
18950604
    expr: &Expr,
121
18950604
) -> Result<Option<WasmType>> {
122
18950604
    match expr {
123
        // ADR-0028: a dimensionless integer literal defaults to Index (I32).
124
        // Operator/binding sites that need a Scalar coerce it explicitly.
125
2332382
        Expr::Number(n) => push_number(ctx, emit, *n).map(Some),
126
        Expr::RuntimeValue(Value::Commodity {
127
            amount,
128
            commodity_id,
129
        }) => {
130
3953
            push_money(ctx, emit, *amount, *commodity_id);
131
3953
            Ok(Some(WasmType::Commodity))
132
        }
133
        Expr::T => {
134
16980
            emit.i32_const(1);
135
16980
            Ok(Some(WasmType::Bool))
136
        }
137
        Expr::Nil => {
138
10577
            emit.i32_const(0);
139
10577
            Ok(Some(WasmType::Bool))
140
        }
141
8547264
        Expr::List(elems) if elems.is_empty() => {
142
1
            compile_literal_for_stack(ctx, emit, symbols, &Expr::Nil)
143
        }
144
        Expr::String(s) => {
145
720931
            let data_idx = ctx.add_data(s.as_bytes())?;
146
720931
            emit.i32_const(0);
147
720931
            emit.i32_const(s.len() as i32);
148
720931
            emit.array_new_data(ctx.ids.ty_i8_array, data_idx);
149
720931
            Ok(Some(WasmType::StringRef))
150
        }
151
15320
        Expr::Keyword(_) => push_symbol(ctx, emit, &format_expr(expr)).map(Some),
152
        Expr::Quote(_) | Expr::Datum(_) => {
153
89232
            let Some(datum) = quoted_datum(expr) else {
154
                return Ok(None);
155
            };
156
89232
            match (list_datum_members(datum), datum) {
157
                (Some(members), _) => {
158
31888
                    let elem = chain_pair_element(&members)?;
159
31887
                    compile_constant_list(ctx, emit, symbols, members, elem).map(Some)
160
                }
161
1665
                (None, Expr::Cons(_, _)) => Err(no_list_cell_representation(expr)),
162
                (None, Expr::Symbol(_) | Expr::Keyword(_)) => {
163
55254
                    push_symbol(ctx, emit, &format_expr(datum)).map(Some)
164
                }
165
425
                _ if is_printed_datum(expr) => render_datum_string(ctx, emit, datum).map(Some),
166
215
                _ => compile_literal_for_stack(ctx, emit, symbols, datum),
167
            }
168
        }
169
15761228
        _ => Ok(None),
170
    }
171
18950604
}
172

            
173
/// The datum a quote form carries; `''x` carries the list `(QUOTE x)`.
174
/// `None` when `expr` is not a quote form.
175
23772503
pub(in crate::compiler) fn quoted_datum(expr: &Expr) -> Option<&Expr> {
176
23772503
    match expr {
177
504018
        Expr::Quote(inner) | Expr::Datum(inner) => Some(inner),
178
23268485
        _ => None,
179
    }
180
23772503
}
181

            
182
/// The members of a non-empty proper list datum, however it is spelled:
183
/// `(1 2)`, or dotted onto a list or `nil` tail — `(1 . (2 3))`, `(a . nil)`.
184
/// A dotted pair with any other tail, or anything but a list, is `None`.
185
164751
pub(in crate::compiler) fn list_datum_members(datum: &Expr) -> Option<Vec<Expr>> {
186
164751
    match datum {
187
47994
        Expr::List(members) if !members.is_empty() => Some(members.clone()),
188
        Expr::Cons(car, cdr) => {
189
2914
            let mut members = vec![car.as_ref().clone()];
190
2914
            let mut tail = cdr.as_ref();
191
2914
            while let Expr::Cons(next_car, next_cdr) = tail {
192
                members.push(next_car.as_ref().clone());
193
                tail = next_cdr;
194
            }
195
2914
            match tail {
196
832
                Expr::Nil => Some(members),
197
                Expr::List(items) => {
198
416
                    members.extend(items.iter().cloned());
199
416
                    Some(members)
200
                }
201
1666
                _ => None,
202
            }
203
        }
204
113843
        _ => None,
205
    }
206
164751
}
207

            
208
/// The structured rejection of a datum with no `$pair` cell representation:
209
/// a symbol, a dotted pair or a quasiquote inside quoted list data, or a
210
/// dotted pair in value position. The one text for it, wherever it is raised.
211
1669
pub(in crate::compiler) fn no_list_cell_representation(datum: &Expr) -> Error {
212
1669
    Error::Compile(format!(
213
1669
        "cannot compile to WASM stack value: {} has no list cell representation",
214
1669
        format_expr(datum)
215
1669
    ))
216
1669
}
217

            
218
/// A number in its default representation: an integer as an index, anything
219
/// else as a scalar.
220
3082704
pub(in crate::compiler) fn push_number(
221
3082704
    ctx: &CompileContext,
222
3082704
    emit: &mut FunctionEmitter,
223
3082704
    n: Number,
224
3082704
) -> Result<WasmType> {
225
3082704
    match n {
226
        Number::Index(i) => {
227
3041351
            emit.i32_const(index_literal(i)?);
228
3041129
            Ok(WasmType::I32)
229
        }
230
        Number::Scalar(f) => {
231
41353
            push_ratio(ctx, emit, *f.numer(), *f.denom());
232
41353
            Ok(WasmType::Ratio)
233
        }
234
    }
235
3082704
}
236

            
237
/// A numeric literal materialized at `target`, ADR-0028's one sanctioned
238
/// Index↔Scalar crossing: any literal becomes a scalar, only an integer an
239
/// index.
240
7152380
pub(in crate::compiler) fn push_number_as(
241
7152380
    ctx: &CompileContext,
242
7152380
    emit: &mut FunctionEmitter,
243
7152380
    n: Number,
244
7152380
    target: WasmType,
245
7152380
) -> Result<()> {
246
7152380
    match (target, n) {
247
        (WasmType::Ratio, n) => {
248
101178
            let value = n.value();
249
101178
            push_ratio(ctx, emit, *value.numer(), *value.denom());
250
101178
            Ok(())
251
        }
252
        (WasmType::I32, Number::Index(i)) => {
253
7050566
            emit.i32_const(index_literal(i)?);
254
7050566
            Ok(())
255
        }
256
636
        (WasmType::I32, Number::Scalar(_)) => Err(Error::Dimension(
257
636
            "a fractional literal is a scalar, not an index".to_string(),
258
636
        )),
259
        (other, _) => Err(Error::Compile(format!(
260
            "a numeric literal cannot be {} value",
261
            with_article(other)
262
        ))),
263
    }
264
7152380
}
265

            
266
/// The integers an index literal may be: what `box_index` keeps in a `ref.i31`.
267
const INDEX_RANGE: std::ops::RangeInclusive<i64> = -(1 << 30)..=(1 << 30) - 1;
268

            
269
/// An integer literal as an index: the one check of its range.
270
881420392
pub(in crate::compiler) fn index_literal(n: i64) -> Result<i32> {
271
881420392
    i32::try_from(n)
272
881420392
        .ok()
273
881420350
        .filter(|_| INDEX_RANGE.contains(&n))
274
293
        .ok_or_else(|| {
275
293
            Error::Compile(format!(
276
293
                "integer literal {n} is outside the index range -1073741824..1073741823"
277
293
            ))
278
293
        })
279
881420392
}
280

            
281
/// The `WasmType` that [`compile_for_stack`] pushes for a literal or
282
/// already-resolved runtime `expr`, or `None` for a shape whose stack type is
283
/// only known by actually evaluating/emitting it (a call/list, a quote, a
284
/// lambda, …). This is the SINGLE SOURCE OF TRUTH for the compile-time
285
/// "stack-type mirrors" — the eval-side functions that PREDICT a form's stack
286
/// type to size let/do/binding locals or unify branch results. Every such
287
/// mirror routes through this so the prediction can't drift from what codegen
288
/// emits (the class of bug that produced the i32/Bool, list-element, and
289
/// recursion-type mismatches). The classified arms match `compile_for_stack`
290
/// exactly: an integer literal is an Index (`I32`), a fractional literal a
291
/// Scalar (`Ratio`), `t` / `nil` / the empty list are `Bool`, a string literal
292
/// and a printed datum (a quasiquote form) are `StringRef`, a quoted symbol or
293
/// keyword and a bare keyword are `SymbolRef`, a quoted list is the `$pair` chain of its members (its element
294
/// by the LIST rule), a `(quote X)` list form is the same as `'X`, a quoted literal is the literal's type, and a runtime
295
/// placeholder/local carries its own type. A quoted dotted pair whose tail
296
/// is not a list has no stack value (`None`).
297
#[must_use]
298
#[spec(ensures: |output| [
299
8182908
    !matches!(expr, Expr::Number(_) | Expr::T | Expr::Nil | Expr::String(_)) || output.is_some(),
300
8182908
    !is_printed_datum(expr) || output == Some(WasmType::StringRef),
301
8182908
    !matches!(quoted_datum(expr), Some(Expr::Symbol(_) | Expr::Keyword(_))) || output == Some(WasmType::SymbolRef),
302
])]
303
8182908
pub(in crate::compiler) fn classify_stack_type(expr: &Expr) -> Option<WasmType> {
304
8182908
    match expr {
305
1035674
        Expr::WasmRuntime(ty) | Expr::WasmLocal(_, ty) | Expr::WasmGlobal(_, ty) => Some(*ty),
306
23090
        Expr::Instance(_, id) => Some(WasmType::StructRef(*id)),
307
        // ADR-0028: an Index literal is I32, a Scalar literal a dimensionless Ratio.
308
6644631
        Expr::Number(Number::Index(_)) => Some(WasmType::I32),
309
32126
        Expr::Number(Number::Scalar(_)) => Some(WasmType::Ratio),
310
1
        Expr::RuntimeValue(Value::Commodity { .. }) => Some(WasmType::Commodity),
311
152328
        Expr::T | Expr::Nil => Some(WasmType::Bool),
312
32211
        Expr::List(elems) if elems.is_empty() => Some(WasmType::Bool),
313
32210
        Expr::List(elems) => match elems.as_slice() {
314
664
            [Expr::Symbol(head), datum] if head.eq_ignore_ascii_case("QUOTE") => {
315
11
                classify_stack_type(&Expr::quoted(datum.clone()))
316
            }
317
32199
            _ => the_result_type(elems),
318
        },
319
209299
        Expr::String(_) => Some(WasmType::StringRef),
320
17144
        Expr::Keyword(_) => Some(WasmType::SymbolRef),
321
        Expr::Quote(_) | Expr::Datum(_) => {
322
31714
            let datum = quoted_datum(expr)?;
323
31714
            match (list_datum_members(datum), datum) {
324
11975
                (Some(members), _) => chain_pair_element(&members).ok().map(WasmType::PairRef),
325
1
                (None, Expr::Cons(_, _)) => None,
326
19730
                (None, Expr::Symbol(_) | Expr::Keyword(_)) => Some(WasmType::SymbolRef),
327
8
                _ if is_printed_datum(expr) => Some(WasmType::StringRef),
328
6
                _ => classify_stack_type(datum),
329
            }
330
        }
331
4690
        _ => None,
332
    }
333
8182908
}
334

            
335
/// A quoted cons, non-empty list or (un)quasiquoted form: data with no runtime
336
/// value of its own. The single test for that shape.
337
#[must_use]
338
2156705
pub(in crate::compiler) fn is_quoted_datum(expr: &Expr) -> bool {
339
2156705
    match quoted_datum(expr) {
340
4
        Some(Expr::Cons(_, _)) => true,
341
72555
        Some(Expr::List(elems)) => !elems.is_empty(),
342
26668
        Some(_) => is_printed_datum(expr),
343
2057478
        None => false,
344
    }
345
2156705
}
346

            
347
/// Emits `expr` coerced to the `target` wasm type — the type-directed boundary
348
/// primitive for closure args, host-fn args, and accumulator seeds. A nil
349
/// resolves to the target's typed default; a numeric literal coerces across the
350
/// sanctioned Index↔Scalar boundary; everything else must already match. The
351
/// nil/literal probe runs on a clone, so a non-literal that resolves to one
352
/// emits its effects on the live table first.
353
10762170
pub(in crate::compiler) fn compile_for_stack_as(
354
10762170
    ctx: &mut CompileContext,
355
10762170
    emit: &mut FunctionEmitter,
356
10762170
    symbols: &mut SymbolTable,
357
10762170
    expr: &Expr,
358
10762170
    target: WasmType,
359
10762170
) -> Result<()> {
360
10762170
    if matches!(probe_value(&mut symbols.clone(), expr)?, Expr::Nil) {
361
109818
        if !matches!(expr, Expr::Nil) {
362
866
            compile_for_effect(ctx, emit, symbols, expr)?;
363
108952
        }
364
109818
        return emit_nil_default(ctx, emit, target);
365
10652352
    }
366
10652352
    match target {
367
143076
        WasmType::Ratio => compile_ratio_operand(ctx, emit, symbols, expr),
368
9840198
        WasmType::I32 => compile_index_operand(ctx, emit, symbols, expr),
369
        _ => {
370
669078
            let mut ty = compile_for_stack(ctx, emit, symbols, expr)?;
371
669078
            if target == WasmType::StringRef {
372
583913
                ty = string_designator(ctx, emit, ty)?;
373
85165
            }
374
669078
            if ty == target {
375
668751
                return Ok(());
376
327
            }
377
327
            emit.reject_if_live(Error::Compile(format!(
378
327
                "type mismatch: expected {target}, got {ty}"
379
327
            )))
380
        }
381
    }
382
10762170
}
383

            
384
/// The one string-designator coercion: a symbol on the stack becomes its
385
/// name, wherever a string is expected. Any other type passes unchanged.
386
606007
pub(in crate::compiler) fn string_designator(
387
606007
    ctx: &mut CompileContext,
388
606007
    emit: &mut FunctionEmitter,
389
606007
    ty: WasmType,
390
606007
) -> Result<WasmType> {
391
606007
    if ty != WasmType::SymbolRef {
392
604743
        return Ok(ty);
393
1264
    }
394
1264
    require_non_null(ctx, emit, WasmType::SymbolRef, ctx.ids.nil_string)?;
395
1264
    emit.call(ctx.ids.symbol_designator);
396
1264
    Ok(WasmType::StringRef)
397
606007
}
398

            
399
8965384
pub(in crate::compiler) fn compile_call_for_stack(
400
8965384
    ctx: &mut CompileContext,
401
8965384
    emit: &mut FunctionEmitter,
402
8965384
    symbols: &mut SymbolTable,
403
8965384
    elems: &[Expr],
404
8965384
) -> Result<WasmType> {
405
8965384
    let (head, args) = elems
406
8965384
        .split_first()
407
        .ok_or_else(|| Error::Compile("empty function call".to_string()))?;
408
8965384
    match head {
409
8538639
        Expr::Symbol(name) => compile_symbol_call_for_stack(ctx, emit, symbols, name, args),
410
15078
        Expr::Datum(inner) => match inner.as_ref() {
411
15078
            Expr::Symbol(name) if !is_special_form(name) || is_function_form(name) => {
412
15078
                compile_symbol_call_for_stack(ctx, emit, symbols, name, args)
413
            }
414
            _ => {
415
                let result = call(symbols, elems)?;
416
                compile_for_stack(ctx, emit, symbols, &result)
417
            }
418
        },
419
12571
        Expr::Lambda(params, body) => applying_lambda(symbols, head, |symbols| {
420
12569
            compile_lambda_call_for_stack(ctx, emit, symbols, params, body, args, None)
421
12569
        }),
422
        Expr::List(inner) => {
423
349632
            let resolved = call(symbols, inner)?;
424
349416
            match resolved {
425
349412
                Expr::Lambda(params, body) => applying_lambda(symbols, head, |symbols| {
426
349401
                    compile_lambda_call_for_stack(ctx, emit, symbols, &params, &body, args, None)
427
349401
                }),
428
4
                _ => Err(not_callable(head)),
429
            }
430
        }
431
45496
        Expr::WasmLocal(..) | Expr::WasmGlobal(..) => match call_target(head) {
432
            Some(CallTarget::Closure(place, sig)) => {
433
38372
                compile_closure_call_for_stack(ctx, emit, symbols, (place, sig), args)
434
            }
435
6708
            Some(CallTarget::Any(place)) => compile_any_call(ctx, emit, symbols, place, args),
436
416
            None => Err(not_callable(head)),
437
        },
438
        _ => {
439
3968
            let result = call(symbols, elems)?;
440
            compile_for_stack(ctx, emit, symbols, &result)
441
        }
442
    }
443
8965384
}
444

            
445
8553717
fn compile_symbol_call_for_stack(
446
8553717
    ctx: &mut CompileContext,
447
8553717
    emit: &mut FunctionEmitter,
448
8553717
    symbols: &mut SymbolTable,
449
8553717
    name: &str,
450
8553717
    args: &[Expr],
451
8553717
) -> Result<WasmType> {
452
8553717
    match symbols.resolve_head(name) {
453
        Head::Macro(params, body) => {
454
22874
            let (params, body) = (params.clone(), body.clone());
455
22874
            expand_macro_then(symbols, &params, &body, args, |symbols, code| {
456
19055
                compile_for_stack(ctx, emit, symbols, &code)
457
19055
            })
458
        }
459
        Head::Function(params, body) => {
460
338260
            let (params, body) = (params.clone(), body.clone());
461
338260
            let args = &lift_function_args(ctx, emit, symbols, (&params, &body), args)?;
462
            if let Some(ty) =
463
338260
                try_compile_runtime_call(ctx, emit, symbols, name, &params, &body, args)?
464
            {
465
30960
                return Ok(ty);
466
307275
            }
467
307275
            ctx.push_inlining_frame(symbols, name)?;
468
            let result =
469
307272
                compile_lambda_call_for_stack(ctx, emit, symbols, &params, &body, args, Some(name));
470
307272
            ctx.pop_inlining_frame(symbols, name)?;
471
307272
            result
472
        }
473
6358704
        Head::Native => crate::compiler::native::compile_for_stack(ctx, emit, symbols, name, args),
474
        Head::SpecialForm => {
475
1827385
            crate::compiler::special::compile_for_stack(ctx, emit, symbols, name, args)
476
        }
477
6494
        Head::Unknown if symbols.contains(name) => {
478
5
            Err(symbols.not_callable(name, " for stack value"))
479
        }
480
6489
        Head::Unknown => Err(Error::undefined_symbol(name)),
481
    }
482
8553717
}
483

            
484
#[cfg(test)]
485
#[path = "stack_tests.rs"]
486
mod tests;