Skip to main content

cranpose_foundation/modifier/
any_element.rs

1// The type-erased modifier element a chain reconciles with: what it tells of
2// the node it makes, and how two compare.
3
4use std::{
5    any::{Any, TypeId, type_name},
6    cell::{Cell, RefCell},
7    fmt,
8    hash::Hasher,
9    marker::PhantomData,
10    rc::Rc,
11};
12
13use cranpose_core::{PackedU64, ProvidedValue, hash::default};
14
15use super::{
16    InvalidationKind, ModifierNode, ModifierNodeElement, NodeCapabilities, PlainFns, PlainValue,
17};
18
19/// Type-erased modifier element used by the runtime to reconcile chains.
20pub trait AnyModifierElement: fmt::Debug {
21    /// The type of the element itself.
22    fn element_type(&self) -> TypeId;
23
24    /// How a chain keeps the element: by a node it makes, or as a value.
25    fn maker(&self) -> ElementMaker<'_>;
26
27    /// The key that tells apart several elements of one type, or `None` when the element has none.
28    fn key(&self) -> Option<u64>;
29
30    /// The capabilities of the nodes that the element creates.
31    fn capabilities(&self) -> NodeCapabilities {
32        NodeCapabilities::default()
33    }
34
35    /// The hash of the element, computed once when the element was wrapped.
36    fn hash_code(&self) -> u64;
37
38    /// Whether `other` is an element of the same type with equal data.
39    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool;
40
41    /// The name that inspector tooling shows for the element.
42    fn inspector_name(&self) -> &'static str;
43
44    /// Reports each inspector property of the element to `visitor` as a name and a value.
45    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String));
46
47    /// Whether the node must be updated even when the new element equals the old one.
48    fn requires_update(&self) -> bool;
49
50    /// Whether updating an existing node invalidates all pipeline stages that its capabilities
51    /// cover.
52    fn auto_invalidates_on_update(&self) -> bool;
53
54    /// The one pipeline stage that an update invalidates, or `None` to invalidate by capabilities.
55    fn update_invalidation_kind(&self) -> Option<InvalidationKind>;
56
57    /// Whether this element has composition locals for its content.
58    fn provides_composition_locals(&self) -> bool {
59        false
60    }
61
62    /// The composition locals this element hands to its content.
63    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
64        Vec::new()
65    }
66
67    /// Returns the element as `Any`, for downcasting to its concrete type.
68    fn as_any(&self) -> &dyn Any;
69
70    /// Whether `node` is of this element's node type and keeps an element
71    /// equal to this one: always `false` for an element whose node keeps
72    /// none.
73    fn equals_node(&self, _node: &dyn ModifierNode) -> bool {
74        false
75    }
76
77    /// Whether `words`, the value of a plain element of the type `fns`
78    /// tells, hold a value equal to this element: always `false` for an
79    /// element that is not plain.
80    fn equals_plain(&self, _fns: &PlainFns, _words: &[u32]) -> bool {
81        false
82    }
83}
84
85/// How a chain keeps an element.
86pub enum ElementMaker<'a> {
87    /// By a node the element makes and updates.
88    Node(&'a dyn NodeMaker),
89    /// As words in the element's chain entry: see [`super::PlainElement`].
90    Plain(&'a dyn PlainValue),
91}
92
93/// An element that makes a node and updates it.
94pub trait NodeMaker {
95    /// The type of node that the element creates.
96    fn node_type(&self) -> TypeId;
97
98    /// A new node for this element, in the shared cell its chain entry keeps.
99    fn create_node(&self) -> Rc<RefCell<dyn ModifierNode>>;
100
101    /// Whether `node` is of the type that this element updates.
102    fn can_update_node(&self, node: &dyn ModifierNode) -> bool;
103
104    /// Brings `node` up to date with the data of this element.
105    fn update_node(&self, node: &mut dyn ModifierNode);
106
107    /// What stands for the element beside its node when the node keeps
108    /// every value of it: see [`ModifierNodeElement::FROM_NODE`].
109    fn held_by_node(&self) -> Option<NodeHeld> {
110        None
111    }
112}
113
114/// What a chain keeps of an element whose node keeps every value of it, in
115/// place of the element: its type, and how to read it from the node. One
116/// word, so an entry keeps it where it keeps an element.
117#[derive(Clone, Copy)]
118pub struct NodeHeld(&'static HeldFns);
119
120impl fmt::Debug for NodeHeld {
121    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122        f.debug_struct("NodeHeld").finish_non_exhaustive()
123    }
124}
125
126impl NodeHeld {
127    pub(crate) fn element_type(self) -> TypeId {
128        (self.0.element_type)()
129    }
130
131    pub(crate) fn node_type(self) -> TypeId {
132        (self.0.node_type)()
133    }
134
135    // The hash of the element `node` holds, as the element itself hashes.
136    pub(crate) fn hash_code(self, node: &dyn ModifierNode) -> u64 {
137        (self.0.hash_code)(node)
138    }
139
140    // The element `node` holds, made again.
141    pub(crate) fn element(self, node: &dyn ModifierNode) -> DynModifierElement {
142        (self.0.element)(node)
143    }
144}
145
146struct HeldFns {
147    element_type: fn() -> TypeId,
148    node_type: fn() -> TypeId,
149    hash_code: fn(&dyn ModifierNode) -> u64,
150    element: fn(&dyn ModifierNode) -> DynModifierElement,
151}
152
153struct HeldBy<E>(PhantomData<fn() -> E>);
154
155impl<E: ModifierNodeElement> HeldBy<E> {
156    const FNS: HeldFns = HeldFns {
157        element_type: TypeId::of::<E>,
158        node_type: TypeId::of::<E::Node>,
159        hash_code: Self::hash_code,
160        element: Self::element,
161    };
162
163    // The element `node` holds. A chain keeps a `NodeHeld` only beside a
164    // node of the element's node type.
165    fn of(node: &dyn ModifierNode) -> E {
166        let from_node = E::FROM_NODE.expect("a node-held element makes itself from its node");
167        from_node(
168            node.as_any()
169                .downcast_ref::<E::Node>()
170                .expect("a node-held element's node is of its node type"),
171        )
172    }
173
174    fn hash_code(node: &dyn ModifierNode) -> u64 {
175        let mut hasher = default::new();
176        Self::of(node).hash(&mut hasher);
177        hasher.finish()
178    }
179
180    fn element(node: &dyn ModifierNode) -> DynModifierElement {
181        modifier_element(Self::of(node))
182    }
183}
184
185struct TypedModifierElement<E: ModifierNodeElement> {
186    element: E,
187    // The element's hash, worked out the first time a chain rebuilding
188    // asks for it: most elements are built for a recomposition and only
189    // compared with the last ones.
190    hash: Cell<Option<PackedU64>>,
191    provides_locals: bool,
192}
193
194impl<E: ModifierNodeElement> TypedModifierElement<E> {
195    fn new(element: E) -> Self {
196        let provides_locals = !element.provided_composition_locals().is_empty();
197        Self {
198            element,
199            hash: Cell::new(None),
200            provides_locals,
201        }
202    }
203}
204
205impl<E> fmt::Debug for TypedModifierElement<E>
206where
207    E: ModifierNodeElement,
208{
209    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
210        f.debug_struct("TypedModifierElement")
211            .field("type", &type_name::<E>())
212            .finish()
213    }
214}
215
216impl<E> NodeMaker for TypedModifierElement<E>
217where
218    E: ModifierNodeElement,
219{
220    fn node_type(&self) -> TypeId {
221        TypeId::of::<E::Node>()
222    }
223
224    fn create_node(&self) -> Rc<RefCell<dyn ModifierNode>> {
225        Rc::new(RefCell::new(self.element.create()))
226    }
227
228    fn can_update_node(&self, node: &dyn ModifierNode) -> bool {
229        node.as_any().is::<E::Node>()
230    }
231
232    fn update_node(&self, node: &mut dyn ModifierNode) {
233        if let Some(typed) = node.as_any_mut().downcast_mut::<E::Node>() {
234            self.element.update(typed);
235        }
236    }
237
238    fn held_by_node(&self) -> Option<NodeHeld> {
239        E::FROM_NODE.map(|_| NodeHeld(&HeldBy::<E>::FNS))
240    }
241}
242
243impl<E> AnyModifierElement for TypedModifierElement<E>
244where
245    E: ModifierNodeElement,
246{
247    fn element_type(&self) -> TypeId {
248        TypeId::of::<E>()
249    }
250
251    fn maker(&self) -> ElementMaker<'_> {
252        ElementMaker::Node(self)
253    }
254
255    fn key(&self) -> Option<u64> {
256        self.element.key()
257    }
258
259    fn capabilities(&self) -> NodeCapabilities {
260        self.element.capabilities()
261    }
262
263    fn provides_composition_locals(&self) -> bool {
264        self.provides_locals
265    }
266
267    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
268        self.element.provided_composition_locals()
269    }
270
271    fn hash_code(&self) -> u64 {
272        if let Some(hash) = self.hash.get() {
273            return hash.get();
274        }
275        let mut hasher = default::new();
276        self.element.hash(&mut hasher);
277        let hash = hasher.finish();
278        self.hash.set(Some(PackedU64::new(hash)));
279        hash
280    }
281
282    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
283        other
284            .as_any()
285            .downcast_ref::<Self>()
286            .is_some_and(|typed| typed.element == self.element)
287    }
288
289    fn inspector_name(&self) -> &'static str {
290        self.element.inspector_name()
291    }
292
293    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String)) {
294        self.element.inspector_properties(visitor);
295    }
296
297    fn requires_update(&self) -> bool {
298        self.element.always_update()
299    }
300
301    fn auto_invalidates_on_update(&self) -> bool {
302        self.element.auto_invalidate_on_update()
303    }
304
305    fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
306        self.element.update_invalidation_kind()
307    }
308
309    fn as_any(&self) -> &dyn Any {
310        self
311    }
312
313    fn equals_node(&self, node: &dyn ModifierNode) -> bool {
314        node.as_any()
315            .downcast_ref::<E::Node>()
316            .is_some_and(|node| self.element.equals_node(node))
317    }
318}
319
320/// Convenience helper for callers to construct a type-erased modifier
321/// element without having to mention the internal wrapper type.
322pub fn modifier_element<E: ModifierNodeElement>(element: E) -> DynModifierElement {
323    Rc::new(TypedModifierElement::new(element))
324}
325
326/// Boxed type-erased modifier element.
327pub type DynModifierElement = Rc<dyn AnyModifierElement>;