Skip to main content

scalars/
lib.rs

1//! scalars — Scala as a fusevm frontend.
2//!
3//! Pipeline: `lexer` → `parser` builds a Scala AST → `compiler` lowers it to a
4//! `fusevm::Chunk` → fusevm executes it on the shared three-tier Cranelift JIT,
5//! calling back into `host` (the strict numeric hook) for Scala's `String` `+`
6//! overload. There is no bespoke VM or JVM here — execution and codegen live in
7//! fusevm, the same engine behind zshrs, stryke, awkrs, elisp, and ruby.
8
9pub mod ast;
10pub mod banner;
11pub mod bigdec;
12pub mod cli;
13pub mod compiler;
14pub mod corpus;
15pub mod dap;
16pub mod embed;
17pub mod fdlibm;
18pub mod host;
19pub mod jlocale;
20pub mod jrandom;
21pub mod lexer;
22pub mod locale_names;
23pub mod lsp;
24pub mod parser;
25pub mod rbtree;
26pub mod resolve;
27pub mod rust_ffi;
28pub mod tiers;
29pub mod timsort;
30
31pub use banner::version_banner;
32pub use embed::run_program;
33use fusevm::{VMResult, Value, VM};
34
35/// Parse Scala `src` to an AST.
36pub fn parse(src: &str) -> Result<ast::Program, String> {
37    parser::parse(src)
38}
39
40/// Parse and lower Scala `src` to a runnable fusevm chunk.
41pub fn compile(src: &str) -> Result<fusevm::Chunk, String> {
42    let prog = parser::parse(src)?;
43    compiler::compile(&prog)
44}
45
46/// Register the scalars builtins + strict numeric hook on a fresh VM, enable the
47/// tracing JIT, and run the chunk. Returns the last top-of-stack value.
48fn run_chunk(chunk: fusevm::Chunk) -> Result<Value, String> {
49    let mut vm = VM::new(chunk);
50    host::install(&mut vm);
51    vm.set_numeric_hook(std::sync::Arc::new(host::numeric_hook));
52    vm.enable_tracing_jit();
53    host::reset_heap(); // start each run with an empty object arena
54    host::reset_types(); // and with an empty declared-type registry
55    host::reset_exceptions(); // and with no exception left in flight
56    host::reset_exit_code(); // and with no `sys.exit` status from a prior run
57    let _ = host::take_error(); // clear any stale FFI fault from a prior run
58    let res = vm.run();
59    // An FFI compile/dispatch fault halts the VM and parks its message; surface
60    // it as an error rather than the (Undef) top of stack.
61    if let Some(err) = host::take_error() {
62        return Err(err);
63    }
64    match res {
65        VMResult::Ok(v) => Ok(v),
66        VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
67        VMResult::Error(e) => Err(e),
68    }
69}
70
71/// Compile and run a Scala source string; return the last VM value.
72pub fn run_str(src: &str) -> Result<Value, String> {
73    run_chunk(compile(src)?)
74}
75
76/// Parse and lower Scala `src` with per-statement `DBG_LINE` markers (for
77/// `scala --dap`).
78pub fn compile_debug(src: &str) -> Result<fusevm::Chunk, String> {
79    let prog = parser::parse(src)?;
80    compiler::compile_debug(&prog)
81}
82
83/// The `DBG_LINE` marker builtin: hand control to the DAP adapter, which pauses
84/// on breakpoints/steps, then return `Unit`.
85fn dbg_line_builtin(vm: &mut VM, _argc: u8) -> Value {
86    dap::on_debug_line(vm);
87    Value::Undef
88}
89
90/// Run a debug-compiled chunk: install the host builtins and the `DBG_LINE`
91/// marker builtin, but do NOT enable the tracing JIT (it would compile hot loops
92/// and skip the markers). Used only by `scala --dap`.
93fn run_chunk_debug(chunk: fusevm::Chunk) -> Result<Value, String> {
94    let mut vm = VM::new(chunk);
95    host::install(&mut vm);
96    vm.register_builtin(host::DBG_LINE, dbg_line_builtin);
97    vm.set_numeric_hook(std::sync::Arc::new(host::numeric_hook));
98    host::reset_heap(); // start each run with an empty object arena
99    host::reset_types(); // and with an empty declared-type registry
100    host::reset_exceptions(); // and with no exception left in flight
101    match vm.run() {
102        VMResult::Ok(v) => Ok(v),
103        VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
104        VMResult::Error(e) => Err(e),
105    }
106}
107
108/// Read and run a `.scala` file under the debug marker path (for `scala --dap`).
109pub fn eval_file_debug(path: &str) -> Result<(), String> {
110    let src =
111        std::fs::read_to_string(path).map_err(|e| format!("scalars: cannot read {path}: {e}"))?;
112    run_chunk_debug(compile_debug(&src)?)?;
113    Ok(())
114}
115
116/// Read and run a `.scala` file.
117pub fn run_file(path: &str) -> Result<Value, String> {
118    let src =
119        std::fs::read_to_string(path).map_err(|e| format!("scalars: cannot read {path}: {e}"))?;
120    run_str(&src)
121}
122
123/// Run a Scala source string with the program arguments a `def main`'s `args`
124/// parameter and a `@main` method's parameters read from.
125pub fn run_str_with_args(src: &str, argv: Vec<String>) -> Result<Value, String> {
126    host::set_argv(argv);
127    run_str(src)
128}
129
130/// Compile `src` and return a human-readable disassembly of the fusevm chunk
131/// (for `scala --disasm`).
132pub fn disassemble(src: &str) -> Result<String, String> {
133    Ok(compile(src)?.disassemble())
134}