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_metrics;
25pub mod flags;
26pub mod glimmer;
27pub mod graphql;
28pub mod html;
29pub mod iconify;
30pub mod inventory;
31pub mod mdx;
32mod parse;
33pub mod sfc;
34pub mod sfc_css;
35mod sfc_props;
36mod sfc_template;
37mod source_map;
38pub mod suppress;
39/// Tailwind CSS arbitrary-value detection.
40pub mod tailwind;
41pub(crate) mod template_complexity;
42mod template_usage;
43/// Visitor utilities for AST extraction.
44pub mod visitor;
45
46use std::path::Path;
47
48use rayon::prelude::*;
49
50use cache::CacheStore;
51use fallow_types::discover::{DiscoveredFile, FileId};
52
53pub use fallow_types::extract::{
54    ClassHeritageInfo, DynamicImportInfo, DynamicImportPattern, ExportInfo, ExportName, ImportInfo,
55    ImportedName, LocalTypeDeclaration, MemberAccess, MemberInfo, MemberKind, ModuleInfo,
56    ParseResult, PublicSignatureTypeReference, ReExportInfo, RequireCallInfo, VisibilityTag,
57    compute_line_offsets,
58};
59
60pub use astro::{
61    extract_astro_frontmatter, extract_astro_style_regions, extract_astro_template_regions,
62};
63pub use css::{
64    ThemeScan, ThemeTokenDef, extract_apply_tokens, extract_css_module_exports, scan_theme_blocks,
65};
66pub use css_classes::{
67    MarkupClassScan, MarkupClassToken, is_edit_distance_one, is_typo_edit, scan_markup_class_tokens,
68};
69pub use css_metrics::compute_css_analytics;
70pub use glimmer::{is_glimmer_file, strip_glimmer_templates};
71pub use mdx::extract_mdx_statements;
72pub use sfc::{
73    SourceRegion, extract_sfc_scripts, extract_sfc_styles, extract_sfc_template_regions,
74    is_sfc_file,
75};
76pub use sfc_css::{scoped_unused_classes, sfc_virtual_stylesheet};
77pub use sfc_template::angular::{ANGULAR_THIS_SPREAD_SENTINEL, ANGULAR_TPL_SENTINEL};
78pub use tailwind::{TailwindArbitraryUse, scan_tailwind_arbitrary_values};
79
80#[expect(
81    clippy::expect_used,
82    reason = "static regex patterns are hard-coded analyzer invariants covered by extraction tests"
83)]
84pub(crate) fn static_regex(pattern: &str) -> regex::Regex {
85    regex::Regex::new(pattern).expect("static regex pattern should compile")
86}
87
88/// Synthetic member-access object used to carry exported-instance bindings.
89///
90/// `MemberAccess { object: format!("{INSTANCE_EXPORT_SENTINEL}{export_name}"), member: target }`
91/// means the exported value named `export_name` is an instance of the local
92/// class/interface symbol named `target`.
93pub const INSTANCE_EXPORT_SENTINEL: &str = "__fallow_instance_export__:";
94
95/// Synthetic member-access object prefix for typed Playwright fixtures.
96///
97/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_DEF_SENTINEL}{test}:{fixture}"), member: type_name }`
98/// means the exported Playwright test object named `test` provides a fixture
99/// named `fixture` whose declared type is `type_name`.
100pub const PLAYWRIGHT_FIXTURE_DEF_SENTINEL: &str = "__fallow_playwright_fixture_def__:";
101
102/// Synthetic member-access object prefix for Playwright fixture wrapper aliases.
103///
104/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_ALIAS_SENTINEL}{alias}:"), member: base }`
105/// means the exported Playwright test object named `alias` inherits fixture
106/// definitions from the exported test object named `base`.
107pub const PLAYWRIGHT_FIXTURE_ALIAS_SENTINEL: &str = "__fallow_playwright_fixture_alias__:";
108
109/// Synthetic member-access object prefix for Playwright fixture member uses.
110///
111/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_USE_SENTINEL}{test}:{fixture}"), member }`
112/// means a callback passed to the Playwright test object named `test`
113/// destructures `fixture` and accesses `fixture.member`.
114pub const PLAYWRIGHT_FIXTURE_USE_SENTINEL: &str = "__fallow_playwright_fixture_use__:";
115
116/// Synthetic member-access object prefix for exported Playwright fixture type aliases.
117///
118/// `MemberAccess { object: format!("{PLAYWRIGHT_FIXTURE_TYPE_SENTINEL}{alias}:{fixture_path}"), member: type_name }`
119/// means a local type alias named `alias` contains a nested fixture path whose
120/// declared type is `type_name`. The analyze layer uses this when a Playwright
121/// fixture generic imports an object type alias from another module.
122pub const PLAYWRIGHT_FIXTURE_TYPE_SENTINEL: &str = "__fallow_playwright_fixture_type__:";
123
124/// Synthetic member-access object prefix for static-factory call returns.
125///
126/// `MemberAccess { object: format!("{FACTORY_CALL_SENTINEL}{callee}:{method}"), member }`
127/// means a local binding was assigned from `<callee>.<method>()` and a member
128/// is accessed on the result. The analyze layer resolves `callee` through the
129/// consumer module's imports to a class export and credits `member` on the
130/// class when the matching method carries `is_instance_returning_static`.
131/// See issue #346.
132pub const FACTORY_CALL_SENTINEL: &str = "__fallow_factory_call__:";
133
134/// Synthetic member-access object prefix for fluent-builder chain credit.
135///
136/// `MemberAccess { object: format!("{FLUENT_CHAIN_SENTINEL}{callee}:{root_method}:{chain}"), member }`
137/// means a fluent chain `<callee>.<root_method>().<...chain>.<member>` was
138/// observed. `chain` is a comma-separated list of method names (empty when
139/// `member` is the first chained call after `root_method`). The analyze layer
140/// resolves `callee` to a class export, validates `root_method` has
141/// `is_instance_returning_static`, walks each `chain` segment requiring
142/// `is_self_returning` on the class, and credits `member` on the class
143/// when the chain remains on the class type. See issue #387.
144pub const FLUENT_CHAIN_SENTINEL: &str = "__fallow_fluent_chain__:";
145
146/// Synthetic member-access object prefix for fluent chains rooted at a `new`
147/// expression.
148///
149/// `MemberAccess { object: format!("{FLUENT_CHAIN_NEW_SENTINEL}{class}:{chain}"), member }`
150/// means a chain `new <class>(...).<...chain>.<member>` was observed. Unlike
151/// `FLUENT_CHAIN_SENTINEL`, there is no root method: a constructor always
152/// returns an instance of `class`, so no `is_instance_returning_static` check
153/// applies. `chain` is a comma-separated list of the intermediate method names
154/// between the constructor and `member` (it always contains at least the first
155/// method, which must be `is_self_returning` to reach `member`). The analyze
156/// layer resolves `class` to a class export, requires every `chain` segment to
157/// be `is_self_returning` on the class, and credits `member` on the class.
158/// The first method directly off the constructor is credited separately via
159/// the `static_member_object_name` `NewExpression` arm. See issue #605.
160pub const FLUENT_CHAIN_NEW_SENTINEL: &str = "__fallow_fluent_chain_new__:";
161
162pub use parse::parse_source_to_module;
163
164/// Leading UTF-8 byte order mark codepoint.
165///
166/// Windows editors (Notepad, older VS settings, some IDE plugins) emit a UTF-8
167/// BOM at the start of source files. fallow's contract is "UTF-8 with or
168/// without BOM; line offsets are computed against the post-BOM view; the BOM,
169/// if present on input, is preserved on output by `fallow fix`."
170const BOM_CHAR: char = '\u{FEFF}';
171
172/// Strip the leading UTF-8 BOM if present.
173///
174/// Called at every file-read entry point in this crate so the rest of the
175/// pipeline (content hash, `compute_line_offsets`, oxc parser, downstream
176/// analyses) sees a consistent post-BOM view. Mirrors the
177/// `fallow_config` layer (`config_writer.rs::BOM`) so config-shaped sources
178/// and source-code-shaped sources are processed symmetrically. See issue #475.
179#[must_use]
180pub(crate) fn strip_bom(source: &str) -> &str {
181    source.strip_prefix(BOM_CHAR).unwrap_or(source)
182}
183
184/// Parse all files in parallel, extracting imports and exports.
185/// Uses the cache to skip reparsing files whose content hasn't changed.
186///
187/// When `need_complexity` is true, per-function cyclomatic/cognitive complexity
188/// metrics are computed during parsing (needed by the `health` command).
189/// Pass `false` for dead-code analysis where complexity data is unused.
190pub fn parse_all_files(
191    files: &[DiscoveredFile],
192    cache: Option<&CacheStore>,
193    need_complexity: bool,
194) -> ParseResult {
195    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
196    let cache_hits = AtomicUsize::new(0);
197    let cache_misses = AtomicUsize::new(0);
198    let parse_cpu_nanos = AtomicU64::new(0);
199
200    let modules: Vec<ModuleInfo> = files
201        .par_iter()
202        .filter_map(|file| {
203            parse_single_file_cached(
204                file,
205                cache,
206                &cache_hits,
207                &cache_misses,
208                &parse_cpu_nanos,
209                need_complexity,
210            )
211        })
212        .collect();
213
214    let hits = cache_hits.load(Ordering::Relaxed);
215    let misses = cache_misses.load(Ordering::Relaxed);
216    if hits > 0 || misses > 0 {
217        tracing::info!(
218            cache_hits = hits,
219            cache_misses = misses,
220            "incremental cache stats"
221        );
222    }
223
224    ParseResult {
225        modules,
226        cache_hits: hits,
227        cache_misses: misses,
228        parse_cpu_ms: parse_cpu_nanos.load(Ordering::Relaxed) as f64 / 1_000_000.0,
229    }
230}
231
232/// Parse a single file, consulting the cache first.
233///
234/// Cache validation strategy (fast path -> slow path):
235/// 1. `stat()` the file to get mtime + size (single syscall, no file read)
236/// 2. If mtime+size match the cached entry -> cache hit, return immediately
237/// 3. If mtime+size differ -> read file, compute content hash
238/// 4. If content hash matches cached entry -> cache hit (file was `touch`ed but unchanged)
239/// 5. Otherwise -> cache miss, full parse
240fn parse_single_file_cached(
241    file: &DiscoveredFile,
242    cache: Option<&CacheStore>,
243    cache_hits: &std::sync::atomic::AtomicUsize,
244    cache_misses: &std::sync::atomic::AtomicUsize,
245    parse_cpu_nanos: &std::sync::atomic::AtomicU64,
246    need_complexity: bool,
247) -> Option<ModuleInfo> {
248    use std::sync::atomic::Ordering;
249
250    if let Some(store) = cache
251        && let Ok(metadata) = std::fs::metadata(&file.path)
252    {
253        let mt = mtime_secs(&metadata);
254        let sz = metadata.len();
255        if let Some(cached) = store.get_by_metadata(&file.path, mt, sz)
256            && (!need_complexity || !cached.complexity.is_empty())
257        {
258            cache_hits.fetch_add(1, Ordering::Relaxed);
259            return Some(cache::cached_to_module_opts(
260                cached,
261                file.id,
262                need_complexity,
263            ));
264        }
265    }
266
267    let raw = std::fs::read_to_string(&file.path).ok()?;
268    let source = strip_bom(&raw);
269    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
270
271    if let Some(store) = cache
272        && let Some(cached) = store.get(&file.path, content_hash)
273        && (!need_complexity || !cached.complexity.is_empty())
274    {
275        cache_hits.fetch_add(1, Ordering::Relaxed);
276        return Some(cache::cached_to_module_opts(
277            cached,
278            file.id,
279            need_complexity,
280        ));
281    }
282    cache_misses.fetch_add(1, Ordering::Relaxed);
283
284    let parse_start = std::time::Instant::now();
285    let module = parse_source_to_module(file.id, &file.path, source, content_hash, need_complexity);
286    parse_cpu_nanos.fetch_add(
287        u64::try_from(parse_start.elapsed().as_nanos()).unwrap_or(u64::MAX),
288        Ordering::Relaxed,
289    );
290    Some(module)
291}
292
293/// Extract mtime (seconds since epoch) from file metadata.
294/// Returns 0 if mtime cannot be determined (pre-epoch, unsupported OS, etc.).
295fn mtime_secs(metadata: &std::fs::Metadata) -> u64 {
296    metadata
297        .modified()
298        .ok()
299        .and_then(|t| t.duration_since(std::time::SystemTime::UNIX_EPOCH).ok())
300        .map_or(0, |d| d.as_secs())
301}
302
303/// Parse a single file and extract module information (without complexity).
304#[must_use]
305pub fn parse_single_file(file: &DiscoveredFile) -> Option<ModuleInfo> {
306    let raw = std::fs::read_to_string(&file.path).ok()?;
307    let source = strip_bom(&raw);
308    let content_hash = xxhash_rust::xxh3::xxh3_64(source.as_bytes());
309    Some(parse_source_to_module(
310        file.id,
311        &file.path,
312        source,
313        content_hash,
314        false,
315    ))
316}
317
318/// Parse from in-memory content (for LSP, includes complexity).
319#[must_use]
320pub fn parse_from_content(file_id: FileId, path: &Path, content: &str) -> ModuleInfo {
321    let content = strip_bom(content);
322    let content_hash = xxhash_rust::xxh3::xxh3_64(content.as_bytes());
323    parse_source_to_module(file_id, path, content, content_hash, true)
324}
325
326#[cfg(all(test, not(miri)))]
327mod tests;