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::time::{SystemTime, UNIX_EPOCH};
11
12use oxc_span::Span;
13
14use crate::ExportName;
15use fallow_types::extract::{NamespaceObjectAlias, VisibilityTag};
16
17/// Seconds-since-Unix-epoch from the wall clock, saturating to 0 if the
18/// system clock is set before the epoch. Used as the LRU bookkeeping
19/// timestamp on `CachedModule.last_access_secs`. Wall-clock (not monotonic)
20/// is the right source here because the value persists across process
21/// invocations.
22#[must_use]
23pub fn current_unix_seconds() -> u64 {
24    SystemTime::now()
25        .duration_since(UNIX_EPOCH)
26        .map_or(0, |d| d.as_secs())
27}
28
29use super::types::{
30    CachedDynamicImport, CachedDynamicImportPattern, CachedExport, CachedImport,
31    CachedLocalTypeDeclaration, CachedMember, CachedModule, CachedNamespaceObjectAlias,
32    CachedPublicSignatureTypeReference, CachedReExport, CachedRequireCall, CachedSuppression,
33    CachedUnknownSuppressionKind, IMPORT_KIND_DEFAULT, IMPORT_KIND_NAMED, IMPORT_KIND_NAMESPACE,
34    IMPORT_KIND_SIDE_EFFECT,
35};
36
37/// Reconstruct a [`ModuleInfo`](crate::ModuleInfo) from a [`CachedModule`].
38#[must_use]
39pub fn cached_to_module(
40    cached: &CachedModule,
41    file_id: fallow_types::discover::FileId,
42) -> crate::ModuleInfo {
43    cached_to_module_opts(cached, file_id, true)
44}
45
46/// Reconstruct a [`ModuleInfo`](crate::ModuleInfo) from a [`CachedModule`], skipping
47/// the per-function complexity vec when `need_complexity` is `false`. Avoids the
48/// `Vec<FunctionComplexity>` clone on warm runs of commands (e.g. `fallow check`)
49/// that don't consume complexity, which adds up across tens of thousands of files.
50#[must_use]
51#[expect(
52    clippy::too_many_lines,
53    reason = "single flat field-by-field deserialization; splitting it harms readability"
54)]
55pub fn cached_to_module_opts(
56    cached: &CachedModule,
57    file_id: fallow_types::discover::FileId,
58    need_complexity: bool,
59) -> crate::ModuleInfo {
60    use crate::{
61        DynamicImportInfo, ExportInfo, ImportInfo, ImportedName, LocalTypeDeclaration, MemberInfo,
62        ModuleInfo, PublicSignatureTypeReference, ReExportInfo, RequireCallInfo,
63    };
64
65    let exports = cached
66        .exports
67        .iter()
68        .map(|e| ExportInfo {
69            name: if e.is_default {
70                ExportName::Default
71            } else {
72                ExportName::Named(e.name.clone())
73            },
74            local_name: e.local_name.clone(),
75            is_type_only: e.is_type_only,
76            is_side_effect_used: e.is_side_effect_used,
77            visibility: match e.visibility {
78                1 => VisibilityTag::Public,
79                2 => VisibilityTag::Internal,
80                3 => VisibilityTag::Beta,
81                4 => VisibilityTag::Alpha,
82                5 => VisibilityTag::ExpectedUnused,
83                _ => VisibilityTag::None,
84            },
85            span: Span::new(e.span_start, e.span_end),
86            members: e
87                .members
88                .iter()
89                .map(|m| MemberInfo {
90                    name: m.name.clone(),
91                    kind: m.kind,
92                    span: Span::new(m.span_start, m.span_end),
93                    has_decorator: m.has_decorator,
94                    decorator_names: m.decorator_names.clone(),
95                    is_instance_returning_static: m.is_instance_returning_static,
96                    is_self_returning: m.is_self_returning,
97                })
98                .collect(),
99            super_class: e.super_class.clone(),
100        })
101        .collect();
102
103    let imports = cached
104        .imports
105        .iter()
106        .map(|i| ImportInfo {
107            source: i.source.clone(),
108            imported_name: match i.kind {
109                IMPORT_KIND_DEFAULT => ImportedName::Default,
110                IMPORT_KIND_NAMESPACE => ImportedName::Namespace,
111                IMPORT_KIND_SIDE_EFFECT => ImportedName::SideEffect,
112                // IMPORT_KIND_NAMED (0) and any unknown value default to Named
113                _ => ImportedName::Named(i.imported_name.clone()),
114            },
115            local_name: i.local_name.clone(),
116            is_type_only: i.is_type_only,
117            from_style: i.from_style,
118            span: Span::new(i.span_start, i.span_end),
119            source_span: Span::new(i.source_span_start, i.source_span_end),
120        })
121        .collect();
122
123    let re_exports = cached
124        .re_exports
125        .iter()
126        .map(|r| ReExportInfo {
127            source: r.source.clone(),
128            imported_name: r.imported_name.clone(),
129            exported_name: r.exported_name.clone(),
130            is_type_only: r.is_type_only,
131            span: Span::new(r.span_start, r.span_end),
132        })
133        .collect();
134
135    let dynamic_imports = cached
136        .dynamic_imports
137        .iter()
138        .map(|d| DynamicImportInfo {
139            source: d.source.clone(),
140            span: Span::new(d.span_start, d.span_end),
141            destructured_names: d.destructured_names.clone(),
142            local_name: d.local_name.clone(),
143            is_speculative: d.is_speculative,
144        })
145        .collect();
146
147    let require_calls = cached
148        .require_calls
149        .iter()
150        .map(|r| RequireCallInfo {
151            source: r.source.clone(),
152            span: Span::new(r.span_start, r.span_end),
153            destructured_names: r.destructured_names.clone(),
154            local_name: r.local_name.clone(),
155        })
156        .collect();
157
158    let dynamic_import_patterns = cached
159        .dynamic_import_patterns
160        .iter()
161        .map(|p| crate::DynamicImportPattern {
162            prefix: p.prefix.clone(),
163            suffix: p.suffix.clone(),
164            span: Span::new(p.span_start, p.span_end),
165        })
166        .collect();
167
168    let suppressions = cached
169        .suppressions
170        .iter()
171        .map(|s| crate::suppress::Suppression {
172            line: s.line,
173            comment_line: s.comment_line,
174            kind: if s.kind == 0 {
175                None
176            } else {
177                crate::suppress::IssueKind::from_discriminant(s.kind)
178            },
179        })
180        .collect();
181
182    let unknown_suppression_kinds = cached
183        .unknown_suppression_kinds
184        .iter()
185        .map(|u| fallow_types::suppress::UnknownSuppressionKind {
186            comment_line: u.comment_line,
187            is_file_level: u.is_file_level,
188            token: u.token.clone(),
189        })
190        .collect();
191
192    ModuleInfo {
193        file_id,
194        exports,
195        imports,
196        re_exports,
197        dynamic_imports,
198        dynamic_import_patterns,
199        require_calls,
200        member_accesses: cached.member_accesses.clone(),
201        whole_object_uses: cached.whole_object_uses.clone(),
202        has_cjs_exports: cached.has_cjs_exports,
203        has_angular_component_template_url: cached.has_angular_component_template_url,
204        content_hash: cached.content_hash,
205        suppressions,
206        unknown_suppression_kinds,
207        unused_import_bindings: cached.unused_import_bindings.clone(),
208        type_referenced_import_bindings: cached.type_referenced_import_bindings.clone(),
209        value_referenced_import_bindings: cached.value_referenced_import_bindings.clone(),
210        line_offsets: cached.line_offsets.clone(),
211        complexity: if need_complexity {
212            cached.complexity.clone()
213        } else {
214            Vec::new()
215        },
216        flag_uses: cached.flag_uses.clone(),
217        class_heritage: cached.class_heritage.clone(),
218        local_type_declarations: cached
219            .local_type_declarations
220            .iter()
221            .map(|decl| LocalTypeDeclaration {
222                name: decl.name.clone(),
223                span: Span::new(decl.span_start, decl.span_end),
224            })
225            .collect(),
226        public_signature_type_references: cached
227            .public_signature_type_references
228            .iter()
229            .map(|reference| PublicSignatureTypeReference {
230                export_name: reference.export_name.clone(),
231                type_name: reference.type_name.clone(),
232                span: Span::new(reference.span_start, reference.span_end),
233            })
234            .collect(),
235        namespace_object_aliases: cached
236            .namespace_object_aliases
237            .iter()
238            .map(|alias| NamespaceObjectAlias {
239                via_export_name: alias.via_export_name.clone(),
240                suffix: alias.suffix.clone(),
241                namespace_local: alias.namespace_local.clone(),
242            })
243            .collect(),
244        iconify_prefixes: cached.iconify_prefixes.clone(),
245        auto_import_candidates: cached.auto_import_candidates.clone(),
246    }
247}
248
249/// Convert a [`ModuleInfo`](crate::ModuleInfo) to a [`CachedModule`] for storage.
250///
251/// `mtime_secs` and `file_size` come from `std::fs::metadata()` at parse time
252/// and enable fast cache validation on subsequent runs (skip file read when
253/// mtime+size match).
254#[must_use]
255#[expect(
256    clippy::too_many_lines,
257    reason = "single flat field-by-field serialization; splitting it harms readability"
258)]
259pub fn module_to_cached(
260    module: &crate::ModuleInfo,
261    mtime_secs: u64,
262    file_size: u64,
263) -> CachedModule {
264    CachedModule {
265        content_hash: module.content_hash,
266        mtime_secs,
267        file_size,
268        last_access_secs: current_unix_seconds(),
269        exports: module
270            .exports
271            .iter()
272            .map(|e| CachedExport {
273                name: match &e.name {
274                    ExportName::Named(n) => n.clone(),
275                    ExportName::Default => String::new(),
276                },
277                is_default: matches!(e.name, ExportName::Default),
278                is_type_only: e.is_type_only,
279                is_side_effect_used: e.is_side_effect_used,
280                visibility: e.visibility as u8,
281                local_name: e.local_name.clone(),
282                span_start: e.span.start,
283                span_end: e.span.end,
284                members: e
285                    .members
286                    .iter()
287                    .map(|m| CachedMember {
288                        name: m.name.clone(),
289                        kind: m.kind,
290                        span_start: m.span.start,
291                        span_end: m.span.end,
292                        has_decorator: m.has_decorator,
293                        decorator_names: m.decorator_names.clone(),
294                        is_instance_returning_static: m.is_instance_returning_static,
295                        is_self_returning: m.is_self_returning,
296                    })
297                    .collect(),
298                super_class: e.super_class.clone(),
299            })
300            .collect(),
301        imports: module
302            .imports
303            .iter()
304            .map(|i| {
305                let (kind, imported_name) = match &i.imported_name {
306                    crate::ImportedName::Named(n) => (IMPORT_KIND_NAMED, n.clone()),
307                    crate::ImportedName::Default => (IMPORT_KIND_DEFAULT, String::new()),
308                    crate::ImportedName::Namespace => (IMPORT_KIND_NAMESPACE, String::new()),
309                    crate::ImportedName::SideEffect => (IMPORT_KIND_SIDE_EFFECT, String::new()),
310                };
311                CachedImport {
312                    source: i.source.clone(),
313                    imported_name,
314                    local_name: i.local_name.clone(),
315                    is_type_only: i.is_type_only,
316                    from_style: i.from_style,
317                    kind,
318                    span_start: i.span.start,
319                    span_end: i.span.end,
320                    source_span_start: i.source_span.start,
321                    source_span_end: i.source_span.end,
322                }
323            })
324            .collect(),
325        re_exports: module
326            .re_exports
327            .iter()
328            .map(|r| CachedReExport {
329                source: r.source.clone(),
330                imported_name: r.imported_name.clone(),
331                exported_name: r.exported_name.clone(),
332                is_type_only: r.is_type_only,
333                span_start: r.span.start,
334                span_end: r.span.end,
335            })
336            .collect(),
337        dynamic_imports: module
338            .dynamic_imports
339            .iter()
340            .map(|d| CachedDynamicImport {
341                source: d.source.clone(),
342                span_start: d.span.start,
343                span_end: d.span.end,
344                destructured_names: d.destructured_names.clone(),
345                local_name: d.local_name.clone(),
346                is_speculative: d.is_speculative,
347            })
348            .collect(),
349        require_calls: module
350            .require_calls
351            .iter()
352            .map(|r| CachedRequireCall {
353                source: r.source.clone(),
354                span_start: r.span.start,
355                span_end: r.span.end,
356                destructured_names: r.destructured_names.clone(),
357                local_name: r.local_name.clone(),
358            })
359            .collect(),
360        member_accesses: module.member_accesses.clone(),
361        whole_object_uses: module.whole_object_uses.clone(),
362        dynamic_import_patterns: module
363            .dynamic_import_patterns
364            .iter()
365            .map(|p| CachedDynamicImportPattern {
366                prefix: p.prefix.clone(),
367                suffix: p.suffix.clone(),
368                span_start: p.span.start,
369                span_end: p.span.end,
370            })
371            .collect(),
372        has_cjs_exports: module.has_cjs_exports,
373        has_angular_component_template_url: module.has_angular_component_template_url,
374        unused_import_bindings: module.unused_import_bindings.clone(),
375        type_referenced_import_bindings: module.type_referenced_import_bindings.clone(),
376        value_referenced_import_bindings: module.value_referenced_import_bindings.clone(),
377        suppressions: module
378            .suppressions
379            .iter()
380            .map(|s| CachedSuppression {
381                line: s.line,
382                comment_line: s.comment_line,
383                kind: s
384                    .kind
385                    .map_or(0, crate::suppress::IssueKind::to_discriminant),
386            })
387            .collect(),
388        unknown_suppression_kinds: module
389            .unknown_suppression_kinds
390            .iter()
391            .map(|u| CachedUnknownSuppressionKind {
392                comment_line: u.comment_line,
393                is_file_level: u.is_file_level,
394                token: u.token.clone(),
395            })
396            .collect(),
397        line_offsets: module.line_offsets.clone(),
398        complexity: module.complexity.clone(),
399        flag_uses: module.flag_uses.clone(),
400        class_heritage: module.class_heritage.clone(),
401        local_type_declarations: module
402            .local_type_declarations
403            .iter()
404            .map(|decl| CachedLocalTypeDeclaration {
405                name: decl.name.clone(),
406                span_start: decl.span.start,
407                span_end: decl.span.end,
408            })
409            .collect(),
410        public_signature_type_references: module
411            .public_signature_type_references
412            .iter()
413            .map(|reference| CachedPublicSignatureTypeReference {
414                export_name: reference.export_name.clone(),
415                type_name: reference.type_name.clone(),
416                span_start: reference.span.start,
417                span_end: reference.span.end,
418            })
419            .collect(),
420        namespace_object_aliases: module
421            .namespace_object_aliases
422            .iter()
423            .map(|alias| CachedNamespaceObjectAlias {
424                via_export_name: alias.via_export_name.clone(),
425                suffix: alias.suffix.clone(),
426                namespace_local: alias.namespace_local.clone(),
427            })
428            .collect(),
429        iconify_prefixes: module.iconify_prefixes.clone(),
430        auto_import_candidates: module.auto_import_candidates.clone(),
431    }
432}