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