Skip to main content

aft_parse/callgraph_store/
dead_code_projection.rs

1use super::{PROVENANCE_NAME_MATCH, PROVENANCE_TYPE_MATCH, PROVENANCE_VALUE_REF};
2use crate::symbols::SymbolKind;
3use std::time::Duration;
4
5pub const UNRESOLVED_VALUE_PATH_PROVENANCE: &str = "unresolved_value_path";
6/// Provenance of a projected outbound call that is not a call: a member an
7/// unknown receiver at that line of the caller file may reach, which dead
8/// code keeps alive (for tests only when the line is test code).
9pub const UNKNOWN_RECEIVER_LIVE_PROVENANCE: &str = "unknown_receiver_live";
10pub const MAX_DELTA_BYTES: usize = 256 * 1024;
11
12/// How a dead-code snapshot was produced: by splicing the previous snapshot
13/// with the caller delta journal, or by re-reading the whole store.
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum ProjectionKind {
16    #[cfg(any(test, feature = "test-support"))]
17    Spliced,
18    Full,
19    /// The cached snapshot for the current revision was handed back without
20    /// touching the store: no projection work at all.
21    #[cfg(any(test, feature = "test-support"))]
22    Reused,
23}
24
25impl ProjectionKind {
26    pub const fn as_str(self) -> &'static str {
27        match self {
28            #[cfg(any(test, feature = "test-support"))]
29            Self::Spliced => "spliced",
30            Self::Full => "full",
31            #[cfg(any(test, feature = "test-support"))]
32            Self::Reused => "reused",
33        }
34    }
35}
36
37/// Why a projection took the path it did, plus the journal/corpus counts that
38/// let an operator see the cost without re-deriving it from timings.
39///
40/// `reason` is `Some` only for `Full` projections; the reasons are `cold`
41/// (no previous snapshot or a legacy store without a durable revision),
42/// `journal_gap` (a missing or unparseable journal entry bridged the revisions),
43/// and `splice_costlier` (the retained root timings predict a full pass is cheaper).
44/// No `generation_changed` arm exists: the cache identity already pairs the
45/// cold-build generation with the durable revision, so a generation change
46/// surfaces as `cold` or a cache miss.
47///
48/// The journal records each write's callers already extended with their
49/// dependents, so `changed_files` counts every file re-projected by a splice;
50/// the caller/dependent split is not recoverable at read time.
51#[derive(Debug, Clone, Copy, PartialEq, Eq)]
52pub struct ProjectionVerdict {
53    pub kind: ProjectionKind,
54    pub reason: Option<&'static str>,
55    /// Bytes of inline or spill-backed journal entries read for a splice.
56    pub journal_bytes: u64,
57    /// Files in the journal delta, including a delta rejected as costlier than full.
58    pub changed_files: usize,
59}
60
61/// Root-local running projection costs used to avoid a splice whose snapshot
62/// fold is predicted to cost more than re-reading the complete store.
63#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
64pub struct ProjectionCostEstimates {
65    full_ns: u64,
66    splice_ns_per_file: u64,
67}
68
69impl ProjectionCostEstimates {
70    pub fn observe(&mut self, verdict: ProjectionVerdict, elapsed: Duration) {
71        let elapsed_ns = elapsed.as_nanos().min(u128::from(u64::MAX)) as u64;
72        match verdict.kind {
73            ProjectionKind::Full => update_running_estimate(&mut self.full_ns, elapsed_ns),
74            #[cfg(any(test, feature = "test-support"))]
75            ProjectionKind::Spliced if verdict.changed_files > 0 => {
76                let per_file = elapsed_ns / verdict.changed_files as u64;
77                update_running_estimate(&mut self.splice_ns_per_file, per_file.max(1));
78            }
79            #[cfg(any(test, feature = "test-support"))]
80            ProjectionKind::Spliced => {}
81            #[cfg(any(test, feature = "test-support"))]
82            ProjectionKind::Reused => {}
83        }
84    }
85}
86
87fn update_running_estimate(estimate: &mut u64, observed: u64) {
88    *estimate = if *estimate == 0 {
89        observed.max(1)
90    } else {
91        estimate
92            .saturating_mul(3)
93            .saturating_add(observed)
94            .saturating_add(2)
95            / 4
96    };
97}
98
99pub fn is_resolved_edge(status: &str, provenance: Option<&str>) -> bool {
100    matches!(status, "resolved" | "resolved_local")
101        || provenance.is_some_and(|provenance| {
102            provenance == PROVENANCE_TYPE_MATCH
103                || provenance == PROVENANCE_VALUE_REF
104                || (provenance != PROVENANCE_NAME_MATCH
105                    && (provenance.contains("treesitter") || provenance.contains("resolver")))
106        })
107}
108
109pub fn is_method_dispatch_callee(full_callee: &str, callee_name: &str) -> bool {
110    let full_callee = full_callee.trim();
111    if !full_callee.contains('.') || full_callee == callee_name.trim() {
112        return false;
113    }
114
115    full_callee
116        .rsplit('.')
117        .next()
118        .map(|segment| segment.trim().trim_start_matches('?') == callee_name.trim())
119        .unwrap_or(false)
120}
121
122pub fn symbol_kind_from_label(label: &str) -> Option<SymbolKind> {
123    match label {
124        "function" => Some(SymbolKind::Function),
125        "kernel" => Some(SymbolKind::Kernel),
126        "class" => Some(SymbolKind::Class),
127        "method" => Some(SymbolKind::Method),
128        "struct" => Some(SymbolKind::Struct),
129        "interface" => Some(SymbolKind::Interface),
130        "enum" => Some(SymbolKind::Enum),
131        "type_alias" => Some(SymbolKind::TypeAlias),
132        "variable" => Some(SymbolKind::Variable),
133        "heading" => Some(SymbolKind::Heading),
134        "file_summary" => Some(SymbolKind::FileSummary),
135        _ => None,
136    }
137}