Skip to main content

cranpose_core/
emit.rs

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