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
9pub 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#[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#[derive(Debug, Clone, PartialEq)]
80pub struct LocatedTypeDeclaration {
81 pub file: PathBuf,
82 pub declaration: SNode,
83}
84
85#[derive(Debug, Clone)]
87pub enum WildcardResolution {
88 Resolved(HashSet<String>),
90 Unknown,
92}
93
94#[derive(Debug, Default)]
96pub struct ModuleGraph {
97 modules: HashMap<PathBuf, Arc<ModuleInfo>>,
98 _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 declarations: HashMap<String, DefSite>,
119 exports: HashSet<String>,
124 own_exports: HashSet<String>,
127 sibling_exports: HashSet<String>,
130 selective_re_exports: HashMap<String, Vec<PathBuf>>,
137 wildcard_re_export_paths: Vec<PathBuf>,
141 namespace_re_exports: HashMap<String, PathBuf>,
148 selective_import_names: HashSet<String>,
150 imports: Vec<ImportRef>,
152 has_unresolved_wildcard_import: bool,
154 has_unresolved_selective_import: bool,
158 has_unresolved_namespace_import: bool,
160 type_declarations: Vec<SNode>,
163 callable_declarations: Vec<SNode>,
166 load_error: Option<ModuleLoadError>,
172}
173
174#[derive(Debug, Clone)]
180pub struct ModuleLoadError {
181 pub message: String,
183 pub span: Span,
185}
186
187#[derive(Debug, Clone)]
190pub struct ImportCompileFailure {
191 pub import_raw_path: String,
193 pub import_span: Span,
195 pub module_path: PathBuf,
197 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 namespace_alias: Option<String>,
209 is_pub: bool,
210 import_span: Span,
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct ModuleImport {
216 pub raw_path: String,
218 pub resolved_path: Option<PathBuf>,
220 pub selective_names: Option<Vec<String>>,
222 pub namespace_alias: Option<String>,
224 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 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 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
333fn 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 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 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 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 pub fn contains_module(&self, path: &Path) -> bool {
389 self.modules.contains_key(path) || self.modules.contains_key(&normalize_path(path))
390 }
391
392 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 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 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(¤t) {
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 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 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 #[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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 for source in ¤t.wildcard_re_export_paths {
967 if let Some(def) = self.definition_of_inner(source, name, visited) {
968 return Some(def);
969 }
970 }
971
972 for import in ¤t.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 for import in ¤t.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 ¤t.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 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 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 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 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 pub fn exported_kind(&self, file: &Path, name: &str) -> Option<DefKind> {
1155 let file = normalize_path(file);
1156 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
1199fn 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
1214const CALLABLE_KINDS: [DefKind; 4] = [
1216 DefKind::Function,
1217 DefKind::Pipeline,
1218 DefKind::Tool,
1219 DefKind::Struct,
1220];
1221
1222pub 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#[derive(Debug, Clone, PartialEq, Eq)]
1235pub struct ReExportConflict {
1236 pub name: String,
1237 pub sources: Vec<PathBuf>,
1238}
1239
1240#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1242pub enum SelectiveImportIssueKind {
1243 Missing,
1245 Private,
1247}
1248
1249#[derive(Debug, Clone, PartialEq, Eq)]
1251pub struct SelectiveImportIssue {
1252 pub name: String,
1254 pub module: String,
1256 pub span: Span,
1258 pub kind: SelectiveImportIssueKind,
1260}
1261
1262impl SelectiveImportIssue {
1263 #[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 #[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
1296pub 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
1307pub 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 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 Err(_) => manifest_walk::normalize_lexically(path),
1346 }
1347}
1348
1349#[cfg(test)]
1350#[path = "tests.rs"]
1351mod tests;