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