pub(crate) mod def;
pub(crate) mod dynamic;
pub(crate) mod handle;
pub(crate) mod keyed;
pub(crate) mod meta;
use std::any::{Any, TypeId, type_name};
use std::collections::{HashMap, HashSet};
use std::fmt;
use std::hash::{DefaultHasher, Hash, Hasher};
use std::panic::Location;
use std::sync::Arc;
use crate::binding::Qualifier;
use crate::module::def::ModuleDef;
use crate::module::keyed::Keyed;
use crate::type_name::short_type_name;
pub trait Module: Send + Sync + 'static {
fn identity(&self) -> ModuleIdentity;
fn register(&self, m: &mut ModuleDef<'_>);
fn settings(&self) -> ModuleSettings {
ModuleSettings::new()
}
fn keyed<Q: 'static>(self) -> Keyed<Q, Self>
where
Self: Sized,
{
Keyed::new(self)
}
}
#[derive(Clone)]
pub struct ModuleIdentity {
ty: TypeId,
ty_name: &'static str,
config: Option<ConfigKey>,
qualifier: Option<Qualifier>,
label: Option<&'static str>,
}
impl ModuleIdentity {
pub fn of_type<M: 'static>() -> Self {
ModuleIdentity { ty: TypeId::of::<M>(), ty_name: type_name::<M>(), config: None, qualifier: None, label: None }
}
pub fn of_value<M: Eq + Hash + Clone + Send + Sync + 'static>(m: &M) -> Self {
ModuleIdentity::of_owner::<M, M>(m)
}
pub fn label(self, name: &'static str) -> Self {
ModuleIdentity { label: Some(name), ..self }
}
pub fn of_owner<O: 'static, C: Eq + Hash + Clone + Send + Sync + 'static>(config: &C) -> Self {
let mut hasher = DefaultHasher::new();
TypeId::of::<C>().hash(&mut hasher);
config.hash(&mut hasher);
ModuleIdentity {
ty: TypeId::of::<O>(),
ty_name: type_name::<O>(),
config: Some(ConfigKey { hash: hasher.finish(), value: Arc::new(config.clone()) }),
qualifier: None,
label: None,
}
}
pub(crate) fn keyed_by(self, qualifier: Qualifier) -> Self {
ModuleIdentity { qualifier: Some(qualifier), ..self }
}
pub(crate) fn type_id(&self) -> TypeId {
self.ty
}
pub(crate) fn type_name(&self) -> &'static str {
self.ty_name
}
pub(crate) fn qualifier(&self) -> Option<Qualifier> {
self.qualifier
}
}
impl PartialEq for ModuleIdentity {
fn eq(&self, other: &Self) -> bool {
self.ty == other.ty && self.qualifier == other.qualifier && self.config == other.config
}
}
impl Eq for ModuleIdentity {}
impl Hash for ModuleIdentity {
fn hash<H: Hasher>(&self, state: &mut H) {
self.ty.hash(state);
self.qualifier.hash(state);
self.config.as_ref().map(|c| c.hash).hash(state);
}
}
#[derive(Clone, Default)]
pub struct ModuleSettings {
entries: Vec<Setting>,
repeats: Vec<Repeat>,
}
#[derive(Clone)]
struct Setting {
name: &'static str,
value: String,
at: &'static Location<'static>,
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(crate) struct Repeat {
pub(crate) name: &'static str,
pub(crate) first: &'static Location<'static>,
pub(crate) second: &'static Location<'static>,
}
impl ModuleSettings {
pub fn new() -> Self {
ModuleSettings::default()
}
#[track_caller]
pub fn with(mut self, name: &'static str, value: impl fmt::Debug) -> Self {
let at = Location::caller();
match self.entries.iter().find(|written| written.name == name) {
Some(first) => self.repeats.push(Repeat { name, first: first.at, second: at }),
None => self.entries.push(Setting { name, value: format!("{value:?}"), at }),
}
self
}
pub(crate) fn repeats(&self) -> &[Repeat] {
&self.repeats
}
fn value(&self, name: &str) -> Option<&str> {
self.entries.iter().find(|written| written.name == name).map(|written| written.value.as_str())
}
pub(crate) fn differences(&self, other: &ModuleSettings) -> Vec<(&'static str, Option<String>, Option<String>)> {
let mut names: Vec<&'static str> = self.entries.iter().map(|written| written.name).collect();
names.extend(other.entries.iter().map(|written| written.name).filter(|name| self.value(name).is_none()));
names
.into_iter()
.filter_map(|name| {
let (first, second) = (self.value(name), other.value(name));
(first != second).then(|| (name, first.map(str::to_owned), second.map(str::to_owned)))
})
.collect()
}
}
impl PartialEq for ModuleSettings {
fn eq(&self, other: &Self) -> bool {
self.entries.len() == other.entries.len()
&& self.entries.iter().zip(&other.entries).all(|(a, b)| a.name == b.name && a.value == b.value)
}
}
impl Eq for ModuleSettings {}
impl fmt::Debug for ModuleSettings {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_map().entries(self.entries.iter().map(|written| (written.name, &written.value))).finish()
}
}
#[derive(Clone)]
pub(crate) struct ConfigKey {
pub(crate) hash: u64,
pub(crate) value: Arc<dyn DynKey>,
}
impl PartialEq for ConfigKey {
fn eq(&self, other: &Self) -> bool {
self.hash == other.hash && self.value.eq_dyn(&*other.value)
}
}
pub(crate) trait DynKey: Any + Send + Sync {
fn eq_dyn(&self, other: &dyn DynKey) -> bool;
fn as_any(&self) -> &dyn Any;
}
impl<C: Eq + Send + Sync + 'static> DynKey for C {
fn eq_dyn(&self, other: &dyn DynKey) -> bool {
other.as_any().downcast_ref::<C>() == Some(self)
}
fn as_any(&self) -> &dyn Any {
self
}
}
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct ModuleName {
text: Arc<str>,
full: Arc<str>,
}
impl ModuleName {
pub(crate) fn of(identity: &ModuleIdentity, instance: usize) -> Self {
ModuleName {
text: Arc::from(ModuleName::render(identity, instance, false)),
full: Arc::from(ModuleName::render(identity, instance, true)),
}
}
fn render(identity: &ModuleIdentity, instance: usize, full: bool) -> String {
let path = |name: &'static str| if full { name.to_owned() } else { short_type_name(name) };
let mut text = match identity.label {
Some(label) if full => format!("{label} ({})", identity.ty_name),
Some(label) => label.to_owned(),
None => path(identity.ty_name),
};
if let Some(qualifier) = identity.qualifier {
text.push_str(" @ ");
text.push_str(&path(qualifier.name));
}
if instance > 0 {
text.push_str(&format!(" #{}", instance + 1));
}
text
}
pub fn as_str(&self) -> &str {
&self.text
}
}
impl fmt::Display for ModuleName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad(if f.alternate() { &self.full } else { &self.text })
}
}
impl fmt::Debug for ModuleName {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
pub(crate) fn colliding_names<'a>(names: impl IntoIterator<Item = &'a ModuleName>) -> HashSet<ModuleName> {
let mut by_text: HashMap<&'a str, Vec<&'a ModuleName>> = HashMap::new();
for name in names {
let group = by_text.entry(name.as_str()).or_default();
if !group.contains(&name) {
group.push(name);
}
}
by_text.into_values().filter(|group| group.len() > 1).flatten().cloned().collect()
}
#[cfg(test)]
mod tests {
use super::ModuleSettings;
#[test]
fn a_setting_name_written_twice_is_recorded_as_a_repeat() {
let first_line = line!() + 2;
let settings = ModuleSettings::new()
.with("lazy", false)
.with("retries", 2)
.with("lazy", true);
assert_eq!(settings, ModuleSettings::new().with("lazy", false).with("retries", 2));
let [repeat] = settings.repeats() else { panic!("expected one repeat: {}", settings.repeats().len()) };
assert_eq!(repeat.name, "lazy");
assert_eq!((repeat.first.file(), repeat.first.line()), (file!(), first_line));
assert_eq!((repeat.second.file(), repeat.second.line()), (file!(), first_line + 2));
}
}