bcgen_lang/lib.rs
1//! # bcgen_lang
2//!
3//! Compiles HIR (the representation every LexerSketch language lowers into)
4//! to LSB, the bytecode `bvm-lang` executes.
5//!
6//! ## The lazy path
7//!
8//! Build or lower a resolved unit, [`compile`] it, and hand the module to a
9//! VM:
10//!
11//! ```
12//! use hir_lang::{Builder, Name, OpKind};
13//! use intern_lang::Interner;
14//!
15//! // fn add(a, b) { a + b }
16//! let mut names = Interner::new();
17//! let mut b = Builder::new();
18//! let (pa, a) = b.local_param(Name::new(names.intern("a")));
19//! let (pb, bb) = b.local_param(Name::new(names.intern("b")));
20//! let (ua, ub) = (b.use_binder(a), b.use_binder(bb));
21//! let sum = b.op(OpKind::Add, &[ua, ub]);
22//! let body = b.block(&[], Some(sum));
23//! let add = b.func(Name::new(names.intern("add")), &[pa, pb], body);
24//! let root = b.module(None, &[add]);
25//! let hir = b.finish(root)?;
26//!
27//! let out = bcgen_lang::compile(&hir, &names)?;
28//! let module = out.module();
29//! assert!(module.function(out.function(add).unwrap()).is_some());
30//! assert!(!bytecode_lang::encode(module).is_empty());
31//! # Ok::<(), Box<dyn std::error::Error>>(())
32//! ```
33//!
34//! Running it (with `bvm-lang`): `Program::load(out.into_module(), &host)`,
35//! then `vm.run(func, &[Value::Int(2), Value::Int(3)])` returns `Int(5)`.
36//!
37//! ## What it compiles
38//!
39//! HIR spec v3 (hir-lang 0.4) to LSB format 2 (bytecode-lang 0.3), in the
40//! **dynamic profile**: every value is an LSB `dyn`. Functions with defaults
41//! (per call or once), named, variadic, and by-reference parameters, each
42//! carrying its LSB parameter list so dynamic calls bind in the VM; locals in
43//! registers, shared variables in LSB references; closures with explicit,
44//! implicit, and recursive captures; generators (keyed `yield`, `yield
45//! from`), `await`, and `spawn`; `if`, the loop primitive with its step,
46//! labeled `break`/`continue`, `return`; `match` by a sequential decision
47//! procedure, raising `NoMatch` when no arm matches; direct, dynamic, host,
48//! and method calls; maps and arrays with PHP value semantics, separation
49//! that copies only what is shared, and key coercion (or shared references);
50//! `let_place` and PHP references into array elements; every OPS v2
51//! operation with its policy (`pow`, `promote`, `shift = saturate`);
52//! union and intersection type tests and casts; `throw` and
53//! `try`/`catch`/`finally` by LSB's canonical lowering, `defer`; globals,
54//! constants, statics, and the module body; named intrinsics through an
55//! [`Intrinsics`] table ([`Intrinsics::mox`] maps every Mox intrinsic to an
56//! inline fast path or a host function). Every instruction maps back to the
57//! HIR node it came from ([`Compiled::origin`]) and to a line-table row.
58//!
59//! Not yet: classes, declared records and sums, and typed fast paths (0.5);
60//! each is a precise [`CompileError::Unsupported`].
61//!
62//! ## Guarantees
63//!
64//! - **Loads.** Every module it emits passes `bvm-lang`'s load-time checks:
65//! registers, windows, constants, branch targets, and handlers in range.
66//! - **Semantics.** Differential tests run random programs through the
67//! compiler and the VM, and through a reference interpreter written in
68//! the tests, comparing results, error kinds, and error locations.
69//! - **No recursion over the input.** Generation is an explicit task stack;
70//! any nesting depth compiles in bounded native stack.
71//! - **Budgeted and deterministic.** Output is bounded by
72//! [`Options::with_max_instructions`]; the same unit compiles to the same
73//! bytes.
74//!
75//! ## `no_std`
76//!
77//! The crate needs only `alloc`. The default `std` feature is additive.
78
79#![cfg_attr(not(feature = "std"), no_std)]
80#![cfg_attr(docsrs, feature(doc_cfg))]
81#![forbid(unsafe_code)]
82#![deny(missing_docs)]
83#![deny(unused_must_use)]
84#![deny(unused_results)]
85#![deny(clippy::unwrap_used)]
86#![deny(clippy::expect_used)]
87#![deny(clippy::todo)]
88#![deny(clippy::unimplemented)]
89#![deny(clippy::print_stdout)]
90#![deny(clippy::print_stderr)]
91#![deny(clippy::dbg_macro)]
92
93extern crate alloc;
94
95mod analysis;
96mod codegen;
97mod error;
98mod func;
99mod intrinsics;
100mod options;
101mod output;
102mod unit;
103
104pub use error::{CompileError, Unsupported};
105pub use intrinsics::{Arity, Fast, IntrinsicDef, Intrinsics, Lowering, LsbOp};
106pub use options::{ArraySemantics, BodyMode, KeyCoercion, LineIndex, Locate, Location, Options};
107pub use output::Compiled;
108
109/// Compiles and runs the `rust` code blocks in `README.md`, `docs/API.md`,
110/// and the current release notes as part of `cargo test`, so the published
111/// examples cannot drift from the API.
112#[cfg(doctest)]
113#[doc = include_str!("../README.md")]
114#[doc = include_str!("../docs/API.md")]
115#[doc = include_str!("../docs/release/v0.3.0.md")]
116pub struct MarkdownDocTests;
117
118use hir_lang::Hir;
119use intern_lang::Lookup;
120
121/// Compiles a resolved unit with the default [`Options`] (the PHP profile).
122///
123/// `names` is the interner the unit's names were interned in; function,
124/// import, property, and debug names are read from it.
125///
126/// # Errors
127///
128/// A [`CompileError`] naming the first form that does not compile, in the
129/// unit's canonical order.
130///
131/// # Examples
132///
133/// ```
134/// use hir_lang::Builder;
135/// use intern_lang::Interner;
136///
137/// let mut b = Builder::new();
138/// let root = b.module(None, &[]);
139/// let hir = b.finish(root)?;
140/// let out = bcgen_lang::compile(&hir, &Interner::new())?;
141/// assert_eq!(out.module().functions().len(), 1); // the entry function
142/// # Ok::<(), Box<dyn std::error::Error>>(())
143/// ```
144pub fn compile<L: Lookup>(hir: &Hir, names: &L) -> Result<Compiled, CompileError> {
145 Compiler::new(Options::new()).compile(hir, names)
146}
147
148/// A configured compiler: [`Options`] and, optionally, a [`Locate`] for the
149/// line tables.
150///
151/// # Examples
152///
153/// ```
154/// use bcgen_lang::{Compiler, LineIndex, Options};
155/// use hir_lang::Builder;
156/// use intern_lang::Interner;
157///
158/// let lines = LineIndex::new("main.mox", 0, "");
159/// let mut b = Builder::new();
160/// let root = b.module(None, &[]);
161/// let hir = b.finish(root)?;
162/// let out = Compiler::new(Options::new())
163/// .with_locator(&lines)
164/// .compile(&hir, &Interner::new())?;
165/// assert!(out.start().is_none());
166/// # Ok::<(), Box<dyn std::error::Error>>(())
167/// ```
168#[derive(Clone)]
169pub struct Compiler<'a> {
170 options: Options,
171 locator: Option<&'a dyn Locate>,
172}
173
174impl core::fmt::Debug for Compiler<'_> {
175 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
176 f.debug_struct("Compiler")
177 .field("options", &self.options)
178 .field("locator", &self.locator.is_some())
179 .finish()
180 }
181}
182
183impl Compiler<'static> {
184 /// A compiler with these options and no locator (line-table rows carry
185 /// byte offsets; see [`Locate`]).
186 ///
187 /// # Examples
188 ///
189 /// ```
190 /// use bcgen_lang::{ArraySemantics, Compiler, Options};
191 ///
192 /// let c = Compiler::new(Options::new().with_arrays(ArraySemantics::Reference));
193 /// assert_eq!(c.options().arrays(), ArraySemantics::Reference);
194 /// ```
195 #[must_use]
196 pub fn new(options: Options) -> Self {
197 Compiler {
198 options,
199 locator: None,
200 }
201 }
202}
203
204impl Compiler<'_> {
205 /// The same compiler, writing line-table rows through `locator`.
206 ///
207 /// # Examples
208 ///
209 /// See [`Compiler`].
210 #[must_use]
211 pub fn with_locator(self, locator: &dyn Locate) -> Compiler<'_> {
212 Compiler {
213 options: self.options,
214 locator: Some(locator),
215 }
216 }
217
218 /// The options.
219 ///
220 /// # Examples
221 ///
222 /// ```
223 /// use bcgen_lang::{Compiler, Options};
224 ///
225 /// assert_eq!(Compiler::new(Options::new()).options(), &Options::new());
226 /// ```
227 #[must_use]
228 pub fn options(&self) -> &Options {
229 &self.options
230 }
231
232 /// Compiles a resolved unit.
233 ///
234 /// # Errors
235 ///
236 /// A [`CompileError`] naming the first form that does not compile.
237 ///
238 /// # Examples
239 ///
240 /// See [`Compiler`].
241 pub fn compile<L: Lookup>(&self, hir: &Hir, names: &L) -> Result<Compiled, CompileError> {
242 unit::compile(hir, names, &self.options, self.locator)
243 }
244}