use std::any::TypeId;
use std::collections::{HashMap, HashSet, VecDeque};
use std::panic::Location;
use crate::binding::Recipe;
use crate::dependency::{Dependencies, DependencyRecord, ReadKind};
use crate::error::wiring::WiringError;
use crate::graph::wire::Declared;
use crate::graph::{
BindingId, EdgeTarget, Effective, FrozenBinding, Graph, ModuleId, Role, Visible, dependency_text, record_key,
};
use crate::key::{BindingKind, Key};
use crate::scope::ScopeKind;
use crate::transport::controller::{EnhancerDep, HandlerRecord};
use crate::type_name::short_type_name;
pub(crate) fn mark_role_contributions(graph: &mut Graph, first_binding: usize, errors: &mut Vec<WiringError>) {
let roles = role_types(graph, &graph.bindings);
let checked = role_types(graph, &graph.bindings[..first_binding]);
for binding in &mut graph.bindings {
if binding.record.kind == BindingKind::Collection
&& binding.role == Role::Provider
&& roles.contains(&binding.record.primary.type_id())
{
binding.role = Role::Enhancer;
}
}
for binding in &graph.bindings {
let record = &binding.record;
let new = binding.id.0 as usize >= first_binding;
let reported = |key: Key| roles.contains(&key.type_id()) && (new || !checked.contains(&key.type_id()));
match record.kind {
BindingKind::Collection => {
let key = record_key(record);
if !key.is_unqualified() && reported(key) {
errors.push(WiringError::QualifiedRoleContribution {
key: key.name(BindingKind::Collection),
module: graph.module_name(binding.origin),
at: record.location,
});
}
}
BindingKind::Single => {
for (key, at) in record.keys_located().filter(|&(key, _)| reported(key)) {
errors.push(WiringError::SingleRoleBinding {
key: key.name(BindingKind::Single),
module: graph.module_name(binding.origin),
at,
});
}
}
}
}
}
pub(crate) fn role_types(graph: &Graph, bindings: &[FrozenBinding]) -> HashSet<TypeId> {
let mut roles: HashSet<TypeId> =
graph.handlers.iter().flat_map(|handler| handler.decl.role_keys).map(|key| key.type_id()).collect();
roles.extend(
bindings
.iter()
.filter(|binding| binding.record.kind == BindingKind::Collection && binding.role == Role::Enhancer)
.map(|binding| binding.record.primary.type_id()),
);
roles
}
pub(crate) fn assign_roles(graph: &mut Graph) {
let mut named: Vec<BindingId> = Vec::new();
for handler in &graph.handlers {
for dep in &handler.decl.enhancer_deps {
if let EnhancerDep::Type(key) = dep {
if let Some(Visible::Binding(id)) = graph.lookup(handler.module, *key) {
named.push(through_aliases(graph, *id));
}
}
}
}
for id in named {
let binding = &mut graph.bindings[id.0 as usize];
if binding.role == Role::Provider {
binding.role = Role::Enhancer;
}
}
}
pub(crate) fn needs_execution(graph: &mut Graph) {
let count = graph.bindings.len();
for binding in &mut graph.bindings {
binding.effective = match binding.record.scope {
ScopeKind::Singleton | ScopeKind::Auto => Effective::Singleton,
ScopeKind::PerExecution => Effective::PerExecution,
ScopeKind::Transient => Effective::Transient,
};
binding.needs_execution = binding.record.scope == ScopeKind::PerExecution
|| binding.edges.iter().any(|edge| matches!(edge.target, EdgeTarget::Execution | EdgeTarget::Input(_)));
if binding.needs_execution {
promote(binding);
}
}
let mut readers: Vec<Vec<BindingId>> = vec![Vec::new(); count];
for index in 0..count {
let reader = BindingId(index as u32);
for dep in graph.construction_deps(reader) {
readers[dep.0 as usize].push(reader);
}
}
let mut queue: VecDeque<BindingId> =
(0..count).map(|index| BindingId(index as u32)).filter(|&id| graph.passes_execution(id)).collect();
while let Some(dep) = queue.pop_front() {
for &reader in &readers[dep.0 as usize] {
{
let binding = &mut graph.bindings[reader.0 as usize];
if binding.needs_execution {
continue;
}
binding.needs_execution = true;
promote(binding);
}
if graph.passes_execution(reader) {
queue.push_back(reader);
}
}
}
}
fn promote(binding: &mut FrozenBinding) {
if binding.record.scope == ScopeKind::Auto && binding.role != Role::Provider {
binding.effective = Effective::PerExecution;
}
}
pub(crate) fn check_scopes(graph: &Graph, errors: &mut Vec<WiringError>) {
for binding in &graph.bindings {
let record = &binding.record;
if matches!(record.recipe, Recipe::Alias { .. } | Recipe::Failed) {
continue;
}
let refused = binding.needs_execution
&& match record.scope {
ScopeKind::Singleton => true,
ScopeKind::Auto => binding.role == Role::Provider,
ScopeKind::PerExecution | ScopeKind::Transient => false,
};
if refused {
errors.push(WiringError::ScopeViolation {
binding: graph.key_name(binding.id),
declared: record.scope,
by_closure: record.by_closure(),
module: graph.module_name(binding.origin),
path: printed_path(graph, binding.id),
});
} else if binding.effective == Effective::PerExecution && (!record.hooks.is_empty() || record.ready.is_some()) {
errors.push(WiringError::HooksOnPerExecution {
binding: graph.key_name(binding.id),
module: graph.module_name(binding.origin),
});
}
}
}
pub(crate) fn closure_scopes(graph: &mut Graph, declared: &Declared, errors: &mut Vec<WiringError>) {
let mut decided = Vec::new();
for handler in graph.handlers.iter().skip(declared.first_handler) {
for dep in &handler.decl.enhancer_deps {
let EnhancerDep::Closure(closure) = dep else { continue };
let read = closure.dependencies.list.iter().find_map(|dependency| {
execution_read(graph, handler.module, None, dependency).map(|steps| {
let mut path = vec![dependency_text(dependency)];
path.extend(steps);
path
})
});
let effective = match closure.scope {
ScopeKind::Auto if read.is_some() => Effective::PerExecution,
ScopeKind::Auto => Effective::Singleton,
ScopeKind::Singleton => {
if let Some(path) = read {
errors.push(WiringError::ClosureScopeViolation {
closure: format!(
"{}-level {} #{} of {}",
closure.tier,
closure.role,
closure.position,
graph.handler_name(handler)
),
transport: handler.decl.transport,
role: closure.role,
path,
at: closure.location,
});
}
Effective::Singleton
}
ScopeKind::PerExecution => Effective::PerExecution,
ScopeKind::Transient => Effective::Transient,
};
decided.push((closure.id, effective));
}
}
graph.closures.extend(decided);
}
pub(crate) fn check_closures(graph: &Graph, declared: &Declared, errors: &mut Vec<WiringError>) {
for binding in graph.bindings.iter().skip(declared.first_binding) {
let module = graph.module_name(binding.origin);
let label = graph.label(binding.id);
if let Some(ready) = &binding.record.ready {
let closure = format!("readiness check of `{label}` in {module}");
let site = Closure { module: binding.origin, owner: Some(binding.id), name: &closure, at: Some(ready.location) };
site.check(graph, &ready.dependencies, errors);
}
for hook in &binding.record.hooks {
let closure = format!("`{}` hook of `{label}` in {module}", hook.kind);
let site = Closure { module: binding.origin, owner: Some(binding.id), name: &closure, at: Some(hook.location) };
site.check(graph, &hook.dependencies, errors);
}
}
for module in graph.modules.iter().skip(declared.first_module) {
for hook in &module.hooks {
let closure = format!("`{}` hook of module {}", hook.kind, module.name);
let site = Closure { module: module.id, owner: None, name: &closure, at: Some(hook.location) };
site.check(graph, &hook.dependencies, errors);
}
}
for (module, name, dependencies) in &declared.meta {
let closure = format!("metadata `{}` of {}", short_type_name(*name), graph.module_name(*module));
let site = Closure { module: *module, owner: None, name: &closure, at: None };
site.check(graph, dependencies, errors);
}
}
struct Closure<'a> {
module: ModuleId,
owner: Option<BindingId>,
name: &'a str,
at: Option<&'static Location<'static>>,
}
impl Closure<'_> {
fn check(&self, graph: &Graph, dependencies: &Dependencies, errors: &mut Vec<WiringError>) {
for dependency in &dependencies.list {
if let Some(steps) = execution_read(graph, self.module, self.owner, dependency) {
let mut path = vec![dependency_text(dependency)];
path.extend(steps);
errors.push(WiringError::ClosureNeedsExecution { closure: self.name.to_owned(), path, at: self.at });
}
}
}
}
fn execution_read(
graph: &Graph,
module: ModuleId,
owner: Option<BindingId>,
dependency: &DependencyRecord,
) -> Option<Vec<String>> {
let through = |id: BindingId| Some(id) != owner && graph.passes_execution(id);
dependency.requirement.reads.iter().find_map(|read| match &read.kind {
ReadKind::Extension(_) | ReadKind::Execution => Some(Vec::new()),
ReadKind::Single(key) => match graph.lookup(module, *key) {
Some(Visible::Input(input)) => Some(vec![format!("input `{}`", input.name(BindingKind::Single))]),
Some(Visible::Binding(id)) if through(*id) => Some(execution_steps(graph, *id)),
_ => None,
},
ReadKind::Collection(key) => {
graph.collection(*key).iter().copied().find(|&id| through(id)).map(|id| execution_steps(graph, id))
}
ReadKind::Module => None,
})
}
fn execution_steps(graph: &Graph, id: BindingId) -> Vec<String> {
let ids = execution_path(graph, id);
let mut steps: Vec<String> = ids.iter().map(|&step| graph.scoped_label(step)).collect();
if let Some(&last) = ids.last() {
if let Some(edge) = graph.direct_execution_edge(last) {
steps.push(graph.dependency_step(last, edge.dependency));
}
}
steps
}
pub(crate) fn check_inputs(graph: &Graph, errors: &mut Vec<WiringError>) {
for handler in &graph.handlers {
for read in input_reads(graph, handler) {
let Some(decl) = graph.inputs.get(&read.input) else { continue };
if decl.seeders.contains(&handler.decl.transport) {
continue;
}
let Some(&seeder) = decl.seeders.first() else { continue };
errors.push(WiringError::InputNotSeeded {
handler: graph.handler_name(handler),
transport: handler.decl.transport,
input: read.input.name(BindingKind::Single),
seeder,
steps: read.steps,
});
}
}
}
pub(crate) struct InputRead {
pub(crate) input: Key,
pub(crate) steps: Vec<String>,
}
pub(crate) fn input_reads(graph: &Graph, handler: &HandlerRecord) -> Vec<InputRead> {
let mut walk = InputWalk::new(graph, handler);
walk.run();
walk.reads
}
struct InputWalk<'g> {
graph: &'g Graph,
handler: &'g HandlerRecord,
seen: HashSet<(Key, Option<BindingId>)>,
reads: Vec<InputRead>,
}
impl<'g> InputWalk<'g> {
fn new(graph: &'g Graph, handler: &'g HandlerRecord) -> Self {
InputWalk { graph, handler, seen: HashSet::new(), reads: Vec::new() }
}
fn run(&mut self) {
let graph = self.graph;
let handler = self.handler;
let mut roots = vec![handler.controller];
for key in handler.decl.role_keys {
roots.extend(graph.collection(key).iter().copied());
}
self.read_roots(&handler.decl.dependencies, None, &mut roots);
for dep in &handler.decl.enhancer_deps {
match dep {
EnhancerDep::Type(key) => {
if let Some(Visible::Binding(id)) = graph.lookup(handler.module, *key) {
roots.push(*id);
}
}
EnhancerDep::Closure(closure) if graph.closures.get(&closure.id) == Some(&Effective::Singleton) => {}
EnhancerDep::Closure(closure) => {
self.read_roots(&closure.dependencies, Some("enhancer closure"), &mut roots);
}
}
}
let mut parent: HashMap<BindingId, Option<BindingId>> = HashMap::new();
let mut queue = VecDeque::new();
for root in roots {
if in_execution(graph, root) && !parent.contains_key(&root) {
parent.insert(root, None);
queue.push_back(root);
}
}
while let Some(node) = queue.pop_front() {
for edge in &graph.binding(node).edges {
if let EdgeTarget::Input(input) = &edge.target {
if !edge.optional {
let mut steps: Vec<String> =
chain(&parent, node).into_iter().map(|step| graph.scoped_label(step)).collect();
steps.push(graph.dependency_step(node, edge.dependency));
self.record(*input, Some(node), steps);
}
}
}
for dep in graph.construction_deps(node) {
if in_execution(graph, dep) && !parent.contains_key(&dep) {
parent.insert(dep, Some(node));
queue.push_back(dep);
}
}
}
}
fn read_roots(&mut self, dependencies: &Dependencies, via: Option<&str>, roots: &mut Vec<BindingId>) {
let graph = self.graph;
let module = self.handler.module;
for dependency in &dependencies.list {
for read in &dependency.requirement.reads {
match &read.kind {
ReadKind::Single(key) => match graph.lookup(module, *key) {
Some(Visible::Input(input)) if !read.optional => {
let mut steps: Vec<String> = via.map(str::to_owned).into_iter().collect();
steps.push(dependency_text(dependency));
self.record(*input, None, steps);
}
Some(Visible::Binding(id)) => roots.push(*id),
_ => {}
},
ReadKind::Collection(key) => roots.extend(graph.collection(*key).iter().copied()),
ReadKind::Extension(_) | ReadKind::Execution | ReadKind::Module => {}
}
}
}
}
fn record(&mut self, input: Key, reader: Option<BindingId>, steps: Vec<String>) {
if self.seen.insert((input, reader)) {
self.reads.push(InputRead { input, steps });
}
}
}
fn in_execution(graph: &Graph, id: BindingId) -> bool {
matches!(graph.binding(id).effective, Effective::PerExecution | Effective::Transient)
}
fn chain(parent: &HashMap<BindingId, Option<BindingId>>, node: BindingId) -> Vec<BindingId> {
let mut steps = vec![node];
let mut current = node;
while let Some(&Some(previous)) = parent.get(¤t) {
if steps.contains(&previous) {
break;
}
steps.push(previous);
current = previous;
}
steps.reverse();
steps
}
pub(crate) fn execution_path(graph: &Graph, from: BindingId) -> Vec<BindingId> {
let reached = |id: BindingId| {
graph.direct_execution_edge(id).is_some() || (id != from && graph.binding(id).effective == Effective::PerExecution)
};
if reached(from) {
return vec![from];
}
let mut parent: HashMap<BindingId, BindingId> = HashMap::new();
let mut queue = VecDeque::from([from]);
while let Some(node) = queue.pop_front() {
for dep in graph.construction_deps(node) {
if dep == from || parent.contains_key(&dep) || !graph.passes_execution(dep) {
continue;
}
parent.insert(dep, node);
if reached(dep) {
let mut path = vec![dep];
let mut current = dep;
while let Some(&previous) = parent.get(¤t) {
path.push(previous);
if previous == from {
break;
}
current = previous;
}
path.reverse();
return path;
}
queue.push_back(dep);
}
}
vec![from]
}
fn printed_path(graph: &Graph, from: BindingId) -> Vec<String> {
let ids = execution_path(graph, from);
let mut steps: Vec<String> = ids
.iter()
.enumerate()
.map(|(position, &id)| if position == 0 { graph.label(id) } else { graph.scoped_label(id) })
.collect();
if let Some(&last) = ids.last() {
if let Some(edge) = graph.direct_execution_edge(last) {
steps.push(graph.dependency_step(last, edge.dependency));
}
}
steps
}
fn through_aliases(graph: &Graph, mut id: BindingId) -> BindingId {
for _ in 0..graph.bindings.len() {
match graph.alias_target(id) {
Some(target) => id = target,
None => break,
}
}
id
}