monkey-wasm 2.0.2

monkey lang parser wasm version
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
mod ast_types;
mod utils;

use crate::utils::set_panic_hook;
use compiler::compiler::Compiler;
use compiler::snapshot::{read_bytecode, write_bytecode};
use compiler::snapshot_layout::describe_bytecode;
use monkey_asm::emitter::AsmDialect;
use monkey_asm::lower::lower_node;
use object::builtins::BuiltIns;
use parser::ast::Node;
use parser::parse as parser_pase;
use parser::validation::validate_program;
use parser::{parse_ast_json_string, parse_ast_lossless_json_string, stringify_integer_literals};
use wasm_bindgen::prelude::*;
use wasm_bindgen::throw_str;

const PLAYGROUND_GC_INSTRUCTION_BUDGET: usize = 10_000;

// When the `wee_alloc` feature is enabled, use `wee_alloc` as the global
// allocator.
#[cfg(feature = "wee_alloc")]
#[global_allocator]
static ALLOC: wee_alloc::WeeAlloc = wee_alloc::WeeAlloc::INIT;

#[wasm_bindgen]
pub fn parse(input: &str) -> String {
    set_panic_hook();
    match parse_ast_json_string(input) {
        Ok(node) => node.to_string(),
        Err(e) => throw_str(format!("parse error: {}", e[0]).as_str()),
    }
}

/// Parse Monkey source to JSON while encoding every i64 literal as a decimal
/// string so JavaScript consumers do not lose integer precision.
#[wasm_bindgen]
pub fn parse_lossless(input: &str) -> String {
    set_panic_hook();
    match parse_ast_lossless_json_string(input) {
        Ok(node) => node,
        Err(e) => throw_str(format!("parse error: {}", e[0]).as_str()),
    }
}

/// Parse *and* validate Monkey source, returning a tagged JSON envelope the
/// linter consumes. Unlike [`parse_lossless`], this runs `parser::validation`
/// (the semantic pass the interpreter and compiler share) so callers see
/// undefined-variable, misplaced-`this`, and constructor-return errors — not
/// just syntax errors. `analyze` is the linter's single entry into the Rust
/// side: TypeScript never re-implements parse or validation.
///
/// Failures are data in the envelope, not JavaScript exceptions:
/// `{ status: "error", stage, message, span? }`. Parser errors are plain
/// strings without a span; validation errors carry a UTF-8 byte span. On
/// success the AST is serialized losslessly (i64 literals as decimal strings),
/// matching [`parse_lossless`]: `{ status: "ok", program }`.
///
/// Standalone source is validated against the same predefined globals a fresh
/// interpreter/compiler sees — the full builtin table (`len`, `puts`, `first`,
/// `last`, `rest`, `push`, `print`).
#[wasm_bindgen]
pub fn analyze_lossless(input: &str) -> String {
    set_panic_hook();

    let envelope = match analyze_envelope(input) {
        Ok(program) => serde_json::json!({
            "status": "ok",
            "program": program,
        }),
        Err((stage, message, span)) => serde_json::json!({
            "status": "error",
            "stage": stage,
            "message": message,
            "span": span.map(|(start, end)| serde_json::json!({ "start": start, "end": end })),
        }),
    };
    serde_json::to_string(&envelope).expect("analyze envelope serialization should not fail")
}

type AnalyzeFailure = (&'static str, String, Option<(usize, usize)>);

fn analyze_envelope(input: &str) -> Result<serde_json::Value, AnalyzeFailure> {
    let node = parser_pase(input).map_err(|errors| {
        let message = errors
            .first()
            .cloned()
            .unwrap_or_else(|| "unknown parse error".to_string());
        ("parse", message, None)
    })?;
    let Node::Program(program) = &node else {
        unreachable!("parse always returns a Program node");
    };

    let predefined = BuiltIns
        .iter()
        .map(|builtin| builtin.name)
        .collect::<Vec<_>>();
    validate_program(program, &predefined)
        .map_err(|error| ("validation", error.message, Some((error.span.start, error.span.end))))?;

    let mut ast = serde_json::to_value(program).expect("AST serialization should not fail");
    stringify_integer_literals(&mut ast);
    Ok(ast)
}

#[wasm_bindgen]
pub fn compile(input: &str) -> String {
    set_panic_hook();

    let program = match parser_pase(input) {
        Ok(ast) => ast,
        Err(e) => throw_str(format!("parse error: {}", e[0]).as_str()),
    };
    let mut compiler = Compiler::new();
    match compiler.compile(&program) {
        Ok(bytecode) => return bytecode.instructions.string(),
        Err(e) => throw_str(format!("compile error: {}", e).as_str()),
    }
}

#[wasm_bindgen]
pub fn compile_detail(input: &str) -> String {
    set_panic_hook();

    let program = match parser_pase(input) {
        Ok(ast) => ast,
        Err(e) => throw_str(format!("parse error: {}", e[0]).as_str()),
    };
    let mut compiler = Compiler::new();
    match compiler.compile(&program) {
        Ok(bytecode) => return bytecode.string(),
        Err(e) => throw_str(format!("compile error: {}", e).as_str()),
    }
}

#[wasm_bindgen]
pub fn compile_with_debug(input: &str) -> String {
    set_panic_hook();

    let program = match parser_pase(input) {
        Ok(ast) => ast,
        Err(e) => throw_str(format!("parse error: {}", e[0]).as_str()),
    };
    let mut compiler = Compiler::new();
    match compiler.compile(&program) {
        Ok(bytecode) => match serde_json::to_string(&bytecode.debug_view()) {
            Ok(json) => json,
            Err(e) => throw_str(format!("json error: {}", e).as_str()),
        },
        Err(e) => throw_str(format!("compile error: {}", e).as_str()),
    }
}

/// Execute Monkey source on the cycle-collecting VM and return a tagged JSON envelope.
///
/// User parse, compile, runtime, and execution-limit failures are data in the envelope,
/// not JavaScript exceptions. This keeps the playground's Run GC path deterministic.
#[wasm_bindgen]
pub fn run_gc_with_report(input: &str) -> String {
    set_panic_hook();

    let envelope =
        match gc::run_source_with_report_classified(input, PLAYGROUND_GC_INSTRUCTION_BUDGET) {
            Ok(success) => serde_json::json!({
                "status": "ok",
                "result": success.result,
                "report": success.report,
            }),
            Err(error) => serde_json::json!({
                "status": "error",
                "stage": error.stage,
                "kind": error.kind,
                "message": error.message,
                "span": error.span,
            }),
        };

    serde_json::to_string(&envelope).expect("GC run envelope serialization should not fail")
}

/// Execute Monkey source on the cycle-collecting VM, recording a snapshot at
/// every `debugger;` statement, and return a tagged JSON envelope.
///
/// Both arms carry `stdout`, `hits`, and `droppedHits`: snapshots recorded
/// before a runtime failure are exactly what the playground's Debugger tab
/// needs to explain that failure. Failures are data in the envelope, not
/// JavaScript exceptions, mirroring [`run_gc_with_report`].
#[wasm_bindgen]
pub fn run_gc_with_debugger(input: &str) -> String {
    set_panic_hook();

    let envelope =
        match gc::run_source_with_debugger_classified(input, PLAYGROUND_GC_INSTRUCTION_BUDGET) {
            gc::GcDebuggerRunOutcome::Ok {
                result,
                stdout,
                hits,
                dropped_hits,
            } => serde_json::json!({
                "status": "ok",
                "result": result,
                "stdout": stdout,
                "hits": hits,
                "droppedHits": dropped_hits,
            }),
            gc::GcDebuggerRunOutcome::Error {
                error,
                stdout,
                hits,
                dropped_hits,
            } => serde_json::json!({
                "status": "error",
                "stage": error.stage,
                "kind": error.kind,
                "message": error.message,
                "span": error.span,
                "stdout": stdout,
                "hits": hits,
                "droppedHits": dropped_hits,
            }),
        };

    serde_json::to_string(&envelope).expect("GC debugger envelope serialization should not fail")
}

/// Compile Monkey source to AArch64 assembly and return a tagged JSON envelope
/// of per-line `text`/`kind`/`span` records for the playground's godbolt-style
/// ARM64 view (arm64 backend design §12 V1).
///
/// The browser only renders the text `monkey-asm emit` would produce — nothing
/// executes arm64 here. Parse and lowering failures are data in the envelope,
/// not JavaScript exceptions, mirroring [`run_gc_with_report`].
#[wasm_bindgen]
pub fn compile_to_arm64(input: &str) -> String {
    set_panic_hook();

    let envelope = match arm64_envelope(input) {
        Ok(envelope) => envelope,
        Err((stage, message, span)) => serde_json::json!({
            "status": "error",
            "stage": stage,
            "kind": stage,
            "message": message,
            "span": span.map(|(start, end)| serde_json::json!({ "start": start, "end": end })),
        }),
    };
    serde_json::to_string(&envelope).expect("arm64 envelope serialization should not fail")
}

type Arm64Failure = (&'static str, String, Option<(usize, usize)>);

fn arm64_envelope(input: &str) -> Result<serde_json::Value, Arm64Failure> {
    let node = parser_pase(input).map_err(|errors| {
        let message = errors
            .first()
            .cloned()
            .unwrap_or_else(|| "unknown parse error".to_string());
        ("parse", message, None)
    })?;
    // The playground always shows the Linux/ELF spelling (design §12).
    let assembly = lower_node(input, &node, AsmDialect::LinuxElf, false)
        .map_err(|error| ("compile", error.message, error.span))?;

    // `Assembly` guarantees one `line_spans` entry per `\n`-terminated line.
    let lines: Vec<serde_json::Value> = assembly
        .text
        .lines()
        .zip(assembly.line_spans.iter())
        .map(|(text, span)| {
            serde_json::json!({
                "text": text,
                "kind": arm64_line_kind(text),
                "span": span.map(|(start, end)| serde_json::json!({ "start": start, "end": end })),
            })
        })
        .collect();
    Ok(serde_json::json!({ "status": "ok", "lines": lines }))
}

/// Presentation-level line class for the playground: the emitter only ever
/// writes `//` comments, so everything before the first `//` is the code part.
fn arm64_line_kind(text: &str) -> &'static str {
    let code = match text.find("//") {
        Some(index) => &text[..index],
        None => text,
    };
    let trimmed = code.trim();
    if trimmed.is_empty() {
        if text.trim().is_empty() {
            "blank"
        } else {
            "comment"
        }
    } else if trimmed.ends_with(':') {
        "label"
    } else if trimmed.starts_with('.') {
        "directive"
    } else {
        "code"
    }
}

/// Compile Monkey source into a `.mbc` snapshot and return a tagged JSON envelope
/// with the raw bytes (lowercase hex) plus a byte-range annotation of the container
/// layout for the playground inspector.
///
/// User parse and compile failures are data in the envelope, not JavaScript
/// exceptions, mirroring [`run_gc_with_report`].
#[wasm_bindgen]
pub fn compile_to_snapshot(input: &str, strip_debug: bool) -> String {
    set_panic_hook();

    let envelope = match snapshot_envelope(input, strip_debug) {
        Ok(envelope) => envelope,
        Err((stage, message)) => serde_json::json!({
            "status": "error",
            "stage": stage,
            "kind": stage,
            "message": message,
        }),
    };
    serde_json::to_string(&envelope).expect("snapshot envelope serialization should not fail")
}

fn snapshot_envelope(
    input: &str,
    strip_debug: bool,
) -> Result<serde_json::Value, (&'static str, String)> {
    let program = parser_pase(input).map_err(|errors| {
        let message = errors
            .first()
            .cloned()
            .unwrap_or_else(|| "unknown parse error".to_string());
        ("parse", message)
    })?;
    let mut compiler = Compiler::new();
    let bytecode = compiler
        .compile(&program)
        .map_err(|message| ("compile", message))?;
    let bytes = write_bytecode(&bytecode, strip_debug)
        .map_err(|error| ("snapshot", format!("{:?}", error)))?;
    let layout = describe_bytecode(&bytes).map_err(|error| ("snapshot", format!("{:?}", error)))?;
    Ok(serde_json::json!({
        "status": "ok",
        "bytesHex": hex_encode(&bytes),
        "layout": layout,
    }))
}

fn hex_encode(bytes: &[u8]) -> String {
    use std::fmt::Write;

    let mut out = String::with_capacity(bytes.len() * 2);
    for byte in bytes {
        write!(out, "{:02x}", byte).expect("writing to a String cannot fail");
    }
    out
}

/// Execute `.mbc` snapshot bytes on the cycle-collecting VM — the browser twin of
/// `monkey-gc run foo.mbc`, running the same VM with raise-site error
/// classification so the envelope can carry a stable `kind`.
///
/// The buffer is untrusted input: it goes through the validating snapshot reader
/// before the VM. Failures are data in the envelope — stage `snapshot` when the
/// bytes are rejected, `runtime` when the VM errors (the span is only present
/// when the snapshot kept its debug info).
#[wasm_bindgen]
pub fn run_snapshot(bytes: &[u8]) -> String {
    set_panic_hook();

    let envelope = match read_bytecode(bytes) {
        Ok(bytecode) => {
            let mut vm = gc::GcVM::new(bytecode);
            match vm
                .run_with_budget_classified(PLAYGROUND_GC_INSTRUCTION_BUDGET)
                .map(|()| vm.last_result_string())
            {
                Ok(result) => serde_json::json!({
                    "status": "ok",
                    "result": result,
                }),
                Err(error) => serde_json::json!({
                    "status": "error",
                    "stage": "runtime",
                    "kind": error.kind,
                    "message": error.message,
                    "span": error.span,
                }),
            }
        }
        Err(error) => serde_json::json!({
            "status": "error",
            "stage": "snapshot",
            "kind": "invalidSnapshot",
            "message": format!("{:?}", error),
            "span": null,
        }),
    };
    serde_json::to_string(&envelope).expect("snapshot run envelope serialization should not fail")
}

/// Execute an untrusted snapshot on a fresh GC VM and capture observable
/// output. `stdout` is present on both success and failure so callers can
/// compare programs that print before raising an error.
#[wasm_bindgen]
pub fn run_snapshot_with_output(bytes: &[u8]) -> String {
    set_panic_hook();

    let envelope = match read_bytecode(bytes) {
        Ok(bytecode) => {
            let (result, stdout) =
                gc::run_bytecode_with_output(bytecode, PLAYGROUND_GC_INSTRUCTION_BUDGET);
            match result {
                Ok(result) => serde_json::json!({
                    "status": "ok",
                    "result": result,
                    "stdout": stdout,
                }),
                Err(error) => serde_json::json!({
                    "status": "error",
                    "stage": "runtime",
                    "kind": error.kind,
                    "message": error.message,
                    "span": error.span,
                    "stdout": stdout,
                }),
            }
        }
        Err(error) => serde_json::json!({
            "status": "error",
            "stage": "snapshot",
            "kind": "invalidSnapshot",
            "message": format!("{:?}", error),
            "span": null,
            "stdout": "",
        }),
    };
    serde_json::to_string(&envelope).expect("snapshot run envelope serialization should not fail")
}