Skip to main content

nybl_compile/
lib.rs

1//! Ahead-of-time Nybl-to-Rust transpiler.
2//!
3//! [`transpile`] parses a Nybl program and emits readable Rust source that
4//! links against `nybl-lang` for runtime values, operators, built-ins, host
5//! calls, and diagnostics. The generated source can be compiled as a native
6//! binary or included as a module in a larger Rust application.
7//!
8//! The AOT engine implements the same language semantics as the tree-walker
9//! and bytecode VM, including methods, closures, string interpolation,
10//! indexed and field mutation, transactional `ref` parameters, structs and
11//! enums, pattern matching, `Result`, lazy iteration, and all forms of `use`.
12//! A three-engine differential suite exercises their observable behavior
13//! together.
14//!
15//! # Basic transpilation
16//!
17//! ```
18//! use nybl_compile::{Options, transpile};
19//!
20//! let rust_source = transpile(
21//!     r#"let answer = 6 * 7
22//! print("answer = {answer}")"#,
23//!     &Options::default(),
24//! ).unwrap();
25//! assert!(rust_source.contains("fn main()"));
26//! ```
27//!
28//! `use` statements need a compile-time [`ModuleResolver`]. For bundled
29//! stdlib modules, callers normally delegate that resolver to
30//! `nybl::stdlib::resolve`; for in-memory programs, [`modules_from_map`] is
31//! convenient:
32//!
33//! ```
34//! use nybl_compile::{Options, modules_from_map, transpile};
35//!
36//! let rust_source = transpile(
37//!     "use config.{answer}\nprint(answer)",
38//!     &Options {
39//!         module_resolver: Some(modules_from_map([
40//!             ("config", "let answer = 42"),
41//!         ])),
42//!         ..Options::default()
43//!     },
44//! ).unwrap();
45//! assert!(rust_source.contains("42"));
46//! ```
47//!
48//! With the default options, the output contains `fn main()` and constructs
49//! `nybl_sys::StandardHost`. Set [`Options::emit_main`] and
50//! [`Options::use_nybl_sys`] to `false` for a library surface driven by a
51//! custom [`nybl::NyblHost`].
52//!
53//! # Sandboxed output
54//!
55//! [`Options::sandbox`] adds [`nybl::NyblLimits`] accounting and host tick
56//! callbacks to generated code. With `sandbox: true` and `emit_main: false`,
57//! direct root-level `pub fn` declarations also generate a persistent
58//! `NyblInstance` API with `load`, `entry_points`, `call`, and `call_value`.
59//! Globals, modules, functions, callbacks, types, methods, and random-number
60//! state remain live between calls.
61//!
62//! Rust calls into the generated `NyblInstance` remain value-only and reject
63//! ref-bearing entries or callbacks before execution. A value-only public
64//! entry can use reference parameters internally. Generated ref calls preserve
65//! the language's target validation, copy-in/copy-out staging, atomic commit,
66//! error rollback, forwarding, and mutating receiver behavior. See the
67//! [reference-parameters
68//! guide](https://nybl-lang.com/docs/functions/reference-parameters/).
69//! Generated user methods also preserve `ref self` receiver write-back and
70//! rollback; ordinary `self` receivers are read-only.
71//!
72//! Unsandboxed library output exposes the one-shot `run` API and deliberately
73//! omits accounting overhead. Do not run untrusted programs through that
74//! mode.
75//!
76//! # Output shaping
77//!
78//! [`Options::module_name`] wraps the generated items in a public Rust module,
79//! which lets one crate include several transpiled programs without name
80//! collisions. [`transpile_ast`] accepts an already parsed Nybl AST for build
81//! tools that perform their own parse and diagnostic pass.
82//!
83//! See the [embedding guide](https://nybl-lang.com/docs/embedding/) and
84//! [stateful instance guide](https://nybl-lang.com/docs/embedding/instances/)
85//! for generated signatures, dependency setup, limits, and lifecycle rules.
86
87use std::cell::RefCell;
88use std::rc::Rc;
89
90use nybl::error::NyblError;
91use nybl::parser::Stmt;
92
93mod emit;
94
95/// A compile-time module resolver. The AOT runs this eagerly for
96/// every `use` it encounters, threading the entire module graph
97/// into the generated Rust. Same contract as
98/// [`nybl::NyblHost::resolve_module`]: `None` = not handled,
99/// `Some(Ok(source))` = module source text,
100/// `Some(Err(_))` = resolver failure.
101///
102/// Wrapped as `Rc<RefCell<..>>` so `Options` stays `Clone` while
103/// the callback keeps `FnMut` freedom.
104pub type ModuleResolver =
105    Rc<RefCell<dyn FnMut(&str) -> Option<Result<String, NyblError>> + 'static>>;
106
107/// Build a [`ModuleResolver`] from an in-memory name→source map.
108/// Convenience for tests and simple embedders.
109pub fn modules_from_map<S: Into<String>>(
110    modules: impl IntoIterator<Item = (S, S)>,
111) -> ModuleResolver {
112    let map: std::collections::HashMap<String, String> = modules
113        .into_iter()
114        .map(|(k, v)| (k.into(), v.into()))
115        .collect();
116    Rc::new(RefCell::new(move |name: &str| {
117        map.get(name).cloned().map(Ok)
118    }))
119}
120
121/// Options that control the shape of the emitted Rust.
122///
123/// `Debug` is skipped — `module_resolver` is a trait object that
124/// has no useful debug representation. If you need to diff options
125/// in tests, compare specific fields directly.
126#[derive(Clone)]
127pub struct Options {
128    /// If true, emit a `fn main()` that drives the program with
129    /// `nybl_sys::StandardHost`. If false, emit only the library
130    /// surface (the caller is expected to provide their own
131    /// entry point and host).
132    pub emit_main: bool,
133    /// If true, pull `nybl-sys::StandardHost` into the generated code
134    /// so `main()` can construct it directly. Implied by
135    /// [`Self::emit_main`].
136    pub use_nybl_sys: bool,
137    /// If true, the emitted code enforces [`nybl::NyblLimits`]: step
138    /// counts are checked at every loop iteration and function
139    /// entry, an explicit memory context enforces `max_memory`, and
140    /// [`nybl::NyblHost::on_tick`] fires at the
141    /// same checkpoints. The generated `run` takes a `&NyblLimits`
142    /// parameter in this mode.
143    ///
144    /// When false (the default), the emitted code uses an untracked
145    /// memory context and has no limit-checking overhead: `run` takes
146    /// only a host, and runaway programs are the caller's problem.
147    pub sandbox: bool,
148    /// If `Some(name)`, wrap the entire emitted output in
149    /// `pub mod <name> { ... }`. Use this when you want to embed
150    /// several transpiled programs in one Rust source file without
151    /// colliding on top-level items (`Ctx`, `run_program`,
152    /// `run`, `__nybl_tick`, user-fn names, etc.). `emit_main` is
153    /// ignored in this mode — you provide your own driver.
154    pub module_name: Option<String>,
155    /// Resolver used to inline imported modules into the emitted
156    /// Rust at transpile time. Required when the program contains
157    /// any `use` statement; missing (`None`) + an import in
158    /// source raises a clear "set `module_resolver`" error.
159    ///
160    /// The resolver is called eagerly for each transitive import
161    /// before any Rust is emitted, so cycle detection and missing
162    /// modules both surface at build time rather than at run time.
163    pub module_resolver: Option<ModuleResolver>,
164    /// Engine builtins the host forbids, mirroring
165    /// [`nybl::NyblLimits::disabled_builtins`]. A definite reference
166    /// in the root program or any resolved module refuses to
167    /// transpile; a reference the static pass cannot prove (a
168    /// shadowing binding might apply) compiles into a fatal runtime
169    /// error at the builtin call site instead of the builtin call.
170    pub disabled_builtins: std::collections::BTreeSet<String>,
171}
172
173impl Default for Options {
174    fn default() -> Self {
175        Self {
176            emit_main: true,
177            use_nybl_sys: true,
178            sandbox: false,
179            module_name: None,
180            module_resolver: None,
181            disabled_builtins: std::collections::BTreeSet::new(),
182        }
183    }
184}
185
186/// Parse Nybl source and emit the equivalent Rust source.
187///
188/// The caller is responsible for writing the returned string to a
189/// crate (or `src/main.rs`) and invoking `cargo` or `rustc` on it.
190/// The result depends on:
191///
192/// - `nybl-lang` (`nybl` crate) — for `Value`, `ops`, `builtins`, …
193/// - `nybl-sys` — only if [`Options::use_nybl_sys`] is true.
194pub fn transpile(source: &str, opts: &Options) -> Result<String, NyblError> {
195    let stmts = nybl::parse(source)?;
196    transpile_ast(&stmts, opts)
197}
198
199/// Lower-level entry point: emit Rust from an already-parsed AST.
200pub fn transpile_ast(stmts: &[Stmt], opts: &Options) -> Result<String, NyblError> {
201    emit::emit(stmts, opts)
202}