Skip to main content

harn_modules/
lib.rs

1use std::collections::{HashMap, HashSet};
2use std::path::{Path, PathBuf};
3
4use crate::package_imports::acquire_package_snapshots;
5use crate::package_snapshot::PackageSnapshot;
6use harn_lexer::Span;
7use harn_parser::{Parser, SNode};
8
9pub mod asset_paths;
10mod declarations;
11pub mod fingerprint;
12pub mod host_capabilities;
13pub mod host_capability_config;
14mod import_recording;
15pub mod manifest_walk;
16mod namespace_imports;
17mod namespace_signatures;
18pub mod package_execution;
19mod package_imports;
20pub mod package_snapshot;
21pub mod personas;
22pub mod project_config;
23mod references;
24mod standalone;
25mod stdlib;
26mod symbol_reachability;
27mod type_dependencies;
28mod typecheck;
29mod visibility;
30
31use declarations::{
32    callable_decl_name, collect_callable_declarations, collect_module_info,
33    collect_type_declarations, decl_site, type_decl_name,
34};
35pub use declarations::{public_declarations, sibling_declarations, DefKind, PublicDeclaration};
36pub use namespace_imports::NamespaceImportInfo;
37pub use namespace_signatures::NamespaceMemberSignature;
38pub use package_imports::{
39    resolve_import_path, resolve_import_path_with_guard, resolve_import_path_with_snapshot,
40    unresolved_package_alias, PackageImport,
41};
42pub use references::{index_references, RefSite, ReferenceEdge, ReferenceIndex};
43pub use standalone::build_with_standalone_source;
44use standalone::PackageContext;
45pub use symbol_reachability::{
46    closed_program_reachability, ExportDemand, ModuleSymbolDemand, SymbolReachability,
47};
48pub use visibility::{sibling_directory_access, sibling_module_access};
49
50/// A resolved definition site within a module.
51#[derive(Debug, Clone, PartialEq, Eq)]
52pub struct DefSite {
53    pub name: String,
54    pub file: PathBuf,
55    pub kind: DefKind,
56    pub span: Span,
57}
58
59/// Wildcard import resolution status for a single importing module.
60#[derive(Debug, Clone)]
61pub enum WildcardResolution {
62    /// Resolved all wildcard imports and can expose wildcard exports.
63    Resolved(HashSet<String>),
64    /// At least one wildcard import could not be resolved.
65    Unknown,
66}
67
68/// Parsed information for a set of module files.
69#[derive(Debug, Default)]
70pub struct ModuleGraph {
71    modules: HashMap<PathBuf, ModuleInfo>,
72    // Resolved definition/import paths remain valid for the graph lifetime.
73    _package_snapshots: Vec<PackageSnapshot>,
74}
75
76#[derive(Debug, Clone)]
77pub struct ParsedModuleSource {
78    pub source: String,
79    pub program: Vec<SNode>,
80}
81
82#[derive(Debug, Default)]
83pub struct ModuleGraphBuild {
84    pub graph: ModuleGraph,
85    pub parsed_sources: HashMap<PathBuf, ParsedModuleSource>,
86}
87
88#[derive(Debug, Default)]
89struct ModuleInfo {
90    /// All declarations visible in this module (for local symbol lookup and
91    /// go-to-definition resolution).
92    declarations: HashMap<String, DefSite>,
93    /// Names exported by this module after re-export resolution. Equal to
94    /// [`own_exports`] union the keys of [`selective_re_exports`] union the
95    /// transitive exports of [`wildcard_re_export_paths`]. Populated in
96    /// `build()` after all modules are loaded.
97    exports: HashSet<String>,
98    /// Names declared locally and exported by this module — i.e. `pub fn`,
99    /// `pub struct`, etc.
100    own_exports: HashSet<String>,
101    /// Local declarations explicitly shared with sibling modules. These are
102    /// absent from every public export projection.
103    sibling_exports: HashSet<String>,
104    /// Selective re-exports introduced by `pub import { name } from "..."`.
105    /// Maps the re-exported name to every canonical source module path it
106    /// could originate from. Multiple entries per name indicate a conflict
107    /// (`pub import { foo } from "a"` and `pub import { foo } from "b"`)
108    /// and are surfaced by [`ModuleGraph::re_export_conflicts`]. Lookup
109    /// callers (e.g. go-to-definition) follow the first recorded source.
110    selective_re_exports: HashMap<String, Vec<PathBuf>>,
111    /// Wildcard re-exports introduced by `pub import "..."`. Each entry is
112    /// the canonical path of a module whose entire public export surface
113    /// this module re-exports.
114    wildcard_re_export_paths: Vec<PathBuf>,
115    /// Namespace re-exports introduced by `pub import * as alias from "..."`.
116    /// Maps the published alias to the canonical target module path. Unlike
117    /// wildcard re-exports, members are **not** flattened into this module's
118    /// public surface — only the alias object itself is exported
119    /// (`DefKind::Variable`). Folded into [`exports`] / [`declarations`] at
120    /// collection time so graph finalization needs no second pass.
121    namespace_re_exports: HashMap<String, PathBuf>,
122    /// Names introduced by selective imports across this module.
123    selective_import_names: HashSet<String>,
124    /// Import references encountered in this file.
125    imports: Vec<ImportRef>,
126    /// True when at least one wildcard import could not be resolved.
127    has_unresolved_wildcard_import: bool,
128    /// True when at least one selective import could not be resolved
129    /// (importing file path missing). Prevents `imported_names_for_file`
130    /// from returning a partial answer when any import is broken.
131    has_unresolved_selective_import: bool,
132    /// True when at least one namespace import could not be resolved.
133    has_unresolved_namespace_import: bool,
134    /// Top-level type-like declarations that can be imported into a caller's
135    /// static type environment.
136    type_declarations: Vec<SNode>,
137    /// Top-level callable signature projections imported into a caller's
138    /// static type environment. Function bodies are discarded at graph ingress.
139    callable_declarations: Vec<SNode>,
140    /// Set when this module's own source failed to lex or parse. The module is
141    /// still recorded in the graph (with an otherwise-empty surface) so that
142    /// importers can be told their target is broken — instead of silently
143    /// seeing zero exports and mislabeling the imported symbol as "undefined"
144    /// at the call site.
145    load_error: Option<ModuleLoadError>,
146}
147
148/// A lex/parse failure captured while loading a module into the graph.
149///
150/// Retained so that `harn check <consumer>` can surface the real error in an
151/// imported file rather than downgrading its exports to "undefined" at the
152/// consumer's call site.
153#[derive(Debug, Clone)]
154pub struct ModuleLoadError {
155    /// Rendered lex/parse error message (includes the failing line:column).
156    pub message: String,
157    /// Span of the failure within the imported module's own source.
158    pub span: Span,
159}
160
161/// A consumer import whose resolved target module failed to compile. Reported
162/// by [`ModuleGraph::import_compile_failures`].
163#[derive(Debug, Clone)]
164pub struct ImportCompileFailure {
165    /// The import path exactly as written in the consumer.
166    pub import_raw_path: String,
167    /// Span of the consumer's `import` statement.
168    pub import_span: Span,
169    /// Canonical path of the broken imported module.
170    pub module_path: PathBuf,
171    /// The imported module's real lex/parse error.
172    pub error: ModuleLoadError,
173}
174
175#[derive(Debug, Clone)]
176struct ImportRef {
177    raw_path: String,
178    path: Option<PathBuf>,
179    selective_names: Option<HashSet<String>>,
180    /// When set, this is `import * as alias from "..."` — only the alias is
181    /// bound in the importer (members stay under the namespace object).
182    namespace_alias: Option<String>,
183    is_pub: bool,
184    import_span: Span,
185}
186
187/// Public import edge summary for static module graph consumers.
188#[derive(Debug, Clone, PartialEq, Eq)]
189pub struct ModuleImport {
190    /// The import string as written in source.
191    pub raw_path: String,
192    /// Resolved module path when the import could be resolved.
193    pub resolved_path: Option<PathBuf>,
194    /// `None` for wildcard / namespace imports; otherwise the selected names.
195    pub selective_names: Option<Vec<String>>,
196    /// When set, this is a namespace import (`import * as alias from "..."`).
197    pub namespace_alias: Option<String>,
198    /// Whether the import republishes its selected projection.
199    pub is_pub: bool,
200}
201
202/// Return the source for a resolved module path.
203///
204/// Real paths are read from disk. `<std>/<module>` virtual paths are backed by
205/// the embedded stdlib source table, so callers can parse resolved stdlib
206/// modules without knowing about the stdlib mirror layout.
207pub fn read_module_source(path: &Path) -> Option<String> {
208    if let Some(stdlib_module) = stdlib_module_name(path) {
209        return stdlib::get_stdlib_source(stdlib_module).map(ToString::to_string);
210    }
211    std::fs::read_to_string(path).ok()
212}
213
214/// Build a module graph from a set of files.
215///
216/// Files referenced via `import` statements are loaded recursively so the
217/// graph contains every module reachable from the seed set. Cycles and
218/// already-loaded files are skipped via a visited set.
219pub fn build(files: &[PathBuf]) -> ModuleGraph {
220    build_inner(
221        files,
222        ParsedSourceRetention::None,
223        None,
224        PackageContext::Project,
225    )
226    .graph
227}
228
229/// Build a module graph using caller-owned source for one root file.
230///
231/// Imported modules still resolve from their normal filesystem or embedded
232/// stdlib locations. This keeps editor diagnostics aligned with unsaved root
233/// buffers without creating a second module resolver.
234pub fn build_with_source(file: &Path, source: &str) -> ModuleGraph {
235    let file = normalize_path(file);
236    let source_overrides = HashMap::from([(file.clone(), source.to_string())]);
237    build_inner(
238        &[file],
239        ParsedSourceRetention::None,
240        Some(&source_overrides),
241        PackageContext::Project,
242    )
243    .graph
244}
245
246/// Build a module graph while retaining parsed sources for the seed files.
247///
248/// Imported-only modules still participate in the graph, but their ASTs are
249/// dropped after graph extraction so callers do not pay extra peak memory for
250/// parsed sources they will not reuse.
251pub fn build_with_parsed_sources(files: &[PathBuf]) -> ModuleGraphBuild {
252    let parsed_source_targets = files.iter().map(|file| normalize_path(file)).collect();
253    build_inner(
254        files,
255        ParsedSourceRetention::Seeds(&parsed_source_targets),
256        None,
257        PackageContext::Project,
258    )
259}
260
261/// Build a closed module graph while retaining every reachable parsed source.
262///
263/// This is intentionally separate from editor-oriented graph construction:
264/// package linking consumes every module AST, while ordinary diagnostics should
265/// not retain an entire dependency graph after extracting its public surface.
266pub fn build_closed_program(files: &[PathBuf]) -> ModuleGraphBuild {
267    build_inner(
268        files,
269        ParsedSourceRetention::All,
270        None,
271        PackageContext::Project,
272    )
273}
274
275#[derive(Clone, Copy)]
276enum ParsedSourceRetention<'a> {
277    None,
278    Seeds(&'a HashSet<PathBuf>),
279    All,
280}
281
282impl ParsedSourceRetention<'_> {
283    fn retains(self, path: &Path) -> bool {
284        match self {
285            Self::None => false,
286            Self::Seeds(targets) => targets.contains(path),
287            Self::All => true,
288        }
289    }
290}
291
292/// Build a module graph that retains every reachable AST and honors unsaved
293/// buffer overrides.
294///
295/// This is the construction find-references and `harn graph` share: one
296/// resolution graph, one inverse index. `source_overrides` replace disk
297/// contents for the named files so an editor buffer wins over the file it
298/// just edited.
299pub fn build_for_reference_index(
300    files: &[PathBuf],
301    source_overrides: Option<&HashMap<PathBuf, String>>,
302) -> ModuleGraphBuild {
303    build_inner(
304        files,
305        ParsedSourceRetention::All,
306        source_overrides,
307        PackageContext::Project,
308    )
309}
310
311fn build_inner(
312    files: &[PathBuf],
313    parsed_source_retention: ParsedSourceRetention<'_>,
314    source_overrides: Option<&HashMap<PathBuf, String>>,
315    package_context: PackageContext,
316) -> ModuleGraphBuild {
317    let package_snapshots = match package_context {
318        PackageContext::Project => acquire_package_snapshots(files),
319        PackageContext::Standalone => Vec::new(),
320    };
321    let mut modules: HashMap<PathBuf, ModuleInfo> = HashMap::new();
322    let mut parsed_sources: HashMap<PathBuf, ParsedModuleSource> = HashMap::new();
323    let mut seen: HashSet<PathBuf> = HashSet::new();
324    let mut wave: Vec<PathBuf> = Vec::new();
325    for file in files {
326        let canonical = normalize_path(file);
327        if seen.insert(canonical.clone()) {
328            wave.push(canonical);
329        }
330    }
331    // Breadth-first over import waves. Every path in a wave is new (the
332    // `seen` set dedupes before enqueue), and `load_module` is a pure
333    // read+lex+parse+extract, so each wave loads in parallel; discovery of
334    // the next wave stays sequential to keep the dedup deterministic. A
335    // whole-tree seed set arrives as one large first wave, which is where
336    // nearly all the parse work is, so the serial-BFS tail on deep import
337    // chains does not matter in practice.
338    while !wave.is_empty() {
339        let loaded = load_wave(
340            &wave,
341            &package_snapshots,
342            parsed_source_retention,
343            source_overrides,
344        );
345        let mut next_wave: Vec<PathBuf> = Vec::new();
346        for (path, (module, parsed)) in wave.drain(..).zip(loaded) {
347            if parsed_source_retention.retains(&path) {
348                if let Some(parsed) = parsed {
349                    parsed_sources.insert(path.clone(), parsed);
350                }
351            }
352            // Enqueue resolved import targets so the whole reachable graph is
353            // discovered without the caller having to pre-walk imports.
354            //
355            // `resolve_import_path` returns paths as `base.join(import)` —
356            // i.e. with `..` segments preserved rather than collapsed. If we
357            // dedupe on those raw forms, two files that import each other
358            // across sibling dirs (`lib/context/` ↔ `lib/runtime/`) produce a
359            // different path spelling on every cycle — `.../context/../runtime/`,
360            // then `.../context/../runtime/../context/`, and so on — each of
361            // which is treated as a new file. The walk only terminates when
362            // `path.exists()` starts failing at the filesystem's `PATH_MAX`,
363            // which is 1024 on macOS but 4096 on Linux. Linux therefore
364            // re-parses the same handful of files thousands of times, balloons
365            // RSS into the multi-GB range, and gets SIGKILL'd by CI runners.
366            // Canonicalize once here so `seen` dedupes by the underlying file,
367            // not by its path spelling.
368            for import in &module.imports {
369                if let Some(import_path) = &import.path {
370                    let canonical = normalize_path(import_path);
371                    if seen.insert(canonical.clone()) {
372                        next_wave.push(canonical);
373                    }
374                }
375            }
376            modules.insert(path, module);
377        }
378        wave = next_wave;
379    }
380    resolve_re_exports(&mut modules);
381    ModuleGraphBuild {
382        graph: ModuleGraph {
383            modules,
384            _package_snapshots: package_snapshots,
385        },
386        parsed_sources,
387    }
388}
389
390/// Environment override for the graph-build worker-pool size. `1` forces the
391/// serial walk; unset defaults to the machine's available parallelism.
392pub const MODULE_GRAPH_JOBS_ENV: &str = "HARN_MODULE_GRAPH_JOBS";
393
394/// Load one BFS wave of module paths, in parallel when the wave is large
395/// enough to pay for the threads. Results are index-aligned with `paths`.
396fn load_wave(
397    paths: &[PathBuf],
398    package_snapshots: &[PackageSnapshot],
399    parsed_source_retention: ParsedSourceRetention<'_>,
400    source_overrides: Option<&HashMap<PathBuf, String>>,
401) -> Vec<(ModuleInfo, Option<ParsedModuleSource>)> {
402    const MIN_PARALLEL_WAVE: usize = 8;
403    let configured = std::env::var(MODULE_GRAPH_JOBS_ENV)
404        .ok()
405        .and_then(|value| value.parse::<usize>().ok())
406        .filter(|&jobs| jobs > 0);
407    let workers = configured
408        .unwrap_or_else(|| {
409            std::thread::available_parallelism()
410                .map(std::num::NonZeroUsize::get)
411                .unwrap_or(1)
412        })
413        .min(paths.len());
414    if workers <= 1 || paths.len() < MIN_PARALLEL_WAVE {
415        return paths
416            .iter()
417            .map(|path| {
418                load_module(
419                    path,
420                    package_snapshots,
421                    source_overrides,
422                    parsed_source_retention.retains(path),
423                )
424            })
425            .collect();
426    }
427    let next = std::sync::atomic::AtomicUsize::new(0);
428    let mut produced: Vec<(usize, (ModuleInfo, Option<ParsedModuleSource>))> =
429        std::thread::scope(|scope| {
430            let handles: Vec<_> = (0..workers)
431                .map(|_| {
432                    scope.spawn(|| {
433                        let mut local = Vec::new();
434                        loop {
435                            let index = next.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
436                            let Some(path) = paths.get(index) else {
437                                break;
438                            };
439                            local.push((
440                                index,
441                                load_module(
442                                    path,
443                                    package_snapshots,
444                                    source_overrides,
445                                    parsed_source_retention.retains(path),
446                                ),
447                            ));
448                        }
449                        local
450                    })
451                })
452                .collect();
453            handles
454                .into_iter()
455                .flat_map(|handle| match handle.join() {
456                    Ok(local) => local,
457                    Err(panic) => std::panic::resume_unwind(panic),
458                })
459                .collect()
460        });
461    produced.sort_unstable_by_key(|(index, _)| *index);
462    produced.into_iter().map(|(_, loaded)| loaded).collect()
463}
464
465/// Iteratively expand each module's `exports` set to include the transitive
466/// public surface of its `pub import "..."` re-export targets. Cycles are
467/// safe because the loop only adds names — once no module's set grows in a
468/// pass, the fixpoint is reached.
469fn resolve_re_exports(modules: &mut HashMap<PathBuf, ModuleInfo>) {
470    let keys: Vec<PathBuf> = modules.keys().cloned().collect();
471    loop {
472        let mut changed = false;
473        for path in &keys {
474            // Snapshot the wildcard target list and gather the union of
475            // their current exports without holding a mutable borrow.
476            let wildcard_paths = modules
477                .get(path)
478                .map(|m| m.wildcard_re_export_paths.clone())
479                .unwrap_or_default();
480            if wildcard_paths.is_empty() {
481                continue;
482            }
483            let mut additions: Vec<String> = Vec::new();
484            for src in &wildcard_paths {
485                let src_canonical = normalize_path(src);
486                if let Some(src_module) = modules.get(src).or_else(|| modules.get(&src_canonical)) {
487                    additions.extend(src_module.exports.iter().cloned());
488                }
489            }
490            if let Some(module) = modules.get_mut(path) {
491                for name in additions {
492                    if module.exports.insert(name) {
493                        changed = true;
494                    }
495                }
496            }
497        }
498        if !changed {
499            break;
500        }
501    }
502}
503
504impl ModuleGraph {
505    /// Sorted list of every module path discovered by [`build`]. Includes
506    /// `<std>/<name>` virtual paths for stdlib modules reached transitively.
507    /// Callers that want only real-disk modules can filter for paths whose
508    /// string form does not start with `<std>/`.
509    pub fn module_paths(&self) -> Vec<PathBuf> {
510        let mut paths: Vec<PathBuf> = self.modules.keys().cloned().collect();
511        paths.sort();
512        paths
513    }
514
515    /// True when `path` (or its canonical form) was discovered during the
516    /// module-graph walk.
517    pub fn contains_module(&self, path: &Path) -> bool {
518        self.modules.contains_key(path) || self.modules.contains_key(&normalize_path(path))
519    }
520
521    /// Collect every name used in selective imports from all files.
522    pub fn all_selective_import_names(&self) -> HashSet<&str> {
523        let mut names = HashSet::new();
524        for module in self.modules.values() {
525            for name in &module.selective_import_names {
526                names.insert(name.as_str());
527            }
528        }
529        names
530    }
531
532    /// Files that directly import `target`. Resolves `target` to a
533    /// canonical path before lookup so callers can pass either spelling.
534    pub fn importers_of(&self, target: &Path) -> Vec<PathBuf> {
535        let target = normalize_path(target);
536        let mut out: Vec<PathBuf> = self
537            .modules
538            .iter()
539            .filter(|(_, info)| {
540                info.imports.iter().any(|import| {
541                    import
542                        .path
543                        .as_ref()
544                        .is_some_and(|p| normalize_path(p) == target)
545                })
546            })
547            .map(|(path, _)| path.clone())
548            .collect();
549        out.sort();
550        out
551    }
552
553    /// Every module that directly or transitively imports `target`.
554    ///
555    /// The target itself is not included. Consumers that invalidate a changed
556    /// module should combine this result with the target when appropriate.
557    /// Cycles are handled by the visited set, and the result is sorted so CI
558    /// plans and editor projections remain deterministic.
559    pub fn transitive_importers_of(&self, target: &Path) -> Vec<PathBuf> {
560        let target = normalize_path(target);
561        let mut visited = HashSet::from([target.clone()]);
562        let mut pending = vec![target];
563        let mut out = Vec::new();
564
565        while let Some(current) = pending.pop() {
566            for importer in self.importers_of(&current) {
567                let importer = normalize_path(&importer);
568                if visited.insert(importer.clone()) {
569                    pending.push(importer.clone());
570                    out.push(importer);
571                }
572            }
573        }
574
575        out.sort();
576        out
577    }
578
579    /// Import edges declared by `file`, sorted by raw path and selected names.
580    pub fn imports_for_module(&self, file: &Path) -> Vec<ModuleImport> {
581        let file = normalize_path(file);
582        let Some(module) = self.modules.get(&file) else {
583            return Vec::new();
584        };
585        let mut imports: Vec<ModuleImport> = module
586            .imports
587            .iter()
588            .map(|import| {
589                let mut selective_names = import
590                    .selective_names
591                    .as_ref()
592                    .map(|names| names.iter().cloned().collect::<Vec<_>>());
593                if let Some(names) = selective_names.as_mut() {
594                    names.sort();
595                }
596                ModuleImport {
597                    raw_path: import.raw_path.clone(),
598                    resolved_path: import.path.as_ref().map(|path| normalize_path(path)),
599                    selective_names,
600                    namespace_alias: import.namespace_alias.clone(),
601                    is_pub: import.is_pub,
602                }
603            })
604            .collect();
605        imports.sort_by(|left, right| {
606            left.raw_path
607                .cmp(&right.raw_path)
608                .then_with(|| left.selective_names.cmp(&right.selective_names))
609                .then_with(|| left.namespace_alias.cmp(&right.namespace_alias))
610                .then_with(|| left.resolved_path.cmp(&right.resolved_path))
611        });
612        imports
613    }
614
615    /// Resolve wildcard imports for `file`.
616    ///
617    /// Returns `Unknown` when any wildcard import cannot be resolved, because
618    /// callers should conservatively disable wildcard-import-sensitive checks.
619    pub fn wildcard_exports_for(&self, file: &Path) -> WildcardResolution {
620        let file = normalize_path(file);
621        let Some(module) = self.modules.get(&file) else {
622            return WildcardResolution::Unknown;
623        };
624        if module.has_unresolved_wildcard_import {
625            return WildcardResolution::Unknown;
626        }
627
628        let mut names = HashSet::new();
629        for import in module
630            .imports
631            .iter()
632            .filter(|import| import.selective_names.is_none())
633        {
634            let Some(import_path) = &import.path else {
635                return WildcardResolution::Unknown;
636            };
637            let imported = self.modules.get(import_path).or_else(|| {
638                let normalized = normalize_path(import_path);
639                self.modules.get(&normalized)
640            });
641            let Some(_imported) = imported else {
642                return WildcardResolution::Unknown;
643            };
644            names.extend(self.exports_for_import(&file, import_path));
645        }
646        WildcardResolution::Resolved(names)
647    }
648
649    /// Collect every statically callable/referenceable name introduced into
650    /// `file` by its imports.
651    ///
652    /// Returns `Some` only when **every** import (wildcard or selective) in
653    /// `file` is fully resolvable via the graph. Returns `None` when any
654    /// import is unresolved, so callers can fall back to conservative
655    /// behavior instead of emitting spurious "undefined name" errors.
656    ///
657    /// The returned set contains:
658    /// - all public exports from wildcard-imported modules (transitively
659    ///   following `pub import` re-export chains), and
660    /// - selectively imported names that the target module actually exports
661    ///   (its `pub` surface or re-exports) — matching what the VM accepts at
662    ///   runtime. A name that exists only privately in the target is NOT
663    ///   importable.
664    ///
665    /// Every import in `file` whose resolved target module failed to lex or
666    /// parse. Lets `harn check <file>` surface the real error inside the
667    /// imported module (anchored at the consumer's `import` statement) instead
668    /// of downgrading the imported symbols to "undefined" at their call sites.
669    #[must_use]
670    pub fn import_compile_failures(&self, file: &Path) -> Vec<ImportCompileFailure> {
671        let file = normalize_path(file);
672        let Some(module) = self.modules.get(&file) else {
673            return Vec::new();
674        };
675        let mut failures = Vec::new();
676        for import in &module.imports {
677            let Some(import_path) = &import.path else {
678                continue;
679            };
680            let Some(target) = self
681                .modules
682                .get(import_path)
683                .or_else(|| self.modules.get(&normalize_path(import_path)))
684            else {
685                continue;
686            };
687            if let Some(error) = &target.load_error {
688                failures.push(ImportCompileFailure {
689                    import_raw_path: import.raw_path.clone(),
690                    import_span: import.import_span,
691                    module_path: normalize_path(import_path),
692                    error: error.clone(),
693                });
694            }
695        }
696        failures
697    }
698
699    pub fn imported_names_for_file(&self, file: &Path) -> Option<HashSet<String>> {
700        let file = normalize_path(file);
701        let module = self.modules.get(&file)?;
702        if module.has_unresolved_wildcard_import
703            || module.has_unresolved_selective_import
704            || module.has_unresolved_namespace_import
705        {
706            return None;
707        }
708
709        let mut names = HashSet::new();
710        for import in &module.imports {
711            // Namespace imports bind only the alias — never flatten members.
712            if let Some(alias) = &import.namespace_alias {
713                names.insert(alias.clone());
714                continue;
715            }
716            let import_path = import.path.as_ref()?;
717            let imported = self
718                .modules
719                .get(import_path)
720                .or_else(|| self.modules.get(&normalize_path(import_path)))?;
721            // The target parsed nothing (lex/parse failure). Fall back to the
722            // conservative `None` answer so the cross-module undefined-name
723            // check stays silent — the real error is surfaced separately by
724            // `import_compile_failures`, not mislabeled as an undefined symbol
725            // at this consumer's call site.
726            if imported.load_error.is_some() {
727                return None;
728            }
729            match &import.selective_names {
730                None => {
731                    names.extend(self.exports_for_import(&file, import_path));
732                }
733                Some(selective) => {
734                    // A selectively imported name is in scope when it exists in
735                    // the target module (as a declaration or a re-export). The
736                    // stricter "must be `pub`" check is reported precisely at
737                    // the import site by the `HARN-IMP-002` preflight scan
738                    // (`scan_selective_import_visibility`) and enforced at load
739                    // time, so it is intentionally *not* duplicated here —
740                    // otherwise a private import would surface both an
741                    // import-site and a redundant call-site error.
742                    for name in selective {
743                        if imported.declarations.contains_key(name)
744                            || imported.exports.contains(name)
745                        {
746                            names.insert(name.clone());
747                        }
748                    }
749                }
750            }
751        }
752        Some(names)
753    }
754
755    /// Collect imported names of one declaration kind from a module's public
756    /// imports. This preserves the target module's export boundary across
757    /// selective, wildcard, and re-exported imports while giving compilers
758    /// the narrow semantic metadata needed for syntax-sensitive lowering.
759    pub fn imported_names_by_kind_for_file(
760        &self,
761        file: &Path,
762        kind: DefKind,
763    ) -> Option<HashSet<String>> {
764        let file = normalize_path(file);
765        let module = self.modules.get(&file)?;
766        if module.has_unresolved_wildcard_import
767            || module.has_unresolved_selective_import
768            || module.has_unresolved_namespace_import
769        {
770            return None;
771        }
772
773        let mut names = HashSet::new();
774        for import in &module.imports {
775            // Namespace aliases are variables, not flattened member kinds.
776            if import.namespace_alias.is_some() {
777                continue;
778            }
779            let import_path = import.path.as_ref()?;
780            let imported_names: Vec<String> = match &import.selective_names {
781                Some(selective) => selective.iter().cloned().collect(),
782                None => self.exports_for_import(&file, import_path),
783            };
784            for name in imported_names {
785                if self.exported_kind_for_import(&file, import_path, &name) == Some(kind) {
786                    names.insert(name);
787                }
788            }
789        }
790        Some(names)
791    }
792
793    /// Collect imported declarations that can be invoked with ordinary call
794    /// syntax. This is the module graph's canonical callable projection for
795    /// compilers; it includes function-like declarations and struct
796    /// constructors while preserving import visibility and resolution.
797    pub fn imported_callable_names_for_file(&self, file: &Path) -> Option<HashSet<String>> {
798        let mut names = HashSet::new();
799        for kind in [
800            DefKind::Function,
801            DefKind::Pipeline,
802            DefKind::Tool,
803            DefKind::Struct,
804        ] {
805            names.extend(self.imported_names_by_kind_for_file(file, kind)?);
806        }
807        Some(names)
808    }
809
810    /// Collect type / struct / enum / interface declarations made visible to
811    /// `file` by its imports. Returns `None` when any import is unresolved so
812    /// callers can fall back to conservative behavior.
813    pub fn imported_type_declarations_for_file(&self, file: &Path) -> Option<Vec<SNode>> {
814        let file = normalize_path(file);
815        let module = self.modules.get(&file)?;
816        if module.has_unresolved_wildcard_import
817            || module.has_unresolved_selective_import
818            || module.has_unresolved_namespace_import
819        {
820            return None;
821        }
822
823        let mut decls = Vec::new();
824        let mut seen = HashSet::new();
825        for import in &module.imports {
826            // Namespace imports do not flatten type names into the caller.
827            if import.namespace_alias.is_some() {
828                continue;
829            }
830            let import_path = import.path.as_ref()?;
831            let imported = self
832                .modules
833                .get(import_path)
834                .or_else(|| self.modules.get(&normalize_path(import_path)))?;
835            // The target parsed nothing (lex/parse failure). Fall back to the
836            // conservative `None` answer so the cross-module undefined-name
837            // check stays silent — the real error is surfaced separately by
838            // `import_compile_failures`, not mislabeled as an undefined symbol
839            // at this consumer's call site.
840            if imported.load_error.is_some() {
841                return None;
842            }
843            let mut names_to_collect: Vec<String> = match &import.selective_names {
844                None => imported.exports.iter().cloned().collect(),
845                Some(selective) => selective.iter().cloned().collect(),
846            };
847            names_to_collect.sort();
848            for name in &names_to_collect {
849                let mut visited = HashSet::new();
850                if let Some(decl) = self.find_exported_type_decl(import_path, name, &mut visited) {
851                    let origin = self
852                        .export_definition_of(import_path, name)
853                        .map_or_else(|| import_path.clone(), |definition| definition.file);
854                    self.extend_type_dependency(&origin, &decl, &mut decls, &mut seen);
855                }
856            }
857            // Every type alias / struct / enum / interface declared in the
858            // imported module is visible to the *typechecker*, `pub` or not:
859            // an imported fn's signature may reference a module-private alias
860            // ("options: PickKeysOptions"), and without its definition the
861            // caller sees only a phantom `Named(...)` and skips contract
862            // checks. This visibility is typing-only — name-level import
863            // privacy is still enforced by `selective_import_issues`
864            // and the runtime loader, which reject importing a non-`pub`
865            // type by name.
866            for ty_decl in &imported.type_declarations {
867                if type_decl_name(ty_decl).is_some() {
868                    self.extend_type_dependency(import_path, ty_decl, &mut decls, &mut seen);
869                }
870            }
871
872            for name in &names_to_collect {
873                let mut visited = HashSet::new();
874                let Some(callable) =
875                    self.find_exported_callable_decl(import_path, name, &mut visited)
876                else {
877                    continue;
878                };
879                let origin = self
880                    .export_definition_of(import_path, name)
881                    .map_or_else(|| import_path.clone(), |definition| definition.file);
882                self.extend_callable_type_dependencies(&origin, &callable, &mut decls, &mut seen);
883            }
884        }
885        Some(decls)
886    }
887
888    /// Collect imported callable signatures; bodies stay in their defining modules.
889    pub fn imported_callable_declarations_for_file(&self, file: &Path) -> Option<Vec<SNode>> {
890        let file = normalize_path(file);
891        let module = self.modules.get(&file)?;
892        if module.has_unresolved_wildcard_import
893            || module.has_unresolved_selective_import
894            || module.has_unresolved_namespace_import
895        {
896            return None;
897        }
898
899        let mut decls = Vec::new();
900        for import in &module.imports {
901            // Namespace imports keep callables under the alias object.
902            if import.namespace_alias.is_some() {
903                continue;
904            }
905            let import_path = import.path.as_ref()?;
906            let imported = self
907                .modules
908                .get(import_path)
909                .or_else(|| self.modules.get(&normalize_path(import_path)))?;
910            // The target parsed nothing (lex/parse failure). Fall back to the
911            // conservative `None` answer so the cross-module undefined-name
912            // check stays silent — the real error is surfaced separately by
913            // `import_compile_failures`, not mislabeled as an undefined symbol
914            // at this consumer's call site.
915            if imported.load_error.is_some() {
916                return None;
917            }
918            let selective_import = import.selective_names.is_some();
919            let names_to_collect: Vec<String> = match &import.selective_names {
920                None => self.exports_for_import(&file, import_path),
921                Some(selective) => selective.iter().cloned().collect(),
922            };
923            for name in &names_to_collect {
924                if selective_import
925                    || imported.own_exports.contains(name)
926                    || (sibling_module_access(&file, import_path)
927                        && imported.sibling_exports.contains(name))
928                {
929                    if let Some(decl) = imported
930                        .callable_declarations
931                        .iter()
932                        .find(|decl| callable_decl_name(decl) == Some(name.as_str()))
933                    {
934                        decls.push(decl.clone());
935                        continue;
936                    }
937                }
938                let mut visited = HashSet::new();
939                if let Some(decl) =
940                    self.find_exported_callable_decl(import_path, name, &mut visited)
941                {
942                    decls.push(decl);
943                }
944            }
945        }
946        Some(decls)
947    }
948
949    /// Walk a module's local type declarations and re-export chains to find
950    /// the SNode for an exported type/struct/enum/interface named `name`.
951    fn find_exported_type_decl(
952        &self,
953        path: &Path,
954        name: &str,
955        visited: &mut HashSet<PathBuf>,
956    ) -> Option<SNode> {
957        let canonical = normalize_path(path);
958        if !visited.insert(canonical.clone()) {
959            return None;
960        }
961        let module = self
962            .modules
963            .get(&canonical)
964            .or_else(|| self.modules.get(path))?;
965        for decl in &module.type_declarations {
966            if type_decl_name(decl) == Some(name) && module.own_exports.contains(name) {
967                return Some(decl.clone());
968            }
969        }
970        if let Some(sources) = module.selective_re_exports.get(name) {
971            for source in sources {
972                if let Some(decl) = self.find_exported_type_decl(source, name, visited) {
973                    return Some(decl);
974                }
975            }
976        }
977        for source in &module.wildcard_re_export_paths {
978            if let Some(decl) = self.find_exported_type_decl(source, name, visited) {
979                return Some(decl);
980            }
981        }
982        None
983    }
984
985    fn find_exported_callable_decl(
986        &self,
987        path: &Path,
988        name: &str,
989        visited: &mut HashSet<PathBuf>,
990    ) -> Option<SNode> {
991        let canonical = normalize_path(path);
992        if !visited.insert(canonical.clone()) {
993            return None;
994        }
995        let module = self
996            .modules
997            .get(&canonical)
998            .or_else(|| self.modules.get(path))?;
999        for decl in &module.callable_declarations {
1000            if callable_decl_name(decl) == Some(name) && module.own_exports.contains(name) {
1001                return Some(decl.clone());
1002            }
1003        }
1004        if let Some(sources) = module.selective_re_exports.get(name) {
1005            for source in sources {
1006                if let Some(decl) = self.find_exported_callable_decl(source, name, visited) {
1007                    return Some(decl);
1008                }
1009            }
1010        }
1011        for source in &module.wildcard_re_export_paths {
1012            if let Some(decl) = self.find_exported_callable_decl(source, name, visited) {
1013                return Some(decl);
1014            }
1015        }
1016        None
1017    }
1018
1019    /// Find the definition of `name` visible from `file`.
1020    ///
1021    /// Recurses through `pub import` re-export chains so go-to-definition
1022    /// lands on the symbol's actual declaration site instead of the facade
1023    /// module that forwarded it.
1024    pub fn definition_of(&self, file: &Path, name: &str) -> Option<DefSite> {
1025        let mut visited = HashSet::new();
1026        self.definition_of_inner(file, name, &mut visited)
1027    }
1028
1029    /// Find the declaration that contributes exported `name` to `file`.
1030    ///
1031    /// Unlike [`Self::definition_of`], this ignores private local declarations
1032    /// and private imports. It follows only the module's public declaration and
1033    /// `pub import` graph, making it suitable for package manifests, API docs,
1034    /// and other consumers of a module's externally visible surface.
1035    pub fn export_definition_of(&self, file: &Path, name: &str) -> Option<DefSite> {
1036        let mut visited = HashSet::new();
1037        self.export_definition_of_inner(file, name, &mut visited)
1038    }
1039
1040    /// Sorted names of every declaration recorded for `file` (functions,
1041    /// pipelines, tools, structs, ...). Used by the check-result cache to
1042    /// key the cross-file lint-exemption subset that applies to this file.
1043    pub fn declared_names_for_file(&self, file: &Path) -> Option<Vec<&str>> {
1044        let module = self.modules.get(&normalize_path(file))?;
1045        let mut names: Vec<&str> = module.declarations.keys().map(String::as_str).collect();
1046        names.sort_unstable();
1047        Some(names)
1048    }
1049
1050    fn definition_of_inner(
1051        &self,
1052        file: &Path,
1053        name: &str,
1054        visited: &mut HashSet<PathBuf>,
1055    ) -> Option<DefSite> {
1056        let file = normalize_path(file);
1057        if !visited.insert(file.clone()) {
1058            return None;
1059        }
1060        let current = self.modules.get(&file)?;
1061
1062        if let Some(local) = current.declarations.get(name) {
1063            return Some(local.clone());
1064        }
1065
1066        // `pub import { name } from "..."` — follow the first recorded
1067        // source. Conflicting re-exports surface separately as
1068        // diagnostics; here we just pick a canonical destination so
1069        // go-to-definition lands somewhere useful.
1070        if let Some(sources) = current.selective_re_exports.get(name) {
1071            for source in sources {
1072                if let Some(def) = self.definition_of_inner(source, name, visited) {
1073                    return Some(def);
1074                }
1075            }
1076        }
1077
1078        // `pub import "..."` — chase each wildcard re-export source.
1079        for source in &current.wildcard_re_export_paths {
1080            if let Some(def) = self.definition_of_inner(source, name, visited) {
1081                return Some(def);
1082            }
1083        }
1084
1085        // Private selective imports.
1086        for import in &current.imports {
1087            let Some(selective_names) = &import.selective_names else {
1088                continue;
1089            };
1090            if !selective_names.contains(name) {
1091                continue;
1092            }
1093            if let Some(path) = &import.path {
1094                if let Some(def) = self.definition_of_inner(path, name, visited) {
1095                    return Some(def);
1096                }
1097            }
1098        }
1099
1100        // Private wildcard imports (not namespace — those bind only the alias).
1101        for import in &current.imports {
1102            if import.selective_names.is_some() || import.namespace_alias.is_some() {
1103                continue;
1104            }
1105            if let Some(path) = &import.path {
1106                if let Some(def) = self.definition_of_inner(path, name, visited) {
1107                    return Some(def);
1108                }
1109            }
1110        }
1111
1112        None
1113    }
1114
1115    fn export_definition_of_inner(
1116        &self,
1117        file: &Path,
1118        name: &str,
1119        visited: &mut HashSet<PathBuf>,
1120    ) -> Option<DefSite> {
1121        let file = normalize_path(file);
1122        if !visited.insert(file.clone()) {
1123            return None;
1124        }
1125        let current = self.modules.get(&file)?;
1126
1127        if current.own_exports.contains(name) {
1128            if let Some(local) = current.declarations.get(name) {
1129                return Some(local.clone());
1130            }
1131        }
1132        if let Some(sources) = current.selective_re_exports.get(name) {
1133            for source in sources {
1134                if let Some(definition) = self.export_definition_of_inner(source, name, visited) {
1135                    return Some(definition);
1136                }
1137            }
1138        }
1139        for source in &current.wildcard_re_export_paths {
1140            if let Some(definition) = self.export_definition_of_inner(source, name, visited) {
1141                return Some(definition);
1142            }
1143        }
1144        None
1145    }
1146
1147    /// Diagnostics for re-export conflicts inside `file`. Each diagnostic
1148    /// names the conflicting symbol and the modules that contributed it,
1149    /// so check-time errors can be precise.
1150    pub fn re_export_conflicts(&self, file: &Path) -> Vec<ReExportConflict> {
1151        let file = normalize_path(file);
1152        let Some(module) = self.modules.get(&file) else {
1153            return Vec::new();
1154        };
1155
1156        // Build, for each re-exported name, the set of source modules it
1157        // could resolve to. Names that resolve to more than one source are
1158        // ambiguous and reported.
1159        let mut sources: HashMap<String, Vec<PathBuf>> = HashMap::new();
1160
1161        for (name, srcs) in &module.selective_re_exports {
1162            sources
1163                .entry(name.clone())
1164                .or_default()
1165                .extend(srcs.iter().cloned());
1166        }
1167        for src in &module.wildcard_re_export_paths {
1168            let canonical = normalize_path(src);
1169            let Some(src_module) = self
1170                .modules
1171                .get(&canonical)
1172                .or_else(|| self.modules.get(src))
1173            else {
1174                continue;
1175            };
1176            for name in &src_module.exports {
1177                sources
1178                    .entry(name.clone())
1179                    .or_default()
1180                    .push(canonical.clone());
1181            }
1182        }
1183
1184        // A re-export that collides with a locally exported declaration is
1185        // also an error: the facade module cannot expose two different
1186        // bindings under the same name.
1187        for name in &module.own_exports {
1188            if let Some(entry) = sources.get_mut(name) {
1189                entry.push(file.clone());
1190            }
1191        }
1192
1193        let mut conflicts = Vec::new();
1194        for (name, mut srcs) in sources {
1195            srcs.sort();
1196            srcs.dedup();
1197            if srcs.len() > 1 {
1198                conflicts.push(ReExportConflict {
1199                    name,
1200                    sources: srcs,
1201                });
1202            }
1203        }
1204        conflicts.sort_by(|a, b| a.name.cmp(&b.name));
1205        conflicts
1206    }
1207
1208    /// Invalid selective imports in `file`, classified as missing or private.
1209    ///
1210    /// This is the static single source of truth for the runtime's export
1211    /// boundary. Consumers project the typed issue into CLI or editor
1212    /// diagnostics without independently re-resolving names or spans.
1213    pub fn selective_import_issues(&self, file: &Path) -> Vec<SelectiveImportIssue> {
1214        let file = normalize_path(file);
1215        let Some(module) = self.modules.get(&file) else {
1216            return Vec::new();
1217        };
1218
1219        let mut out = Vec::new();
1220        for import in &module.imports {
1221            let Some(selective) = &import.selective_names else {
1222                continue;
1223            };
1224            let Some(import_path) = &import.path else {
1225                continue;
1226            };
1227            let Some(target) = self
1228                .modules
1229                .get(import_path)
1230                .or_else(|| self.modules.get(&normalize_path(import_path)))
1231            else {
1232                continue;
1233            };
1234            if target.load_error.is_some() {
1235                continue;
1236            }
1237            let visible: HashSet<_> = self
1238                .exports_for_import(&file, import_path)
1239                .into_iter()
1240                .collect();
1241            for name in selective {
1242                let can_bind = visible.contains(name);
1243                let can_publish = !import.is_pub || target.exports.contains(name);
1244                let kind = if can_bind && can_publish {
1245                    continue;
1246                } else if target.declarations.contains_key(name) {
1247                    SelectiveImportIssueKind::Private
1248                } else {
1249                    SelectiveImportIssueKind::Missing
1250                };
1251                out.push(SelectiveImportIssue {
1252                    name: name.clone(),
1253                    module: import.raw_path.clone(),
1254                    span: import.import_span,
1255                    kind,
1256                });
1257            }
1258        }
1259        out.sort_by(|a, b| (&a.name, &a.module, a.kind).cmp(&(&b.name, &b.module, b.kind)));
1260        out.dedup();
1261        out
1262    }
1263
1264    /// Return the declaration kind for a name on a module's public surface.
1265    /// Explicit and wildcard re-exports are followed so callers can consume
1266    /// the same source-owned contract regardless of the import path used.
1267    pub fn exported_kind(&self, file: &Path, name: &str) -> Option<DefKind> {
1268        self.exported_kind_inner(file, name, &mut HashSet::new())
1269    }
1270
1271    fn exported_kind_inner(
1272        &self,
1273        file: &Path,
1274        name: &str,
1275        visited: &mut HashSet<PathBuf>,
1276    ) -> Option<DefKind> {
1277        let file = normalize_path(file);
1278        if !visited.insert(file.clone()) {
1279            return None;
1280        }
1281        let result = self.modules.get(&file).and_then(|module| {
1282            if module.own_exports.contains(name) {
1283                return module
1284                    .declarations
1285                    .get(name)
1286                    .map(|definition| definition.kind)
1287                    .or_else(|| {
1288                        stdlib_module_name(&file).and_then(|stdlib_module| {
1289                            stdlib::builtin_reexports(stdlib_module)
1290                                .contains(&name)
1291                                .then_some(DefKind::Function)
1292                        })
1293                    });
1294            }
1295            if let Some(sources) = module.selective_re_exports.get(name) {
1296                for source in sources {
1297                    if let Some(kind) = self.exported_kind_inner(source, name, visited) {
1298                        return Some(kind);
1299                    }
1300                }
1301            }
1302            for source in &module.wildcard_re_export_paths {
1303                if let Some(kind) = self.exported_kind_inner(source, name, visited) {
1304                    return Some(kind);
1305                }
1306            }
1307            None
1308        });
1309        visited.remove(&file);
1310        result
1311    }
1312}
1313
1314/// A duplicate or ambiguous re-export inside a single module. Reported by
1315/// [`ModuleGraph::re_export_conflicts`].
1316#[derive(Debug, Clone, PartialEq, Eq)]
1317pub struct ReExportConflict {
1318    pub name: String,
1319    pub sources: Vec<PathBuf>,
1320}
1321
1322/// Why a selective import cannot cross the target module's export boundary.
1323#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1324pub enum SelectiveImportIssueKind {
1325    /// No declaration or transitive export has the requested name.
1326    Missing,
1327    /// The target declares the requested name without exporting it.
1328    Private,
1329}
1330
1331/// A selective import rejected by the target module's public surface.
1332#[derive(Debug, Clone, PartialEq, Eq)]
1333pub struct SelectiveImportIssue {
1334    /// The requested name.
1335    pub name: String,
1336    /// The module path exactly as written in the import statement.
1337    pub module: String,
1338    /// Span anchored to the selective import statement.
1339    pub span: Span,
1340    /// Whether the requested name is absent or private.
1341    pub kind: SelectiveImportIssueKind,
1342}
1343
1344impl SelectiveImportIssue {
1345    /// Stable user-facing explanation shared by CLI and editor projections.
1346    #[must_use]
1347    pub fn message(&self) -> String {
1348        match self.kind {
1349            SelectiveImportIssueKind::Missing => format!(
1350                "imported symbol `{}` does not exist in `{}`",
1351                self.name, self.module
1352            ),
1353            SelectiveImportIssueKind::Private => format!(
1354                "imported symbol `{}` is not exported by `{}` — it is defined there but not `pub`",
1355                self.name, self.module
1356            ),
1357        }
1358    }
1359
1360    /// Stable repair guidance shared by CLI and editor projections.
1361    #[must_use]
1362    pub fn help(&self) -> String {
1363        match self.kind {
1364            SelectiveImportIssueKind::Missing => format!(
1365                "update the import to a symbol exported by `{}`",
1366                self.module
1367            ),
1368            SelectiveImportIssueKind::Private => {
1369                format!(
1370                    "mark `{}` as `pub` in `{}` to export it",
1371                    self.name, self.module
1372                )
1373            }
1374        }
1375    }
1376}
1377
1378fn load_module(
1379    path: &Path,
1380    package_snapshots: &[PackageSnapshot],
1381    source_overrides: Option<&HashMap<PathBuf, String>>,
1382    retain_parsed_source: bool,
1383) -> (ModuleInfo, Option<ParsedModuleSource>) {
1384    let source = source_overrides
1385        .and_then(|overrides| overrides.get(&normalize_path(path)).cloned())
1386        .or_else(|| read_module_source(path));
1387    let Some(source) = source else {
1388        return (ModuleInfo::default(), None);
1389    };
1390    let mut lexer = harn_lexer::Lexer::new(&source);
1391    let tokens = match lexer.tokenize() {
1392        Ok(tokens) => tokens,
1393        Err(error) => {
1394            let module = ModuleInfo {
1395                load_error: Some(ModuleLoadError {
1396                    message: error.to_string(),
1397                    span: error.span(),
1398                }),
1399                ..ModuleInfo::default()
1400            };
1401            return (module, None);
1402        }
1403    };
1404    let mut parser = Parser::new(tokens);
1405    let program = match parser.parse() {
1406        Ok(program) => program,
1407        Err(error) => {
1408            let module = ModuleInfo {
1409                load_error: Some(ModuleLoadError {
1410                    message: error.to_string(),
1411                    span: error.span(),
1412                }),
1413                ..ModuleInfo::default()
1414            };
1415            return (module, None);
1416        }
1417    };
1418
1419    let mut module = ModuleInfo::default();
1420    for node in &program {
1421        collect_module_info(path, node, &mut module, package_snapshots);
1422        collect_type_declarations(node, &mut module.type_declarations);
1423        collect_callable_declarations(node, &mut module.callable_declarations);
1424    }
1425    if let Some(stdlib_module) = stdlib_module_name(path) {
1426        module.own_exports.extend(
1427            stdlib::builtin_reexports(stdlib_module)
1428                .iter()
1429                .map(|name| (*name).to_string()),
1430        );
1431    }
1432    // Seed the transitive `exports` set from local exports plus selective
1433    // re-export names. Wildcard re-exports are folded in by
1434    // [`resolve_re_exports`] after every module has been loaded.
1435    module.exports.extend(module.own_exports.iter().cloned());
1436    module
1437        .exports
1438        .extend(module.selective_re_exports.keys().cloned());
1439    let parsed = retain_parsed_source.then_some(ParsedModuleSource { source, program });
1440    (module, parsed)
1441}
1442
1443/// Extract the stdlib module name when `path` is a `<std>/<name>`
1444/// virtual path, otherwise `None`.
1445pub fn stdlib_module_name(path: &Path) -> Option<&str> {
1446    let s = path.to_str()?;
1447    s.strip_prefix("<std>/")
1448}
1449
1450fn normalize_path(path: &Path) -> PathBuf {
1451    canonical_path(path)
1452}
1453
1454/// Canonicalize `path`, memoized process-wide.
1455///
1456/// Module-graph construction and every per-file graph query canonicalize
1457/// paths to dedupe import-edge spellings, and the check preflight scan
1458/// canonicalizes each visited module per checked file. `Path::canonicalize`
1459/// resolves every component through the kernel, so a whole-tree `harn check`
1460/// used to spend the bulk of its wall clock in path-resolution syscalls
1461/// (`getattrlist` dominated system time). One positive-result memo removes
1462/// the `O(files x import closure)` repetition; failed canonicalizations are
1463/// not memoized (mirroring the bytecode cache's `canonicalize_cached`) so a
1464/// file that appears later still resolves correctly in long-lived processes.
1465/// `<std>/` virtual paths pass through untouched.
1466pub fn canonical_path(path: &Path) -> PathBuf {
1467    use std::sync::OnceLock;
1468    if stdlib_module_name(path).is_some() {
1469        return path.to_path_buf();
1470    }
1471    static MEMO: OnceLock<std::sync::Mutex<HashMap<PathBuf, PathBuf>>> = OnceLock::new();
1472    let memo = MEMO.get_or_init(|| std::sync::Mutex::new(HashMap::new()));
1473    if let Some(hit) = memo
1474        .lock()
1475        .expect("canonical path memo lock poisoned")
1476        .get(path)
1477        .cloned()
1478    {
1479        return hit;
1480    }
1481    match path.canonicalize() {
1482        Ok(canonical) => {
1483            memo.lock()
1484                .expect("canonical path memo lock poisoned")
1485                .insert(path.to_path_buf(), canonical.clone());
1486            canonical
1487        }
1488        // A prepared generation may outlive its source tree, so preserve its
1489        // lexical identity when the kernel can no longer resolve the path.
1490        Err(_) => manifest_walk::normalize_lexically(path),
1491    }
1492}
1493
1494#[cfg(test)]
1495#[path = "tests.rs"]
1496mod tests;