use std::collections::BTreeMap;
use std::path::PathBuf;
use crate::Reach;
use vvv_core::{Address, Layout, Project, ReachKind, Semantics, Symbol, SymbolKind};
use crate::EngineError;
use crate::graph::Graph;
#[derive(Debug, Clone)]
pub struct Violation {
pub path: PathBuf,
pub symbol: Symbol,
pub declaring: Address,
pub consumers: Vec<Address>,
pub needs: ReachKind,
}
pub struct Reachability<'a> {
layout: &'a dyn Layout,
semantics: &'static Semantics,
project: &'a Project,
old: &'a Address,
new: &'a Address,
}
impl<'a> Reachability<'a> {
pub fn new(
layout: &'a dyn Layout,
semantics: &'static Semantics,
project: &'a Project,
old: &'a Address,
new: &'a Address,
) -> Self {
Self {
layout,
semantics,
project,
old,
new,
}
}
pub fn check(
&self,
graph: &Graph,
references: &[(Address, Address)],
) -> Result<Vec<Violation>, EngineError> {
let mut offended: BTreeMap<Address, (PathBuf, Symbol, Address, Vec<Address>)> =
BTreeMap::new();
let mut seen: BTreeMap<Address, Option<(PathBuf, Symbol)>> = BTreeMap::new();
for (from, target) in references {
for step in Self::chain(target) {
let Some(declaring) = step.parent() else {
continue; };
let found = match seen.get(&step) {
Some(found) => found.clone(),
None => {
let found = self.declaration(graph, &step, step == *target)?;
seen.insert(step.clone(), found.clone());
found
}
};
let Some((path, symbol)) = found else {
continue; };
let reach = Reach::of(
self.semantics.reach_kind(symbol.modifier()),
&declaring,
None,
);
if reach.admits(from) {
continue;
}
let entry = offended
.entry(step.clone())
.or_insert_with(|| (path, symbol, declaring, Vec::new()));
if !entry.3.contains(from) {
entry.3.push(from.clone());
}
}
}
Ok(offended
.into_values()
.map(|(path, symbol, declaring, consumers)| {
let needs = Reach::narrowest(&declaring, &consumers);
Violation {
path,
symbol,
declaring,
consumers,
needs,
}
})
.collect())
}
fn chain(target: &Address) -> impl Iterator<Item = Address> + '_ {
(1..=target.path().len())
.map(|n| Address::new(target.package().clone(), target.path()[..n].iter().cloned()))
}
fn declaration(
&self,
graph: &Graph,
after: &Address,
last: bool,
) -> Result<Option<(PathBuf, Symbol)>, EngineError> {
let before = after
.rebase(self.new, self.old)
.unwrap_or_else(|| after.clone());
let Some(parent) = before.parent() else {
return Ok(None);
};
let Some(name) = before.path().last() else {
return Ok(None);
};
let Some(file) = self
.layout
.candidates(self.project, &parent)
.into_iter()
.find(|p| self.project.files.contains(p))
else {
return Ok(None);
};
let Some(candidate) = graph.candidate(&file) else {
return Ok(None);
};
let facts = candidate.facts()?;
let symbol = facts
.symbols
.iter()
.filter(|s| s.name == name.as_str())
.find(|s| {
s.kind == SymbolKind::Module || (last && self.semantics.is_addressable(s.kind))
})
.cloned();
Ok(symbol.map(|s| (file, s)))
}
}