lex-syntax 0.11.13

Tokenizer + parser for the Lex programming language.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
//! Multi-file loader: resolves `import "./..."`, `import "../..."`, and
//! `import "/abs/..."` statements relative to the importer, recursively
//! parses, and produces a single [`Program`] with all stages merged.
//!
//! Names that are local to an imported file are mangled with a
//! **per-file-path** prefix, so the same module imported via multiple
//! aliases (or from multiple parents in a diamond shape) collapses to
//! one set of mangled names — same SigId, same nominal identity.
//! Stdlib imports (`import "std.foo" as bar`) pass through unchanged.
//!
//! ## Mangling
//!
//! Each loaded file gets a prefix derived from its filesystem path.
//! The entry file's prefix is empty (so `lex run main.lex process`
//! works unchanged). Imported files use `<stem>_<hash>` where `hash`
//! is the first 8 hex chars of SHA-256 of the file's *mangling key*.
//! The hash disambiguates same-stem files in different directories
//! without forcing a project manifest.
//!
//! The mangling key is the canonical absolute path by default, and the
//! path **relative to a caller-supplied root** when loading through
//! [`load_program_with_root`] or [`load_package`]. Absolute paths are
//! only stable as long as the tree stays put, which makes them unusable
//! for anything that loads the same logical package from a fresh
//! directory each time: a server unpacking an uploaded package into a
//! per-request temp dir got a different prefix — and therefore a
//! brand-new set of function names — for every file reached through a
//! local import on every single request, so byte-identical republishes
//! diffed as all-new functions and grew the branch's function set
//! without bound (#826). Pass the package root and the key becomes
//! `src/error.lex`, identical across requests. Files outside the root
//! keep the absolute-path key (a dependency in the shared package cache
//! lives at a stable absolute path of its own, and "relative to this
//! package" says nothing useful about it).
//!
//! [`load_package`] adds a `namespace` ahead of the relative path
//! (`lex-schema/src/error.lex`), because a relative key is only unique
//! *within* one package: two packages published into one branch can both
//! have a `src/error.lex`, and without the namespace both get the same
//! `error_<hash>.format`.
//!
//! ## Whole-package loading
//!
//! [`load_program`] and [`load_program_with_root`] each flatten one
//! entry's entire local-import closure into that entry's program, which
//! is what `lex run`/`lex check` want for a single file. A caller holding
//! *every* file of a package — a publish server, say — gets each shared
//! dependency back once per importer instead: 2,239 declarations for 693
//! distinct names on a real 21-file package whose `error.lex` 17 files
//! import (#828). [`load_package`] is the whole-package entry point: one
//! shared pass, every file exactly once, and every file mangled (no
//! unmangled entry), since bare names from different files would collide
//! in one program.
//!
//! Within a file at prefix `P`:
//!
//! - `fn foo` declared in this file becomes `<P>.foo` (just `foo` at root).
//! - `type T` declared in this file becomes `<P>.T`.
//! - References to a locally-declared name get mangled, **unless** the
//!   name is shadowed by a binder (let, fn param, lambda param, or
//!   pattern binder) in scope.
//! - `m.foo` where `m` is a path-import alias is rewritten to the
//!   imported file's prefix-qualified name. Two parents importing the
//!   same file see the same prefix → calls and types unify.
//! - `m.foo` where `m` is a stdlib alias is unchanged.
//!
//! Variant constructors are **not** mangled — they live in a global
//! namespace, and a collision between two imported types' constructors
//! surfaces later as a type-check error. Same for record field names.
//!
//! ## Diamond imports
//!
//! `main.lex` imports `./left` and `./right`, both of which import
//! `./shared`. `shared.lex` is parsed once per resolution, but its
//! mangled items are merged into the output exactly once (subsequent
//! loads from the same canonical path return an empty Program). This
//! is what makes `s.build_report(...)` and `v.read_score(...)` agree
//! on `Report`'s nominal identity.
//!
//! ## Limitations (tracked separately)
//!
//! The mangling key is a filesystem path (see above). Moving a file
//! changes its SigId; renaming changes the file-stem half of the
//! prefix, and under [`load_package`] that applies to every
//! declaration, not only imported ones — a function moved between two
//! files of a package is a new function there. A root-relative key
//! narrows this to moves *within* the package, but does not remove it.
//! The eventual fix — content-addressed identity decoupled from
//! filesystem layout — lives with store-native imports
//! (`import "stage:..."`); see the corresponding follow-up tracker.

use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::path::{Path, PathBuf};
use thiserror::Error;

use sha2::{Digest, Sha256};

use crate::syntax::*;
use crate::workspace::{resolve_package_import, PackageError};
use crate::{parse_source, SyntaxError};

#[derive(Debug, Error)]
pub enum LoadError {
    #[error("read {path}: {source}")]
    Io {
        path: String,
        #[source]
        source: std::io::Error,
    },
    #[error("parse {path}: {source}")]
    Syntax {
        path: String,
        #[source]
        source: SyntaxError,
    },
    #[error("import cycle: {chain}")]
    Cycle { chain: String },
    #[error("import \"{reference}\" from {importer}: file not found")]
    NotFound { importer: String, reference: String },
    #[error("local imports (`./`, `../`, `/`) require a base path; cannot resolve from a string source")]
    LocalImportInStringSource,
    #[error(
        "alias `{alias}` is bound to both \"{first}\" and \"{second}\" within one package; \
         loading the package as a single unit cannot keep both"
    )]
    ConflictingAlias {
        alias: String,
        first: String,
        second: String,
    },
    #[error("package import error: {0}")]
    Package(#[from] PackageError),
}

/// Load a multi-file Lex program, expanding local imports relative to
/// the entry path. Stdlib imports (`std.*`) pass through unchanged.
pub fn load_program(entry: &Path) -> Result<Program, LoadError> {
    load_rooted(entry, None)
}

/// Load a multi-file Lex program like [`load_program`], but derive
/// mangling prefixes from each file's path **relative to `root`**
/// instead of its absolute path.
///
/// Use this whenever the same logical package can be loaded from a
/// different directory each time — an unpacked upload, a CI checkout, a
/// scratch clone — and the mangled names it produces must match across
/// those loads (#826). Files that do not live under `root` keep the
/// absolute-path key, as do all files if `root` cannot be canonicalized.
pub fn load_program_with_root(entry: &Path, root: &Path) -> Result<Program, LoadError> {
    // Canonicalize the root too: the entry path is canonicalized below,
    // and a root reached through a symlink (macOS's `/var/folders/...`
    // temp dirs being the common case) would never prefix-match the
    // canonicalized file paths otherwise.
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    load_rooted(entry, Some(root))
}

/// A package loaded as one unit by [`load_package`].
#[derive(Debug)]
pub struct LoadedPackage {
    /// Every file's declarations, each exactly once, all prefix-mangled.
    pub program: Program,
    /// The stdlib modules each file imports *itself*, keyed by the file's
    /// path relative to the package root (`src/schema.lex`). Unlike
    /// `program`, this is per-file: the flattening entry points cannot
    /// report it, because by the time they return, a file's imports and
    /// those of everything it imports are one undifferentiated list.
    pub imports_by_file: BTreeMap<String, BTreeSet<String>>,
}

/// Load a whole package as **one** program: every file gets its
/// path-derived mangling prefix (no file is the unmangled "entry"), and
/// each file's declarations appear exactly once however many other files
/// import it.
///
/// [`load_program`] and [`load_program_with_root`] flatten each entry's
/// whole local-import closure into that entry's program, so a caller
/// holding N top-level files gets every shared dependency back N times —
/// once per importer. The real 21-file `lex-schema` package, whose
/// `error.lex` is imported by 17 of its files, yielded 2,239 `FnDecl`s
/// for 693 distinct names that way, and a server that canonicalizes,
/// type-checks, diffs and publishes each copy paid for all 2,239 (#828).
/// One shared pass yields 447 — one per declaration.
///
/// Because no file is the entry, **no declaration keeps its bare
/// source-level name**: `fn validate` in `src/field.lex` is
/// `field_<hash>.validate`, not `validate`. That is what makes one
/// program safe to type-check as a unit — two files may each declare
/// their own local `validate`, and the checker's global scope is a map
/// keyed by name, so bare names from different files would silently
/// overwrite each other and check bodies against the wrong signature.
///
/// `namespace` is mixed into every mangling key ahead of the relative
/// path, so the same internal layout in two different packages does not
/// collapse onto one set of names. Callers publishing into a shared
/// branch should pass the package name: a tenant hosting both
/// `lex-schema` and `lex-ocpi` has two `src/error.lex` files, and a
/// purely path-derived key gives both the same `error_<hash>.format`.
///
/// Stdlib imports are deduped by `(reference, alias)`. An alias bound to
/// two *different* references inside one package is rejected with
/// [`LoadError::ConflictingAlias`] rather than merged: the checker's
/// alias scope is also name-keyed, so merging would silently resolve one
/// file's calls against the other file's module.
pub fn load_package(
    entries: &[PathBuf],
    root: &Path,
    namespace: &str,
) -> Result<LoadedPackage, LoadError> {
    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
    let mut state = LoaderState {
        in_progress: Vec::new(),
        loaded: HashSet::new(),
        prefixes: HashMap::new(),
        prefix_root: Some(root),
        prefix_namespace: Some(namespace.to_string()),
        imports_by_file: BTreeMap::new(),
    };
    // Deliberately no empty-prefix seeding: see the doc comment above.
    let mut items: Vec<Item> = Vec::new();
    let mut aliases: HashMap<String, String> = HashMap::new();
    for entry in entries {
        let canonical = entry.canonicalize().map_err(|source| LoadError::Io {
            path: entry.display().to_string(),
            source,
        })?;
        for item in state.load(&canonical)?.items {
            if let Item::Import(imp) = &item {
                match aliases.get(&imp.alias) {
                    // Same module under the same alias: one import is enough.
                    Some(existing) if existing == &imp.reference => continue,
                    Some(existing) => {
                        return Err(LoadError::ConflictingAlias {
                            alias: imp.alias.clone(),
                            first: existing.clone(),
                            second: imp.reference.clone(),
                        })
                    }
                    None => {
                        aliases.insert(imp.alias.clone(), imp.reference.clone());
                    }
                }
            }
            items.push(item);
        }
    }
    Ok(LoadedPackage {
        program: Program {
            items,
            leading_comments: Vec::new(),
            trailing_comments: Vec::new(),
        },
        imports_by_file: state.imports_by_file,
    })
}

fn load_rooted(entry: &Path, prefix_root: Option<PathBuf>) -> Result<Program, LoadError> {
    let entry_canonical = entry.canonicalize().map_err(|source| LoadError::Io {
        path: entry.display().to_string(),
        source,
    })?;
    let mut state = LoaderState {
        in_progress: Vec::new(),
        loaded: HashSet::new(),
        prefixes: HashMap::new(),
        prefix_root,
        prefix_namespace: None,
        imports_by_file: BTreeMap::new(),
    };
    // Entry file's prefix is empty so `lex run main.lex process` works
    // without users typing the hashed prefix.
    state.prefixes.insert(entry_canonical.clone(), String::new());
    state.load(&entry_canonical)
}

/// Load a Lex program from a string source. Local-path imports are
/// rejected up-front since there's no base path to resolve from.
pub fn load_program_from_str(src: &str) -> Result<Program, LoadError> {
    let prog = parse_source(src).map_err(|source| LoadError::Syntax {
        path: "<input>".into(),
        source,
    })?;
    for item in &prog.items {
        if let Item::Import(imp) = item {
            if is_path_import(&imp.reference)
                || split_package_import(&imp.reference).is_some()
            {
                return Err(LoadError::LocalImportInStringSource);
            }
        }
    }
    Ok(prog)
}

struct LoaderState {
    in_progress: Vec<PathBuf>,
    /// Canonical paths that have already been merged into the output.
    /// A second `import "./shared"` from a different parent skips
    /// re-merging — the file's mangled items are already there.
    loaded: HashSet<PathBuf>,
    /// Stable mangling prefix per canonical path. Computed lazily;
    /// the entry file is seeded with an empty prefix.
    prefixes: HashMap<PathBuf, String>,
    /// When set, mangling prefixes hash each file's path relative to
    /// this (already canonicalized) directory rather than its absolute
    /// path, so the same package layout mangles identically wherever it
    /// is unpacked. See the module header's "Mangling" section.
    prefix_root: Option<PathBuf>,
    /// Mixed into every relative mangling key ahead of the path, so two
    /// packages sharing an internal layout (two `src/error.lex` files)
    /// do not mangle to one set of names. Only [`load_package`] sets it.
    prefix_namespace: Option<String>,
    /// Stdlib modules imported by each file itself, keyed by the file's
    /// root-relative path. Recorded for every file the loader reads;
    /// only [`load_package`] hands it back.
    imports_by_file: BTreeMap<String, BTreeSet<String>>,
}

impl LoaderState {
    fn prefix_for(&mut self, canonical: &Path) -> String {
        if let Some(p) = self.prefixes.get(canonical) {
            return p.clone();
        }
        let stem = canonical
            .file_stem()
            .and_then(|s| s.to_str())
            .unwrap_or("module");
        let mut hasher = Sha256::new();
        hasher.update(self.mangling_key(canonical).as_bytes());
        let digest = hasher.finalize();
        let prefix = format!("{stem}_{:08x}", u32::from_be_bytes([
            digest[0], digest[1], digest[2], digest[3],
        ]));
        self.prefixes.insert(canonical.to_path_buf(), prefix.clone());
        prefix
    }

    /// The string a file's mangling hash is taken over: `prefix_namespace`
    /// (when set) followed by the file's path relative to `prefix_root`,
    /// else its canonical absolute path. Relative keys are joined with
    /// `/` regardless of platform so the same layout hashes the same on
    /// Windows and Unix.
    fn mangling_key(&self, canonical: &Path) -> String {
        match (self.relative_key(canonical), &self.prefix_namespace) {
            (Some(rel), Some(ns)) => format!("{ns}/{rel}"),
            (Some(rel), None) => rel,
            (None, _) => canonical.to_string_lossy().into_owned(),
        }
    }

    /// A file's path relative to `prefix_root`, `/`-joined — `None` when
    /// there is no root or the file lives outside it. Also the key
    /// `imports_by_file` is reported under, which is why it carries no
    /// namespace: those keys name files in the archive, and history
    /// already records them under exactly this spelling.
    fn relative_key(&self, canonical: &Path) -> Option<String> {
        let root = self.prefix_root.as_ref()?;
        let rel = canonical.strip_prefix(root).ok()?;
        let key = rel
            .components()
            .map(|c| c.as_os_str().to_string_lossy())
            .collect::<Vec<_>>()
            .join("/");
        // An empty key means `canonical == root` (a root pointing at the
        // file itself) — not a usable key, and it would collide with any
        // other such file.
        if key.is_empty() {
            None
        } else {
            Some(key)
        }
    }

    fn load(&mut self, canonical: &Path) -> Result<Program, LoadError> {
        if self.in_progress.contains(&canonical.to_path_buf()) {
            let mut chain: Vec<String> = self
                .in_progress
                .iter()
                .map(|p| p.display().to_string())
                .collect();
            chain.push(canonical.display().to_string());
            return Err(LoadError::Cycle {
                chain: chain.join(" -> "),
            });
        }
        // Diamond dedupe: if this file was already merged on another
        // path through the import graph, its items are already in the
        // output Vec — return an empty Program so the caller's
        // `merged_children.extend(...)` is a no-op for items, but the
        // call still resolves so the parent's `path_imports` map gets
        // populated below.
        if self.loaded.contains(canonical) {
            return Ok(Program {
                items: Vec::new(),
                leading_comments: Vec::new(),
                trailing_comments: Vec::new(),
            });
        }
        self.in_progress.push(canonical.to_path_buf());

        let src = std::fs::read_to_string(canonical).map_err(|source| LoadError::Io {
            path: canonical.display().to_string(),
            source,
        })?;
        let prog = parse_source(&src).map_err(|source| LoadError::Syntax {
            path: canonical.display().to_string(),
            source,
        })?;

        let local_names: HashSet<String> = prog
            .items
            .iter()
            .filter_map(|item| match item {
                Item::FnDecl(fd) => Some(fd.name.clone()),
                Item::TypeDecl(td) => Some(td.name.clone()),
                _ => None,
            })
            .collect();

        // alias used by this file → mangling prefix of the imported file
        let mut path_imports: HashMap<String, String> = HashMap::new();
        let mut merged_children: Vec<Item> = Vec::new();
        let mut std_imports: Vec<Item> = Vec::new();
        let mut my_items: Vec<Item> = Vec::new();

        for item in prog.items {
            match item {
                Item::Import(ref imp) if is_path_import(&imp.reference) => {
                    let resolved = resolve_import(canonical, &imp.reference)?;
                    let child_prefix = self.prefix_for(&resolved);
                    path_imports.insert(imp.alias.clone(), child_prefix);
                    let child_prog = self.load(&resolved)?;
                    merged_children.extend(child_prog.items);
                }
                Item::Import(ref imp)
                    if split_package_import(&imp.reference).is_some() =>
                {
                    let (pkg, module) =
                        split_package_import(&imp.reference).unwrap();
                    let resolved =
                        resolve_package_import(canonical, pkg, module)
                            .map_err(LoadError::Package)?
                            .canonicalize()
                            .map_err(|source| LoadError::Io {
                                path: imp.reference.clone(),
                                source,
                            })?;
                    let child_prefix = self.prefix_for(&resolved);
                    path_imports.insert(imp.alias.clone(), child_prefix);
                    let child_prog = self.load(&resolved)?;
                    merged_children.extend(child_prog.items);
                }
                Item::Import(_) => std_imports.push(item),
                _ => my_items.push(item),
            }
        }

        // Attribute this file's own stdlib imports to this file, before
        // the merge below makes them indistinguishable from its
        // children's. Every file gets an entry, imports or not, so a
        // file that has dropped its last import is still represented.
        if let Some(key) = self.relative_key(canonical) {
            let entry = self.imports_by_file.entry(key).or_default();
            for item in &std_imports {
                if let Item::Import(imp) = item {
                    entry.insert(imp.reference.clone());
                }
            }
        }

        let my_prefix = self.prefix_for(canonical);
        let mangler = Mangler {
            prefix: my_prefix,
            local_names: &local_names,
            path_imports: &path_imports,
        };
        let mangled: Vec<Item> = my_items
            .into_iter()
            .map(|i| mangler.mangle_item(i))
            .collect();

        self.in_progress.pop();
        self.loaded.insert(canonical.to_path_buf());

        // Output order: std imports first (deduped against children's),
        // then merged children's items, then this file's items.
        let mut out: Vec<Item> = Vec::new();
        for s in std_imports {
            if !merged_children.iter().any(|m| m == &s) {
                out.push(s);
            }
        }
        out.extend(merged_children);
        out.extend(mangled);
        // Top-of-file comments live on each source file independently;
        // after import merging the merged Program represents many
        // files at once, and there is no obvious single "top of file"
        // to attribute them to. Drop here — they're preserved by
        // `lex fmt` (which operates per-file) but not by the loader's
        // import-merging path. Same rationale for trailing_comments.
        Ok(Program {
            items: out,
            leading_comments: Vec::new(),
            trailing_comments: Vec::new(),
        })
    }
}

fn is_path_import(reference: &str) -> bool {
    reference.starts_with("./") || reference.starts_with("../") || reference.starts_with('/')
}

/// Returns `Some((pkg_name, module_path))` for package imports like
/// `"lex-schema/validate"`. Stdlib (`std.*`) and relative paths are
/// excluded — they are handled elsewhere.
fn split_package_import(reference: &str) -> Option<(&str, &str)> {
    if reference.starts_with("./")
        || reference.starts_with("../")
        || reference.starts_with('/')
        || reference.starts_with("std.")
    {
        return None;
    }
    reference.split_once('/')
}

fn resolve_import(importer: &Path, reference: &str) -> Result<PathBuf, LoadError> {
    let importer_dir = importer.parent().unwrap_or_else(|| Path::new("."));
    let mut resolved: PathBuf = if reference.starts_with('/') {
        PathBuf::from(reference)
    } else {
        importer_dir.join(reference)
    };
    if resolved.extension().is_none() {
        resolved.set_extension("lex");
    }
    if !resolved.exists() {
        return Err(LoadError::NotFound {
            importer: importer.display().to_string(),
            reference: reference.to_string(),
        });
    }
    // Canonicalize so that `../../shared/foo` and `../other/../shared/foo`
    // resolve to the same HashMap key, preventing duplicate loads and
    // mismatched mangling prefixes in diamond-import graphs (#358).
    resolved.canonicalize().map_err(|source| LoadError::Io {
        path: resolved.display().to_string(),
        source,
    })
}

struct Mangler<'a> {
    /// Mangling prefix for items declared in this file. Empty for the
    /// entry file, `<stem>_<hash8>` for imported files.
    prefix: String,
    local_names: &'a HashSet<String>,
    /// Map from local alias to the imported file's mangling prefix.
    /// `m.foo` rewrites to `<imported_prefix>.foo` regardless of which
    /// alias `m` was, so two parents importing the same module agree.
    path_imports: &'a HashMap<String, String>,
}

impl<'a> Mangler<'a> {
    fn qualify(&self, name: &str) -> String {
        if self.prefix.is_empty() {
            name.to_string()
        } else {
            format!("{}.{}", self.prefix, name)
        }
    }

    fn mangle_item(&self, item: Item) -> Item {
        match item {
            Item::Import(imp) => Item::Import(imp),
            Item::TypeDecl(td) => Item::TypeDecl(self.mangle_type_decl(td)),
            Item::FnDecl(fd) => Item::FnDecl(self.mangle_fn_decl(fd)),
        }
    }

    fn mangle_type_decl(&self, td: TypeDecl) -> TypeDecl {
        TypeDecl {
            name: self.qualify(&td.name),
            params: td.params,
            definition: self.mangle_type_expr(td.definition),
            leading_comments: td.leading_comments,
        }
    }

    fn mangle_fn_decl(&self, fd: FnDecl) -> FnDecl {
        let mut shadow = HashSet::new();
        for p in &fd.params {
            shadow.insert(p.name.clone());
        }
        // Example args/expected sit outside the body's parameter scope:
        // they're top-level expressions evaluated against the function
        // signature, so the only names they can see are the file's
        // top-level fns/types and any path-import aliases — i.e., an
        // empty shadow set (#391).
        let empty_shadow = HashSet::new();
        let examples = fd
            .examples
            .into_iter()
            .map(|ex| Example {
                args: ex
                    .args
                    .into_iter()
                    .map(|a| self.mangle_expr(a, &empty_shadow))
                    .collect(),
                expected: self.mangle_expr(ex.expected, &empty_shadow),
            })
            .collect();
        FnDecl {
            name: self.qualify(&fd.name),
            type_params: fd.type_params,
            params: fd
                .params
                .into_iter()
                .map(|p| Param {
                    name: p.name,
                    ty: self.mangle_type_expr(p.ty),
                })
                .collect(),
            effects: fd.effects,
            effect_row_var: fd.effect_row_var,
            return_type: self.mangle_type_expr(fd.return_type),
            body: self.mangle_block(fd.body, &shadow),
            examples,
            leading_comments: fd.leading_comments,
        }
    }

    fn mangle_type_expr(&self, te: TypeExpr) -> TypeExpr {
        match te {
            TypeExpr::Named { name, args } => TypeExpr::Named {
                name: self.rewrite_type_name(&name),
                args: args.into_iter().map(|a| self.mangle_type_expr(a)).collect(),
            },
            TypeExpr::Record(fields) => TypeExpr::Record(
                fields
                    .into_iter()
                    .map(|f| TypeField {
                        name: f.name,
                        ty: self.mangle_type_expr(f.ty),
                    })
                    .collect(),
            ),
            TypeExpr::RecordWithSpreads { spreads, fields } => TypeExpr::RecordWithSpreads {
                spreads: spreads.into_iter().map(|s| self.rewrite_type_name(&s)).collect(),
                fields: fields
                    .into_iter()
                    .map(|f| TypeField {
                        name: f.name,
                        ty: self.mangle_type_expr(f.ty),
                    })
                    .collect(),
            },
            TypeExpr::Tuple(items) => {
                TypeExpr::Tuple(items.into_iter().map(|t| self.mangle_type_expr(t)).collect())
            }
            TypeExpr::Function {
                params,
                effects,
                effect_row_var,
                ret,
            } => TypeExpr::Function {
                params: params
                    .into_iter()
                    .map(|t| self.mangle_type_expr(t))
                    .collect(),
                effects,
                effect_row_var,
                ret: Box::new(self.mangle_type_expr(*ret)),
            },
            TypeExpr::Union(variants) => TypeExpr::Union(
                variants
                    .into_iter()
                    .map(|v| UnionVariant {
                        name: v.name,
                        payload: v.payload.map(|t| self.mangle_type_expr(t)),
                    })
                    .collect(),
            ),
            TypeExpr::Refined { base, binding, predicate } => TypeExpr::Refined {
                base: Box::new(self.mangle_type_expr(*base)),
                binding,
                // The predicate is an expression; its names are
                // resolved during type-check, not loader-time, so
                // it passes through unchanged here. Slice 2 wires
                // up discharge through the spec-checker.
                predicate,
            },
        }
    }

    /// Rewrite a possibly-qualified type name to its mangled form.
    fn rewrite_type_name(&self, name: &str) -> String {
        if let Some((alias, rest)) = name.split_once('.') {
            if let Some(child) = self.path_imports.get(alias) {
                return format!("{child}.{rest}");
            }
            return name.to_string();
        }
        if self.local_names.contains(name) {
            return self.qualify(name);
        }
        name.to_string()
    }

    fn mangle_block(&self, b: Block, shadow: &HashSet<String>) -> Block {
        let mut shadow = shadow.clone();
        let statements = b
            .statements
            .into_iter()
            .map(|s| match s {
                Statement::Let { name, ty, value } => {
                    let value = self.mangle_expr(value, &shadow);
                    let ty = ty.map(|t| self.mangle_type_expr(t));
                    shadow.insert(name.clone());
                    Statement::Let { name, ty, value }
                }
                Statement::Expr(e) => Statement::Expr(self.mangle_expr(e, &shadow)),
            })
            .collect();
        let result = Box::new(self.mangle_expr(*b.result, &shadow));
        Block { statements, result }
    }

    fn mangle_expr(&self, e: Expr, shadow: &HashSet<String>) -> Expr {
        match e {
            Expr::Lit(_) => e,
            Expr::Var(name) => {
                if !shadow.contains(&name) && self.local_names.contains(&name) {
                    Expr::Var(self.qualify(&name))
                } else {
                    Expr::Var(name)
                }
            }
            Expr::Block(b) => Expr::Block(self.mangle_block(b, shadow)),
            Expr::Call { callee, args } => {
                let mangled_args: Vec<Expr> = args
                    .into_iter()
                    .map(|a| self.mangle_expr(a, shadow))
                    .collect();
                if let Expr::Field { value, field } = (*callee).clone() {
                    if let Expr::Var(alias) = *value {
                        if !shadow.contains(&alias) {
                            if let Some(child) = self.path_imports.get(&alias) {
                                return Expr::Call {
                                    callee: Box::new(Expr::Var(format!("{child}.{field}"))),
                                    args: mangled_args,
                                };
                            }
                        }
                    }
                }
                Expr::Call {
                    callee: Box::new(self.mangle_expr(*callee, shadow)),
                    args: mangled_args,
                }
            }
            Expr::Pipe { left, right } => Expr::Pipe {
                left: Box::new(self.mangle_expr(*left, shadow)),
                right: Box::new(self.mangle_expr(*right, shadow)),
            },
            Expr::Try(inner) => Expr::Try(Box::new(self.mangle_expr(*inner, shadow))),
            Expr::Field { value, field } => {
                if let Expr::Var(alias) = (*value).clone() {
                    if !shadow.contains(&alias) {
                        if let Some(child) = self.path_imports.get(&alias) {
                            return Expr::Var(format!("{child}.{field}"));
                        }
                    }
                }
                Expr::Field {
                    value: Box::new(self.mangle_expr(*value, shadow)),
                    field,
                }
            }
            Expr::BinOp { op, lhs, rhs } => Expr::BinOp {
                op,
                lhs: Box::new(self.mangle_expr(*lhs, shadow)),
                rhs: Box::new(self.mangle_expr(*rhs, shadow)),
            },
            Expr::UnaryOp { op, expr } => Expr::UnaryOp {
                op,
                expr: Box::new(self.mangle_expr(*expr, shadow)),
            },
            Expr::If {
                cond,
                then_block,
                else_block,
            } => Expr::If {
                cond: Box::new(self.mangle_expr(*cond, shadow)),
                then_block: self.mangle_block(then_block, shadow),
                else_block: self.mangle_block(else_block, shadow),
            },
            Expr::Match { scrutinee, arms } => Expr::Match {
                scrutinee: Box::new(self.mangle_expr(*scrutinee, shadow)),
                arms: arms
                    .into_iter()
                    .map(|a| {
                        let mut arm_shadow = shadow.clone();
                        collect_pattern_binders(&a.pattern, &mut arm_shadow);
                        Arm {
                            pattern: self.mangle_pattern(a.pattern),
                            body: self.mangle_expr(a.body, &arm_shadow),
                        }
                    })
                    .collect(),
            },
            Expr::RecordLit(fields) => Expr::RecordLit(
                fields
                    .into_iter()
                    .map(|f| RecordLitField {
                        name: f.name,
                        value: self.mangle_expr(f.value, shadow),
                    })
                    .collect(),
            ),
            Expr::TupleLit(items) => Expr::TupleLit(
                items
                    .into_iter()
                    .map(|i| self.mangle_expr(i, shadow))
                    .collect(),
            ),
            Expr::ListLit(items) => Expr::ListLit(
                items
                    .into_iter()
                    .map(|i| self.mangle_expr(i, shadow))
                    .collect(),
            ),
            Expr::Constructor { name, args } => Expr::Constructor {
                name,
                args: args
                    .into_iter()
                    .map(|a| self.mangle_expr(a, shadow))
                    .collect(),
            },
            Expr::Ascription { value, ty } => Expr::Ascription {
                value: Box::new(self.mangle_expr(*value, shadow)),
                ty: self.mangle_type_expr(ty),
            },
            Expr::Lambda(lambda) => {
                let mut lam_shadow = shadow.clone();
                for p in &lambda.params {
                    lam_shadow.insert(p.name.clone());
                }
                Expr::Lambda(Box::new(Lambda {
                    params: lambda
                        .params
                        .into_iter()
                        .map(|p| Param {
                            name: p.name,
                            ty: self.mangle_type_expr(p.ty),
                        })
                        .collect(),
                    return_type: self.mangle_type_expr(lambda.return_type),
                    effects: lambda.effects,
                    effect_row_var: lambda.effect_row_var,
                    body: self.mangle_block(lambda.body, &lam_shadow),
                }))
            }
        }
    }

    fn mangle_pattern(&self, p: Pattern) -> Pattern {
        match p {
            Pattern::Constructor { name, args } => Pattern::Constructor {
                name,
                args: args.into_iter().map(|a| self.mangle_pattern(a)).collect(),
            },
            Pattern::Record { fields, rest } => Pattern::Record {
                fields: fields
                    .into_iter()
                    .map(|f| RecordPatField {
                        name: f.name,
                        pattern: f.pattern.map(|p| self.mangle_pattern(p)),
                    })
                    .collect(),
                rest,
            },
            Pattern::Tuple(items) => {
                Pattern::Tuple(items.into_iter().map(|p| self.mangle_pattern(p)).collect())
            }
            Pattern::Lit(_) | Pattern::Var(_) | Pattern::Wild => p,
        }
    }
}

fn collect_pattern_binders(p: &Pattern, out: &mut HashSet<String>) {
    match p {
        Pattern::Var(name) => {
            out.insert(name.clone());
        }
        Pattern::Constructor { args, .. } => {
            for a in args {
                collect_pattern_binders(a, out);
            }
        }
        Pattern::Record { fields, .. } => {
            for f in fields {
                match &f.pattern {
                    Some(p) => collect_pattern_binders(p, out),
                    // `{ name }` shorthand binds `name`.
                    None => {
                        out.insert(f.name.clone());
                    }
                }
            }
        }
        Pattern::Tuple(items) => {
            for p in items {
                collect_pattern_binders(p, out);
            }
        }
        Pattern::Lit(_) | Pattern::Wild => {}
    }
}