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