fallow_extract/lib.rs
1//! Parsing and extraction engine for fallow codebase intelligence.
2//!
3//! This crate handles all file parsing: JS/TS via Oxc, Vue/Svelte SFC extraction,
4//! Astro frontmatter, MDX import/export extraction, CSS Module class name extraction,
5//! HTML asset reference extraction, and incremental caching of parse results.
6
7#![warn(missing_docs)]
8#![cfg_attr(not(test), deny(clippy::disallowed_methods))]
9#![cfg_attr(
10 test,
11 allow(
12 clippy::unwrap_used,
13 clippy::expect_used,
14 reason = "tests use unwrap and expect to keep fixture setup concise"
15 )
16)]
17
18mod asset_url;
19pub mod astro;
20pub mod cache;
21pub(crate) mod complexity;
22pub mod css;
23pub mod flags;
24pub mod glimmer;
25pub mod graphql;
26pub mod html;
27pub mod iconify;
28pub mod inventory;
29pub mod mdx;
30mod parse;
31pub mod sfc;
32mod sfc_template;
33mod source_map;
34pub mod suppress;
35pub(crate) mod template_complexity;
36mod template_usage;
37/// Visitor utilities for AST extraction.
38pub mod visitor;
39
40use std::path::Path;
41
42use rayon::prelude::*;
43
44use cache::CacheStore;
45use fallow_types::discover::{DiscoveredFile, FileId};
46
47pub use fallow_types::extract::{
48 ClassHeritageInfo, DynamicImportInfo, DynamicImportPattern, ExportInfo, ExportName, ImportInfo,
49 ImportedName, LocalTypeDeclaration, MemberAccess, MemberInfo, MemberKind, ModuleInfo,
50 ParseResult, PublicSignatureTypeReference, ReExportInfo, RequireCallInfo, VisibilityTag,
51 compute_line_offsets,
52};
53
54pub use astro::extract_astro_frontmatter;
55pub use css::extract_css_module_exports;
56pub use glimmer::{is_glimmer_file, strip_glimmer_templates};
57pub use mdx::extract_mdx_statements;
58pub use sfc::{extract_sfc_scripts, is_sfc_file};
59pub use sfc_template::angular::ANGULAR_TPL_SENTINEL;
60
61#[expect(
62 clippy::expect_used,
63 reason = "static regex patterns are hard-coded analyzer invariants covered by extraction tests"
64)]
65pub(crate) fn static_regex(pattern: &str) -> regex::Regex {
66 regex::Regex::new(pattern).expect("static regex pattern should compile")
67}
68
69/// Synthetic member-access object used to carry exported-instance bindings.
70///
71/// `MemberAccess { object: format!("{INSTANCE_EXPORT_SENTINEL}{export_name}"), member: target }`
72/// means the exported value named `export_name` is an instance of the local
73/// class/interface symbol named `target`.
74pub const INSTANCE_EXPORT_SENTINEL: &str = "__fallow_instance_export__:";
75
76/// Synthetic member-access object prefix for typed Playwright fixtures.
77///
78/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_DEF_SENTINEL}{test}:{fixture}"), member: type_name }`
79/// means the exported Playwright test object named `test` provides a fixture
80/// named `fixture` whose declared type is `type_name`.
81pub const PLAYWRIGHT_FIXTURE_DEF_SENTINEL: &str = "__fallow_playwright_fixture_def__:";
82
83/// Synthetic member-access object prefix for Playwright fixture wrapper aliases.
84///
85/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_ALIAS_SENTINEL}{alias}:"), member: base }`
86/// means the exported Playwright test object named `alias` inherits fixture
87/// definitions from the exported test object named `base`.
88pub const PLAYWRIGHT_FIXTURE_ALIAS_SENTINEL: &str = "__fallow_playwright_fixture_alias__:";
89
90/// Synthetic member-access object prefix for Playwright fixture member uses.
91///
92/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_USE_SENTINEL}{test}:{fixture}"), member }`
93/// means a callback passed to the Playwright test object named `test`
94/// destructures `fixture` and accesses `fixture.member`.
95pub const PLAYWRIGHT_FIXTURE_USE_SENTINEL: &str = "__fallow_playwright_fixture_use__:";
96
97/// Synthetic member-access object prefix for exported Playwright fixture type aliases.
98///
99/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_TYPE_SENTINEL}{alias}:{fixture_path}"), member: type_name }`
100/// means a local type alias named `alias` contains a nested fixture path whose
101/// declared type is `type_name`. The analyze layer uses this when a Playwright
102/// fixture generic imports an object type alias from another module.
103pub const PLAYWRIGHT_FIXTURE_TYPE_SENTINEL: &str = "__fallow_playwright_fixture_type__:";
104
105/// Synthetic member-access object prefix for static-factory call returns.
106///
107/// `MemberAccess { object: format!("{FACTORY_CALL_SENTINEL}{callee}:{method}"), member }`
108/// means a local binding was assigned from `<callee>.<method>()` and a member
109/// is accessed on the result. The analyze layer resolves `callee` through the
110/// consumer module's imports to a class export and credits `member` on the
111/// class when the matching method carries `is_instance_returning_static`.
112/// See issue #346.
113pub const FACTORY_CALL_SENTINEL: &str = "__fallow_factory_call__:";
114
115/// Synthetic member-access object prefix for fluent-builder chain credit.
116///
117/// `MemberAccess { object: format!("{FLUENT_CHAIN_SENTINEL}{callee}:{root_method}:{chain}"), member }`
118/// means a fluent chain `<callee>.<root_method>().<...chain>.<member>` was
119/// observed. `chain` is a comma-separated list of method names (empty when
120/// `member` is the first chained call after `root_method`). The analyze layer
121/// resolves `callee` to a class export, validates `root_method` has
122/// `is_instance_returning_static`, walks each `chain` segment requiring
123/// `is_self_returning` on the class, and credits `member` on the class
124/// when the chain remains on the class type. See issue #387.
125pub const FLUENT_CHAIN_SENTINEL: &str = "__fallow_fluent_chain__:";
126
127/// Synthetic member-access object prefix for fluent chains rooted at a `new`
128/// expression.
129///
130/// `MemberAccess { object: format!("{FLUENT_CHAIN_NEW_SENTINEL}{class}:{chain}"), member }`
131/// means a chain `new <class>(...).<...chain>.<member>` was observed. Unlike
132/// `FLUENT_CHAIN_SENTINEL`, there is no root method: a constructor always
133/// returns an instance of `class`, so no `is_instance_returning_static` check
134/// applies. `chain` is a comma-separated list of the intermediate method names
135/// between the constructor and `member` (it always contains at least the first
136/// method, which must be `is_self_returning` to reach `member`). The analyze
137/// layer resolves `class` to a class export, requires every `chain` segment to
138/// be `is_self_returning` on the class, and credits `member` on the class.
139/// The first method directly off the constructor is credited separately via
140/// the `static_member_object_name` `NewExpression` arm. See issue #605.
141pub const FLUENT_CHAIN_NEW_SENTINEL: &str = "__fallow_fluent_chain_new__:";
142
143pub use parse::parse_source_to_module;
144
145/// Leading UTF-8 byte order mark codepoint.
146///
147/// Windows editors (Notepad, older VS settings, some IDE plugins) emit a UTF-8
148/// BOM at the start of source files. fallow's contract is "UTF-8 with or
149/// without BOM; line offsets are computed against the post-BOM view; the BOM,
150/// if present on input, is preserved on output by `fallow fix`."
151const BOM_CHAR: char = '\u{FEFF}';
152
153/// Strip the leading UTF-8 BOM if present.
154///
155/// Called at every file-read entry point in this crate so the rest of the
156/// pipeline (content hash, `compute_line_offsets`, oxc parser, downstream
157/// analyses) sees a consistent post-BOM view. Mirrors the
158/// `fallow_config` layer (`config_writer.rs::BOM`) so config-shaped sources
159/// and source-code-shaped sources are processed symmetrically. See issue #475.
160#[must_use]
161pub(crate) fn strip_bom(source: &str) -> &str {
162 source.strip_prefix(BOM_CHAR).unwrap_or(source)
163}
164
165/// Parse all files in parallel, extracting imports and exports.
166/// Uses the cache to skip reparsing files whose content hasn't changed.
167///
168/// When `need_complexity` is true, per-function cyclomatic/cognitive complexity
169/// metrics are computed during parsing (needed by the `health` command).
170/// Pass `false` for dead-code analysis where complexity data is unused.
171pub fn parse_all_files(
172 files: &[DiscoveredFile],
173 cache: Option<&CacheStore>,
174 need_complexity: bool,
175) -> ParseResult {
176 use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
177 let cache_hits = AtomicUsize::new(0);
178 let cache_misses = AtomicUsize::new(0);
179 let parse_cpu_nanos = AtomicU64::new(0);
180
181 let modules: Vec<ModuleInfo> = files
182 .par_iter()
183 .filter_map(|file| {
184 parse_single_file_cached(
185 file,
186 cache,
187 &cache_hits,
188 &cache_misses,
189 &parse_cpu_nanos,
190 need_complexity,
191 )
192 })
193 .collect();
194
195 let hits = cache_hits.load(Ordering::Relaxed);
196 let misses = cache_misses.load(Ordering::Relaxed);
197 if hits > 0 || misses > 0 {
198 tracing::info!(
199 cache_hits = hits,
200 cache_misses = misses,
201 "incremental cache stats"
202 );
203 }
204
205 ParseResult {
206 modules,
207 cache_hits: hits,
208 cache_misses: misses,
209 parse_cpu_ms: parse_cpu_nanos.load(Ordering::Relaxed) as f64 / 1_000_000.0,
210 }
211}
212
213/// Parse a single file, consulting the cache first.
214///
215/// Cache validation strategy (fast path -> slow path):
216/// 1. `stat()` the file to get mtime + size (single syscall, no file read)
217/// 2. If mtime+size match the cached entry -> cache hit, return immediately
218/// 3. If mtime+size differ -> read file, compute content hash
219/// 4. If content hash matches cached entry -> cache hit (file was `touch`ed but unchanged)
220/// 5. Otherwise -> cache miss, full parse
221fn parse_single_file_cached(
222 file: &DiscoveredFile,
223 cache: Option<&CacheStore>,
224 cache_hits: &std::sync::atomic::AtomicUsize,
225 cache_misses: &std::sync::atomic::AtomicUsize,
226 parse_cpu_nanos: &std::sync::atomic::AtomicU64,
227 need_complexity: bool,
228) -> Option<ModuleInfo> {
229 use std::sync::atomic::Ordering;
230
231 if let Some(store) = cache
232 && let Ok(metadata) = std::fs::metadata(&file.path)
233 {
234 let mt = mtime_secs(&metadata);
235 let sz = metadata.len();
236 if let Some(cached) = store.get_by_metadata(&file.path, mt, sz)
237 && (!need_complexity || !cached.complexity.is_empty())
238 {
239 cache_hits.fetch_add(1, Ordering::Relaxed);
240 return Some(cache::cached_to_module_opts(
241 cached,
242 file.id,
243 need_complexity,
244 ));
245 }
246 }
247
248 let raw = std::fs::read_to_string(&file.path).ok()?;
249 let source = strip_bom(&raw);
250 let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
251
252 if let Some(store) = cache
253 && let Some(cached) = store.get(&file.path, content_hash)
254 && (!need_complexity || !cached.complexity.is_empty())
255 {
256 cache_hits.fetch_add(1, Ordering::Relaxed);
257 return Some(cache::cached_to_module_opts(
258 cached,
259 file.id,
260 need_complexity,
261 ));
262 }
263 cache_misses.fetch_add(1, Ordering::Relaxed);
264
265 let parse_start = std::time::Instant::now();
266 let module = parse_source_to_module(file.id, &file.path, source, content_hash, need_complexity);
267 parse_cpu_nanos.fetch_add(
268 u64::try_from(parse_start.elapsed().as_nanos()).unwrap_or(u64::MAX),
269 Ordering::Relaxed,
270 );
271 Some(module)
272}
273
274/// Extract mtime (seconds since epoch) from file metadata.
275/// Returns 0 if mtime cannot be determined (pre-epoch, unsupported OS, etc.).
276fn mtime_secs(metadata: &std::fs::Metadata) -> u64 {
277 metadata
278 .modified()
279 .ok()
280 .and_then(|t| t.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
281 .map_or(0, |d| d.as_secs())
282}
283
284/// Parse a single file and extract module information (without complexity).
285#[must_use]
286pub fn parse_single_file(file: &DiscoveredFile) -> Option<ModuleInfo> {
287 let raw = std::fs::read_to_string(&file.path).ok()?;
288 let source = strip_bom(&raw);
289 let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
290 Some(parse_source_to_module(
291 file.id,
292 &file.path,
293 source,
294 content_hash,
295 false,
296 ))
297}
298
299/// Parse from in-memory content (for LSP, includes complexity).
300#[must_use]
301pub fn parse_from_content(file_id: FileId, path: &Path, content: &str) -> ModuleInfo {
302 let content = strip_bom(content);
303 let content_hash = xxhash_rust::xxh3::xxh3_64(content.as_bytes());
304 parse_source_to_module(file_id, path, content, content_hash, true)
305}
306
307#[cfg(all(test, not(miri)))]
308mod tests;