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