Skip to main content

sealmap_frontend/
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_frontend::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 frontend 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    /// (`?::name`). Verbose; useful for debugging the frontend.
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 call(t: &str, c: Confidence) -> Step {
88        Step::Call(Call {
89            target: SymbolId::new(t),
90            label: t.into(),
91            kind: CallKind::Function,
92            confidence: c,
93            awaited: false,
94            fallible: false,
95            line: 1,
96        })
97    }
98
99    #[test]
100    fn aggregation_keeps_the_strongest_evidence() {
101        let mut cb = Codebase::new("app");
102        let mut s =
103            Symbol::new(SymbolId::new("app::f"), "f", SymbolKind::Function, SourcePath::new("src/lib.rs").unwrap());
104        s.flow = Some(Flow::new(vec![
105            call("app::g", Confidence::Inferred),
106            call("app::g", Confidence::Exact),
107            call("dep::h", Confidence::External),
108        ]));
109        cb.add_symbol(s);
110        aggregate_calls(&mut cb);
111        let edges: Vec<_> = cb.relations.iter().map(|r| (r.to.as_str().to_owned(), r.confidence)).collect();
112        assert_eq!(edges, [("app::g".to_owned(), Confidence::Exact), ("dep::h".to_owned(), Confidence::External)]);
113    }
114
115    #[test]
116    fn policy_table() {
117        for p in [ExternalCalls::All, ExternalCalls::NonStd, ExternalCalls::None] {
118            assert!(p.keeps(Confidence::Exact, || unreachable!()));
119            assert!(p.keeps(Confidence::Inferred, || unreachable!()));
120        }
121        assert!(ExternalCalls::All.keeps(Confidence::External, || false));
122        assert!(!ExternalCalls::None.keeps(Confidence::External, || true));
123    }
124}