Skip to main content

gors/
lib.rs

1//! go-rs — Go as a fusevm frontend.
2//!
3//! Pipeline: `lexer` (with Go automatic semicolon insertion) → `parser` builds a
4//! Go AST → `compiler` lowers it to a `fusevm::Chunk` → fusevm executes it on
5//! the shared three-tier Cranelift JIT, calling back into `host` (the strict
6//! numeric hook) for Go's `+` string-concatenation overload and string
7//! ordering. There is no bespoke VM and no Go runtime here — execution and
8//! codegen live in fusevm, the same engine behind zshrs, strykelang, awkrs,
9//! vimlrs, elisprs, rubylang, javars, kotlinrs, and scalars.
10
11pub mod aot_native;
12pub mod ast;
13pub mod banner;
14pub mod cli;
15pub mod compiler;
16pub mod dap;
17pub mod embed;
18pub mod escape;
19pub mod host;
20mod isprint;
21pub mod lexer;
22pub mod lsp;
23pub mod parser;
24pub mod pkg;
25pub mod returns;
26pub mod rust_ffi;
27pub mod scope;
28mod stdio;
29pub mod stdlib_vendor;
30pub mod tiers;
31mod unicase;
32
33pub use banner::version_banner;
34pub use embed::run_program;
35use fusevm::{Op, Scheduler, VMResult, Value, VM};
36
37/// Parse Go `src` to an AST. Inline `rust { ... }` FFI blocks are desugared to
38/// `__rust_compile(...)` statements first (see [`rust_ffi`]), so every parse
39/// path — run, `--dump-ast`, `--disasm`, `--dap` — sees the same rewritten
40/// source. No-op when the source has no `rust` block.
41pub fn parse(src: &str) -> Result<ast::Program, String> {
42    let src = rust_ffi::desugar(src);
43    parser::parse(&src)
44}
45
46/// Parse and lower Go `src` to a runnable fusevm chunk. Imported (non-native)
47/// packages are resolved to source, linked in, and compiled together (see
48/// [`pkg`]) — the standard library is executed, not reimplemented.
49pub fn compile(src: &str) -> Result<fusevm::Chunk, String> {
50    let prog = parse(src)?;
51    let linked = pkg::link(prog)?;
52    compiler::compile(&linked)
53}
54
55/// Configure a fresh VM for running go-rs bytecode: install the builtins and the
56/// strict numeric hook. Used for the main VM and every goroutine VM.
57fn configure_vm(chunk: fusevm::Chunk) -> VM {
58    let mut vm = VM::new(chunk);
59    host::install(&mut vm);
60    vm.set_numeric_hook(std::sync::Arc::new(host::numeric_hook));
61    vm
62}
63
64/// Run a chunk on a single VM (no goroutines), with the tracing JIT enabled.
65fn run_chunk(chunk: fusevm::Chunk) -> Result<Value, String> {
66    let mut vm = configure_vm(chunk);
67    vm.enable_tracing_jit();
68    let result = vm.run();
69    // An inline-Rust FFI fault stashes its message and halts the VM; it must be
70    // checked on both the `Halted` and `Ok` paths (a fault mid-expression can
71    // leave a value on the stack), so surface it before reporting success.
72    if let Some(e) = host::take_ffi_error() {
73        return Err(e);
74    }
75    match result {
76        VMResult::Ok(v) => Ok(v),
77        VMResult::Halted => Ok(vm.stack.last().cloned().unwrap_or(Value::Undef)),
78        VMResult::Error(e) => Err(e),
79    }
80}
81
82/// Run a chunk that uses goroutines/channels under the cooperative scheduler.
83/// Every goroutine is its own VM sharing the program and the thread-local heap;
84/// the scheduler drives them and services channel operations.
85fn run_scheduled(chunk: fusevm::Chunk) -> Result<Value, String> {
86    let main_vm = configure_vm(chunk.clone());
87    let make_vm = move || configure_vm(chunk.clone());
88    // A receive on a closed, drained channel is the one case Go reports as
89    // `ok == false`. The scheduler decides it atomically and yields whatever
90    // value the frontend nominates, so nominating a unique heap handle (rather
91    // than the default `Int(0)`, which a real zero is indistinguishable from)
92    // is what makes `v, ok := <-ch` and `for v := range ch` expressible.
93    let sched = Scheduler::new(make_vm).with_recv_zero(host::chan_closed_sentinel());
94    match sched.run(main_vm) {
95        Ok(()) => match host::take_ffi_error() {
96            Some(e) => Err(e),
97            None => Ok(Value::Undef),
98        },
99        // Go's runtime reports a deadlock as a fatal error on stderr and exits
100        // 2 (`runtime.fatal` -> `exit(2)`), not as a toolchain diagnostic. The
101        // goroutine dump Go prints below that line is not reproduced.
102        // An embedded run reports it as an error instead.
103        Err(fusevm::SchedError::Deadlock) if stdio::embedded() => {
104            Err(fusevm::SchedError::Deadlock.to_string())
105        }
106        Err(fusevm::SchedError::Deadlock) => {
107            use std::io::Write as _;
108            let _ = std::io::stdout().flush();
109            eprintln!("{}", fusevm::SchedError::Deadlock);
110            std::process::exit(2);
111        }
112        Err(e) => Err(format!("go-rs: {e}")),
113    }
114}
115
116/// True if the chunk uses any cooperative-concurrency op (so it must run under
117/// the scheduler rather than a single VM).
118fn uses_scheduler(chunk: &fusevm::Chunk) -> bool {
119    chunk.ops.iter().any(|op| {
120        matches!(
121            op,
122            Op::Go(..)
123                | Op::ChanMake
124                | Op::ChanSend
125                | Op::ChanRecv
126                | Op::ChanClose
127                | Op::ChanLen
128                | Op::ChanCap
129                | Op::Select(..)
130        )
131    })
132}
133
134/// Compile and run a Go source string; return the last VM value.
135pub fn run_str(src: &str) -> Result<Value, String> {
136    let chunk = compile(src)?;
137    // A fresh object heap per run — no composite handles leak across programs.
138    // Goroutine VMs share this (single-threaded) thread-local heap.
139    host::heap_reset();
140    if uses_scheduler(&chunk) {
141        run_scheduled(chunk)
142    } else {
143        run_chunk(chunk)
144    }
145}
146
147/// Read and run a `.go` file.
148pub fn run_file(path: &str) -> Result<Value, String> {
149    let src =
150        std::fs::read_to_string(path).map_err(|e| format!("go-rs: cannot read {path}: {e}"))?;
151    run_str(&src)
152}
153
154/// Compile `src` and return a human-readable disassembly of the fusevm chunk
155/// (for `go --disasm`).
156pub fn disassemble(src: &str) -> Result<String, String> {
157    Ok(compile(src)?.disassemble())
158}
159
160/// `go vet`: parse and compile `src`, returning `Ok(())` if it is well-formed
161/// (no lex/parse/compile error) without running it.
162pub fn vet(src: &str) -> Result<(), String> {
163    compile(src).map(|_| ())
164}
165
166/// `go env`: the Go environment as go-rs reports it. A curated, deterministic
167/// subset (no `go` toolchain paths — go-rs has no module system).
168pub fn env_report() -> String {
169    let arch = match std::env::consts::ARCH {
170        "aarch64" => "arm64",
171        "x86_64" => "amd64",
172        other => other,
173    };
174    let os = match std::env::consts::OS {
175        "macos" => "darwin",
176        other => other,
177    };
178    [
179        ("GOOS", os.to_string()),
180        ("GOARCH", arch.to_string()),
181        ("GOVERSION", format!("go{}", banner::GO_COMPAT_VERSION)),
182        ("GOENGINE", format!("go-rs {}", env!("CARGO_PKG_VERSION"))),
183        ("CGO_ENABLED", "0".to_string()),
184        ("GOROOT", String::new()),
185        ("GOPATH", String::new()),
186    ]
187    .iter()
188    .map(|(k, v)| format!("{k}=\"{v}\""))
189    .collect::<Vec<_>>()
190    .join("\n")
191        + "\n"
192}