Skip to main content

harn_modules/
lib.rs

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