Skip to main content

cranpose_core/
emit.rs

1use std::any::TypeId;
2
3use smallvec::SmallVec;
4
5use crate::{
6    Applier, CHILD_LIST_INLINE, ChildList, Command, CommandQueue, Composer, DirtyBubble,
7    EmittedNode, MutableState, Node, NodeError, NodeId, OwnedMutableState, ParentAttachMode,
8    ParentFrame, RecyclableShell, debug_scope_label, join_made_children,
9    recompose::RecomposeChildCursor, slot::NodeSlotUpdate,
10};
11
12#[expect(clippy::multiple_inherent_impl, reason = "one file per concern")]
13impl Composer {
14    fn planned_node_parent(&self, id: NodeId) -> Option<NodeId> {
15        if let Some(parent) = self.current_parent_hint().filter(|parent| *parent != id) {
16            return Some(parent);
17        }
18        let mut applier = self.borrow_applier();
19        applier.get_mut(id).ok().and_then(|node| node.parent())
20    }
21
22    fn queue_replaced_slot_node_removal(&self, old_id: NodeId, old_generation: u32) {
23        let current_generation = self.borrow_applier().node_generation(old_id);
24        if current_generation != old_generation {
25            log::trace!(
26                target: "cranpose::compose::emit",
27                "skipping stale replacement cleanup for node #{old_id} (slot_generation={old_generation} current_generation={current_generation})",
28            );
29            return;
30        }
31
32        log::trace!(
33            target: "cranpose::compose::emit",
34            "removing replaced node #{old_id} (generation={old_generation})",
35        );
36        self.commands_mut().push(Command::RemoveNode { id: old_id });
37    }
38
39    /// Returns a [`MutableState`] holding the value `init` made on the first composition at this
40    /// call site. Later compositions return the same state, so its value survives recomposition.
41    #[track_caller]
42    pub fn use_state<T: Clone + 'static>(&self, init: impl FnOnce() -> T) -> MutableState<T> {
43        let source = crate::caller_location_key();
44        let runtime = self.runtime_handle();
45        let state = self.with_slot_session_mut(|slots| {
46            slots.remember(source, || {
47                OwnedMutableState::with_runtime(init(), runtime.clone())
48            })
49        });
50        state.with(OwnedMutableState::handle)
51    }
52
53    /// The current scope's id and debug label, for a trace line.
54    fn trace_scope(&self) -> (usize, Option<&'static str>) {
55        self.peek_recompose_scope().map_or((0, None), |scope| {
56            (scope.id(), debug_scope_label(scope.id()))
57        })
58    }
59
60    fn emit_node_box<N: Node + 'static>(
61        &self,
62        source: crate::Key,
63        make_node: impl FnOnce(&mut dyn Applier) -> EmittedNode,
64    ) -> NodeId {
65        let adopted = {
66            let mut skip = 0;
67            loop {
68                let Some(found) = self
69                    .with_slot_session_mut(|slots| slots.peek_node_record_by_source(source, skip))
70                else {
71                    break None;
72                };
73                let (type_ok, gen_ok) = {
74                    let mut applier = self.borrow_applier();
75                    let gen_ok = applier.node_generation(found.id) == found.generation;
76                    let type_ok = match applier.get_mut(found.id) {
77                        Ok(node) => node.as_any_mut().downcast_ref::<N>().is_some(),
78                        Err(_) => false,
79                    };
80                    (type_ok, gen_ok)
81                };
82                if type_ok && gen_ok {
83                    break Some(found);
84                }
85                skip += 1;
86            }
87        };
88
89        let Some(found) = adopted else {
90            return self.emit_new_node::<N>(source, make_node);
91        };
92        let id = found.id;
93        if log::log_enabled!(target: "cranpose::compose::emit", log::Level::Trace) {
94            self.trace_reused_node::<N>(id);
95        }
96        self.attach_to_parent(id);
97        let parent_id = self.planned_node_parent(id);
98        let recorded =
99            self.with_slot_session_mut(|slots| slots.adopt_node_record(found, parent_id, source));
100        match recorded {
101            NodeSlotUpdate::Reused {
102                id: recorded_id,
103                generation,
104            } => {
105                debug_assert_eq!(recorded_id, id);
106                debug_assert_eq!(generation, found.generation);
107            }
108            NodeSlotUpdate::Inserted { .. } => {
109                log::warn!(
110                    target: "cranpose::compose::emit",
111                    "slot writer inserted node #{id} while reusing the same node identity",
112                );
113            }
114            NodeSlotUpdate::Replaced {
115                old_id,
116                old_generation,
117                ..
118            } => {
119                log::warn!(
120                    target: "cranpose::compose::emit",
121                    "slot writer replaced node #{old_id} while reusing node #{id}",
122                );
123                self.queue_replaced_slot_node_removal(old_id, old_generation);
124            }
125        }
126        id
127    }
128
129    #[cold]
130    #[inline(never)]
131    fn trace_reused_node<N: Node + 'static>(&self, id: NodeId) {
132        let (scope_id, scope_label) = self.trace_scope();
133        log::trace!(
134            target: "cranpose::compose::emit",
135            "reusing node #{id} as {} [scope_id={scope_id} scope_label={scope_label:?}]",
136            std::any::type_name::<N>(),
137        );
138    }
139
140    // Makes the node `make_node` gives and records it at `source`. Out of
141    // line: a composition that reuses its nodes never runs it, and the emit
142    // of every node stays small.
143    #[inline(never)]
144    fn emit_new_node<N: Node + 'static>(
145        &self,
146        source: crate::Key,
147        make_node: impl FnOnce(&mut dyn Applier) -> EmittedNode,
148    ) -> NodeId {
149        let (id, generation) = {
150            let mut applier = self.borrow_applier();
151            let emitted = make_node(&mut *applier);
152            let id = match emitted {
153                EmittedNode::Fresh(node) => applier.create(node),
154                EmittedNode::Recycled(recycled) => {
155                    let (stable_id, node, origin) = recycled.into_parts();
156                    let insertion = applier.insert_recycled_node_or_create(stable_id, node);
157                    if let Some(error) = insertion.fallback_error.as_ref() {
158                        log::warn!(
159                            target: "cranpose::compose::emit",
160                            "discarding stale recycled stable id #{stable_id}: {error}",
161                        );
162                    }
163                    applier.set_recycled_node_origin(insertion.id, origin);
164                    insertion.id
165                }
166            };
167            let generation = applier.node_generation(id);
168            (id, generation)
169        };
170        if log::log_enabled!(target: "cranpose::compose::emit", log::Level::Trace) {
171            let (scope_id, scope_label) = self.trace_scope();
172            log::trace!(
173                target: "cranpose::compose::emit",
174                "creating node #{} (gen={}) as {} [scope_id={} scope_label={:?}]",
175                id,
176                generation,
177                std::any::type_name::<N>(),
178                scope_id,
179                scope_label,
180            );
181        }
182        self.mount_made_node(id);
183        let parent_id = self.planned_node_parent(id);
184        let recorded = self.with_slot_session_mut(|slots| {
185            slots.record_node_with_parent(id, generation, parent_id, source)
186        });
187        match recorded {
188            NodeSlotUpdate::Inserted {
189                id: recorded_id,
190                generation: recorded_generation,
191            } => {
192                debug_assert_eq!(recorded_id, id);
193                debug_assert_eq!(recorded_generation, generation);
194            }
195            NodeSlotUpdate::Replaced {
196                old_id,
197                old_generation,
198                new_id,
199                new_generation,
200            } => {
201                debug_assert_eq!(new_id, id);
202                debug_assert_eq!(new_generation, generation);
203                self.queue_replaced_slot_node_removal(old_id, old_generation);
204            }
205            NodeSlotUpdate::Reused { .. } => {
206                log::warn!(
207                    target: "cranpose::compose::emit",
208                    "slot writer reported reuse for newly emitted node #{id}",
209                );
210            }
211        }
212        id
213    }
214
215    // Mounts node `id`, which the pass just made, under the frame it is made
216    // in: a frame the pass made takes it as it is, and joins it when it
217    // closes; any other frame attaches it as it attaches a kept node.
218    fn mount_made_node(&self, id: NodeId) {
219        let made_parent = {
220            let mut parent_stack = self.parent_stack();
221            parent_stack
222                .last_mut()
223                .filter(|frame| frame.id != id)
224                .and_then(|frame| {
225                    frame.last_made = Some(id);
226                    (frame.attach_mode == ParentAttachMode::Made).then(|| {
227                        frame.new_children.push(id);
228                        frame.id
229                    })
230                })
231        };
232        if made_parent.is_none() {
233            self.attach_to_parent(id);
234        }
235        let mut applier = self.borrow_applier();
236        let Ok(node) = applier.get_mut(id) else {
237            return;
238        };
239        match made_parent {
240            Some(parent) => node.mount_under(parent, id),
241            None => {
242                node.set_node_id(id);
243                node.mount();
244            }
245        }
246    }
247
248    /// Emits a node of type `N` as a child of the current parent and returns its id. The first
249    /// composition at this call site calls `init` to make the node. Later compositions reuse that
250    /// node and do not call `init`.
251    #[track_caller]
252    pub fn emit_node<N: Node + 'static>(&self, init: impl FnOnce() -> N) -> NodeId {
253        let source = crate::caller_location_key();
254        self.emit_node_box::<N>(source, |_| EmittedNode::Fresh(Box::new(init())))
255    }
256
257    /// Emits a node of type `N` as `emit_node` does, reusing a pooled node when one exists. With
258    /// no pooled `N`, `init` makes a bare one in a new box. `reset` then makes the pooled or bare
259    /// node, which [`RecyclableShell`] names, this emit's node, where it lies.
260    #[track_caller]
261    pub fn emit_recyclable_node<N: Node + 'static>(
262        &self,
263        init: impl FnOnce() -> N,
264        reset: impl FnOnce(&mut N, RecyclableShell),
265    ) -> NodeId {
266        let source = crate::caller_location_key();
267        self.emit_node_box::<N>(source, |applier| {
268            let key = TypeId::of::<N>();
269            if let Some(mut recycled) = applier.take_recycled_node(key) {
270                if let Some(typed) = recycled.node_mut().as_any_mut().downcast_mut::<N>() {
271                    reset(typed, RecyclableShell::Pooled);
272                    return EmittedNode::Recycled(recycled);
273                }
274                log::warn!(
275                    target: "cranpose::compose::emit",
276                    "discarding recycled node shell with mismatched type for {}",
277                    std::any::type_name::<N>(),
278                );
279            }
280
281            // The box comes first, so `init` can make the node in it.
282            let mut node = Box::write(Box::new_uninit(), init());
283            applier.record_fresh_recyclable_creation(key);
284            applier.seed_recycled_node_shell(key, &*node);
285            reset(&mut node, RecyclableShell::Fresh);
286            EmittedNode::Fresh(node)
287        })
288    }
289
290    fn skip_recompose_child(&self) {
291        let cursor = match self.core.recompose_child_cursor.get() {
292            RecomposeChildCursor::After { first, placed } => RecomposeChildCursor::After {
293                first,
294                placed: placed + 1,
295            },
296            RecomposeChildCursor::At(index) => RecomposeChildCursor::At(index + 1),
297            RecomposeChildCursor::Unknown => return,
298        };
299        self.core.recompose_child_cursor.set(cursor);
300    }
301
302    fn next_recompose_insert_index(&self) -> Option<usize> {
303        let RecomposeChildCursor::At(index) = self.resolve_recompose_child_cursor() else {
304            return None;
305        };
306        self.core
307            .recompose_child_cursor
308            .set(RecomposeChildCursor::At(index + 1));
309        Some(index)
310    }
311
312    pub(crate) fn attach_to_parent(&self, id: NodeId) {
313        if self.attach_to_current_parent(id) {
314            return;
315        }
316        self.attach_without_parent_frame(id);
317    }
318
319    fn attach_to_current_parent(&self, id: NodeId) -> bool {
320        let mut parent_stack = self.parent_stack();
321        if let Some(parent_id) = parent_stack.last().map(|frame| frame.id) {
322            let stale_root_parent = self.core.root.get() == Some(parent_id) && {
323                let mut applier = self.borrow_applier();
324                applier.get_mut(parent_id).is_err()
325            };
326            if stale_root_parent {
327                parent_stack.pop();
328                self.set_root(None);
329            } else {
330                let Some(frame) = parent_stack.last_mut() else {
331                    return false;
332                };
333                if parent_id == id {
334                    return true;
335                }
336                // A node the pass did not make joins a frame the pass made:
337                // the frame syncs its children as a kept node's frame does.
338                if frame.attach_mode == ParentAttachMode::Made {
339                    frame.attach_mode = ParentAttachMode::DeferredSync;
340                }
341                let attach_mode = frame.attach_mode;
342                // A child where the parent held it before is already attached
343                // to the parent: its node needs no visit.
344                let attached_before = frame.previous.get(frame.new_children.len()) == Some(&id);
345                if matches!(attach_mode, ParentAttachMode::DeferredSync) {
346                    frame.new_children.push(id);
347                }
348                drop(parent_stack);
349
350                if attached_before {
351                    debug_assert!(
352                        self.borrow_applier()
353                            .get_mut(id)
354                            .map_or(true, |node| node.parent().is_none_or(|p| p == parent_id)),
355                        "a parent's previous child must name no other parent"
356                    );
357                } else {
358                    let mut applier = self.borrow_applier();
359                    if let Ok(child_node) = applier.get_mut(id) {
360                        child_node.set_parent_for_bubbling(parent_id);
361                    }
362                }
363                if matches!(attach_mode, ParentAttachMode::ImmediateAppend) {
364                    self.commands_mut().push(Command::AttachChild {
365                        parent_id,
366                        child_id: id,
367                        insert_index: None,
368                        bubble: DirtyBubble::LAYOUT_AND_MEASURE,
369                    });
370                }
371                return true;
372            }
373        }
374        false
375    }
376
377    fn attach_without_parent_frame(&self, id: NodeId) {
378        let in_subcompose = !self.subcompose_stack().is_empty();
379        if in_subcompose {
380            let has_parent = {
381                let mut applier = self.borrow_applier();
382                applier
383                    .get_mut(id)
384                    .is_ok_and(|node| node.parent().is_some())
385            };
386
387            if !has_parent {
388                let mut subcompose_stack = self.subcompose_stack();
389                if let Some(frame) = subcompose_stack.last_mut() {
390                    frame.nodes.push(id);
391                }
392            }
393            return;
394        }
395
396        if let Some(parent_hint) = self.core.recompose_parent_hint.get() {
397            if parent_hint == id {
398                debug_assert_ne!(
399                    parent_hint, id,
400                    "a node cannot be attached as its own parent"
401                );
402                return;
403            }
404            let parent_status = {
405                let mut applier = self.borrow_applier();
406                applier.get_mut(id).map_or(None, |node| node.parent())
407            };
408            match parent_status {
409                Some(existing) if existing == parent_hint => {
410                    self.skip_recompose_child();
411                }
412                None => {
413                    let insert_index = self.next_recompose_insert_index();
414                    self.commands_mut().push(Command::AttachChild {
415                        parent_id: parent_hint,
416                        child_id: id,
417                        insert_index,
418                        bubble: DirtyBubble::LAYOUT_AND_MEASURE,
419                    });
420                }
421                Some(_) => {}
422            }
423            return;
424        }
425
426        let has_parent = {
427            let mut applier = self.borrow_applier();
428            applier
429                .get_mut(id)
430                .is_ok_and(|node| node.parent().is_some())
431        };
432        if has_parent {
433            return;
434        }
435
436        self.set_root(Some(id));
437    }
438
439    /// Runs `f` on the node `id` as an `N`. Returns an error if the node does not exist or is not
440    /// an `N`.
441    pub fn with_node_mut<N: Node + 'static, R>(
442        &self,
443        id: NodeId,
444        f: impl FnOnce(&mut N) -> R,
445    ) -> Result<R, NodeError> {
446        let mut applier = self.borrow_applier();
447        let node = applier.get_mut(id)?;
448        let typed =
449            node.as_any_mut()
450                .downcast_mut::<N>()
451                .ok_or_else(|| NodeError::TypeMismatch {
452                    id,
453                    expected: std::any::type_name::<N>(),
454                })?;
455        Ok(f(typed))
456    }
457
458    /// Makes the node `id` the parent of the nodes emitted next. Each call needs a matching
459    /// `pop_parent`.
460    pub fn push_parent(&self, id: NodeId) {
461        let made = self
462            .parent_stack()
463            .last_mut()
464            .is_some_and(|frame| frame.last_made.take() == Some(id));
465        if made {
466            self.parent_stack().push(ParentFrame {
467                id,
468                previous: SmallVec::new(),
469                new_children: ChildList::new(),
470                attach_mode: ParentAttachMode::Made,
471                synthetic_root: false,
472                last_made: None,
473            });
474            return;
475        }
476        let in_subcompose = !self.core.subcompose_stack.borrow().is_empty();
477
478        let previous = self.get_node_children(id);
479        let attach_mode = if in_subcompose || !previous.is_empty() {
480            ParentAttachMode::DeferredSync
481        } else {
482            ParentAttachMode::ImmediateAppend
483        };
484        // A pass mostly composes as many children as the node held: a list
485        // past its inline room takes their room at once and does not grow
486        // child by child.
487        let new_children = if previous.len() > CHILD_LIST_INLINE {
488            ChildList::with_capacity(previous.len())
489        } else {
490            ChildList::new()
491        };
492
493        self.parent_stack().push(ParentFrame {
494            id,
495            previous,
496            new_children,
497            attach_mode,
498            synthetic_root: false,
499            last_made: None,
500        });
501    }
502
503    /// Composes nothing under node `id`, which holds children when
504    /// `holds_children`: the parent frame [`Composer::push_parent`] and
505    /// [`Composer::pop_parent`] would open and close around nothing is left
506    /// out where closing it would sync nothing, which is outside a
507    /// subcomposition for a node that holds no children.
508    pub fn compose_no_children(&self, id: NodeId, holds_children: bool) {
509        if holds_children || !self.core.subcompose_stack.borrow().is_empty() {
510            self.push_parent(id);
511            self.pop_parent();
512        }
513    }
514
515    /// Closes the parent opened by the matching `push_parent` and sets that node's children to the
516    /// nodes emitted since.
517    pub fn pop_parent(&self) {
518        let frame_opt = {
519            let mut stack = self.parent_stack();
520            stack.pop()
521        };
522        if let Some(frame) = frame_opt {
523            let ParentFrame {
524                id,
525                previous,
526                new_children,
527                attach_mode,
528                synthetic_root: _synthetic_root,
529                last_made: _,
530            } = frame;
531
532            log::trace!(target: "cranpose::compose::parent", "pop_parent: node #{id}");
533            log::trace!(
534                target: "cranpose::compose::parent",
535                "previous children: {previous:?}"
536            );
537            log::trace!(
538                target: "cranpose::compose::parent",
539                "new children: {new_children:?}"
540            );
541            match attach_mode {
542                ParentAttachMode::Made => {
543                    join_made_children(&mut *self.borrow_applier(), id, &new_children);
544                }
545                ParentAttachMode::DeferredSync => {
546                    // Children composed as the parent held them need no sync
547                    // of their list, only the parent's settling. An empty
548                    // list still syncs: it removes what the parent took
549                    // since, as a subcomposition's slot host may.
550                    let kept = !previous.is_empty() && new_children == previous;
551                    let expected_children = (!kept).then_some(new_children);
552                    self.commands_mut().push(Command::SyncChildren {
553                        parent_id: id,
554                        expected_children,
555                    });
556                }
557                ParentAttachMode::ImmediateAppend => {}
558            }
559        }
560    }
561
562    pub(crate) fn take_commands(&self) -> CommandQueue {
563        std::mem::take(&mut *self.commands_mut())
564    }
565
566    /// Lends the queued commands to `f` where they are, without moving the
567    /// queue.
568    pub(crate) fn with_commands<R>(&self, f: impl FnOnce(&mut CommandQueue) -> R) -> R {
569        f(&mut self.commands_mut())
570    }
571
572    /// Applies any pending applier commands and runtime updates.
573    ///
574    /// This is useful during measure-time subcomposition to ensure newly created
575    /// nodes are available for measurement before the full composition is committed.
576    pub fn apply_pending_commands(&self) -> Result<(), NodeError> {
577        self.resolve_recompose_child_cursor();
578        let mut commands = self.take_commands();
579        let runtime_handle = self.runtime_handle();
580        let result = {
581            let mut applier = self.borrow_applier();
582            let mut result = commands.apply(&mut *applier);
583            if result.is_ok() {
584                for update in runtime_handle.take_updates() {
585                    if let Err(err) = update.apply(&mut *applier) {
586                        result = Err(err);
587                        break;
588                    }
589                }
590            }
591            result
592        };
593        // The pass goes on queueing: hand it back the storage just applied.
594        let mut queued = self.commands_mut();
595        if queued.len() == 0 {
596            std::mem::swap(&mut *queued, &mut commands);
597        }
598        drop(queued);
599        if result.is_err() {
600            let host = self.active_slots_host();
601            if !host.has_active_pass() {
602                host.abandon_after_apply_failure();
603            }
604        }
605        result
606    }
607
608    /// Queues `effect` to run after this pass has applied its node changes.
609    pub fn register_side_effect(&self, effect: impl FnOnce() + 'static) {
610        self.queue_side_effect(Box::new(effect));
611    }
612
613    /// Removes and returns the side effects queued during this pass.
614    pub fn take_side_effects(&self) -> Vec<Box<dyn FnOnce()>> {
615        std::mem::take(&mut *self.side_effects_mut())
616    }
617
618    pub(crate) fn root(&self) -> Option<NodeId> {
619        self.core.root.get()
620    }
621
622    pub(crate) fn set_root(&self, node: Option<NodeId>) {
623        self.core.root.set(node);
624    }
625}