Lines
95.04 %
Functions
92 %
Branches
100 %
use super::super::context::CompileContext;
use super::super::emit::FunctionEmitter;
use super::super::expr::{
classify_stack_type, compile_for_effect, compile_for_stack, compile_nil, emit_box_anyref,
eval_value, fold_value, format_datum, format_expr, is_instance_leaf, list_datum_members,
probe_value, quoted_datum,
};
use super::NativeSpec;
use crate::ast::{Expr, WasmType};
use crate::error::Result;
use crate::runtime::SymbolTable;
use wasm_encoder::BlockType;
pub(super) const NATIVES: &[NativeSpec] = &[
NativeSpec {
name: "DEBUG",
eval: debug_call,
stack: Some(compile_debug_to_stack),
effect: Some(compile_debug),
},
name: "PRINT",
eval: print_call,
stack: Some(compile_print_to_stack),
effect: None,
name: "DISPLAY",
stack: Some(compile_display_to_stack),
name: "NEWLINE",
eval: newline_call,
stack: Some(compile_newline_to_stack),
effect: Some(compile_newline),
];
const SCRATCH_OFFSET: u32 = 0;
/// The staging area ends where the script's input begins.
const SCRATCH_SIZE: usize = scripting_format::BASE_OFFSET as usize;
// The textual-output natives have a side effect (host `log`), so their eval
// handlers must NOT fold to a pure `Expr::Nil` — a constant return lets the
// `and`/`or` short-circuit folder (and effect-position constant elision) drop
// the call entirely, silently losing the output. Returning a `WasmRuntime`
// truth-value placeholder forces every consumer down the runtime path so the
// side effect is always emitted. The runtime value is nil-typed (`Bool`,
// serializing as Nil) — these forms evaluate to nil.
pub(super) fn debug_call(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
// Eval is pure classification — it must NOT perform I/O. The type-inference
// probe (`infer_wasm_type`) evaluates pure-native forms on a cloned table
// for sizing; logging here would emit compile-time output (and leak the
// message) during mere type analysis. The actual `[script]` log is emitted
// by the codegen handler (`compile_debug_effect` → host `log`), exactly
// like PRINT / NEWLINE. Eval only validates args and yields the nil-typed
// runtime placeholder.
for arg in args {
eval_value(symbols, arg)?;
}
Ok(Expr::WasmRuntime(WasmType::Bool))
/// PRINT answers its last argument (CL PRINT returns its object), typed as
/// `compile_print_to_stack` pushes it; never a constant, so the log is kept.
/// A lambda answers `AnyRef`: eval cannot see the signature codegen interns.
pub(super) fn print_call(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
let mut answer = WasmType::Bool;
let value = eval_value(symbols, arg)?;
answer = match value.wasm_type() {
_ if is_lambda(&value) => WasmType::AnyRef,
Some(ty) => ty,
None if has_runtime_value(&value) => {
classify_stack_type(&value).unwrap_or(WasmType::Bool)
None => WasmType::Bool,
Ok(Expr::WasmRuntime(answer))
pub(super) fn newline_call(_symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
if !args.is_empty() {
return Err(crate::error::Error::Arity {
name: "NEWLINE".to_string(),
expected: 0,
actual: args.len(),
});
/// Emits `log` calls for the joined printed forms — constant text goes out
/// through the host `log` channel. A message longer
/// than the staging area goes out in consecutive pieces, so staging never
/// reaches the input headers.
pub(in crate::compiler) fn emit_log_text(
ctx: &mut CompileContext,
emit: &mut FunctionEmitter,
text: &str,
) -> Result<()> {
for piece in scratch_pieces(text) {
let data_idx = ctx.add_data(piece.as_bytes())?;
let len = piece.len() as u32;
emit.memory_init(data_idx, SCRATCH_OFFSET, len);
emit.i32_const(0);
emit.i32_const(SCRATCH_OFFSET as i32);
emit.i32_const(len as i32);
emit.call(ctx.ids.log);
Ok(())
/// Splits `text` on char boundaries into pieces that fit the staging area; an
/// empty text is one empty piece, so it still reaches the host.
fn scratch_pieces(text: &str) -> Vec<&str> {
let mut pieces = Vec::new();
let mut rest = text;
loop {
let (piece, tail) = rest.split_at(rest.floor_char_boundary(SCRATCH_SIZE));
pieces.push(piece);
rest = tail;
if rest.is_empty() {
return pieces;
pub(super) fn compile_newline(
symbols: &mut SymbolTable,
args: &[Expr],
compile_newline_effect(ctx, emit, symbols, args)?;
compile_nil(ctx, emit)?;
// Stack-position handlers: emit the `log` side effect and leave the form's
// value on the operand stack — nil for NEWLINE and DEBUG, the printed argument
// for PRINT / DISPLAY. Used when these forms appear as a subexpression, e.g.
// an `and`/`or` operand or a `let` init.
/// Value-position PRINT / DISPLAY: logs the printed forms and answers the
/// last argument, evaluated once, before the log as CL evaluates it. A value
/// with no runtime representation (a lambda, a dotted pair) is
/// still printed, but answers nil.
pub(super) fn compile_print_to_stack(
) -> Result<WasmType> {
print_to_stack(ctx, emit, symbols, args)
pub(super) fn compile_display_to_stack(
fn print_to_stack(
match emit_print(ctx, emit, symbols, true, args)? {
Answer::Local(local, ty) => {
emit.local_get(local);
Ok(ty)
Answer::Constant(datum) => compile_for_stack(ctx, emit, symbols, &datum),
Answer::Nil => {
Ok(WasmType::Bool)
pub(super) fn compile_newline_to_stack(
pub(super) fn compile_debug_to_stack(
compile_debug_effect(ctx, emit, symbols, args)?;
pub(in crate::compiler) fn compile_debug_effect(
emit_print(ctx, emit, symbols, false, args).map(drop)
/// Effect-position PRINT / DISPLAY: emit the `log` side effect and leave NO
/// value on the stack (effect position discards); `effect.rs` dispatches
/// these names explicitly (mirrors DEBUG).
pub(in crate::compiler) fn compile_print_effect(
pub(in crate::compiler) fn compile_display_effect(
pub(in crate::compiler) fn compile_newline_effect(
_symbols: &mut SymbolTable,
emit_log_text(ctx, emit, "\n")
/// What a PRINT-family call leaves to answer: the last argument's local, a
/// constant datum, or nil.
enum Answer {
Local(u32, WasmType),
Constant(Expr),
Nil,
/// How one argument prints: a folded datum, a form whose value has no runtime
/// cell (it runs for effect and prints what the evaluator resolves it to), or
/// a runtime value.
enum Part<'a> {
Datum(Expr),
Resolved(&'a Expr, Expr),
Runtime(&'a Expr),
fn is_lambda(value: &Expr) -> bool {
matches!(value, Expr::Lambda(_, _))
fn classify_arg<'a>(symbols: &mut SymbolTable, arg: &'a Expr) -> Result<Part<'a>> {
let folded = fold_value(symbols, arg)?;
if let Some(datum) = folded.filter(|datum| !is_instance_leaf(datum) && !is_lambda(datum)) {
return Ok(Part::Datum(datum));
let probed = probe_value(&mut symbols.clone(), arg)?;
if is_lambda(&probed) || has_runtime_value(&probed) {
Ok(Part::Runtime(arg))
} else {
Ok(Part::Resolved(arg, probed))
/// Logs the printed forms of `args` joined with a space, as one message. With
/// no runtime argument the text is built at compile time (`(print (list 1
/// '(2)))` prints `(1 (2))`, ISS-009). Otherwise the arguments run once, in
/// order, and reach the host as one `$pair` list through `env.log_value`; a
/// constant among them rides as its pre-printed text, so it prints as it
/// always did. Each argument is classified after the earlier ones have been
/// compiled, so it sees their effects. `used` keeps the last argument's value
/// for the call's answer.
fn emit_print(
used: bool,
) -> Result<Answer> {
let mut texts = Vec::new();
let mut runtime = false;
let mut answer = Answer::Nil;
for (index, arg) in args.iter().enumerate() {
let keep = used && index + 1 == args.len();
answer = Answer::Nil;
let text = match classify_arg(symbols, arg)? {
Part::Runtime(arg) => {
if !runtime {
runtime = true;
for text in texts.drain(..) {
compile_for_stack(ctx, emit, symbols, &Expr::String(text))?;
answer = emit_runtime_arg(ctx, emit, symbols, arg, keep)?;
continue;
Part::Datum(datum) => {
answer = constant_answer(datum.clone());
printed_form(datum)
Part::Resolved(arg, probed) => {
compile_for_effect(ctx, emit, symbols, arg)?;
printed_form(probed)
if runtime {
texts.push(text);
emit_log_value(ctx, emit, args.len())?;
emit_log_text(ctx, emit, &texts.join(" "))?;
Ok(answer)
/// Compiles a runtime argument and boxes it into its list cell; with `keep`
/// it is also stored in a local, as the call's answer.
fn emit_runtime_arg(
arg: &Expr,
keep: bool,
let ty = compile_for_stack(ctx, emit, symbols, arg)?;
if keep {
let local = ctx.alloc_local(ty)?;
emit.local_set(local);
answer = Answer::Local(local, ty);
emit_box_anyref(ctx, emit, ty);
/// Builds the argument list and prints it; the host answers nonzero for a
/// value it cannot read, which raises a catchable `TYPE-ERROR`.
fn emit_log_value(
count: usize,
emit.ref_null(ctx.ids.ty_pair);
for _ in 0..count {
emit.call(ctx.ids.pair_new);
emit.call(ctx.ids.log_value);
emit.if_block(BlockType::Empty);
emit.call(ctx.ids.not_printable);
emit.block_end()
fn constant_answer(datum: Expr) -> Answer {
if has_runtime_value(&datum) {
Answer::Constant(datum)
Answer::Nil
/// Whether PRINT can answer `value`: it has a stack type and holds no datum
/// without a runtime cell (a dotted pair, a quasiquote form).
/// Walked with an explicit stack, so a deep datum cannot overflow.
fn has_runtime_value(value: &Expr) -> bool {
let Some(datum @ (Expr::List(_) | Expr::Cons(_, _))) = quoted_datum(value) else {
return classify_stack_type(value).is_some();
if list_datum_members(datum).is_none() {
return false;
let mut pending = vec![datum];
while let Some(item) = pending.pop() {
match item {
Expr::List(members) => pending.extend(members),
Expr::Cons(car, cdr) => pending.extend([car.as_ref(), cdr.as_ref()]),
Expr::Number(_)
| Expr::String(_)
| Expr::Symbol(_)
| Expr::Keyword(_)
| Expr::Instance(_, _)
| Expr::Lambda(_, _)
| Expr::T
| Expr::Nil => {}
_ => return false,
true
fn printed_form(value: Expr) -> String {
match value {
Expr::Datum(datum) => format_datum(&datum),
other => format_expr(&other),
pub(super) fn compile_debug(
#[cfg(test)]
#[path = "io_tests.rs"]
mod tests;