use std::collections::BTreeMap;
use sealmap_model::{Codebase, Confidence, Relation, RelationKind, SymbolId};
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ExternalCalls {
All,
#[default]
NonStd,
None,
}
impl ExternalCalls {
pub fn keeps(self, confidence: Confidence, is_dependency: impl FnOnce() -> bool) -> bool {
match confidence {
Confidence::Exact | Confidence::Inferred => true,
Confidence::External => match self {
ExternalCalls::All => true,
ExternalCalls::NonStd => is_dependency(),
ExternalCalls::None => false,
},
}
}
}
pub fn strongest(a: Confidence, b: Confidence) -> Confidence {
a.min(b)
}
pub fn aggregate_calls(cb: &mut Codebase) {
let mut calls: BTreeMap<(SymbolId, SymbolId), Confidence> = BTreeMap::new();
for s in cb.symbols.values() {
if let Some(flow) = &s.flow {
for c in flow.calls() {
let e = calls.entry((s.id.clone(), c.target.clone())).or_insert(c.confidence);
*e = strongest(*e, c.confidence);
}
}
}
for ((from, to), c) in calls {
cb.add_relation(Relation::new(from, to, RelationKind::Calls, c));
}
}
#[cfg(test)]
mod tests {
use sealmap_model::{Call, CallKind, Flow, SourcePath, Step, Symbol, SymbolKind};
use super::*;
fn sym(s: &str) -> SymbolId {
SymbolId::parse(s).unwrap()
}
fn call(t: &str, c: Confidence) -> Step {
Step::Call(Call {
target: SymbolId::parse(t).unwrap(),
label: t.into(),
kind: CallKind::Function,
confidence: c,
awaited: false,
fallible: false,
line: 1,
})
}
#[test]
fn aggregation_keeps_the_strongest_evidence() {
let mut cb = Codebase::new("app");
let mut s =
Symbol::new(sym("sym:cargo app . f()."), "f", SymbolKind::Function, SourcePath::new("src/lib.rs").unwrap());
s.flow = Some(Flow::new(vec![
call("sym:cargo app . g().", Confidence::Inferred),
call("sym:cargo app . g().", Confidence::Exact),
call("sym:extern dep::h", Confidence::External),
]));
cb.add_symbol(s);
aggregate_calls(&mut cb);
let edges: Vec<_> = cb.relations.iter().map(|r| (r.to.to_string(), r.confidence)).collect();
assert_eq!(
edges,
[
("sym:cargo app . g().".to_owned(), Confidence::Exact),
("sym:extern dep::h".to_owned(), Confidence::External)
]
);
}
#[test]
fn policy_table() {
for p in [ExternalCalls::All, ExternalCalls::NonStd, ExternalCalls::None] {
assert!(p.keeps(Confidence::Exact, || unreachable!()));
assert!(p.keeps(Confidence::Inferred, || unreachable!()));
}
assert!(ExternalCalls::All.keeps(Confidence::External, || false));
assert!(!ExternalCalls::None.keeps(Confidence::External, || true));
}
}