Skip to main content

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 css_classes;
24pub mod css_in_js;
25pub mod css_metrics;
26pub mod flags;
27pub mod glimmer;
28pub(crate) mod graphql;
29pub(crate) mod html;
30pub(crate) mod iconify;
31pub mod inventory;
32pub mod mdx;
33mod module_info;
34mod parse;
35pub mod sfc;
36pub mod sfc_css;
37mod sfc_props;
38mod sfc_template;
39pub mod similar_code;
40mod source_map;
41pub mod suppress;
42/// Tailwind CSS arbitrary-value detection.
43pub mod tailwind;
44pub(crate) mod template_complexity;
45mod template_expression_scan;
46mod template_usage;
47/// Visitor utilities for AST extraction.
48pub mod visitor;
49
50use std::path::Path;
51use std::sync::atomic::{AtomicBool, Ordering};
52
53use rayon::prelude::*;
54
55use cache::CacheStore;
56use fallow_types::discover::{DiscoveredFile, FileId};
57
58pub use fallow_types::extract::{
59    AngularComponentFieldArrayTypeFact, AngularTemplateMemberAccessFact, AngularThisSpreadFact,
60    ClassHeritageInfo, ClassThisMemberAccessFact, ClassThisWholeObjectUseFact,
61    ComputedEnumKeyUseFact, DefaultImportWholeObjectUseFact, DynamicCustomElementRenderFact,
62    DynamicImportInfo, DynamicImportPattern, ExportInfo, ExportName, FactoryCallMemberAccessFact,
63    FactoryFnMemberAccessFact, FactoryFnWholeObjectFact, FactoryReturnExport,
64    FactoryReturnObjectPropertyAccessFact, FactoryReturnObjectShapeExport,
65    FluentChainMemberAccessFact, FluentChainNewMemberAccessFact, ImportInfo, ImportedName,
66    InstanceExportBindingFact, LocalTypeDeclaration, MemberAccess, MemberInfo, MemberKind,
67    ModuleInfo, ModuleLoadMechanism, ParseResult, PlaywrightFixtureAliasFact,
68    PlaywrightFixtureDefinitionFact, PlaywrightFixtureTypeFact, PlaywrightFixtureUseFact,
69    PublicSignatureTypeReference, ReExportInfo, RequireCallInfo, RequiredTypeMemberFact,
70    SemanticFact, SourceReadFailure, StringEnumMemberValueFact, TypeAliasSurfaceTargetFact,
71    TypeMemberTypeEntry, TypedPropertyMemberAccessFact, VisibilityTag, VitestModuleMockAction,
72    VitestModuleMockOperationFact, compute_line_offsets,
73};
74
75pub use astro::{
76    extract_astro_frontmatter, extract_astro_style_regions, extract_astro_template_regions,
77};
78pub use css::{
79    ThemeScan, ThemeTokenDef, extract_apply_tokens, extract_apply_tokens_located,
80    extract_css_module_exports, extract_css_var_reads_located, scan_theme_blocks,
81};
82pub use css_classes::{
83    MarkupClassScan, MarkupClassToken, is_edit_distance_one, is_typo_edit, scan_markup_class_tokens,
84};
85pub use css_in_js::{
86    ConsumerQuery, CssInJsObjectSheets, CssInJsToken, CssInJsTokenDef, CssInJsTokenOrigin,
87    TokenConsumerHit, css_in_js_consumer_scan, css_in_js_object_sheets, css_in_js_theme_consumers,
88    css_in_js_theme_token_defs, css_in_js_token_consumers, css_in_js_token_defs,
89    css_in_js_virtual_stylesheet, panda_style_value_consumers, panda_token_call_consumers,
90};
91pub use css_metrics::{compute_css_analytics, parse_css_color_rgb};
92pub use glimmer::{is_glimmer_file, strip_glimmer_templates};
93pub use mdx::{extract_mdx_statements, extract_mdx_statements_mapped};
94pub use sfc::{
95    SourceRegion, extract_sfc_scripts, extract_sfc_styles, extract_sfc_template_regions,
96    is_sfc_file,
97};
98pub use sfc_css::{
99    scoped_unused_classes, sfc_preprocessor_virtual_stylesheet, sfc_virtual_stylesheet,
100};
101pub use similar_code::extract_similar_code_functions;
102pub use source_map::ExtractionResult;
103pub use tailwind::{TailwindArbitraryUse, scan_tailwind_arbitrary_values};
104
105#[expect(
106    clippy::expect_used,
107    reason = "static regex patterns are hard-coded analyzer invariants covered by extraction tests"
108)]
109fn static_regex(pattern: &str) -> regex::Regex {
110    regex::Regex::new(pattern).expect("static regex pattern should compile")
111}
112
113pub use parse::parse_source_to_module;
114
115/// Leading UTF-8 byte order mark codepoint.
116///
117/// Windows editors (Notepad, older VS settings, some IDE plugins) emit a UTF-8
118/// BOM at the start of source files. fallow's contract is "UTF-8 with or
119/// without BOM; line offsets are computed against the post-BOM view; the BOM,
120/// if present on input, is preserved on output by `fallow fix`."
121const BOM_CHAR: char = '\u{FEFF}';
122// Small, cache-hot inputs are faster on one thread than through Rayon setup.
123// Larger file sets still use parallel parsing where parse work dominates.
124const PARALLEL_PARSE_FILE_THRESHOLD: usize = 32;
125
126/// Strip the leading UTF-8 BOM if present.
127///
128/// Called at every file-read entry point in this crate so the rest of the
129/// pipeline (content hash, `compute_line_offsets`, oxc parser, downstream
130/// analyses) sees a consistent post-BOM view. Mirrors the
131/// `fallow_config` layer (`config_writer.rs::BOM`) so config-shaped sources
132/// and source-code-shaped sources are processed symmetrically. See issue #475.
133#[must_use]
134fn strip_bom(source: &str) -> &str {
135    source.strip_prefix(BOM_CHAR).unwrap_or(source)
136}
137
138/// Parse all files, extracting imports and exports.
139///
140/// Small file sets use a sequential fast path to avoid parallel scheduling
141/// overhead; larger file sets use parallel extraction.
142/// Uses the cache to skip reparsing files whose content hasn't changed.
143///
144/// When `need_complexity` is true, per-function cyclomatic/cognitive complexity
145/// metrics are computed during parsing (needed by the `health` command).
146/// Pass `false` for dead-code analysis where complexity data is unused.
147pub fn parse_all_files(
148    files: &[DiscoveredFile],
149    cache: Option<&CacheStore>,
150    need_complexity: bool,
151) -> ParseResult {
152    parse_all_files_cancellable(files, cache, need_complexity, None)
153}
154
155/// Parse all files, abandoning the remaining ones once `cancellation` is set.
156///
157/// Rayon's `map`/`collect` cannot short-circuit, so cancellation makes the
158/// per-file body a no-op instead of stopping the iteration: the scheduled
159/// items still drain, but at one atomic load each. The returned
160/// [`ParseResult`] is therefore truncated whenever the token flipped, and
161/// callers must treat a set token as a failed run rather than as a project
162/// with fewer modules.
163pub fn parse_all_files_cancellable(
164    files: &[DiscoveredFile],
165    cache: Option<&CacheStore>,
166    need_complexity: bool,
167    cancellation: Option<&AtomicBool>,
168) -> ParseResult {
169    let parse_one = |file: &DiscoveredFile| {
170        if cancellation.is_some_and(|cancelled| cancelled.load(Ordering::SeqCst)) {
171            return ParseFileResult::default();
172        }
173        parse_single_file_cached(file, cache, need_complexity)
174    };
175    let results: Vec<ParseFileResult> = if files.len() <= PARALLEL_PARSE_FILE_THRESHOLD {
176        files.iter().map(parse_one).collect()
177    } else {
178        files.par_iter().map(parse_one).collect()
179    };
180
181    let mut modules = Vec::with_capacity(results.len());
182    let mut read_failures = Vec::new();
183    let mut hits = 0usize;
184    let mut misses = 0usize;
185    let mut parse_cpu_nanos = 0u64;
186
187    for result in results {
188        hits += result.cache_hits;
189        misses += result.cache_misses;
190        parse_cpu_nanos = parse_cpu_nanos.saturating_add(result.parse_cpu_nanos);
191        if let Some(module) = result.module {
192            modules.push(module);
193        }
194        if let Some(failure) = result.read_failure {
195            read_failures.push(failure);
196        }
197    }
198
199    if hits > 0 || misses > 0 {
200        tracing::info!(
201            cache_hits = hits,
202            cache_misses = misses,
203            "incremental cache stats"
204        );
205    }
206
207    ParseResult {
208        modules,
209        read_failures,
210        cache_hits: hits,
211        cache_misses: misses,
212        parse_cpu_ms: parse_cpu_nanos as f64 / 1_000_000.0,
213    }
214}
215
216#[derive(Default)]
217struct ParseFileResult {
218    module: Option<ModuleInfo>,
219    read_failure: Option<SourceReadFailure>,
220    cache_hits: usize,
221    cache_misses: usize,
222    parse_cpu_nanos: u64,
223}
224
225impl ParseFileResult {
226    fn cache_hit(module: ModuleInfo) -> Self {
227        Self {
228            module: Some(module),
229            read_failure: None,
230            cache_hits: 1,
231            cache_misses: 0,
232            parse_cpu_nanos: 0,
233        }
234    }
235
236    fn cache_miss(module: ModuleInfo, parse_cpu_nanos: u64) -> Self {
237        Self {
238            module: Some(module),
239            read_failure: None,
240            cache_hits: 0,
241            cache_misses: 1,
242            parse_cpu_nanos,
243        }
244    }
245
246    fn read_failure(file: &DiscoveredFile, error: &std::io::Error) -> Self {
247        Self {
248            module: None,
249            read_failure: Some(SourceReadFailure {
250                file_id: file.id,
251                path: file.path.clone(),
252                error: error.to_string(),
253            }),
254            cache_hits: 0,
255            cache_misses: 0,
256            parse_cpu_nanos: 0,
257        }
258    }
259}
260
261/// Parse a single file, consulting the cache first.
262///
263/// Cache validation strategy (fast path -> slow path):
264/// 1. Open the file so unreadable sources cannot use stale cached analysis
265/// 2. Read mtime + size from the open handle
266/// 3. If mtime+size match the cached entry -> cache hit, return immediately
267/// 4. If mtime+size differ -> read file, compute content hash
268/// 5. If content hash matches cached entry -> cache hit (file was `touch`ed but unchanged)
269/// 6. Otherwise -> cache miss, full parse
270fn parse_single_file_cached(
271    file: &DiscoveredFile,
272    cache: Option<&CacheStore>,
273    need_complexity: bool,
274) -> ParseFileResult {
275    let cached_by_path = cache.and_then(|store| store.get_by_path_only(&file.path));
276
277    if let Some(cached) = cached_by_path
278        && cached.file_size == file.size_bytes
279    {
280        let source_file = match std::fs::File::open(&file.path) {
281            Ok(source_file) => source_file,
282            Err(error) => return ParseFileResult::read_failure(file, &error),
283        };
284        if let Ok(metadata) = source_file.metadata()
285            && metadata.len() == cached.file_size
286        {
287            let fingerprint =
288                fallow_types::source_fingerprint::SourceFingerprint::from_metadata(&metadata);
289            if cached.source_fingerprint() == fingerprint
290                && fingerprint.has_known_mtime()
291                && (!need_complexity || !cached.complexity.is_empty())
292            {
293                return ParseFileResult::cache_hit(cache::cached_to_module_opts(
294                    cached,
295                    file.id,
296                    need_complexity,
297                ));
298            }
299        }
300    }
301
302    let raw = match std::fs::read_to_string(&file.path) {
303        Ok(raw) => raw,
304        Err(error) => return ParseFileResult::read_failure(file, &error),
305    };
306    let source = strip_bom(&raw);
307    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
308
309    if let Some(cached) = cached_by_path
310        && cached.content_hash == content_hash
311        && (!need_complexity || !cached.complexity.is_empty())
312    {
313        return ParseFileResult::cache_hit(cache::cached_to_module_opts(
314            cached,
315            file.id,
316            need_complexity,
317        ));
318    }
319
320    let parse_start = std::time::Instant::now();
321    let module = parse_source_to_module(file.id, &file.path, source, content_hash, need_complexity);
322    let parse_cpu_nanos = u64::try_from(parse_start.elapsed().as_nanos()).unwrap_or(u64::MAX);
323    ParseFileResult::cache_miss(module, parse_cpu_nanos)
324}
325
326/// Parse a single file and extract module information (without complexity).
327#[must_use]
328pub fn parse_single_file(file: &DiscoveredFile) -> Option<ModuleInfo> {
329    let raw = std::fs::read_to_string(&file.path).ok()?;
330    let source = strip_bom(&raw);
331    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
332    Some(parse_source_to_module(
333        file.id,
334        &file.path,
335        source,
336        content_hash,
337        false,
338    ))
339}
340
341/// Parse from in-memory content (for LSP, includes complexity).
342#[must_use]
343pub fn parse_from_content(file_id: FileId, path: &Path, content: &str) -> ModuleInfo {
344    let content = strip_bom(content);
345    let content_hash = xxhash_rust::xxh3::xxh3_64(content.as_bytes());
346    parse_source_to_module(file_id, path, content, content_hash, true)
347}
348
349#[cfg(all(test, not(miri)))]
350mod tests;