Skip to main content

blue_lang_runtime/
uses.rs

1//! `use("name")` — how a blue program consumes a bidama.
2//!
3//! ## The gap this closes
4//!
5//! Before this, blue's packaging had a manifest (`Bluefile`), a resolver
6//! (`blue-lang-pkg`), a git registry and a nix derivation per package — and
7//! **no way for a program to consume any of it**. `retsu/Bluefile` declared
8//! `needs("kazu", "^0.1")` while `retsu`'s source never referenced a single
9//! thing from kazu, because the language had no import form at all. The
10//! dependency graph was described by four layers and traversed by none.
11//!
12//! That is the difference between packaging that exists and packaging that
13//! works, and it is why this is a load-bearing addition rather than a
14//! convenience: a distribution whose packages cannot see each other is a
15//! directory of unrelated files wearing a distribution's name.
16//!
17//! ## Why a pipeline pass and not a builtin
18//!
19//! A `register_fn` native takes `(&[Value], &mut H, Span)`. It cannot define
20//! anything, because it never sees the interpreter — so `use` implemented as a
21//! builtin could load a package's text and would have nowhere to put its
22//! definitions. Resolution therefore happens on the FORM tree, before
23//! evaluation: a `use` is replaced by the forms of the package it names, and
24//! the whole program is then checked and run as one unit.
25//!
26//! That ordering is deliberate and worth stating, because it decides a real
27//! behaviour: the type checker sees the imported code, so a package that fails
28//! `blue-lang-check` fails at the point its consumer imports it rather than at
29//! whatever later moment its code first ran.
30//!
31//! ## Why the loader is a trait
32//!
33//! Loading a package means reading a filesystem, and this crate compiles to
34//! `wasm32-unknown-unknown` with zero host imports (`blue-lang-wasm`). A
35//! direct `std::fs` call here would break that target for every consumer,
36//! including ones that never call `use`.
37//!
38//! So the capability is injected — [`Loader`] here, the real filesystem
39//! implementation in `blue-lang-pkg`, which is native-only. This is the
40//! fleet's mockable-`Environment` seam, and it buys the usual thing: every
41//! test below drives the whole resolution pass against an in-memory loader,
42//! with no temp directories and no fixture files on disk.
43//!
44//! ## Why this module also owns file identity
45//!
46//! Splicing several files into one program is exactly the act that destroys a
47//! byte offset's meaning, so the record of where each form came from is kept by
48//! the pass that does the splicing rather than reconstructed downstream by
49//! something that no longer has the sources. [`ResolvedProgram`] is that
50//! record, and [`ResolvedProgram::locate`] spends it.
51
52use std::collections::BTreeSet;
53use std::path::{Path, PathBuf};
54
55use tatara_lisp::{Sexp, Span, Spanned};
56
57/// Supplies the source of a named bidama.
58///
59/// One method, because resolution needs exactly one thing: given a name, the
60/// blue source that name refers to. *Where* it came from — a working tree, a
61/// nix store path, a git object, memory — is the implementation's business and
62/// deliberately invisible here.
63pub trait Loader {
64    /// The `.b` sources of `name`, as `(label, source)` pairs.
65    ///
66    /// The label is for diagnostics only; nothing keys on it. A package with
67    /// several files returns several pairs, and their relative order is the
68    /// implementation's to fix — [`FsLoader`](../../blue_lang_pkg/load_path/index.html)
69    /// sorts by filename so a load is reproducible rather than
70    /// directory-order-dependent.
71    ///
72    /// `Err` is a human-readable reason the package could not be loaded. It
73    /// must name what was looked for, because "package not found" without a
74    /// name sends the reader grepping a distribution to find which one.
75    fn load(&self, name: &str) -> Result<Vec<(String, String)>, String>;
76
77    /// The bidama an ENTRY file at `path` belongs to, if it belongs to one:
78    /// the `package(name, …)` of the Bluefile beside it. `blue test
79    /// bidamas/retsu/retsu.b` checks and runs retsu's own definitions, under
80    /// retsu's namespace, exactly as an importer sees them.
81    ///
82    /// A file with no bidama around it (a script, `spec/*.b`) is in the root
83    /// namespace, and so is every entry a loader without a filesystem is
84    /// handed, which is this default.
85    fn entry_package(&self, _path: &Path) -> Option<String> {
86        None
87    }
88
89    /// The bidamas `package`'s Bluefile.lock records as `needs` (with no lock,
90    /// its Bluefile's rows), when the loader can read it.
91    /// `None` when it cannot, and the check stage then has nothing to compare
92    /// the package's `use` forms against (B0019).
93    ///
94    /// `entry_dir` is the directory of the entry file, for the entry's own
95    /// bidama, which a loader may not find under its roots.
96    fn needs(&self, _package: &str, _entry_dir: Option<&Path>) -> Option<BTreeSet<String>> {
97        None
98    }
99
100    /// Bidama `package`'s Bluefile version, when the loader can read it —
101    /// what a `legacy_names` window is measured against.
102    fn version(&self, _package: &str, _entry_dir: Option<&Path>) -> Option<String> {
103        None
104    }
105
106    /// The spanned tree of one source this loader handed out, or of the entry.
107    /// Resolution parses through here, so a loader that has seen a text
108    /// before (an editor's session) can answer without parsing it again.
109    ///
110    /// # Errors
111    ///
112    /// The parser's, unchanged.
113    fn parse(&self, src: &str) -> Result<Vec<Spanned>, blue_lang_syntax::ParseError> {
114        blue_lang_syntax::parse_program_tree(src)
115    }
116
117    /// Every bidama this loader could load, by name, when it can enumerate
118    /// them: what an editor offers behind a `use` the file does not have yet.
119    fn available(&self) -> Vec<String> {
120        Vec::new()
121    }
122
123    fn frontend(&self, _entry: &Path) -> Option<Frontend> {
124        None
125    }
126}
127
128#[derive(Clone, Debug, Default, PartialEq, Eq)]
129pub struct Frontend {
130    pub table: Option<(String, String)>,
131    pub view: bool,
132}
133
134/// A loader that resolves nothing, and says so.
135///
136/// The default for [`run`](crate::pipeline::run), so a program using `use` in
137/// a context with no packaging configured gets a typed error naming the
138/// package — not a silently-undefined function that fails much later as an
139/// unbound symbol pointing at innocent code.
140pub struct NoLoader;
141
142impl Loader for NoLoader {
143    fn load(&self, name: &str) -> Result<Vec<(String, String)>, String> {
144        Err(format!(
145            "cannot load bidama \"{name}\": no loader is installed. A program \
146             that uses packages must run with one — `blue_lang_pkg::LoadPath` \
147             reads BLUE_PATH, which `nix develop` and the bidama derivations \
148             populate."
149        ))
150    }
151}
152
153pub trait Scopes {
154    fn scope(&self, entry: Option<&Path>) -> Vec<PathBuf>;
155    fn loader(&self, scope: &[PathBuf]) -> std::rc::Rc<dyn Loader>;
156    fn set_workspace(&mut self, _folders: Vec<PathBuf>) {}
157}
158
159pub struct OneScope(pub std::rc::Rc<dyn Loader>);
160
161impl Scopes for OneScope {
162    fn scope(&self, _entry: Option<&Path>) -> Vec<PathBuf> {
163        Vec::new()
164    }
165
166    fn loader(&self, _scope: &[PathBuf]) -> std::rc::Rc<dyn Loader> {
167        self.0.clone()
168    }
169}
170
171/// Identity of one source file inside a [`ResolvedProgram`].
172///
173/// Opaque on purpose. It means nothing outside the program that minted it, and
174/// the only way to spend it is [`ResolvedProgram::file`] — a caller that could
175/// compute a file index is a caller that can compute the *wrong* one, which is
176/// the failure this whole type exists to make impossible.
177#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
178pub struct FileId(usize);
179
180impl FileId {
181    /// The file's position in its program's file table: a key, never an
182    /// index a caller may compute.
183    #[must_use]
184    pub fn index(self) -> usize {
185        self.0
186    }
187}
188
189/// One file that contributed forms to a [`ResolvedProgram`].
190#[derive(Clone, Debug)]
191pub struct SourceFile {
192    /// Its handle in the program that owns it.
193    pub id: FileId,
194    /// Where it came from.
195    ///
196    /// `None` only for an entry program handed to the pipeline as bare text —
197    /// an embedder, a test, a WASM host. An imported file always has one,
198    /// because a [`Loader`] cannot name a package without naming a place.
199    pub path: Option<PathBuf>,
200    /// The bidama this file belongs to — the name `use` was given, or for the
201    /// entry file its [`Loader::entry_package`] — or `None` for a file in the
202    /// root namespace. The namespace its definitions are resolved under
203    /// (`blue_lang_check::Namespace::Bidama`).
204    pub package: Option<String>,
205    /// The file's text.
206    ///
207    /// Kept, not dropped after parsing, because a [`Span`] is a byte range and
208    /// nothing else: turning one into `line:col` needs the exact string it
209    /// indexes. Before this, `resolve_uses` read a package's source and let it
210    /// fall out of scope one line later, which is why an imported type error
211    /// had no position to report.
212    pub text: String,
213}
214
215/// The program the pipeline was handed, and what to call it.
216///
217/// The path travels *with* the text rather than beside it, so a caller cannot
218/// name one file and hand over another's source — the pairing is what every
219/// position in the entry file is resolved against.
220#[derive(Clone, Copy, Debug)]
221pub struct Entry<'a> {
222    /// The file the text was read from, if it was read from one.
223    pub path: Option<&'a Path>,
224    /// The source itself.
225    pub text: &'a str,
226}
227
228impl<'a> Entry<'a> {
229    /// An entry program with no file behind it.
230    #[must_use]
231    pub fn anonymous(text: &'a str) -> Self {
232        Self { path: None, text }
233    }
234}
235
236/// A program with its imports spliced in, and the file each top-level form
237/// came from.
238///
239/// ## Why file identity is per TOP-LEVEL FORM
240///
241/// [`resolve_uses`] splices whole files' worth of top-level forms: a `use` is
242/// replaced by every form of the package it names, in order. So a boundary
243/// between two files is always a boundary between two top-level forms, and
244/// every node beneath a top-level form came from exactly one file — the one
245/// that form came from. **A `FileId` per top-level form is therefore exactly as
246/// precise as a `FileId` per node**, at a fraction of the cost and with nothing
247/// upstream to change.
248///
249/// That last part is the point. `Span` lives in tatara-lisp and carries no file
250/// identity by a documented decision — "Spans are not portable across source
251/// inputs — they are meaningful only relative to the string that produced them,
252/// which the caller is responsible for holding onto." blue is the caller. This
253/// is blue holding onto them, beside the span rather than inside it.
254///
255/// ## Why the fields are private
256///
257/// `forms` and `owner` are parallel, and `files[i].id` is `FileId(i)`. Both
258/// invariants are maintained by `push` and `intern`, the only places either
259/// vector grows, and by [`retain`](Self::retain), the only place either
260/// shrinks. Public fields would make `program.forms.retain(...)` — the exact
261/// call `pipeline::run_in_surface` makes to drop `test` blocks — shift every
262/// form off its owner by one and report every subsequent diagnostic against the
263/// wrong file, silently.
264#[derive(Debug)]
265pub struct ResolvedProgram {
266    forms: Vec<Spanned>,
267    owner: Vec<FileId>,
268    files: Vec<SourceFile>,
269    imports: Vec<(FileId, Import)>,
270    needs: std::collections::BTreeMap<String, BTreeSet<String>>,
271    versions: std::collections::BTreeMap<String, String>,
272    frontend: Option<Frontend>,
273}
274
275impl ResolvedProgram {
276    /// The entry program's own file. Always present; always first.
277    pub const ENTRY: FileId = FileId(0);
278
279    fn new(entry: Entry<'_>, package: Option<String>) -> Self {
280        let mut program = Self {
281            forms: Vec::new(),
282            owner: Vec::new(),
283            files: Vec::new(),
284            imports: Vec::new(),
285            needs: std::collections::BTreeMap::new(),
286            versions: std::collections::BTreeMap::new(),
287            frontend: None,
288        };
289        let id = program.intern(
290            entry.path.map(Path::to_path_buf),
291            package,
292            entry.text.to_owned(),
293        );
294        debug_assert_eq!(id, Self::ENTRY);
295        program
296    }
297
298    /// Record a file's text and hand back its handle.
299    fn intern(&mut self, path: Option<PathBuf>, package: Option<String>, text: String) -> FileId {
300        let id = FileId(self.files.len());
301        self.files.push(SourceFile {
302            id,
303            path,
304            package,
305            text,
306        });
307        id
308    }
309
310    /// Append a top-level form together with the file it came from.
311    ///
312    /// The ONE place `forms` and `owner` grow, so they cannot grow apart.
313    fn push(&mut self, form: Spanned, owner: FileId) {
314        self.forms.push(form);
315        self.owner.push(owner);
316    }
317
318    #[must_use]
319    pub fn frontend(&self) -> Option<&Frontend> {
320        self.frontend.as_ref()
321    }
322
323    /// Every top-level form, in evaluation order.
324    #[must_use]
325    pub fn forms(&self) -> &[Spanned] {
326        &self.forms
327    }
328
329    /// The same forms with their spans projected away, for the stages that do
330    /// not report positions — erasure, evaluation, the test harness. A `use`
331    /// form is a declaration the resolver consumed, and projects to `nil`, so
332    /// every index still names its top-level form.
333    #[must_use]
334    pub fn sexps(&self) -> Vec<Sexp> {
335        self.forms
336            .iter()
337            .map(|f| {
338                if use_target(f).is_some() || blue_lang_syntax::scope::legacy_target(f).is_some() {
339                    Sexp::Nil
340                } else {
341                    f.to_sexp()
342                }
343            })
344            .collect()
345    }
346
347    /// Each loaded bidama's Bluefile `needs`, where the loader read one.
348    #[must_use]
349    pub fn needs(&self) -> &std::collections::BTreeMap<String, BTreeSet<String>> {
350        &self.needs
351    }
352
353    /// Each loaded bidama's Bluefile version, where the loader read one.
354    #[must_use]
355    pub fn versions(&self) -> &std::collections::BTreeMap<String, String> {
356        &self.versions
357    }
358
359    /// Every `use` form, with the file that wrote it.
360    #[must_use]
361    pub fn imports(&self) -> &[(FileId, Import)] {
362        &self.imports
363    }
364
365    /// Every file that contributed, entry first.
366    #[must_use]
367    pub fn files(&self) -> &[SourceFile] {
368        &self.files
369    }
370
371    /// Which file the `top_level`-th form came from.
372    #[must_use]
373    pub fn owner_of(&self, top_level: usize) -> Option<FileId> {
374        self.owner.get(top_level).copied()
375    }
376
377    /// A file by its handle.
378    #[must_use]
379    pub fn file(&self, id: FileId) -> Option<&SourceFile> {
380        self.files.get(id.0)
381    }
382
383    /// Drop the top-level forms `keep` rejects, taking their owners with them.
384    ///
385    /// The lockstep is the whole reason this method exists rather than a public
386    /// `forms` field: `Vec::retain` on one of two parallel vectors is a silent
387    /// mis-attribution, not a compile error.
388    pub fn retain(&mut self, keep: impl Fn(&Spanned) -> bool) {
389        // Zipped rather than two `Vec::retain` calls over the same predicate:
390        // this way the pairing is carried by the iterator instead of by two
391        // traversals agreeing, and there is no order assumption to be wrong
392        // about.
393        let paired = std::mem::take(&mut self.forms)
394            .into_iter()
395            .zip(std::mem::take(&mut self.owner));
396        for (form, owner) in paired {
397            if keep(&form) {
398                self.push(form, owner);
399            }
400        }
401    }
402
403    /// Resolve a diagnostic's position against the file it actually came from.
404    ///
405    /// `top_level` is `blue_lang_check::Diagnostic::top_level` — the join key.
406    /// An index with no owner (a diagnostic that escaped stamping) renders
407    /// without a position rather than borrowing the entry file's: a missing
408    /// position costs the reader a search, a wrong one sends them to innocent
409    /// code and is believed.
410    #[must_use]
411    pub fn locate<'a>(&'a self, top_level: usize, span: Span, message: &'a str) -> Located<'a> {
412        let Some(file) = self.owner_of(top_level).and_then(|id| self.file(id)) else {
413            return Located {
414                origin: Origin::Unresolved,
415                line_col: None,
416                message,
417            };
418        };
419        Located {
420            origin: file.path.as_deref().map_or(Origin::Anonymous, Origin::File),
421            // A synthetic span indexes nothing, so it resolves to no line —
422            // `Span::line_col` would happily answer for `usize::MAX` by walking
423            // off the end and returning the last position in the file.
424            //
425            // **And so would a span that is real but belongs to a DIFFERENT
426            // file**, which is the case a runtime error can reach and a check
427            // error cannot: a check diagnostic's span is a node inside the very
428            // top-level form it is stamped with, so it is in range by
429            // construction, while a raise inside a callee carries the callee's
430            // offsets and the executing top-level form may be someone else's.
431            // An out-of-range offset is proof the span is not this file's, and
432            // `line_col` answers it anyway with the file's last position — a
433            // fabricated `path:line:col` a reader has every reason to believe.
434            // Refuse instead, which is `EvalError::render`'s own rule
435            // (`span.end > src.len()` → no source context) applied at the one
436            // place blue owns the file table.
437            //
438            // In range is NECESSARY, not sufficient: two files long enough to
439            // share an offset can still trade a plausible number. A runtime
440            // error now avoids that by locating against the innermost frame's
441            // definition (`observe::Fault`), so the residue is a frame with no
442            // named definition, not a wider guard here.
443            line_col: (!span.is_synthetic() && span.end <= file.text.len())
444                .then(|| Span::line_col(&file.text, span.start)),
445            message,
446        }
447    }
448}
449
450/// What a position is being reported against.
451#[derive(Clone, Copy, Debug)]
452enum Origin<'a> {
453    File(&'a Path),
454    /// Source handed over as text, with no file behind it.
455    Anonymous,
456    /// No owning file could be found. Distinct from [`Origin::Anonymous`] on
457    /// purpose: "you gave me unnamed text" and "I lost track of where this came
458    /// from" are different admissions, and collapsing them would hide the
459    /// second inside the first.
460    Unresolved,
461}
462
463/// A diagnostic rendered against the file it came from: `path:line:col: text`.
464///
465/// A typed `Display` rather than a `format!` at the call site, per ★★ TYPED
466/// EMISSION — the shape every editor and every `cc` already knows how to jump
467/// to, produced by exactly one `write!`.
468#[derive(Clone, Copy, Debug)]
469pub struct Located<'a> {
470    origin: Origin<'a>,
471    line_col: Option<(usize, usize)>,
472    message: &'a str,
473}
474
475impl Located<'_> {
476    /// The file it names, as [`std::fmt::Display`] prints it: a path,
477    /// `<anonymous>`, or `None` when no owning file could be found.
478    #[must_use]
479    pub fn file_name(&self) -> Option<String> {
480        match self.origin {
481            Origin::File(p) => Some(p.display().to_string()),
482            Origin::Anonymous => Some("<anonymous>".to_string()),
483            Origin::Unresolved => None,
484        }
485    }
486
487    /// The 1-based line and column, when the span is a real range in that file.
488    #[must_use]
489    pub fn line_col(&self) -> Option<(usize, usize)> {
490        self.line_col
491    }
492}
493
494impl std::fmt::Display for Located<'_> {
495    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
496        match self.origin {
497            Origin::File(p) => write!(f, "{}", p.display())?,
498            Origin::Anonymous => f.write_str("<anonymous>")?,
499            Origin::Unresolved => f.write_str("<unknown file>")?,
500        }
501        if let Some((line, col)) = self.line_col {
502            write!(f, ":{line}:{col}")?;
503        }
504        write!(f, ": {}", self.message)
505    }
506}
507
508pub use blue_lang_syntax::scope::{use_target, Import};
509
510/// Is this form a lowered `test` block?
511///
512/// `test "…" … end` lowers to `(deftest …)`, which only the test harness
513/// binds. Public because two callers need it and for opposite reasons: the
514/// resolver drops IMPORTED tests (a dependency's tests are not the importer's
515/// to run), and `pipeline::run` drops ALL of them (a `test` block is a
516/// declaration for the harness, not code to execute — without this,
517/// `blue run` on any file that contains its own tests dies on an unbound
518/// `deftest`, which is every package in this distribution).
519pub fn is_test_form(form: &Spanned) -> bool {
520    let Some(items) = form.as_list() else {
521        return false;
522    };
523    matches!(items.first().and_then(Spanned::as_symbol), Some("deftest"))
524}
525
526/// Replace every `use(...)` with the forms of the package it names.
527///
528/// Transitive by construction: a loaded package's own `use` calls are resolved
529/// the same way, depth-first, so a consumer names its direct dependency and
530/// gets the closure.
531///
532/// **A package is loaded at most once.** Two importers of one package must
533/// share its definitions — loading twice would re-evaluate them, which is at
534/// best wasted work and at worst two distinct copies of anything stateful.
535/// That same visited-set is what makes a dependency CYCLE terminate: the
536/// second visit is a no-op rather than infinite recursion, so a cyclic
537/// distribution loads and runs instead of hanging.
538///
539/// The result carries **which file each top-level form came from** — see
540/// [`ResolvedProgram`] for why that is per top-level form and not per node.
541///
542/// # Errors
543///
544/// Returns the loader's message, prefixed with the import chain that reached
545/// it, when a package cannot be loaded or its source cannot be parsed.
546pub fn resolve_uses(
547    forms: Vec<Spanned>,
548    entry: Entry<'_>,
549    loader: &dyn Loader,
550) -> Result<ResolvedProgram, String> {
551    let package = entry.path.and_then(|p| loader.entry_package(p));
552    let mut seen = BTreeSet::new();
553    // The entry's own bidama is already loaded: it IS the entry. A cycle back
554    // to it must not splice a second copy of its definitions in.
555    if let Some(p) = &package {
556        seen.insert(p.clone());
557    }
558    let mut out = ResolvedProgram::new(entry, package.clone());
559    out.frontend = entry.path.and_then(|p| loader.frontend(p));
560    if let Some(p) = &package {
561        if let Some(n) = loader.needs(p, entry.path.and_then(Path::parent)) {
562            out.needs.insert(p.clone(), n);
563        }
564        if let Some(v) = loader.version(p, entry.path.and_then(Path::parent)) {
565            out.versions.insert(p.clone(), v);
566        }
567    }
568    expand(
569        forms,
570        ResolvedProgram::ENTRY,
571        loader,
572        &mut out,
573        &mut seen,
574        &[],
575    )?;
576    Ok(out)
577}
578
579fn expand(
580    forms: Vec<Spanned>,
581    owner: FileId,
582    loader: &dyn Loader,
583    out: &mut ResolvedProgram,
584    seen: &mut BTreeSet<String>,
585    chain: &[String],
586) -> Result<(), String> {
587    for form in forms {
588        let Some(import) = use_target(&form) else {
589            // The file boundary is erased HERE — this is the append that used
590            // to make every form indistinguishable from every other. Each one
591            // now carries the file it came from, which is the whole fix.
592            out.push(form, owner);
593            continue;
594        };
595        let name = import.package.clone();
596        out.imports.push((owner, import));
597        if !seen.insert(name.clone()) {
598            // Loaded already: the declaration stays, for the check stage.
599            out.push(form, owner);
600            continue;
601        }
602
603        let sources = loader.load(&name).map_err(|e| describe(chain, &name, &e))?;
604        if let Some(n) = loader.needs(&name, None) {
605            out.needs.insert(name.clone(), n);
606        }
607        if let Some(v) = loader.version(&name, None) {
608            out.versions.insert(name.clone(), v);
609        }
610        let mut inner_chain = chain.to_vec();
611        inner_chain.push(name.clone());
612
613        for (label, src) in sources {
614            // `parse_program_tree`, not `parse_program`. The spanless door
615            // discarded every imported position one line after the text
616            // arrived, so an imported type error had nothing to report but a
617            // message — see `ResolvedProgram`.
618            let parsed = loader
619                .parse(&src)
620                .map_err(|e| describe(chain, &name, &format!("{label}: {e}")))?;
621            // An imported package's TEST blocks do not come along.
622            //
623            // A dependency's tests are not the importer's to run, and trying
624            // is not merely untidy — it is a hard failure. `test` lowers to
625            // `deftest`, which only the test harness binds, so the ordinary
626            // evaluator sees an unbound symbol. Measured, the moment kazu
627            // gained test blocks: every program importing it died with
628            // `unbound symbol: deftest`, pointing at a line the importer never
629            // wrote.
630            //
631            // Dropping them here also makes the distribution gate honest for
632            // free: `blue test kikagaku.b` now reports kikagaku's tests
633            // rather than kikagaku's plus everything it transitively imports.
634            let parsed: Vec<Spanned> = parsed.into_iter().filter(|f| !is_test_form(f)).collect();
635            // Interned AFTER parsing, so a package that does not parse never
636            // becomes a file in the table — and BEFORE the recursion, because
637            // every form below belongs to this file, not to the importer's.
638            let id = out.intern(Some(PathBuf::from(label)), Some(name.clone()), src);
639            expand(parsed, id, loader, out, seen, &inner_chain)?;
640        }
641        // The declaration itself, after the forms it brought in.
642        out.push(form, owner);
643    }
644    Ok(())
645}
646
647/// Prefix a failure with the import chain that reached it.
648///
649/// A transitive failure otherwise names only the leaf, and the reader has no
650/// way to tell which of their own imports pulled it in — the exact question
651/// they need answered to fix it.
652fn describe(chain: &[String], name: &str, reason: &str) -> String {
653    if chain.is_empty() {
654        return reason.to_owned();
655    }
656    format!("while loading {} -> {name}: {reason}", chain.join(" -> "))
657}
658
659#[cfg(test)]
660pub(crate) mod tests {
661    use super::*;
662    use std::collections::BTreeMap;
663
664    /// An in-memory distribution — the whole pass runs with no filesystem.
665    pub(crate) struct MemLoader(pub(crate) BTreeMap<&'static str, &'static str>);
666
667    impl Loader for MemLoader {
668        fn load(&self, name: &str) -> Result<Vec<(String, String)>, String> {
669            self.0
670                .get(name)
671                .map(|s| vec![(format!("{name}.b"), (*s).to_owned())])
672                .ok_or_else(|| format!("no bidama named \"{name}\""))
673        }
674    }
675
676    fn parse(src: &str) -> Vec<Spanned> {
677        blue_lang_syntax::parse_program_tree(src).expect("test source must parse")
678    }
679
680    /// Resolve a program that came from nowhere in particular.
681    fn resolve(src: &str, loader: &dyn Loader) -> Result<ResolvedProgram, String> {
682        resolve_uses(parse(src), Entry::anonymous(src), loader)
683    }
684
685    #[test]
686    fn a_use_is_replaced_by_the_packages_forms() {
687        let loader = MemLoader(BTreeMap::from([("kazu", "def double(n)\n  n * 2\nend")]));
688        let out = resolve("use(\"kazu\")\ndouble(21)", &loader).expect("resolves");
689        // The `use` itself stays, for the check stage to point at, and never
690        // reaches the evaluator, where `use` is not a defined function: the
691        // evaluated projection has it as `nil`.
692        assert_eq!(
693            out.forms()
694                .iter()
695                .filter(|f| super::use_target(f).is_some())
696                .count(),
697            1
698        );
699        assert!(
700            !out.sexps().iter().any(|f| f.to_string().contains("use")),
701            "a use form would reach the evaluator as an unbound function: {:?}",
702            out.sexps()
703        );
704        assert!(
705            out.forms().len() > 1,
706            "the package's definitions must be spliced in, not dropped: {:?}",
707            out.forms()
708        );
709    }
710
711    #[test]
712    fn imports_are_transitive() {
713        let loader = MemLoader(BTreeMap::from([
714            ("retsu", "use(\"kazu\")\ndef sum2(a, b)\n  a + b\nend"),
715            ("kazu", "def double(n)\n  n * 2\nend"),
716        ]));
717        let out = resolve("use(\"retsu\")", &loader).expect("resolves");
718        // A consumer names retsu only; kazu arrives because retsu needs it.
719        assert!(
720            out.forms().len() >= 2,
721            "the transitive dependency did not arrive: {:?}",
722            out.forms()
723        );
724    }
725
726    #[test]
727    fn a_package_is_loaded_at_most_once() {
728        let loader = MemLoader(BTreeMap::from([("kazu", "def double(n)\n  n * 2\nend")]));
729        let once = resolve("use(\"kazu\")", &loader).expect("resolves");
730        let twice = resolve("use(\"kazu\")\nuse(\"kazu\")", &loader).expect("resolves");
731        let definitions = |p: &ResolvedProgram| {
732            p.forms()
733                .iter()
734                .filter(|f| super::use_target(f).is_none())
735                .count()
736        };
737        assert_eq!(
738            definitions(&once),
739            definitions(&twice),
740            "importing a package twice duplicated its definitions; two \
741             importers of one package must share it"
742        );
743        assert_eq!(
744            once.files().len(),
745            twice.files().len(),
746            "importing a package twice interned its source twice; the file \
747             table must have one entry per file, not one per import"
748        );
749    }
750
751    /// The property that keeps a cyclic distribution from hanging.
752    #[test]
753    fn a_dependency_cycle_terminates() {
754        let loader = MemLoader(BTreeMap::from([
755            ("a", "use(\"b\")\ndef fa()\n  1\nend"),
756            ("b", "use(\"a\")\ndef fb()\n  2\nend"),
757        ]));
758        let out = resolve("use(\"a\")", &loader).expect("a cycle must resolve");
759        assert!(
760            !out.forms().is_empty(),
761            "a cycle resolved to nothing: {:?}",
762            out.forms()
763        );
764    }
765
766    #[test]
767    fn a_missing_package_names_itself_and_the_chain() {
768        let loader = MemLoader(BTreeMap::from([("retsu", "use(\"nowhere\")")]));
769        let err = resolve("use(\"retsu\")", &loader).expect_err("must fail");
770        assert!(
771            err.contains("nowhere"),
772            "the error must name the missing package: {err}"
773        );
774        assert!(
775            err.contains("retsu"),
776            "the error must name the import that pulled it in, or the reader \
777             cannot tell which of their own imports is at fault: {err}"
778        );
779    }
780
781    #[test]
782    fn the_default_loader_refuses_by_name() {
783        let err = resolve("use(\"kazu\")", &NoLoader).expect_err("must fail");
784        assert!(
785            err.contains("kazu"),
786            "NoLoader must name what was asked for: {err}"
787        );
788    }
789
790    /// A non-`use` program must come out byte-identical.
791    ///
792    /// This pass runs on EVERY program, so a bug here would corrupt source
793    /// that never mentions a package.
794    /// An imported package's tests must NOT come along.
795    ///
796    /// Not a tidiness point: `deftest` is unbound outside the test harness, so
797    /// an inherited test block kills any program that imports a tested
798    /// package — which is every package in a distribution worth having.
799    #[test]
800    fn an_imported_packages_tests_are_not_inherited() {
801        let loader = MemLoader(BTreeMap::from([(
802            "kazu",
803            "def double(n)\n  n * 2\nend\n\ntest \"doubles\"\n  assert double(2) == 4\nend",
804        )]));
805        let out = resolve("use(\"kazu\")\ndouble(21)", &loader).expect("resolves");
806        assert!(
807            out.forms().iter().all(|f| !super::is_test_form(f)),
808            "an imported test block survived and would reach the evaluator as \
809             an unbound `deftest`: {:?}",
810            out.forms()
811        );
812        // The DEFINITIONS still arrive — dropping tests must not drop code.
813        assert!(
814            out.forms().len() >= 2,
815            "filtering tests also removed the package's definitions: {:?}",
816            out.forms()
817        );
818    }
819
820    /// But the ENTRY program keeps its own tests.
821    #[test]
822    fn the_entry_programs_own_tests_survive() {
823        let loader = MemLoader(BTreeMap::new());
824        let src = "def f(n)\n  n\nend\n\ntest \"t\"\n  assert f(1) == 1\nend";
825        let out = resolve(src, &loader).expect("resolves");
826        assert!(
827            out.forms().iter().any(super::is_test_form),
828            "the file's OWN tests were dropped; only imported ones should be: {:?}",
829            out.forms()
830        );
831    }
832
833    #[test]
834    fn a_program_without_imports_is_unchanged() {
835        let loader = MemLoader(BTreeMap::new());
836        let src = "def f(n)\n  n + 1\nend\nf(1)";
837        let before: Vec<Sexp> = parse(src).iter().map(Spanned::to_sexp).collect();
838        let out = resolve(src, &loader).expect("resolves");
839        assert_eq!(format!("{before:?}"), format!("{:?}", out.sexps()));
840    }
841
842    // ---- file identity ---------------------------------------------------
843
844    /// **Every form's span indexes ITS OWN file, and the text proves it.**
845    ///
846    /// The independent evidence is the source itself: slice each top-level
847    /// form's span out of the file its owner names and re-parse the slice. If
848    /// the owner is wrong the bytes are some other file's, and the re-parsed
849    /// tree does not match — checked against the tree, which the file table had
850    /// no hand in producing.
851    ///
852    /// This is the contract `Span`'s own docs put on the caller — spans "are
853    /// meaningful only relative to the string that produced them" — asserted
854    /// rather than assumed.
855    ///
856    /// **Red run** (2026-08-12), `expand` pushing `ResolvedProgram::ENTRY` as
857    /// every form's owner instead of `owner`:
858    /// ```text
859    /// form 0: its own source does not re-parse: expected an expression, found
860    /// Eof at 25..25
861    /// ```
862    /// It trips at the re-parse rather than the comparison, because kazu's
863    /// byte range cut against the entry file's text lands mid-token — which is
864    /// the mis-attribution stated in bytes.
865    ///
866    /// **Second red run**, the ORIGINAL spanless `parse_program` restored in
867    /// `expand` (the bug this change fixes):
868    /// ```text
869    /// form 0 has no position at all — its file was parsed through the
870    /// spanless door
871    /// ```
872    #[test]
873    fn every_forms_span_indexes_the_file_it_came_from() {
874        let loader = MemLoader(BTreeMap::from([
875            ("retsu", "use(\"kazu\")\ndef sum2(a, b)\n  a + b\nend"),
876            ("kazu", "def double(n)\n  n * 2\nend"),
877        ]));
878        let out = resolve("use(\"retsu\")\nsum2(double(1), 2)", &loader).expect("resolves");
879        assert_eq!(
880            out.files().len(),
881            3,
882            "expected the entry plus retsu plus kazu: {:?}",
883            out.files()
884        );
885        for (i, form) in out.forms().iter().enumerate() {
886            let file = out
887                .owner_of(i)
888                .and_then(|id| out.file(id))
889                .unwrap_or_else(|| panic!("form {i} has no owning file"));
890            assert!(
891                !form.span.is_synthetic(),
892                "form {i} has no position at all — its file was parsed through \
893                 the spanless door"
894            );
895            let slice = file
896                .text
897                .get(form.span.start..form.span.end)
898                .unwrap_or_else(|| {
899                    panic!(
900                        "form {i}'s span {:?} is not a range in its owner ({} bytes)",
901                        form.span,
902                        file.text.len()
903                    )
904                });
905            let reparsed = blue_lang_syntax::parse_program_tree(slice)
906                .unwrap_or_else(|e| panic!("form {i}: its own source does not re-parse: {e}"));
907            assert_eq!(
908                reparsed.iter().map(Spanned::to_sexp).collect::<Vec<_>>(),
909                vec![form.to_sexp()],
910                "form {i} sliced out of its owner ({}) re-parses to a different \
911                 tree; slice was {slice:?}",
912                file.path
913                    .as_deref()
914                    .map_or_else(|| "<anonymous>".to_string(), |p| p.display().to_string())
915            );
916        }
917        // Anti-vacuity: an empty program passes the loop above.
918        assert!(out.forms().len() >= 3, "{:?}", out.forms());
919    }
920
921    /// Dropping a form takes its owner with it.
922    ///
923    /// The parallel-vector failure, asserted directly: after `retain` removes
924    /// the entry file's `test` block, every surviving form must still resolve
925    /// to the file it came from. Checked through the same slice-and-re-parse
926    /// evidence, because "the lengths still match" would pass on a program
927    /// where every owner shifted by one.
928    ///
929    /// **Red run** (2026-08-12), `retain` filtering `self.forms` only and
930    /// leaving `self.owner` whole:
931    /// ```text
932    /// after retain, form 0 does not belong to the file it is attributed to:
933    /// slice "test \"t\"\n  assert 1 == 1\n" of <anonymous>
934    ///   left: []
935    ///  right: [List([Atom(Symbol("define")), …double…])]
936    /// ```
937    /// The surviving forms kept the DROPPED form's owner, so kazu's `double`
938    /// was attributed to the entry file and sliced out of it.
939    #[test]
940    fn retain_drops_a_forms_owner_with_it() {
941        let loader = MemLoader(BTreeMap::from([("kazu", "def double(n)\n  n * 2\nend")]));
942        let src = "test \"t\"\n  assert 1 == 1\nend\nuse(\"kazu\")\ndouble(21)";
943        let mut out = resolve(src, &loader).expect("resolves");
944        assert!(
945            out.forms().iter().any(super::is_test_form),
946            "the fixture must contain the test block this drops"
947        );
948        out.retain(|f| !super::is_test_form(f));
949        assert!(!out.forms().iter().any(super::is_test_form));
950        for (i, form) in out.forms().iter().enumerate() {
951            let file = out
952                .owner_of(i)
953                .and_then(|id| out.file(id))
954                .unwrap_or_else(|| panic!("form {i} lost its owner"));
955            let slice = &file.text[form.span.start..form.span.end];
956            let reparsed = blue_lang_syntax::parse_program_tree(slice)
957                .map(|f| f.iter().map(Spanned::to_sexp).collect::<Vec<_>>())
958                .unwrap_or_default();
959            assert_eq!(
960                reparsed,
961                vec![form.to_sexp()],
962                "after retain, form {i} does not belong to the file it is \
963                 attributed to: slice {slice:?} of {}",
964                file.path
965                    .as_deref()
966                    .map_or_else(|| "<anonymous>".to_string(), |p| p.display().to_string())
967            );
968        }
969        // `double`, the `use` declaration, and the call.
970        assert_eq!(out.forms().len(), 3, "{:?}", out.forms());
971    }
972
973    /// An unresolvable index reports no position rather than the entry file's.
974    #[test]
975    fn an_unstamped_diagnostic_gets_no_position_rather_than_a_wrong_one() {
976        let loader = MemLoader(BTreeMap::new());
977        let out = resolve("def f(n)\n  n\nend", &loader).expect("resolves");
978        let rendered = out
979            .locate(
980                blue_lang_check::Diagnostic::UNSTAMPED,
981                tatara_lisp::Span::new(0, 1),
982                "something went wrong",
983            )
984            .to_string();
985        assert_eq!(rendered, "<unknown file>: something went wrong");
986        assert!(
987            !rendered.contains(":1:1"),
988            "an unowned diagnostic borrowed a position from somewhere: {rendered}"
989        );
990    }
991}