Skip to main content

lex_syntax/
loader.rs

1//! Multi-file loader: resolves `import "./..."`, `import "../..."`, and
2//! `import "/abs/..."` statements relative to the importer, recursively
3//! parses, and produces a single [`Program`] with all stages merged.
4//!
5//! Names that are local to an imported file are mangled with a
6//! **per-file-path** prefix, so the same module imported via multiple
7//! aliases (or from multiple parents in a diamond shape) collapses to
8//! one set of mangled names — same SigId, same nominal identity.
9//! Stdlib imports (`import "std.foo" as bar`) pass through unchanged.
10//!
11//! ## Mangling
12//!
13//! Each loaded file gets a prefix derived from its filesystem path.
14//! The entry file's prefix is empty (so `lex run main.lex process`
15//! works unchanged). Imported files use `<stem>_<hash>` where `hash`
16//! is the first 8 hex chars of SHA-256 of the file's *mangling key*.
17//! The hash disambiguates same-stem files in different directories
18//! without forcing a project manifest.
19//!
20//! The mangling key is the canonical absolute path by default, and the
21//! path **relative to a caller-supplied root** when loading through
22//! [`load_program_with_root`] or [`load_package`]. Absolute paths are
23//! only stable as long as the tree stays put, which makes them unusable
24//! for anything that loads the same logical package from a fresh
25//! directory each time: a server unpacking an uploaded package into a
26//! per-request temp dir got a different prefix — and therefore a
27//! brand-new set of function names — for every file reached through a
28//! local import on every single request, so byte-identical republishes
29//! diffed as all-new functions and grew the branch's function set
30//! without bound (#826). Pass the package root and the key becomes
31//! `src/error.lex`, identical across requests. Files outside the root
32//! keep the absolute-path key (a dependency in the shared package cache
33//! lives at a stable absolute path of its own, and "relative to this
34//! package" says nothing useful about it).
35//!
36//! [`load_package`] adds a `namespace` ahead of the relative path
37//! (`lex-schema/src/error.lex`), because a relative key is only unique
38//! *within* one package: two packages published into one branch can both
39//! have a `src/error.lex`, and without the namespace both get the same
40//! `error_<hash>.format`.
41//!
42//! ## Whole-package loading
43//!
44//! [`load_program`] and [`load_program_with_root`] each flatten one
45//! entry's entire local-import closure into that entry's program, which
46//! is what `lex run`/`lex check` want for a single file. A caller holding
47//! *every* file of a package — a publish server, say — gets each shared
48//! dependency back once per importer instead: 2,239 declarations for 693
49//! distinct names on a real 21-file package whose `error.lex` 17 files
50//! import (#828). [`load_package`] is the whole-package entry point: one
51//! shared pass, every file exactly once, and every file mangled (no
52//! unmangled entry), since bare names from different files would collide
53//! in one program.
54//!
55//! Within a file at prefix `P`:
56//!
57//! - `fn foo` declared in this file becomes `<P>.foo` (just `foo` at root).
58//! - `type T` declared in this file becomes `<P>.T`.
59//! - References to a locally-declared name get mangled, **unless** the
60//!   name is shadowed by a binder (let, fn param, lambda param, or
61//!   pattern binder) in scope.
62//! - `m.foo` where `m` is a path-import alias is rewritten to the
63//!   imported file's prefix-qualified name. Two parents importing the
64//!   same file see the same prefix → calls and types unify.
65//! - `m.foo` where `m` is a stdlib alias is unchanged.
66//!
67//! Variant constructors are **not** mangled — they live in a global
68//! namespace, and a collision between two imported types' constructors
69//! surfaces later as a type-check error. Same for record field names.
70//!
71//! ## Diamond imports
72//!
73//! `main.lex` imports `./left` and `./right`, both of which import
74//! `./shared`. `shared.lex` is parsed once per resolution, but its
75//! mangled items are merged into the output exactly once (subsequent
76//! loads from the same canonical path return an empty Program). This
77//! is what makes `s.build_report(...)` and `v.read_score(...)` agree
78//! on `Report`'s nominal identity.
79//!
80//! ## Limitations (tracked separately)
81//!
82//! The mangling key is a filesystem path (see above). Moving a file
83//! changes its SigId; renaming changes the file-stem half of the
84//! prefix, and under [`load_package`] that applies to every
85//! declaration, not only imported ones — a function moved between two
86//! files of a package is a new function there. A root-relative key
87//! narrows this to moves *within* the package, but does not remove it.
88//! The eventual fix — content-addressed identity decoupled from
89//! filesystem layout — lives with store-native imports
90//! (`import "stage:..."`); see the corresponding follow-up tracker.
91
92use std::collections::{BTreeMap, HashMap, HashSet};
93use std::path::{Path, PathBuf};
94use thiserror::Error;
95
96use sha2::{Digest, Sha256};
97
98use crate::syntax::*;
99use crate::workspace::{resolve_package_import, PackageError};
100use crate::{parse_source, SyntaxError};
101
102#[derive(Debug, Error)]
103pub enum LoadError {
104    #[error("read {path}: {source}")]
105    Io {
106        path: String,
107        #[source]
108        source: std::io::Error,
109    },
110    #[error("parse {path}: {source}")]
111    Syntax {
112        path: String,
113        #[source]
114        source: SyntaxError,
115    },
116    #[error("import cycle: {chain}")]
117    Cycle { chain: String },
118    #[error("import \"{reference}\" from {importer}: file not found")]
119    NotFound { importer: String, reference: String },
120    #[error("local imports (`./`, `../`, `/`) require a base path; cannot resolve from a string source")]
121    LocalImportInStringSource,
122    #[error(
123        "alias `{alias}` is bound to both \"{first}\" and \"{second}\" within one package; \
124         loading the package as a single unit cannot keep both"
125    )]
126    ConflictingAlias {
127        alias: String,
128        first: String,
129        second: String,
130    },
131    #[error("package import error: {0}")]
132    Package(#[from] PackageError),
133}
134
135/// Load a multi-file Lex program, expanding local imports relative to
136/// the entry path. Stdlib imports (`std.*`) pass through unchanged.
137pub fn load_program(entry: &Path) -> Result<Program, LoadError> {
138    load_rooted(entry, None)
139}
140
141/// Load a multi-file Lex program like [`load_program`], but derive
142/// mangling prefixes from each file's path **relative to `root`**
143/// instead of its absolute path.
144///
145/// Use this whenever the same logical package can be loaded from a
146/// different directory each time — an unpacked upload, a CI checkout, a
147/// scratch clone — and the mangled names it produces must match across
148/// those loads (#826). Files that do not live under `root` keep the
149/// absolute-path key, as do all files if `root` cannot be canonicalized.
150pub fn load_program_with_root(entry: &Path, root: &Path) -> Result<Program, LoadError> {
151    // Canonicalize the root too: the entry path is canonicalized below,
152    // and a root reached through a symlink (macOS's `/var/folders/...`
153    // temp dirs being the common case) would never prefix-match the
154    // canonicalized file paths otherwise.
155    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
156    load_rooted(entry, Some(root))
157}
158
159/// A package loaded as one unit by [`load_package`].
160#[derive(Debug)]
161pub struct LoadedPackage {
162    /// Every file's declarations, each exactly once, all prefix-mangled.
163    pub program: Program,
164    /// The non-inlined imports each file makes *itself* — stdlib always, plus
165    /// registry/git package imports when the package was loaded without
166    /// inlining (#930) — keyed by the file's path relative to the package root
167    /// (`src/schema.lex`), each mapping the import *reference* to its `as`
168    /// alias. Unlike `program`, this is per-file: the flattening entry points
169    /// cannot report it, because by the time they return, a file's imports and
170    /// those of everything it imports are one undifferentiated list. The alias
171    /// is preserved so a non-default `import "lex-nt/lib" as nt` round-trips as
172    /// `nt` rather than the default last-segment `lib` (#909).
173    pub imports_by_file: BTreeMap<String, BTreeMap<String, String>>,
174    /// Mangling prefix → the file it belongs to (`schema_a1b2` →
175    /// `src/schema.lex`), for every file in the package. A declaration's
176    /// mangled name is `<prefix>.<local>`, so this is what lets a
177    /// consumer attribute each declaration in `program` back to its
178    /// source file — the record `export-git` needs to de-flatten the
179    /// package into its `src/*.lex` tree (#894).
180    pub module_prefixes: BTreeMap<String, String>,
181}
182
183/// Load a whole package as **one** program: every file gets its
184/// path-derived mangling prefix (no file is the unmangled "entry"), and
185/// each file's declarations appear exactly once however many other files
186/// import it.
187///
188/// [`load_program`] and [`load_program_with_root`] flatten each entry's
189/// whole local-import closure into that entry's program, so a caller
190/// holding N top-level files gets every shared dependency back N times —
191/// once per importer. The real 21-file `lex-schema` package, whose
192/// `error.lex` is imported by 17 of its files, yielded 2,239 `FnDecl`s
193/// for 693 distinct names that way, and a server that canonicalizes,
194/// type-checks, diffs and publishes each copy paid for all 2,239 (#828).
195/// One shared pass yields 447 — one per declaration.
196///
197/// Because no file is the entry, **no declaration keeps its bare
198/// source-level name**: `fn validate` in `src/field.lex` is
199/// `field_<hash>.validate`, not `validate`. That is what makes one
200/// program safe to type-check as a unit — two files may each declare
201/// their own local `validate`, and the checker's global scope is a map
202/// keyed by name, so bare names from different files would silently
203/// overwrite each other and check bodies against the wrong signature.
204///
205/// `namespace` is mixed into every mangling key ahead of the relative
206/// path, so the same internal layout in two different packages does not
207/// collapse onto one set of names. Callers publishing into a shared
208/// branch should pass the package name: a tenant hosting both
209/// `lex-schema` and `lex-ocpi` has two `src/error.lex` files, and a
210/// purely path-derived key gives both the same `error_<hash>.format`.
211///
212/// Stdlib imports are deduped by `(reference, alias)`. An alias bound to
213/// two *different* references inside one package is rejected with
214/// [`LoadError::ConflictingAlias`] rather than merged: the checker's
215/// alias scope is also name-keyed, so merging would silently resolve one
216/// file's calls against the other file's module.
217pub fn load_package(
218    entries: &[PathBuf],
219    root: &Path,
220    namespace: &str,
221    inline_packages: bool,
222) -> Result<LoadedPackage, LoadError> {
223    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
224    let mut state = LoaderState {
225        in_progress: Vec::new(),
226        loaded: HashSet::new(),
227        prefixes: HashMap::new(),
228        prefix_root: Some(root),
229        prefix_namespace: Some(namespace.to_string()),
230        imports_by_file: BTreeMap::new(),
231        inline_packages,
232    };
233    // Deliberately no empty-prefix seeding: see the doc comment above.
234    let mut items: Vec<Item> = Vec::new();
235    let mut aliases: HashMap<String, String> = HashMap::new();
236    for entry in entries {
237        let canonical = entry.canonicalize().map_err(|source| LoadError::Io {
238            path: entry.display().to_string(),
239            source,
240        })?;
241        for item in state.load(&canonical)?.items {
242            if let Item::Import(imp) = &item {
243                match aliases.get(&imp.alias) {
244                    // Same module under the same alias: one import is enough.
245                    Some(existing) if existing == &imp.reference => continue,
246                    Some(existing) => {
247                        return Err(LoadError::ConflictingAlias {
248                            alias: imp.alias.clone(),
249                            first: existing.clone(),
250                            second: imp.reference.clone(),
251                        })
252                    }
253                    None => {
254                        aliases.insert(imp.alias.clone(), imp.reference.clone());
255                    }
256                }
257            }
258            items.push(item);
259        }
260    }
261    // prefix → relative file path, for every mangled file (the entry
262    // has no empty prefix under `load_package`, so all are included).
263    let module_prefixes: BTreeMap<String, String> = state
264        .prefixes
265        .iter()
266        .filter(|(_, prefix)| !prefix.is_empty())
267        .filter_map(|(path, prefix)| state.relative_key(path).map(|rel| (prefix.clone(), rel)))
268        .collect();
269    Ok(LoadedPackage {
270        program: Program {
271            items,
272            leading_comments: Vec::new(),
273            trailing_comments: Vec::new(),
274        },
275        imports_by_file: state.imports_by_file,
276        module_prefixes,
277    })
278}
279
280fn load_rooted(entry: &Path, prefix_root: Option<PathBuf>) -> Result<Program, LoadError> {
281    let entry_canonical = entry.canonicalize().map_err(|source| LoadError::Io {
282        path: entry.display().to_string(),
283        source,
284    })?;
285    let mut state = LoaderState {
286        in_progress: Vec::new(),
287        loaded: HashSet::new(),
288        prefixes: HashMap::new(),
289        prefix_root,
290        prefix_namespace: None,
291        imports_by_file: BTreeMap::new(),
292        // Single-entry loads (`lex run`/`lex check`) inline every dependency
293        // so the program is self-contained without a resolver, as before #930.
294        inline_packages: true,
295    };
296    // Entry file's prefix is empty so `lex run main.lex process` works
297    // without users typing the hashed prefix.
298    state.prefixes.insert(entry_canonical.clone(), String::new());
299    state.load(&entry_canonical)
300}
301
302/// Load a Lex program from a string source. Local-path imports are
303/// rejected up-front since there's no base path to resolve from.
304pub fn load_program_from_str(src: &str) -> Result<Program, LoadError> {
305    let prog = parse_source(src).map_err(|source| LoadError::Syntax {
306        path: "<input>".into(),
307        source,
308    })?;
309    for item in &prog.items {
310        if let Item::Import(imp) = item {
311            if is_path_import(&imp.reference)
312                || split_package_import(&imp.reference).is_some()
313            {
314                return Err(LoadError::LocalImportInStringSource);
315            }
316        }
317    }
318    Ok(prog)
319}
320
321struct LoaderState {
322    in_progress: Vec<PathBuf>,
323    /// Canonical paths that have already been merged into the output.
324    /// A second `import "./shared"` from a different parent skips
325    /// re-merging — the file's mangled items are already there.
326    loaded: HashSet<PathBuf>,
327    /// Stable mangling prefix per canonical path. Computed lazily;
328    /// the entry file is seeded with an empty prefix.
329    prefixes: HashMap<PathBuf, String>,
330    /// When set, mangling prefixes hash each file's path relative to
331    /// this (already canonicalized) directory rather than its absolute
332    /// path, so the same package layout mangles identically wherever it
333    /// is unpacked. See the module header's "Mangling" section.
334    prefix_root: Option<PathBuf>,
335    /// Mixed into every relative mangling key ahead of the path, so two
336    /// packages sharing an internal layout (two `src/error.lex` files)
337    /// do not mangle to one set of names. Only [`load_package`] sets it.
338    prefix_namespace: Option<String>,
339    /// Non-inlined imports each file makes itself — stdlib always, and (when
340    /// `inline_packages` is false) registry/git package imports too — keyed by
341    /// the file's root-relative path, each mapping the import *reference* to
342    /// its `as` alias. Recorded for every file the loader reads; only
343    /// [`load_package`] hands it back. The alias is kept (not defaulted) so a
344    /// non-inlined `import "lex-nt/lib" as nt` round-trips as `nt`, not the
345    /// default last-segment `lib` (#909/#930).
346    imports_by_file: BTreeMap<String, BTreeMap<String, String>>,
347    /// When false, registry/git package imports are recorded as import edges
348    /// (like stdlib) instead of being resolved and inlined — the op-log then
349    /// keeps the dependency edge and the consumer resolves it (#930). Local
350    /// (`./`, `../`, `/`) imports are always inlined. [`load_package`] sets
351    /// this per call; the single-entry loaders always inline.
352    inline_packages: bool,
353}
354
355impl LoaderState {
356    fn prefix_for(&mut self, canonical: &Path) -> String {
357        if let Some(p) = self.prefixes.get(canonical) {
358            return p.clone();
359        }
360        let stem = canonical
361            .file_stem()
362            .and_then(|s| s.to_str())
363            .unwrap_or("module");
364        let mut hasher = Sha256::new();
365        hasher.update(self.mangling_key(canonical).as_bytes());
366        let digest = hasher.finalize();
367        let prefix = format!("{stem}_{:08x}", u32::from_be_bytes([
368            digest[0], digest[1], digest[2], digest[3],
369        ]));
370        self.prefixes.insert(canonical.to_path_buf(), prefix.clone());
371        prefix
372    }
373
374    /// The string a file's mangling hash is taken over: `prefix_namespace`
375    /// (when set) followed by the file's path relative to `prefix_root`,
376    /// else its canonical absolute path. Relative keys are joined with
377    /// `/` regardless of platform so the same layout hashes the same on
378    /// Windows and Unix.
379    fn mangling_key(&self, canonical: &Path) -> String {
380        match (self.relative_key(canonical), &self.prefix_namespace) {
381            (Some(rel), Some(ns)) => format!("{ns}/{rel}"),
382            (Some(rel), None) => rel,
383            (None, _) => canonical.to_string_lossy().into_owned(),
384        }
385    }
386
387    /// A file's path relative to `prefix_root`, `/`-joined — `None` when
388    /// there is no root or the file lives outside it. Also the key
389    /// `imports_by_file` is reported under, which is why it carries no
390    /// namespace: those keys name files in the archive, and history
391    /// already records them under exactly this spelling.
392    fn relative_key(&self, canonical: &Path) -> Option<String> {
393        let root = self.prefix_root.as_ref()?;
394        let rel = canonical.strip_prefix(root).ok()?;
395        let key = rel
396            .components()
397            .map(|c| c.as_os_str().to_string_lossy())
398            .collect::<Vec<_>>()
399            .join("/");
400        // An empty key means `canonical == root` (a root pointing at the
401        // file itself) — not a usable key, and it would collide with any
402        // other such file.
403        if key.is_empty() {
404            None
405        } else {
406            Some(key)
407        }
408    }
409
410    fn load(&mut self, canonical: &Path) -> Result<Program, LoadError> {
411        if self.in_progress.contains(&canonical.to_path_buf()) {
412            let mut chain: Vec<String> = self
413                .in_progress
414                .iter()
415                .map(|p| p.display().to_string())
416                .collect();
417            chain.push(canonical.display().to_string());
418            return Err(LoadError::Cycle {
419                chain: chain.join(" -> "),
420            });
421        }
422        // Diamond dedupe: if this file was already merged on another
423        // path through the import graph, its items are already in the
424        // output Vec — return an empty Program so the caller's
425        // `merged_children.extend(...)` is a no-op for items, but the
426        // call still resolves so the parent's `path_imports` map gets
427        // populated below.
428        if self.loaded.contains(canonical) {
429            return Ok(Program {
430                items: Vec::new(),
431                leading_comments: Vec::new(),
432                trailing_comments: Vec::new(),
433            });
434        }
435        self.in_progress.push(canonical.to_path_buf());
436
437        let src = std::fs::read_to_string(canonical).map_err(|source| LoadError::Io {
438            path: canonical.display().to_string(),
439            source,
440        })?;
441        let prog = parse_source(&src).map_err(|source| LoadError::Syntax {
442            path: canonical.display().to_string(),
443            source,
444        })?;
445
446        let local_names: HashSet<String> = prog
447            .items
448            .iter()
449            .filter_map(|item| match item {
450                Item::FnDecl(fd) => Some(fd.name.clone()),
451                Item::TypeDecl(td) => Some(td.name.clone()),
452                _ => None,
453            })
454            .collect();
455
456        // alias used by this file → mangling prefix of the imported file
457        let mut path_imports: HashMap<String, String> = HashMap::new();
458        let mut merged_children: Vec<Item> = Vec::new();
459        let mut std_imports: Vec<Item> = Vec::new();
460        let mut my_items: Vec<Item> = Vec::new();
461
462        for item in prog.items {
463            match item {
464                Item::Import(ref imp) if is_path_import(&imp.reference) => {
465                    let resolved = resolve_import(canonical, &imp.reference)?;
466                    let child_prefix = self.prefix_for(&resolved);
467                    path_imports.insert(imp.alias.clone(), child_prefix);
468                    let child_prog = self.load(&resolved)?;
469                    merged_children.extend(child_prog.items);
470                }
471                // A registry/git package import. With `inline_packages`, resolve
472                // and inline it (self-contained program, pre-#930 behavior);
473                // otherwise leave it as an import edge (recorded below like
474                // stdlib) so the op-log keeps the dependency edge and the
475                // consumer resolves it — refs stay `<alias>.name`, unmangled.
476                Item::Import(ref imp)
477                    if self.inline_packages && split_package_import(&imp.reference).is_some() =>
478                {
479                    let (pkg, module) =
480                        split_package_import(&imp.reference).unwrap();
481                    let resolved =
482                        resolve_package_import(canonical, pkg, module)
483                            .map_err(LoadError::Package)?
484                            .canonicalize()
485                            .map_err(|source| LoadError::Io {
486                                path: imp.reference.clone(),
487                                source,
488                            })?;
489                    let child_prefix = self.prefix_for(&resolved);
490                    path_imports.insert(imp.alias.clone(), child_prefix);
491                    let child_prog = self.load(&resolved)?;
492                    merged_children.extend(child_prog.items);
493                }
494                Item::Import(_) => std_imports.push(item),
495                _ => my_items.push(item),
496            }
497        }
498
499        // Attribute this file's own stdlib imports to this file, before
500        // the merge below makes them indistinguishable from its
501        // children's. Every file gets an entry, imports or not, so a
502        // file that has dropped its last import is still represented.
503        if let Some(key) = self.relative_key(canonical) {
504            let entry = self.imports_by_file.entry(key).or_default();
505            for item in &std_imports {
506                if let Item::Import(imp) = item {
507                    entry.insert(imp.reference.clone(), imp.alias.clone());
508                }
509            }
510        }
511
512        let my_prefix = self.prefix_for(canonical);
513        let mangler = Mangler {
514            prefix: my_prefix,
515            local_names: &local_names,
516            path_imports: &path_imports,
517        };
518        let mangled: Vec<Item> = my_items
519            .into_iter()
520            .map(|i| mangler.mangle_item(i))
521            .collect();
522
523        self.in_progress.pop();
524        self.loaded.insert(canonical.to_path_buf());
525
526        // Output order: std imports first (deduped against children's),
527        // then merged children's items, then this file's items.
528        let mut out: Vec<Item> = Vec::new();
529        for s in std_imports {
530            if !merged_children.iter().any(|m| m == &s) {
531                out.push(s);
532            }
533        }
534        out.extend(merged_children);
535        out.extend(mangled);
536        // Top-of-file comments live on each source file independently;
537        // after import merging the merged Program represents many
538        // files at once, and there is no obvious single "top of file"
539        // to attribute them to. Drop here — they're preserved by
540        // `lex fmt` (which operates per-file) but not by the loader's
541        // import-merging path. Same rationale for trailing_comments.
542        Ok(Program {
543            items: out,
544            leading_comments: Vec::new(),
545            trailing_comments: Vec::new(),
546        })
547    }
548}
549
550fn is_path_import(reference: &str) -> bool {
551    reference.starts_with("./") || reference.starts_with("../") || reference.starts_with('/')
552}
553
554/// Returns `Some((pkg_name, module_path))` for package imports like
555/// `"lex-schema/validate"`. Stdlib (`std.*`) and relative paths are
556/// excluded — they are handled elsewhere.
557fn split_package_import(reference: &str) -> Option<(&str, &str)> {
558    if reference.starts_with("./")
559        || reference.starts_with("../")
560        || reference.starts_with('/')
561        || reference.starts_with("std.")
562    {
563        return None;
564    }
565    reference.split_once('/')
566}
567
568fn resolve_import(importer: &Path, reference: &str) -> Result<PathBuf, LoadError> {
569    let importer_dir = importer.parent().unwrap_or_else(|| Path::new("."));
570    let mut resolved: PathBuf = if reference.starts_with('/') {
571        PathBuf::from(reference)
572    } else {
573        importer_dir.join(reference)
574    };
575    if resolved.extension().is_none() {
576        resolved.set_extension("lex");
577    }
578    if !resolved.exists() {
579        return Err(LoadError::NotFound {
580            importer: importer.display().to_string(),
581            reference: reference.to_string(),
582        });
583    }
584    // Canonicalize so that `../../shared/foo` and `../other/../shared/foo`
585    // resolve to the same HashMap key, preventing duplicate loads and
586    // mismatched mangling prefixes in diamond-import graphs (#358).
587    resolved.canonicalize().map_err(|source| LoadError::Io {
588        path: resolved.display().to_string(),
589        source,
590    })
591}
592
593struct Mangler<'a> {
594    /// Mangling prefix for items declared in this file. Empty for the
595    /// entry file, `<stem>_<hash8>` for imported files.
596    prefix: String,
597    local_names: &'a HashSet<String>,
598    /// Map from local alias to the imported file's mangling prefix.
599    /// `m.foo` rewrites to `<imported_prefix>.foo` regardless of which
600    /// alias `m` was, so two parents importing the same module agree.
601    path_imports: &'a HashMap<String, String>,
602}
603
604impl<'a> Mangler<'a> {
605    fn qualify(&self, name: &str) -> String {
606        if self.prefix.is_empty() {
607            name.to_string()
608        } else {
609            format!("{}.{}", self.prefix, name)
610        }
611    }
612
613    fn mangle_item(&self, item: Item) -> Item {
614        match item {
615            Item::Import(imp) => Item::Import(imp),
616            Item::TypeDecl(td) => Item::TypeDecl(self.mangle_type_decl(td)),
617            Item::FnDecl(fd) => Item::FnDecl(self.mangle_fn_decl(fd)),
618        }
619    }
620
621    fn mangle_type_decl(&self, td: TypeDecl) -> TypeDecl {
622        TypeDecl {
623            name: self.qualify(&td.name),
624            params: td.params,
625            definition: self.mangle_type_expr(td.definition),
626            leading_comments: td.leading_comments,
627        }
628    }
629
630    fn mangle_fn_decl(&self, fd: FnDecl) -> FnDecl {
631        let mut shadow = HashSet::new();
632        for p in &fd.params {
633            shadow.insert(p.name.clone());
634        }
635        // Example args/expected sit outside the body's parameter scope:
636        // they're top-level expressions evaluated against the function
637        // signature, so the only names they can see are the file's
638        // top-level fns/types and any path-import aliases — i.e., an
639        // empty shadow set (#391).
640        let empty_shadow = HashSet::new();
641        let examples = fd
642            .examples
643            .into_iter()
644            .map(|ex| Example {
645                args: ex
646                    .args
647                    .into_iter()
648                    .map(|a| self.mangle_expr(a, &empty_shadow))
649                    .collect(),
650                expected: self.mangle_expr(ex.expected, &empty_shadow),
651            })
652            .collect();
653        FnDecl {
654            name: self.qualify(&fd.name),
655            type_params: fd.type_params,
656            params: fd
657                .params
658                .into_iter()
659                .map(|p| Param {
660                    name: p.name,
661                    ty: self.mangle_type_expr(p.ty),
662                })
663                .collect(),
664            effects: fd.effects,
665            effect_row_var: fd.effect_row_var,
666            return_type: self.mangle_type_expr(fd.return_type),
667            body: self.mangle_block(fd.body, &shadow),
668            examples,
669            leading_comments: fd.leading_comments,
670        }
671    }
672
673    fn mangle_type_expr(&self, te: TypeExpr) -> TypeExpr {
674        match te {
675            TypeExpr::Named { name, args } => TypeExpr::Named {
676                name: self.rewrite_type_name(&name),
677                args: args.into_iter().map(|a| self.mangle_type_expr(a)).collect(),
678            },
679            TypeExpr::Record(fields) => TypeExpr::Record(
680                fields
681                    .into_iter()
682                    .map(|f| TypeField {
683                        name: f.name,
684                        ty: self.mangle_type_expr(f.ty),
685                    })
686                    .collect(),
687            ),
688            TypeExpr::RecordWithSpreads { spreads, fields } => TypeExpr::RecordWithSpreads {
689                spreads: spreads.into_iter().map(|s| self.rewrite_type_name(&s)).collect(),
690                fields: fields
691                    .into_iter()
692                    .map(|f| TypeField {
693                        name: f.name,
694                        ty: self.mangle_type_expr(f.ty),
695                    })
696                    .collect(),
697            },
698            TypeExpr::Tuple(items) => {
699                TypeExpr::Tuple(items.into_iter().map(|t| self.mangle_type_expr(t)).collect())
700            }
701            TypeExpr::Function {
702                params,
703                effects,
704                effect_row_var,
705                ret,
706            } => TypeExpr::Function {
707                params: params
708                    .into_iter()
709                    .map(|t| self.mangle_type_expr(t))
710                    .collect(),
711                effects,
712                effect_row_var,
713                ret: Box::new(self.mangle_type_expr(*ret)),
714            },
715            TypeExpr::Union(variants) => TypeExpr::Union(
716                variants
717                    .into_iter()
718                    .map(|v| UnionVariant {
719                        name: v.name,
720                        payload: v.payload.map(|t| self.mangle_type_expr(t)),
721                    })
722                    .collect(),
723            ),
724            TypeExpr::Refined { base, binding, predicate } => TypeExpr::Refined {
725                base: Box::new(self.mangle_type_expr(*base)),
726                binding,
727                // The predicate is an expression; its names are
728                // resolved during type-check, not loader-time, so
729                // it passes through unchanged here. Slice 2 wires
730                // up discharge through the spec-checker.
731                predicate,
732            },
733        }
734    }
735
736    /// Rewrite a possibly-qualified type name to its mangled form.
737    fn rewrite_type_name(&self, name: &str) -> String {
738        if let Some((alias, rest)) = name.split_once('.') {
739            if let Some(child) = self.path_imports.get(alias) {
740                return format!("{child}.{rest}");
741            }
742            return name.to_string();
743        }
744        if self.local_names.contains(name) {
745            return self.qualify(name);
746        }
747        name.to_string()
748    }
749
750    fn mangle_block(&self, b: Block, shadow: &HashSet<String>) -> Block {
751        let mut shadow = shadow.clone();
752        let statements = b
753            .statements
754            .into_iter()
755            .map(|s| match s {
756                Statement::Let { name, ty, value } => {
757                    let value = self.mangle_expr(value, &shadow);
758                    let ty = ty.map(|t| self.mangle_type_expr(t));
759                    shadow.insert(name.clone());
760                    Statement::Let { name, ty, value }
761                }
762                Statement::Expr(e) => Statement::Expr(self.mangle_expr(e, &shadow)),
763            })
764            .collect();
765        let result = Box::new(self.mangle_expr(*b.result, &shadow));
766        Block { statements, result }
767    }
768
769    fn mangle_expr(&self, e: Expr, shadow: &HashSet<String>) -> Expr {
770        match e {
771            Expr::Lit(_) => e,
772            Expr::Var(name) => {
773                if !shadow.contains(&name) && self.local_names.contains(&name) {
774                    Expr::Var(self.qualify(&name))
775                } else {
776                    Expr::Var(name)
777                }
778            }
779            Expr::Block(b) => Expr::Block(self.mangle_block(b, shadow)),
780            Expr::Call { callee, args } => {
781                let mangled_args: Vec<Expr> = args
782                    .into_iter()
783                    .map(|a| self.mangle_expr(a, shadow))
784                    .collect();
785                if let Expr::Field { value, field } = (*callee).clone() {
786                    if let Expr::Var(alias) = *value {
787                        if !shadow.contains(&alias) {
788                            if let Some(child) = self.path_imports.get(&alias) {
789                                return Expr::Call {
790                                    callee: Box::new(Expr::Var(format!("{child}.{field}"))),
791                                    args: mangled_args,
792                                };
793                            }
794                        }
795                    }
796                }
797                Expr::Call {
798                    callee: Box::new(self.mangle_expr(*callee, shadow)),
799                    args: mangled_args,
800                }
801            }
802            Expr::Pipe { left, right } => Expr::Pipe {
803                left: Box::new(self.mangle_expr(*left, shadow)),
804                right: Box::new(self.mangle_expr(*right, shadow)),
805            },
806            Expr::Try(inner) => Expr::Try(Box::new(self.mangle_expr(*inner, shadow))),
807            Expr::Field { value, field } => {
808                if let Expr::Var(alias) = (*value).clone() {
809                    if !shadow.contains(&alias) {
810                        if let Some(child) = self.path_imports.get(&alias) {
811                            return Expr::Var(format!("{child}.{field}"));
812                        }
813                    }
814                }
815                Expr::Field {
816                    value: Box::new(self.mangle_expr(*value, shadow)),
817                    field,
818                }
819            }
820            Expr::BinOp { op, lhs, rhs } => Expr::BinOp {
821                op,
822                lhs: Box::new(self.mangle_expr(*lhs, shadow)),
823                rhs: Box::new(self.mangle_expr(*rhs, shadow)),
824            },
825            Expr::UnaryOp { op, expr } => Expr::UnaryOp {
826                op,
827                expr: Box::new(self.mangle_expr(*expr, shadow)),
828            },
829            Expr::If {
830                cond,
831                then_block,
832                else_block,
833            } => Expr::If {
834                cond: Box::new(self.mangle_expr(*cond, shadow)),
835                then_block: self.mangle_block(then_block, shadow),
836                else_block: self.mangle_block(else_block, shadow),
837            },
838            Expr::Match { scrutinee, arms } => Expr::Match {
839                scrutinee: Box::new(self.mangle_expr(*scrutinee, shadow)),
840                arms: arms
841                    .into_iter()
842                    .map(|a| {
843                        let mut arm_shadow = shadow.clone();
844                        collect_pattern_binders(&a.pattern, &mut arm_shadow);
845                        Arm {
846                            pattern: self.mangle_pattern(a.pattern),
847                            body: self.mangle_expr(a.body, &arm_shadow),
848                        }
849                    })
850                    .collect(),
851            },
852            Expr::RecordLit(fields) => Expr::RecordLit(
853                fields
854                    .into_iter()
855                    .map(|f| RecordLitField {
856                        name: f.name,
857                        value: self.mangle_expr(f.value, shadow),
858                    })
859                    .collect(),
860            ),
861            Expr::TupleLit(items) => Expr::TupleLit(
862                items
863                    .into_iter()
864                    .map(|i| self.mangle_expr(i, shadow))
865                    .collect(),
866            ),
867            Expr::ListLit(items) => Expr::ListLit(
868                items
869                    .into_iter()
870                    .map(|i| self.mangle_expr(i, shadow))
871                    .collect(),
872            ),
873            Expr::Constructor { name, args } => Expr::Constructor {
874                name,
875                args: args
876                    .into_iter()
877                    .map(|a| self.mangle_expr(a, shadow))
878                    .collect(),
879            },
880            Expr::Ascription { value, ty } => Expr::Ascription {
881                value: Box::new(self.mangle_expr(*value, shadow)),
882                ty: self.mangle_type_expr(ty),
883            },
884            Expr::Lambda(lambda) => {
885                let mut lam_shadow = shadow.clone();
886                for p in &lambda.params {
887                    lam_shadow.insert(p.name.clone());
888                }
889                Expr::Lambda(Box::new(Lambda {
890                    params: lambda
891                        .params
892                        .into_iter()
893                        .map(|p| Param {
894                            name: p.name,
895                            ty: self.mangle_type_expr(p.ty),
896                        })
897                        .collect(),
898                    return_type: self.mangle_type_expr(lambda.return_type),
899                    effects: lambda.effects,
900                    effect_row_var: lambda.effect_row_var,
901                    body: self.mangle_block(lambda.body, &lam_shadow),
902                }))
903            }
904        }
905    }
906
907    fn mangle_pattern(&self, p: Pattern) -> Pattern {
908        match p {
909            Pattern::Constructor { name, args } => Pattern::Constructor {
910                name,
911                args: args.into_iter().map(|a| self.mangle_pattern(a)).collect(),
912            },
913            Pattern::Record { fields, rest } => Pattern::Record {
914                fields: fields
915                    .into_iter()
916                    .map(|f| RecordPatField {
917                        name: f.name,
918                        pattern: f.pattern.map(|p| self.mangle_pattern(p)),
919                    })
920                    .collect(),
921                rest,
922            },
923            Pattern::Tuple(items) => {
924                Pattern::Tuple(items.into_iter().map(|p| self.mangle_pattern(p)).collect())
925            }
926            Pattern::Lit(_) | Pattern::Var(_) | Pattern::Wild => p,
927        }
928    }
929}
930
931fn collect_pattern_binders(p: &Pattern, out: &mut HashSet<String>) {
932    match p {
933        Pattern::Var(name) => {
934            out.insert(name.clone());
935        }
936        Pattern::Constructor { args, .. } => {
937            for a in args {
938                collect_pattern_binders(a, out);
939            }
940        }
941        Pattern::Record { fields, .. } => {
942            for f in fields {
943                match &f.pattern {
944                    Some(p) => collect_pattern_binders(p, out),
945                    // `{ name }` shorthand binds `name`.
946                    None => {
947                        out.insert(f.name.clone());
948                    }
949                }
950            }
951        }
952        Pattern::Tuple(items) => {
953            for p in items {
954                collect_pattern_binders(p, out);
955            }
956        }
957        Pattern::Lit(_) | Pattern::Wild => {}
958    }
959}