use std::any::{Any, TypeId};
use std::fmt;
use std::sync::Arc;
use techy::core::node::NodeRef;
use crate::model::names::ElementName;
use crate::lang::Flm;
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct ElemIdx(pub u32);
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AspectCollision {
pub aspect: &'static str,
}
impl fmt::Display for AspectCollision {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"an element can carry one implementation of each aspect, but aspect `{}` \
is already attached to this element",
self.aspect
)
}
}
impl std::error::Error for AspectCollision {}
#[derive(Clone)]
struct AspectEntry {
id: TypeId,
name: &'static str,
imp: Arc<dyn Any + Send + Sync>,
}
#[derive(Clone, Default)]
pub struct AspectMap {
entries: Vec<AspectEntry>,
}
impl AspectMap {
pub fn new() -> AspectMap {
AspectMap::default()
}
pub fn insert<A: ?Sized + Any + Send + Sync>(
&mut self,
imp: Arc<A>,
) -> Result<(), AspectCollision> {
const {
assert!(
size_of::<&A>() == 2 * size_of::<*const ()>(),
"the aspect must be given as its trait-object type, as in \
.with::<dyn MyAspect>(…) or .insert::<dyn MyAspect>(…)"
);
}
self.insert_erased(TypeId::of::<A>(), std::any::type_name::<A>(), Arc::new(imp))
}
pub fn insert_erased(
&mut self,
id: TypeId,
name: &'static str,
imp: Arc<dyn Any + Send + Sync>,
) -> Result<(), AspectCollision> {
if self.entries.iter().any(|entry| entry.id == id) {
return Err(AspectCollision { aspect: name });
}
self.entries.push(AspectEntry { id, name, imp });
Ok(())
}
pub fn get<A: ?Sized + Any>(&self) -> Option<&A> {
let id = TypeId::of::<A>();
self.entries
.iter()
.find(|entry| entry.id == id)
.and_then(|entry| entry.imp.downcast_ref::<Arc<A>>())
.map(|arc| &**arc)
}
pub fn get_arc<A: ?Sized + Any>(&self) -> Option<Arc<A>> {
let id = TypeId::of::<A>();
self.entries
.iter()
.find(|entry| entry.id == id)
.and_then(|entry| entry.imp.downcast_ref::<Arc<A>>())
.map(Arc::clone)
}
pub fn has<A: ?Sized + Any>(&self) -> bool {
let id = TypeId::of::<A>();
self.entries.iter().any(|entry| entry.id == id)
}
pub fn entries(
&self,
) -> impl Iterator<Item = (TypeId, &'static str, Arc<dyn Any + Send + Sync>)> + '_ {
self.entries.iter().map(|entry| (entry.id, entry.name, Arc::clone(&entry.imp)))
}
pub fn aspect_ids(&self) -> impl Iterator<Item = TypeId> + '_ {
self.entries.iter().map(|entry| entry.id)
}
pub fn len(&self) -> usize {
self.entries.len()
}
pub fn is_empty(&self) -> bool {
self.entries.is_empty()
}
}
impl fmt::Debug for AspectMap {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_list().entries(self.entries.iter().map(|entry| entry.name)).finish()
}
}
#[derive(Clone)]
pub struct ElementSpec {
pub name: ElementName,
pub docs: String,
pub aspects: AspectMap,
pub value: Option<Arc<dyn Any + Send + Sync>>,
}
impl ElementSpec {
pub fn new(name: impl Into<ElementName>) -> ElementSpec {
ElementSpec {
name: name.into(),
docs: String::new(),
aspects: AspectMap::new(),
value: None,
}
}
pub fn docs(mut self, docs: impl Into<String>) -> ElementSpec {
self.docs = crate::kept_docs(docs);
self
}
pub fn with_value(mut self, value: Arc<dyn Any + Send + Sync>) -> ElementSpec {
self.value = Some(value);
self
}
pub fn with<A: ?Sized + Any + Send + Sync>(mut self, imp: Arc<A>) -> ElementSpec {
if let Err(collision) = self.aspects.insert::<A>(imp) {
panic!(
"element `{}`: {} (code that may attach an aspect twice uses the fallible \
`AspectMap::insert` rather than `ElementSpec::with`)",
self.name, collision
);
}
self
}
pub fn aspect<A: ?Sized + Any>(&self) -> Option<&A> {
self.aspects.get::<A>()
}
pub fn has_aspect<A: ?Sized + Any>(&self) -> bool {
self.aspects.has::<A>()
}
pub fn value_as<V: Any + Send + Sync>(&self) -> Option<&V> {
self.value.as_deref().and_then(|value| value.downcast_ref::<V>())
}
pub fn same_value(this: &Arc<ElementSpec>, other: &Arc<ElementSpec>) -> bool {
Arc::ptr_eq(this, other)
}
}
impl fmt::Debug for ElementSpec {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("ElementSpec")
.field("name", &self.name)
.field("aspects", &self.aspects)
.field("value", &self.value.as_ref().map(|_| "…"))
.finish()
}
}
pub fn element_of<'t>(node: &NodeRef<'t, Flm>) -> &'t Arc<ElementSpec> {
&node.ext().element
}
pub fn element_value<'t, V: Any + Send + Sync>(node: &NodeRef<'t, Flm>) -> Option<&'t V> {
node.ext().element.value.as_deref().and_then(|value| value.downcast_ref::<V>())
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct AmbiguousElement {
pub name: ElementName,
pub owners: Vec<crate::model::names::FeatureName>,
}
impl fmt::Display for AmbiguousElement {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"the element type name `{}` must belong to exactly one registered element, \
but {} elements are registered under it (by {})",
self.name,
self.owners.len(),
self.owners.iter().map(|o| format!("`{o}`")).collect::<Vec<_>>().join(", ")
)
}
}
impl std::error::Error for AmbiguousElement {}
#[cfg(test)]
mod tests {
use super::*;
trait Glossary: Send + Sync {
fn term(&self) -> &str;
}
struct Term(&'static str);
impl Glossary for Term {
fn term(&self) -> &str {
self.0
}
}
#[test]
fn aspect_map_finds_an_attached_aspect_by_trait_object_type() {
let mut map = AspectMap::new();
map.insert::<dyn Glossary>(Arc::new(Term("stabilizer"))).unwrap();
assert_eq!(map.get::<dyn Glossary>().map(|g| g.term()), Some("stabilizer"));
assert!(map.has::<dyn Glossary>());
assert_eq!(map.len(), 1);
}
#[test]
fn aspect_map_reports_a_second_attachment_of_one_aspect() {
let mut map = AspectMap::new();
map.insert::<dyn Glossary>(Arc::new(Term("a"))).unwrap();
let collision = map.insert::<dyn Glossary>(Arc::new(Term("b"))).unwrap_err();
assert_eq!(collision.aspect, std::any::type_name::<dyn Glossary>());
assert_eq!(map.get::<dyn Glossary>().map(|g| g.term()), Some("a"));
}
#[test]
fn erased_entries_round_trip_through_insert_erased() {
let mut map = AspectMap::new();
map.insert::<dyn Glossary>(Arc::new(Term("t"))).unwrap();
let mut copy = AspectMap::new();
for (id, name, imp) in map.entries() {
copy.insert_erased(id, name, imp).unwrap();
}
assert_eq!(copy.get::<dyn Glossary>().map(|g| g.term()), Some("t"));
}
#[test]
fn element_value_downcasts_to_the_declared_type() {
struct Heading {
level: u8,
}
let value = Arc::new(Heading { level: 2 });
let element = ElementSpec::new("flm.heading").docs("a heading").with_value(value);
assert_eq!(element.value_as::<Heading>().map(|h| h.level), Some(2));
assert!(element.value_as::<Term>().is_none());
}
#[test]
#[should_panic]
fn attaching_one_aspect_twice_on_the_builder_panics() {
let _ = ElementSpec::new("flm.term")
.with::<dyn Glossary>(Arc::new(Term("a")))
.with::<dyn Glossary>(Arc::new(Term("b")));
}
#[test]
fn identity_is_the_shared_value_not_the_name() {
let a = Arc::new(ElementSpec::new("flm.heading"));
let b = Arc::new(ElementSpec::new("flm.heading"));
assert!(ElementSpec::same_value(&a, &Arc::clone(&a)));
assert!(!ElementSpec::same_value(&a, &b));
}
}