Skip to main content

fallow_extract/
lib.rs

1//! Parsing and extraction engine for the fallow codebase analyzer.
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
9pub mod astro;
10pub mod cache;
11pub(crate) mod complexity;
12pub mod css;
13pub mod flags;
14pub mod html;
15pub mod mdx;
16mod parse;
17pub mod sfc;
18mod sfc_template;
19pub mod suppress;
20mod template_usage;
21pub mod visitor;
22
23use std::path::Path;
24
25use rayon::prelude::*;
26
27use cache::CacheStore;
28use fallow_types::discover::{DiscoveredFile, FileId};
29
30// Re-export all extract types from fallow-types
31pub use fallow_types::extract::{
32    DynamicImportInfo, DynamicImportPattern, ExportInfo, ExportName, ImportInfo, ImportedName,
33    MemberAccess, MemberInfo, MemberKind, ModuleInfo, ParseResult, ReExportInfo, RequireCallInfo,
34    compute_line_offsets,
35};
36
37// Re-export extraction functions for internal use and fuzzing
38pub use astro::extract_astro_frontmatter;
39pub use css::extract_css_module_exports;
40pub use mdx::extract_mdx_statements;
41pub use sfc::{extract_sfc_scripts, is_sfc_file};
42pub use sfc_template::angular::ANGULAR_TPL_SENTINEL;
43
44use parse::parse_source_to_module;
45
46/// Parse all files in parallel, extracting imports and exports.
47/// Uses the cache to skip reparsing files whose content hasn't changed.
48///
49/// When `need_complexity` is true, per-function cyclomatic/cognitive complexity
50/// metrics are computed during parsing (needed by the `health` command).
51/// Pass `false` for dead-code analysis where complexity data is unused.
52pub fn parse_all_files(
53    files: &[DiscoveredFile],
54    cache: Option<&CacheStore>,
55    need_complexity: bool,
56) -> ParseResult {
57    use std::sync::atomic::{AtomicUsize, Ordering};
58    let cache_hits = AtomicUsize::new(0);
59    let cache_misses = AtomicUsize::new(0);
60
61    let modules: Vec<ModuleInfo> = files
62        .par_iter()
63        .filter_map(|file| {
64            parse_single_file_cached(file, cache, &cache_hits, &cache_misses, need_complexity)
65        })
66        .collect();
67
68    let hits = cache_hits.load(Ordering::Relaxed);
69    let misses = cache_misses.load(Ordering::Relaxed);
70    if hits > 0 || misses > 0 {
71        tracing::info!(
72            cache_hits = hits,
73            cache_misses = misses,
74            "incremental cache stats"
75        );
76    }
77
78    ParseResult {
79        modules,
80        cache_hits: hits,
81        cache_misses: misses,
82    }
83}
84
85/// Extract mtime (seconds since epoch) from file metadata.
86/// Returns 0 if mtime cannot be determined (pre-epoch, unsupported OS, etc.).
87fn mtime_secs(metadata: &std::fs::Metadata) -> u64 {
88    metadata
89        .modified()
90        .ok()
91        .and_then(|t| t.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
92        .map_or(0, |d| d.as_secs())
93}
94
95/// Parse a single file, consulting the cache first.
96///
97/// Cache validation strategy (fast path -> slow path):
98/// 1. `stat()` the file to get mtime + size (single syscall, no file read)
99/// 2. If mtime+size match the cached entry -> cache hit, return immediately
100/// 3. If mtime+size differ -> read file, compute content hash
101/// 4. If content hash matches cached entry -> cache hit (file was `touch`ed but unchanged)
102/// 5. Otherwise -> cache miss, full parse
103fn parse_single_file_cached(
104    file: &DiscoveredFile,
105    cache: Option<&CacheStore>,
106    cache_hits: &std::sync::atomic::AtomicUsize,
107    cache_misses: &std::sync::atomic::AtomicUsize,
108    need_complexity: bool,
109) -> Option<ModuleInfo> {
110    use std::sync::atomic::Ordering;
111
112    // Fast path: check mtime+size before reading file content.
113    // A single stat() syscall is ~100x cheaper than read()+hash().
114    if let Some(store) = cache
115        && let Ok(metadata) = std::fs::metadata(&file.path)
116    {
117        let mt = mtime_secs(&metadata);
118        let sz = metadata.len();
119        if let Some(cached) = store.get_by_metadata(&file.path, mt, sz) {
120            // When complexity is requested but the cached entry lacks it
121            // (populated by a prior `check` run), skip the cache and re-parse.
122            if !need_complexity || !cached.complexity.is_empty() {
123                cache_hits.fetch_add(1, Ordering::Relaxed);
124                return Some(cache::cached_to_module(cached, file.id));
125            }
126        }
127    }
128
129    // Slow path: read file content and compute content hash.
130    let source = std::fs::read_to_string(&file.path).ok()?;
131    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
132
133    // Check cache by content hash (handles touch/save-without-change)
134    if let Some(store) = cache
135        && let Some(cached) = store.get(&file.path, content_hash)
136        && (!need_complexity || !cached.complexity.is_empty())
137    {
138        cache_hits.fetch_add(1, Ordering::Relaxed);
139        return Some(cache::cached_to_module(cached, file.id));
140    }
141    cache_misses.fetch_add(1, Ordering::Relaxed);
142
143    // Cache miss — do a full parse
144    Some(parse_source_to_module(
145        file.id,
146        &file.path,
147        &source,
148        content_hash,
149        need_complexity,
150    ))
151}
152
153/// Parse a single file and extract module information (without complexity).
154#[must_use]
155pub fn parse_single_file(file: &DiscoveredFile) -> Option<ModuleInfo> {
156    let source = std::fs::read_to_string(&file.path).ok()?;
157    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
158    Some(parse_source_to_module(
159        file.id,
160        &file.path,
161        &source,
162        content_hash,
163        false,
164    ))
165}
166
167/// Parse from in-memory content (for LSP, includes complexity).
168#[must_use]
169pub fn parse_from_content(file_id: FileId, path: &Path, content: &str) -> ModuleInfo {
170    let content_hash = xxhash_rust::xxh3::xxh3_64(content.as_bytes());
171    parse_source_to_module(file_id, path, content, content_hash, true)
172}
173
174// Parser integration tests invoke Oxc under Miri which is ~1000x slower.
175// Unit tests in individual modules (visitor, suppress, sfc, css, etc.) still run.
176#[cfg(all(test, not(miri)))]
177mod tests;