Skip to main content

sealmap_extract/
confidence.rs

1//! The confidence lattice, the external-call policy and call-edge
2//! aggregation.
3//!
4//! [`Confidence`] is totally ordered from strongest to weakest evidence:
5//! `Exact < Inferred < External`. Where one function calls the same target
6//! several times, the call edge keeps the **strongest** evidence any of those
7//! calls had ([`strongest`]).
8//!
9//! ```
10//! use sealmap_extract::confidence::{ExternalCalls, strongest};
11//! use sealmap_model::Confidence;
12//!
13//! assert_eq!(strongest(Confidence::Inferred, Confidence::Exact), Confidence::Exact);
14//! // External calls are kept under the default policy only if they look
15//! // like a dependency (the language adapter decides what that means).
16//! assert!(ExternalCalls::NonStd.keeps(Confidence::External, || true));
17//! assert!(!ExternalCalls::NonStd.keeps(Confidence::External, || false));
18//! assert!(ExternalCalls::None.keeps(Confidence::Inferred, || false));
19//! ```
20
21use std::collections::BTreeMap;
22
23use sealmap_model::{Codebase, Confidence, Relation, RelationKind, SymbolId};
24
25/// Which calls to external code are kept in flows.
26#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
27pub enum ExternalCalls {
28    /// Keep every external call, including `std` and unresolved method calls
29    /// (`sym:? name`). Verbose; useful for debugging the language adapter.
30    All,
31    /// Keep calls into non-std dependencies (`tokio::spawn`,
32    /// `serde_json::to_string`); drop `std`/`core`/`alloc` and unresolved
33    /// method calls. The default.
34    #[default]
35    NonStd,
36    /// Keep only calls into the analysed code.
37    None,
38}
39
40impl ExternalCalls {
41    /// Whether a call resolved with `confidence` stays in the flow. Exact and
42    /// inferred calls always stay; an external call stays under
43    /// [`ExternalCalls::NonStd`] only if `is_dependency` says its target is a
44    /// real dependency (not the standard library, not an unresolved name).
45    /// `is_dependency` is only evaluated when needed.
46    pub fn keeps(self, confidence: Confidence, is_dependency: impl FnOnce() -> bool) -> bool {
47        match confidence {
48            Confidence::Exact | Confidence::Inferred => true,
49            Confidence::External => match self {
50                ExternalCalls::All => true,
51                ExternalCalls::NonStd => is_dependency(),
52                ExternalCalls::None => false,
53            },
54        }
55    }
56}
57
58/// The stronger of two pieces of evidence for the same edge.
59pub fn strongest(a: Confidence, b: Confidence) -> Confidence {
60    a.min(b)
61}
62
63/// Add one [`RelationKind::Calls`] relation per distinct (caller, target)
64/// pair found in the flows of `cb`, with the strongest confidence among the
65/// calls behind it.
66pub fn aggregate_calls(cb: &mut Codebase) {
67    let mut calls: BTreeMap<(SymbolId, SymbolId), Confidence> = BTreeMap::new();
68    for s in cb.symbols.values() {
69        if let Some(flow) = &s.flow {
70            for c in flow.calls() {
71                let e = calls.entry((s.id.clone(), c.target.clone())).or_insert(c.confidence);
72                *e = strongest(*e, c.confidence);
73            }
74        }
75    }
76    for ((from, to), c) in calls {
77        cb.add_relation(Relation::new(from, to, RelationKind::Calls, c));
78    }
79}
80
81#[cfg(test)]
82mod tests {
83    use sealmap_model::{Call, CallKind, Flow, SourcePath, Step, Symbol, SymbolKind};
84
85    use super::*;
86
87    fn sym(s: &str) -> SymbolId {
88        SymbolId::parse(s).unwrap()
89    }
90
91    fn call(t: &str, c: Confidence) -> Step {
92        Step::Call(Call {
93            target: SymbolId::parse(t).unwrap(),
94            label: t.into(),
95            kind: CallKind::Function,
96            confidence: c,
97            awaited: false,
98            fallible: false,
99            line: 1,
100        })
101    }
102
103    #[test]
104    fn aggregation_keeps_the_strongest_evidence() {
105        let mut cb = Codebase::new("app");
106        let mut s =
107            Symbol::new(sym("sym:cargo app . f()."), "f", SymbolKind::Function, SourcePath::new("src/lib.rs").unwrap());
108        s.flow = Some(Flow::new(vec![
109            call("sym:cargo app . g().", Confidence::Inferred),
110            call("sym:cargo app . g().", Confidence::Exact),
111            call("sym:extern dep::h", Confidence::External),
112        ]));
113        cb.add_symbol(s);
114        aggregate_calls(&mut cb);
115        let edges: Vec<_> = cb.relations.iter().map(|r| (r.to.to_string(), r.confidence)).collect();
116        assert_eq!(
117            edges,
118            [
119                ("sym:cargo app . g().".to_owned(), Confidence::Exact),
120                ("sym:extern dep::h".to_owned(), Confidence::External)
121            ]
122        );
123    }
124
125    #[test]
126    fn policy_table() {
127        for p in [ExternalCalls::All, ExternalCalls::NonStd, ExternalCalls::None] {
128            assert!(p.keeps(Confidence::Exact, || unreachable!()));
129            assert!(p.keeps(Confidence::Inferred, || unreachable!()));
130        }
131        assert!(ExternalCalls::All.keeps(Confidence::External, || false));
132        assert!(!ExternalCalls::None.keeps(Confidence::External, || true));
133    }
134}