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    /// The feature flag facts (`ModuleInfo::flag_uses` and
206    /// `ModuleInfo::flag_registry_facts`), for the feature flag report.
207    pub flags: bool,
208    /// The component contract facts (`ModuleInfo::component_contracts`), for
209    /// the `absent-component-prop` rule.
210    pub component_contracts: bool,
211}
212
213impl ParseNeeds {
214    /// Every optional fact. A caller without a resolved config uses this to
215    /// get a full module.
216    pub const ALL: Self = Self {
217        complexity: true,
218        call_facts: true,
219        flags: true,
220        component_contracts: true,
221    };
222
223    /// Whether a parse that collected the facts of `self` gives every fact
224    /// that `needs` asks for.
225    #[must_use]
226    pub const fn covers(self, needs: Self) -> bool {
227        (self.complexity || !needs.complexity)
228            && (self.call_facts || !needs.call_facts)
229            && (self.flags || !needs.flags)
230            && (self.component_contracts || !needs.component_contracts)
231    }
232}
233
234/// Parse all files, extracting imports and exports.
235///
236/// Small file sets use a sequential fast path to avoid parallel scheduling
237/// overhead; larger file sets use parallel extraction.
238/// Uses the cache to skip reparsing files whose content hasn't changed.
239///
240/// When `need_complexity` is true, per-function cyclomatic/cognitive complexity
241/// metrics are computed during parsing (needed by the `health` command).
242/// Pass `false` for dead-code analysis where complexity data is unused.
243///
244/// Flag detection uses the built-in patterns only. A caller with a resolved
245/// config uses [`parse_all_files_cancellable`] with the config's patterns,
246/// because the cache keys on them.
247///
248/// The modules carry no call facts, as in a run of the default config. A
249/// caller that reads them uses [`parse_all_files_with_mode`].
250pub fn parse_all_files(
251    files: &[DiscoveredFile],
252    cache: Option<&CacheStore>,
253    need_complexity: bool,
254) -> ParseResult {
255    parse_all_files_cancellable(
256        files,
257        cache,
258        need_complexity,
259        None,
260        &FlagPatterns::default(),
261    )
262}
263
264/// Parse all files, abandoning the remaining ones once `cancellation` is set.
265///
266/// Rayon's `map`/`collect` cannot short-circuit, so cancellation makes the
267/// per-file body a no-op instead of stopping the iteration: the scheduled
268/// items still drain, but at one atomic load each. The returned
269/// [`ParseResult`] is therefore truncated whenever the token flipped, and
270/// callers must treat a set token as a failed run rather than as a project
271/// with fewer modules.
272///
273/// `flag_patterns` are the user flag patterns that detection applies on top
274/// of the built-in ones. They must match the patterns the cache was keyed on.
275/// The modules carry no call facts, as for [`parse_all_files`].
276pub fn parse_all_files_cancellable(
277    files: &[DiscoveredFile],
278    cache: Option<&CacheStore>,
279    need_complexity: bool,
280    cancellation: Option<&AtomicBool>,
281    flag_patterns: &FlagPatterns,
282) -> ParseResult {
283    parse_all_files_with_mode(
284        files,
285        cache,
286        ParseNeeds {
287            complexity: need_complexity,
288            call_facts: false,
289            flags: true,
290            component_contracts: true,
291        },
292        cancellation,
293        flag_patterns,
294        fallow_types::shared_state::ExtractionMode::Standard,
295    )
296}
297
298/// Parse files with an explicit optional-fact mode matching the cache identity.
299///
300/// When `needs.call_facts` is `false`, the returned modules carry no call
301/// facts (`function_contracts` is `None`), and a cache hit does not decode
302/// them. When it is `true`, a cache entry that did not record call facts is a
303/// miss, so each returned module has its call facts.
304pub fn parse_all_files_with_mode(
305    files: &[DiscoveredFile],
306    cache: Option<&CacheStore>,
307    needs: ParseNeeds,
308    cancellation: Option<&AtomicBool>,
309    flag_patterns: &FlagPatterns,
310    mode: fallow_types::shared_state::ExtractionMode,
311) -> ParseResult {
312    let parse_one = |file: &DiscoveredFile| {
313        if cancellation.is_some_and(|cancelled| cancelled.load(Ordering::SeqCst)) {
314            return ParseFileResult::default();
315        }
316        parse_single_file_cached(file, cache, needs, flag_patterns, mode)
317    };
318    let results: Vec<ParseFileResult> = if files.len() <= PARALLEL_PARSE_FILE_THRESHOLD {
319        files.iter().map(parse_one).collect()
320    } else {
321        files.par_iter().map(parse_one).collect()
322    };
323
324    let mut modules = Vec::with_capacity(results.len());
325    let mut read_failures = Vec::new();
326    let mut parse_degradations = Vec::new();
327    let mut hits = 0usize;
328    let mut misses = 0usize;
329    let mut parse_cpu_nanos = 0u64;
330    let mut files_read = 0u64;
331    let mut source_bytes_read = 0u64;
332    let mut css_masked_bytes = 0u64;
333    let mut metadata_hits = Vec::new();
334
335    // `results` is a positional map over `files`, so zipping recovers the path
336    // for a module without carrying one on `ModuleInfo`.
337    for (file, result) in files.iter().zip(results) {
338        hits += result.cache_hits;
339        misses += result.cache_misses;
340        parse_cpu_nanos = parse_cpu_nanos.saturating_add(result.parse_cpu_nanos);
341        if let Some(bytes) = result.source_bytes_read {
342            files_read += 1;
343            source_bytes_read += bytes;
344        } else if result.cache_hits == 1 && result.module.is_some() {
345            metadata_hits.push(file.id);
346        }
347        css_masked_bytes += result.css_masked_bytes;
348        if let Some(module) = result.module {
349            if module.parse_error_count > 0 {
350                parse_degradations.push(SourceParseDegradation {
351                    file_id: module.file_id,
352                    path: file.path.clone(),
353                    error_count: module.parse_error_count,
354                    panicked: module.parse_panicked,
355                    nesting_limit: module.parse_nesting_too_deep.then_some(MAX_NESTING_DEPTH),
356                });
357            }
358            modules.push(module);
359        }
360        if let Some(failure) = result.read_failure {
361            read_failures.push(failure);
362        }
363    }
364
365    // A caller can pass the files in any id order, and a cache writer looks
366    // the ids up by binary search.
367    metadata_hits.sort_unstable_by_key(|id| id.0);
368
369    if hits > 0 || misses > 0 {
370        tracing::info!(
371            cache_hits = hits,
372            cache_misses = misses,
373            "incremental cache stats"
374        );
375    }
376
377    ParseResult {
378        modules,
379        read_failures,
380        parse_degradations,
381        cache_hits: hits,
382        cache_misses: misses,
383        parse_cpu_ms: parse_cpu_nanos as f64 / 1_000_000.0,
384        files_read,
385        source_bytes_read,
386        css_masked_bytes,
387        metadata_hits,
388    }
389}
390
391/// Whether the parse served `file_id` from cache metadata, given the sorted
392/// [`ParseResult::metadata_hits`] of that parse.
393///
394/// A cache writer can keep the stored fingerprint of such a file and skip its
395/// metadata read. The parse found that the stored fingerprint has a ctime and
396/// equals the metadata of the open file, so the entry is current. A write after
397/// that check moves the ctime. The next run then compares the content hash, as
398/// it does when the writer stores the new metadata.
399#[must_use]
400pub fn is_metadata_hit(metadata_hits: &[FileId], file_id: FileId) -> bool {
401    metadata_hits
402        .binary_search_by_key(&file_id.0, |id| id.0)
403        .is_ok()
404}
405
406#[derive(Default)]
407struct ParseFileResult {
408    module: Option<ModuleInfo>,
409    read_failure: Option<SourceReadFailure>,
410    cache_hits: usize,
411    cache_misses: usize,
412    parse_cpu_nanos: u64,
413    /// Source bytes read from disk for this file, or `None` when the file was
414    /// served from cache metadata without a read.
415    source_bytes_read: Option<u64>,
416    /// Source bytes that the CSS comment mask read during the parse.
417    css_masked_bytes: u64,
418}
419
420impl ParseFileResult {
421    /// A hit from metadata alone. A hit that read the source adds
422    /// `with_source_bytes_read`, so a hit without read bytes is a metadata hit.
423    fn cache_hit(module: ModuleInfo) -> Self {
424        Self {
425            module: Some(module),
426            read_failure: None,
427            cache_hits: 1,
428            cache_misses: 0,
429            parse_cpu_nanos: 0,
430            source_bytes_read: None,
431            css_masked_bytes: 0,
432        }
433    }
434
435    fn cache_miss(module: ModuleInfo, parse_cpu_nanos: u64) -> Self {
436        Self {
437            module: Some(module),
438            read_failure: None,
439            cache_hits: 0,
440            cache_misses: 1,
441            parse_cpu_nanos,
442            source_bytes_read: None,
443            css_masked_bytes: 0,
444        }
445    }
446
447    const fn with_source_bytes_read(mut self, bytes: usize) -> Self {
448        self.source_bytes_read = Some(bytes as u64);
449        self
450    }
451
452    fn read_failure(file: &DiscoveredFile, error: &std::io::Error) -> Self {
453        Self {
454            module: None,
455            read_failure: Some(SourceReadFailure {
456                file_id: file.id,
457                path: file.path.clone(),
458                error: error.to_string(),
459            }),
460            cache_hits: 0,
461            cache_misses: 0,
462            parse_cpu_nanos: 0,
463            source_bytes_read: None,
464            css_masked_bytes: 0,
465        }
466    }
467}
468
469/// Parse a single file, consulting the cache first.
470///
471/// Cache validation strategy (fast path -> slow path):
472/// 1. Open the file so unreadable sources cannot use stale cached analysis
473/// 2. Read mtime + ctime + size from the open handle
474/// 3. If all three match the cached entry -> cache hit, return immediately
475/// 4. Otherwise -> read file, compute content hash
476/// 5. If content hash matches cached entry -> cache hit (file was rewritten or
477///    `touch`ed but its content is unchanged)
478/// 6. Otherwise -> cache miss, full parse
479///
480/// Step 3 requires ctime as well as mtime because mtime is writer-controlled:
481/// a same-length rewrite whose mtime is restored (`touch -r`, a codemod, a
482/// `git checkout` of an equal-length revision) leaves `(mtime, size)`
483/// unchanged, and serving the cached module for it means reporting the OLD
484/// file's unused exports with an auto-fixable `remove-export` action. A file
485/// whose ctime moved falls through to step 4 and still hits on the content
486/// hash, so the cost of the stricter gate is one read, not a reparse.
487///
488/// Step 3 also needs a stored fingerprint that settled before the run that
489/// wrote it read the file. A same-length write in the same timestamp tick as
490/// the previous write keeps mtime, ctime and size, so the cache writer stores
491/// a recent fingerprint without its ctime
492/// (`SourceFingerprint::for_content_read_at`). Such an entry never matches at
493/// step 3, and the next run compares the content hash.
494fn parse_single_file_cached(
495    file: &DiscoveredFile,
496    cache: Option<&CacheStore>,
497    needs: ParseNeeds,
498    flag_patterns: &FlagPatterns,
499    mode: fallow_types::shared_state::ExtractionMode,
500) -> ParseFileResult {
501    let cached_by_path = cache.and_then(|store| store.get_by_path_only(&file.path));
502
503    if let Some(cached) = cached_by_path
504        && cached.file_size == file.size_bytes
505    {
506        let source_file = match std::fs::File::open(&file.path) {
507            Ok(source_file) => source_file,
508            Err(error) => return ParseFileResult::read_failure(file, &error),
509        };
510        if let Ok(metadata) = source_file.metadata()
511            && metadata.len() == cached.file_size
512        {
513            let fingerprint =
514                fallow_types::source_fingerprint::SourceFingerprint::from_metadata(&metadata);
515            if cached.source_fingerprint() == fingerprint
516                && fingerprint.is_trustworthy_without_content()
517                && let Some(module) = cache::cached_hit_to_module(cached, file.id, needs)
518            {
519                return ParseFileResult::cache_hit(module);
520            }
521        }
522    }
523
524    let raw = match std::fs::read_to_string(&file.path) {
525        Ok(raw) => raw,
526        Err(error) => return ParseFileResult::read_failure(file, &error),
527    };
528    let source = strip_bom(&raw);
529    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
530
531    if let Some(cached) = cached_by_path
532        && cached.content_hash == content_hash
533        && let Some(module) = cache::cached_hit_to_module(cached, file.id, needs)
534    {
535        return ParseFileResult::cache_hit(module).with_source_bytes_read(raw.len());
536    }
537
538    let parse_start = std::time::Instant::now();
539    // Drop a count that a scan outside a parse left on this thread.
540    css_masked_bytes::take();
541    let module = module_parse::parse_source_without_bom(
542        file.id,
543        &file.path,
544        source,
545        content_hash,
546        needs.complexity,
547        &module_parse::ExtractionOptions {
548            flag_patterns,
549            mode,
550            // A cache hit of the same run gives none of the facts that the run
551            // does not need, so a parsed module must not give them either.
552            call_facts: needs.call_facts,
553            flags: needs.flags,
554            component_contracts: needs.component_contracts,
555        },
556    );
557    let parse_cpu_nanos = u64::try_from(parse_start.elapsed().as_nanos()).unwrap_or(u64::MAX);
558    let mut result =
559        ParseFileResult::cache_miss(module, parse_cpu_nanos).with_source_bytes_read(raw.len());
560    result.css_masked_bytes = css_masked_bytes::take();
561    result
562}
563
564/// Parse a single file and extract module information (without complexity).
565#[must_use]
566pub fn parse_single_file(file: &DiscoveredFile) -> Option<ModuleInfo> {
567    let raw = std::fs::read_to_string(&file.path).ok()?;
568    let source = strip_bom(&raw);
569    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
570    Some(module_parse::parse_source_without_bom(
571        file.id,
572        &file.path,
573        source,
574        content_hash,
575        false,
576        &module_parse::ExtractionOptions {
577            flag_patterns: &FlagPatterns::default(),
578            mode: fallow_types::shared_state::ExtractionMode::Standard,
579            call_facts: true,
580            flags: true,
581            component_contracts: true,
582        },
583    ))
584}
585
586/// Parse from in-memory content (for LSP, includes complexity).
587#[must_use]
588pub fn parse_from_content(file_id: FileId, path: &Path, content: &str) -> ModuleInfo {
589    let content = strip_bom(content);
590    let content_hash = xxhash_rust::xxh3::xxh3_64(content.as_bytes());
591    module_parse::parse_source_without_bom(
592        file_id,
593        path,
594        content,
595        content_hash,
596        true,
597        &module_parse::ExtractionOptions {
598            flag_patterns: &FlagPatterns::default(),
599            mode: fallow_types::shared_state::ExtractionMode::Standard,
600            call_facts: true,
601            flags: true,
602            component_contracts: true,
603        },
604    )
605}
606
607#[cfg(all(test, not(miri)))]
608mod tests;
609#[cfg(all(test, not(miri)))]
610mod unicode_span_oracle;