1use 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#[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#[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 })
86 .collect(),
87 super_class: export.super_class.clone(),
88 })
89 .collect()
90}
91
92fn cached_to_imported_name(kind: u8, name: &str) -> crate::ImportedName {
93 match kind {
94 IMPORT_KIND_DEFAULT => crate::ImportedName::Default,
95 IMPORT_KIND_NAMESPACE => crate::ImportedName::Namespace,
96 IMPORT_KIND_SIDE_EFFECT => crate::ImportedName::SideEffect,
97 _ => crate::ImportedName::Named(name.to_owned()),
98 }
99}
100
101fn imported_name_to_cached(imported_name: &crate::ImportedName) -> (u8, String) {
102 match imported_name {
103 crate::ImportedName::Named(name) => (IMPORT_KIND_NAMED, name.clone()),
104 crate::ImportedName::Default => (IMPORT_KIND_DEFAULT, String::new()),
105 crate::ImportedName::Namespace => (IMPORT_KIND_NAMESPACE, String::new()),
106 crate::ImportedName::SideEffect => (IMPORT_KIND_SIDE_EFFECT, String::new()),
107 }
108}
109
110fn cached_imports_to_module(imports: &[CachedImport]) -> Vec<crate::ImportInfo> {
111 imports
112 .iter()
113 .map(|import| crate::ImportInfo {
114 source: import.source.clone(),
115 imported_name: cached_to_imported_name(import.kind, &import.imported_name),
116 local_name: import.local_name.clone(),
117 is_type_only: import.is_type_only,
118 is_type_only_star: import.is_type_only_star,
119 from_style: import.from_style,
120 span: Span::new(import.span_start, import.span_end),
121 source_span: Span::new(import.source_span_start, import.source_span_end),
122 })
123 .collect()
124}
125
126fn cached_re_exports_to_module(re_exports: &[CachedReExport]) -> Vec<crate::ReExportInfo> {
127 re_exports
128 .iter()
129 .map(|re_export| crate::ReExportInfo {
130 source: re_export.source.clone(),
131 imported_name: re_export.imported_name.clone(),
132 exported_name: re_export.exported_name.clone(),
133 is_type_only: re_export.is_type_only,
134 span: Span::new(re_export.span_start, re_export.span_end),
135 statement_span: Span::new(re_export.statement_span_start, re_export.statement_span_end),
136 source_span: Span::new(re_export.source_span_start, re_export.source_span_end),
137 visibility: visibility_from_cached(re_export.visibility),
138 expected_unused_reason: re_export.expected_unused_reason.clone(),
139 })
140 .collect()
141}
142
143const fn visibility_from_cached(raw: u8) -> VisibilityTag {
145 match raw {
146 1 => VisibilityTag::Public,
147 2 => VisibilityTag::Internal,
148 3 => VisibilityTag::Beta,
149 4 => VisibilityTag::Alpha,
150 5 => VisibilityTag::ExpectedUnused,
151 _ => VisibilityTag::None,
152 }
153}
154
155fn cached_dynamic_imports_to_module(
156 dynamic_imports: &[CachedDynamicImport],
157) -> Vec<crate::DynamicImportInfo> {
158 dynamic_imports
159 .iter()
160 .map(|dynamic_import| crate::DynamicImportInfo {
161 source: dynamic_import.source.clone(),
162 span: Span::new(dynamic_import.span_start, dynamic_import.span_end),
163 destructured_names: dynamic_import.destructured_names.clone(),
164 local_name: dynamic_import.local_name.clone(),
165 is_speculative: dynamic_import.is_speculative,
166 value_escapes: dynamic_import.value_escapes,
167 })
168 .collect()
169}
170
171fn cached_require_calls_to_module(
172 require_calls: &[CachedRequireCall],
173) -> Vec<crate::RequireCallInfo> {
174 require_calls
175 .iter()
176 .map(|require_call| crate::RequireCallInfo {
177 source: require_call.source.clone(),
178 span: Span::new(require_call.span_start, require_call.span_end),
179 source_span: Span::new(require_call.source_span_start, require_call.source_span_end),
180 destructured_names: require_call.destructured_names.clone(),
181 destructured_locals: require_call.destructured_locals.clone(),
182 local_name: require_call.local_name.clone(),
183 is_type_only: require_call.is_type_only,
184 })
185 .collect()
186}
187
188fn cached_dynamic_patterns_to_module(
189 dynamic_import_patterns: &[CachedDynamicImportPattern],
190) -> Vec<crate::DynamicImportPattern> {
191 dynamic_import_patterns
192 .iter()
193 .map(|pattern| crate::DynamicImportPattern {
194 prefix: pattern.prefix.clone(),
195 suffix: pattern.suffix.clone(),
196 excludes: pattern.excludes.clone(),
197 span: Span::new(pattern.span_start, pattern.span_end),
198 mechanism: pattern.mechanism,
199 imported_name: cached_to_imported_name(pattern.import_kind, &pattern.imported_name),
200 })
201 .collect()
202}
203
204fn cached_suppressions_to_module(
205 suppressions: &[CachedSuppression],
206) -> Vec<crate::suppress::Suppression> {
207 suppressions
208 .iter()
209 .map(|suppression| {
210 let target = if suppression.kind == 0 {
211 None
212 } else if suppression.kind
213 == crate::suppress::IssueKind::PolicyViolation.to_discriminant()
214 && !suppression.policy_pack.is_empty()
215 && !suppression.policy_rule_id.is_empty()
216 {
217 Some(SuppressionTarget::PolicyRule(PolicyRuleSuppression::new(
218 suppression.policy_pack.clone(),
219 suppression.policy_rule_id.clone(),
220 )))
221 } else {
222 crate::suppress::IssueKind::from_discriminant(suppression.kind)
223 .map(SuppressionTarget::Issue)
224 };
225 crate::suppress::Suppression {
226 line: suppression.line,
227 comment_line: suppression.comment_line,
228 target,
229 reason: suppression.reason.clone(),
230 scope: cached_scope(suppression.line, suppression.range_end_line),
231 }
232 })
233 .collect()
234}
235
236const fn cached_scope(line: u32, range_end_line: u32) -> SuppressionScope {
239 if range_end_line == 0 {
240 SuppressionScope::for_line(line)
241 } else {
242 SuppressionScope::Range {
243 end_line: range_end_line,
244 }
245 }
246}
247
248fn cached_range_problems_to_module(
249 problems: &[CachedRangeMarkerProblem],
250) -> Vec<fallow_types::suppress::RangeMarkerProblem> {
251 problems
252 .iter()
253 .filter_map(|problem| {
254 Some(fallow_types::suppress::RangeMarkerProblem {
255 line: problem.line,
256 kind: fallow_types::suppress::RangeMarkerProblemKind::from_code(problem.kind)?,
257 token: problem.token.clone(),
258 })
259 })
260 .collect()
261}
262
263fn module_range_problems_to_cached(
264 problems: &[fallow_types::suppress::RangeMarkerProblem],
265) -> Vec<CachedRangeMarkerProblem> {
266 problems
267 .iter()
268 .map(|problem| CachedRangeMarkerProblem {
269 line: problem.line,
270 kind: problem.kind.to_code(),
271 token: problem.token.clone(),
272 })
273 .collect()
274}
275
276fn cached_inline_thresholds_to_module(
277 cached: &CachedModule,
278) -> fallow_types::inline_threshold::InlineThresholdOverrides {
279 use fallow_types::inline_threshold::{
280 InlineThresholdOverride, InlineThresholdProblem, InlineThresholdProblemKind,
281 };
282 fallow_types::inline_threshold::InlineThresholdOverrides {
283 entries: cached
284 .inline_thresholds
285 .iter()
286 .map(|entry| InlineThresholdOverride {
287 line: entry.line,
288 comment_line: entry.comment_line,
289 max_cyclomatic: entry.max_cyclomatic,
290 max_cognitive: entry.max_cognitive,
291 max_crap: entry.max_crap,
292 max_unit_size: entry.max_unit_size,
293 reason: entry.reason.clone(),
294 })
295 .collect(),
296 problems: cached
297 .inline_threshold_problems
298 .iter()
299 .filter_map(|problem| {
300 Some(InlineThresholdProblem {
301 line: problem.line,
302 kind: InlineThresholdProblemKind::from_code(problem.kind)?,
303 token: problem.token.clone(),
304 })
305 })
306 .collect(),
307 }
308}
309
310fn cached_unknown_suppressions_to_module(
311 unknown_suppression_kinds: &[CachedUnknownSuppressionKind],
312) -> Vec<fallow_types::suppress::UnknownSuppressionKind> {
313 unknown_suppression_kinds
314 .iter()
315 .map(|unknown| fallow_types::suppress::UnknownSuppressionKind {
316 comment_line: unknown.comment_line,
317 is_file_level: unknown.is_file_level,
318 token: unknown.token.clone(),
319 reason: unknown.reason.clone(),
320 })
321 .collect()
322}
323
324fn cached_local_types_to_module(
325 local_type_declarations: &[CachedLocalTypeDeclaration],
326) -> Vec<crate::LocalTypeDeclaration> {
327 local_type_declarations
328 .iter()
329 .map(|declaration| crate::LocalTypeDeclaration {
330 name: declaration.name.clone(),
331 span: Span::new(declaration.span_start, declaration.span_end),
332 })
333 .collect()
334}
335
336fn cached_signature_refs_to_module(
337 public_signature_type_references: &[CachedPublicSignatureTypeReference],
338) -> Vec<crate::PublicSignatureTypeReference> {
339 public_signature_type_references
340 .iter()
341 .map(|reference| crate::PublicSignatureTypeReference {
342 export_name: reference.export_name.clone(),
343 type_name: reference.type_name.clone(),
344 span: Span::new(reference.span_start, reference.span_end),
345 from_satisfies: reference.from_satisfies,
346 })
347 .collect()
348}
349
350fn cached_namespace_aliases_to_module(
351 namespace_object_aliases: &[CachedNamespaceObjectAlias],
352) -> Vec<NamespaceObjectAlias> {
353 namespace_object_aliases
354 .iter()
355 .map(|alias| NamespaceObjectAlias {
356 via_export_name: alias.via_export_name.clone(),
357 suffix: alias.suffix.clone(),
358 namespace_local: alias.namespace_local.clone(),
359 })
360 .collect()
361}
362
363fn module_exports_to_cached(exports: &[crate::ExportInfo]) -> Vec<CachedExport> {
364 exports
365 .iter()
366 .map(|export| CachedExport {
367 name: match &export.name {
368 ExportName::Named(name) => name.clone(),
369 ExportName::Default => String::new(),
370 },
371 is_default: matches!(export.name, ExportName::Default),
372 is_type_only: export.is_type_only,
373 is_side_effect_used: export.is_side_effect_used,
374 visibility: export.visibility as u8,
375 expected_unused_reason: export.expected_unused_reason.clone(),
376 deprecated: export.deprecated,
377 deprecated_reason: export.deprecated_reason.clone(),
378 local_name: export.local_name.clone(),
379 span_start: export.span.start,
380 span_end: export.span.end,
381 members: export
382 .members
383 .iter()
384 .map(|member| CachedMember {
385 name: member.name.clone(),
386 kind: member.kind,
387 span_start: member.span.start,
388 span_end: member.span.end,
389 has_decorator: member.has_decorator,
390 decorator_names: member.decorator_names.clone(),
391 is_instance_returning_static: member.is_instance_returning_static,
392 is_self_returning: member.is_self_returning,
393 override_base: member.override_base.clone(),
394 is_protected: member.is_protected,
395 is_static: member.is_static,
396 })
397 .collect(),
398 super_class: export.super_class.clone(),
399 })
400 .collect()
401}
402
403fn module_imports_to_cached(imports: &[crate::ImportInfo]) -> Vec<CachedImport> {
404 imports
405 .iter()
406 .map(|import| {
407 let (kind, imported_name) = imported_name_to_cached(&import.imported_name);
408 CachedImport {
409 source: import.source.clone(),
410 imported_name,
411 local_name: import.local_name.clone(),
412 is_type_only: import.is_type_only,
413 is_type_only_star: import.is_type_only_star,
414 from_style: import.from_style,
415 kind,
416 span_start: import.span.start,
417 span_end: import.span.end,
418 source_span_start: import.source_span.start,
419 source_span_end: import.source_span.end,
420 }
421 })
422 .collect()
423}
424
425fn module_re_exports_to_cached(re_exports: &[crate::ReExportInfo]) -> Vec<CachedReExport> {
426 re_exports
427 .iter()
428 .map(|re_export| CachedReExport {
429 source: re_export.source.clone(),
430 imported_name: re_export.imported_name.clone(),
431 exported_name: re_export.exported_name.clone(),
432 is_type_only: re_export.is_type_only,
433 span_start: re_export.span.start,
434 span_end: re_export.span.end,
435 statement_span_start: re_export.statement_span.start,
436 statement_span_end: re_export.statement_span.end,
437 source_span_start: re_export.source_span.start,
438 source_span_end: re_export.source_span.end,
439 visibility: re_export.visibility as u8,
440 expected_unused_reason: re_export.expected_unused_reason.clone(),
441 })
442 .collect()
443}
444
445fn module_dynamic_imports_to_cached(
446 dynamic_imports: &[crate::DynamicImportInfo],
447) -> Vec<CachedDynamicImport> {
448 dynamic_imports
449 .iter()
450 .map(|dynamic_import| CachedDynamicImport {
451 source: dynamic_import.source.clone(),
452 span_start: dynamic_import.span.start,
453 span_end: dynamic_import.span.end,
454 destructured_names: dynamic_import.destructured_names.clone(),
455 local_name: dynamic_import.local_name.clone(),
456 is_speculative: dynamic_import.is_speculative,
457 value_escapes: dynamic_import.value_escapes,
458 })
459 .collect()
460}
461
462fn module_require_calls_to_cached(
463 require_calls: &[crate::RequireCallInfo],
464) -> Vec<CachedRequireCall> {
465 require_calls
466 .iter()
467 .map(|require_call| CachedRequireCall {
468 source: require_call.source.clone(),
469 span_start: require_call.span.start,
470 span_end: require_call.span.end,
471 source_span_start: require_call.source_span.start,
472 source_span_end: require_call.source_span.end,
473 destructured_names: require_call.destructured_names.clone(),
474 destructured_locals: require_call.destructured_locals.clone(),
475 local_name: require_call.local_name.clone(),
476 is_type_only: require_call.is_type_only,
477 })
478 .collect()
479}
480
481fn module_dynamic_patterns_to_cached(
482 dynamic_import_patterns: &[crate::DynamicImportPattern],
483) -> Vec<CachedDynamicImportPattern> {
484 dynamic_import_patterns
485 .iter()
486 .map(|pattern| {
487 let (import_kind, imported_name) = imported_name_to_cached(&pattern.imported_name);
488 CachedDynamicImportPattern {
489 prefix: pattern.prefix.clone(),
490 suffix: pattern.suffix.clone(),
491 excludes: pattern.excludes.clone(),
492 span_start: pattern.span.start,
493 span_end: pattern.span.end,
494 mechanism: pattern.mechanism,
495 import_kind,
496 imported_name,
497 }
498 })
499 .collect()
500}
501
502fn module_suppressions_to_cached(
503 suppressions: &[crate::suppress::Suppression],
504) -> Vec<CachedSuppression> {
505 suppressions
506 .iter()
507 .map(|suppression| {
508 let (kind, policy_pack, policy_rule_id) = match &suppression.target {
509 None => (0, String::new(), String::new()),
510 Some(SuppressionTarget::Issue(kind)) => {
511 (kind.to_discriminant(), String::new(), String::new())
512 }
513 Some(SuppressionTarget::PolicyRule(target)) => (
514 crate::suppress::IssueKind::PolicyViolation.to_discriminant(),
515 target.pack.clone(),
516 target.rule_id.clone(),
517 ),
518 };
519 CachedSuppression {
520 line: suppression.line,
521 comment_line: suppression.comment_line,
522 kind,
523 policy_pack,
524 policy_rule_id,
525 reason: suppression.reason.clone(),
526 range_end_line: suppression.range_end_line().unwrap_or(0),
527 }
528 })
529 .collect()
530}
531
532fn module_unknown_suppressions_to_cached(
533 unknown_suppression_kinds: &[fallow_types::suppress::UnknownSuppressionKind],
534) -> Vec<CachedUnknownSuppressionKind> {
535 unknown_suppression_kinds
536 .iter()
537 .map(|unknown| CachedUnknownSuppressionKind {
538 comment_line: unknown.comment_line,
539 is_file_level: unknown.is_file_level,
540 token: unknown.token.clone(),
541 reason: unknown.reason.clone(),
542 })
543 .collect()
544}
545
546fn module_local_types_to_cached(
547 local_type_declarations: &[crate::LocalTypeDeclaration],
548) -> Vec<CachedLocalTypeDeclaration> {
549 local_type_declarations
550 .iter()
551 .map(|declaration| CachedLocalTypeDeclaration {
552 name: declaration.name.clone(),
553 span_start: declaration.span.start,
554 span_end: declaration.span.end,
555 })
556 .collect()
557}
558
559fn module_signature_refs_to_cached(
560 public_signature_type_references: &[crate::PublicSignatureTypeReference],
561) -> Vec<CachedPublicSignatureTypeReference> {
562 public_signature_type_references
563 .iter()
564 .map(|reference| CachedPublicSignatureTypeReference {
565 export_name: reference.export_name.clone(),
566 type_name: reference.type_name.clone(),
567 span_start: reference.span.start,
568 span_end: reference.span.end,
569 from_satisfies: reference.from_satisfies,
570 })
571 .collect()
572}
573
574fn module_namespace_aliases_to_cached(
575 namespace_object_aliases: &[NamespaceObjectAlias],
576) -> Vec<CachedNamespaceObjectAlias> {
577 namespace_object_aliases
578 .iter()
579 .map(|alias| CachedNamespaceObjectAlias {
580 via_export_name: alias.via_export_name.clone(),
581 suffix: alias.suffix.clone(),
582 namespace_local: alias.namespace_local.clone(),
583 })
584 .collect()
585}
586
587fn cached_opt_to_arc<T: Clone>(cached: Option<&[T]>) -> Arc<[T]> {
589 cached.map(Arc::from).unwrap_or_default()
590}
591
592#[must_use]
601#[expect(
602 clippy::too_many_lines,
603 reason = "flat field projection preserves the complete extraction cache contract"
604)]
605pub fn cached_to_module_opts(
606 cached: &CachedModule,
607 file_id: fallow_types::discover::FileId,
608 need_complexity: bool,
609 need_call_facts: bool,
610) -> crate::ModuleInfo {
611 crate::ModuleInfo {
612 file_id,
613 exports: cached_exports_to_module(&cached.exports).into(),
614 imports: cached_imports_to_module(&cached.imports),
615 re_exports: cached_re_exports_to_module(&cached.re_exports),
616 dynamic_imports: cached_dynamic_imports_to_module(&cached.dynamic_imports),
617 dynamic_import_patterns: cached_dynamic_patterns_to_module(&cached.dynamic_import_patterns),
618 require_calls: cached_require_calls_to_module(&cached.require_calls),
619 package_path_references: cached.package_path_references.clone(),
620 type_package_references: cached.type_package_references.clone(),
621 bin_path_references: cached.bin_path_references.clone(),
622 package_resolve_sites: cached.package_resolve_sites.clone(),
623 member_accesses: cached.member_accesses.clone().into(),
624 semantic_facts: cached_opt_to_arc(cached.semantic_facts.as_deref()),
625 whole_object_uses: Arc::from(&*cached.whole_object_uses),
626 has_cjs_exports: cached.has_cjs_exports,
627 has_angular_component_template_url: cached.has_angular_component_template_url,
628 content_hash: cached.content_hash,
629 parse_error_count: cached.parse_error_count,
630 parse_panicked: cached.parse_panicked,
631 parse_nesting_too_deep: cached.parse_nesting_too_deep,
632 suppressions: cached_suppressions_to_module(&cached.suppressions),
633 unknown_suppression_kinds: cached_unknown_suppressions_to_module(
634 &cached.unknown_suppression_kinds,
635 ),
636 range_marker_problems: cached_range_problems_to_module(&cached.range_marker_problems),
637 inline_threshold_overrides: cached_inline_thresholds_to_module(cached),
638 unused_import_bindings: cached.unused_import_bindings.clone(),
639 type_referenced_import_bindings: cached.type_referenced_import_bindings.clone(),
640 value_referenced_import_bindings: cached.value_referenced_import_bindings.clone(),
641 line_offsets: cached.line_offsets.clone(),
642 complexity: if need_complexity {
643 cached.complexity.clone()
644 } else {
645 Vec::new()
646 },
647 flag_uses: cached.flag_uses.clone(),
648 flag_registry_facts: cached.flag_registry_facts.clone(),
649 class_heritage: cached.class_heritage.clone(),
650 exported_factory_returns: cached_opt_to_arc(cached.exported_factory_returns.as_deref()),
651 exported_factory_return_object_shapes: cached_opt_to_arc(
652 cached.exported_factory_return_object_shapes.as_deref(),
653 ),
654 type_member_types: cached_opt_to_arc(cached.type_member_types.as_deref()),
655 injection_tokens: cached.injection_tokens.clone(),
656 local_type_declarations: cached_local_types_to_module(&cached.local_type_declarations),
657 public_signature_type_references: cached_signature_refs_to_module(
658 &cached.public_signature_type_references,
659 ),
660 namespace_object_aliases: cached_namespace_aliases_to_module(
661 &cached.namespace_object_aliases,
662 ),
663 iconify_prefixes: cached.iconify_prefixes.clone(),
664 iconify_icon_names: cached.iconify_icon_names.clone(),
665 auto_import_candidates: cached.auto_import_candidates.clone(),
666 directives: cached.directives.clone(),
667 client_only_dynamic_import_spans: cached.client_only_dynamic_import_spans.clone(),
668 env_reads: cached.env_reads.clone(),
669 security_sinks: cached.security_sinks.clone(),
670 security_sinks_skipped: cached.security_sinks_skipped,
671 security_unresolved_callee_sites: cached.security_unresolved_callee_sites.clone(),
672 inert_function_exports: cached.inert_function_exports.clone(),
673 tainted_bindings: cached.tainted_bindings.clone(),
674 sanitized_sink_args: cached.sanitized_sink_args.clone(),
675 security_control_sites: cached.security_control_sites.clone(),
676 callee_uses: cached.callee_uses.clone(),
677 command_invocations: cached.command_invocations.clone(),
678 imported_call_sites: cached.imported_call_sites.clone().into(),
679 import_binding_references: cached.import_binding_references.clone().into(),
680 misplaced_directives: cached.misplaced_directives.clone(),
681 inline_server_action_exports: cached.inline_server_action_exports.clone(),
682 di_key_sites: cached.di_key_sites.clone(),
683 has_dynamic_provide: cached.has_dynamic_provide,
684 is_server_action_module: cached.is_server_action_module,
685 has_global_declarations: cached.has_global_declarations,
686 triple_slash_reference_paths: cached.triple_slash_reference_paths.clone(),
687 jsx_runtime_from_config: cached.jsx_runtime_from_config,
688 referenced_import_bindings: Vec::new(),
691 component_props: cached.component_props.clone(),
692 component_contracts: cached.component_contracts.clone(),
693 effect_facts: cached.effect_facts.clone(),
694 function_contracts: match need_call_facts.then(|| cached_call_facts(cached)) {
695 Some(CachedCallFacts::Usable(facts)) => facts,
696 Some(CachedCallFacts::Unusable) | None => None,
697 },
698 has_props_attrs_fallthrough: cached.has_props_attrs_fallthrough,
699 has_define_expose: cached.has_define_expose,
700 has_define_model: cached.has_define_model,
701 has_unharvestable_props: cached.has_unharvestable_props,
702 component_emits: cached.component_emits.clone(),
703 angular_inputs: cached.angular_inputs.clone(),
704 angular_outputs: cached.angular_outputs.clone(),
705 angular_component_selectors: cached.angular_component_selectors.clone(),
706 registered_custom_elements: cached.registered_custom_elements.clone(),
707 used_custom_element_tags: cached.used_custom_element_tags.clone(),
708 angular_used_selectors: cached.angular_used_selectors.clone(),
709 angular_entry_component_refs: cached.angular_entry_component_refs.clone(),
710 has_dynamic_component_render: cached.has_dynamic_component_render,
711 has_unharvestable_emits: cached.has_unharvestable_emits,
712 has_dynamic_emit: cached.has_dynamic_emit,
713 has_emit_whole_object_use: cached.has_emit_whole_object_use,
714 load_return_keys: cached.load_return_keys.clone(),
715 has_unharvestable_load: cached.has_unharvestable_load,
716 has_load_data_whole_use: cached.has_load_data_whole_use,
717 has_page_data_store_whole_use: false,
719 has_route_loader_data_whole_use: false,
721 component_functions: cached.component_functions.clone(),
722 react_props: cached.react_props.clone(),
723 hook_uses: cached.hook_uses.clone(),
724 render_edges: cached.render_edges.clone(),
725 svelte_dispatched_events: cached.svelte_dispatched_events.clone(),
726 svelte_listened_events: cached.svelte_listened_events.clone(),
727 has_dynamic_dispatch: cached.has_dynamic_dispatch,
728 }
729}
730
731#[must_use]
742pub fn module_to_cached(
743 module: &crate::ModuleInfo,
744 fingerprint: fallow_types::source_fingerprint::SourceFingerprint,
745 complexity_extracted: bool,
746 call_facts_extracted: bool,
747) -> CachedModule {
748 let mut cached = module_to_cached_payload(module);
749 cached.call_facts =
750 call_facts_extracted.then(|| encode_call_facts(module.function_contracts.as_deref()));
751 cached.mtime_ns = fingerprint.mtime_ns;
752 cached.ctime_ns = fingerprint.ctime_ns;
753 cached.file_size = fingerprint.file_size;
754 cached.complexity_extracted = complexity_extracted;
755 cached
756}
757
758#[expect(
759 clippy::too_many_lines,
760 reason = "flat field projection preserves the complete extraction cache contract"
761)]
762fn module_to_cached_payload(module: &crate::ModuleInfo) -> CachedModule {
763 CachedModule {
764 content_hash: module.content_hash,
765 mtime_ns: 0,
766 ctime_ns: 0,
767 file_size: 0,
768 last_seen_secs: current_unix_seconds(),
769 exports: module_exports_to_cached(&module.exports),
770 imports: module_imports_to_cached(&module.imports),
771 re_exports: module_re_exports_to_cached(&module.re_exports),
772 dynamic_imports: module_dynamic_imports_to_cached(&module.dynamic_imports),
773 require_calls: module_require_calls_to_cached(&module.require_calls),
774 package_path_references: module.package_path_references.clone(),
775 type_package_references: module.type_package_references.clone(),
776 bin_path_references: module.bin_path_references.clone(),
777 package_resolve_sites: module.package_resolve_sites.clone(),
778 member_accesses: module.member_accesses.to_vec(),
779 semantic_facts: cached_semantic_facts(&module.semantic_facts),
780 whole_object_uses: Box::from(&*module.whole_object_uses),
781 dynamic_import_patterns: module_dynamic_patterns_to_cached(&module.dynamic_import_patterns),
782 parse_error_count: module.parse_error_count,
783 parse_panicked: module.parse_panicked,
784 parse_nesting_too_deep: module.parse_nesting_too_deep,
785 has_cjs_exports: module.has_cjs_exports,
786 has_angular_component_template_url: module.has_angular_component_template_url,
787 unused_import_bindings: module.unused_import_bindings.clone(),
788 type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
789 value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
790 suppressions: module_suppressions_to_cached(&module.suppressions),
791 unknown_suppression_kinds: module_unknown_suppressions_to_cached(
792 &module.unknown_suppression_kinds,
793 ),
794 range_marker_problems: module_range_problems_to_cached(&module.range_marker_problems),
795 inline_thresholds: module
796 .inline_threshold_overrides
797 .entries
798 .iter()
799 .map(|entry| CachedInlineThreshold {
800 line: entry.line,
801 comment_line: entry.comment_line,
802 max_cyclomatic: entry.max_cyclomatic,
803 max_cognitive: entry.max_cognitive,
804 max_crap: entry.max_crap,
805 max_unit_size: entry.max_unit_size,
806 reason: entry.reason.clone(),
807 })
808 .collect(),
809 inline_threshold_problems: module
810 .inline_threshold_overrides
811 .problems
812 .iter()
813 .map(|problem| CachedInlineThresholdProblem {
814 line: problem.line,
815 kind: problem.kind.to_code(),
816 token: problem.token.clone(),
817 })
818 .collect(),
819 line_offsets: module.line_offsets.clone(),
820 complexity: module.complexity.clone(),
821 complexity_extracted: false,
822 flag_uses: module.flag_uses.clone(),
823 flag_registry_facts: module.flag_registry_facts.clone(),
824 class_heritage: module.class_heritage.clone(),
825 exported_factory_returns: (!module.exported_factory_returns.is_empty())
826 .then(|| Box::from(&*module.exported_factory_returns)),
827 exported_factory_return_object_shapes: (!module
828 .exported_factory_return_object_shapes
829 .is_empty())
830 .then(|| Box::from(&*module.exported_factory_return_object_shapes)),
831 type_member_types: (!module.type_member_types.is_empty())
832 .then(|| Box::from(&*module.type_member_types)),
833 injection_tokens: module.injection_tokens.clone(),
834 local_type_declarations: module_local_types_to_cached(&module.local_type_declarations),
835 public_signature_type_references: module_signature_refs_to_cached(
836 &module.public_signature_type_references,
837 ),
838 namespace_object_aliases: module_namespace_aliases_to_cached(
839 &module.namespace_object_aliases,
840 ),
841 iconify_prefixes: module.iconify_prefixes.clone(),
842 iconify_icon_names: module.iconify_icon_names.clone(),
843 auto_import_candidates: module.auto_import_candidates.clone(),
844 directives: module.directives.clone(),
845 client_only_dynamic_import_spans: module.client_only_dynamic_import_spans.clone(),
846 env_reads: module.env_reads.clone(),
847 security_sinks: module.security_sinks.clone(),
848 security_sinks_skipped: module.security_sinks_skipped,
849 security_unresolved_callee_sites: module.security_unresolved_callee_sites.clone(),
850 inert_function_exports: module.inert_function_exports.clone(),
851 tainted_bindings: module.tainted_bindings.clone(),
852 sanitized_sink_args: module.sanitized_sink_args.clone(),
853 security_control_sites: module.security_control_sites.clone(),
854 callee_uses: module.callee_uses.clone(),
855 command_invocations: module.command_invocations.clone(),
856 imported_call_sites: module.imported_call_sites.to_vec(),
857 import_binding_references: module.import_binding_references.to_vec(),
858 misplaced_directives: module.misplaced_directives.clone(),
859 inline_server_action_exports: module.inline_server_action_exports.clone(),
860 di_key_sites: module.di_key_sites.clone(),
861 has_dynamic_provide: module.has_dynamic_provide,
862 is_server_action_module: module.is_server_action_module,
863 has_global_declarations: module.has_global_declarations,
864 triple_slash_reference_paths: module.triple_slash_reference_paths.clone(),
865 jsx_runtime_from_config: module.jsx_runtime_from_config,
866 component_props: module.component_props.clone(),
867 component_contracts: module.component_contracts.clone(),
868 effect_facts: module.effect_facts.clone(),
869 call_facts: None,
870 has_props_attrs_fallthrough: module.has_props_attrs_fallthrough,
871 has_define_expose: module.has_define_expose,
872 has_define_model: module.has_define_model,
873 has_unharvestable_props: module.has_unharvestable_props,
874 component_emits: module.component_emits.clone(),
875 angular_inputs: module.angular_inputs.clone(),
876 angular_outputs: module.angular_outputs.clone(),
877 angular_component_selectors: module.angular_component_selectors.clone(),
878 registered_custom_elements: module.registered_custom_elements.clone(),
879 used_custom_element_tags: module.used_custom_element_tags.clone(),
880 angular_used_selectors: module.angular_used_selectors.clone(),
881 angular_entry_component_refs: module.angular_entry_component_refs.clone(),
882 has_dynamic_component_render: module.has_dynamic_component_render,
883 has_unharvestable_emits: module.has_unharvestable_emits,
884 has_dynamic_emit: module.has_dynamic_emit,
885 has_emit_whole_object_use: module.has_emit_whole_object_use,
886 load_return_keys: module.load_return_keys.clone(),
887 has_unharvestable_load: module.has_unharvestable_load,
888 has_load_data_whole_use: module.has_load_data_whole_use,
889 component_functions: module.component_functions.clone(),
890 react_props: module.react_props.clone(),
891 hook_uses: module.hook_uses.clone(),
892 render_edges: module.render_edges.clone(),
893 svelte_dispatched_events: module.svelte_dispatched_events.clone(),
894 svelte_listened_events: module.svelte_listened_events.clone(),
895 has_dynamic_dispatch: module.has_dynamic_dispatch,
896 }
897}
898
899#[cfg(test)]
904#[must_use]
905pub fn module_to_cached_from_parts(
906 module: &crate::ModuleInfo,
907 mtime_ns: u64,
908 file_size: u64,
909) -> CachedModule {
910 module_to_cached(
911 module,
912 fallow_types::source_fingerprint::SourceFingerprint::new(mtime_ns, file_size),
913 !module.complexity.is_empty(),
914 true,
915 )
916}
917
918fn encode_call_facts(facts: Option<&fallow_types::extract::FunctionContractFacts>) -> Box<[u8]> {
921 facts.map_or_else(Box::default, |facts| {
922 bitcode::encode(facts).into_boxed_slice()
923 })
924}
925
926#[must_use]
933pub fn cached_hit_to_module(
934 cached: &CachedModule,
935 file_id: fallow_types::discover::FileId,
936 need_complexity: bool,
937 need_call_facts: bool,
938) -> Option<crate::ModuleInfo> {
939 let facts = if need_call_facts {
940 match cached_call_facts(cached) {
941 CachedCallFacts::Usable(facts) => facts,
942 CachedCallFacts::Unusable => return None,
943 }
944 } else {
945 None
946 };
947 let mut module = cached_to_module_opts(cached, file_id, need_complexity, false);
948 module.function_contracts = facts;
949 Some(module)
950}
951
952enum CachedCallFacts {
954 Usable(Option<Box<fallow_types::extract::FunctionContractFacts>>),
956 Unusable,
958}
959
960fn cached_call_facts(cached: &CachedModule) -> CachedCallFacts {
961 let Some(blob) = cached.call_facts.as_deref() else {
962 return CachedCallFacts::Unusable;
963 };
964 if blob.is_empty() {
965 return CachedCallFacts::Usable(None);
966 }
967 match bitcode::decode(blob) {
968 Ok(facts) => CachedCallFacts::Usable(Some(Box::new(facts))),
969 Err(_) => {
970 tracing::warn!("Cached call facts could not be decoded, parsing the file again");
971 CachedCallFacts::Unusable
972 }
973 }
974}
975
976fn cached_semantic_facts(
977 facts: &[fallow_types::extract::SemanticFact],
978) -> Option<Box<[fallow_types::extract::SemanticFact]>> {
979 (!facts.is_empty()).then(|| Box::from(facts))
980}