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.
68///
69/// Bumped to 99 for issue #605: methods reached via `new Class(...).method()`
70/// receivers (direct and fluent-chain) now emit member accesses crediting the
71/// constructed class. Pre-fix entries lack those accesses, so such methods can
72/// be reported as unused class members until the file is re-extracted.
73///
74/// Bumped to 100 for issue #608: static Iconify icon strings (`icon="jam:github"`,
75/// `name="ic:round-home"`) in markup now populate `iconify_prefixes` so the
76/// `@iconify-json/<prefix>` package is credited. Pre-fix entries omit the field,
77/// so icon-set packages can be reported as unused until the file is re-extracted.
78pub(super) const CACHE_VERSION: u32 = 100;
79
80/// Duplication token cache version. Bump when duplicate tokenization,
81/// normalization, or the on-disk token cache schema changes.
82pub const DUPES_CACHE_VERSION: u32 = 4;
83
84/// Default maximum cache size (256 MB). Overridable per-project via
85/// `cache.maxSizeMb` in the config file or `FALLOW_CACHE_MAX_SIZE` env var.
86/// Also used as the hard ceiling on load-time deserialization as a defence
87/// against pathological on-disk files.
88pub const DEFAULT_CACHE_MAX_SIZE: usize = 256 * 1024 * 1024;
89
90/// Trigger LRU eviction when the serialized cache exceeds 80% of the cap.
91/// Basis points (1/100 of a percent) for integer arithmetic without floats.
92pub(super) const EVICTION_TRIGGER_BPS: usize = 8000;
93
94/// Evict down to 60% of the cap so subsequent saves leave headroom.
95pub(super) const EVICTION_TARGET_BPS: usize = 6000;
96
97/// Promote the eviction log from `debug!` to `info!` when at least 25% of
98/// entries are removed in a single save. Default-noise concerns mean
99/// small-turnover saves should not be visible without `RUST_LOG=debug`.
100pub(super) const EVICTION_SIGNIFICANT_BPS: usize = 2500;
101
102/// Import kind discriminant for `CachedImport`:
103/// 0 = Named, 1 = Default, 2 = Namespace, 3 = `SideEffect`.
104pub(super) const IMPORT_KIND_NAMED: u8 = 0;
105pub(super) const IMPORT_KIND_DEFAULT: u8 = 1;
106pub(super) const IMPORT_KIND_NAMESPACE: u8 = 2;
107pub(super) const IMPORT_KIND_SIDE_EFFECT: u8 = 3;
108
109macro_rules! assert_cached_type_size {
110    ($ty:ty, $size:expr) => {
111        const _: () = assert!(
112            std::mem::size_of::<$ty>() == $size,
113            concat!(
114                stringify!($ty),
115                " size changed; bump CACHE_VERSION if the cached wire shape or extraction semantics changed, then update this assertion"
116            )
117        );
118    };
119}
120
121assert_cached_type_size!(CachedModule, 544);
122assert_cached_type_size!(CachedNamespaceObjectAlias, 72);
123assert_cached_type_size!(CachedLocalTypeDeclaration, 32);
124assert_cached_type_size!(CachedPublicSignatureTypeReference, 56);
125assert_cached_type_size!(CachedSuppression, 12);
126assert_cached_type_size!(CachedUnknownSuppressionKind, 32);
127assert_cached_type_size!(CachedExport, 112);
128assert_cached_type_size!(CachedImport, 96);
129assert_cached_type_size!(CachedDynamicImport, 88);
130assert_cached_type_size!(CachedRequireCall, 80);
131assert_cached_type_size!(CachedReExport, 88);
132assert_cached_type_size!(CachedMember, 64);
133assert_cached_type_size!(CachedDynamicImportPattern, 56);
134assert_cached_type_size!(crate::MemberAccess, 48);
135assert_cached_type_size!(fallow_types::extract::FunctionComplexity, 48);
136assert_cached_type_size!(fallow_types::extract::FlagUse, 80);
137assert_cached_type_size!(fallow_types::extract::ClassHeritageInfo, 96);
138
139/// Cached data for a single module.
140#[derive(Debug, Clone, Encode, Decode)]
141pub struct CachedModule {
142    /// xxh3 hash of the file content.
143    pub content_hash: u64,
144    /// File modification time (seconds since epoch) for fast cache validation.
145    /// When mtime+size match the on-disk file, we skip reading file content entirely.
146    pub mtime_secs: u64,
147    /// File size in bytes for fast cache validation.
148    pub file_size: u64,
149    /// Seconds-since-epoch at the time this entry was last WRITTEN
150    /// (first parse or content-change refresh). NOT updated on cache-hit
151    /// reads: `update_cache` already iterates every in-scope file every run,
152    /// so refreshing on read would collapse the LRU to "last run this file
153    /// was discovered" for every retained entry. With write-only refresh,
154    /// the LRU genuinely targets stale (in-scope-but-unchanged-for-many-runs)
155    /// entries. Used by `CacheStore::save` for write-time eviction ordering.
156    pub last_access_secs: u64,
157    /// Exported symbols.
158    pub exports: Vec<CachedExport>,
159    /// Import specifiers.
160    pub imports: Vec<CachedImport>,
161    /// Re-export specifiers.
162    pub re_exports: Vec<CachedReExport>,
163    /// Dynamic import specifiers.
164    pub dynamic_imports: Vec<CachedDynamicImport>,
165    /// `require()` specifiers.
166    pub require_calls: Vec<CachedRequireCall>,
167    /// Static member accesses (e.g., `Status.Active`).
168    pub member_accesses: Vec<crate::MemberAccess>,
169    /// Identifiers used as whole objects (Object.values, for..in, spread, etc.).
170    pub whole_object_uses: Vec<String>,
171    /// Dynamic import patterns with partial static resolution.
172    pub dynamic_import_patterns: Vec<CachedDynamicImportPattern>,
173    /// Whether this module uses CJS exports.
174    pub has_cjs_exports: bool,
175    /// Whether this module declares at least one Angular `@Component({
176    /// templateUrl: ... })` decorator. Mirrors `ModuleInfo.has_angular_component_template_url`
177    /// so the CRAP-inherit walker's gate survives a warm-cache load.
178    pub has_angular_component_template_url: bool,
179    /// Local names of import bindings that are never referenced in this file.
180    pub unused_import_bindings: Vec<String>,
181    /// Local import bindings referenced from type positions.
182    pub type_referenced_import_bindings: Vec<String>,
183    /// Local import bindings referenced from value positions.
184    pub value_referenced_import_bindings: Vec<String>,
185    /// Inline suppression directives.
186    pub suppressions: Vec<CachedSuppression>,
187    /// Suppression tokens that did not parse to any known `IssueKind`. See #449.
188    pub unknown_suppression_kinds: Vec<CachedUnknownSuppressionKind>,
189    /// Pre-computed line-start byte offsets for O(log N) byte-to-line/col conversion.
190    pub line_offsets: Vec<u32>,
191    /// Per-function complexity metrics.
192    pub complexity: Vec<fallow_types::extract::FunctionComplexity>,
193    /// Feature flag use sites.
194    pub flag_uses: Vec<fallow_types::extract::FlagUse>,
195    /// Heritage metadata for exported classes.
196    pub class_heritage: Vec<fallow_types::extract::ClassHeritageInfo>,
197    /// Local type-capable declarations.
198    pub local_type_declarations: Vec<CachedLocalTypeDeclaration>,
199    /// Type references from exported public signatures.
200    pub public_signature_type_references: Vec<CachedPublicSignatureTypeReference>,
201    /// Namespace-import aliases re-exported through an object literal
202    /// (`export const API = { foo }` where `foo` is `import * as foo from './bar'`).
203    pub namespace_object_aliases: Vec<CachedNamespaceObjectAlias>,
204    /// Iconify collection prefixes found in static icon props (issue #608).
205    pub iconify_prefixes: Vec<String>,
206}
207
208/// Cached namespace-object alias.
209#[derive(Debug, Clone, Encode, Decode)]
210pub struct CachedNamespaceObjectAlias {
211    /// Canonical export name on this module.
212    pub via_export_name: String,
213    /// Dotted suffix of the property path relative to the export.
214    pub suffix: String,
215    /// Local name of the namespace import on this module.
216    pub namespace_local: String,
217}
218
219/// Cached local type declaration.
220#[derive(Debug, Clone, Encode, Decode)]
221pub struct CachedLocalTypeDeclaration {
222    /// Local declaration name.
223    pub name: String,
224    /// Byte offset of the declaration span start.
225    pub span_start: u32,
226    /// Byte offset of the declaration span end.
227    pub span_end: u32,
228}
229
230/// Cached public signature type reference.
231#[derive(Debug, Clone, Encode, Decode)]
232pub struct CachedPublicSignatureTypeReference {
233    /// Exported symbol whose signature contains the reference.
234    pub export_name: String,
235    /// Referenced type name.
236    pub type_name: String,
237    /// Byte offset of the reference span start.
238    pub span_start: u32,
239    /// Byte offset of the reference span end.
240    pub span_end: u32,
241}
242
243/// Cached suppression directive.
244#[derive(Debug, Clone, Encode, Decode)]
245pub struct CachedSuppression {
246    /// 1-based line this suppression applies to. 0 = file-wide.
247    pub line: u32,
248    /// 1-based line where the comment itself appears.
249    pub comment_line: u32,
250    /// 0 = suppress all, 1-20 = `IssueKind` discriminant.
251    pub kind: u8,
252}
253
254/// Cached unknown suppression kind token (see #449).
255#[derive(Debug, Clone, Encode, Decode)]
256pub struct CachedUnknownSuppressionKind {
257    /// 1-based line where the comment itself appears.
258    pub comment_line: u32,
259    /// True when the marker was `fallow-ignore-file`.
260    pub is_file_level: bool,
261    /// The verbatim token that did not parse.
262    pub token: String,
263}
264
265/// Cached export data for a single export declaration.
266#[derive(Debug, Clone, Encode, Decode)]
267pub struct CachedExport {
268    /// Export name (or "default" for default exports).
269    pub name: String,
270    /// Whether this is a default export.
271    pub is_default: bool,
272    /// Whether this is a type-only export.
273    pub is_type_only: bool,
274    /// Whether this export is registered through a runtime side effect at
275    /// module load time (Lit `@customElement` decorator or
276    /// `customElements.define` call). Persisted so warm-cache runs continue
277    /// to skip unused-export reporting for these classes.
278    pub is_side_effect_used: bool,
279    /// Visibility tag discriminant (0=None, 1=Public, 2=Internal, 3=Beta, 4=Alpha).
280    pub visibility: u8,
281    /// The local binding name, if different.
282    pub local_name: Option<String>,
283    /// Byte offset of the export span start.
284    pub span_start: u32,
285    /// Byte offset of the export span end.
286    pub span_end: u32,
287    /// Members of this export (for enums and classes).
288    pub members: Vec<CachedMember>,
289    /// The local name of the parent class from `extends` clause, if any.
290    pub super_class: Option<String>,
291}
292
293/// Cached import data for a single import declaration.
294#[derive(Debug, Clone, Encode, Decode)]
295pub struct CachedImport {
296    /// The import specifier.
297    pub source: String,
298    /// For Named imports, the imported symbol name. Empty for other kinds.
299    pub imported_name: String,
300    /// The local binding name.
301    pub local_name: String,
302    /// Whether this is a type-only import.
303    pub is_type_only: bool,
304    /// Whether this import originated from an SFC `<style>` block / `<style src>` (CSS context).
305    pub from_style: bool,
306    /// Import kind: 0=Named, 1=Default, 2=Namespace, 3=SideEffect.
307    pub kind: u8,
308    /// Byte offset of the import span start.
309    pub span_start: u32,
310    /// Byte offset of the import span end.
311    pub span_end: u32,
312    /// Byte offset of the source string literal span start.
313    pub source_span_start: u32,
314    /// Byte offset of the source string literal span end.
315    pub source_span_end: u32,
316}
317
318/// Cached dynamic import data.
319#[derive(Debug, Clone, Encode, Decode)]
320pub struct CachedDynamicImport {
321    /// The import specifier.
322    pub source: String,
323    /// Byte offset of the span start.
324    pub span_start: u32,
325    /// Byte offset of the span end.
326    pub span_end: u32,
327    /// Names destructured from the import result.
328    pub destructured_names: Vec<String>,
329    /// Local variable name for namespace imports.
330    pub local_name: Option<String>,
331    /// True when this dynamic import was synthesised by fallow (see
332    /// `DynamicImportInfo::is_speculative`).
333    pub is_speculative: bool,
334}
335
336/// Cached `require()` call data.
337#[derive(Debug, Clone, Encode, Decode)]
338pub struct CachedRequireCall {
339    /// The require specifier.
340    pub source: String,
341    /// Byte offset of the span start.
342    pub span_start: u32,
343    /// Byte offset of the span end.
344    pub span_end: u32,
345    /// Names destructured from the require result.
346    pub destructured_names: Vec<String>,
347    /// Local variable name for namespace requires.
348    pub local_name: Option<String>,
349}
350
351/// Cached re-export data.
352#[derive(Debug, Clone, Encode, Decode)]
353pub struct CachedReExport {
354    /// The module being re-exported from.
355    pub source: String,
356    /// Name imported from the source.
357    pub imported_name: String,
358    /// Name exported from this module.
359    pub exported_name: String,
360    /// Whether this is a type-only re-export.
361    pub is_type_only: bool,
362    /// Byte offset of the re-export span start (for line-number reporting).
363    pub span_start: u32,
364    /// Byte offset of the re-export span end.
365    pub span_end: u32,
366}
367
368/// Cached enum or class member data.
369#[derive(Debug, Clone, Encode, Decode)]
370pub struct CachedMember {
371    /// Member name.
372    pub name: String,
373    /// Member kind (enum, method, or property).
374    pub kind: MemberKind,
375    /// Byte offset of the span start.
376    pub span_start: u32,
377    /// Byte offset of the span end.
378    pub span_end: u32,
379    /// Whether this member has decorators.
380    pub has_decorator: bool,
381    /// Full dotted path of each decorator (e.g. `step`, `ns.foo`).
382    /// Empty for undecorated members and decorators with non-identifier
383    /// expressions.
384    pub decorator_names: Vec<String>,
385    /// True when this is a static method that returns a fresh instance of
386    /// the class: body returns `new this()` / `new <SameClassName>()`, or the
387    /// declared return type matches the class name. Treated as a factory.
388    /// See issues #346, #387.
389    pub is_instance_returning_static: bool,
390    /// True when this instance method's call result is an instance of the
391    /// same class (declared return type matches the class name, or body's
392    /// last statement is `return this`). Drives fluent-chain credit. See
393    /// issue #387.
394    pub is_self_returning: bool,
395}
396
397/// Cached dynamic import pattern data (template literals, `import.meta.glob`).
398#[derive(Debug, Clone, Encode, Decode)]
399pub struct CachedDynamicImportPattern {
400    /// Static prefix of the import path.
401    pub prefix: String,
402    /// Static suffix, if any.
403    pub suffix: Option<String>,
404    /// Byte offset of the span start.
405    pub span_start: u32,
406    /// Byte offset of the span end.
407    pub span_end: u32,
408}