use super::Analysis;
use super::modules::{Crate, Module, calls_macro, use_leaves};
use crate::language::doc::{impl_owner, named};
use crate::language::text;
use crate::protocol::SymbolRef;
use proc_macro2::{TokenStream, TokenTree};
use quote::ToTokens;
use std::collections::{HashMap, HashSet};
use std::path::Path;
use syn::Item;
type Key = (Vec<String>, String);
const BY_MACROS: &str = "!";
#[derive(Default)]
struct Unit {
fingerprint: String,
uses: Vec<Key>,
}
fn without_docs(stream: TokenStream) -> TokenStream {
let trees: Vec<TokenTree> = stream.into_iter().collect();
let is_doc = |tree: Option<&TokenTree>| match tree {
Some(TokenTree::Group(group)) => {
matches!(group.stream().into_iter().next(), Some(TokenTree::Ident(i)) if i == "doc")
}
_ => false,
};
let mut out = Vec::new();
let mut k = 0;
while k < trees.len() {
match &trees[k] {
TokenTree::Punct(p) if p.as_char() == '#' && is_doc(trees.get(k + 1)) => k += 1,
TokenTree::Group(group) => {
out.push(TokenTree::Group(proc_macro2::Group::new(
group.delimiter(),
without_docs(group.stream()),
)));
}
other => out.push(other.clone()),
}
k += 1;
}
out.into_iter().collect()
}
fn owner(item: &Item) -> Option<String> {
match item {
Item::Impl(block) => impl_owner(block),
call if calls_macro(call) => Some(BY_MACROS.to_string()),
Item::Use(_) | Item::Mod(_) => None,
other => named(other).map(|(name, _)| name),
}
}
fn units(krate: &Crate) -> HashMap<Key, Unit> {
let mut out: HashMap<Key, Unit> = HashMap::new();
for module in &krate.modules {
let imports = imports(module);
for item in &module.items {
let Some(name) = owner(item) else { continue };
let tokens = without_docs(item.to_token_stream()).to_string();
let unit = out.entry((module.path.clone(), name)).or_default();
unit.uses.extend(
text::paths(&tokens).iter().filter_map(|path| resolve(krate, module, &imports, path)),
);
unit.fingerprint.push_str(&tokens);
unit.fingerprint.push('\n');
}
}
out
}
struct Imports {
named: HashMap<String, Vec<String>>,
whole: Vec<Vec<String>>,
}
fn imports(module: &Module) -> Imports {
let uses = module.items.iter().filter_map(|item| match item {
Item::Use(used) => Some(use_leaves(&used.tree)),
_ => None,
});
let (whole, named): (Vec<_>, Vec<_>) = uses.flatten().partition(|(name, _)| name == "*");
Imports { named: named.into_iter().collect(), whole: whole.into_iter().map(|(_, path)| path).collect() }
}
fn resolve(krate: &Crate, module: &Module, imports: &Imports, written: &[String]) -> Option<Key> {
let below = |prefix: &[String], rest: &[String]| prefix.iter().chain(rest).cloned().collect::<Vec<_>>();
let brought = |whole: &Vec<String>| match krate.whole(&module.path, whole) {
Some(_) => Some(below(whole, written)),
None => has_variant(krate, module, whole, &written[0]).then(|| whole.clone()),
};
let readings: Vec<Vec<String>> = match imports.named.get(&written[0]) {
Some(stands_for) => vec![below(stands_for, &written[1..])],
None => std::iter::once(written.to_vec()).chain(imports.whole.iter().filter_map(brought)).collect(),
};
let declared = readings.iter().find_map(|full| declared(krate, module, full));
declared.or_else(|| readings.iter().find_map(|full| by_macros(krate, module, full)))
}
fn has_variant(krate: &Crate, module: &Module, path: &[String], variant: &str) -> bool {
let Some((at, name)) = krate.resolve(&module.path, path) else { return false };
let is_it = |item: &Item| match item {
Item::Enum(found) => found.ident == name && found.variants.iter().any(|held| held.ident == variant),
_ => false,
};
krate.module(&at).is_some_and(|module| module.items.iter().any(is_it))
}
fn declared(krate: &Crate, module: &Module, full: &[String]) -> Option<Key> {
(1..=full.len()).rev().find_map(|len| {
let (at, name) = krate.resolve(&module.path, &full[..len])?;
let exported = krate.exports(&at).iter().any(|export| export.name == name);
(exported || declares(krate, &at, &name)).then(|| krate.origin(&at, &name))
})
}
fn by_macros(krate: &Crate, module: &Module, full: &[String]) -> Option<Key> {
(1..=full.len()).rev().find_map(|len| {
let (at, _) = krate.resolve(&module.path, &full[..len])?;
declares(krate, &at, BY_MACROS).then(|| (at, BY_MACROS.to_string()))
})
}
fn declares(krate: &Crate, module: &[String], name: &str) -> bool {
krate
.module(module)
.is_some_and(|module| module.items.iter().any(|item| owner(item).as_deref() == Some(name)))
}
fn reaching(units: &HashMap<Key, Unit>, set: &HashSet<Key>) -> HashSet<Key> {
let mut found = set.clone();
loop {
let grown: Vec<Key> = units
.iter()
.filter(|(key, unit)| !found.contains(*key) && unit.uses.iter().any(|used| found.contains(used)))
.map(|(key, _)| key.clone())
.collect();
if grown.is_empty() {
return found;
}
found.extend(grown);
}
}
impl Analysis {
pub(crate) fn affected(&self, base: &HashMap<String, Option<String>>) -> Vec<SymbolRef> {
let was: HashMap<_, _> = base.iter().map(|(rel, text)| (self.abs(rel), text.clone())).collect();
let read_now = |path: &Path| std::fs::read_to_string(path).ok();
let read_was = |path: &Path| was.get(path).cloned().unwrap_or_else(|| read_now(path));
let mut out: Vec<SymbolRef> = Vec::new();
let mut crates: HashMap<String, (Crate, Crate, Changes)> = HashMap::new();
for surface in &self.surfaces {
let Some(package) = &surface.package else {
continue;
};
let (now, before, changes) = crates.entry(package.lib.clone()).or_insert_with(|| {
let (now, before) = (
Crate::load(&package.lib, &package.root, &read_now),
Crate::load(&package.lib, &package.root, &read_was),
);
let changes = Changes::between(&now, &before);
(now, before, changes)
});
let listed = self.exports(surface).unwrap_or_default();
let mut exports: Vec<(String, Key)> =
listed.into_iter().filter_map(|export| Some((export.name, export.origin?))).collect();
for krate in [&*now, &*before] {
let read = krate.exports(&surface.module).into_iter();
exports.extend(read.map(|export| {
let unit = krate.origin(&surface.module, &export.name);
(export.name, unit)
}));
}
let from = out.len();
for (name, unit) in exports {
if changes.touch(&unit) && !out[from..].iter().any(|found| found.name == name) {
out.push(SymbolRef { name, surface: surface.name.clone() });
}
}
}
out
}
}
struct Changes {
touched: HashSet<Key>,
declared: HashSet<Key>,
}
impl Changes {
fn between(now: &Crate, before: &Crate) -> Changes {
let (units_now, units_before) = (units(now), units(before));
let mut differing: HashSet<Key> = HashSet::new();
for (key, unit) in &units_now {
if units_before.get(key).is_none_or(|was| was.fingerprint != unit.fingerprint) {
differing.insert(key.clone());
}
}
differing.extend(units_before.keys().filter(|key| !units_now.contains_key(*key)).cloned());
let mut touched = reaching(&units_now, &differing);
touched.extend(reaching(&units_before, &differing));
Changes { touched, declared: units_now.into_keys().chain(units_before.into_keys()).collect() }
}
fn touch(&self, unit: &Key) -> bool {
if self.declared.contains(unit) {
return self.touched.contains(unit);
}
self.touched.contains(&(unit.0.clone(), BY_MACROS.to_string()))
}
}