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