bynk_driver/project/entry.rs
1use super::diagnostics::Mode;
2use super::diagnostics::ProjectFailure;
3use super::options::CompileOptions;
4use super::output::compatibility_flag_warnings;
5use super::output::finish_build;
6use super::pipeline::RunChecks;
7use super::pipeline::run_checks;
8use bynk_emit::emit_model::ProjectOutput;
9use bynk_project::AttributedError;
10use bynk_project::Roots;
11use bynk_project::discovery::ParsedFile;
12use std::collections::HashMap;
13use std::path::PathBuf;
14use std::sync::Arc;
15
16use bynk_check::checker::{ExprId, Types};
17
18/// #57: turn `options.sources` into the `(overlay, discovered)` pair
19/// `run_checks` expects — the caller-supplied file list, partitioned across
20/// `trees` the same way a real walk would (single-tree: every file lands in
21/// the first tree's list, matching `compile_in_memory`'s own convention).
22/// Shared by [`compile_project`] and [`check_project`] so the two can't drift
23/// on this.
24///
25/// #1077/#1081 review: sorts every partition. `sources`'s own key order is a
26/// `HashMap`'s — unspecified, randomised per process — but `phase_parse`
27/// walks each tree's file list in order to assign sequential `FileId`s and
28/// `ExprId`s (embedded in emitted spans/source maps) and `run_checks` pushes
29/// diagnostics in file order, both of which a real disk walk already
30/// guaranteed via `discover_bynk_files`'s own `out.sort()`. Without this, a
31/// `sources`-driven compile (the CLI's own path as of #1081) would silently
32/// vary its diagnostic order and `FileId` assignment run to run.
33///
34/// R3.9 (#1113): partitions across every `trees` entry, not a hardcoded
35/// primary/secondary pair — a path that doesn't start with any tree's root
36/// (shouldn't happen for a well-formed `sources` map) falls back to the
37/// *last* tree, matching the pre-R3.9 two-tree `partition`'s fallback (an
38/// unmatched key landed in `tests_files`, the second/last half of the pair).
39/// Falling back to the *first* tree instead — silently tried during this
40/// slice's initial cut — would move an unmatched file into whichever tree
41/// `check_file_directory_conflicts` and `identity_path` treat as primary,
42/// changing its attribution with no diagnostic raised either way; matching
43/// the old convention at least keeps this rare path's behaviour unchanged by
44/// the crate move.
45type Overlay = HashMap<PathBuf, String>;
46
47/// One file list per `trees` entry — the same shape `phase_discovery` and
48/// `run_checks`'s own `discovered` parameter already use.
49type Discovered = Vec<Vec<PathBuf>>;
50
51/// #2223: the trees a manifest-backed project compiles — its own
52/// ([`Roots::trees`]) and then each path dependency's
53/// ([`bynk_project::dependency_trees`]) — so the source map partitions a
54/// dependency's files into their own tree rather than the last one.
55fn project_trees(options: &CompileOptions) -> Vec<(PathBuf, PathBuf)> {
56 let mut trees = options.roots.trees();
57 if let Roots::Split { project_root, .. } = &options.roots {
58 let empty = HashMap::new();
59 let overlay = options.sources.as_ref().unwrap_or(&empty);
60 trees.extend(bynk_project::dependency_trees(project_root, overlay));
61 }
62 trees
63}
64
65pub(super) fn sources_to_discovered(
66 sources: &HashMap<PathBuf, String>,
67 trees: &[(PathBuf, PathBuf)],
68) -> (Overlay, Option<Discovered>) {
69 let mut buckets: Vec<Vec<PathBuf>> = vec![Vec::new(); trees.len()];
70 let mut keys: Vec<PathBuf> = sources.keys().cloned().collect();
71 keys.sort();
72 for p in keys {
73 let idx = trees
74 .iter()
75 .position(|(root, _)| p.starts_with(root))
76 .unwrap_or(trees.len().saturating_sub(1));
77 buckets[idx].push(p);
78 }
79 (sources.clone(), Some(buckets))
80}
81
82/// Compile a Bynk project, keeping error attribution + snapshots on failure
83/// (so the CLI can render project errors with source context, ADR 0052). Use
84/// `.map_err(ProjectFailure::flatten)` for the flattened `Vec<CompileError>`
85/// shape.
86pub fn compile_project(options: &CompileOptions) -> Result<ProjectOutput, ProjectFailure> {
87 // T3.6b (R4.1): one table per build, shared across every unit compiled.
88 let tys = &Arc::new(Types::new());
89 let trees = project_trees(options);
90 let excludes = options.roots.excludes();
91 let (overlay, discovered) = match &options.sources {
92 Some(sources) => sources_to_discovered(sources, &trees),
93 None => (HashMap::new(), None),
94 };
95 let run = run_checks(
96 &trees,
97 options.target,
98 options.platform,
99 options.import_ext,
100 Mode::Build,
101 &overlay,
102 &excludes,
103 discovered,
104 options.contracts,
105 options.trace_requests,
106 options.inspect_agents,
107 options.tests,
108 &options.schema_registry,
109 options.remote_tests.as_ref(),
110 options.roots.project_root(),
111 options.asset_files.as_ref(),
112 options.embed_files.as_ref(),
113 options.fixture_files.as_ref(),
114 options.migration_files.as_ref(),
115 options.snapshot_files.as_ref(),
116 matches!(options.roots, Roots::Split { .. }),
117 tys,
118 options.progress.as_ref(),
119 );
120 // #1078: `bynk-emit` no longer writes `bynk.schema.lock` itself — the
121 // reconciled content comes back on `ProjectOutput::schema_lock`
122 // (`finish_build` populates it from `RunChecks::Checked`, only ever
123 // constructed on the `Ok` path, i.e. only on a fully clean build — a
124 // build that fails for any reason, including a schema mismatch
125 // reconciliation itself just reported, produces `Err(ProjectFailure)`
126 // instead and has no revised content for a caller to persist). The
127 // caller (today, `bynk-driver`'s two wiring points) does the atomic
128 // write.
129 finish_build(
130 run,
131 options.import_ext,
132 options.roots.project_root(),
133 &options.compatibility_flags,
134 options.workers_dev,
135 options.out_dir.as_deref(),
136 options.contracts_lock.as_deref(),
137 )
138}
139
140/// Result of [`check_project`]: every diagnostic from a non-bailing project
141/// analysis — errors *and* warnings together (ADR 0117), unconditionally,
142/// unlike [`ProjectOutput`]/[`ProjectFailure`] where `errors`/`warnings` is
143/// picked by which variant the caller got. `bynk check`'s exit code is
144/// decided by [`Self::has_errors`], not by whether this was reached at all.
145pub struct ProjectCheck {
146 pub errors: Vec<AttributedError>,
147 pub snapshots: Vec<(PathBuf, String)>,
148 /// #1772: the project or tree root the build was given, as the caller
149 /// spelled it. `snapshots` and each error's `source_path` are keyed by
150 /// identity path, relative to this root; a renderer shows
151 /// `display_root.join(identity)`, the path as typed from the working
152 /// directory. Empty for an in-memory build.
153 pub display_root: PathBuf,
154 /// State-migrations S4 (#2259): each agent class's lock version, oldest
155 /// readable version and valid `migrate` steps, keyed `<unit>.<Agent>`.
156 /// Empty without a lock, or when the check stopped before reconciling.
157 pub agent_versions: HashMap<String, bynk_check::schema_registry::AgentVersions>,
158 /// #3142: the SQL arguments the checker tied to a D1 call (`all`, `first`,
159 /// `run`, `select`, `firstAs`, or an inline `batch` statement). Read by
160 /// `bynk test --mutate` to pick SQL mutants. Empty when the check stopped
161 /// before the units ran.
162 pub d1_sql_sites: Vec<D1SqlRef>,
163 /// #3355: every `Forward(...)` verdict a `from email` handler returns, as
164 /// the checker resolved it. Read by `bynk deploy` to warn about a
165 /// destination Cloudflare will refuse. Empty when the check stopped before
166 /// the units ran.
167 pub email_forwards: Vec<EmailForward>,
168}
169
170/// #3355: one `Forward(to)` verdict in a `from email` handler's body.
171#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
172pub struct EmailForward {
173 /// The context holding the handler, as written (`shop.support`).
174 pub context: String,
175 /// The `from email` service.
176 pub service: String,
177 /// The address the service claims (`[email protected]`, or `*@domain`).
178 pub address: String,
179 /// The literal destination, or `None` when the argument is computed and so
180 /// cannot be known at deploy time.
181 pub to: Option<String>,
182}
183
184/// #3142: one D1 call's SQL argument, as the checker recorded it.
185#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
186pub struct D1SqlRef {
187 /// The unit the call is in.
188 pub unit: String,
189 /// The absolute path of the file holding the argument.
190 pub path: PathBuf,
191 /// The argument's byte span: the string literal itself, or, when `konst` is
192 /// set, the reference to the constant.
193 pub start: usize,
194 pub end: usize,
195 /// The name of the `String` constant the argument refers to, if it is one.
196 pub konst: Option<String>,
197}
198
199impl ProjectCheck {
200 /// Finding #64: `bynk check`'s exit-code gate is "does any error-severity
201 /// diagnostic exist in the project" — not "did the pipeline reach the end
202 /// without bailing", which is what `compile_project`'s `Result` encoded
203 /// and why a `bynk.toml`-wide structural error anywhere silently hid every
204 /// later diagnostic (including a test body's own type errors) from
205 /// `bynk check`, even though the editor (via
206 /// `bynk_check::analysis::analyse_project`, which shares this same
207 /// non-bailing shape) still reported them.
208 pub fn has_errors(&self) -> bool {
209 self.errors
210 .iter()
211 .any(|ae| bynk_syntax::Severity::for_error(&ae.error) == bynk_syntax::Severity::Error)
212 }
213}
214
215/// Check a project without building (finding #64) — never bails after
216/// discovery (`Mode::Analyse`, the same mode `bynk_check::analysis::analyse_project`
217/// runs for the editor), so a diagnostic anywhere in the project does not
218/// suppress diagnostics elsewhere. `compile_project`'s `Mode::Build` bails at
219/// the first structural error and returns only what it collected up to that
220/// point — correct for `build`/`test`, which must not emit past a real
221/// error, but wrong for `check`, whose only job is to report everything.
222/// `bynk check`'s directory path calls this instead of `compile_project`.
223pub fn check_project(options: &CompileOptions) -> ProjectCheck {
224 // T3.6b (R4.1): one table per check, shared across every unit.
225 let tys = &Arc::new(Types::new());
226 let trees = project_trees(options);
227 let excludes = options.roots.excludes();
228 let (overlay, discovered) = match &options.sources {
229 Some(sources) => sources_to_discovered(sources, &trees),
230 None => (HashMap::new(), None),
231 };
232 let run = run_checks(
233 &trees,
234 options.target,
235 options.platform,
236 options.import_ext,
237 Mode::Analyse,
238 &overlay,
239 &excludes,
240 discovered,
241 options.contracts,
242 options.trace_requests,
243 options.inspect_agents,
244 options.tests,
245 // #2078: `bynk check` reconciles against the committed
246 // `bynk.schema.lock` whenever the caller pre-read it
247 // (`SchemaLock::On`), so a non-additive event change fails the check
248 // the way it fails a build. Read-only by construction: a
249 // `ProjectCheck` carries no reconciled content for anyone to write.
250 &options.schema_registry,
251 options.remote_tests.as_ref(),
252 options.roots.project_root(),
253 options.asset_files.as_ref(),
254 options.embed_files.as_ref(),
255 options.fixture_files.as_ref(),
256 options.migration_files.as_ref(),
257 options.snapshot_files.as_ref(),
258 matches!(options.roots, Roots::Split { .. }),
259 tys,
260 None,
261 );
262 let (errors, snapshots, agent_versions, d1_sql_sites, email_forwards) = match run {
263 RunChecks::Bailed {
264 errors, snapshots, ..
265 } => (errors, snapshots, HashMap::new(), Vec::new(), Vec::new()),
266 RunChecks::Checked {
267 errors,
268 snapshots,
269 agent_versions,
270 unit_callees,
271 parsed,
272 ..
273 } => {
274 // #3142: a site's span carries the durable `FileId` its file's
275 // absolute path interns to.
276 let paths: HashMap<_, _> = parsed
277 .iter()
278 .filter_map(|pf| {
279 let abs = pf.abs_path()?;
280 Some((bynk_project::parse_cache::file_id_for(&abs), abs))
281 })
282 .collect();
283 let mut lits: Vec<D1SqlRef> = unit_callees
284 .iter()
285 .flat_map(|(unit, m)| m.values().map(move |c| (unit, c)))
286 .filter_map(|(unit, c)| {
287 let (site, konst) = match c {
288 bynk_check::checker::Callee::D1Sql(site) => (site, None),
289 bynk_check::checker::Callee::Const(name, Some(site)) => {
290 (&**site, Some(name.clone()))
291 }
292 _ => return None,
293 };
294 let path = paths.get(&site.span.file)?;
295 Some(D1SqlRef {
296 unit: unit.clone(),
297 path: path.clone(),
298 start: site.span.start,
299 end: site.span.end,
300 konst,
301 })
302 })
303 .collect();
304 lits.sort();
305 lits.dedup();
306 let forwards = email_forwards_of(&parsed, &unit_callees);
307 (errors, snapshots, agent_versions, lits, forwards)
308 }
309 };
310 ProjectCheck {
311 // #1890: the manifest's duplicate-flag warnings, as a build reports.
312 errors: errors
313 .into_all()
314 .into_iter()
315 .chain(compatibility_flag_warnings(&options.compatibility_flags))
316 .collect(),
317 snapshots,
318 display_root: options.roots.project_root().to_path_buf(),
319 agent_versions,
320 d1_sql_sites,
321 email_forwards,
322 }
323}
324
325/// #3355: the `Forward(to)` verdicts of every `from email` handler, found on
326/// the parsed declarations by the checker's own classification of each call
327/// (`Callee::Ctor` of `EmailVerdict`'s `Forward`), never by text: a comment,
328/// a string that spells `Forward("x@y")`, or a user type with a `Forward`
329/// variant of its own is not one. The destination is the first argument when it
330/// is a string literal, and `None` otherwise (an interpolated or computed one).
331///
332/// A handler may delegate to a helper `fn` of its context, so a `Forward` in
333/// any `fn` of a context that has a `from email` service is attributed to each
334/// of that context's email handlers. That can over-report (a helper no handler
335/// calls), which is cheap: the result only ever warns.
336fn email_forwards_of(
337 parsed: &[ParsedFile],
338 unit_callees: &HashMap<String, HashMap<ExprId, bynk_check::checker::Callee>>,
339) -> Vec<EmailForward> {
340 use bynk_syntax::ast::{CommonsItem, ServiceProtocol, SourceUnit};
341 let mut out = Vec::new();
342 for pf in parsed {
343 let SourceUnit::Context(ctx) = pf.unit() else {
344 continue;
345 };
346 let helpers: Vec<Option<String>> = ctx
347 .items
348 .iter()
349 .filter_map(|item| match item {
350 CommonsItem::Fn(f) => Some(forwards_in(&f.body, unit_callees)),
351 _ => None,
352 })
353 .flatten()
354 .collect();
355 for item in &ctx.items {
356 let CommonsItem::Service(service) = item else {
357 continue;
358 };
359 let ServiceProtocol::Email { address } = &service.protocol else {
360 continue;
361 };
362 let own = service
363 .handlers
364 .iter()
365 .flat_map(|h| forwards_in(&h.body, unit_callees));
366 out.extend(own.chain(helpers.iter().cloned()).map(|to| EmailForward {
367 context: ctx.name.joined(),
368 service: service.name.name.clone(),
369 address: address.clone(),
370 to,
371 }));
372 }
373 }
374 out.sort();
375 out.dedup();
376 out
377}
378
379/// The destination of each `EmailVerdict`'s `Forward(...)` call under `body`:
380/// its string literal, or `None` when computed.
381fn forwards_in(
382 body: &bynk_syntax::ast::Block,
383 unit_callees: &HashMap<String, HashMap<ExprId, bynk_check::checker::Callee>>,
384) -> Vec<Option<String>> {
385 use bynk_syntax::ast::ExprKind;
386 let is_forward = |id: &ExprId| {
387 unit_callees.values().any(|m| {
388 matches!(
389 m.get(id),
390 Some(bynk_check::checker::Callee::Ctor { sum, tag })
391 if tag == "Forward" && sum.name.name == "EmailVerdict"
392 )
393 })
394 };
395 let mut found = Vec::new();
396 let mut stack: Vec<&bynk_syntax::ast::Expr> = Vec::new();
397 for s in &body.statements {
398 bynk_syntax::ast::statement_exprs(s, &mut stack);
399 }
400 stack.push(&body.tail);
401 while let Some(e) = stack.pop() {
402 if let ExprKind::Call { args, .. } = &e.kind
403 && is_forward(&e.id)
404 {
405 found.push(match args.first().map(|a| &a.kind) {
406 Some(ExprKind::StrLit(s)) => Some(s.clone()),
407 _ => None,
408 });
409 }
410 stack.extend(bynk_syntax::ast::expr_children(e));
411 }
412 found
413}