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