Skip to main content

fallow_extract/cache/
types.rs

1//! Serialization types for the incremental parse cache.
2//!
3//! All types use bitcode `Encode`/`Decode` for fast binary serialization.
4
5use bitcode::{Decode, Encode};
6
7use crate::MemberKind;
8
9/// Cache version, bump when the cache format or cached extraction semantics change.
10///
11/// Bumped to 89 for issue #475: extraction now strips a leading UTF-8 BOM
12/// before hashing and computing line offsets, so pre-fix entries whose source
13/// included a BOM carry hashes over the wrong byte sequence and would
14/// fast-path into stale `member_accesses` / `exports` for any BOM-bearing
15/// file. The bump invalidates user caches once on upgrade; subsequent runs
16/// are warm.
17///
18/// Bumped to 90 for issue #540: CSS Modules class extraction now strips
19/// `@layer` and `@import` at-rule preludes before scanning class names, so
20/// pre-fix entries for `.module.css` files using nested cascade-layer syntax
21/// (`@layer foo.bar { ... }`) carry phantom `bar` / `baz` exports that the
22/// new scanner no longer produces.
23///
24/// Bumped to 91 for issue #549: CSS Modules class extraction now records a
25/// real `Span` pointing at each class's declaration position in the source.
26/// Pre-fix cache entries for `.module.css` / `.module.scss` files carry
27/// `Span::default()` (start=0, end=0) on every export, which renders every
28/// finding at line:1 col:0; the new scanner produces real offsets.
29///
30/// Bumped to 92 for issue #563: feature flag extraction recognizes additional
31/// built-in SDK providers (PostHog, Vercel Flags, Optimizely, Eppo, plus more
32/// ConfigCat surfaces) and Vercel `flag({ key: "..." })` object arguments, so
33/// pre-fix entries can carry stale `flag_uses`.
34///
35/// Bumped to 93 for issue #589: Node `module.register()` loader calls now
36/// emit `DynamicImportInfo.destructured_names` populated with the loader-hook
37/// allowlist (current `initialize` / `resolve` / `load` / `globalPreload`
38/// plus legacy `getFormat` / `getSource` / `transformSource`) for every
39/// relative or `file:` specifier, including specifiers bound via
40/// `new URL(..., import.meta.url)`. Pre-fix entries carry empty
41/// `destructured_names` for the same source, so they would silently miss
42/// the named-export credit until the file is touched.
43///
44/// Bumped to 94 for issue #586: Playwright helper fixture extraction recognizes
45/// helpers with local setup before the final `return base.extend<T>(...)`, so
46/// pre-fix entries can miss fixture definition sentinels.
47///
48/// Bumped to 95 for the Glimmer `<template>` scanner: imported-binding usage
49/// and `MemberAccess { object: "this", member }` records for `{{this.foo}}`
50/// template references are now folded into the extractor before
51/// `into_module_info`. Pre-fix entries for `.gts` / `.gjs` files omit both,
52/// so template-only imports surface as `unused-import` and template-only
53/// class members as `unused-class-member` until the cache is re-extracted.
54///
55/// Bumped to 96 for issue #640: generic JSX `<script src>` and
56/// `<link rel="stylesheet|modulepreload" href>` attributes no longer emit
57/// synthetic `SideEffect` imports, so pre-fix entries can carry stale JSX
58/// resource edges that surface as false `unresolved-imports`.
59///
60/// Bumped to 97 for issue #639: MDX import/export extraction now skips
61/// fenced Markdown code blocks, so pre-fix entries can carry stale example
62/// imports that surface as false `unresolved-imports`.
63///
64/// Bumped to 98 for issue #638: statically resolvable `child_process.fork()`
65/// targets now emit `DynamicImportInfo` entries for local runner files.
66/// Pre-fix entries omit those dynamic imports, so forked script files can be
67/// reported as unused until the file is re-extracted.
68pub(super) const CACHE_VERSION: u32 = 98;
69
70/// Duplication token cache version. Bump when duplicate tokenization,
71/// normalization, or the on-disk token cache schema changes.
72pub const DUPES_CACHE_VERSION: u32 = 4;
73
74/// Default maximum cache size (256 MB). Overridable per-project via
75/// `cache.maxSizeMb` in the config file or `FALLOW_CACHE_MAX_SIZE` env var.
76/// Also used as the hard ceiling on load-time deserialization as a defence
77/// against pathological on-disk files.
78pub const DEFAULT_CACHE_MAX_SIZE: usize = 256 * 1024 * 1024;
79
80/// Trigger LRU eviction when the serialized cache exceeds 80% of the cap.
81/// Basis points (1/100 of a percent) for integer arithmetic without floats.
82pub(super) const EVICTION_TRIGGER_BPS: usize = 8000;
83
84/// Evict down to 60% of the cap so subsequent saves leave headroom.
85pub(super) const EVICTION_TARGET_BPS: usize = 6000;
86
87/// Promote the eviction log from `debug!` to `info!` when at least 25% of
88/// entries are removed in a single save. Default-noise concerns mean
89/// small-turnover saves should not be visible without `RUST_LOG=debug`.
90pub(super) const EVICTION_SIGNIFICANT_BPS: usize = 2500;
91
92/// Import kind discriminant for `CachedImport`:
93/// 0 = Named, 1 = Default, 2 = Namespace, 3 = `SideEffect`.
94pub(super) const IMPORT_KIND_NAMED: u8 = 0;
95pub(super) const IMPORT_KIND_DEFAULT: u8 = 1;
96pub(super) const IMPORT_KIND_NAMESPACE: u8 = 2;
97pub(super) const IMPORT_KIND_SIDE_EFFECT: u8 = 3;
98
99/// Cached data for a single module.
100#[derive(Debug, Clone, Encode, Decode)]
101pub struct CachedModule {
102    /// xxh3 hash of the file content.
103    pub content_hash: u64,
104    /// File modification time (seconds since epoch) for fast cache validation.
105    /// When mtime+size match the on-disk file, we skip reading file content entirely.
106    pub mtime_secs: u64,
107    /// File size in bytes for fast cache validation.
108    pub file_size: u64,
109    /// Seconds-since-epoch at the time this entry was last WRITTEN
110    /// (first parse or content-change refresh). NOT updated on cache-hit
111    /// reads: `update_cache` already iterates every in-scope file every run,
112    /// so refreshing on read would collapse the LRU to "last run this file
113    /// was discovered" for every retained entry. With write-only refresh,
114    /// the LRU genuinely targets stale (in-scope-but-unchanged-for-many-runs)
115    /// entries. Used by `CacheStore::save` for write-time eviction ordering.
116    pub last_access_secs: u64,
117    /// Exported symbols.
118    pub exports: Vec<CachedExport>,
119    /// Import specifiers.
120    pub imports: Vec<CachedImport>,
121    /// Re-export specifiers.
122    pub re_exports: Vec<CachedReExport>,
123    /// Dynamic import specifiers.
124    pub dynamic_imports: Vec<CachedDynamicImport>,
125    /// `require()` specifiers.
126    pub require_calls: Vec<CachedRequireCall>,
127    /// Static member accesses (e.g., `Status.Active`).
128    pub member_accesses: Vec<crate::MemberAccess>,
129    /// Identifiers used as whole objects (Object.values, for..in, spread, etc.).
130    pub whole_object_uses: Vec<String>,
131    /// Dynamic import patterns with partial static resolution.
132    pub dynamic_import_patterns: Vec<CachedDynamicImportPattern>,
133    /// Whether this module uses CJS exports.
134    pub has_cjs_exports: bool,
135    /// Whether this module declares at least one Angular `@Component({
136    /// templateUrl: ... })` decorator. Mirrors `ModuleInfo.has_angular_component_template_url`
137    /// so the CRAP-inherit walker's gate survives a warm-cache load.
138    pub has_angular_component_template_url: bool,
139    /// Local names of import bindings that are never referenced in this file.
140    pub unused_import_bindings: Vec<String>,
141    /// Local import bindings referenced from type positions.
142    pub type_referenced_import_bindings: Vec<String>,
143    /// Local import bindings referenced from value positions.
144    pub value_referenced_import_bindings: Vec<String>,
145    /// Inline suppression directives.
146    pub suppressions: Vec<CachedSuppression>,
147    /// Suppression tokens that did not parse to any known `IssueKind`. See #449.
148    pub unknown_suppression_kinds: Vec<CachedUnknownSuppressionKind>,
149    /// Pre-computed line-start byte offsets for O(log N) byte-to-line/col conversion.
150    pub line_offsets: Vec<u32>,
151    /// Per-function complexity metrics.
152    pub complexity: Vec<fallow_types::extract::FunctionComplexity>,
153    /// Feature flag use sites.
154    pub flag_uses: Vec<fallow_types::extract::FlagUse>,
155    /// Heritage metadata for exported classes.
156    pub class_heritage: Vec<fallow_types::extract::ClassHeritageInfo>,
157    /// Local type-capable declarations.
158    pub local_type_declarations: Vec<CachedLocalTypeDeclaration>,
159    /// Type references from exported public signatures.
160    pub public_signature_type_references: Vec<CachedPublicSignatureTypeReference>,
161    /// Namespace-import aliases re-exported through an object literal
162    /// (`export const API = { foo }` where `foo` is `import * as foo from './bar'`).
163    pub namespace_object_aliases: Vec<CachedNamespaceObjectAlias>,
164}
165
166/// Cached namespace-object alias.
167#[derive(Debug, Clone, Encode, Decode)]
168pub struct CachedNamespaceObjectAlias {
169    /// Canonical export name on this module.
170    pub via_export_name: String,
171    /// Dotted suffix of the property path relative to the export.
172    pub suffix: String,
173    /// Local name of the namespace import on this module.
174    pub namespace_local: String,
175}
176
177/// Cached local type declaration.
178#[derive(Debug, Clone, Encode, Decode)]
179pub struct CachedLocalTypeDeclaration {
180    /// Local declaration name.
181    pub name: String,
182    /// Byte offset of the declaration span start.
183    pub span_start: u32,
184    /// Byte offset of the declaration span end.
185    pub span_end: u32,
186}
187
188/// Cached public signature type reference.
189#[derive(Debug, Clone, Encode, Decode)]
190pub struct CachedPublicSignatureTypeReference {
191    /// Exported symbol whose signature contains the reference.
192    pub export_name: String,
193    /// Referenced type name.
194    pub type_name: String,
195    /// Byte offset of the reference span start.
196    pub span_start: u32,
197    /// Byte offset of the reference span end.
198    pub span_end: u32,
199}
200
201/// Cached suppression directive.
202#[derive(Debug, Clone, Encode, Decode)]
203pub struct CachedSuppression {
204    /// 1-based line this suppression applies to. 0 = file-wide.
205    pub line: u32,
206    /// 1-based line where the comment itself appears.
207    pub comment_line: u32,
208    /// 0 = suppress all, 1-20 = `IssueKind` discriminant.
209    pub kind: u8,
210}
211
212/// Cached unknown suppression kind token (see #449).
213#[derive(Debug, Clone, Encode, Decode)]
214pub struct CachedUnknownSuppressionKind {
215    /// 1-based line where the comment itself appears.
216    pub comment_line: u32,
217    /// True when the marker was `fallow-ignore-file`.
218    pub is_file_level: bool,
219    /// The verbatim token that did not parse.
220    pub token: String,
221}
222
223/// Cached export data for a single export declaration.
224#[derive(Debug, Clone, Encode, Decode)]
225pub struct CachedExport {
226    /// Export name (or "default" for default exports).
227    pub name: String,
228    /// Whether this is a default export.
229    pub is_default: bool,
230    /// Whether this is a type-only export.
231    pub is_type_only: bool,
232    /// Whether this export is registered through a runtime side effect at
233    /// module load time (Lit `@customElement` decorator or
234    /// `customElements.define` call). Persisted so warm-cache runs continue
235    /// to skip unused-export reporting for these classes.
236    pub is_side_effect_used: bool,
237    /// Visibility tag discriminant (0=None, 1=Public, 2=Internal, 3=Beta, 4=Alpha).
238    pub visibility: u8,
239    /// The local binding name, if different.
240    pub local_name: Option<String>,
241    /// Byte offset of the export span start.
242    pub span_start: u32,
243    /// Byte offset of the export span end.
244    pub span_end: u32,
245    /// Members of this export (for enums and classes).
246    pub members: Vec<CachedMember>,
247    /// The local name of the parent class from `extends` clause, if any.
248    pub super_class: Option<String>,
249}
250
251/// Cached import data for a single import declaration.
252#[derive(Debug, Clone, Encode, Decode)]
253pub struct CachedImport {
254    /// The import specifier.
255    pub source: String,
256    /// For Named imports, the imported symbol name. Empty for other kinds.
257    pub imported_name: String,
258    /// The local binding name.
259    pub local_name: String,
260    /// Whether this is a type-only import.
261    pub is_type_only: bool,
262    /// Whether this import originated from an SFC `<style>` block / `<style src>` (CSS context).
263    pub from_style: bool,
264    /// Import kind: 0=Named, 1=Default, 2=Namespace, 3=SideEffect.
265    pub kind: u8,
266    /// Byte offset of the import span start.
267    pub span_start: u32,
268    /// Byte offset of the import span end.
269    pub span_end: u32,
270    /// Byte offset of the source string literal span start.
271    pub source_span_start: u32,
272    /// Byte offset of the source string literal span end.
273    pub source_span_end: u32,
274}
275
276/// Cached dynamic import data.
277#[derive(Debug, Clone, Encode, Decode)]
278pub struct CachedDynamicImport {
279    /// The import specifier.
280    pub source: String,
281    /// Byte offset of the span start.
282    pub span_start: u32,
283    /// Byte offset of the span end.
284    pub span_end: u32,
285    /// Names destructured from the import result.
286    pub destructured_names: Vec<String>,
287    /// Local variable name for namespace imports.
288    pub local_name: Option<String>,
289    /// True when this dynamic import was synthesised by fallow (see
290    /// `DynamicImportInfo::is_speculative`).
291    pub is_speculative: bool,
292}
293
294/// Cached `require()` call data.
295#[derive(Debug, Clone, Encode, Decode)]
296pub struct CachedRequireCall {
297    /// The require specifier.
298    pub source: String,
299    /// Byte offset of the span start.
300    pub span_start: u32,
301    /// Byte offset of the span end.
302    pub span_end: u32,
303    /// Names destructured from the require result.
304    pub destructured_names: Vec<String>,
305    /// Local variable name for namespace requires.
306    pub local_name: Option<String>,
307}
308
309/// Cached re-export data.
310#[derive(Debug, Clone, Encode, Decode)]
311pub struct CachedReExport {
312    /// The module being re-exported from.
313    pub source: String,
314    /// Name imported from the source.
315    pub imported_name: String,
316    /// Name exported from this module.
317    pub exported_name: String,
318    /// Whether this is a type-only re-export.
319    pub is_type_only: bool,
320    /// Byte offset of the re-export span start (for line-number reporting).
321    pub span_start: u32,
322    /// Byte offset of the re-export span end.
323    pub span_end: u32,
324}
325
326/// Cached enum or class member data.
327#[derive(Debug, Clone, Encode, Decode)]
328pub struct CachedMember {
329    /// Member name.
330    pub name: String,
331    /// Member kind (enum, method, or property).
332    pub kind: MemberKind,
333    /// Byte offset of the span start.
334    pub span_start: u32,
335    /// Byte offset of the span end.
336    pub span_end: u32,
337    /// Whether this member has decorators.
338    pub has_decorator: bool,
339    /// Full dotted path of each decorator (e.g. `step`, `ns.foo`).
340    /// Empty for undecorated members and decorators with non-identifier
341    /// expressions.
342    pub decorator_names: Vec<String>,
343    /// True when this is a static method that returns a fresh instance of
344    /// the class: body returns `new this()` / `new <SameClassName>()`, or the
345    /// declared return type matches the class name. Treated as a factory.
346    /// See issues #346, #387.
347    pub is_instance_returning_static: bool,
348    /// True when this instance method's call result is an instance of the
349    /// same class (declared return type matches the class name, or body's
350    /// last statement is `return this`). Drives fluent-chain credit. See
351    /// issue #387.
352    pub is_self_returning: bool,
353}
354
355/// Cached dynamic import pattern data (template literals, `import.meta.glob`).
356#[derive(Debug, Clone, Encode, Decode)]
357pub struct CachedDynamicImportPattern {
358    /// Static prefix of the import path.
359    pub prefix: String,
360    /// Static suffix, if any.
361    pub suffix: Option<String>,
362    /// Byte offset of the span start.
363    pub span_start: u32,
364    /// Byte offset of the span end.
365    pub span_end: u32,
366}