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    PlainWords,
18};
19
20/// Type-erased modifier element used by the runtime to reconcile chains.
21pub trait AnyModifierElement: fmt::Debug {
22    /// The type of the element itself.
23    fn element_type(&self) -> TypeId;
24
25    /// How a chain keeps the element: by a node it makes, or as a value.
26    fn maker(&self) -> ElementMaker<'_>;
27
28    /// The key that tells apart several elements of one type, or `None` when the element has none.
29    fn key(&self) -> Option<u64>;
30
31    /// The capabilities of the nodes that the element creates.
32    fn capabilities(&self) -> NodeCapabilities {
33        NodeCapabilities::default()
34    }
35
36    /// The hash of the element, computed once when the element was wrapped.
37    fn hash_code(&self) -> u64;
38
39    /// Whether `other` is an element of the same type with equal data.
40    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool;
41
42    /// The name that inspector tooling shows for the element.
43    fn inspector_name(&self) -> &'static str;
44
45    /// Reports each inspector property of the element to `visitor` as a name and a value.
46    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String));
47
48    /// Whether the node must be updated even when the new element equals the old one.
49    fn requires_update(&self) -> bool;
50
51    /// Whether updating an existing node invalidates all pipeline stages that its capabilities
52    /// cover.
53    fn auto_invalidates_on_update(&self) -> bool;
54
55    /// The one pipeline stage that an update invalidates, or `None` to invalidate by capabilities.
56    fn update_invalidation_kind(&self) -> Option<InvalidationKind>;
57
58    /// Whether this element has composition locals for its content.
59    fn provides_composition_locals(&self) -> bool {
60        false
61    }
62
63    /// The composition locals this element hands to its content.
64    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
65        Vec::new()
66    }
67
68    /// Returns the element as `Any`, for downcasting to its concrete type.
69    fn as_any(&self) -> &dyn Any;
70
71    /// Whether `node` is of this element's node type and keeps an element
72    /// equal to this one: always `false` for an element whose node keeps
73    /// none.
74    fn equals_node(&self, _node: &dyn ModifierNode) -> bool {
75        false
76    }
77
78    /// Whether `words`, the value of a plain element of the type `fns`
79    /// tells, hold a value equal to this element: always `false` for an
80    /// element that is not plain.
81    fn equals_plain(&self, _fns: &PlainFns, _words: &[u32]) -> bool {
82        false
83    }
84}
85
86/// How a chain keeps an element.
87pub enum ElementMaker<'a> {
88    /// By a node the element makes and updates.
89    Node(&'a dyn NodeMaker),
90    /// As words in the element's chain entry: see [`super::PlainElement`].
91    Plain(&'a dyn PlainValue),
92}
93
94/// An element that makes a node and updates it.
95pub trait NodeMaker {
96    /// The type of node that the element creates.
97    fn node_type(&self) -> TypeId;
98
99    /// A new node for this element, in the shared cell its chain entry keeps.
100    fn create_node(&self) -> Rc<RefCell<dyn ModifierNode>>;
101
102    /// Whether `node` is of the type that this element updates.
103    fn can_update_node(&self, node: &dyn ModifierNode) -> bool;
104
105    /// Brings `node` up to date with the data of this element.
106    fn update_node(&self, node: &mut dyn ModifierNode);
107
108    /// What stands for the element beside its node when the node keeps
109    /// every value of it: see [`ModifierNodeElement::FROM_NODE`].
110    fn held_by_node(&self) -> Option<NodeHeld> {
111        None
112    }
113}
114
115/// What a chain keeps of an element whose node keeps every value of it, in
116/// place of the element: its type, and how to read it from the node. One
117/// word, so an entry keeps it where it keeps an element.
118#[derive(Clone, Copy)]
119pub struct NodeHeld(&'static HeldFns);
120
121impl fmt::Debug for NodeHeld {
122    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
123        f.debug_struct("NodeHeld").finish_non_exhaustive()
124    }
125}
126
127impl NodeHeld {
128    pub(crate) fn element_type(self) -> TypeId {
129        (self.0.element_type)()
130    }
131
132    pub(crate) fn node_type(self) -> TypeId {
133        (self.0.node_type)()
134    }
135
136    // The hash of the element `node` holds, as the element itself hashes.
137    pub(crate) fn hash_code(self, node: &dyn ModifierNode) -> u64 {
138        (self.0.hash_code)(node)
139    }
140
141    // The element `node` holds, made again.
142    pub(crate) fn element(self, node: &dyn ModifierNode) -> DynModifierElement {
143        (self.0.element)(node)
144    }
145}
146
147struct HeldFns {
148    element_type: fn() -> TypeId,
149    node_type: fn() -> TypeId,
150    hash_code: fn(&dyn ModifierNode) -> u64,
151    element: fn(&dyn ModifierNode) -> DynModifierElement,
152}
153
154struct HeldBy<E>(PhantomData<fn() -> E>);
155
156impl<E: ModifierNodeElement> HeldBy<E> {
157    const FNS: HeldFns = HeldFns {
158        element_type: TypeId::of::<E>,
159        node_type: TypeId::of::<E::Node>,
160        hash_code: Self::hash_code,
161        element: Self::element,
162    };
163
164    // The element `node` holds. A chain keeps a `NodeHeld` only beside a
165    // node of the element's node type.
166    fn of(node: &dyn ModifierNode) -> E {
167        let from_node = E::FROM_NODE.expect("a node-held element makes itself from its node");
168        from_node(
169            node.as_any()
170                .downcast_ref::<E::Node>()
171                .expect("a node-held element's node is of its node type"),
172        )
173    }
174
175    fn hash_code(node: &dyn ModifierNode) -> u64 {
176        let mut hasher = default::new();
177        Self::of(node).hash(&mut hasher);
178        hasher.finish()
179    }
180
181    fn element(node: &dyn ModifierNode) -> DynModifierElement {
182        modifier_element(Self::of(node))
183    }
184}
185
186struct TypedModifierElement<E: ModifierNodeElement> {
187    element: E,
188    // The element's hash, worked out the first time a chain rebuilding
189    // asks for it: most elements are built for a recomposition and only
190    // compared with the last ones.
191    hash: Cell<Option<PackedU64>>,
192    provides_locals: bool,
193}
194
195impl<E: ModifierNodeElement> TypedModifierElement<E> {
196    fn new(element: E) -> Self {
197        let provides_locals = !element.provided_composition_locals().is_empty();
198        Self {
199            element,
200            hash: Cell::new(None),
201            provides_locals,
202        }
203    }
204}
205
206impl<E> fmt::Debug for TypedModifierElement<E>
207where
208    E: ModifierNodeElement,
209{
210    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
211        f.debug_struct("TypedModifierElement")
212            .field("type", &type_name::<E>())
213            .finish()
214    }
215}
216
217impl<E> NodeMaker for TypedModifierElement<E>
218where
219    E: ModifierNodeElement,
220{
221    fn node_type(&self) -> TypeId {
222        TypeId::of::<E::Node>()
223    }
224
225    fn create_node(&self) -> Rc<RefCell<dyn ModifierNode>> {
226        Rc::new(RefCell::new(self.element.create()))
227    }
228
229    fn can_update_node(&self, node: &dyn ModifierNode) -> bool {
230        node.as_any().is::<E::Node>()
231    }
232
233    fn update_node(&self, node: &mut dyn ModifierNode) {
234        if let Some(typed) = node.as_any_mut().downcast_mut::<E::Node>() {
235            self.element.update(typed);
236        }
237    }
238
239    fn held_by_node(&self) -> Option<NodeHeld> {
240        E::FROM_NODE.map(|_| NodeHeld(&HeldBy::<E>::FNS))
241    }
242}
243
244impl<E> AnyModifierElement for TypedModifierElement<E>
245where
246    E: ModifierNodeElement,
247{
248    fn element_type(&self) -> TypeId {
249        TypeId::of::<E>()
250    }
251
252    fn maker(&self) -> ElementMaker<'_> {
253        ElementMaker::Node(self)
254    }
255
256    fn key(&self) -> Option<u64> {
257        self.element.key()
258    }
259
260    fn capabilities(&self) -> NodeCapabilities {
261        self.element.capabilities()
262    }
263
264    fn provides_composition_locals(&self) -> bool {
265        self.provides_locals
266    }
267
268    fn provided_composition_locals(&self) -> Vec<ProvidedValue> {
269        self.element.provided_composition_locals()
270    }
271
272    fn hash_code(&self) -> u64 {
273        if let Some(hash) = self.hash.get() {
274            return hash.get();
275        }
276        let mut hasher = default::new();
277        self.element.hash(&mut hasher);
278        let hash = hasher.finish();
279        self.hash.set(Some(PackedU64::new(hash)));
280        hash
281    }
282
283    fn equals_element(&self, other: &dyn AnyModifierElement) -> bool {
284        other
285            .as_any()
286            .downcast_ref::<Self>()
287            .is_some_and(|typed| typed.element == self.element)
288    }
289
290    fn inspector_name(&self) -> &'static str {
291        self.element.inspector_name()
292    }
293
294    fn record_inspector_properties(&self, visitor: &mut dyn FnMut(&'static str, String)) {
295        self.element.inspector_properties(visitor);
296    }
297
298    fn requires_update(&self) -> bool {
299        self.element.always_update()
300    }
301
302    fn auto_invalidates_on_update(&self) -> bool {
303        self.element.auto_invalidate_on_update()
304    }
305
306    fn update_invalidation_kind(&self) -> Option<InvalidationKind> {
307        self.element.update_invalidation_kind()
308    }
309
310    fn as_any(&self) -> &dyn Any {
311        self
312    }
313
314    fn equals_node(&self, node: &dyn ModifierNode) -> bool {
315        node.as_any()
316            .downcast_ref::<E::Node>()
317            .is_some_and(|node| self.element.equals_node(node))
318    }
319}
320
321/// Convenience helper for callers to construct a type-erased modifier
322/// element without having to mention the internal wrapper type.
323pub fn modifier_element<E: ModifierNodeElement>(element: E) -> DynModifierElement {
324    let element = TypedModifierElement::new(element);
325    let provides_locals = element.provides_locals;
326    DynModifierElement(Repr::Shared {
327        element: Rc::new(element),
328        provides_locals,
329    })
330}
331
332/// A type-erased modifier element, as a modifier holds it: a plain
333/// element's value in place, or a shared element that makes a node. A plain
334/// element takes no allocation of its own.
335#[derive(Clone)]
336pub struct DynModifierElement(Repr);
337
338// What a `DynModifierElement` holds. A shared element keeps beside it
339// whether it has composition locals, in bytes the plain value's room leaves,
340// so a modifier of one element tells without a call.
341#[derive(Clone)]
342pub(crate) enum Repr {
343    Plain(PlainWords),
344    Shared {
345        element: Rc<dyn AnyModifierElement>,
346        provides_locals: bool,
347    },
348}
349
350impl DynModifierElement {
351    pub(crate) fn plain(words: PlainWords) -> Self {
352        Self(Repr::Plain(words))
353    }
354
355    pub(crate) fn of_shared(element: Rc<dyn AnyModifierElement>) -> Self {
356        let provides_locals = element.provides_composition_locals();
357        Self(Repr::Shared {
358            element,
359            provides_locals,
360        })
361    }
362
363    pub(crate) fn repr(&self) -> &Repr {
364        &self.0
365    }
366
367    // The shared element, or `None` for a plain one, which is a value.
368    pub(crate) fn shared(&self) -> Option<&Rc<dyn AnyModifierElement>> {
369        match &self.0 {
370            Repr::Plain(_) => None,
371            Repr::Shared { element, .. } => Some(element),
372        }
373    }
374
375    // The element as a shared one, which a plain value becomes by a copy in
376    // an allocation of its own.
377    pub(crate) fn to_shared(&self) -> Rc<dyn AnyModifierElement> {
378        match &self.0 {
379            Repr::Plain(words) => Rc::new(*words),
380            Repr::Shared { element, .. } => Rc::clone(element),
381        }
382    }
383
384    /// Whether this element has composition locals for its content. A plain
385    /// element has none, which this tells without a call.
386    #[inline]
387    pub fn provides_composition_locals(&self) -> bool {
388        match &self.0 {
389            Repr::Plain(_) => false,
390            Repr::Shared {
391                provides_locals, ..
392            } => *provides_locals,
393        }
394    }
395
396    /// Whether `other` is this element itself, not only an equal one: two
397    /// plain elements are values, which are never one element.
398    pub fn is(&self, other: &Self) -> bool {
399        match (&self.0, &other.0) {
400            (Repr::Shared { element: a, .. }, Repr::Shared { element: b, .. }) => Rc::ptr_eq(a, b),
401            _ => false,
402        }
403    }
404}
405
406impl std::ops::Deref for DynModifierElement {
407    type Target = dyn AnyModifierElement;
408
409    #[inline]
410    fn deref(&self) -> &Self::Target {
411        match &self.0 {
412            Repr::Plain(words) => words,
413            Repr::Shared { element, .. } => &**element,
414        }
415    }
416}
417
418impl fmt::Debug for DynModifierElement {
419    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
420        fmt::Debug::fmt(&**self, f)
421    }
422}