1use crate::evaluation_diagnostics::{EventStage, Span};
20use crate::phase_events::{EventScope, Outcome as EventOutcome, RootIdentity, RootKind};
21use serde::Serialize;
22use std::cell::{Cell, RefCell};
23
24pub const ROOT_NAME_LIMIT: usize = 256;
26
27#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
29#[serde(rename_all = "snake_case")]
30pub enum SourceKind {
31 Expr,
33 Doc,
35}
36
37#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
39#[serde(rename_all = "snake_case")]
40pub enum Outcome {
41 Bound,
43 Defer,
45 EvalError,
47 Taint,
49 Skipped,
51 Unwound,
53 Incomplete,
55}
56
57#[derive(Clone, Copy, Debug, PartialEq, Eq, Serialize)]
62#[serde(rename_all = "snake_case")]
63pub enum Completion {
64 Published,
66 DeferredQueued,
68 DeferIgnored,
70 EvalError,
72 Taint,
74 Skipped,
76}
77
78#[derive(Serialize)]
80pub struct RootRecord {
81 pub root_name: String,
83 pub root_name_original_bytes: usize,
85 pub root_name_truncated: bool,
87 pub initial_phase: u8,
89 pub source_kind: SourceKind,
91 pub producer_calls: usize,
93 pub source_successes: usize,
95 pub binding_returns: usize,
97 pub dispatch_outcome: Option<Outcome>,
99 pub completion: Option<Completion>,
101 pub outcome: Outcome,
103 pub interrupted_stage: Option<&'static str>,
105 pub span: Span,
107}
108
109struct State {
110 record: RootRecord,
111 active: &'static str,
112 events: EventScope,
113}
114
115thread_local! {
116 static ROOTS: RefCell<Vec<RootRecord>> = const { RefCell::new(Vec::new()) };
117 static NEXT_ORDINAL: Cell<usize> = const { Cell::new(0) };
118}
119
120pub struct RootAttempt {
125 state: RefCell<Option<State>>,
126}
127
128impl RootAttempt {
129 pub fn new(name: &str, initial_phase: u8, source_kind: SourceKind) -> Self {
132 let mut end = name.len().min(ROOT_NAME_LIMIT);
133 while !name.is_char_boundary(end) {
134 end -= 1;
135 }
136 let root_name = name[..end].to_owned();
137 let ordinal = NEXT_ORDINAL
138 .try_with(|next| {
139 let ordinal = next.get();
140 next.set(ordinal.saturating_add(1));
141 ordinal
142 })
143 .unwrap_or(usize::MAX);
144 let identity = RootIdentity::new(
145 name,
146 match source_kind {
147 SourceKind::Expr => RootKind::Expression,
148 SourceKind::Doc => RootKind::Document,
149 },
150 );
151 Self {
152 state: RefCell::new(Some(State {
153 record: RootRecord {
154 root_name,
155 root_name_original_bytes: name.len(),
156 root_name_truncated: end != name.len(),
157 initial_phase,
158 source_kind,
159 producer_calls: 0,
160 source_successes: 0,
161 binding_returns: 0,
162 dispatch_outcome: None,
163 completion: None,
164 outcome: Outcome::Incomplete,
165 interrupted_stage: None,
166 span: Span::new("root_bind", ordinal),
167 },
168 active: "dispatch",
169 events: EventScope::begin(
170 EventStage::RootDispatch as u32,
171 ordinal as u64,
172 identity,
173 ),
174 })),
175 }
176 }
177
178 pub fn source_started(&self) {
180 let mut state = self.state.borrow_mut();
181 let state = state.as_mut().unwrap();
182 state.record.span.mark(state.active);
183 state.record.producer_calls += 1;
184 state.active = "source_eval";
185 state.events.transition(EventStage::RootSourceEval as u32);
186 }
187
188 pub fn source_evaluated(&self) {
190 let mut state = self.state.borrow_mut();
191 let state = state.as_mut().unwrap();
192 state.record.span.mark(state.active);
193 state.record.source_successes += 1;
194 state.active = "recursive_bind";
195 state.events.transition(EventStage::RootTypeBind as u32);
196 }
197
198 pub fn binding_returned(&self) {
200 let mut state = self.state.borrow_mut();
201 let state = state.as_mut().unwrap();
202 state.record.span.mark(state.active);
203 state.record.binding_returns += 1;
204 state.active = "dispatch_return";
205 state
206 .events
207 .transition(EventStage::RootDispatchReturn as u32);
208 }
209
210 pub fn dispatch_returned(&self, outcome: Outcome) {
213 let mut state = self.state.borrow_mut();
214 let state = state.as_mut().unwrap();
215 state.record.span.mark(state.active);
216 state.record.dispatch_outcome = Some(outcome);
217 state.active = "publish_or_handle";
218 state
219 .events
220 .transition(EventStage::RootPublishOrDefer as u32);
221 }
222
223 pub fn body_returned(&self, completion: Completion) {
225 let mut state = self.state.borrow_mut();
226 let state = state.as_mut().unwrap();
227 state.record.span.mark(state.active);
228 state.record.completion = Some(completion);
229 state.active = "scope_release";
230 state.events.transition(EventStage::RootScopeRelease as u32);
231 }
232
233 pub fn skipped(&self) {
235 let mut state = self.state.borrow_mut();
236 let state = state.as_mut().unwrap();
237 state.record.span.mark(state.active);
238 state.record.completion = Some(Completion::Skipped);
239 state.active = "scope_release";
240 state.events.transition(EventStage::RootScopeRelease as u32);
241 }
242}
243
244impl Drop for RootAttempt {
245 fn drop(&mut self) {
246 let Some(mut state) = self.state.get_mut().take() else {
247 return;
248 };
249 let unwound = std::thread::panicking();
250 state.record.span.mark(state.active);
251 state.record.outcome = if unwound {
252 Outcome::Unwound
253 } else if state.record.completion == Some(Completion::Skipped) {
254 Outcome::Skipped
255 } else if state.record.completion.is_some() {
256 state.record.dispatch_outcome.unwrap_or(Outcome::Incomplete)
257 } else {
258 Outcome::Incomplete
259 };
260 if unwound || state.record.completion.is_none() {
261 state.record.interrupted_stage = Some(state.active);
262 }
263 state.events.finish(match state.record.outcome {
264 Outcome::Bound | Outcome::Skipped => EventOutcome::Ok,
265 Outcome::Defer => EventOutcome::Defer,
266 Outcome::EvalError => EventOutcome::Eval,
267 Outcome::Taint => EventOutcome::Taint,
268 Outcome::Unwound => EventOutcome::Unwound,
269 Outcome::Incomplete => EventOutcome::Incomplete,
270 });
271 let _ = ROOTS.try_with(|roots| roots.borrow_mut().push(state.record));
274 }
275}
276
277pub fn take_root_binding_diagnostics() -> Vec<RootRecord> {
280 ROOTS.with(|roots| std::mem::take(&mut *roots.borrow_mut()))
281}
282
283#[cfg(test)]
284#[path = "../tests/private/root_binding_diagnostics_test.rs"]
285mod tests;