Skip to main content

fallow_extract/cache/
conversion.rs

1//! Conversion between [`ModuleInfo`](crate::ModuleInfo) and [`CachedModule`].
2//!
3//! Both functions convert between borrowed source structs and owned target structs
4//! (`&CachedModule -> ModuleInfo`, `&ModuleInfo -> CachedModule`). All `String` clones
5//! are structurally necessary: the cache store retains ownership of `CachedModule`
6//! entries (for persistence), and `ModuleInfo` must outlive the cache for the
7//! analysis pipeline. Eliminating these clones would require shared ownership
8//! (`Arc<str>`) across the entire extraction + analysis pipeline.
9
10use std::sync::Arc;
11use std::time::{SystemTime, UNIX_EPOCH};
12
13use oxc_span::Span;
14
15use crate::ExportName;
16use fallow_types::extract::{NamespaceObjectAlias, VisibilityTag};
17use fallow_types::suppress::{PolicyRuleSuppression, SuppressionScope, SuppressionTarget};
18
19/// Seconds-since-Unix-epoch from the wall clock, saturating to 0 if the
20/// system clock is set before the epoch. Used as the LRU bookkeeping
21/// timestamp on `CachedModule.last_seen_secs`. Wall-clock (not monotonic)
22/// is the right source here because the value persists across process
23/// invocations.
24#[must_use]
25pub fn current_unix_seconds() -> u64 {
26    SystemTime::now()
27        .duration_since(UNIX_EPOCH)
28        .map_or(0, |d| d.as_secs())
29}
30
31use super::types::{
32    CachedDynamicImport, CachedDynamicImportPattern, CachedExport, CachedImport,
33    CachedInlineThreshold, CachedInlineThresholdProblem, CachedLocalTypeDeclaration, CachedMember,
34    CachedModule, CachedNamespaceObjectAlias, CachedPublicSignatureTypeReference,
35    CachedRangeMarkerProblem, CachedReExport, CachedRequireCall, CachedSuppression,
36    CachedUnknownSuppressionKind, IMPORT_KIND_DEFAULT, IMPORT_KIND_NAMED, IMPORT_KIND_NAMESPACE,
37    IMPORT_KIND_SIDE_EFFECT,
38};
39
40/// Reconstruct a [`ModuleInfo`](crate::ModuleInfo) from a [`CachedModule`],
41/// with its complexity and its call facts.
42///
43/// An entry that holds no usable call facts gives `function_contracts: None`,
44/// the same as a module with no facts. A parse that must have the facts uses
45/// [`cached_hit_to_module`], which treats such an entry as a miss.
46#[must_use]
47pub fn cached_to_module(
48    cached: &CachedModule,
49    file_id: fallow_types::discover::FileId,
50) -> crate::ModuleInfo {
51    cached_to_module_opts(cached, file_id, true, true)
52}
53
54fn cached_exports_to_module(exports: &[CachedExport]) -> Vec<crate::ExportInfo> {
55    exports
56        .iter()
57        .map(|export| crate::ExportInfo {
58            name: if export.is_default {
59                ExportName::Default
60            } else {
61                ExportName::Named(export.name.clone())
62            },
63            local_name: export.local_name.clone(),
64            is_type_only: export.is_type_only,
65            is_side_effect_used: export.is_side_effect_used,
66            visibility: visibility_from_cached(export.visibility),
67            expected_unused_reason: export.expected_unused_reason.clone(),
68            deprecated: export.deprecated,
69            deprecated_reason: export.deprecated_reason.clone(),
70            span: Span::new(export.span_start, export.span_end),
71            members: export
72                .members
73                .iter()
74                .map(|member| crate::MemberInfo {
75                    name: member.name.clone(),
76                    kind: member.kind,
77                    span: Span::new(member.span_start, member.span_end),
78                    has_decorator: member.has_decorator,
79                    decorator_names: member.decorator_names.clone(),
80                    is_instance_returning_static: member.is_instance_returning_static,
81                    is_self_returning: member.is_self_returning,
82                    override_base: member.override_base.clone(),
83                    is_protected: member.is_protected,
84                    is_static: member.is_static,
85                    pairs_with_symbol_dispose: member.pairs_with_symbol_dispose,
86                })
87                .collect(),
88            super_class: export.super_class.clone(),
89        })
90        .collect()
91}
92
93fn cached_to_imported_name(kind: u8, name: &str) -> crate::ImportedName {
94    match kind {
95        IMPORT_KIND_DEFAULT => crate::ImportedName::Default,
96        IMPORT_KIND_NAMESPACE => crate::ImportedName::Namespace,
97        IMPORT_KIND_SIDE_EFFECT => crate::ImportedName::SideEffect,
98        _ => crate::ImportedName::Named(name.to_owned()),
99    }
100}
101
102fn imported_name_to_cached(imported_name: &crate::ImportedName) -> (u8, String) {
103    match imported_name {
104        crate::ImportedName::Named(name) => (IMPORT_KIND_NAMED, name.clone()),
105        crate::ImportedName::Default => (IMPORT_KIND_DEFAULT, String::new()),
106        crate::ImportedName::Namespace => (IMPORT_KIND_NAMESPACE, String::new()),
107        crate::ImportedName::SideEffect => (IMPORT_KIND_SIDE_EFFECT, String::new()),
108    }
109}
110
111fn cached_imports_to_module(imports: &[CachedImport]) -> Vec<crate::ImportInfo> {
112    imports
113        .iter()
114        .map(|import| crate::ImportInfo {
115            source: import.source.clone(),
116            imported_name: cached_to_imported_name(import.kind, &import.imported_name),
117            local_name: import.local_name.clone(),
118            is_type_only: import.is_type_only,
119            is_type_only_star: import.is_type_only_star,
120            from_style: import.from_style,
121            span: Span::new(import.span_start, import.span_end),
122            source_span: Span::new(import.source_span_start, import.source_span_end),
123        })
124        .collect()
125}
126
127fn cached_re_exports_to_module(re_exports: &[CachedReExport]) -> Vec<crate::ReExportInfo> {
128    re_exports
129        .iter()
130        .map(|re_export| crate::ReExportInfo {
131            source: re_export.source.clone(),
132            imported_name: re_export.imported_name.clone(),
133            exported_name: re_export.exported_name.clone(),
134            is_type_only: re_export.is_type_only,
135            span: Span::new(re_export.span_start, re_export.span_end),
136            statement_span: Span::new(re_export.statement_span_start, re_export.statement_span_end),
137            source_span: Span::new(re_export.source_span_start, re_export.source_span_end),
138            visibility: visibility_from_cached(re_export.visibility),
139            expected_unused_reason: re_export.expected_unused_reason.clone(),
140        })
141        .collect()
142}
143
144/// Decode the `u8` that `VisibilityTag as u8` wrote into the cache.
145const fn visibility_from_cached(raw: u8) -> VisibilityTag {
146    match raw {
147        1 => VisibilityTag::Public,
148        2 => VisibilityTag::Internal,
149        3 => VisibilityTag::Beta,
150        4 => VisibilityTag::Alpha,
151        5 => VisibilityTag::ExpectedUnused,
152        _ => VisibilityTag::None,
153    }
154}
155
156fn cached_dynamic_imports_to_module(
157    dynamic_imports: &[CachedDynamicImport],
158) -> Vec<crate::DynamicImportInfo> {
159    dynamic_imports
160        .iter()
161        .map(|dynamic_import| crate::DynamicImportInfo {
162            source: dynamic_import.source.clone(),
163            span: Span::new(dynamic_import.span_start, dynamic_import.span_end),
164            destructured_names: dynamic_import.destructured_names.clone(),
165            local_name: dynamic_import.local_name.clone(),
166            is_speculative: dynamic_import.is_speculative,
167            value_escapes: dynamic_import.value_escapes,
168        })
169        .collect()
170}
171
172fn cached_require_calls_to_module(
173    require_calls: &[CachedRequireCall],
174) -> Vec<crate::RequireCallInfo> {
175    require_calls
176        .iter()
177        .map(|require_call| crate::RequireCallInfo {
178            source: require_call.source.clone(),
179            span: Span::new(require_call.span_start, require_call.span_end),
180            source_span: Span::new(require_call.source_span_start, require_call.source_span_end),
181            destructured_names: require_call.destructured_names.clone(),
182            destructured_locals: require_call.destructured_locals.clone(),
183            local_name: require_call.local_name.clone(),
184            is_type_only: require_call.is_type_only,
185        })
186        .collect()
187}
188
189fn cached_dynamic_patterns_to_module(
190    dynamic_import_patterns: &[CachedDynamicImportPattern],
191) -> Vec<crate::DynamicImportPattern> {
192    dynamic_import_patterns
193        .iter()
194        .map(|pattern| crate::DynamicImportPattern {
195            prefix: pattern.prefix.clone(),
196            suffix: pattern.suffix.clone(),
197            excludes: pattern.excludes.clone(),
198            span: Span::new(pattern.span_start, pattern.span_end),
199            mechanism: pattern.mechanism,
200            imported_name: cached_to_imported_name(pattern.import_kind, &pattern.imported_name),
201        })
202        .collect()
203}
204
205fn cached_suppressions_to_module(
206    suppressions: &[CachedSuppression],
207) -> Vec<crate::suppress::Suppression> {
208    suppressions
209        .iter()
210        .map(|suppression| {
211            let target = if suppression.kind == 0 {
212                None
213            } else if suppression.kind
214                == crate::suppress::IssueKind::PolicyViolation.to_discriminant()
215                && !suppression.policy_pack.is_empty()
216                && !suppression.policy_rule_id.is_empty()
217            {
218                Some(SuppressionTarget::PolicyRule(PolicyRuleSuppression::new(
219                    suppression.policy_pack.clone(),
220                    suppression.policy_rule_id.clone(),
221                )))
222            } else {
223                crate::suppress::IssueKind::from_discriminant(suppression.kind)
224                    .map(SuppressionTarget::Issue)
225            };
226            crate::suppress::Suppression {
227                line: suppression.line,
228                comment_line: suppression.comment_line,
229                target,
230                reason: suppression.reason.clone(),
231                scope: cached_scope(suppression.line, suppression.range_end_line),
232            }
233        })
234        .collect()
235}
236
237/// The scope of a cached suppression. A range stores its end line; any other
238/// suppression stores 0 there.
239const fn cached_scope(line: u32, range_end_line: u32) -> SuppressionScope {
240    if range_end_line == 0 {
241        SuppressionScope::for_line(line)
242    } else {
243        SuppressionScope::Range {
244            end_line: range_end_line,
245        }
246    }
247}
248
249fn cached_range_problems_to_module(
250    problems: &[CachedRangeMarkerProblem],
251) -> Vec<fallow_types::suppress::RangeMarkerProblem> {
252    problems
253        .iter()
254        .filter_map(|problem| {
255            Some(fallow_types::suppress::RangeMarkerProblem {
256                line: problem.line,
257                kind: fallow_types::suppress::RangeMarkerProblemKind::from_code(problem.kind)?,
258                token: problem.token.clone(),
259            })
260        })
261        .collect()
262}
263
264fn module_range_problems_to_cached(
265    problems: &[fallow_types::suppress::RangeMarkerProblem],
266) -> Vec<CachedRangeMarkerProblem> {
267    problems
268        .iter()
269        .map(|problem| CachedRangeMarkerProblem {
270            line: problem.line,
271            kind: problem.kind.to_code(),
272            token: problem.token.clone(),
273        })
274        .collect()
275}
276
277fn cached_inline_thresholds_to_module(
278    cached: &CachedModule,
279) -> fallow_types::inline_threshold::InlineThresholdOverrides {
280    use fallow_types::inline_threshold::{
281        InlineThresholdOverride, InlineThresholdProblem, InlineThresholdProblemKind,
282    };
283    fallow_types::inline_threshold::InlineThresholdOverrides {
284        entries: cached
285            .inline_thresholds
286            .iter()
287            .map(|entry| InlineThresholdOverride {
288                line: entry.line,
289                comment_line: entry.comment_line,
290                max_cyclomatic: entry.max_cyclomatic,
291                max_cognitive: entry.max_cognitive,
292                max_crap: entry.max_crap,
293                max_unit_size: entry.max_unit_size,
294                reason: entry.reason.clone(),
295            })
296            .collect(),
297        problems: cached
298            .inline_threshold_problems
299            .iter()
300            .filter_map(|problem| {
301                Some(InlineThresholdProblem {
302                    line: problem.line,
303                    kind: InlineThresholdProblemKind::from_code(problem.kind)?,
304                    token: problem.token.clone(),
305                })
306            })
307            .collect(),
308    }
309}
310
311fn cached_unknown_suppressions_to_module(
312    unknown_suppression_kinds: &[CachedUnknownSuppressionKind],
313) -> Vec<fallow_types::suppress::UnknownSuppressionKind> {
314    unknown_suppression_kinds
315        .iter()
316        .map(|unknown| fallow_types::suppress::UnknownSuppressionKind {
317            comment_line: unknown.comment_line,
318            is_file_level: unknown.is_file_level,
319            token: unknown.token.clone(),
320            reason: unknown.reason.clone(),
321        })
322        .collect()
323}
324
325fn cached_local_types_to_module(
326    local_type_declarations: &[CachedLocalTypeDeclaration],
327) -> Vec<crate::LocalTypeDeclaration> {
328    local_type_declarations
329        .iter()
330        .map(|declaration| crate::LocalTypeDeclaration {
331            name: declaration.name.clone(),
332            span: Span::new(declaration.span_start, declaration.span_end),
333        })
334        .collect()
335}
336
337fn cached_signature_refs_to_module(
338    public_signature_type_references: &[CachedPublicSignatureTypeReference],
339) -> Vec<crate::PublicSignatureTypeReference> {
340    public_signature_type_references
341        .iter()
342        .map(|reference| crate::PublicSignatureTypeReference {
343            export_name: reference.export_name.clone(),
344            type_name: reference.type_name.clone(),
345            span: Span::new(reference.span_start, reference.span_end),
346            from_satisfies: reference.from_satisfies,
347        })
348        .collect()
349}
350
351fn cached_namespace_aliases_to_module(
352    namespace_object_aliases: &[CachedNamespaceObjectAlias],
353) -> Vec<NamespaceObjectAlias> {
354    namespace_object_aliases
355        .iter()
356        .map(|alias| NamespaceObjectAlias {
357            via_export_name: alias.via_export_name.clone(),
358            suffix: alias.suffix.clone(),
359            namespace_local: alias.namespace_local.clone(),
360        })
361        .collect()
362}
363
364fn module_exports_to_cached(exports: &[crate::ExportInfo]) -> Vec<CachedExport> {
365    exports
366        .iter()
367        .map(|export| CachedExport {
368            name: match &export.name {
369                ExportName::Named(name) => name.clone(),
370                ExportName::Default => String::new(),
371            },
372            is_default: matches!(export.name, ExportName::Default),
373            is_type_only: export.is_type_only,
374            is_side_effect_used: export.is_side_effect_used,
375            visibility: export.visibility as u8,
376            expected_unused_reason: export.expected_unused_reason.clone(),
377            deprecated: export.deprecated,
378            deprecated_reason: export.deprecated_reason.clone(),
379            local_name: export.local_name.clone(),
380            span_start: export.span.start,
381            span_end: export.span.end,
382            members: export
383                .members
384                .iter()
385                .map(|member| CachedMember {
386                    name: member.name.clone(),
387                    kind: member.kind,
388                    span_start: member.span.start,
389                    span_end: member.span.end,
390                    has_decorator: member.has_decorator,
391                    decorator_names: member.decorator_names.clone(),
392                    is_instance_returning_static: member.is_instance_returning_static,
393                    is_self_returning: member.is_self_returning,
394                    override_base: member.override_base.clone(),
395                    is_protected: member.is_protected,
396                    is_static: member.is_static,
397                    pairs_with_symbol_dispose: member.pairs_with_symbol_dispose,
398                })
399                .collect(),
400            super_class: export.super_class.clone(),
401        })
402        .collect()
403}
404
405fn module_imports_to_cached(imports: &[crate::ImportInfo]) -> Vec<CachedImport> {
406    imports
407        .iter()
408        .map(|import| {
409            let (kind, imported_name) = imported_name_to_cached(&import.imported_name);
410            CachedImport {
411                source: import.source.clone(),
412                imported_name,
413                local_name: import.local_name.clone(),
414                is_type_only: import.is_type_only,
415                is_type_only_star: import.is_type_only_star,
416                from_style: import.from_style,
417                kind,
418                span_start: import.span.start,
419                span_end: import.span.end,
420                source_span_start: import.source_span.start,
421                source_span_end: import.source_span.end,
422            }
423        })
424        .collect()
425}
426
427fn module_re_exports_to_cached(re_exports: &[crate::ReExportInfo]) -> Vec<CachedReExport> {
428    re_exports
429        .iter()
430        .map(|re_export| CachedReExport {
431            source: re_export.source.clone(),
432            imported_name: re_export.imported_name.clone(),
433            exported_name: re_export.exported_name.clone(),
434            is_type_only: re_export.is_type_only,
435            span_start: re_export.span.start,
436            span_end: re_export.span.end,
437            statement_span_start: re_export.statement_span.start,
438            statement_span_end: re_export.statement_span.end,
439            source_span_start: re_export.source_span.start,
440            source_span_end: re_export.source_span.end,
441            visibility: re_export.visibility as u8,
442            expected_unused_reason: re_export.expected_unused_reason.clone(),
443        })
444        .collect()
445}
446
447fn module_dynamic_imports_to_cached(
448    dynamic_imports: &[crate::DynamicImportInfo],
449) -> Vec<CachedDynamicImport> {
450    dynamic_imports
451        .iter()
452        .map(|dynamic_import| CachedDynamicImport {
453            source: dynamic_import.source.clone(),
454            span_start: dynamic_import.span.start,
455            span_end: dynamic_import.span.end,
456            destructured_names: dynamic_import.destructured_names.clone(),
457            local_name: dynamic_import.local_name.clone(),
458            is_speculative: dynamic_import.is_speculative,
459            value_escapes: dynamic_import.value_escapes,
460        })
461        .collect()
462}
463
464fn module_require_calls_to_cached(
465    require_calls: &[crate::RequireCallInfo],
466) -> Vec<CachedRequireCall> {
467    require_calls
468        .iter()
469        .map(|require_call| CachedRequireCall {
470            source: require_call.source.clone(),
471            span_start: require_call.span.start,
472            span_end: require_call.span.end,
473            source_span_start: require_call.source_span.start,
474            source_span_end: require_call.source_span.end,
475            destructured_names: require_call.destructured_names.clone(),
476            destructured_locals: require_call.destructured_locals.clone(),
477            local_name: require_call.local_name.clone(),
478            is_type_only: require_call.is_type_only,
479        })
480        .collect()
481}
482
483fn module_dynamic_patterns_to_cached(
484    dynamic_import_patterns: &[crate::DynamicImportPattern],
485) -> Vec<CachedDynamicImportPattern> {
486    dynamic_import_patterns
487        .iter()
488        .map(|pattern| {
489            let (import_kind, imported_name) = imported_name_to_cached(&pattern.imported_name);
490            CachedDynamicImportPattern {
491                prefix: pattern.prefix.clone(),
492                suffix: pattern.suffix.clone(),
493                excludes: pattern.excludes.clone(),
494                span_start: pattern.span.start,
495                span_end: pattern.span.end,
496                mechanism: pattern.mechanism,
497                import_kind,
498                imported_name,
499            }
500        })
501        .collect()
502}
503
504fn module_suppressions_to_cached(
505    suppressions: &[crate::suppress::Suppression],
506) -> Vec<CachedSuppression> {
507    suppressions
508        .iter()
509        .map(|suppression| {
510            let (kind, policy_pack, policy_rule_id) = match &suppression.target {
511                None => (0, String::new(), String::new()),
512                Some(SuppressionTarget::Issue(kind)) => {
513                    (kind.to_discriminant(), String::new(), String::new())
514                }
515                Some(SuppressionTarget::PolicyRule(target)) => (
516                    crate::suppress::IssueKind::PolicyViolation.to_discriminant(),
517                    target.pack.clone(),
518                    target.rule_id.clone(),
519                ),
520            };
521            CachedSuppression {
522                line: suppression.line,
523                comment_line: suppression.comment_line,
524                kind,
525                policy_pack,
526                policy_rule_id,
527                reason: suppression.reason.clone(),
528                range_end_line: suppression.range_end_line().unwrap_or(0),
529            }
530        })
531        .collect()
532}
533
534fn module_unknown_suppressions_to_cached(
535    unknown_suppression_kinds: &[fallow_types::suppress::UnknownSuppressionKind],
536) -> Vec<CachedUnknownSuppressionKind> {
537    unknown_suppression_kinds
538        .iter()
539        .map(|unknown| CachedUnknownSuppressionKind {
540            comment_line: unknown.comment_line,
541            is_file_level: unknown.is_file_level,
542            token: unknown.token.clone(),
543            reason: unknown.reason.clone(),
544        })
545        .collect()
546}
547
548fn module_local_types_to_cached(
549    local_type_declarations: &[crate::LocalTypeDeclaration],
550) -> Vec<CachedLocalTypeDeclaration> {
551    local_type_declarations
552        .iter()
553        .map(|declaration| CachedLocalTypeDeclaration {
554            name: declaration.name.clone(),
555            span_start: declaration.span.start,
556            span_end: declaration.span.end,
557        })
558        .collect()
559}
560
561fn module_signature_refs_to_cached(
562    public_signature_type_references: &[crate::PublicSignatureTypeReference],
563) -> Vec<CachedPublicSignatureTypeReference> {
564    public_signature_type_references
565        .iter()
566        .map(|reference| CachedPublicSignatureTypeReference {
567            export_name: reference.export_name.clone(),
568            type_name: reference.type_name.clone(),
569            span_start: reference.span.start,
570            span_end: reference.span.end,
571            from_satisfies: reference.from_satisfies,
572        })
573        .collect()
574}
575
576fn module_namespace_aliases_to_cached(
577    namespace_object_aliases: &[NamespaceObjectAlias],
578) -> Vec<CachedNamespaceObjectAlias> {
579    namespace_object_aliases
580        .iter()
581        .map(|alias| CachedNamespaceObjectAlias {
582            via_export_name: alias.via_export_name.clone(),
583            suffix: alias.suffix.clone(),
584            namespace_local: alias.namespace_local.clone(),
585        })
586        .collect()
587}
588
589/// Rehydrate an optional cached slice into the shared `Arc<[T]>` module form.
590fn cached_opt_to_arc<T: Clone>(cached: Option<&[T]>) -> Arc<[T]> {
591    cached.map(Arc::from).unwrap_or_default()
592}
593
594/// Reconstruct a [`ModuleInfo`](crate::ModuleInfo) from a [`CachedModule`], skipping
595/// the per-function complexity vec when `need_complexity` is `false`. Avoids the
596/// `Vec<FunctionComplexity>` clone on warm runs of commands (e.g. `fallow dead-code`)
597/// that don't consume complexity, which adds up across tens of thousands of files.
598///
599/// The call facts are decoded only when `need_call_facts` is `true`. Otherwise
600/// `function_contracts` stays `None`, so a run that reads no call facts does
601/// not pay their decode.
602#[must_use]
603#[expect(
604    clippy::too_many_lines,
605    reason = "flat field projection preserves the complete extraction cache contract"
606)]
607pub fn cached_to_module_opts(
608    cached: &CachedModule,
609    file_id: fallow_types::discover::FileId,
610    need_complexity: bool,
611    need_call_facts: bool,
612) -> crate::ModuleInfo {
613    crate::ModuleInfo {
614        file_id,
615        exports: cached_exports_to_module(&cached.exports).into(),
616        imports: cached_imports_to_module(&cached.imports),
617        re_exports: cached_re_exports_to_module(&cached.re_exports),
618        dynamic_imports: cached_dynamic_imports_to_module(&cached.dynamic_imports),
619        dynamic_import_patterns: cached_dynamic_patterns_to_module(&cached.dynamic_import_patterns),
620        require_calls: cached_require_calls_to_module(&cached.require_calls),
621        package_path_references: cached.package_path_references.clone(),
622        type_package_references: cached.type_package_references.clone(),
623        bin_path_references: cached.bin_path_references.clone(),
624        package_resolve_sites: cached.package_resolve_sites.clone(),
625        member_accesses: cached.member_accesses.clone().into(),
626        semantic_facts: cached_opt_to_arc(cached.semantic_facts.as_deref()),
627        whole_object_uses: Arc::from(&*cached.whole_object_uses),
628        has_cjs_exports: cached.has_cjs_exports,
629        has_angular_component_template_url: cached.has_angular_component_template_url,
630        content_hash: cached.content_hash,
631        parse_error_count: cached.parse_error_count,
632        parse_panicked: cached.parse_panicked,
633        parse_nesting_too_deep: cached.parse_nesting_too_deep,
634        suppressions: cached_suppressions_to_module(&cached.suppressions),
635        unknown_suppression_kinds: cached_unknown_suppressions_to_module(
636            &cached.unknown_suppression_kinds,
637        ),
638        range_marker_problems: cached_range_problems_to_module(&cached.range_marker_problems),
639        inline_threshold_overrides: cached_inline_thresholds_to_module(cached),
640        unused_import_bindings: cached.unused_import_bindings.clone(),
641        type_referenced_import_bindings: cached.type_referenced_import_bindings.clone(),
642        value_referenced_import_bindings: cached.value_referenced_import_bindings.clone(),
643        line_offsets: cached.line_offsets.clone(),
644        complexity: if need_complexity {
645            cached.complexity.clone()
646        } else {
647            Vec::new()
648        },
649        flag_uses: cached.flag_uses.clone(),
650        flag_registry_facts: cached.flag_registry_facts.clone(),
651        class_heritage: cached.class_heritage.clone(),
652        exported_factory_returns: cached_opt_to_arc(cached.exported_factory_returns.as_deref()),
653        exported_factory_return_object_shapes: cached_opt_to_arc(
654            cached.exported_factory_return_object_shapes.as_deref(),
655        ),
656        type_member_types: cached_opt_to_arc(cached.type_member_types.as_deref()),
657        injection_tokens: cached.injection_tokens.clone(),
658        local_type_declarations: cached_local_types_to_module(&cached.local_type_declarations),
659        public_signature_type_references: cached_signature_refs_to_module(
660            &cached.public_signature_type_references,
661        ),
662        namespace_object_aliases: cached_namespace_aliases_to_module(
663            &cached.namespace_object_aliases,
664        ),
665        iconify_prefixes: cached.iconify_prefixes.clone(),
666        iconify_icon_names: cached.iconify_icon_names.clone(),
667        auto_import_candidates: cached.auto_import_candidates.clone(),
668        directives: cached.directives.clone(),
669        client_only_dynamic_import_spans: cached.client_only_dynamic_import_spans.clone(),
670        env_reads: cached.env_reads.clone(),
671        security_sinks: cached.security_sinks.clone(),
672        security_sinks_skipped: cached.security_sinks_skipped,
673        security_unresolved_callee_sites: cached.security_unresolved_callee_sites.clone(),
674        inert_function_exports: cached.inert_function_exports.clone(),
675        tainted_bindings: cached.tainted_bindings.clone(),
676        sanitized_sink_args: cached.sanitized_sink_args.clone(),
677        security_control_sites: cached.security_control_sites.clone(),
678        callee_uses: cached.callee_uses.clone(),
679        command_invocations: cached.command_invocations.clone(),
680        imported_call_sites: cached.imported_call_sites.clone().into(),
681        import_binding_references: cached.import_binding_references.clone().into(),
682        misplaced_directives: cached.misplaced_directives.clone(),
683        inline_server_action_exports: cached.inline_server_action_exports.clone(),
684        di_key_sites: cached.di_key_sites.clone(),
685        has_dynamic_provide: cached.has_dynamic_provide,
686        is_server_action_module: cached.is_server_action_module,
687        has_global_declarations: cached.has_global_declarations,
688        triple_slash_reference_paths: cached.triple_slash_reference_paths.clone(),
689        jsx_runtime_from_config: cached.jsx_runtime_from_config,
690        // Derived in `release_resolution_payload` from `imports` + `unused_import_bindings`
691        // (both cached); never persisted, so the cache-load path leaves it empty.
692        referenced_import_bindings: Vec::new(),
693        component_props: cached.component_props.clone(),
694        component_contracts: cached.component_contracts.clone(),
695        effect_facts: cached.effect_facts.clone(),
696        function_contracts: match need_call_facts.then(|| cached_call_facts(cached)) {
697            Some(CachedCallFacts::Usable(facts)) => facts,
698            Some(CachedCallFacts::Unusable) | None => None,
699        },
700        has_props_attrs_fallthrough: cached.has_props_attrs_fallthrough,
701        has_define_expose: cached.has_define_expose,
702        has_define_model: cached.has_define_model,
703        has_unharvestable_props: cached.has_unharvestable_props,
704        component_emits: cached.component_emits.clone(),
705        angular_inputs: cached.angular_inputs.clone(),
706        angular_outputs: cached.angular_outputs.clone(),
707        angular_component_selectors: cached.angular_component_selectors.clone(),
708        registered_custom_elements: cached.registered_custom_elements.clone(),
709        used_custom_element_tags: cached.used_custom_element_tags.clone(),
710        angular_used_selectors: cached.angular_used_selectors.clone(),
711        angular_entry_component_refs: cached.angular_entry_component_refs.clone(),
712        has_dynamic_component_render: cached.has_dynamic_component_render,
713        has_unharvestable_emits: cached.has_unharvestable_emits,
714        has_dynamic_emit: cached.has_dynamic_emit,
715        has_emit_whole_object_use: cached.has_emit_whole_object_use,
716        load_return_keys: cached.load_return_keys.clone(),
717        has_unharvestable_load: cached.has_unharvestable_load,
718        has_load_data_whole_use: cached.has_load_data_whole_use,
719        // Derived in `release_resolution_payload` from `whole_object_uses`.
720        has_page_data_store_whole_use: false,
721        // Derived in `release_resolution_payload` from `whole_object_uses`.
722        has_route_loader_data_whole_use: false,
723        component_functions: cached.component_functions.clone(),
724        react_props: cached.react_props.clone(),
725        hook_uses: cached.hook_uses.clone(),
726        render_edges: cached.render_edges.clone(),
727        svelte_dispatched_events: cached.svelte_dispatched_events.clone(),
728        svelte_listened_events: cached.svelte_listened_events.clone(),
729        has_dynamic_dispatch: cached.has_dynamic_dispatch,
730    }
731}
732
733/// Convert a [`ModuleInfo`](crate::ModuleInfo) to a [`CachedModule`] for storage.
734///
735/// The [`SourceFingerprint`](fallow_types::source_fingerprint::SourceFingerprint)
736/// comes from `std::fs::metadata()` at parse time and enables fast cache
737/// validation on subsequent runs.
738///
739/// `call_facts_extracted` is `true` when the run parsed the module with its
740/// call facts. Only then does the entry store them. A run that reads no call
741/// facts passes `false`, so it does not pay their encode, and the entry
742/// records that the facts are absent.
743#[must_use]
744pub fn module_to_cached(
745    module: &crate::ModuleInfo,
746    fingerprint: fallow_types::source_fingerprint::SourceFingerprint,
747    complexity_extracted: bool,
748    call_facts_extracted: bool,
749) -> CachedModule {
750    let mut cached = module_to_cached_payload(module);
751    cached.call_facts =
752        call_facts_extracted.then(|| encode_call_facts(module.function_contracts.as_deref()));
753    cached.mtime_ns = fingerprint.mtime_ns;
754    cached.ctime_ns = fingerprint.ctime_ns;
755    cached.file_size = fingerprint.file_size;
756    cached.complexity_extracted = complexity_extracted;
757    cached
758}
759
760#[expect(
761    clippy::too_many_lines,
762    reason = "flat field projection preserves the complete extraction cache contract"
763)]
764fn module_to_cached_payload(module: &crate::ModuleInfo) -> CachedModule {
765    CachedModule {
766        content_hash: module.content_hash,
767        mtime_ns: 0,
768        ctime_ns: 0,
769        file_size: 0,
770        last_seen_secs: current_unix_seconds(),
771        exports: module_exports_to_cached(&module.exports),
772        imports: module_imports_to_cached(&module.imports),
773        re_exports: module_re_exports_to_cached(&module.re_exports),
774        dynamic_imports: module_dynamic_imports_to_cached(&module.dynamic_imports),
775        require_calls: module_require_calls_to_cached(&module.require_calls),
776        package_path_references: module.package_path_references.clone(),
777        type_package_references: module.type_package_references.clone(),
778        bin_path_references: module.bin_path_references.clone(),
779        package_resolve_sites: module.package_resolve_sites.clone(),
780        member_accesses: module.member_accesses.to_vec(),
781        semantic_facts: cached_semantic_facts(&module.semantic_facts),
782        whole_object_uses: Box::from(&*module.whole_object_uses),
783        dynamic_import_patterns: module_dynamic_patterns_to_cached(&module.dynamic_import_patterns),
784        parse_error_count: module.parse_error_count,
785        parse_panicked: module.parse_panicked,
786        parse_nesting_too_deep: module.parse_nesting_too_deep,
787        has_cjs_exports: module.has_cjs_exports,
788        has_angular_component_template_url: module.has_angular_component_template_url,
789        unused_import_bindings: module.unused_import_bindings.clone(),
790        type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
791        value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
792        suppressions: module_suppressions_to_cached(&module.suppressions),
793        unknown_suppression_kinds: module_unknown_suppressions_to_cached(
794            &module.unknown_suppression_kinds,
795        ),
796        range_marker_problems: module_range_problems_to_cached(&module.range_marker_problems),
797        inline_thresholds: module
798            .inline_threshold_overrides
799            .entries
800            .iter()
801            .map(|entry| CachedInlineThreshold {
802                line: entry.line,
803                comment_line: entry.comment_line,
804                max_cyclomatic: entry.max_cyclomatic,
805                max_cognitive: entry.max_cognitive,
806                max_crap: entry.max_crap,
807                max_unit_size: entry.max_unit_size,
808                reason: entry.reason.clone(),
809            })
810            .collect(),
811        inline_threshold_problems: module
812            .inline_threshold_overrides
813            .problems
814            .iter()
815            .map(|problem| CachedInlineThresholdProblem {
816                line: problem.line,
817                kind: problem.kind.to_code(),
818                token: problem.token.clone(),
819            })
820            .collect(),
821        line_offsets: module.line_offsets.clone(),
822        complexity: module.complexity.clone(),
823        complexity_extracted: false,
824        flag_uses: module.flag_uses.clone(),
825        flag_registry_facts: module.flag_registry_facts.clone(),
826        class_heritage: module.class_heritage.clone(),
827        exported_factory_returns: (!module.exported_factory_returns.is_empty())
828            .then(|| Box::from(&*module.exported_factory_returns)),
829        exported_factory_return_object_shapes: (!module
830            .exported_factory_return_object_shapes
831            .is_empty())
832        .then(|| Box::from(&*module.exported_factory_return_object_shapes)),
833        type_member_types: (!module.type_member_types.is_empty())
834            .then(|| Box::from(&*module.type_member_types)),
835        injection_tokens: module.injection_tokens.clone(),
836        local_type_declarations: module_local_types_to_cached(&module.local_type_declarations),
837        public_signature_type_references: module_signature_refs_to_cached(
838            &module.public_signature_type_references,
839        ),
840        namespace_object_aliases: module_namespace_aliases_to_cached(
841            &module.namespace_object_aliases,
842        ),
843        iconify_prefixes: module.iconify_prefixes.clone(),
844        iconify_icon_names: module.iconify_icon_names.clone(),
845        auto_import_candidates: module.auto_import_candidates.clone(),
846        directives: module.directives.clone(),
847        client_only_dynamic_import_spans: module.client_only_dynamic_import_spans.clone(),
848        env_reads: module.env_reads.clone(),
849        security_sinks: module.security_sinks.clone(),
850        security_sinks_skipped: module.security_sinks_skipped,
851        security_unresolved_callee_sites: module.security_unresolved_callee_sites.clone(),
852        inert_function_exports: module.inert_function_exports.clone(),
853        tainted_bindings: module.tainted_bindings.clone(),
854        sanitized_sink_args: module.sanitized_sink_args.clone(),
855        security_control_sites: module.security_control_sites.clone(),
856        callee_uses: module.callee_uses.clone(),
857        command_invocations: module.command_invocations.clone(),
858        imported_call_sites: module.imported_call_sites.to_vec(),
859        import_binding_references: module.import_binding_references.to_vec(),
860        misplaced_directives: module.misplaced_directives.clone(),
861        inline_server_action_exports: module.inline_server_action_exports.clone(),
862        di_key_sites: module.di_key_sites.clone(),
863        has_dynamic_provide: module.has_dynamic_provide,
864        is_server_action_module: module.is_server_action_module,
865        has_global_declarations: module.has_global_declarations,
866        triple_slash_reference_paths: module.triple_slash_reference_paths.clone(),
867        jsx_runtime_from_config: module.jsx_runtime_from_config,
868        component_props: module.component_props.clone(),
869        component_contracts: module.component_contracts.clone(),
870        effect_facts: module.effect_facts.clone(),
871        call_facts: None,
872        has_props_attrs_fallthrough: module.has_props_attrs_fallthrough,
873        has_define_expose: module.has_define_expose,
874        has_define_model: module.has_define_model,
875        has_unharvestable_props: module.has_unharvestable_props,
876        component_emits: module.component_emits.clone(),
877        angular_inputs: module.angular_inputs.clone(),
878        angular_outputs: module.angular_outputs.clone(),
879        angular_component_selectors: module.angular_component_selectors.clone(),
880        registered_custom_elements: module.registered_custom_elements.clone(),
881        used_custom_element_tags: module.used_custom_element_tags.clone(),
882        angular_used_selectors: module.angular_used_selectors.clone(),
883        angular_entry_component_refs: module.angular_entry_component_refs.clone(),
884        has_dynamic_component_render: module.has_dynamic_component_render,
885        has_unharvestable_emits: module.has_unharvestable_emits,
886        has_dynamic_emit: module.has_dynamic_emit,
887        has_emit_whole_object_use: module.has_emit_whole_object_use,
888        load_return_keys: module.load_return_keys.clone(),
889        has_unharvestable_load: module.has_unharvestable_load,
890        has_load_data_whole_use: module.has_load_data_whole_use,
891        component_functions: module.component_functions.clone(),
892        react_props: module.react_props.clone(),
893        hook_uses: module.hook_uses.clone(),
894        render_edges: module.render_edges.clone(),
895        svelte_dispatched_events: module.svelte_dispatched_events.clone(),
896        svelte_listened_events: module.svelte_listened_events.clone(),
897        has_dynamic_dispatch: module.has_dynamic_dispatch,
898    }
899}
900
901/// Convert a module to a cache entry from explicit source-fingerprint parts.
902///
903/// Kept for tests that need literal invalidation inputs without filesystem
904/// metadata.
905#[cfg(test)]
906#[must_use]
907pub fn module_to_cached_from_parts(
908    module: &crate::ModuleInfo,
909    mtime_ns: u64,
910    file_size: u64,
911) -> CachedModule {
912    module_to_cached(
913        module,
914        fallow_types::source_fingerprint::SourceFingerprint::new(mtime_ns, file_size),
915        !module.complexity.is_empty(),
916        true,
917    )
918}
919
920/// Encode the call facts of a module as the blob of its cache entry. A module
921/// with no call facts gets an empty blob.
922fn encode_call_facts(facts: Option<&fallow_types::extract::FunctionContractFacts>) -> Box<[u8]> {
923    facts.map_or_else(Box::default, |facts| {
924        bitcode::encode(facts).into_boxed_slice()
925    })
926}
927
928/// Reconstruct a [`ModuleInfo`](crate::ModuleInfo) for a cache hit.
929///
930/// Returns `None` when `need_call_facts` is `true` and the entry cannot give
931/// the call facts: the run that wrote it did not record them, or the blob
932/// does not decode. The caller then parses the file again, so a run that
933/// reads call facts never sees a module whose facts are missing.
934#[must_use]
935pub fn cached_hit_to_module(
936    cached: &CachedModule,
937    file_id: fallow_types::discover::FileId,
938    need_complexity: bool,
939    need_call_facts: bool,
940) -> Option<crate::ModuleInfo> {
941    let facts = if need_call_facts {
942        match cached_call_facts(cached) {
943            CachedCallFacts::Usable(facts) => facts,
944            CachedCallFacts::Unusable => return None,
945        }
946    } else {
947        None
948    };
949    let mut module = cached_to_module_opts(cached, file_id, need_complexity, false);
950    module.function_contracts = facts;
951    Some(module)
952}
953
954/// The call facts of a cache entry.
955enum CachedCallFacts {
956    /// The facts of the module. `None` means that the module has none.
957    Usable(Option<Box<fallow_types::extract::FunctionContractFacts>>),
958    /// The writer did not record the facts, or the blob does not decode.
959    Unusable,
960}
961
962fn cached_call_facts(cached: &CachedModule) -> CachedCallFacts {
963    let Some(blob) = cached.call_facts.as_deref() else {
964        return CachedCallFacts::Unusable;
965    };
966    if blob.is_empty() {
967        return CachedCallFacts::Usable(None);
968    }
969    match bitcode::decode(blob) {
970        Ok(facts) => CachedCallFacts::Usable(Some(Box::new(facts))),
971        Err(_) => {
972            tracing::warn!("Cached call facts could not be decoded, parsing the file again");
973            CachedCallFacts::Unusable
974        }
975    }
976}
977
978fn cached_semantic_facts(
979    facts: &[fallow_types::extract::SemanticFact],
980) -> Option<Box<[fallow_types::extract::SemanticFact]>> {
981    (!facts.is_empty()).then(|| Box::from(facts))
982}