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 member uses.
84///
85/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_USE_SENTINEL}{test}:{fixture}"), member }`
86/// means a callback passed to the Playwright test object named `test`
87/// destructures `fixture` and accesses `fixture.member`.
88pub const PLAYWRIGHT_FIXTURE_USE_SENTINEL: &str = "__fallow_playwright_fixture_use__:";
89
90/// Synthetic member-access object prefix for static-factory call returns.
91///
92/// `MemberAccess { object: format!("{FACTORY_CALL_SENTINEL}{callee}:{method}"), member }`
93/// means a local binding was assigned from `<callee>.<method>()` and a member
94/// is accessed on the result. The analyze layer resolves `callee` through the
95/// consumer module's imports to a class export and credits `member` on the
96/// class when the matching method carries `is_instance_returning_static`.
97/// See issue #346.
98pub const FACTORY_CALL_SENTINEL: &str = "__fallow_factory_call__:";
99
100/// Synthetic member-access object prefix for fluent-builder chain credit.
101///
102/// `MemberAccess { object: format!("{FLUENT_CHAIN_SENTINEL}{callee}:{root_method}:{chain}"), member }`
103/// means a fluent chain `<callee>.<root_method>().<...chain>.<member>` was
104/// observed. `chain` is a comma-separated list of method names (empty when
105/// `member` is the first chained call after `root_method`). The analyze layer
106/// resolves `callee` to a class export, validates `root_method` has
107/// `is_instance_returning_static`, walks each `chain` segment requiring
108/// `is_self_returning` on the class, and credits `member` on the class
109/// when the chain remains on the class type. See issue #387.
110pub const FLUENT_CHAIN_SENTINEL: &str = "__fallow_fluent_chain__:";
111
112/// Synthetic member-access object prefix for fluent chains rooted at a `new`
113/// expression.
114///
115/// `MemberAccess { object: format!("{FLUENT_CHAIN_NEW_SENTINEL}{class}:{chain}"), member }`
116/// means a chain `new <class>(...).<...chain>.<member>` was observed. Unlike
117/// `FLUENT_CHAIN_SENTINEL`, there is no root method: a constructor always
118/// returns an instance of `class`, so no `is_instance_returning_static` check
119/// applies. `chain` is a comma-separated list of the intermediate method names
120/// between the constructor and `member` (it always contains at least the first
121/// method, which must be `is_self_returning` to reach `member`). The analyze
122/// layer resolves `class` to a class export, requires every `chain` segment to
123/// be `is_self_returning` on the class, and credits `member` on the class.
124/// The first method directly off the constructor is credited separately via
125/// the `static_member_object_name` `NewExpression` arm. See issue #605.
126pub const FLUENT_CHAIN_NEW_SENTINEL: &str = "__fallow_fluent_chain_new__:";
127
128pub use parse::parse_source_to_module;
129
130/// Leading UTF-8 byte order mark codepoint.
131///
132/// Windows editors (Notepad, older VS settings, some IDE plugins) emit a UTF-8
133/// BOM at the start of source files. fallow's contract is "UTF-8 with or
134/// without BOM; line offsets are computed against the post-BOM view; the BOM,
135/// if present on input, is preserved on output by `fallow fix`."
136const BOM_CHAR: char = '\u{FEFF}';
137
138/// Strip the leading UTF-8 BOM if present.
139///
140/// Called at every file-read entry point in this crate so the rest of the
141/// pipeline (content hash, `compute_line_offsets`, oxc parser, downstream
142/// analyses) sees a consistent post-BOM view. Mirrors the
143/// `fallow_config` layer (`config_writer.rs::BOM`) so config-shaped sources
144/// and source-code-shaped sources are processed symmetrically. See issue #475.
145#[must_use]
146pub(crate) fn strip_bom(source: &str) -> &str {
147 source.strip_prefix(BOM_CHAR).unwrap_or(source)
148}
149
150/// Parse all files in parallel, extracting imports and exports.
151/// Uses the cache to skip reparsing files whose content hasn't changed.
152///
153/// When `need_complexity` is true, per-function cyclomatic/cognitive complexity
154/// metrics are computed during parsing (needed by the `health` command).
155/// Pass `false` for dead-code analysis where complexity data is unused.
156pub fn parse_all_files(
157 files: &[DiscoveredFile],
158 cache: Option<&CacheStore>,
159 need_complexity: bool,
160) -> ParseResult {
161 use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
162 let cache_hits = AtomicUsize::new(0);
163 let cache_misses = AtomicUsize::new(0);
164 let parse_cpu_nanos = AtomicU64::new(0);
165
166 let modules: Vec<ModuleInfo> = files
167 .par_iter()
168 .filter_map(|file| {
169 parse_single_file_cached(
170 file,
171 cache,
172 &cache_hits,
173 &cache_misses,
174 &parse_cpu_nanos,
175 need_complexity,
176 )
177 })
178 .collect();
179
180 let hits = cache_hits.load(Ordering::Relaxed);
181 let misses = cache_misses.load(Ordering::Relaxed);
182 if hits > 0 || misses > 0 {
183 tracing::info!(
184 cache_hits = hits,
185 cache_misses = misses,
186 "incremental cache stats"
187 );
188 }
189
190 ParseResult {
191 modules,
192 cache_hits: hits,
193 cache_misses: misses,
194 parse_cpu_ms: parse_cpu_nanos.load(Ordering::Relaxed) as f64 / 1_000_000.0,
195 }
196}
197
198/// Parse a single file, consulting the cache first.
199///
200/// Cache validation strategy (fast path -> slow path):
201/// 1. `stat()` the file to get mtime + size (single syscall, no file read)
202/// 2. If mtime+size match the cached entry -> cache hit, return immediately
203/// 3. If mtime+size differ -> read file, compute content hash
204/// 4. If content hash matches cached entry -> cache hit (file was `touch`ed but unchanged)
205/// 5. Otherwise -> cache miss, full parse
206fn parse_single_file_cached(
207 file: &DiscoveredFile,
208 cache: Option<&CacheStore>,
209 cache_hits: &std::sync::atomic::AtomicUsize,
210 cache_misses: &std::sync::atomic::AtomicUsize,
211 parse_cpu_nanos: &std::sync::atomic::AtomicU64,
212 need_complexity: bool,
213) -> Option<ModuleInfo> {
214 use std::sync::atomic::Ordering;
215
216 if let Some(store) = cache
217 && let Ok(metadata) = std::fs::metadata(&file.path)
218 {
219 let mt = mtime_secs(&metadata);
220 let sz = metadata.len();
221 if let Some(cached) = store.get_by_metadata(&file.path, mt, sz)
222 && (!need_complexity || !cached.complexity.is_empty())
223 {
224 cache_hits.fetch_add(1, Ordering::Relaxed);
225 return Some(cache::cached_to_module_opts(
226 cached,
227 file.id,
228 need_complexity,
229 ));
230 }
231 }
232
233 let raw = std::fs::read_to_string(&file.path).ok()?;
234 let source = strip_bom(&raw);
235 let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
236
237 if let Some(store) = cache
238 && let Some(cached) = store.get(&file.path, content_hash)
239 && (!need_complexity || !cached.complexity.is_empty())
240 {
241 cache_hits.fetch_add(1, Ordering::Relaxed);
242 return Some(cache::cached_to_module_opts(
243 cached,
244 file.id,
245 need_complexity,
246 ));
247 }
248 cache_misses.fetch_add(1, Ordering::Relaxed);
249
250 let parse_start = std::time::Instant::now();
251 let module = parse_source_to_module(file.id, &file.path, source, content_hash, need_complexity);
252 parse_cpu_nanos.fetch_add(
253 u64::try_from(parse_start.elapsed().as_nanos()).unwrap_or(u64::MAX),
254 Ordering::Relaxed,
255 );
256 Some(module)
257}
258
259/// Extract mtime (seconds since epoch) from file metadata.
260/// Returns 0 if mtime cannot be determined (pre-epoch, unsupported OS, etc.).
261fn mtime_secs(metadata: &std::fs::Metadata) -> u64 {
262 metadata
263 .modified()
264 .ok()
265 .and_then(|t| t.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
266 .map_or(0, |d| d.as_secs())
267}
268
269/// Parse a single file and extract module information (without complexity).
270#[must_use]
271pub fn parse_single_file(file: &DiscoveredFile) -> Option<ModuleInfo> {
272 let raw = std::fs::read_to_string(&file.path).ok()?;
273 let source = strip_bom(&raw);
274 let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
275 Some(parse_source_to_module(
276 file.id,
277 &file.path,
278 source,
279 content_hash,
280 false,
281 ))
282}
283
284/// Parse from in-memory content (for LSP, includes complexity).
285#[must_use]
286pub fn parse_from_content(file_id: FileId, path: &Path, content: &str) -> ModuleInfo {
287 let content = strip_bom(content);
288 let content_hash = xxhash_rust::xxh3::xxh3_64(content.as_bytes());
289 parse_source_to_module(file_id, path, content, content_hash, true)
290}
291
292#[cfg(all(test, not(miri)))]
293mod tests;