Skip to main content

bynk_emit/
lib.rs

1//! Bynk's TypeScript emission, plus the per-unit build sequencing that drives
2//! it — the layer above `bynk-project` (discovery, the dependency graph),
3//! `bynk-check` (all semantic checking, R3.5), and (since the P7.12 crate
4//! carve) `bynk-ir`/`bynk-lower` (the typed IR and its `&CheckedProgram → Ir`
5//! lowering pass).
6//!
7//! `project` owns `compile_project`/`run_checks`: the two-pass sequence over
8//! a project's units — discover and parse (`bynk-project`), then resolve,
9//! type-check (`bynk-check`) and emit each unit with full visibility of what
10//! it `uses`/`consumes`. `emitter` lowers a checked program to TypeScript.
11//! Input: a project tree (or an in-memory overlay). Output: TypeScript files
12//! plus diagnostics — this crate originates none of its own (P5.5,
13//! `design/tracks/semantics-in-the-checker.md` §3.5, R10.1).
14//!
15//! `testgen` generates the test harness: each suite's test module, the test entry and the
16//! discovery manifest, with the test-runtime fragments they embed. The driver calls it, and
17//! keeps orchestration, file I/O and process spawning (1B.2a, #4028).
18//!
19//! Extracted from `bynkc` as slice 4 of the crate-decomposition track over
20//! `bynk-syntax` + `bynk-check`. Behaviour is unchanged; `bynk` depends on this
21//! crate and re-exports its modules so its public API (`compile_project`,
22//! `ProjectOutput`, …) and the binary are untouched.
23
24// The README's `rust` examples are compiled (and, unless marked `no_run`, run)
25// as doctests, so they cannot rot (#1645). `cfg(doctest)` keeps this item out of
26// every build and out of the docs.rs front page, which the `//!` docs above own.
27#[cfg(doctest)]
28#[doc = include_str!("../README.md")]
29struct ReadmeDoctests;
30
31pub mod emit_model;
32pub mod emitter;
33pub mod testgen;
34pub(crate) mod ts_build;
35
36#[cfg(test)]
37pub(crate) mod testkit;
38
39use bynk_check::{checker, resolver};
40use bynk_syntax::{CompileError, lexer, parser};
41
42/// A single-file compile that also returns the non-failing warnings produced on
43/// success — what a CLI prints (v0.89, ADR 0117). [`compile`] is the
44/// warning-discarding convenience over this.
45///
46/// Lives in `bynk-emit` (slice 7 precedent, alongside [`NODE_MAJOR_FLOOR`]) so
47/// both `bynk` and the `bynk` driver can compile a self-contained single-file
48/// commons in-process without depending on each other.
49pub struct Compiled {
50    pub ts: String,
51    pub warnings: Vec<CompileError>,
52}
53
54/// Compile a single Bynk source string to a TypeScript string.
55///
56/// Parses the input as a self-contained, single-file commons with no `uses`
57/// against other commons. Use `bynk_driver::project::compile_project` for multi-file
58/// projects or for any source that declares `uses`. `filename` is used only for
59/// diagnostic rendering.
60pub fn compile(source: &str, filename: &str) -> Result<String, Vec<CompileError>> {
61    compile_with_warnings(source, filename).map(|c| c.ts)
62}
63
64/// The warning-preserving single-file compile behind [`compile`]. See [`Compiled`].
65pub fn compile_with_warnings(source: &str, _filename: &str) -> Result<Compiled, Vec<CompileError>> {
66    let (program, warnings) = check_single_file(source, SingleFileMode::Build)?;
67    // 1A.34: a missing checker fact is reported as a `bynk.internal.missing_checker_fact`
68    // diagnostic, never as output.
69    let ts = emitter::emit(&program).map_err(|faults| {
70        faults
71            .into_iter()
72            .map(emitter::InternalFault::into_compile_error)
73            .collect::<Vec<_>>()
74    })?;
75    Ok(Compiled { ts, warnings })
76}
77
78/// Check a single-file commons without building it: the same diagnostics as
79/// [`compile_with_warnings`], minus the build-only ones, and no emission.
80/// Returns the non-failing warnings on success. The single-file half of
81/// `bynk check` (`bynk_driver::run_check`); a directory goes
82/// through the project pipeline in `Mode::Check` instead.
83///
84/// #1883, slice 1a (review of #1903): before this, `run_check` reused
85/// [`compile_with_warnings`], so `bynk check page.bynk` failed with the
86/// build-only asset refusal, contradicting §5.12's "checking is unaffected".
87pub fn check_with_warnings(
88    source: &str,
89    _filename: &str,
90) -> Result<Vec<CompileError>, Vec<CompileError>> {
91    check_single_file(source, SingleFileMode::Check).map(|(_, warnings)| warnings)
92}
93
94/// Whether a single-file run will go on to emit (`Build`) or only report
95/// (`Check`). Only build-only diagnostics differ: today, the asset gate.
96#[derive(Clone, Copy, PartialEq, Eq)]
97enum SingleFileMode {
98    Check,
99    Build,
100}
101
102/// The shared single-file pipeline: lex, parse, check, certify.
103fn check_single_file(
104    source: &str,
105    mode: SingleFileMode,
106) -> Result<(checker::CheckedProgram, Vec<CompileError>), Vec<CompileError>> {
107    let (typed, warnings) = check_single_typed(source, mode)?;
108    // T3.7 (R3.10): `check` already gated on error-severity diagnostics, so
109    // `typed.warnings` — the only diagnostics left riding along with it — can
110    // never contain one; `certify` re-asserts that structurally rather than
111    // trusting the caller not to skip it.
112    let program = checker::certify(typed, warnings.clone()).unwrap_or_else(|_| {
113        panic!("bynk internal error: check() already gated on error-severity diagnostics")
114    });
115    Ok((program, warnings))
116}
117
118/// [`check_single_file`] up to, and not including, `certify`: the checked commons and its
119/// warnings. Split out so a test can take one checker fact away before certifying it.
120fn check_single_typed(
121    source: &str,
122    mode: SingleFileMode,
123) -> Result<(checker::TypedCommons, Vec<CompileError>), Vec<CompileError>> {
124    // #2807: a lexical error is reported with the rest of the file's, but the
125    // file is still refused.
126    let (tokens, lex_errors) = lexer::tokenize_recovering(source);
127    if !lex_errors.is_empty() {
128        return Err(bynk_check::recovery::diagnose_unlexable(
129            &tokens,
130            source,
131            lex_errors,
132            Vec::new(),
133        ));
134    }
135    // ADR 0117: parse-time warnings (orphan doc blocks) ride alongside the
136    // AST — they surface with the build's warnings instead of failing it.
137    let (mut commons, mut warnings) = match parser::parse_with_warnings(&tokens, source) {
138        Ok(parsed) => parsed,
139        // #1663: the strict parse stops at the first syntax error. Diagnose the
140        // file as the editor does instead, and still refuse to compile it.
141        Err(strict) => {
142            return Err(bynk_check::recovery::diagnose_unparsable(
143                &tokens, source, strict,
144            ));
145        }
146    };
147    // #3445: a constant named by a literal-only annotation argument is replaced
148    // by the literal it denotes, as the project path does.
149    bynk_check::annotation_consts::resolve_single_file(&mut commons);
150    // v0.20a: function types are confined to non-boundary positions — the same
151    // rule the project path applies.
152    let mut boundary_errors = Vec::new();
153    let boundary_types = bynk_check::project_model::collect_type_decls(commons.items.iter());
154    bynk_check::project_model::check_function_type_boundary_items(
155        &commons.items,
156        &boundary_types,
157        &mut boundary_errors,
158    );
159    // #1883: the asset declaration rules (path, duplicates, name conflicts),
160    // which the project path raises in `build_unit_table`; and, in a build
161    // only, `bynk.asset.needs_project` — a single file has no project root to
162    // find `assets/` under and emits no Worker to serve it beside.
163    boundary_errors.extend(bynk_check::assets::single_file_asset_errors(
164        &commons.items,
165        mode == SingleFileMode::Build,
166    ));
167    // #2387: the same for `embed` — its path and name rules, and, in
168    // a build only, `bynk.embed.needs_project` — a single file has no project root
169    // to find `embeds/` under.
170    boundary_errors.extend(bynk_check::embeds::single_file_embed_errors(
171        &commons.items,
172        mode == SingleFileMode::Build,
173    ));
174    // #2617: the `const` name rules (duplicates, name conflicts), which the
175    // project path raises in `build_unit_table`.
176    boundary_errors.extend(bynk_check::consts::single_file_const_errors(&commons.items));
177    // #1663: a boundary or resolve error is local to its declaration, so the
178    // checker still runs over every declaration and its diagnostics join
179    // theirs (minus echoes); any error still refuses the compile.
180    let item_spans: Vec<_> = commons.items.iter().map(|i| i.span()).collect();
181    let (resolved, resolve_errors) = resolver::resolve_recovering(commons);
182    let mut errors = boundary_errors;
183    errors.extend(resolve_errors.iter().cloned());
184    let typed = match checker::check(resolved) {
185        Ok(typed) if errors.is_empty() => typed,
186        Ok(_) => return Err(errors),
187        Err(checked) => {
188            errors.extend(resolver::without_resolve_echoes(
189                checked,
190                &resolve_errors,
191                &item_spans,
192            ));
193            return Err(errors);
194        }
195    };
196    warnings.extend(typed.warnings.clone());
197    Ok((typed, warnings))
198}
199
200/// Minimum supported Node.js **major** version for the `node` platform binding
201/// and for running Bynk's emitted TypeScript.
202///
203/// Single source of truth for the Node floor: the emitted code targets it, the
204/// `bynk` driver's `doctor` command compares a detected `node` against it, so
205/// the number is stated once. Lives in `bynk-emit` (which emits the TS that runs
206/// on Node) so the driver and the emitter share one definition (slice 7; was a
207/// `bynkc` const before the driver dropped that dep).
208///
209/// #1674: 22, the oldest Node major still in support (18 reached end-of-life in
210/// April 2025, 20 in April 2026), and the one `bynk test --inspect` needs. So
211/// `bynk doctor`'s `ok` means the commands work, not merely that Node exists.
212/// The `--inspect` path checks its own minor floor (22.6 to run, 22.18 for
213/// source-mapped breakpoints) and says so when it isn't met.
214pub const NODE_MAJOR_FLOOR: u32 = 22;
215
216/// The minor version within [`NODE_MAJOR_FLOOR`] the floor sits at: 22.13,
217/// the first 22.x whose built-in `node:sqlite` loads without
218/// `--experimental-sqlite` (standard-library P4a, #2602: the `D1` test double
219/// runs on it). CI's floor job installs exactly this version.
220pub const NODE_MINOR_FLOOR: u32 = 13;
221
222/// The Node floor as `(major, minor)`: what `bynk doctor` compares against.
223pub const NODE_FLOOR: (u32, u32) = (NODE_MAJOR_FLOOR, NODE_MINOR_FLOOR);
224
225/// The TypeScript major the emitted output is verified against, and the only
226/// one Bynk supports (#3420): the one users get from `npm install -g
227/// typescript`. Every CI leg installs it and type-checks every positive fixture
228/// under it, the `npx` fallbacks provision it, and `bynk doctor` warns on a
229/// `tsc` below it and reports one newer than it as untested. (There was a lower
230/// floor, 5, until #3420: tsc 5 cost about 4x tsc 7 per `bynk test`, and the
231/// shape of the generated code is meant to be independent of the tooling.)
232pub const TYPESCRIPT_MAJOR_TESTED: u32 = 7;
233
234/// I2 (#1971): the value of every edge key off the deployed path. `bynk dev`
235/// passes it for each edge a Worker is on (`BYNK_CALL_TO_<callee>`,
236/// `BYNK_CALL_FROM_<caller>`, named by `bynk_check::wire_format`), and the
237/// generated test harnesses put it in every participant's `env`. Fixed rather
238/// than random so two `bynk dev --context` sessions run side by side still
239/// admit each other's calls. It guards nothing, so it must never reach a
240/// deployed Worker: `bynk deploy` mints one key per edge, and none is ever
241/// written into a generated `wrangler.toml`.
242pub const LOCAL_CALL_KEY: &str = "bynk-local-call-key";
243
244/// #3581 (the dev agent-inspection track): the caller name `bynk dev inspect` signs
245/// its requests as, and the variable under which `bynk dev` gives every served
246/// Worker the local key for it (`BYNK_CALL_FROM_` plus the caller's edge suffix). The
247/// runtime's `INSPECT_CALLER` is the same name.
248pub const INSPECT_CALLER: &str = "bynk.dev";
249pub use bynk_project::env_protocol::CALL_FROM_BYNK_DEV as INSPECT_CALLER_KEY_VAR;
250
251/// #3562 (G6): the file a `bynk dev` group build stages beside its entry, naming each
252/// member that hosts an agent and its classes, so `bynk dev inspect` can sign a request
253/// for the member that answers it.
254pub const INSPECT_MEMBERS_FILE: &str = "bynk-inspect.json";
255
256/// #3562 (G5): the file every Worker that hosts an agent stages beside its entry, naming each
257/// context and the agent classes it owns, which `bynk deploy` reads to guard a move.
258pub const AGENTS_MANIFEST: &str = "bynk-agents.json";
259
260/// The storage layout this emitter writes an agent's state in (#3189, the
261/// retired per-entry-storage track in `design/archive/retired-tracks.md`): 1 is
262/// the wholesale layout, with every collection inline in the one `"state"`
263/// record, and 2 is the per-entry layout, with each `Map`/`Set`/`Cache`/`Log`
264/// entry and index posting under its own key. `bynk deploy` records it in each
265/// version's facts so that `bynk deploy revert` can refuse a rollback to a build
266/// that writes an older layout over stored data. The slice that changes the layout
267/// raises this together with the emitter's writer.
268pub const STORAGE_LAYOUT: i64 = 2;
269
270/// State-migrations S4 (#2259): the call signature and the sweep route's
271/// names, for `bynk migrate sweep`, which signs as the runtime verifies.
272pub use bynk_check::wire_format;
273/// I2 (#1971): the edge keys' names, for the driver (`bynk dev`, `bynk
274/// deploy`), which sees the compiler only through this crate.
275pub use bynk_check::wire_format::{EDGE_FROM_PREFIX, EDGE_TO_PREFIX, edge_key_from, edge_key_to};
276
277pub use emitter::wrangler::{
278    COMPATIBILITY_DATE, CONTAINERS_UNAVAILABLE_VAR, DEFAULT_COMPATIBILITY_FLAGS, WRANGLER_MIN,
279    compatibility_flags,
280};
281
282// `write_output`/`write_document` moved to `bynk-driver` (#1047, R2.3/
283// T0.7 residue): every caller was already at driver level, so this crate
284// never needed direct filesystem access for it — the pure move closes it
285// out of this crate's `fs_below_driver` count. See `bynk-driver::output`.