pub(crate) mod cycles;
pub(crate) mod order;
pub(crate) mod register;
pub(crate) mod scopes;
pub(crate) mod visibility;
pub(crate) mod wire;
use std::any::TypeId;
use std::collections::HashMap;
use std::sync::Arc;
use crate::binding::{BindingRecord, Qualifier, Recipe};
use crate::dependency::{Dependencies, DependencyLabel, DependencyRecord, ReadKind};
use crate::error::wiring::InputOrigin;
use crate::error::{LookupError, LookupKind};
use crate::graph::register::Site;
use crate::hooks::HookRecord;
use crate::key::{BindingKind, Key, KeyName};
use crate::module::meta::FrozenMeta;
use crate::module::{ModuleIdentity, ModuleName, ModuleSettings};
use crate::redact::SecretRegistry;
use crate::transport::controller::HandlerRecord;
use crate::transport::enhancer::ClosureId;
use crate::type_name::{TypeName, short_type_name};
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct ModuleId(pub(crate) u32);
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub(crate) struct BindingId(pub(crate) u32);
#[derive(Clone)]
pub(crate) struct Graph {
pub(crate) modules: Vec<FrozenModule>,
pub(crate) bindings: Vec<FrozenBinding>,
pub(crate) visibility: Vec<VisibilityTable>,
pub(crate) collections: HashMap<Key, Arc<[BindingId]>>,
pub(crate) inputs: HashMap<Key, InputDecl>,
pub(crate) by_identity: HashMap<ModuleIdentity, ModuleId>,
pub(crate) root: ModuleId,
pub(crate) connect_order: Vec<BindingId>,
pub(crate) handlers: Vec<HandlerRecord>,
pub(crate) closures: HashMap<ClosureId, Effective>,
pub(crate) secrets: SecretRegistry,
pub(in crate::graph) exported: Vec<Vec<(Key, BindingId)>>,
}
#[derive(Clone)]
pub(crate) struct FrozenModule {
pub(crate) id: ModuleId,
pub(crate) identity: ModuleIdentity,
pub(crate) name: ModuleName,
pub(crate) global: bool,
pub(crate) keyed: Option<Qualifier>,
pub(crate) imports: Vec<ModuleId>,
pub(crate) bindings: Vec<BindingId>,
pub(crate) hooks: Vec<HookRecord>,
pub(crate) meta: FrozenMeta,
pub(crate) loaded: Option<u32>,
pub(crate) settings: ModuleSettings,
pub(crate) site: Site,
}
#[derive(Clone)]
pub(crate) struct FrozenBinding {
pub(crate) id: BindingId,
pub(crate) origin: ModuleId,
pub(crate) record: BindingRecord,
pub(crate) role: Role,
pub(crate) effective: Effective,
pub(crate) needs_execution: bool,
pub(crate) edges: Vec<Edge>,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Role {
Provider,
Controller,
Enhancer,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Effective {
Singleton,
PerExecution,
Transient,
}
#[derive(Clone)]
pub(crate) struct Edge {
pub(crate) target: EdgeTarget,
pub(crate) dependency: usize,
pub(crate) optional: bool,
}
#[derive(Clone)]
pub(crate) enum EdgeTarget {
Binding(BindingId),
Collection(Key),
Input(Key),
Execution,
Module,
}
#[derive(Clone, Default)]
pub(crate) struct VisibilityTable {
pub(crate) entries: HashMap<Key, Visible>,
}
#[derive(Clone)]
pub(crate) enum Visible {
Binding(BindingId),
Input(Key),
Ambiguous(Vec<(ModuleId, BindingId)>),
}
#[derive(Clone)]
pub(crate) struct InputDecl {
pub(crate) key: Key,
pub(crate) seeders: Vec<TypeName>,
pub(crate) origin: InputOrigin,
}
impl InputDecl {
pub(crate) fn same_seeders(&self, other: &[TypeName]) -> bool {
self.seeders.len() == other.len() && self.seeders.iter().all(|seeder| other.contains(seeder))
}
}
impl Graph {
pub(crate) fn binding(&self, id: BindingId) -> &FrozenBinding {
&self.bindings[id.0 as usize]
}
pub(crate) fn module(&self, id: ModuleId) -> &FrozenModule {
&self.modules[id.0 as usize]
}
pub(crate) fn lookup(&self, module: ModuleId, key: Key) -> Option<&Visible> {
self.visibility[module.0 as usize].entries.get(&key)
}
pub(crate) fn collection(&self, key: Key) -> Arc<[BindingId]> {
match self.collections.get(&key) {
Some(ids) => Arc::clone(ids),
None => Arc::from(Vec::new()),
}
}
pub(crate) fn module_of(&self, identity: &ModuleIdentity) -> Result<ModuleId, LookupError> {
if let Some(&id) = self.by_identity.get(identity) {
return Ok(id);
}
let q = identity.qualifier().unwrap_or_else(Qualifier::none);
Err(LookupError::NotFound {
key: Key::from_parts(identity.type_id(), identity.type_name(), q.id, q.name).name(BindingKind::Single),
kind: LookupKind::Module,
})
}
pub(crate) fn find_module(&self, ty: TypeId, type_name: &'static str, qualifier: Option<Qualifier>) -> Result<ModuleId, LookupError> {
let found: Vec<&FrozenModule> = self
.modules
.iter()
.filter(|m| m.identity.type_id() == ty && (qualifier.is_none() || m.identity.qualifier() == qualifier))
.collect();
match found.as_slice() {
[one] => Ok(one.id),
[] => {
let q = qualifier.unwrap_or_else(Qualifier::none);
Err(LookupError::NotFound {
key: Key::from_parts(ty, type_name, q.id, q.name).name(BindingKind::Single),
kind: LookupKind::Module,
})
}
several => Err(LookupError::AmbiguousModule {
module: type_name,
candidates: several.iter().map(|m| m.name.clone()).collect(),
}),
}
}
pub(in crate::graph) fn empty() -> Graph {
Graph {
modules: Vec::new(),
bindings: Vec::new(),
visibility: Vec::new(),
collections: HashMap::new(),
inputs: HashMap::new(),
by_identity: HashMap::new(),
root: ModuleId(0),
connect_order: Vec::new(),
handlers: Vec::new(),
closures: HashMap::new(),
secrets: SecretRegistry::default(),
exported: Vec::new(),
}
}
pub(in crate::graph) fn module_name(&self, id: ModuleId) -> ModuleName {
self.module(id).name.clone()
}
pub(in crate::graph) fn key_name(&self, id: BindingId) -> KeyName {
let record = &self.binding(id).record;
record_key(record).name(record.kind)
}
pub(in crate::graph) fn label(&self, id: BindingId) -> String {
let record = &self.binding(id).record;
let mut text = short_type_name(record.built);
if record.qualifier != Qualifier::none() {
text.push_str(" @ ");
text.push_str(&short_type_name(record.qualifier.name));
}
text
}
pub(in crate::graph) fn scoped_label(&self, id: BindingId) -> String {
let mut text = self.label(id);
match self.binding(id).effective {
Effective::PerExecution => text.push_str(" (execution)"),
Effective::Transient => text.push_str(" (transient)"),
Effective::Singleton => {}
}
text
}
pub(in crate::graph) fn consumer(&self, id: BindingId, index: usize) -> String {
let record = &self.binding(id).record;
let mut text = self.label(id);
if matches!(record.recipe, Recipe::Factory(_)) && !record.constructs {
text.push_str(" factory");
}
match record.dependencies.list.get(index) {
Some(dependency) => format!("{text} ({})", dependency_label(dependency.label)),
None => text,
}
}
pub(in crate::graph) fn alias_target(&self, id: BindingId) -> Option<BindingId> {
let binding = self.binding(id);
let Recipe::Alias { target } = &binding.record.recipe else { return None };
match self.lookup(binding.origin, *target) {
Some(Visible::Binding(target)) => Some(*target),
_ => None,
}
}
pub(in crate::graph) fn construction_deps(&self, id: BindingId) -> Vec<BindingId> {
let mut deps = Vec::new();
for edge in &self.binding(id).edges {
match &edge.target {
EdgeTarget::Binding(dep) => deps.push(*dep),
EdgeTarget::Collection(key) => deps.extend(self.collections.get(key).into_iter().flat_map(|ids| ids.iter().copied())),
EdgeTarget::Input(_) | EdgeTarget::Execution | EdgeTarget::Module => {}
}
}
deps.extend(self.alias_target(id));
deps
}
pub(in crate::graph) fn closure_deps(&self, module: ModuleId, dependencies: &Dependencies) -> Vec<BindingId> {
let mut deps = Vec::new();
for read in dependencies.list.iter().flat_map(|d| &d.requirement.reads) {
match &read.kind {
ReadKind::Single(key) => {
if let Some(Visible::Binding(dep)) = self.lookup(module, *key) {
deps.push(*dep);
}
}
ReadKind::Collection(key) => {
deps.extend(self.collections.get(key).into_iter().flat_map(|ids| ids.iter().copied()));
}
ReadKind::Extension(_) | ReadKind::Execution | ReadKind::Module => {}
}
}
deps
}
pub(in crate::graph) fn readiness_deps(&self, id: BindingId) -> Vec<BindingId> {
let binding = self.binding(id);
match &binding.record.ready {
Some(ready) => self.closure_deps(binding.origin, &ready.dependencies).into_iter().filter(|dep| *dep != id).collect(),
None => Vec::new(),
}
}
pub(in crate::graph) fn passes_execution(&self, id: BindingId) -> bool {
let binding = self.binding(id);
match binding.effective {
Effective::PerExecution => true,
Effective::Transient => binding.needs_execution,
Effective::Singleton => false,
}
}
pub(in crate::graph) fn direct_execution_edge(&self, id: BindingId) -> Option<&Edge> {
self.binding(id)
.edges
.iter()
.find(|edge| matches!(edge.target, EdgeTarget::Execution | EdgeTarget::Input(_)))
}
pub(in crate::graph) fn handler_name(&self, handler: &HandlerRecord) -> String {
format!("{}::{}", self.label(handler.controller), handler.decl.name)
}
pub(in crate::graph) fn dependency_step(&self, id: BindingId, index: usize) -> String {
match self.binding(id).record.dependencies.list.get(index) {
Some(dependency) => dependency_text(dependency),
None => String::new(),
}
}
}
pub(in crate::graph) fn record_key(record: &BindingRecord) -> Key {
record.primary.with_qualifier(record.qualifier.id, record.qualifier.name)
}
pub(in crate::graph) fn boundary_key(keyed: Option<Qualifier>, key: Key) -> Key {
match keyed {
Some(q) if key.is_unqualified() => key.with_qualifier(q.id, q.name),
_ => key,
}
}
pub(in crate::graph) fn dependency_label(label: DependencyLabel) -> String {
match label {
DependencyLabel::Field(name) => format!("field `{name}`"),
DependencyLabel::Param(name) => format!("param `{name}`"),
DependencyLabel::Position(index) => format!("param #{}", index + 1),
}
}
pub(in crate::graph) fn dependency_text(dependency: &DependencyRecord) -> String {
format!("{} ({})", short_type_name(dependency.type_name), dependency_label(dependency.label))
}