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//! User documentation for the supported file types is on [fallow.tools](https://fallow.tools/docs/analysis/file-types/):
8//!
9//! - [Supported file types](https://fallow.tools/docs/analysis/file-types/)
10//! - [CSS analysis](https://fallow.tools/docs/analysis/css-analysis/)
11//! - [Framework plugins](https://fallow.tools/docs/frameworks/built-in/)
12
13#![warn(missing_docs)]
14#![cfg_attr(not(test), deny(clippy::disallowed_methods))]
15#![cfg_attr(
16    test,
17    allow(
18        clippy::unwrap_used,
19        clippy::expect_used,
20        reason = "tests use unwrap and expect to keep fixture setup concise"
21    )
22)]
23
24pub mod alchemy;
25mod asset_url;
26pub mod astro;
27mod binding_references;
28pub mod cache;
29pub(crate) mod complexity;
30mod complexity_names;
31mod component_contracts;
32pub(crate) mod cost;
33pub mod css;
34pub mod css_classes;
35mod css_composes;
36pub mod css_in_js;
37mod css_mask;
38mod css_masked_bytes;
39pub mod css_metrics;
40mod css_module_classes;
41mod css_url;
42pub mod dom_classes;
43pub mod effect_facts;
44mod effect_schema;
45pub mod federation_runtime;
46pub mod flags;
47mod function_body;
48mod function_contracts;
49mod function_hash;
50mod generated_file;
51pub mod glimmer;
52pub(crate) mod graphql;
53pub(crate) mod html;
54mod iconify;
55pub mod inventory;
56pub mod js_text;
57mod jsdoc_attach;
58mod jsdoc_deprecated;
59mod literal_membership;
60pub mod mdx;
61mod module_info;
62mod module_parse;
63mod namespace_member_uses;
64mod nesting;
65pub mod og_image;
66mod opaque_loads;
67mod parse;
68mod parse_degradation;
69mod parse_options;
70pub mod sfc;
71pub mod sfc_css;
72mod sfc_props;
73mod sfc_template;
74mod shared_state;
75pub mod similar_code;
76mod sink_identity;
77mod source_map;
78mod stack;
79mod style_tokens;
80pub mod suppress;
81mod suppress_literals;
82/// Tailwind CSS arbitrary-value detection.
83pub mod tailwind;
84pub(crate) mod template_complexity;
85mod template_expression_scan;
86mod template_usage;
87/// Visitor utilities for AST extraction.
88pub mod visitor;
89
90use std::path::Path;
91use std::sync::atomic::{AtomicBool, Ordering};
92
93use rayon::prelude::*;
94
95use cache::CacheStore;
96use fallow_types::discover::{DiscoveredFile, FileId};
97
98pub use fallow_types::extract::{
99    AngularComponentFieldArrayTypeFact, AngularTemplateMemberAccessFact, AngularThisSpreadFact,
100    ClassHeritageInfo, ClassThisMemberAccessFact, ClassThisWholeObjectUseFact,
101    ComputedEnumKeyUseFact, DefaultImportWholeObjectUseFact, DynamicCustomElementRenderFact,
102    DynamicImportInfo, DynamicImportPattern, ExportInfo, ExportName,
103    ExportedObjectInstancePropertyFact, FactoryCallMemberAccessFact, FactoryFnMemberAccessFact,
104    FactoryFnWholeObjectFact, FactoryPropertySource, FactoryReturnExport,
105    FactoryReturnObjectPropertyAccessFact, FactoryReturnObjectPropertySourceFact,
106    FactoryReturnObjectShapeExport, FlagPatterns, FluentChainMemberAccessFact,
107    FluentChainNewMemberAccessFact, ImportInfo, ImportedName, InstanceExportBindingFact,
108    LocalTypeDeclaration, MemberAccess, MemberInfo, MemberKind, ModuleInfo, ModuleLoadMechanism,
109    ParseResult, PlaywrightConditionalFixtureDefinitionFact, PlaywrightFixtureAliasFact,
110    PlaywrightFixtureDefinitionFact, PlaywrightFixtureTypeFact, PlaywrightFixtureUseFact,
111    PlaywrightTestBindingFact, PublicSignatureTypeReference, QualifiedClassMemberAccessFact,
112    ReExportInfo, RequireCallInfo, RequiredTypeMemberFact, SemanticFact, SourceParseDegradation,
113    SourceReadFailure, StringEnumMemberValueFact, TypeAliasSurfaceTargetFact, TypeMemberTypeEntry,
114    TypedPropertyMemberAccessFact, VisibilityTag, VitestModuleMockAction,
115    VitestModuleMockOperationFact, compute_line_offsets,
116};
117
118pub use astro::{
119    extract_astro_frontmatter, extract_astro_style_regions, extract_astro_template_regions,
120};
121pub use css::{
122    StylesheetTokens, ThemeScan, ThemeTokenDef, extract_apply_tokens, extract_apply_tokens_located,
123    extract_css_module_exports, extract_css_var_reads_located, scan_stylesheet_tokens,
124    scan_theme_blocks,
125};
126pub use css_classes::{
127    MarkupClassScan, MarkupClassToken, is_edit_distance_one, is_typo_edit, scan_markup_class_tokens,
128};
129pub use css_in_js::{
130    ConsumerQuery, CssInJsObjectSheets, CssInJsToken, CssInJsTokenDef, CssInJsTokenOrigin,
131    TokenConsumerHit, css_in_js_consumer_scan, css_in_js_object_sheets, css_in_js_theme_token_defs,
132    css_in_js_token_defs, css_in_js_virtual_stylesheet,
133};
134pub use css_metrics::{compute_css_analytics, parse_css_color_rgb};
135pub use dom_classes::{DomClassScan, scan_dom_class_values};
136pub use function_contracts::{ParameterCondition, parameter_conditions};
137pub use generated_file::is_generated_file;
138pub use glimmer::{is_glimmer_file, strip_glimmer_templates};
139pub use js_text::JsText;
140pub use mdx::{extract_mdx_statements, extract_mdx_statements_mapped};
141pub(crate) use nesting::parse_style_bounded;
142pub use nesting::{MAX_NESTING_DEPTH, parse_bounded, parse_bounded_or_default};
143pub use sfc::{
144    SourceRegion, extract_sfc_scripts, extract_sfc_styles, extract_sfc_template_regions,
145    is_sfc_file, sfc_merged_script_source,
146};
147pub use sfc_css::{
148    scoped_unused_classes, sfc_preprocessor_virtual_stylesheet, sfc_virtual_stylesheet,
149};
150pub use similar_code::extract_similar_code_functions;
151pub use sink_identity::sink_identity_text;
152pub use source_map::{ExtractionResult, ScriptSection, embedded_script_sections};
153pub use stack::register_thread_stack;
154pub use suppress_literals::parse_suppressions_for_file;
155pub use tailwind::{TailwindArbitraryUse, scan_tailwind_arbitrary_values};
156pub use template_usage::TEMPLATE_SINK_CALLEE_PREFIX;
157
158#[expect(
159    clippy::expect_used,
160    reason = "static regex patterns are hard-coded analyzer invariants covered by extraction tests"
161)]
162fn static_regex(pattern: &str) -> regex::Regex {
163    regex::Regex::new(pattern).expect("static regex pattern should compile")
164}
165
166#[cfg(test)]
167use module_parse::parse_source_to_module_with_mode;
168pub use module_parse::{parse_source_to_module, parse_source_to_module_with_flags};
169
170/// Leading UTF-8 byte order mark codepoint.
171///
172/// Windows editors (Notepad, older VS settings, some IDE plugins) emit a UTF-8
173/// BOM at the start of source files. fallow's contract is "UTF-8 with or
174/// without BOM; line offsets are computed against the post-BOM view; the BOM,
175/// if present on input, is preserved on output by `fallow fix`."
176const BOM_CHAR: char = '\u{FEFF}';
177// Small, cache-hot inputs are faster on one thread than through Rayon setup.
178// Larger file sets still use parallel parsing where parse work dominates.
179const PARALLEL_PARSE_FILE_THRESHOLD: usize = 32;
180
181/// Strip the leading UTF-8 BOM if present.
182///
183/// Called at every file-read entry point in this crate so the rest of the
184/// pipeline (content hash, `compute_line_offsets`, oxc parser, downstream
185/// analyses) sees a consistent post-BOM view. Mirrors the
186/// `fallow_config` layer (`config_writer.rs::BOM`) so config-shaped sources
187/// and source-code-shaped sources are processed symmetrically. See issue #475.
188///
189/// Call it once for each source. Only the first U+FEFF of a file is the
190/// mark, so a second call removes a U+FEFF that is source text.
191#[must_use]
192fn strip_bom(source: &str) -> &str {
193    source.strip_prefix(BOM_CHAR).unwrap_or(source)
194}
195
196/// The optional facts that a parse run must give for each module.
197#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
198pub struct ParseNeeds {
199    /// Per-function complexity, for the `health` command.
200    pub complexity: bool,
201    /// The call facts (`ModuleInfo::function_contracts`), for the rules that
202    /// read them.
203    pub call_facts: bool,
204}
205
206/// Parse all files, extracting imports and exports.
207///
208/// Small file sets use a sequential fast path to avoid parallel scheduling
209/// overhead; larger file sets use parallel extraction.
210/// Uses the cache to skip reparsing files whose content hasn't changed.
211///
212/// When `need_complexity` is true, per-function cyclomatic/cognitive complexity
213/// metrics are computed during parsing (needed by the `health` command).
214/// Pass `false` for dead-code analysis where complexity data is unused.
215///
216/// Flag detection uses the built-in patterns only. A caller with a resolved
217/// config uses [`parse_all_files_cancellable`] with the config's patterns,
218/// because the cache keys on them.
219///
220/// The modules carry no call facts, as in a run of the default config. A
221/// caller that reads them uses [`parse_all_files_with_mode`].
222pub fn parse_all_files(
223    files: &[DiscoveredFile],
224    cache: Option<&CacheStore>,
225    need_complexity: bool,
226) -> ParseResult {
227    parse_all_files_cancellable(
228        files,
229        cache,
230        need_complexity,
231        None,
232        &FlagPatterns::default(),
233    )
234}
235
236/// Parse all files, abandoning the remaining ones once `cancellation` is set.
237///
238/// Rayon's `map`/`collect` cannot short-circuit, so cancellation makes the
239/// per-file body a no-op instead of stopping the iteration: the scheduled
240/// items still drain, but at one atomic load each. The returned
241/// [`ParseResult`] is therefore truncated whenever the token flipped, and
242/// callers must treat a set token as a failed run rather than as a project
243/// with fewer modules.
244///
245/// `flag_patterns` are the user flag patterns that detection applies on top
246/// of the built-in ones. They must match the patterns the cache was keyed on.
247/// The modules carry no call facts, as for [`parse_all_files`].
248pub fn parse_all_files_cancellable(
249    files: &[DiscoveredFile],
250    cache: Option<&CacheStore>,
251    need_complexity: bool,
252    cancellation: Option<&AtomicBool>,
253    flag_patterns: &FlagPatterns,
254) -> ParseResult {
255    parse_all_files_with_mode(
256        files,
257        cache,
258        ParseNeeds {
259            complexity: need_complexity,
260            call_facts: false,
261        },
262        cancellation,
263        flag_patterns,
264        fallow_types::shared_state::ExtractionMode::Standard,
265    )
266}
267
268/// Parse files with an explicit optional-fact mode matching the cache identity.
269///
270/// When `needs.call_facts` is `false`, the returned modules carry no call
271/// facts (`function_contracts` is `None`), and a cache hit does not decode
272/// them. When it is `true`, a cache entry that did not record call facts is a
273/// miss, so each returned module has its call facts.
274pub fn parse_all_files_with_mode(
275    files: &[DiscoveredFile],
276    cache: Option<&CacheStore>,
277    needs: ParseNeeds,
278    cancellation: Option<&AtomicBool>,
279    flag_patterns: &FlagPatterns,
280    mode: fallow_types::shared_state::ExtractionMode,
281) -> ParseResult {
282    let parse_one = |file: &DiscoveredFile| {
283        if cancellation.is_some_and(|cancelled| cancelled.load(Ordering::SeqCst)) {
284            return ParseFileResult::default();
285        }
286        parse_single_file_cached(file, cache, needs, flag_patterns, mode)
287    };
288    let results: Vec<ParseFileResult> = if files.len() <= PARALLEL_PARSE_FILE_THRESHOLD {
289        files.iter().map(parse_one).collect()
290    } else {
291        files.par_iter().map(parse_one).collect()
292    };
293
294    let mut modules = Vec::with_capacity(results.len());
295    let mut read_failures = Vec::new();
296    let mut parse_degradations = Vec::new();
297    let mut hits = 0usize;
298    let mut misses = 0usize;
299    let mut parse_cpu_nanos = 0u64;
300    let mut files_read = 0u64;
301    let mut source_bytes_read = 0u64;
302    let mut css_masked_bytes = 0u64;
303
304    // `results` is a positional map over `files`, so zipping recovers the path
305    // for a module without carrying one on `ModuleInfo`.
306    for (file, result) in files.iter().zip(results) {
307        hits += result.cache_hits;
308        misses += result.cache_misses;
309        parse_cpu_nanos = parse_cpu_nanos.saturating_add(result.parse_cpu_nanos);
310        if let Some(bytes) = result.source_bytes_read {
311            files_read += 1;
312            source_bytes_read += bytes;
313        }
314        css_masked_bytes += result.css_masked_bytes;
315        if let Some(module) = result.module {
316            if module.parse_error_count > 0 {
317                parse_degradations.push(SourceParseDegradation {
318                    file_id: module.file_id,
319                    path: file.path.clone(),
320                    error_count: module.parse_error_count,
321                    panicked: module.parse_panicked,
322                    nesting_limit: module.parse_nesting_too_deep.then_some(MAX_NESTING_DEPTH),
323                });
324            }
325            modules.push(module);
326        }
327        if let Some(failure) = result.read_failure {
328            read_failures.push(failure);
329        }
330    }
331
332    if hits > 0 || misses > 0 {
333        tracing::info!(
334            cache_hits = hits,
335            cache_misses = misses,
336            "incremental cache stats"
337        );
338    }
339
340    ParseResult {
341        modules,
342        read_failures,
343        parse_degradations,
344        cache_hits: hits,
345        cache_misses: misses,
346        parse_cpu_ms: parse_cpu_nanos as f64 / 1_000_000.0,
347        files_read,
348        source_bytes_read,
349        css_masked_bytes,
350    }
351}
352
353#[derive(Default)]
354struct ParseFileResult {
355    module: Option<ModuleInfo>,
356    read_failure: Option<SourceReadFailure>,
357    cache_hits: usize,
358    cache_misses: usize,
359    parse_cpu_nanos: u64,
360    /// Source bytes read from disk for this file, or `None` when the file was
361    /// served from cache metadata without a read.
362    source_bytes_read: Option<u64>,
363    /// Source bytes that the CSS comment mask read during the parse.
364    css_masked_bytes: u64,
365}
366
367impl ParseFileResult {
368    fn cache_hit(module: ModuleInfo) -> Self {
369        Self {
370            module: Some(module),
371            read_failure: None,
372            cache_hits: 1,
373            cache_misses: 0,
374            parse_cpu_nanos: 0,
375            source_bytes_read: None,
376            css_masked_bytes: 0,
377        }
378    }
379
380    fn cache_miss(module: ModuleInfo, parse_cpu_nanos: u64) -> Self {
381        Self {
382            module: Some(module),
383            read_failure: None,
384            cache_hits: 0,
385            cache_misses: 1,
386            parse_cpu_nanos,
387            source_bytes_read: None,
388            css_masked_bytes: 0,
389        }
390    }
391
392    const fn with_source_bytes_read(mut self, bytes: usize) -> Self {
393        self.source_bytes_read = Some(bytes as u64);
394        self
395    }
396
397    fn read_failure(file: &DiscoveredFile, error: &std::io::Error) -> Self {
398        Self {
399            module: None,
400            read_failure: Some(SourceReadFailure {
401                file_id: file.id,
402                path: file.path.clone(),
403                error: error.to_string(),
404            }),
405            cache_hits: 0,
406            cache_misses: 0,
407            parse_cpu_nanos: 0,
408            source_bytes_read: None,
409            css_masked_bytes: 0,
410        }
411    }
412}
413
414/// Parse a single file, consulting the cache first.
415///
416/// Cache validation strategy (fast path -> slow path):
417/// 1. Open the file so unreadable sources cannot use stale cached analysis
418/// 2. Read mtime + ctime + size from the open handle
419/// 3. If all three match the cached entry -> cache hit, return immediately
420/// 4. Otherwise -> read file, compute content hash
421/// 5. If content hash matches cached entry -> cache hit (file was rewritten or
422///    `touch`ed but its content is unchanged)
423/// 6. Otherwise -> cache miss, full parse
424///
425/// Step 3 requires ctime as well as mtime because mtime is writer-controlled:
426/// a same-length rewrite whose mtime is restored (`touch -r`, a codemod, a
427/// `git checkout` of an equal-length revision) leaves `(mtime, size)`
428/// unchanged, and serving the cached module for it means reporting the OLD
429/// file's unused exports with an auto-fixable `remove-export` action. A file
430/// whose ctime moved falls through to step 4 and still hits on the content
431/// hash, so the cost of the stricter gate is one read, not a reparse.
432///
433/// Step 3 also needs a stored fingerprint that settled before the run that
434/// wrote it read the file. A same-length write in the same timestamp tick as
435/// the previous write keeps mtime, ctime and size, so the cache writer stores
436/// a recent fingerprint without its ctime
437/// (`SourceFingerprint::for_content_read_at`). Such an entry never matches at
438/// step 3, and the next run compares the content hash.
439fn parse_single_file_cached(
440    file: &DiscoveredFile,
441    cache: Option<&CacheStore>,
442    needs: ParseNeeds,
443    flag_patterns: &FlagPatterns,
444    mode: fallow_types::shared_state::ExtractionMode,
445) -> ParseFileResult {
446    let ParseNeeds {
447        complexity: need_complexity,
448        call_facts: need_call_facts,
449    } = needs;
450    let cached_by_path = cache.and_then(|store| store.get_by_path_only(&file.path));
451
452    if let Some(cached) = cached_by_path
453        && cached.file_size == file.size_bytes
454    {
455        let source_file = match std::fs::File::open(&file.path) {
456            Ok(source_file) => source_file,
457            Err(error) => return ParseFileResult::read_failure(file, &error),
458        };
459        if let Ok(metadata) = source_file.metadata()
460            && metadata.len() == cached.file_size
461        {
462            let fingerprint =
463                fallow_types::source_fingerprint::SourceFingerprint::from_metadata(&metadata);
464            if cached.source_fingerprint() == fingerprint
465                && fingerprint.is_trustworthy_without_content()
466                && (!need_complexity || cached.complexity_extracted)
467                && let Some(module) =
468                    cache::cached_hit_to_module(cached, file.id, need_complexity, need_call_facts)
469            {
470                return ParseFileResult::cache_hit(module);
471            }
472        }
473    }
474
475    let raw = match std::fs::read_to_string(&file.path) {
476        Ok(raw) => raw,
477        Err(error) => return ParseFileResult::read_failure(file, &error),
478    };
479    let source = strip_bom(&raw);
480    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
481
482    if let Some(cached) = cached_by_path
483        && cached.content_hash == content_hash
484        && (!need_complexity || cached.complexity_extracted)
485        && let Some(module) =
486            cache::cached_hit_to_module(cached, file.id, need_complexity, need_call_facts)
487    {
488        return ParseFileResult::cache_hit(module).with_source_bytes_read(raw.len());
489    }
490
491    let parse_start = std::time::Instant::now();
492    // Drop a count that a scan outside a parse left on this thread.
493    css_masked_bytes::take();
494    let mut module = module_parse::parse_source_without_bom(
495        file.id,
496        &file.path,
497        source,
498        content_hash,
499        need_complexity,
500        &module_parse::ExtractionOptions {
501            flag_patterns,
502            mode,
503        },
504    );
505    if !need_call_facts {
506        // A cache hit of the same run gives no call facts, so a parsed module
507        // must not give them either.
508        module.function_contracts = None;
509    }
510    let parse_cpu_nanos = u64::try_from(parse_start.elapsed().as_nanos()).unwrap_or(u64::MAX);
511    let mut result =
512        ParseFileResult::cache_miss(module, parse_cpu_nanos).with_source_bytes_read(raw.len());
513    result.css_masked_bytes = css_masked_bytes::take();
514    result
515}
516
517/// Parse a single file and extract module information (without complexity).
518#[must_use]
519pub fn parse_single_file(file: &DiscoveredFile) -> Option<ModuleInfo> {
520    let raw = std::fs::read_to_string(&file.path).ok()?;
521    let source = strip_bom(&raw);
522    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
523    Some(module_parse::parse_source_without_bom(
524        file.id,
525        &file.path,
526        source,
527        content_hash,
528        false,
529        &module_parse::ExtractionOptions {
530            flag_patterns: &FlagPatterns::default(),
531            mode: fallow_types::shared_state::ExtractionMode::Standard,
532        },
533    ))
534}
535
536/// Parse from in-memory content (for LSP, includes complexity).
537#[must_use]
538pub fn parse_from_content(file_id: FileId, path: &Path, content: &str) -> ModuleInfo {
539    let content = strip_bom(content);
540    let content_hash = xxhash_rust::xxh3::xxh3_64(content.as_bytes());
541    module_parse::parse_source_without_bom(
542        file_id,
543        path,
544        content,
545        content_hash,
546        true,
547        &module_parse::ExtractionOptions {
548            flag_patterns: &FlagPatterns::default(),
549            mode: fallow_types::shared_state::ExtractionMode::Standard,
550        },
551    )
552}
553
554#[cfg(all(test, not(miri)))]
555mod tests;
556#[cfg(all(test, not(miri)))]
557mod unicode_span_oracle;