1use std::collections::BTreeMap;
34use std::fmt;
35use std::sync::Arc;
36
37pub const INTERNAL_SENTINEL: char = '\u{1f}';
41
42pub fn sanitize_internal_encoding(text: &str) -> String {
46 text.replace(INTERNAL_SENTINEL, " ")
47}
48
49pub fn assert_no_internal_encodings(text: &str) {
54 if text.contains(INTERNAL_SENTINEL) {
55 panic!("internal encoding leaked into user-facing diagnostic: {text:?}");
56 }
57}
58
59#[derive(Debug, Clone, Default, PartialEq, Eq)]
62pub struct Span {
63 pub line: usize,
65 pub col_start: Option<usize>,
67 pub col_end: Option<usize>,
69 pub source_line: Option<String>,
71}
72
73impl Span {
74 pub fn line_only(line: usize) -> Self {
76 Self {
77 line,
78 col_start: None,
79 col_end: None,
80 source_line: None,
81 }
82 }
83
84 pub fn full(line: usize, col_start: usize, col_end: usize, source_line: String) -> Self {
86 Self {
87 line,
88 col_start: Some(col_start),
89 col_end: Some(col_end),
90 source_line: Some(source_line),
91 }
92 }
93
94 pub fn line_col(line: usize, col: usize) -> Self {
99 Self {
100 line,
101 col_start: Some(col),
102 col_end: None,
103 source_line: None,
104 }
105 }
106}
107
108pub type DiagnosticResult<T> = Result<T, Diagnostic>;
114
115pub fn flatten_chain(reason: &Diagnostic) -> String {
126 let mut parts = vec![reason.to_string()];
127 let mut current =
128 std::error::Error::source(reason).map(|node| node as &(dyn std::error::Error + 'static));
129 while let Some(node) = current {
130 parts.push(node.to_string());
131 current = node.source();
132 }
133 parts.join(": ")
134}
135
136#[derive(Debug, Clone)]
146pub struct Diagnostic(Box<DiagnosticInner>);
147
148#[derive(Debug, Clone)]
151struct DiagnosticInner {
152 key: &'static str,
153 message: String,
154 fields: BTreeMap<String, String>,
155 span: Option<Span>,
156 hint: Option<String>,
157 source: Option<Arc<dyn std::error::Error + Send + Sync>>,
158 contexts: Vec<String>,
165 snapshot: Option<String>,
170}
171
172impl Diagnostic {
173 pub fn new(key: &'static str, message: String, fields: BTreeMap<String, String>) -> Self {
178 let message = sanitize_internal_encoding(&message);
179 let fields = fields
180 .into_iter()
181 .map(|(k, v)| {
182 (
183 sanitize_internal_encoding(&k),
184 sanitize_internal_encoding(&v),
185 )
186 })
187 .collect();
188 Self(Box::new(DiagnosticInner {
189 key,
190 message,
191 fields,
192 span: None,
193 hint: None,
194 source: None,
195 contexts: Vec::new(),
196 snapshot: None,
197 }))
198 }
199
200 pub fn make_fields(pairs: &[(&str, &str)]) -> BTreeMap<String, String> {
204 let mut map = BTreeMap::new();
205 for (k, v) in pairs {
206 map.insert(sanitize_internal_encoding(k), sanitize_internal_encoding(v));
207 }
208 map
209 }
210
211 pub fn key(&self) -> &'static str {
215 self.0.key
216 }
217
218 pub fn message(&self) -> &str {
220 &self.0.message
221 }
222
223 pub fn fields(&self) -> &BTreeMap<String, String> {
225 &self.0.fields
226 }
227
228 pub fn span(&self) -> Option<&Span> {
230 self.0.span.as_ref()
231 }
232
233 pub fn hint(&self) -> Option<&str> {
235 self.0.hint.as_deref()
236 }
237
238 pub fn contexts(&self) -> &[String] {
242 &self.0.contexts
243 }
244
245 pub fn snapshot(&self) -> Option<&str> {
247 self.0.snapshot.as_deref()
248 }
249
250 pub fn shared_source(&self) -> Option<Arc<dyn std::error::Error + Send + Sync>> {
254 self.0.source.clone()
255 }
256
257 pub fn with_span(mut self, span: Span) -> Self {
259 self.0.span = Some(span);
260 self
261 }
262
263 pub fn with_hint(mut self, hint: String) -> Self {
265 self.0.hint = Some(sanitize_internal_encoding(&hint));
266 self
267 }
268
269 pub fn with_source(mut self, source: Arc<dyn std::error::Error + Send + Sync>) -> Self {
273 self.0.source = Some(source);
274 self
275 }
276
277 pub fn with_contexts(mut self, frames: Vec<String>) -> Self {
285 self.0.contexts.splice(
286 0..0,
287 frames.into_iter().map(|f| sanitize_internal_encoding(&f)),
288 );
289 self
290 }
291
292 pub fn with_snapshot(mut self, snapshot: &str) -> Self {
296 self.0.snapshot = Some(sanitize_internal_encoding(snapshot));
297 self
298 }
299}
300
301impl PartialEq for Diagnostic {
302 fn eq(&self, other: &Self) -> bool {
303 self.0.key == other.0.key
308 && self.0.message == other.0.message
309 && self.0.fields == other.0.fields
310 && self.0.span == other.0.span
311 && self.0.hint == other.0.hint
312 }
313}
314
315impl Eq for Diagnostic {}
316
317impl fmt::Display for Diagnostic {
318 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
319 if let Some(snapshot) = &self.0.snapshot {
320 let mut seq: Vec<String> = self.0.contexts.clone();
328 let mut own = self.0.message.clone();
329 if let Some(hint) = &self.0.hint {
330 own = format!("{own}\nhint: {hint}");
331 }
332 seq.push(own);
333 let mut current = self
334 .0
335 .source
336 .as_ref()
337 .map(|s| s.as_ref() as &(dyn std::error::Error + 'static));
338 while let Some(node) = current {
339 seq.push(node.to_string());
340 current = node.source();
341 }
342 if seq.len() <= 1 {
343 write!(f, "{}\n{snapshot}", seq[0])?;
344 } else if seq.len() == 2 {
345 write!(f, "{} ({})\n{snapshot}", seq[0], seq[1])?;
346 } else {
347 let causes = seq[2..].join("\n ");
348 write!(
349 f,
350 "{} ({})\ncauses:\n {causes}\n{snapshot}",
351 seq[0], seq[1]
352 )?;
353 }
354 return Ok(());
355 }
356 if self.0.contexts.is_empty() {
357 write!(f, "{}", self.0.message)?;
358 } else {
359 write!(f, "{}: {}", self.0.contexts.join(": "), self.0.message)?;
360 }
361 if let Some(hint) = &self.0.hint {
362 write!(f, "\nhint: {hint}")?;
363 }
364 if let Some(span) = &self.0.span
365 && span.line > 0
366 {
367 match (span.col_start, span.col_end) {
368 (Some(s), Some(e)) => {
369 write!(f, "\n --> line {}, col {s}-{e}", span.line)?;
370 if let Some(line_text) = &span.source_line {
371 write!(f, "\n {} | {line_text}", span.line)?;
372 let width = e.saturating_sub(s).saturating_add(1).max(1);
373 let pad = " ".repeat(s.saturating_sub(1));
374 let carets = "^".repeat(width.min(80));
375 let gutter = " ".repeat(span.line.to_string().len());
376 write!(f, "\n {gutter} | {pad}{carets}")?;
377 }
378 }
379 _ => {
380 write!(f, "\n --> line {}", span.line)?;
381 if let Some(line_text) = &span.source_line {
382 write!(f, "\n {} | {line_text}", span.line)?;
383 }
384 }
385 }
386 }
387 Ok(())
395 }
396}
397
398impl std::error::Error for Diagnostic {
399 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
400 self.0
401 .source
402 .as_ref()
403 .map(|s| s.as_ref() as &(dyn std::error::Error + 'static))
404 }
405}
406
407#[cfg(test)]
408mod tests {
409 use super::*;
410 use std::io;
411
412 #[test]
413 fn transport_sanitizes_sentinel_instead_of_panicking() {
414 let evil = format!("bad{}text", INTERNAL_SENTINEL);
415 let d = Diagnostic::new(
416 "test.sanitize",
417 evil.clone(),
418 Diagnostic::make_fields(&[("k", &evil)]),
419 );
420 assert!(!d.message().contains(INTERNAL_SENTINEL));
421 assert!(d.message().contains(' '));
422 assert_no_internal_encodings(d.message());
423 }
424
425 #[test]
426 fn source_chain_is_preserved() {
427 let io_err = Arc::new(io::Error::new(io::ErrorKind::NotFound, "missing file"));
428 let d = Diagnostic::new(
429 "test.io",
430 "failed to read script".to_string(),
431 Diagnostic::make_fields(&[("path", "x.ox")]),
432 )
433 .with_source(io_err);
434 let src = std::error::Error::source(&d).expect("source preserved");
435 assert!(src.to_string().contains("missing file"));
436 }
437
438 #[test]
439 fn caret_gutter_aligns_for_any_line_width() {
440 for line in [1usize, 9, 10, 99, 100, 1234] {
441 let d = Diagnostic::new(
442 "test.span",
443 "boom".to_string(),
444 Diagnostic::make_fields(&[]),
445 )
446 .with_span(Span::full(line, 2, 3, "hi".to_string()));
447 let rendered = d.to_string();
448 let width = line.to_string().len();
449 let gutter = format!(" {} |", " ".repeat(width));
450 assert!(rendered.contains(&gutter), "line {line}: {rendered}");
451 }
452 }
453
454 #[test]
455 fn diagnostic_stays_pointer_sized() {
456 assert_eq!(
457 std::mem::size_of::<Diagnostic>(),
458 std::mem::size_of::<usize>(),
459 "Diagnostic must stay one pointer wide so DiagnosticResult keeps the anyhow footprint"
460 );
461 }
462
463 #[test]
464 fn equality_ignores_source_chain() {
465 let a = Diagnostic::new("k", "m".to_string(), Diagnostic::make_fields(&[]));
466 let b = a.clone().with_source(Arc::new(io::Error::other("chain")));
467 assert_eq!(a, b);
468 }
469
470 #[test]
471 fn contexts_prefix_display_without_touching_message() {
472 let d = Diagnostic::new("k", "boom".to_string(), Diagnostic::make_fields(&[]))
473 .with_contexts(vec!["step 1".to_string(), "step 2".to_string()]);
474 assert_eq!(d.message(), "boom");
475 assert_eq!(d.contexts(), &["step 1".to_string(), "step 2".to_string()]);
476 assert_eq!(d.to_string(), "step 1: step 2: boom");
477 let bare = Diagnostic::new("k", "boom".to_string(), Diagnostic::make_fields(&[]));
478 assert_eq!(bare.to_string(), "boom");
479 assert_eq!(d, bare, "frames are provenance, excluded like sources");
480 let evil = Diagnostic::new("k", "m".to_string(), Diagnostic::make_fields(&[]))
481 .with_contexts(vec![format!("bad{}frame", INTERNAL_SENTINEL)]);
482 assert!(!evil.contexts()[0].contains(INTERNAL_SENTINEL));
483 }
484
485 #[test]
486 fn later_outer_frames_prepend_ahead_of_inner_ones() {
487 let d = Diagnostic::new("k", "boom".to_string(), Diagnostic::make_fields(&[]))
490 .with_contexts(vec!["step 2".to_string()])
491 .with_contexts(vec!["step 1".to_string()]);
492 assert_eq!(d.contexts(), &["step 1".to_string(), "step 2".to_string()]);
493 assert_eq!(d.to_string(), "step 1: step 2: boom");
494 }
495
496 #[test]
497 fn snapshot_renders_failure_then_section_without_flattening_key() {
498 let snapshot = "filesystem snapshot: pending";
499 let d = Diagnostic::new("k", "boom".to_string(), Diagnostic::make_fields(&[]))
500 .with_contexts(vec!["step 1".to_string()])
501 .with_snapshot(snapshot);
502 assert_eq!(d.message(), "boom");
503 assert_eq!(d.snapshot(), Some(snapshot));
504 assert_eq!(d.to_string(), format!("step 1 (boom)\n{snapshot}"));
505 let bare = Diagnostic::new("k", "boom".to_string(), Diagnostic::make_fields(&[]));
506 assert_eq!(bare.to_string(), "boom");
507 assert_eq!(
508 d, bare,
509 "snapshot section is provenance, excluded like sources"
510 );
511 }
512
513 #[test]
514 fn snapshot_renders_three_node_chain_with_causes_block() {
515 let snapshot = "filesystem snapshot: pending";
516 let d = Diagnostic::new("k", "boom".to_string(), Diagnostic::make_fields(&[]))
517 .with_contexts(vec!["step 1".to_string()])
518 .with_source(Arc::new(io::Error::other("root cause")))
519 .with_snapshot(snapshot);
520 assert_eq!(d.message(), "boom");
521 assert_eq!(d.snapshot(), Some(snapshot));
522 assert_eq!(
523 d.to_string(),
524 format!("step 1 (boom)\ncauses:\n root cause\n{snapshot}")
525 );
526 }
527
528 #[test]
529 fn result_alias_carries_ok_and_err() {
530 let ok: DiagnosticResult<u32> = Ok(7);
531 let got = match ok {
532 Ok(got) => got,
533 Err(_) => panic!("expected ok"),
534 };
535 assert_eq!(got, 7);
536 let diag = Diagnostic::new(
537 "test.alias",
538 "boom".to_string(),
539 Diagnostic::make_fields(&[]),
540 );
541 let err: DiagnosticResult<u32> = Err(diag.clone());
542 let got = match err {
543 Ok(_) => panic!("expected err"),
544 Err(got) => got,
545 };
546 assert_eq!(got, diag);
547 }
548
549 #[test]
550 fn anyhow_blanket_from_preserves_message_and_chain() {
551 let io_err = Arc::new(io::Error::other("missing file"));
552 let diag = Diagnostic::new(
553 "test.interop",
554 "failed to read script".to_string(),
555 Diagnostic::make_fields(&[("path", "x.ox")]),
556 )
557 .with_source(io_err);
558 let anyhow_err: anyhow::Error = diag.into();
559 assert!(anyhow_err.to_string().contains("failed to read script"));
560 assert!(format!("{anyhow_err:#}").contains("missing file"));
561 }
562
563 #[test]
564 fn question_mark_converts_into_anyhow_result() {
565 fn fallible() -> DiagnosticResult<u32> {
566 Err(Diagnostic::new(
567 "test.qmark",
568 "boom".to_string(),
569 Diagnostic::make_fields(&[]),
570 ))
571 }
572 fn caller() -> anyhow::Result<u32> {
573 Ok(fallible()? + 1)
574 }
575 let err = caller().expect_err("must propagate");
576 assert!(err.to_string().contains("boom"));
577 }
578}