1
use super::super::context::CompileContext;
2
use super::super::emit::FunctionEmitter;
3
use super::super::expr::{
4
    classify_stack_type, compile_for_effect, compile_for_stack, compile_nil, emit_box_anyref,
5
    eval_value, fold_value, format_datum, format_expr, is_instance_leaf, list_datum_members,
6
    probe_value, quoted_datum,
7
};
8
use super::NativeSpec;
9
use crate::ast::{Expr, WasmType};
10
use crate::error::Result;
11
use crate::runtime::SymbolTable;
12
use wasm_encoder::BlockType;
13

            
14
pub(super) const NATIVES: &[NativeSpec] = &[
15
    NativeSpec {
16
        name: "DEBUG",
17
        eval: debug_call,
18
        stack: Some(compile_debug_to_stack),
19
        effect: Some(compile_debug),
20
    },
21
    NativeSpec {
22
        name: "PRINT",
23
        eval: print_call,
24
        stack: Some(compile_print_to_stack),
25
        effect: None,
26
    },
27
    NativeSpec {
28
        name: "DISPLAY",
29
        eval: print_call,
30
        stack: Some(compile_display_to_stack),
31
        effect: None,
32
    },
33
    NativeSpec {
34
        name: "NEWLINE",
35
        eval: newline_call,
36
        stack: Some(compile_newline_to_stack),
37
        effect: Some(compile_newline),
38
    },
39
];
40

            
41
const SCRATCH_OFFSET: u32 = 0;
42
/// The staging area ends where the script's input begins.
43
const SCRATCH_SIZE: usize = scripting_format::BASE_OFFSET as usize;
44

            
45
// The textual-output natives have a side effect (host `log`), so their eval
46
// handlers must NOT fold to a pure `Expr::Nil` — a constant return lets the
47
// `and`/`or` short-circuit folder (and effect-position constant elision) drop
48
// the call entirely, silently losing the output. Returning a `WasmRuntime`
49
// truth-value placeholder forces every consumer down the runtime path so the
50
// side effect is always emitted. The runtime value is nil-typed (`Bool`,
51
// serializing as Nil) — these forms evaluate to nil.
52

            
53
832
pub(super) fn debug_call(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
54
    // Eval is pure classification — it must NOT perform I/O. The type-inference
55
    // probe (`infer_wasm_type`) evaluates pure-native forms on a cloned table
56
    // for sizing; logging here would emit compile-time output (and leak the
57
    // message) during mere type analysis. The actual `[script]` log is emitted
58
    // by the codegen handler (`compile_debug_effect` → host `log`), exactly
59
    // like PRINT / NEWLINE. Eval only validates args and yields the nil-typed
60
    // runtime placeholder.
61
832
    for arg in args {
62
832
        eval_value(symbols, arg)?;
63
    }
64
832
    Ok(Expr::WasmRuntime(WasmType::Bool))
65
832
}
66

            
67
/// PRINT answers its last argument (CL PRINT returns its object), typed as
68
/// `compile_print_to_stack` pushes it; never a constant, so the log is kept.
69
/// A lambda answers `AnyRef`: eval cannot see the signature codegen interns.
70
52231
pub(super) fn print_call(symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
71
52231
    let mut answer = WasmType::Bool;
72
52231
    for arg in args {
73
52231
        let value = eval_value(symbols, arg)?;
74
52231
        answer = match value.wasm_type() {
75
52231
            _ if is_lambda(&value) => WasmType::AnyRef,
76
698
            Some(ty) => ty,
77
47722
            None if has_runtime_value(&value) => {
78
47722
                classify_stack_type(&value).unwrap_or(WasmType::Bool)
79
            }
80
            None => WasmType::Bool,
81
        };
82
    }
83
52231
    Ok(Expr::WasmRuntime(answer))
84
52231
}
85

            
86
4
pub(super) fn newline_call(_symbols: &mut SymbolTable, args: &[Expr]) -> Result<Expr> {
87
4
    if !args.is_empty() {
88
        return Err(crate::error::Error::Arity {
89
            name: "NEWLINE".to_string(),
90
            expected: 0,
91
            actual: args.len(),
92
        });
93
4
    }
94
4
    Ok(Expr::WasmRuntime(WasmType::Bool))
95
4
}
96

            
97
/// Emits `log` calls for the joined printed forms — constant text goes out
98
/// through the host `log` channel. A message longer
99
/// than the staging area goes out in consecutive pieces, so staging never
100
/// reaches the input headers.
101
51993
pub(in crate::compiler) fn emit_log_text(
102
51993
    ctx: &mut CompileContext,
103
51993
    emit: &mut FunctionEmitter,
104
51993
    text: &str,
105
51993
) -> Result<()> {
106
51993
    for piece in scratch_pieces(text) {
107
52825
        let data_idx = ctx.add_data(piece.as_bytes())?;
108
52825
        let len = piece.len() as u32;
109
52825
        emit.memory_init(data_idx, SCRATCH_OFFSET, len);
110
52825
        emit.i32_const(0);
111
52825
        emit.i32_const(SCRATCH_OFFSET as i32);
112
52825
        emit.i32_const(len as i32);
113
52825
        emit.call(ctx.ids.log);
114
    }
115
51993
    Ok(())
116
51993
}
117

            
118
/// Splits `text` on char boundaries into pieces that fit the staging area; an
119
/// empty text is one empty piece, so it still reaches the host.
120
51997
fn scratch_pieces(text: &str) -> Vec<&str> {
121
51997
    let mut pieces = Vec::new();
122
51997
    let mut rest = text;
123
    loop {
124
52832
        let (piece, tail) = rest.split_at(rest.floor_char_boundary(SCRATCH_SIZE));
125
52832
        pieces.push(piece);
126
52832
        rest = tail;
127
52832
        if rest.is_empty() {
128
51997
            return pieces;
129
835
        }
130
    }
131
51997
}
132

            
133
628
pub(super) fn compile_newline(
134
628
    ctx: &mut CompileContext,
135
628
    emit: &mut FunctionEmitter,
136
628
    symbols: &mut SymbolTable,
137
628
    args: &[Expr],
138
628
) -> Result<()> {
139
628
    compile_newline_effect(ctx, emit, symbols, args)?;
140
418
    compile_nil(ctx, emit)?;
141
418
    Ok(())
142
628
}
143

            
144
// Stack-position handlers: emit the `log` side effect and leave the form's
145
// value on the operand stack — nil for NEWLINE and DEBUG, the printed argument
146
// for PRINT / DISPLAY. Used when these forms appear as a subexpression, e.g.
147
// an `and`/`or` operand or a `let` init.
148

            
149
/// Value-position PRINT / DISPLAY: logs the printed forms and answers the
150
/// last argument, evaluated once, before the log as CL evaluates it. A value
151
/// with no runtime representation (a lambda, a dotted pair) is
152
/// still printed, but answers nil.
153
19010
pub(super) fn compile_print_to_stack(
154
19010
    ctx: &mut CompileContext,
155
19010
    emit: &mut FunctionEmitter,
156
19010
    symbols: &mut SymbolTable,
157
19010
    args: &[Expr],
158
19010
) -> Result<WasmType> {
159
19010
    print_to_stack(ctx, emit, symbols, args)
160
19010
}
161

            
162
1676
pub(super) fn compile_display_to_stack(
163
1676
    ctx: &mut CompileContext,
164
1676
    emit: &mut FunctionEmitter,
165
1676
    symbols: &mut SymbolTable,
166
1676
    args: &[Expr],
167
1676
) -> Result<WasmType> {
168
1676
    print_to_stack(ctx, emit, symbols, args)
169
1676
}
170

            
171
20686
fn print_to_stack(
172
20686
    ctx: &mut CompileContext,
173
20686
    emit: &mut FunctionEmitter,
174
20686
    symbols: &mut SymbolTable,
175
20686
    args: &[Expr],
176
20686
) -> Result<WasmType> {
177
20686
    match emit_print(ctx, emit, symbols, true, args)? {
178
        Answer::Local(local, ty) => {
179
13701
            emit.local_get(local);
180
13701
            Ok(ty)
181
        }
182
6558
        Answer::Constant(datum) => compile_for_stack(ctx, emit, symbols, &datum),
183
        Answer::Nil => {
184
4
            emit.i32_const(0);
185
4
            Ok(WasmType::Bool)
186
        }
187
    }
188
20686
}
189

            
190
8
pub(super) fn compile_newline_to_stack(
191
8
    ctx: &mut CompileContext,
192
8
    emit: &mut FunctionEmitter,
193
8
    symbols: &mut SymbolTable,
194
8
    args: &[Expr],
195
8
) -> Result<WasmType> {
196
8
    compile_newline_effect(ctx, emit, symbols, args)?;
197
6
    emit.i32_const(0);
198
6
    Ok(WasmType::Bool)
199
8
}
200

            
201
210
pub(super) fn compile_debug_to_stack(
202
210
    ctx: &mut CompileContext,
203
210
    emit: &mut FunctionEmitter,
204
210
    symbols: &mut SymbolTable,
205
210
    args: &[Expr],
206
210
) -> Result<WasmType> {
207
210
    compile_debug_effect(ctx, emit, symbols, args)?;
208
210
    emit.i32_const(0);
209
210
    Ok(WasmType::Bool)
210
210
}
211

            
212
11858
pub(in crate::compiler) fn compile_debug_effect(
213
11858
    ctx: &mut CompileContext,
214
11858
    emit: &mut FunctionEmitter,
215
11858
    symbols: &mut SymbolTable,
216
11858
    args: &[Expr],
217
11858
) -> Result<()> {
218
11858
    emit_print(ctx, emit, symbols, false, args).map(drop)
219
11858
}
220

            
221
/// Effect-position PRINT / DISPLAY: emit the `log` side effect and leave NO
222
/// value on the stack (effect position discards); `effect.rs` dispatches
223
/// these names explicitly (mirrors DEBUG).
224
37348
pub(in crate::compiler) fn compile_print_effect(
225
37348
    ctx: &mut CompileContext,
226
37348
    emit: &mut FunctionEmitter,
227
37348
    symbols: &mut SymbolTable,
228
37348
    args: &[Expr],
229
37348
) -> Result<()> {
230
37348
    emit_print(ctx, emit, symbols, false, args).map(drop)
231
37348
}
232

            
233
210
pub(in crate::compiler) fn compile_display_effect(
234
210
    ctx: &mut CompileContext,
235
210
    emit: &mut FunctionEmitter,
236
210
    symbols: &mut SymbolTable,
237
210
    args: &[Expr],
238
210
) -> Result<()> {
239
210
    emit_print(ctx, emit, symbols, false, args).map(drop)
240
210
}
241

            
242
636
pub(in crate::compiler) fn compile_newline_effect(
243
636
    ctx: &mut CompileContext,
244
636
    emit: &mut FunctionEmitter,
245
636
    _symbols: &mut SymbolTable,
246
636
    args: &[Expr],
247
636
) -> Result<()> {
248
636
    if !args.is_empty() {
249
212
        return Err(crate::error::Error::Arity {
250
212
            name: "NEWLINE".to_string(),
251
212
            expected: 0,
252
212
            actual: args.len(),
253
212
        });
254
424
    }
255
424
    emit_log_text(ctx, emit, "\n")
256
636
}
257

            
258
/// What a PRINT-family call leaves to answer: the last argument's local, a
259
/// constant datum, or nil.
260
enum Answer {
261
    Local(u32, WasmType),
262
    Constant(Expr),
263
    Nil,
264
}
265

            
266
/// How one argument prints: a folded datum, a form whose value has no runtime
267
/// cell (it runs for effect and prints what the evaluator resolves it to), or
268
/// a runtime value.
269
enum Part<'a> {
270
    Datum(Expr),
271
    Resolved(&'a Expr, Expr),
272
    Runtime(&'a Expr),
273
}
274

            
275
128387
fn is_lambda(value: &Expr) -> bool {
276
128387
    matches!(value, Expr::Lambda(_, _))
277
128387
}
278

            
279
76158
fn classify_arg<'a>(symbols: &mut SymbolTable, arg: &'a Expr) -> Result<Part<'a>> {
280
76158
    let folded = fold_value(symbols, arg)?;
281
76158
    if let Some(datum) = folded.filter(|datum| !is_instance_leaf(datum) && !is_lambda(datum)) {
282
57414
        return Ok(Part::Datum(datum));
283
18744
    }
284
18744
    let probed = probe_value(&mut symbols.clone(), arg)?;
285
18742
    if is_lambda(&probed) || has_runtime_value(&probed) {
286
18742
        Ok(Part::Runtime(arg))
287
    } else {
288
        Ok(Part::Resolved(arg, probed))
289
    }
290
76158
}
291

            
292
/// Logs the printed forms of `args` joined with a space, as one message. With
293
/// no runtime argument the text is built at compile time (`(print (list 1
294
/// '(2)))` prints `(1 (2))`, ISS-009). Otherwise the arguments run once, in
295
/// order, and reach the host as one `$pair` list through `env.log_value`; a
296
/// constant among them rides as its pre-printed text, so it prints as it
297
/// always did. Each argument is classified after the earlier ones have been
298
/// compiled, so it sees their effects. `used` keeps the last argument's value
299
/// for the call's answer.
300
70102
fn emit_print(
301
70102
    ctx: &mut CompileContext,
302
70102
    emit: &mut FunctionEmitter,
303
70102
    symbols: &mut SymbolTable,
304
70102
    used: bool,
305
70102
    args: &[Expr],
306
70102
) -> Result<Answer> {
307
70102
    let mut texts = Vec::new();
308
70102
    let mut runtime = false;
309
70102
    let mut answer = Answer::Nil;
310
70102
    for (index, arg) in args.iter().enumerate() {
311
76158
        let keep = used && index + 1 == args.len();
312
76158
        answer = Answer::Nil;
313
76158
        let text = match classify_arg(symbols, arg)? {
314
            Part::Runtime(arg) => {
315
18742
                if !runtime {
316
18531
                    runtime = true;
317
18531
                    for text in texts.drain(..) {
318
3752
                        compile_for_stack(ctx, emit, symbols, &Expr::String(text))?;
319
                    }
320
211
                }
321
18742
                answer = emit_runtime_arg(ctx, emit, symbols, arg, keep)?;
322
18321
                continue;
323
            }
324
            Part::Datum(datum) => {
325
57414
                answer = constant_answer(datum.clone());
326
57414
                printed_form(datum)
327
            }
328
            Part::Resolved(arg, probed) => {
329
                compile_for_effect(ctx, emit, symbols, arg)?;
330
                printed_form(probed)
331
            }
332
        };
333
57414
        if runtime {
334
630
            compile_for_stack(ctx, emit, symbols, &Expr::String(text))?;
335
        } else {
336
56784
            texts.push(text);
337
        }
338
    }
339
69679
    if runtime {
340
18110
        emit_log_value(ctx, emit, args.len())?;
341
    } else {
342
51569
        emit_log_text(ctx, emit, &texts.join(" "))?;
343
    }
344
69679
    Ok(answer)
345
70102
}
346

            
347
/// Compiles a runtime argument and boxes it into its list cell; with `keep`
348
/// it is also stored in a local, as the call's answer.
349
18742
fn emit_runtime_arg(
350
18742
    ctx: &mut CompileContext,
351
18742
    emit: &mut FunctionEmitter,
352
18742
    symbols: &mut SymbolTable,
353
18742
    arg: &Expr,
354
18742
    keep: bool,
355
18742
) -> Result<Answer> {
356
18742
    let ty = compile_for_stack(ctx, emit, symbols, arg)?;
357
18321
    let mut answer = Answer::Nil;
358
18321
    if keep {
359
13701
        let local = ctx.alloc_local(ty)?;
360
13701
        emit.local_set(local);
361
13701
        emit.local_get(local);
362
13701
        answer = Answer::Local(local, ty);
363
4620
    }
364
18321
    emit_box_anyref(ctx, emit, ty);
365
18321
    Ok(answer)
366
18742
}
367

            
368
/// Builds the argument list and prints it; the host answers nonzero for a
369
/// value it cannot read, which raises a catchable `TYPE-ERROR`.
370
18110
fn emit_log_value(
371
18110
    ctx: &mut CompileContext,
372
18110
    emit: &mut FunctionEmitter,
373
18110
    count: usize,
374
18110
) -> Result<()> {
375
18110
    emit.ref_null(ctx.ids.ty_pair);
376
18110
    for _ in 0..count {
377
22495
        emit.call(ctx.ids.pair_new);
378
    }
379
18110
    emit.call(ctx.ids.log_value);
380
18110
    emit.if_block(BlockType::Empty);
381
18110
    emit.call(ctx.ids.not_printable);
382
18110
    emit.block_end()
383
18110
}
384

            
385
57414
fn constant_answer(datum: Expr) -> Answer {
386
57414
    if has_runtime_value(&datum) {
387
57414
        Answer::Constant(datum)
388
    } else {
389
        Answer::Nil
390
    }
391
57414
}
392

            
393
/// Whether PRINT can answer `value`: it has a stack type and holds no datum
394
/// without a runtime cell (a dotted pair, a quasiquote form).
395
/// Walked with an explicit stack, so a deep datum cannot overflow.
396
118825
fn has_runtime_value(value: &Expr) -> bool {
397
118825
    let Some(datum @ (Expr::List(_) | Expr::Cons(_, _))) = quoted_datum(value) else {
398
117971
        return classify_stack_type(value).is_some();
399
    };
400
854
    if list_datum_members(datum).is_none() {
401
        return false;
402
854
    }
403
854
    let mut pending = vec![datum];
404
5092
    while let Some(item) = pending.pop() {
405
4238
        match item {
406
1276
            Expr::List(members) => pending.extend(members),
407
            Expr::Cons(car, cdr) => pending.extend([car.as_ref(), cdr.as_ref()]),
408
            Expr::Number(_)
409
            | Expr::String(_)
410
            | Expr::Symbol(_)
411
            | Expr::Keyword(_)
412
            | Expr::Instance(_, _)
413
            | Expr::Lambda(_, _)
414
            | Expr::T
415
2962
            | Expr::Nil => {}
416
            _ => return false,
417
        }
418
    }
419
854
    true
420
118825
}
421

            
422
57414
fn printed_form(value: Expr) -> String {
423
57414
    match value {
424
1500
        Expr::Datum(datum) => format_datum(&datum),
425
55914
        other => format_expr(&other),
426
    }
427
57414
}
428

            
429
3120
pub(super) fn compile_debug(
430
3120
    ctx: &mut CompileContext,
431
3120
    emit: &mut FunctionEmitter,
432
3120
    symbols: &mut SymbolTable,
433
3120
    args: &[Expr],
434
3120
) -> Result<()> {
435
3120
    compile_debug_effect(ctx, emit, symbols, args)?;
436
3120
    compile_nil(ctx, emit)?;
437
3120
    Ok(())
438
3120
}
439

            
440
#[cfg(test)]
441
#[path = "io_tests.rs"]
442
mod tests;