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_reads;
29pub use source_reads::{
30 build_with_source, build_with_sources, module_source_disk_reads, read_module_source,
31};
32mod references;
33mod standalone;
34mod stdlib;
35pub use stdlib::{ensure_stdlib_installed, stdlib_catalog, try_stdlib_catalog};
36mod symbol_reachability;
37mod type_dependencies;
38mod typecheck;
39mod visibility;
40mod wave_load;
41use wave_load::load_wave;
42pub use wave_load::MODULE_GRAPH_JOBS_ENV;
43
44pub use construction::{
45 build, build_closed_program, build_for_reference_index, build_with_module_projection,
46 build_with_parsed_sources,
47};
48
49use declarations::{callable_decl_name, decl_site, type_decl_name};
50pub use declarations::{public_declarations, sibling_declarations, DefKind, PublicDeclaration};
51pub use namespace_imports::NamespaceImportInfo;
52pub use namespace_signatures::NamespaceMemberSignature;
53pub use package_imports::{
54 resolve_import_path, resolve_import_path_with_guard, resolve_import_path_with_snapshot,
55 unresolved_package_alias, PackageImport,
56};
57pub use references::{
58 file_reference_edges, index_references, RefSite, ReferenceEdge, ReferenceIndex,
59};
60pub use standalone::build_with_standalone_source;
61use standalone::PackageContext;
62pub use symbol_reachability::{
63 closed_program_reachability, ExportDemand, ModuleSymbolDemand, SymbolReachability,
64};
65pub use visibility::{sibling_directory_access, sibling_module_access};
66
67#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct DefSite {
70 pub name: String,
71 pub file: PathBuf,
72 pub kind: DefKind,
73 pub span: Span,
74}
75
76#[derive(Debug, Clone)]
78pub enum WildcardResolution {
79 Resolved(HashSet<String>),
81 Unknown,
83}
84
85#[derive(Debug, Default)]
87pub struct ModuleGraph {
88 modules: HashMap<PathBuf, Arc<ModuleInfo>>,
89 _package_snapshots: Vec<PackageSnapshot>,
91}
92
93#[derive(Debug, Clone)]
94pub struct ParsedModuleSource {
95 pub source: String,
96 pub program: Vec<SNode>,
97}
98
99#[derive(Debug, Default)]
100pub struct ModuleGraphBuild {
101 pub graph: ModuleGraph,
102 pub parsed_sources: HashMap<PathBuf, ParsedModuleSource>,
103}
104
105#[derive(Debug, Default, Clone)]
106struct ModuleInfo {
107 declarations: HashMap<String, DefSite>,
110 exports: HashSet<String>,
115 own_exports: HashSet<String>,
118 sibling_exports: HashSet<String>,
121 selective_re_exports: HashMap<String, Vec<PathBuf>>,
128 wildcard_re_export_paths: Vec<PathBuf>,
132 namespace_re_exports: HashMap<String, PathBuf>,
139 selective_import_names: HashSet<String>,
141 imports: Vec<ImportRef>,
143 has_unresolved_wildcard_import: bool,
145 has_unresolved_selective_import: bool,
149 has_unresolved_namespace_import: bool,
151 type_declarations: Vec<SNode>,
154 callable_declarations: Vec<SNode>,
157 load_error: Option<ModuleLoadError>,
163}
164
165#[derive(Debug, Clone)]
171pub struct ModuleLoadError {
172 pub message: String,
174 pub span: Span,
176}
177
178#[derive(Debug, Clone)]
181pub struct ImportCompileFailure {
182 pub import_raw_path: String,
184 pub import_span: Span,
186 pub module_path: PathBuf,
188 pub error: ModuleLoadError,
190}
191
192#[derive(Debug, Clone)]
193struct ImportRef {
194 raw_path: String,
195 path: Option<PathBuf>,
196 selective_names: Option<HashSet<String>>,
197 namespace_alias: Option<String>,
200 is_pub: bool,
201 import_span: Span,
202}
203
204#[derive(Debug, Clone, PartialEq, Eq)]
206pub struct ModuleImport {
207 pub raw_path: String,
209 pub resolved_path: Option<PathBuf>,
211 pub selective_names: Option<Vec<String>>,
213 pub namespace_alias: Option<String>,
215 pub is_pub: bool,
217}
218
219type ModuleObserver<'a> = dyn Fn(&Path, &str, Option<&[SNode]>) + Sync + 'a;
220
221#[derive(Clone, Copy)]
222enum ParsedSourceRetention<'a> {
223 None,
224 Seeds(&'a HashSet<PathBuf>),
225 All,
226}
227
228impl ParsedSourceRetention<'_> {
229 fn retains(self, path: &Path) -> bool {
230 match self {
231 Self::None => false,
232 Self::Seeds(targets) => targets.contains(path),
233 Self::All => true,
234 }
235 }
236}
237
238fn build_inner(
239 files: &[PathBuf],
240 parsed_source_retention: ParsedSourceRetention<'_>,
241 source_overrides: Option<&HashMap<PathBuf, String>>,
242 package_context: PackageContext,
243 observer: Option<&ModuleObserver<'_>>,
244) -> ModuleGraphBuild {
245 let package_snapshots = match package_context {
246 PackageContext::Project => acquire_package_snapshots(files),
247 PackageContext::Standalone => Vec::new(),
248 };
249 let mut modules: HashMap<PathBuf, Arc<ModuleInfo>> = HashMap::new();
250 let mut parsed_sources: HashMap<PathBuf, ParsedModuleSource> = HashMap::new();
251 let mut seen: HashSet<PathBuf> = HashSet::new();
252 let mut wave: Vec<PathBuf> = Vec::new();
253 for file in files {
254 let canonical = normalize_path(file);
255 if seen.insert(canonical.clone()) {
256 wave.push(canonical);
257 }
258 }
259 while !wave.is_empty() {
267 let loaded = load_wave(
268 &wave,
269 &package_snapshots,
270 parsed_source_retention,
271 source_overrides,
272 observer,
273 );
274 let mut next_wave: Vec<PathBuf> = Vec::new();
275 for (path, (module, parsed)) in wave.drain(..).zip(loaded) {
276 if parsed_source_retention.retains(&path) {
277 if let Some(parsed) = parsed {
278 parsed_sources.insert(path.clone(), parsed);
279 }
280 }
281 for import in &module.imports {
298 if let Some(import_path) = &import.path {
299 let canonical = normalize_path(import_path);
300 if seen.insert(canonical.clone()) {
301 next_wave.push(canonical);
302 }
303 }
304 }
305 modules.insert(path, module);
306 }
307 wave = next_wave;
308 }
309 resolve_re_exports(&mut modules);
310 ModuleGraphBuild {
311 graph: ModuleGraph {
312 modules,
313 _package_snapshots: package_snapshots,
314 },
315 parsed_sources,
316 }
317}
318
319fn resolve_re_exports(modules: &mut HashMap<PathBuf, Arc<ModuleInfo>>) {
324 let keys: Vec<PathBuf> = modules.keys().cloned().collect();
325 loop {
326 let mut changed = false;
327 for path in &keys {
328 let wildcard_paths = modules
331 .get(path)
332 .map(|m| m.wildcard_re_export_paths.clone())
333 .unwrap_or_default();
334 if wildcard_paths.is_empty() {
335 continue;
336 }
337 let mut additions: Vec<String> = Vec::new();
338 for src in &wildcard_paths {
339 let src_canonical = normalize_path(src);
340 if let Some(src_module) = modules.get(src).or_else(|| modules.get(&src_canonical)) {
341 additions.extend(src_module.exports.iter().cloned());
342 }
343 }
344 let Some(module) = modules.get_mut(path) else {
347 continue;
348 };
349 additions.retain(|name| !module.exports.contains(name));
350 if !additions.is_empty() {
351 Arc::make_mut(module).exports.extend(additions);
352 changed = true;
353 }
354 }
355 if !changed {
356 break;
357 }
358 }
359}
360
361impl ModuleGraph {
362 pub fn module_paths(&self) -> Vec<PathBuf> {
367 let mut paths: Vec<PathBuf> = self.modules.keys().cloned().collect();
368 paths.sort();
369 paths
370 }
371
372 pub fn contains_module(&self, path: &Path) -> bool {
375 self.modules.contains_key(path) || self.modules.contains_key(&normalize_path(path))
376 }
377
378 pub fn all_selective_import_names(&self) -> HashSet<&str> {
380 let mut names = HashSet::new();
381 for module in self.modules.values() {
382 for name in &module.selective_import_names {
383 names.insert(name.as_str());
384 }
385 }
386 names
387 }
388
389 pub fn importers_of(&self, target: &Path) -> Vec<PathBuf> {
392 let target = normalize_path(target);
393 let mut out: Vec<PathBuf> = self
394 .modules
395 .iter()
396 .filter(|(_, info)| {
397 info.imports.iter().any(|import| {
398 import
399 .path
400 .as_ref()
401 .is_some_and(|p| normalize_path(p) == target)
402 })
403 })
404 .map(|(path, _)| path.clone())
405 .collect();
406 out.sort();
407 out
408 }
409
410 pub fn transitive_importers_of(&self, target: &Path) -> Vec<PathBuf> {
417 let target = normalize_path(target);
418 let mut visited = HashSet::from([target.clone()]);
419 let mut pending = vec![target];
420 let mut out = Vec::new();
421
422 while let Some(current) = pending.pop() {
423 for importer in self.importers_of(¤t) {
424 let importer = normalize_path(&importer);
425 if visited.insert(importer.clone()) {
426 pending.push(importer.clone());
427 out.push(importer);
428 }
429 }
430 }
431
432 out.sort();
433 out
434 }
435
436 pub fn imports_for_module(&self, file: &Path) -> Vec<ModuleImport> {
438 let file = normalize_path(file);
439 let Some(module) = self.modules.get(&file) else {
440 return Vec::new();
441 };
442 let mut imports: Vec<ModuleImport> = module
443 .imports
444 .iter()
445 .map(|import| {
446 let mut selective_names = import
447 .selective_names
448 .as_ref()
449 .map(|names| names.iter().cloned().collect::<Vec<_>>());
450 if let Some(names) = selective_names.as_mut() {
451 names.sort();
452 }
453 ModuleImport {
454 raw_path: import.raw_path.clone(),
455 resolved_path: import.path.as_ref().map(|path| normalize_path(path)),
456 selective_names,
457 namespace_alias: import.namespace_alias.clone(),
458 is_pub: import.is_pub,
459 }
460 })
461 .collect();
462 imports.sort_by(|left, right| {
463 left.raw_path
464 .cmp(&right.raw_path)
465 .then_with(|| left.selective_names.cmp(&right.selective_names))
466 .then_with(|| left.namespace_alias.cmp(&right.namespace_alias))
467 .then_with(|| left.resolved_path.cmp(&right.resolved_path))
468 });
469 imports
470 }
471
472 pub fn wildcard_exports_for(&self, file: &Path) -> WildcardResolution {
477 let file = normalize_path(file);
478 let Some(module) = self.modules.get(&file) else {
479 return WildcardResolution::Unknown;
480 };
481 if module.has_unresolved_wildcard_import {
482 return WildcardResolution::Unknown;
483 }
484
485 let mut names = HashSet::new();
486 for import in module
487 .imports
488 .iter()
489 .filter(|import| import.selective_names.is_none())
490 {
491 let Some(import_path) = &import.path else {
492 return WildcardResolution::Unknown;
493 };
494 let imported = self.modules.get(import_path).or_else(|| {
495 let normalized = normalize_path(import_path);
496 self.modules.get(&normalized)
497 });
498 let Some(_imported) = imported else {
499 return WildcardResolution::Unknown;
500 };
501 names.extend(self.exports_for_import(&file, import_path));
502 }
503 WildcardResolution::Resolved(names)
504 }
505
506 #[must_use]
527 pub fn import_compile_failures(&self, file: &Path) -> Vec<ImportCompileFailure> {
528 let file = normalize_path(file);
529 let Some(module) = self.modules.get(&file) else {
530 return Vec::new();
531 };
532 let mut failures = Vec::new();
533 for import in &module.imports {
534 let Some(import_path) = &import.path else {
535 continue;
536 };
537 let Some(target) = self
538 .modules
539 .get(import_path)
540 .or_else(|| self.modules.get(&normalize_path(import_path)))
541 else {
542 continue;
543 };
544 if let Some(error) = &target.load_error {
545 failures.push(ImportCompileFailure {
546 import_raw_path: import.raw_path.clone(),
547 import_span: import.import_span,
548 module_path: normalize_path(import_path),
549 error: error.clone(),
550 });
551 }
552 }
553 failures
554 }
555
556 pub fn imported_names_for_file(&self, file: &Path) -> Option<HashSet<String>> {
557 let file = normalize_path(file);
558 let module = self.modules.get(&file)?;
559 if module.has_unresolved_wildcard_import
560 || module.has_unresolved_selective_import
561 || module.has_unresolved_namespace_import
562 {
563 return None;
564 }
565
566 let mut names = HashSet::new();
567 for import in &module.imports {
568 if let Some(alias) = &import.namespace_alias {
570 names.insert(alias.clone());
571 continue;
572 }
573 let import_path = import.path.as_ref()?;
574 let imported = self
575 .modules
576 .get(import_path)
577 .or_else(|| self.modules.get(&normalize_path(import_path)))?;
578 if imported.load_error.is_some() {
584 return None;
585 }
586 match &import.selective_names {
587 None => {
588 names.extend(self.exports_for_import(&file, import_path));
589 }
590 Some(selective) => {
591 for name in selective {
600 if imported.declarations.contains_key(name)
601 || imported.exports.contains(name)
602 {
603 names.insert(name.clone());
604 }
605 }
606 }
607 }
608 }
609 Some(names)
610 }
611
612 pub fn imported_names_by_kind_for_file(
617 &self,
618 file: &Path,
619 kind: DefKind,
620 ) -> Option<HashSet<String>> {
621 let mut grouped = self.imported_names_grouped_by_kind(file)?;
622 Some(grouped.remove(&kind).unwrap_or_default())
623 }
624
625 pub fn imported_names_grouped_by_kind(
629 &self,
630 file: &Path,
631 ) -> Option<HashMap<DefKind, HashSet<String>>> {
632 let file = normalize_path(file);
633 let module = self.modules.get(&file)?;
634 if module.has_unresolved_wildcard_import
635 || module.has_unresolved_selective_import
636 || module.has_unresolved_namespace_import
637 {
638 return None;
639 }
640
641 let mut grouped: HashMap<DefKind, HashSet<String>> = HashMap::new();
642 for import in &module.imports {
643 if import.namespace_alias.is_some() {
645 continue;
646 }
647 let import_path = import.path.as_ref()?;
648 let target = normalize_path(import_path);
649 let sibling = sibling_module_access(&file, &target);
650 let imported_names: Vec<String> = match &import.selective_names {
651 Some(selective) => selective.iter().cloned().collect(),
652 None => self.exports_for_import(&file, import_path),
653 };
654 for name in imported_names {
655 if let Some(kind) = self.exported_kind_for_resolved_import(sibling, &target, &name)
656 {
657 grouped.entry(kind).or_default().insert(name);
658 }
659 }
660 }
661 Some(grouped)
662 }
663
664 pub fn imported_callable_names_for_file(&self, file: &Path) -> Option<HashSet<String>> {
669 let grouped = self.imported_names_grouped_by_kind(file)?;
670 Some(callable_names(&grouped))
671 }
672
673 pub fn imported_type_declarations_for_file(&self, file: &Path) -> Option<Vec<SNode>> {
677 let file = normalize_path(file);
678 let module = self.modules.get(&file)?;
679 if module.has_unresolved_wildcard_import
680 || module.has_unresolved_selective_import
681 || module.has_unresolved_namespace_import
682 {
683 return None;
684 }
685
686 let mut decls = Vec::new();
687 let mut seen = HashSet::new();
688 for import in &module.imports {
689 if import.namespace_alias.is_some() {
691 continue;
692 }
693 let import_path = import.path.as_ref()?;
694 let imported = self
695 .modules
696 .get(import_path)
697 .or_else(|| self.modules.get(&normalize_path(import_path)))?;
698 if imported.load_error.is_some() {
704 return None;
705 }
706 let mut names_to_collect: Vec<String> = match &import.selective_names {
707 None => imported.exports.iter().cloned().collect(),
708 Some(selective) => selective.iter().cloned().collect(),
709 };
710 names_to_collect.sort();
711 for name in &names_to_collect {
712 let mut visited = HashSet::new();
713 if let Some(decl) = self.find_exported_type_decl(import_path, name, &mut visited) {
714 let origin = self
715 .export_definition_of(import_path, name)
716 .map_or_else(|| import_path.clone(), |definition| definition.file);
717 self.extend_type_dependency(&origin, &decl, &mut decls, &mut seen);
718 }
719 }
720 for ty_decl in &imported.type_declarations {
730 if type_decl_name(ty_decl).is_some() {
731 self.extend_type_dependency(import_path, ty_decl, &mut decls, &mut seen);
732 }
733 }
734
735 for name in &names_to_collect {
736 let mut visited = HashSet::new();
737 let Some(callable) =
738 self.find_exported_callable_decl(import_path, name, &mut visited)
739 else {
740 continue;
741 };
742 let origin = self
743 .export_definition_of(import_path, name)
744 .map_or_else(|| import_path.clone(), |definition| definition.file);
745 self.extend_callable_type_dependencies(&origin, &callable, &mut decls, &mut seen);
746 }
747 }
748 Some(decls)
749 }
750
751 pub fn imported_callable_declarations_for_file(&self, file: &Path) -> Option<Vec<SNode>> {
753 let file = normalize_path(file);
754 let module = self.modules.get(&file)?;
755 if module.has_unresolved_wildcard_import
756 || module.has_unresolved_selective_import
757 || module.has_unresolved_namespace_import
758 {
759 return None;
760 }
761
762 let mut decls = Vec::new();
763 for import in &module.imports {
764 if import.namespace_alias.is_some() {
766 continue;
767 }
768 let import_path = import.path.as_ref()?;
769 let imported = self
770 .modules
771 .get(import_path)
772 .or_else(|| self.modules.get(&normalize_path(import_path)))?;
773 if imported.load_error.is_some() {
779 return None;
780 }
781 let selective_import = import.selective_names.is_some();
782 let names_to_collect: Vec<String> = match &import.selective_names {
783 None => self.exports_for_import(&file, import_path),
784 Some(selective) => selective.iter().cloned().collect(),
785 };
786 for name in &names_to_collect {
787 if selective_import
788 || imported.own_exports.contains(name)
789 || (sibling_module_access(&file, import_path)
790 && imported.sibling_exports.contains(name))
791 {
792 if let Some(decl) = imported
793 .callable_declarations
794 .iter()
795 .find(|decl| callable_decl_name(decl) == Some(name.as_str()))
796 {
797 decls.push(decl.clone());
798 continue;
799 }
800 }
801 let mut visited = HashSet::new();
802 if let Some(decl) =
803 self.find_exported_callable_decl(import_path, name, &mut visited)
804 {
805 decls.push(decl);
806 }
807 }
808 }
809 Some(decls)
810 }
811
812 fn find_exported_type_decl(
815 &self,
816 path: &Path,
817 name: &str,
818 visited: &mut HashSet<PathBuf>,
819 ) -> Option<SNode> {
820 let canonical = normalize_path(path);
821 if !visited.insert(canonical.clone()) {
822 return None;
823 }
824 let module = self
825 .modules
826 .get(&canonical)
827 .or_else(|| self.modules.get(path))?;
828 for decl in &module.type_declarations {
829 if type_decl_name(decl) == Some(name) && module.own_exports.contains(name) {
830 return Some(decl.clone());
831 }
832 }
833 if let Some(sources) = module.selective_re_exports.get(name) {
834 for source in sources {
835 if let Some(decl) = self.find_exported_type_decl(source, name, visited) {
836 return Some(decl);
837 }
838 }
839 }
840 for source in &module.wildcard_re_export_paths {
841 if let Some(decl) = self.find_exported_type_decl(source, name, visited) {
842 return Some(decl);
843 }
844 }
845 None
846 }
847
848 fn find_exported_callable_decl(
849 &self,
850 path: &Path,
851 name: &str,
852 visited: &mut HashSet<PathBuf>,
853 ) -> Option<SNode> {
854 let canonical = normalize_path(path);
855 if !visited.insert(canonical.clone()) {
856 return None;
857 }
858 let module = self
859 .modules
860 .get(&canonical)
861 .or_else(|| self.modules.get(path))?;
862 for decl in &module.callable_declarations {
863 if callable_decl_name(decl) == Some(name) && module.own_exports.contains(name) {
864 return Some(decl.clone());
865 }
866 }
867 if let Some(sources) = module.selective_re_exports.get(name) {
868 for source in sources {
869 if let Some(decl) = self.find_exported_callable_decl(source, name, visited) {
870 return Some(decl);
871 }
872 }
873 }
874 for source in &module.wildcard_re_export_paths {
875 if let Some(decl) = self.find_exported_callable_decl(source, name, visited) {
876 return Some(decl);
877 }
878 }
879 None
880 }
881
882 pub fn definition_of(&self, file: &Path, name: &str) -> Option<DefSite> {
888 let mut visited = HashSet::new();
889 self.definition_of_inner(file, name, &mut visited)
890 }
891
892 pub fn export_definition_of(&self, file: &Path, name: &str) -> Option<DefSite> {
899 let mut visited = HashSet::new();
900 self.export_definition_of_inner(file, name, &mut visited)
901 }
902
903 pub fn declared_names_for_file(&self, file: &Path) -> Option<Vec<&str>> {
907 let module = self.modules.get(&normalize_path(file))?;
908 let mut names: Vec<&str> = module.declarations.keys().map(String::as_str).collect();
909 names.sort_unstable();
910 Some(names)
911 }
912
913 fn definition_of_inner(
914 &self,
915 file: &Path,
916 name: &str,
917 visited: &mut HashSet<PathBuf>,
918 ) -> Option<DefSite> {
919 let file = normalize_path(file);
920 if !visited.insert(file.clone()) {
921 return None;
922 }
923 let current = self.modules.get(&file)?;
924
925 if let Some(local) = current.declarations.get(name) {
926 return Some(local.clone());
927 }
928
929 if let Some(sources) = current.selective_re_exports.get(name) {
934 for source in sources {
935 if let Some(def) = self.definition_of_inner(source, name, visited) {
936 return Some(def);
937 }
938 }
939 }
940
941 for source in ¤t.wildcard_re_export_paths {
943 if let Some(def) = self.definition_of_inner(source, name, visited) {
944 return Some(def);
945 }
946 }
947
948 for import in ¤t.imports {
950 let Some(selective_names) = &import.selective_names else {
951 continue;
952 };
953 if !selective_names.contains(name) {
954 continue;
955 }
956 if let Some(path) = &import.path {
957 if let Some(def) = self.definition_of_inner(path, name, visited) {
958 return Some(def);
959 }
960 }
961 }
962
963 for import in ¤t.imports {
965 if import.selective_names.is_some() || import.namespace_alias.is_some() {
966 continue;
967 }
968 if let Some(path) = &import.path {
969 if let Some(def) = self.definition_of_inner(path, name, visited) {
970 return Some(def);
971 }
972 }
973 }
974
975 None
976 }
977
978 fn export_definition_of_inner(
979 &self,
980 file: &Path,
981 name: &str,
982 visited: &mut HashSet<PathBuf>,
983 ) -> Option<DefSite> {
984 let file = normalize_path(file);
985 if !visited.insert(file.clone()) {
986 return None;
987 }
988 let current = self.modules.get(&file)?;
989
990 if current.own_exports.contains(name) {
991 if let Some(local) = current.declarations.get(name) {
992 return Some(local.clone());
993 }
994 }
995 if let Some(sources) = current.selective_re_exports.get(name) {
996 for source in sources {
997 if let Some(definition) = self.export_definition_of_inner(source, name, visited) {
998 return Some(definition);
999 }
1000 }
1001 }
1002 for source in ¤t.wildcard_re_export_paths {
1003 if let Some(definition) = self.export_definition_of_inner(source, name, visited) {
1004 return Some(definition);
1005 }
1006 }
1007 None
1008 }
1009
1010 pub fn re_export_conflicts(&self, file: &Path) -> Vec<ReExportConflict> {
1014 let file = normalize_path(file);
1015 let Some(module) = self.modules.get(&file) else {
1016 return Vec::new();
1017 };
1018
1019 let mut sources: HashMap<String, Vec<PathBuf>> = HashMap::new();
1023
1024 for (name, srcs) in &module.selective_re_exports {
1025 sources
1026 .entry(name.clone())
1027 .or_default()
1028 .extend(srcs.iter().cloned());
1029 }
1030 for src in &module.wildcard_re_export_paths {
1031 let canonical = normalize_path(src);
1032 let Some(src_module) = self
1033 .modules
1034 .get(&canonical)
1035 .or_else(|| self.modules.get(src))
1036 else {
1037 continue;
1038 };
1039 for name in &src_module.exports {
1040 sources
1041 .entry(name.clone())
1042 .or_default()
1043 .push(canonical.clone());
1044 }
1045 }
1046
1047 for name in &module.own_exports {
1051 if let Some(entry) = sources.get_mut(name) {
1052 entry.push(file.clone());
1053 }
1054 }
1055
1056 let mut conflicts = Vec::new();
1057 for (name, mut srcs) in sources {
1058 srcs.sort();
1059 srcs.dedup();
1060 if srcs.len() > 1 {
1061 conflicts.push(ReExportConflict {
1062 name,
1063 sources: srcs,
1064 });
1065 }
1066 }
1067 conflicts.sort_by(|a, b| a.name.cmp(&b.name));
1068 conflicts
1069 }
1070
1071 pub fn selective_import_issues(&self, file: &Path) -> Vec<SelectiveImportIssue> {
1077 let file = normalize_path(file);
1078 let Some(module) = self.modules.get(&file) else {
1079 return Vec::new();
1080 };
1081
1082 let mut out = Vec::new();
1083 for import in &module.imports {
1084 let Some(selective) = &import.selective_names else {
1085 continue;
1086 };
1087 let Some(import_path) = &import.path else {
1088 continue;
1089 };
1090 let Some(target) = self
1091 .modules
1092 .get(import_path)
1093 .or_else(|| self.modules.get(&normalize_path(import_path)))
1094 else {
1095 continue;
1096 };
1097 if target.load_error.is_some() {
1098 continue;
1099 }
1100 let visible: HashSet<_> = self
1101 .exports_for_import(&file, import_path)
1102 .into_iter()
1103 .collect();
1104 for name in selective {
1105 let can_bind = visible.contains(name);
1106 let can_publish = !import.is_pub || target.exports.contains(name);
1107 let kind = if can_bind && can_publish {
1108 continue;
1109 } else if target.declarations.contains_key(name) {
1110 SelectiveImportIssueKind::Private
1111 } else {
1112 SelectiveImportIssueKind::Missing
1113 };
1114 out.push(SelectiveImportIssue {
1115 name: name.clone(),
1116 module: import.raw_path.clone(),
1117 span: import.import_span,
1118 kind,
1119 });
1120 }
1121 }
1122 out.sort_by(|a, b| (&a.name, &a.module, a.kind).cmp(&(&b.name, &b.module, b.kind)));
1123 out.dedup();
1124 out
1125 }
1126
1127 pub fn exported_kind(&self, file: &Path, name: &str) -> Option<DefKind> {
1131 let file = normalize_path(file);
1132 if let Some(module) = self.modules.get(&file) {
1135 if module.own_exports.contains(name) {
1136 return own_export_kind(module, &file, name);
1137 }
1138 }
1139 self.exported_kind_inner(&file, name, &mut HashSet::new())
1140 }
1141
1142 fn exported_kind_inner(
1143 &self,
1144 file: &Path,
1145 name: &str,
1146 visited: &mut HashSet<PathBuf>,
1147 ) -> Option<DefKind> {
1148 let file = normalize_path(file);
1149 if !visited.insert(file.clone()) {
1150 return None;
1151 }
1152 let result = self.modules.get(&file).and_then(|module| {
1153 if module.own_exports.contains(name) {
1154 return own_export_kind(module, &file, name);
1155 }
1156 if let Some(sources) = module.selective_re_exports.get(name) {
1157 for source in sources {
1158 if let Some(kind) = self.exported_kind_inner(source, name, visited) {
1159 return Some(kind);
1160 }
1161 }
1162 }
1163 for source in &module.wildcard_re_export_paths {
1164 if let Some(kind) = self.exported_kind_inner(source, name, visited) {
1165 return Some(kind);
1166 }
1167 }
1168 None
1169 });
1170 visited.remove(&file);
1171 result
1172 }
1173}
1174
1175fn own_export_kind(module: &ModuleInfo, file: &Path, name: &str) -> Option<DefKind> {
1177 module
1178 .declarations
1179 .get(name)
1180 .map(|definition| definition.kind)
1181 .or_else(|| {
1182 stdlib_module_name(file).and_then(|stdlib_module| {
1183 stdlib::builtin_reexports(stdlib_module)
1184 .contains(&name)
1185 .then_some(DefKind::Function)
1186 })
1187 })
1188}
1189
1190const CALLABLE_KINDS: [DefKind; 4] = [
1192 DefKind::Function,
1193 DefKind::Pipeline,
1194 DefKind::Tool,
1195 DefKind::Struct,
1196];
1197
1198pub fn callable_names(grouped: &HashMap<DefKind, HashSet<String>>) -> HashSet<String> {
1200 CALLABLE_KINDS
1201 .iter()
1202 .filter_map(|kind| grouped.get(kind))
1203 .flatten()
1204 .cloned()
1205 .collect()
1206}
1207
1208#[derive(Debug, Clone, PartialEq, Eq)]
1211pub struct ReExportConflict {
1212 pub name: String,
1213 pub sources: Vec<PathBuf>,
1214}
1215
1216#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
1218pub enum SelectiveImportIssueKind {
1219 Missing,
1221 Private,
1223}
1224
1225#[derive(Debug, Clone, PartialEq, Eq)]
1227pub struct SelectiveImportIssue {
1228 pub name: String,
1230 pub module: String,
1232 pub span: Span,
1234 pub kind: SelectiveImportIssueKind,
1236}
1237
1238impl SelectiveImportIssue {
1239 #[must_use]
1241 pub fn message(&self) -> String {
1242 match self.kind {
1243 SelectiveImportIssueKind::Missing => format!(
1244 "imported symbol `{}` does not exist in `{}`",
1245 self.name, self.module
1246 ),
1247 SelectiveImportIssueKind::Private => format!(
1248 "imported symbol `{}` is not exported by `{}` — it is defined there but not `pub`",
1249 self.name, self.module
1250 ),
1251 }
1252 }
1253
1254 #[must_use]
1256 pub fn help(&self) -> String {
1257 match self.kind {
1258 SelectiveImportIssueKind::Missing => format!(
1259 "update the import to a symbol exported by `{}`",
1260 self.module
1261 ),
1262 SelectiveImportIssueKind::Private => {
1263 format!(
1264 "mark `{}` as `pub` in `{}` to export it",
1265 self.name, self.module
1266 )
1267 }
1268 }
1269 }
1270}
1271
1272pub fn stdlib_module_name(path: &Path) -> Option<&str> {
1275 let s = path.to_str()?;
1276 s.strip_prefix("<std>/")
1277}
1278
1279fn normalize_path(path: &Path) -> PathBuf {
1280 canonical_path(path)
1281}
1282
1283pub fn canonical_path(path: &Path) -> PathBuf {
1296 use std::sync::OnceLock;
1297 if let Some(virtual_path) = stdlib::canonical_virtual_path(path) {
1298 return virtual_path;
1299 }
1300 static MEMO: OnceLock<std::sync::RwLock<HashMap<PathBuf, PathBuf>>> = OnceLock::new();
1303 let memo = MEMO.get_or_init(|| std::sync::RwLock::new(HashMap::new()));
1304 if let Some(hit) = memo
1305 .read()
1306 .expect("canonical path memo lock poisoned")
1307 .get(path)
1308 .cloned()
1309 {
1310 return hit;
1311 }
1312 match path.canonicalize() {
1313 Ok(canonical) => {
1314 memo.write()
1315 .expect("canonical path memo lock poisoned")
1316 .insert(path.to_path_buf(), canonical.clone());
1317 canonical
1318 }
1319 Err(_) => manifest_walk::normalize_lexically(path),
1322 }
1323}
1324
1325#[cfg(test)]
1326#[path = "tests.rs"]
1327mod tests;