1use serde::{Deserialize, Serialize};
9
10use crate::core::call_graph::ScopeMatch;
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
14#[serde(rename_all = "snake_case")]
15pub enum EvidenceGrade {
16 HeuristicStructural,
19 ResolvedStructural,
21 VerifiedSemantic,
23}
24
25impl EvidenceGrade {
26 pub fn from_scope(via: ScopeMatch) -> Self {
27 match via {
28 ScopeMatch::SameFile | ScopeMatch::UniqueImport => Self::ResolvedStructural,
29 ScopeMatch::UniqueInProject => Self::HeuristicStructural,
30 }
31 }
32
33 pub fn as_str(self) -> &'static str {
34 match self {
35 Self::HeuristicStructural => "heuristic",
36 Self::ResolvedStructural => "resolved",
37 Self::VerifiedSemantic => "verified",
38 }
39 }
40
41 pub fn weight_factor(self) -> f64 {
45 match self {
46 Self::HeuristicStructural => 0.5,
47 Self::ResolvedStructural | Self::VerifiedSemantic => 1.0,
48 }
49 }
50}
51
52#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Default, Serialize, Deserialize)]
55#[serde(rename_all = "snake_case")]
56pub enum EvidenceOrigin {
57 #[default]
59 Enrichment,
60 ImpactIndex,
62}
63
64#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
66pub struct Contribution {
67 pub origin: EvidenceOrigin,
68 pub grade: EvidenceGrade,
69 #[serde(default, skip_serializing_if = "Option::is_none")]
71 pub backend: Option<String>,
72 pub sites: u32,
74}
75
76#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
83pub struct EdgeEvidence {
84 pub v: u8,
86 pub grade: EvidenceGrade,
88 pub by: Vec<Contribution>,
90}
91
92impl EdgeEvidence {
93 pub const VERSION: u8 = 1;
94
95 pub fn new(
97 grade: EvidenceGrade,
98 origin: EvidenceOrigin,
99 backend: Option<String>,
100 sites: u32,
101 ) -> Self {
102 Self {
103 v: Self::VERSION,
104 grade,
105 by: vec![Contribution {
106 origin,
107 grade,
108 backend,
109 sites,
110 }],
111 }
112 }
113
114 fn from_contributions(mut by: Vec<Contribution>) -> Option<Self> {
115 by.sort_by_key(|c| c.origin);
116 let grade = by.iter().map(|c| c.grade).max()?;
117 Some(Self {
118 v: Self::VERSION,
119 grade,
120 by,
121 })
122 }
123
124 pub fn primary(&self) -> Option<&Contribution> {
127 self.by
128 .iter()
129 .max_by(|a, b| a.grade.cmp(&b.grade).then(b.origin.cmp(&a.origin)))
130 }
131
132 pub fn has(&self, origin: EvidenceOrigin) -> bool {
133 self.by.iter().any(|c| c.origin == origin)
134 }
135
136 pub fn merge(existing: Option<Self>, incoming: Self) -> Self {
140 let mut by: Vec<Contribution> = existing
141 .map(|e| e.by)
142 .unwrap_or_default()
143 .into_iter()
144 .filter(|c| !incoming.has(c.origin))
145 .collect();
146 by.extend(incoming.by.iter().cloned());
147 Self::from_contributions(by).unwrap_or(incoming)
149 }
150
151 pub fn without(self, origin: EvidenceOrigin) -> Option<Self> {
154 Self::from_contributions(self.by.into_iter().filter(|c| c.origin != origin).collect())
155 }
156
157 pub fn to_metadata(&self) -> String {
158 serde_json::to_string(self).unwrap_or_default()
159 }
160
161 pub fn from_metadata(metadata: Option<&str>) -> Option<Self> {
164 serde_json::from_str::<Self>(metadata?)
165 .ok()
166 .filter(|e| e.v == Self::VERSION)
167 }
168
169 pub fn weight_factor_of(metadata: Option<&str>) -> f64 {
172 Self::from_metadata(metadata).map_or(1.0, |e| e.grade.weight_factor())
173 }
174}
175
176#[cfg(test)]
177mod tests {
178 use super::*;
179
180 #[test]
184 fn contributions_are_owned_per_producer() {
185 use EvidenceGrade::{ResolvedStructural, VerifiedSemantic};
186 use EvidenceOrigin::{Enrichment, ImpactIndex};
187 let verified = EdgeEvidence::new(VerifiedSemantic, Enrichment, Some("lsp:ra@1".into()), 1);
188 let structural = |origin| EdgeEvidence::new(ResolvedStructural, origin, None, 1);
189
190 let both = EdgeEvidence::merge(Some(verified.clone()), structural(ImpactIndex));
191 assert_eq!(both.grade, VerifiedSemantic, "no cross-producer downgrade");
192 assert_eq!(
193 both.primary().and_then(|c| c.backend.as_deref()),
194 Some("lsp:ra@1")
195 );
196
197 let recomputed = EdgeEvidence::merge(Some(both.clone()), structural(Enrichment));
198 assert_eq!(
199 recomputed.grade, ResolvedStructural,
200 "owner may weaken its own part"
201 );
202 assert!(recomputed.has(ImpactIndex));
203
204 let kept = both.clone().without(Enrichment).unwrap();
205 assert_eq!(
206 kept.grade, ResolvedStructural,
207 "impact still derives the edge"
208 );
209 assert!(
210 kept.without(ImpactIndex).is_none(),
211 "nobody derives it → delete"
212 );
213 assert_eq!(
214 EdgeEvidence::from_metadata(Some(&both.to_metadata())),
215 Some(both),
216 "deterministic round trip of the stored form"
217 );
218 }
219
220 #[test]
221 fn foreign_or_legacy_metadata_keeps_full_weight() {
222 let heuristic = EdgeEvidence::new(
223 EvidenceGrade::HeuristicStructural,
224 EvidenceOrigin::Enrichment,
225 None,
226 1,
227 );
228 assert_eq!(
229 EdgeEvidence::weight_factor_of(Some(&heuristic.to_metadata())),
230 0.5
231 );
232 assert_eq!(EdgeEvidence::weight_factor_of(None), 1.0);
233 assert_eq!(
234 EdgeEvidence::weight_factor_of(Some("kind=fn;exported")),
235 1.0
236 );
237 assert_eq!(
238 EdgeEvidence::weight_factor_of(Some(
239 r#"{"v":9,"grade":"verified_semantic","sites":1}"#
240 )),
241 1.0,
242 "unknown schema versions are ignored, not misread"
243 );
244 }
245}