rustia/diagnostic_data.rs
1//! Owned diagnostic data; engine storage and budget leases stay private.
2
3use std::sync::Arc;
4
5/// Host-side reporting budgets, separate from script fuel and memory limits.
6///
7/// Start with [`default`](Self::default) and adjust the limits your application
8/// needs. Defaults are 4 MiB of retained-source accounting, 256 KiB per source,
9/// 32 captured frames, and 16 KiB per formatted report. These limits do not
10/// constrain script execution or change the error value received by `pcall`.
11/// A zero source budget omits nonempty source text while retaining available
12/// locations; zero frames disables frame storage, and zero report bytes produces
13/// an empty report for captured diagnostics. Errors without captured diagnostics
14/// use the formatter's fallback budget instead.
15#[derive(Clone, Copy, Debug, Eq, PartialEq)]
16#[non_exhaustive]
17pub struct DiagnosticLimits {
18 /// Total budget for retained source snapshots, including accounting overhead,
19 /// shared by compiled scripts and outstanding errors. Measured in bytes.
20 pub retained_source_bytes: usize,
21 /// Maximum source length in bytes retained for one script.
22 /// A larger source is omitted rather than stored as a partial snapshot.
23 pub source_bytes: usize,
24 /// Maximum number of captured script frames.
25 pub frames: usize,
26 /// Maximum bytes written by a formatted error report.
27 pub report_bytes: usize,
28}
29
30impl DiagnosticLimits {
31 /// Uses the default source, frame, and report budgets.
32 pub fn new() -> Self {
33 Self::default()
34 }
35
36 /// Returns the total retained-source budget.
37 pub const fn retained_source_bytes(&self) -> usize {
38 self.retained_source_bytes
39 }
40
41 /// Returns the largest source retained for one script.
42 pub const fn source_bytes(&self) -> usize {
43 self.source_bytes
44 }
45
46 /// Returns the maximum captured frame count.
47 pub const fn frames(&self) -> usize {
48 self.frames
49 }
50
51 /// Returns the maximum formatted report size.
52 pub const fn report_bytes(&self) -> usize {
53 self.report_bytes
54 }
55
56 /// Sets the total retained-source budget.
57 pub const fn with_retained_source_bytes(mut self, bytes: usize) -> Self {
58 self.retained_source_bytes = bytes;
59 self
60 }
61
62 /// Sets the maximum source size retained for one script.
63 pub const fn with_source_bytes(mut self, bytes: usize) -> Self {
64 self.source_bytes = bytes;
65 self
66 }
67
68 /// Sets the number of frames captured for one error.
69 pub const fn with_frames(mut self, frames: usize) -> Self {
70 self.frames = frames;
71 self
72 }
73
74 /// Sets the maximum formatted report size.
75 pub const fn with_report_bytes(mut self, bytes: usize) -> Self {
76 self.report_bytes = bytes;
77 self
78 }
79
80 pub(crate) const fn from_core(limits: rustia_vm::diagnostic::DiagnosticLimits) -> Self {
81 Self {
82 retained_source_bytes: limits.retained_source_bytes,
83 source_bytes: limits.source_bytes,
84 frames: limits.frames,
85 report_bytes: limits.report_bytes,
86 }
87 }
88
89 pub(crate) const fn to_core(self) -> rustia_vm::diagnostic::DiagnosticLimits {
90 rustia_vm::diagnostic::DiagnosticLimits {
91 retained_source_bytes: self.retained_source_bytes,
92 source_bytes: self.source_bytes,
93 frames: self.frames,
94 report_bytes: self.report_bytes,
95 }
96 }
97}
98
99impl Default for DiagnosticLimits {
100 fn default() -> Self {
101 Self::from_core(rustia_vm::diagnostic::DiagnosticLimits::default())
102 }
103}
104
105/// A retained copy of the exact source used for an error report.
106///
107/// Keeping a snapshot alive retains its reporting-budget charge. It does not
108/// retain script objects or keep the interpreter alive.
109#[derive(Debug)]
110pub struct SourceSnapshot {
111 core: Arc<rustia_vm::diagnostic::SourceSnapshot>,
112}
113
114impl SourceSnapshot {
115 /// Returns the original bytes; source is not required to be valid UTF-8.
116 pub fn bytes(&self) -> &[u8] {
117 self.core.bytes()
118 }
119
120 pub(crate) fn copy_with_limit(bytes: &[u8], limit: usize) -> Option<Arc<Self>> {
121 rustia_vm::diagnostic::SourceSnapshot::copy_with_limit(bytes, limit).map(Self::from_core)
122 }
123
124 fn from_core(core: Arc<rustia_vm::diagnostic::SourceSnapshot>) -> Arc<Self> {
125 Arc::new(Self { core })
126 }
127}
128
129/// A half-open byte range in the exact input source.
130#[derive(Clone, Copy, Debug, Eq, PartialEq)]
131pub struct DiagnosticSpan {
132 /// The zero-based offset of the first byte in the range.
133 pub start: usize,
134 /// The zero-based offset immediately after the range's final byte.
135 pub end: usize,
136}
137
138/// Facts captured by a failing script operation.
139#[derive(Clone, Debug)]
140#[non_exhaustive]
141pub enum DiagnosticReason {
142 /// A value could not be indexed.
143 Index {
144 /// The runtime type of the value being indexed.
145 object_type: &'static str,
146 /// The field name when captured; `None` means no field name is available.
147 key: Option<String>,
148 },
149 /// A value could not be called.
150 Call {
151 /// The runtime type of the value used as a function.
152 value_type: &'static str,
153 },
154 /// An arithmetic operation received incompatible values.
155 Arithmetic {
156 /// The arithmetic operation's name.
157 operation: &'static str,
158 /// The left operand's runtime type.
159 left_type: &'static str,
160 /// The right operand's runtime type.
161 right_type: &'static str,
162 },
163}
164
165/// A script call frame captured before execution state is discarded.
166#[derive(Clone, Debug, Eq, PartialEq)]
167#[non_exhaustive]
168pub struct DiagnosticFrame {
169 /// The source label recorded for this call site; not necessarily a filesystem path.
170 pub source: Arc<str>,
171 /// The one-based source line of the call site.
172 pub line: u32,
173 /// The function's debug name, when available. Long names may be truncated.
174 pub function: Option<String>,
175}
176
177/// Source details and call frames that remain available after reset or drop.
178///
179/// This data is separate from the script's error value and never changes what
180/// `pcall` receives. Source and frames may be absent when their budgets are zero.
181#[derive(Clone, Debug)]
182#[non_exhaustive]
183pub struct Diagnostic {
184 /// Whether runtime call-trace capture has been performed.
185 /// This can be true even when no frames were retained.
186 pub trace_captured: bool,
187 /// Structured facts from the failing operation, when they were captured.
188 pub reason: Option<DiagnosticReason>,
189 /// The field or array path associated with a data-conversion failure, when known.
190 pub data_path: Option<String>,
191 /// Whether the failure falls in generated wrapper text rather than mapped input.
192 pub generated_source: bool,
193 /// The original typed host error, when a host cause was preserved.
194 pub host_cause: Option<Arc<dyn std::error::Error + Send + Sync>>,
195 /// The source label, when known; it need not name a file on disk.
196 pub source: Option<Arc<str>>,
197 /// The one-based source line, when known.
198 pub line: Option<u32>,
199 /// The one-based opening line and expected closing keyword for an unclosed block.
200 pub unclosed_block: Option<(u32, &'static str)>,
201 /// The half-open source byte range, when known. A source map may adjust it
202 /// to refer to the retained input rather than generated wrapper text.
203 pub span: Option<DiagnosticSpan>,
204 /// Retained source text for this failure. It may be absent when the source
205 /// or total retention budget is exceeded, allocation fails, or source is unavailable.
206 pub snapshot: Option<Arc<SourceSnapshot>>,
207 /// The maximum UTF-8 byte length of [`crate::Error::report`] output.
208 /// This is a formatting budget, not the current report's length; zero emits nothing.
209 pub report_bytes: usize,
210 /// Captured caller frames, starting with the caller nearest the failure.
211 /// An empty list can mean no callers, disabled capture, or unavailable frame data.
212 pub frames: Vec<DiagnosticFrame>,
213 /// Whether additional call frames were omitted when capture reached its bound.
214 pub frames_truncated: bool,
215}
216
217impl Diagnostic {
218 pub(crate) fn from_core(diagnostic: &rustia_vm::diagnostic::Diagnostic) -> Self {
219 Self {
220 trace_captured: diagnostic.trace_captured,
221 reason: diagnostic.reason.as_ref().map(|reason| match reason {
222 rustia_vm::diagnostic::DiagnosticReason::Index { object_type, key } => {
223 DiagnosticReason::Index {
224 object_type,
225 key: key.clone(),
226 }
227 }
228 rustia_vm::diagnostic::DiagnosticReason::Call { value_type } => {
229 DiagnosticReason::Call { value_type }
230 }
231 rustia_vm::diagnostic::DiagnosticReason::Arithmetic {
232 operation,
233 left_type,
234 right_type,
235 } => DiagnosticReason::Arithmetic {
236 operation,
237 left_type,
238 right_type,
239 },
240 }),
241 data_path: diagnostic.data_path.clone(),
242 generated_source: diagnostic.generated_source,
243 host_cause: diagnostic.host_cause.clone(),
244 source: diagnostic.source.clone(),
245 line: diagnostic.line,
246 unclosed_block: diagnostic.unclosed_block,
247 span: diagnostic.span.map(|span| DiagnosticSpan {
248 start: span.start,
249 end: span.end,
250 }),
251 snapshot: diagnostic.snapshot.clone().map(SourceSnapshot::from_core),
252 report_bytes: diagnostic.report_bytes,
253 frames: diagnostic
254 .frames
255 .iter()
256 .map(|frame| DiagnosticFrame {
257 source: frame.source.clone(),
258 line: frame.line,
259 function: frame.function.clone(),
260 })
261 .collect(),
262 frames_truncated: diagnostic.frames_truncated,
263 }
264 }
265
266 pub(crate) fn to_core(&self) -> rustia_vm::diagnostic::Diagnostic {
267 rustia_vm::diagnostic::Diagnostic {
268 trace_captured: self.trace_captured,
269 reason: self.reason.as_ref().map(|reason| match reason {
270 DiagnosticReason::Index { object_type, key } => {
271 rustia_vm::diagnostic::DiagnosticReason::Index {
272 object_type,
273 key: key.clone(),
274 }
275 }
276 DiagnosticReason::Call { value_type } => {
277 rustia_vm::diagnostic::DiagnosticReason::Call { value_type }
278 }
279 DiagnosticReason::Arithmetic {
280 operation,
281 left_type,
282 right_type,
283 } => rustia_vm::diagnostic::DiagnosticReason::Arithmetic {
284 operation,
285 left_type,
286 right_type,
287 },
288 }),
289 data_path: self.data_path.clone(),
290 generated_source: self.generated_source,
291 host_cause: self.host_cause.clone(),
292 source: self.source.clone(),
293 line: self.line,
294 unclosed_block: self.unclosed_block,
295 span: self.span.map(|span| rustia_vm::diagnostic::DiagnosticSpan {
296 start: span.start,
297 end: span.end,
298 }),
299 snapshot: self.snapshot.as_ref().map(|snapshot| snapshot.core.clone()),
300 report_bytes: self.report_bytes,
301 frames: self
302 .frames
303 .iter()
304 .map(|frame| rustia_vm::diagnostic::DiagnosticFrame {
305 source: frame.source.clone(),
306 line: frame.line,
307 function: frame.function.clone(),
308 })
309 .collect(),
310 frames_truncated: self.frames_truncated,
311 }
312 }
313}
314
315impl Default for Diagnostic {
316 fn default() -> Self {
317 Self::from_core(&rustia_vm::diagnostic::Diagnostic::default())
318 }
319}