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