Skip to main content

cranpose_core/
source_trace.rs

1//! Optional composition origins for development tools.
2
3/// A composable definition active when a layout node was emitted.
4#[derive(Clone, Debug, PartialEq, Eq)]
5pub struct SourceLocation {
6    /// Composable function name.
7    pub name: &'static str,
8    /// Source file reported by the compiler.
9    pub file: &'static str,
10    /// One-based declaration line.
11    pub line: u32,
12    /// Package directory reported by the compiler.
13    pub manifest_dir: &'static str,
14    #[cfg(all(feature = "inspection", debug_assertions))]
15    recompositions: Option<RecompositionCounter>,
16}
17
18impl SourceLocation {
19    /// Body executions after the initial composition for this composable instance.
20    /// Returns `None` unless a debug preview enabled recomposition tracking.
21    /// A `#[composable(no_skip)]` function runs in its caller's scope, as
22    /// Compose's inline composables do, so it has no count either.
23    pub fn recompositions(&self) -> Option<u64> {
24        #[cfg(all(feature = "inspection", debug_assertions))]
25        return self
26            .recompositions
27            .as_ref()
28            .map(|counter| counter.0.executions.get().saturating_sub(1));
29        #[cfg(not(all(feature = "inspection", debug_assertions)))]
30        None
31    }
32}
33
34#[cfg(all(feature = "inspection", debug_assertions))]
35#[derive(Clone, Debug)]
36pub(crate) struct RecompositionCounter(std::rc::Rc<Counter>);
37
38#[cfg(all(feature = "inspection", debug_assertions))]
39#[derive(Debug)]
40struct Counter {
41    executions: std::cell::Cell<u64>,
42    instance_id: u64,
43    name: &'static str,
44    file: &'static str,
45    line: u32,
46    manifest_dir: &'static str,
47}
48
49/// A live composable instance, including functions which emit no layout nodes.
50#[derive(Debug, PartialEq, Eq)]
51pub struct RecompositionInfo {
52    /// Identity of this instance for the lifetime of the preview composition thread.
53    pub instance_id: u64,
54    /// Composable function name.
55    pub name: &'static str,
56    /// Compiler-reported source file.
57    pub file: &'static str,
58    /// One-based declaration line.
59    pub line: u32,
60    /// Compiler-reported package directory.
61    pub manifest_dir: &'static str,
62    /// Body executions after the initial composition.
63    pub recompositions: u64,
64}
65
66/// Captures live instances without inspecting or traversing the layout tree.
67/// Returns an empty list unless tracking is enabled in a debug inspection build.
68pub fn recomposition_snapshot() -> Vec<RecompositionInfo> {
69    #[cfg(all(feature = "inspection", debug_assertions))]
70    {
71        if !crate::thread_state::cells(|cells| cells.track_recompositions.get()) {
72            return Vec::new();
73        }
74        crate::thread_state::runtimes(|state| {
75            let mut registry = state.recomposition_counters.borrow_mut();
76            let mut result = Vec::with_capacity(registry.len());
77            registry.retain(|weak| {
78                let Some(scope) = crate::RecomposeScope::upgrade(weak) else {
79                    return false;
80                };
81                if scope.is_effectively_active()
82                    && let Some(counter) = scope.inner.recompositions.get()
83                {
84                    result.push(RecompositionInfo {
85                        instance_id: counter.0.instance_id,
86                        name: counter.0.name,
87                        file: counter.0.file,
88                        line: counter.0.line,
89                        manifest_dir: counter.0.manifest_dir,
90                        recompositions: counter.0.executions.get().saturating_sub(1),
91                    });
92                }
93                true
94            });
95            result
96        })
97    }
98    #[cfg(not(all(feature = "inspection", debug_assertions)))]
99    Vec::new()
100}
101
102#[cfg(all(feature = "inspection", debug_assertions))]
103impl PartialEq for RecompositionCounter {
104    fn eq(&self, other: &Self) -> bool {
105        std::rc::Rc::ptr_eq(&self.0, &other.0)
106    }
107}
108
109#[cfg(all(feature = "inspection", debug_assertions))]
110impl Eq for RecompositionCounter {}
111
112/// Enables counters for composable instances on this preview's composition thread.
113/// Tracking defaults to disabled and is compiled out of release builds and builds
114/// without `inspection`. Skipped bodies and source call-site markers are not counted.
115pub fn set_recomposition_tracking(enabled: bool) {
116    #[cfg(all(feature = "inspection", debug_assertions))]
117    crate::thread_state::cells(|cells| cells.track_recompositions.set(enabled));
118    #[cfg(not(all(feature = "inspection", debug_assertions)))]
119    let _ = enabled;
120}
121
122#[cfg(all(feature = "inspection", debug_assertions))]
123fn record_composition(
124    name: &'static str,
125    file: &'static str,
126    line: u32,
127    manifest_dir: &'static str,
128) -> Option<RecompositionCounter> {
129    if !crate::thread_state::cells(|cells| cells.track_recompositions.get())
130        || name.starts_with("__cranpose_call:")
131    {
132        return None;
133    }
134    crate::with_current_composer_opt(|composer| {
135        // A body counts its runs on its scope, which it makes when its group
136        // has none yet.
137        let scope = composer.current_recompose_scope()?;
138        let counter = scope.inner.recompositions.get_or_init(|| {
139            crate::thread_state::runtimes(|state| {
140                state
141                    .recomposition_counters
142                    .borrow_mut()
143                    .push(scope.downgrade());
144            });
145            let instance_id = crate::thread_state::cells(|cells| {
146                let next = &cells.next_recomposition_instance;
147                let id = next.get().saturating_add(1);
148                next.set(id);
149                id
150            });
151            RecompositionCounter(std::rc::Rc::new(Counter {
152                executions: std::cell::Cell::new(0),
153                instance_id,
154                name,
155                file,
156                line,
157                manifest_dir,
158            }))
159        });
160        counter
161            .0
162            .executions
163            .set(counter.0.executions.get().saturating_add(1));
164        Some(counter.clone())
165    })
166    .flatten()
167}
168
169/// Restores the composition origin stack when the function returns or unwinds.
170#[doc(hidden)]
171pub struct SourceScope {
172    #[cfg(feature = "inspection")]
173    depth: usize,
174    marker: std::marker::PhantomData<std::rc::Rc<()>>,
175}
176
177impl Drop for SourceScope {
178    fn drop(&mut self) {
179        #[cfg(feature = "inspection")]
180        crate::thread_state::runtimes(|state| state.source_stack.borrow_mut().truncate(self.depth));
181    }
182}
183
184/// Used by the composable macro for a composable with a scope of its own;
185/// compiles to an empty guard without inspection.
186#[doc(hidden)]
187#[inline]
188pub fn __source_scope(
189    name: &'static str,
190    file: &'static str,
191    line: u32,
192    manifest_dir: &'static str,
193) -> SourceScope {
194    enter_source(name, file, line, manifest_dir, Composes::InOwnScope)
195}
196
197/// Used by the composable macro for a composable that composes in its
198/// caller's scope; compiles to an empty guard without inspection.
199#[doc(hidden)]
200#[inline]
201pub fn __inline_source_scope(
202    name: &'static str,
203    file: &'static str,
204    line: u32,
205    manifest_dir: &'static str,
206) -> SourceScope {
207    enter_source(name, file, line, manifest_dir, Composes::InCallerScope)
208}
209
210// A body in its caller's scope runs with the caller's, as Compose's inline
211// composables do, so it counts nothing.
212#[derive(Clone, Copy)]
213enum Composes {
214    InOwnScope,
215    InCallerScope,
216}
217
218#[inline]
219fn enter_source(
220    name: &'static str,
221    file: &'static str,
222    line: u32,
223    manifest_dir: &'static str,
224    #[cfg_attr(
225        not(all(feature = "inspection", debug_assertions)),
226        expect(unused_variables, reason = "only debug inspection builds count bodies")
227    )]
228    composes: Composes,
229) -> SourceScope {
230    // The count comes first: a scope it makes reads the stack for its trace.
231    #[cfg(all(feature = "inspection", debug_assertions))]
232    let recompositions = match composes {
233        Composes::InOwnScope => record_composition(name, file, line, manifest_dir),
234        Composes::InCallerScope => None,
235    };
236    #[cfg(feature = "inspection")]
237    let depth = crate::thread_state::runtimes(|state| {
238        let mut stack = state.source_stack.borrow_mut();
239        let depth = stack.len();
240        stack.push(SourceLocation {
241            name,
242            file,
243            line,
244            manifest_dir,
245            #[cfg(debug_assertions)]
246            recompositions,
247        });
248        depth
249    });
250    #[cfg(not(feature = "inspection"))]
251    let _ = (name, file, line, manifest_dir);
252    SourceScope {
253        #[cfg(feature = "inspection")]
254        depth,
255        marker: std::marker::PhantomData,
256    }
257}
258
259/// Captures the active composable definitions, outermost first.
260#[cfg(feature = "inspection")]
261pub fn current_source_trace() -> std::rc::Rc<[SourceLocation]> {
262    crate::thread_state::runtimes(|state| std::rc::Rc::from(state.source_stack.borrow().as_slice()))
263}
264
265#[cfg(feature = "inspection")]
266pub(crate) struct SourceContext(Vec<SourceLocation>);
267
268#[cfg(feature = "inspection")]
269impl Drop for SourceContext {
270    fn drop(&mut self) {
271        crate::thread_state::runtimes(|state| {
272            *state.source_stack.borrow_mut() = std::mem::take(&mut self.0);
273        });
274    }
275}
276
277#[cfg(feature = "inspection")]
278pub(crate) fn restore_source_trace(trace: &[SourceLocation]) -> SourceContext {
279    SourceContext(crate::thread_state::runtimes(|state| {
280        state.source_stack.replace(trace.to_vec())
281    }))
282}
283
284#[cfg(all(test, feature = "inspection"))]
285#[path = "tests/source_trace_tests.rs"]
286mod tests;