Skip to main content

fallow_graph/resolve/
types.rs

1//! Type definitions and constants for import resolution.
2
3use std::path::{Path, PathBuf};
4use std::sync::Mutex;
5
6use oxc_resolver::Resolver;
7use rustc_hash::{FxHashMap, FxHashSet};
8
9use fallow_types::discover::FileId;
10
11/// Result of resolving an import specifier.
12#[derive(Debug, Clone)]
13pub enum ResolveResult {
14    /// Resolved to a file within the project.
15    InternalModule(FileId),
16    /// Resolved to a file outside the project (`node_modules`, `.json`, etc.).
17    ExternalFile(PathBuf),
18    /// Bare specifier — an npm package.
19    NpmPackage(String),
20    /// Could not resolve.
21    Unresolvable(String),
22}
23
24/// A resolved import with its target.
25#[derive(Debug, Clone)]
26pub struct ResolvedImport {
27    /// The original import information.
28    pub info: fallow_types::extract::ImportInfo,
29    /// Where the import resolved to.
30    pub target: ResolveResult,
31}
32
33/// A resolved re-export with its target.
34#[derive(Debug, Clone)]
35pub struct ResolvedReExport {
36    /// The original re-export information.
37    pub info: fallow_types::extract::ReExportInfo,
38    /// Where the re-export source resolved to.
39    pub target: ResolveResult,
40}
41
42/// Fully resolved module with all imports mapped to targets.
43#[derive(Debug)]
44pub struct ResolvedModule {
45    /// Unique file identifier.
46    pub file_id: FileId,
47    /// Absolute path to the module file.
48    pub path: PathBuf,
49    /// All export declarations in this module.
50    pub exports: Vec<fallow_types::extract::ExportInfo>,
51    /// All re-exports with resolved targets.
52    pub re_exports: Vec<ResolvedReExport>,
53    /// All static imports with resolved targets.
54    pub resolved_imports: Vec<ResolvedImport>,
55    /// All dynamic imports with resolved targets.
56    pub resolved_dynamic_imports: Vec<ResolvedImport>,
57    /// Dynamic import patterns matched against discovered files.
58    pub resolved_dynamic_patterns: Vec<(fallow_types::extract::DynamicImportPattern, Vec<FileId>)>,
59    /// Static member accesses (e.g., `Status.Active`).
60    pub member_accesses: Vec<fallow_types::extract::MemberAccess>,
61    /// Identifiers used as whole objects (Object.values, for..in, spread, etc.).
62    pub whole_object_uses: Vec<String>,
63    /// Whether this module uses `CommonJS` exports.
64    pub has_cjs_exports: bool,
65    /// Local names of import bindings that are never referenced in this file.
66    pub unused_import_bindings: FxHashSet<String>,
67}
68
69impl Default for ResolvedModule {
70    fn default() -> Self {
71        Self {
72            file_id: FileId(0),
73            path: PathBuf::new(),
74            exports: vec![],
75            re_exports: vec![],
76            resolved_imports: vec![],
77            resolved_dynamic_imports: vec![],
78            resolved_dynamic_patterns: vec![],
79            member_accesses: vec![],
80            whole_object_uses: vec![],
81            has_cjs_exports: false,
82            unused_import_bindings: FxHashSet::default(),
83        }
84    }
85}
86
87/// Shared context for resolving import specifiers.
88///
89/// Groups the immutable lookup tables and caches that are shared across all
90/// `resolve_specifier` calls within a single `resolve_all_imports` invocation.
91pub(super) struct ResolveContext<'a> {
92    /// The oxc_resolver instance (configured once, shared across threads).
93    pub resolver: &'a Resolver,
94    /// Canonical path → FileId lookup (raw paths when root is canonical).
95    pub path_to_id: &'a FxHashMap<&'a Path, FileId>,
96    /// Raw (non-canonical) path → FileId lookup.
97    pub raw_path_to_id: &'a FxHashMap<&'a Path, FileId>,
98    /// Workspace name → canonical root path.
99    pub workspace_roots: &'a FxHashMap<&'a str, &'a Path>,
100    /// Plugin-provided path aliases (prefix, replacement).
101    pub path_aliases: &'a [(String, String)],
102    /// Absolute directories to search when resolving bare SCSS/Sass
103    /// `@import` / `@use` specifiers. Populated from Angular's
104    /// `stylePreprocessorOptions.includePaths` and equivalent settings.
105    pub scss_include_paths: &'a [PathBuf],
106    /// Project root directory.
107    pub root: &'a Path,
108    /// Lazy canonical path → FileId fallback for intra-project symlinks.
109    /// Only initialized on first miss when root is canonical. `None` when
110    /// path_to_id already uses canonical paths (root is not canonical).
111    pub canonical_fallback: Option<&'a CanonicalFallback<'a>>,
112    /// Dedup set for broken-tsconfig warnings. Emits one `tracing::warn!`
113    /// per unique error message instead of spamming the log with one
114    /// warning per affected file. Shared across all parallel resolver
115    /// threads via `Mutex`. Empty and unused when no tsconfig errors occur.
116    pub tsconfig_warned: &'a Mutex<FxHashSet<String>>,
117}
118
119/// Thread-safe lazy canonical path index, built on first access.
120pub(super) struct CanonicalFallback<'a> {
121    files: &'a [fallow_types::discover::DiscoveredFile],
122    map: std::sync::OnceLock<FxHashMap<std::path::PathBuf, FileId>>,
123}
124
125impl<'a> CanonicalFallback<'a> {
126    pub const fn new(files: &'a [fallow_types::discover::DiscoveredFile]) -> Self {
127        Self {
128            files,
129            map: std::sync::OnceLock::new(),
130        }
131    }
132
133    /// Look up a canonical path, lazily building the index on first call.
134    pub fn get(&self, canonical: &Path) -> Option<FileId> {
135        let map = self.map.get_or_init(|| {
136            tracing::debug!(
137                "intra-project symlinks detected — building canonical path index ({} files)",
138                self.files.len()
139            );
140            self.files
141                .iter()
142                .filter_map(|f| {
143                    dunce::canonicalize(&f.path)
144                        .ok()
145                        .map(|canonical| (canonical, f.id))
146                })
147                .collect()
148        });
149        map.get(canonical).copied()
150    }
151}
152
153#[cfg(all(test, not(miri)))]
154mod tests {
155    use super::*;
156    use fallow_types::discover::DiscoveredFile;
157
158    #[test]
159    fn canonical_fallback_returns_none_for_empty_files() {
160        let files: Vec<DiscoveredFile> = vec![];
161        let fallback = CanonicalFallback::new(&files);
162        assert!(fallback.get(Path::new("/nonexistent")).is_none());
163    }
164
165    #[test]
166    fn canonical_fallback_finds_existing_file() {
167        let temp = std::env::temp_dir().join("fallow-test-canonical-fallback");
168        let _ = std::fs::create_dir_all(&temp);
169        let test_file = temp.join("test.ts");
170        std::fs::write(&test_file, "").unwrap();
171
172        let files = vec![DiscoveredFile {
173            id: FileId(42),
174            path: test_file.clone(),
175            size_bytes: 0,
176        }];
177        let fallback = CanonicalFallback::new(&files);
178
179        let canonical = dunce::canonicalize(&test_file).unwrap();
180        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
181
182        // Second call uses cached map (OnceLock)
183        assert_eq!(fallback.get(&canonical), Some(FileId(42)));
184
185        let _ = std::fs::remove_dir_all(&temp);
186    }
187
188    #[test]
189    fn canonical_fallback_returns_none_for_missing_path() {
190        let temp = std::env::temp_dir().join("fallow-test-canonical-miss");
191        let _ = std::fs::create_dir_all(&temp);
192        let test_file = temp.join("exists.ts");
193        std::fs::write(&test_file, "").unwrap();
194
195        let files = vec![DiscoveredFile {
196            id: FileId(1),
197            path: test_file,
198            size_bytes: 0,
199        }];
200        let fallback = CanonicalFallback::new(&files);
201        assert!(fallback.get(Path::new("/nonexistent/file.ts")).is_none());
202
203        let _ = std::fs::remove_dir_all(&temp);
204    }
205}
206
207/// Known output directory names that may appear in exports map targets.
208/// When an exports map points to `./dist/utils.js`, we try replacing these
209/// prefixes with `src/` (the conventional source directory) to find the tracked
210/// source file.
211pub const OUTPUT_DIRS: &[&str] = &["dist", "build", "out", "esm", "cjs"];
212
213/// Source extensions to try when mapping a built output file back to source.
214pub const SOURCE_EXTS: &[&str] = &["ts", "tsx", "mts", "cts", "js", "jsx", "mjs", "cjs"];
215
216/// React Native platform extension prefixes.
217/// Metro resolves platform-specific files (e.g., `./foo` -> `./foo.web.tsx` on web).
218pub const RN_PLATFORM_PREFIXES: &[&str] = &[".web", ".ios", ".android", ".native"];