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