Skip to main content

bynk_project/
discovery.rs

1use std::collections::{HashMap, HashSet};
2use std::fs;
3use std::path::{Path, PathBuf};
4
5use bynk_syntax::ast::{
6    AdapterDecl, Case, Commons, CommonsItem, ConsumesDecl, ExportsDecl, SourceUnit, SuiteDecl,
7    TestTier, Trivia, TypeRef, UsesDecl,
8};
9use bynk_syntax::error::CompileError;
10use bynk_syntax::span::Span;
11
12use crate::roots::{Roots, UnitKind};
13
14/// v0.118: a case's *effective* tier — its own `as <tier>`, else the suite
15/// default, else `unit`.
16pub fn case_effective_tier(case: &Case, suite: &SuiteDecl) -> TestTier {
17    case.tier.or(suite.tier).unwrap_or(TestTier::Unit)
18}
19
20/// v0.118: whether a suite's *effective* tier is `system` — the suite default
21/// is `system`, or any case opts up to `system`. Such a suite is emitted via
22/// the wired cross-Worker (`Integration`) machinery; otherwise it stays
23/// in-process (`Test`).
24pub fn suite_effective_tier_is_system(suite: &SuiteDecl) -> bool {
25    suite.tier == Some(TestTier::System)
26        || suite.cases.iter().any(|c| c.tier == Some(TestTier::System))
27}
28
29/// Read a source file from the overlay (keyed by canonicalised absolute
30/// path; falls back to the literal path so a not-yet-created overlay entry
31/// still matches). Every caller into this module now supplies a complete
32/// overlay — content-ownership track (#1086) slice 5 removed the disk-read
33/// fallback this used to have on a miss, so an incomplete overlay is a real
34/// `NotFound` error here, not a silent disk read.
35///
36/// Finding #55/#65: tries the literal path first, `canonicalize()` only on a
37/// miss — an in-memory/wasm project's synthetic overlay keys never exist on
38/// disk, so `canonicalize()` was a guaranteed-failing syscall on every read of
39/// every such file, for no benefit (the literal-path lookup below already
40/// finds the same entry).
41pub fn read_source(path: &Path, overlay: &HashMap<PathBuf, String>) -> std::io::Result<String> {
42    if let Some(text) = overlay.get(path) {
43        return Ok(text.clone());
44    }
45    let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
46    if let Some(text) = overlay.get(&canonical) {
47        return Ok(text.clone());
48    }
49    Err(std::io::Error::new(
50        std::io::ErrorKind::NotFound,
51        format!("no overlay entry for `{}`", path.display()),
52    ))
53}
54
55/// An adapter's `.binding.ts` module: overlay-first (an open, unsaved
56/// binding buffer), else a real disk read. Content-ownership track (#1086)
57/// scope note, found under slice 5's implementation: unlike a project's
58/// `.bynk` sources — enumerable ahead of time by extension, and this
59/// track's actual charter — a binding module's *path* is only known once
60/// its declaring adapter has been parsed (`adapter … { binding: "…" }`), so
61/// no discovery walk (`bynk-testkit`, `bynk-driver::discovery`) can
62/// pre-populate it into a sources map the way `.bynk` files are. Keeping a
63/// disk-read fallback here — the CLI's real production path has always
64/// worked exactly this way, `#1077`/`#1081` notwithstanding — is a
65/// deliberate, narrow carve-out, not a straggler.
66pub fn read_adapter_binding(
67    path: &Path,
68    overlay: &HashMap<PathBuf, String>,
69) -> std::io::Result<String> {
70    if let Some(text) = overlay.get(path) {
71        return Ok(text.clone());
72    }
73    let canonical = path.canonicalize().unwrap_or_else(|_| path.to_path_buf());
74    if let Some(text) = overlay.get(&canonical) {
75        return Ok(text.clone());
76    }
77    fs::read_to_string(path)
78}
79
80/// #2321: read one file an adapter `binding … includes [ … ]` list names, as
81/// bytes. Binary, so the text `overlay` (unsaved editor buffers) does not apply:
82/// an included module is always the file on disk.
83pub fn read_adapter_include(path: &Path) -> std::io::Result<Vec<u8>> {
84    fs::read(path)
85}
86
87/// A parsed `.bynk` file: its source, AST, and the two path forms it needs.
88///
89/// Slice 0: `source_path` and `identity_path` are **different things**, and
90/// conflating them is what made a two-root project's file identity ambiguous.
91/// They coincide for a single-root project, which is why one field sufficed
92/// until `include` could hold two entries.
93///
94/// P4.0 (#1113, [DECISION B]): fields are crate-private now that `ParsedFile`
95/// lives in `bynk-project` — `bynk-emit`'s `symbols`/`validate` read them
96/// through the accessors below instead of the direct field pokes a
97/// same-crate `pub(crate)` allowed before the move.
98#[derive(Clone)]
99pub struct ParsedFile {
100    /// The path **relative to the `include` root that contains this file** —
101    /// the form unit validation requires. `src/todos.bynk` under the `src`
102    /// root is `todos.bynk`, which is what lets it declare `context todos`
103    /// ([`crate::paths::unit_path_matches`], via
104    /// [`crate::consistency::check_path_name_alignment`]). Prefixing this
105    /// would make every unit in every project fail alignment.
106    pub(crate) source_path: PathBuf,
107    /// Slice 0: the path **relative to the project root** — this file's
108    /// identity, unique across `include` roots. `src/todos.bynk` and
109    /// `tests/todos.bynk` share a `source_path` (`todos.bynk`) but differ
110    /// here. Everything that *keys* a file — the analysed snapshots, the
111    /// diagnostic attribution — uses this; nothing that *validates a unit's
112    /// name* may.
113    ///
114    /// Equal to `source_path` for a single-root project (`Roots::Single`
115    /// resolves to one tree with an empty prefix), so single-root behaviour
116    /// is unchanged by construction.
117    pub(crate) identity_path: PathBuf,
118    /// v0.72: the absolute path the compiler read this file from, used as the
119    /// source-map `sources` entry so an editor's breakpoint (set on the real
120    /// `.bynk` file) resolves to the same path the debugger loads. `None` for
121    /// toolchain-injected synthetic units, which have no on-disk source.
122    pub(crate) abs_path: Option<PathBuf>,
123    pub(crate) source: String,
124    pub(crate) unit: SourceUnit,
125    pub(crate) kind: UnitKind,
126    /// v0.17: true for toolchain-injected units (the `bynk` surface) — exempt
127    /// from the reserved-namespace and missing-binding checks.
128    pub(crate) synthetic: bool,
129    /// #2223: the dependency package this file belongs to, or `None` for the
130    /// project's own files and first-party units. Set by `bynk-check` once
131    /// the package graph is known ([`Self::assign_package`]).
132    pub(crate) package: Option<crate::packages::PackageId>,
133}
134
135impl ParsedFile {
136    /// Construct directly — used by `bynk-emit`'s first-party synthetic-unit
137    /// injection (`firstparty_parsed`), which builds a `ParsedFile` for a
138    /// toolchain-supplied source (`bynk.bynk`, `bynk.cloudflare`, …) that
139    /// never went through [`parse_sources`]'s discovery-driven path.
140    pub fn synthetic(
141        identity_path: PathBuf,
142        source_path: PathBuf,
143        source: String,
144        unit: SourceUnit,
145        kind: UnitKind,
146    ) -> Self {
147        ParsedFile {
148            source_path,
149            identity_path,
150            abs_path: None,
151            source,
152            unit,
153            kind,
154            synthetic: true,
155            package: None,
156        }
157    }
158
159    /// General constructor — `bynk-emit`'s own tests use this to build a
160    /// hand-rolled `ParsedFile` fixture (a specific `source_path`/
161    /// `identity_path` pair, a non-synthetic unit) that neither
162    /// [`Self::synthetic`] (forces `source_path == identity_path`,
163    /// `synthetic: true`) nor [`parse_sources`] (needs a real token stream)
164    /// fits.
165    #[allow(clippy::too_many_arguments)]
166    pub fn new(
167        source_path: PathBuf,
168        identity_path: PathBuf,
169        abs_path: Option<PathBuf>,
170        source: String,
171        unit: SourceUnit,
172        kind: UnitKind,
173        synthetic: bool,
174    ) -> Self {
175        ParsedFile {
176            source_path,
177            identity_path,
178            abs_path,
179            source,
180            unit,
181            kind,
182            synthetic,
183            package: None,
184        }
185    }
186
187    /// The path **relative to the `include` root that contains this file**.
188    pub fn source_path(&self) -> PathBuf {
189        self.source_path.clone()
190    }
191
192    /// The path **relative to the project root** — this file's identity,
193    /// unique across `include` roots. See the field's own doc for why this
194    /// and [`Self::source_path`] must not be conflated.
195    pub fn identity_path(&self) -> PathBuf {
196        self.identity_path.clone()
197    }
198
199    /// The absolute path this file was read from, when it has one — `None`
200    /// for toolchain-injected synthetic units.
201    pub fn abs_path(&self) -> Option<PathBuf> {
202        self.abs_path.clone()
203    }
204
205    pub fn kind(&self) -> UnitKind {
206        self.kind
207    }
208
209    /// #2223: the dependency package this file belongs to; `None` for the
210    /// project's own files and first-party units.
211    pub fn package(&self) -> Option<&crate::packages::PackageId> {
212        self.package.as_ref()
213    }
214
215    /// #2223: mark this file as part of dependency `id`, and give it the path
216    /// its units' canonical names map to (`deps/<org>/<package>/<rel>`), so
217    /// name alignment and the emitted layout both follow from
218    /// [`crate::commons_dir_for`]. The identity path — the real file, relative
219    /// to the consuming project — is unchanged.
220    pub fn assign_package(&mut self, id: crate::packages::PackageId) {
221        self.source_path = id.out_dir().join(&self.source_path);
222        self.package = Some(id);
223    }
224
225    /// Override the discovered kind — `bynk-emit`'s own tests use this to
226    /// build a scenario's intermediate unit as a commons regardless of what
227    /// AST shape (`context_using`, …) constructed it, without needing a
228    /// second builder per kind.
229    pub fn set_kind(&mut self, kind: UnitKind) {
230        self.kind = kind;
231    }
232
233    /// True for toolchain-injected units (the `bynk` surface).
234    pub fn is_synthetic(&self) -> bool {
235        self.synthetic
236    }
237
238    pub fn unit(&self) -> &SourceUnit {
239        &self.unit
240    }
241
242    /// Mutable access to the parsed unit — `bynk-emit`'s
243    /// `normalize_service_defaults` (service `by`/`given` default injection)
244    /// is the one caller that rewrites a unit's items in place, ahead of
245    /// grouping/checking.
246    pub fn unit_mut(&mut self) -> &mut SourceUnit {
247        &mut self.unit
248    }
249
250    /// The raw source text this file was parsed from.
251    pub fn source(&self) -> &str {
252        &self.source
253    }
254
255    /// v0.72: the source-map `sources` entry for this file — the absolute path
256    /// the compiler read it from (forward slashes), so an editor breakpoint set
257    /// on the real `.bynk` resolves to the same path the debugger loads. A
258    /// project-relative name would resolve against the emitted `.ts`'s directory,
259    /// which is the wrong place. Synthetic units (no on-disk source) fall back to
260    /// their relative path.
261    pub fn map_source_name(&self) -> String {
262        self.abs_path
263            .as_deref()
264            .unwrap_or(self.source_path.as_path())
265            .to_string_lossy()
266            .replace('\\', "/")
267    }
268
269    /// State-migrations S3 (#2248): a context file's `removed agent`
270    /// declarations; empty for every other unit.
271    pub fn removed_agents(&self) -> &[bynk_syntax::ast::RemovedAgentDecl] {
272        match &self.unit {
273            SourceUnit::Context(c) => &c.removed_agents,
274            _ => &[],
275        }
276    }
277
278    pub fn items(&self) -> &Vec<CommonsItem> {
279        match &self.unit {
280            SourceUnit::Commons(c) => &c.items,
281            SourceUnit::Context(c) => &c.items,
282            SourceUnit::Adapter(a) => &a.items,
283            SourceUnit::Suite(_) => {
284                // Tests don't contribute CommonsItem items; the production
285                // pipeline never asks them to. Return a singleton empty vec.
286                static EMPTY: std::sync::OnceLock<Vec<CommonsItem>> = std::sync::OnceLock::new();
287                EMPTY.get_or_init(Vec::new)
288            }
289        }
290    }
291
292    /// P6.x (#1137): does this file declare a `messages { … }` block? The one
293    /// predicate a `messages`-bundle emitter needs — whether to inject the
294    /// `bynk.locale` `render` fallback import — without the caller having to
295    /// walk [`items`](Self::items) and match [`CommonsItem::Messages`] itself.
296    pub fn declares_messages(&self) -> bool {
297        self.items()
298            .iter()
299            .any(|it| matches!(it, CommonsItem::Messages(_)))
300    }
301
302    /// 1B.2a (#4028): does this file declare an `agent`? The commons barrel's merged helpers
303    /// read this and [`declares_services`](Self::declares_services), as the `messages`
304    /// emitter reads [`declares_messages`](Self::declares_messages), so that the production
305    /// barrel need not name the AST.
306    pub fn declares_agents(&self) -> bool {
307        self.items()
308            .iter()
309            .any(|it| matches!(it, CommonsItem::Agent(_)))
310    }
311
312    /// 1B.2a (#4028): does this file declare a `service`? See
313    /// [`declares_agents`](Self::declares_agents).
314    pub fn declares_services(&self) -> bool {
315        self.items()
316            .iter()
317            .any(|it| matches!(it, CommonsItem::Service(_)))
318    }
319
320    pub fn uses(&self) -> &Vec<UsesDecl> {
321        match &self.unit {
322            SourceUnit::Commons(c) => &c.uses,
323            SourceUnit::Context(c) => &c.uses,
324            SourceUnit::Adapter(a) => &a.uses,
325            SourceUnit::Suite(t) => &t.uses,
326        }
327    }
328
329    pub fn consumes(&self) -> &[ConsumesDecl] {
330        match &self.unit {
331            SourceUnit::Commons(_) => &[],
332            SourceUnit::Context(c) => &c.consumes,
333            // v0.18: adapter-to-adapter capability dependencies (spec §4.5).
334            SourceUnit::Adapter(a) => &a.consumes,
335            // An integration test's participant edges are resolved separately
336            // (the harness root consumes every participant); it has no
337            // `consumes` of its own.
338            SourceUnit::Suite(_) => &[],
339        }
340    }
341
342    /// `exports` clauses, for the unit kinds that have them (contexts and
343    /// adapters). Empty for commons/tests.
344    pub fn exports(&self) -> &[ExportsDecl] {
345        match &self.unit {
346            SourceUnit::Context(c) => &c.exports,
347            SourceUnit::Adapter(a) => &a.exports,
348            _ => &[],
349        }
350    }
351
352    pub fn adapter(&self) -> Option<&AdapterDecl> {
353        match &self.unit {
354            SourceUnit::Adapter(a) => Some(a),
355            _ => None,
356        }
357    }
358
359    pub fn test(&self) -> Option<&SuiteDecl> {
360        match &self.unit {
361            SourceUnit::Suite(t) => Some(t),
362            _ => None,
363        }
364    }
365
366    /// v0.119 (ADR 0155): the agent names this file's own `for all run:
367    /// History[Agent]` properties drive — `emit_agent` gates the exported
368    /// `__bynkDriveHistory_<Agent>` driver on membership. Empty for a
369    /// non-suite file, or a suite with no such property.
370    pub fn history_target_agent_names(&self) -> impl Iterator<Item = &str> {
371        self.test()
372            .into_iter()
373            .flat_map(|t| &t.properties)
374            .flat_map(|prop| &prop.forall.bindings)
375            .filter_map(|b| match &b.type_ref {
376                TypeRef::History(inner, _) => match inner.as_ref() {
377                    TypeRef::Named(id) => Some(id.name.as_str()),
378                    _ => None,
379                },
380                _ => None,
381            })
382    }
383
384    /// v0.118: a suite whose *effective* tier is `system` is emitted through
385    /// the wired cross-Worker machinery (the retired standalone `integration`
386    /// path, now re-driven from tiers). Returns the underlying [`SuiteDecl`]
387    /// when this file is such a suite.
388    pub fn integration(&self) -> Option<&SuiteDecl> {
389        match &self.unit {
390            SourceUnit::Suite(t) if suite_effective_tier_is_system(t) => Some(t),
391            _ => None,
392        }
393    }
394
395    /// Build a synthetic Commons AST node carrying the given items, so the
396    /// existing resolver/checker pipeline can be driven uniformly.
397    pub fn as_synthetic_commons(&self, items: Vec<CommonsItem>) -> Commons {
398        let (name, uses, documentation, form, span) = match &self.unit {
399            SourceUnit::Commons(c) => (
400                c.name.clone(),
401                c.uses.clone(),
402                c.documentation.clone(),
403                c.form,
404                c.span,
405            ),
406            SourceUnit::Context(c) => (
407                c.name.clone(),
408                c.uses.clone(),
409                c.documentation.clone(),
410                c.form,
411                c.span,
412            ),
413            SourceUnit::Suite(t) => (
414                t.target.clone(),
415                t.uses.clone(),
416                t.documentation.clone(),
417                t.form,
418                t.span,
419            ),
420            SourceUnit::Adapter(a) => (
421                a.name.clone(),
422                a.uses.clone(),
423                a.documentation.clone(),
424                a.form,
425                a.span,
426            ),
427        };
428        Commons {
429            name,
430            items,
431            uses,
432            documentation,
433            form,
434            span,
435            trivia: Trivia::default(),
436            trailing_comments: Vec::new(),
437        }
438    }
439}
440
441/// Parse already-read source text into a [`ParsedFile`]. The read happens
442/// at the call site (v0.24): the pipeline owns the text for snapshots and
443/// per-file error attribution, and the overlay supplies unsaved buffers.
444/// Slice 0: `prefix` is this tree's project-root-relative `include` prefix
445/// (`src`, `tests`, …), empty for a single-root project. It builds each file's
446/// `identity_path`; `source_path` stays relative to `root` (the tree), which is
447/// what unit validation reads. See [`ParsedFile`].
448///
449/// P8.4 (#1515): the actual tokenize+parse now runs through
450/// [`crate::parse_cache::cached_parse`], keyed on the file's own absolute
451/// path — durable across separate calls to this function, not just within
452/// one, so a `FileId` (and the `ExprId`s a file's own expressions carry) no
453/// longer resets every time a fresh analysis pass parses an unchanged file.
454/// `next_expr_id`/`next_file_id` are no longer threaded in from the caller
455/// for this reason — the cache owns both counters now, durably.
456pub fn parse_sources(
457    root: &Path,
458    prefix: &Path,
459    path: &Path,
460    source: String,
461) -> Result<(Vec<ParsedFile>, Vec<CompileError>), Vec<CompileError>> {
462    // v0.72: cache (and identify a `ParsedFile`) by the *absolute* path —
463    // `path` is relative when the compiler was invoked with a relative input
464    // (`bynk test .`), and a relative cache key would let the same file seen
465    // through two differently-rooted calls collide, or worse, miss. Falls
466    // back to `path` itself on the rare `std::path::absolute` failure, same
467    // as the pre-existing `abs_path` field it also feeds.
468    let abs_path = std::path::absolute(path).ok();
469    let cache_key: &Path = abs_path.as_deref().unwrap_or(path);
470    // v0.113: a file may declare more than one top-level unit — an *atomic*
471    // file holding `commons`/`context` alongside a `suite` (DECISION S). Each
472    // unit becomes its own `ParsedFile` sharing the file's source and path, so
473    // the downstream grouping partitions *declarations* by kind: the source
474    // units flow to the build, the suites to `bynk test` only.
475    // ADR 0117: a warning-severity parse diagnostic (an orphan doc block)
476    // must not hard-fail discovery — the parsed units flow to the build and
477    // the warnings ride out to the caller's severity-aware sink.
478    let (_file_id, result) = crate::parse_cache::cached_parse(cache_key, &source);
479    let (units, warnings) = result.map_err(|errors| (*errors).clone())?;
480    let files = parsed_files(root, prefix, path, abs_path, &source, units.iter().cloned());
481    Ok((files, (*warnings).clone()))
482}
483
484/// #1710: what a file the strict parse rejects still yields, from its
485/// recovering parse: a [`ParsedFile`] per unit it recovered, the names of the
486/// declarations recovery had to skip (references to them are known names, not
487/// unknown ones; #1663's Decision B), and the recovering parse's diagnostics.
488/// `files` is empty when no unit survived (a broken header); the diagnostics
489/// still come from this recovery, with real spans. These files are for
490/// diagnostics only: the strict parse's error still stands, so nothing they
491/// belong to is ever emitted.
492pub struct RecoveredSources {
493    pub files: Vec<ParsedFile>,
494    pub broken_decl_names: Vec<String>,
495    pub errors: Vec<CompileError>,
496}
497
498/// #1710: [`parse_sources`] for a file whose strict parse failed, from the
499/// recovering parse the parse cache keeps beside that failure. `None` only
500/// when there is none: the source didn't lex.
501pub fn parse_sources_recovering(
502    root: &Path,
503    prefix: &Path,
504    path: &Path,
505    source: String,
506) -> Option<RecoveredSources> {
507    let abs_path = std::path::absolute(path).ok();
508    let cache_key: &Path = abs_path.as_deref().unwrap_or(path);
509    let recovered = crate::parse_cache::cached_recovery(cache_key, &source)?;
510    let files = parsed_files(
511        root,
512        prefix,
513        path,
514        abs_path,
515        &source,
516        recovered.units.iter().cloned(),
517    );
518    Some(RecoveredSources {
519        files,
520        broken_decl_names: recovered.broken_decl_names.clone(),
521        errors: recovered.errors.clone(),
522    })
523}
524
525/// One [`ParsedFile`] per unit of a file (a file may declare several, v0.113),
526/// each classified by kind and sharing the file's source and paths.
527fn parsed_files(
528    root: &Path,
529    prefix: &Path,
530    path: &Path,
531    abs_path: Option<PathBuf>,
532    source: &str,
533    units: impl Iterator<Item = SourceUnit>,
534) -> Vec<ParsedFile> {
535    let rel = path.strip_prefix(root).unwrap_or(path).to_path_buf();
536    units
537        .map(|unit| {
538            let kind = match &unit {
539                SourceUnit::Commons(_) => UnitKind::Commons,
540                SourceUnit::Context(_) => UnitKind::Context,
541                // v0.118: a suite whose effective tier is `system` is emitted
542                // through the wired cross-Worker machinery (classified as
543                // `Integration`); unit/integration-tier suites stay in-process.
544                SourceUnit::Suite(t) if suite_effective_tier_is_system(t) => UnitKind::Integration,
545                SourceUnit::Suite(_) => UnitKind::Test,
546                SourceUnit::Adapter(_) => UnitKind::Adapter,
547            };
548            ParsedFile {
549                abs_path: abs_path.clone(),
550                identity_path: prefix.join(&rel),
551                source_path: rel.clone(),
552                source: source.to_string(),
553                unit,
554                kind,
555                synthetic: false,
556                package: None,
557            }
558        })
559        .collect()
560}
561
562/// #3242: whether `dir` is the root of another project: it holds its own
563/// `bynk.toml`. Discovery never crosses such a boundary, the way it never enters
564/// `out/`. The directory a walk *starts* at is not tested, only the
565/// subdirectories below it, so a project's own root is never its own boundary.
566pub fn is_project_boundary(dir: &Path) -> bool {
567    dir.join("bynk.toml").is_file()
568}
569
570/// #3242: the projects nested below `root`: each directory under it holding its
571/// own `bynk.toml`, outermost only (a project's own subtree isn't entered), in
572/// path order. Walked as discovery walks, skipping `excludes`, hidden
573/// directories and the tool's `out` and `node_modules` caches. `root` itself is
574/// not reported even if it holds a manifest.
575pub fn nested_projects(root: &Path, excludes: &[PathBuf]) -> Vec<PathBuf> {
576    let mut found = Vec::new();
577    let mut stack = vec![root.to_path_buf()];
578    while let Some(dir) = stack.pop() {
579        let Ok(rd) = fs::read_dir(&dir) else {
580            continue;
581        };
582        for entry in rd.flatten() {
583            let p = entry.path();
584            if !p.is_dir() || is_skipped_dir(&p, excludes) {
585                continue;
586            }
587            if is_project_boundary(&p) {
588                found.push(p);
589            } else {
590                stack.push(p);
591            }
592        }
593    }
594    found.sort();
595    found
596}
597
598/// #3242: whether any `.bynk` file sits under `dir`, walked as discovery walks
599/// (hidden directories and the `out`/`node_modules` caches skipped).
600pub fn holds_bynk_source(dir: &Path) -> bool {
601    let Ok(rd) = fs::read_dir(dir) else {
602        return false;
603    };
604    rd.flatten().any(|entry| {
605        let p = entry.path();
606        if p.is_dir() {
607            let name = entry.file_name();
608            let name = name.to_string_lossy();
609            !name.starts_with('.')
610                && name != "out"
611                && name != "node_modules"
612                && holds_bynk_source(&p)
613        } else {
614            p.extension().and_then(|e| e.to_str()) == Some("bynk")
615        }
616    })
617}
618
619/// Whether a walk skips `dir`: an author `exclude`, or a hidden directory.
620pub(crate) fn is_skipped_dir(dir: &Path, excludes: &[PathBuf]) -> bool {
621    excludes.iter().any(|ex| dir == ex || dir.starts_with(ex))
622        || dir
623            .file_name()
624            .and_then(|n| n.to_str())
625            .is_some_and(|n| n.starts_with('.') && n != ".")
626        || dir
627            .file_name()
628            .and_then(|n| n.to_str())
629            .is_some_and(|n| n == "out" || n == "node_modules")
630}
631
632pub fn discover_bynk_files(
633    root: &Path,
634    excludes: &[PathBuf],
635) -> Result<Vec<PathBuf>, CompileError> {
636    if !root.exists() {
637        return Err(CompileError::new(
638            "bynk.project.no_root",
639            Span::default(),
640            format!("project root does not exist: {}", root.display()),
641        ));
642    }
643    // v0.113: skip excluded subtrees (author `exclude` + the tool's own caches)
644    // and hidden directories, so an `include` root at the project root does not
645    // sweep up generated, vendored, or dot-directory `.bynk`.
646    let is_excluded = |dir: &Path| {
647        excludes.iter().any(|ex| dir == ex || dir.starts_with(ex))
648            || dir
649                .file_name()
650                .and_then(|n| n.to_str())
651                .is_some_and(|n| n.starts_with('.') && n != ".")
652    };
653    let mut out = Vec::new();
654    let mut stack = vec![root.to_path_buf()];
655    while let Some(dir) = stack.pop() {
656        let rd = match fs::read_dir(&dir) {
657            Ok(r) => r,
658            Err(e) => {
659                return Err(CompileError::new(
660                    "bynk.project.read_failed",
661                    Span::default(),
662                    format!("could not read directory `{}`: {e}", dir.display()),
663                ));
664            }
665        };
666        for entry in rd.flatten() {
667            let p = entry.path();
668            if p.is_dir() {
669                // #3242: another project's root is that project's, not ours.
670                if !is_excluded(&p) && !is_project_boundary(&p) {
671                    stack.push(p);
672                }
673            } else if p.extension().and_then(|e| e.to_str()) == Some("bynk") {
674                out.push(p);
675            }
676        }
677    }
678    out.sort();
679    Ok(out)
680}
681
682/// Slice A: the `.bynk` files these roots contain — the **same walk**
683/// `compile_project` performs, honouring `exclude` and the tool's own `out`/
684/// `node_modules` caches.
685///
686/// P4.2 (#1122, Decision B): moved here from `bynk-emit/src/project.rs` — its
687/// body called only `bynk-project`-local functions already, with no
688/// `bynk-emit`-specific state. `bynk-emit` re-exports it at its existing
689/// `bynk_driver::project::discover_project_files` path so `read_disk_sources`
690/// and `bynk-testkit` need no edit; `bynk-ide` calls this path directly.
691pub fn discover_project_files(roots: &Roots) -> Vec<PathBuf> {
692    let mut trees = roots.trees();
693    // #2223: a manifest-backed project's path dependencies are part of it, so
694    // the editor's content sweep and the test kit read their files too.
695    if let Roots::Split { project_root, .. } = roots {
696        trees.extend(crate::packages::dependency_trees(
697            project_root,
698            &HashMap::new(),
699        ));
700    }
701    let excludes = roots.excludes();
702    let mut out = Vec::new();
703    for (root, _prefix) in &trees {
704        // Every tree past the first is optional — a project may simply have
705        // no such subtree (R3.9, #1113: every `include` entry is walked, not
706        // just the first two). `unwrap_or_default` already treats a missing
707        // root the same as "no files here" for every tree, first included —
708        // no need to `root.exists()` before calling `discover_bynk_files`
709        // (itself a `fs::read_dir`) just to decide whether to call it: that
710        // would cost a redundant `stat()` per tree for the same answer.
711        out.extend(discover_bynk_files(root, &excludes).unwrap_or_default());
712    }
713    out.sort();
714    out.dedup();
715    out
716}
717
718pub fn check_file_directory_conflicts(
719    root: &Path,
720    files: &[PathBuf],
721) -> Result<(), Vec<CompileError>> {
722    let mut errors: Vec<CompileError> = Vec::new();
723    let mut bynk_files: HashSet<PathBuf> = HashSet::new();
724    let mut dirs_with_bynk: HashSet<PathBuf> = HashSet::new();
725    for p in files {
726        let rel = p.strip_prefix(root).unwrap_or(p);
727        bynk_files.insert(rel.to_path_buf());
728        if let Some(parent) = rel.parent() {
729            dirs_with_bynk.insert(parent.to_path_buf());
730        }
731    }
732    for f in &bynk_files {
733        let stem = f.with_extension("");
734        if dirs_with_bynk.contains(&stem) {
735            errors.push(
736                CompileError::new(
737                    "bynk.project.file_and_directory",
738                    Span::default(),
739                    format!(
740                        "commons at `{}` is ambiguous: both `{}` and `{}/` exist with `.bynk` content",
741                        f.with_extension("").display(),
742                        f.display(),
743                        stem.display()
744                    ),
745                )
746                .with_note(
747                    "a commons can be a single `.bynk` file OR a directory of `.bynk` files, not both",
748                ),
749            );
750        }
751    }
752    if errors.is_empty() {
753        Ok(())
754    } else {
755        Err(errors)
756    }
757}
758
759#[cfg(test)]
760mod tests {
761    use super::*;
762
763    /// #1662: discovery reports a missing project root as a diagnostic, which
764    /// a library host (the LSP, a multi-root build) surfaces as-is; the CLI
765    /// checks the path itself first, so only this test reaches the code.
766    #[test]
767    fn a_missing_root_is_reported_as_no_root() {
768        let root = std::env::temp_dir().join(format!(
769            "bynk-discovery-no-root-{}-does-not-exist",
770            std::process::id()
771        ));
772        let err =
773            discover_bynk_files(&root, &[]).expect_err("a missing root must not discover files");
774        assert_eq!(err.category, "bynk.project.no_root");
775    }
776
777    /// Finding #55/#65: a synthetic path that never exists on disk (the
778    /// in-memory/wasm case) must still resolve via the overlay's literal-path
779    /// entry — `canonicalize()` on such a path always fails, so the fix tries
780    /// the literal path first rather than paying for that failing syscall on
781    /// every read.
782    #[test]
783    fn read_source_finds_a_synthetic_overlay_path_that_does_not_exist_on_disk() {
784        let path = PathBuf::from("./__bynk_in_memory__/t.bynk");
785        let mut overlay = HashMap::new();
786        overlay.insert(path.clone(), "context t\n".to_string());
787        let got = read_source(&path, &overlay).expect("the overlay entry must be found");
788        assert_eq!(got, "context t\n");
789    }
790
791    /// Content-ownership track (#1086) slice 5: a real on-disk file with no
792    /// overlay entry must now error, never silently fall back to reading it
793    /// off disk — the disk-read fallback this test guards the absence of was
794    /// deleted in this slice; every caller supplies a complete overlay.
795    #[test]
796    fn read_source_errors_on_a_real_file_with_no_overlay_entry_rather_than_reading_disk() {
797        let dir = std::env::temp_dir().join(format!(
798            "bynk-emit-discovery-fallback-test-{}",
799            std::process::id()
800        ));
801        std::fs::create_dir_all(&dir).expect("create test dir");
802        let path = dir.join("t.bynk");
803        std::fs::write(&path, "context t\n").expect("write real file");
804        let got = read_source(&path, &HashMap::new());
805        std::fs::remove_dir_all(&dir).ok();
806        assert!(
807            got.is_err(),
808            "a real file with no overlay entry must not be silently read from disk"
809        );
810        assert_eq!(got.unwrap_err().kind(), std::io::ErrorKind::NotFound);
811    }
812}