Skip to main content

oxdock_diagnostics/
lib.rs

1//! Generic keyed diagnostics for OxDock.
2//!
3//! This crate owns only the transport: a stable dotted `key`, a rendered
4//! message, structured fields, an optional span and hint, and an optional
5//! chained source. It owns no domain templates.
6//!
7//! Domain constructors live with their owners:
8//!
9//! - DSL spelling diagnostics live in `oxdock-parser`
10//!   (`dsl.spelling.*`, `dsl.alias.*` arity).
11//! - DSL typing diagnostics live in `oxdock-core`
12//!   (`dsl.map.*`, `dsl.alias.*` uniqueness).
13//! - CLI diagnostics live in `oxdock-cli/src/errors.rs` (`cli.*`).
14//!
15//! Rules:
16//!
17//! - Call sites pass structured fields, never `format!` strings. Each
18//!   template lives once inside its owning constructor.
19//! - Constructors take decoded fields, never raw mid-parse text. The
20//!   transport sanitizes the internal boundary marker (`\u{1f}`) to a
21//!   space so untrusted input can never crash a release build through
22//!   this path. Tests assert the absence of the marker via
23//!   [`assert_no_internal_encodings`].
24//! - The crate stays dependency-light (std plus `Arc`, never workspace
25//!   crates) so parser, core, and CLI can all depend on it without a
26//!   cycle. Conversion into `anyhow::Error` needs no local impl:
27//!   `anyhow`'s blanket `From<E: StdError + Send + Sync + 'static>`
28//!   already covers [`Diagnostic`], so `?` and `.into()` carry keyed
29//!   diagnostics into not-yet-migrated `anyhow::Result` signatures
30//!   with the message and chain intact. New fallible signatures
31//!   should return [`DiagnosticResult`] instead.
32
33use std::collections::BTreeMap;
34use std::fmt;
35use std::sync::Arc;
36
37/// Internal boundary marker that must never leak into user output.
38/// Mirrors `WS_SENTINEL` in `oxdock-parser/src/tag.rs`: transient
39/// mid-parse only, decoded or sanitized before display.
40pub const INTERNAL_SENTINEL: char = '\u{1f}';
41
42/// Replace the internal boundary marker with a space. The transport
43/// applies this to every message, field, and hint so untrusted input
44/// containing `\u{1f}` renders safely instead of crashing release.
45pub fn sanitize_internal_encoding(text: &str) -> String {
46    text.replace(INTERNAL_SENTINEL, " ")
47}
48
49/// Test helper asserting user-facing text carries no internal
50/// encoding. Panics when the marker is present. Production code never
51/// calls this on untrusted input; the transport sanitizes instead.
52/// Downstream test suites may call this directly.
53pub 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/// Optional source span for a diagnostic. CLI diagnostics leave this
60/// empty; parser diagnostics fill line plus column range and source text.
61#[derive(Debug, Clone, Default, PartialEq, Eq)]
62pub struct Span {
63    /// 1-based line number. Zero means unknown.
64    pub line: usize,
65    /// 1-based start column, when known.
66    pub col_start: Option<usize>,
67    /// 1-based end column inclusive, when known.
68    pub col_end: Option<usize>,
69    /// Raw source line text, when available.
70    pub source_line: Option<String>,
71}
72
73impl Span {
74    /// Bare line, used when no column information exists.
75    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    /// Full span with columns and source text.
85    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    /// Start position without end column or source text (e.g. token
95    /// head coordinates). Downstream crates construct spans only
96    /// through these constructors, never struct literals, so future
97    /// fields (file ids, byte offsets) stay additive.
98    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
108/// Fallible result with a keyed diagnostic. New fallible signatures
109/// return this instead of `anyhow::Result`: callers add context with
110/// [`Diagnostic::with_hint`] / [`Diagnostic::with_source`] and convert
111/// into `anyhow::Error` with `?` or `.into()` (via `anyhow`'s blanket
112/// `From`) while the rest of the workspace migrates leaf to root.
113pub type DiagnosticResult<T> = Result<T, Diagnostic>;
114
115/// `{anyhow:#}`-equivalent flattening: joins one-layer node texts
116/// with `": "`, exactly what the alternate renderer prints for the
117/// same chain, so boundary messages that inline the cause keep the
118/// pre-flip byte-identical wording after an `&anyhow::Error` to
119/// `&Diagnostic` flip. Wrappers that inline stay sourceless (the
120/// chain text is the message); wrappers that chain stay bare (the
121/// join renders the depth). Mixing both prints every cause twice.
122/// Single owner for the whole workspace: leaf crates (`utils`,
123/// `pty`, `process`, plugins) and `exec`/`build` all reuse this,
124/// never restate the walk.
125pub 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/// One user-facing error: stable key, rendered message, structured
137/// fields, optional span, hint, and chained source. Construct through
138/// [`Diagnostic::new`] from the owning domain module, one constructor
139/// per diagnostic at its owner.
140///
141/// Pointer-sized by design: the payload lives behind one `Box` so
142/// [`DiagnosticResult`] returns stay at the `anyhow::Error` footprint
143/// on the happy path (the error value is constructed only on the cold
144/// path). A test pins `size_of::<Diagnostic>()` below.
145#[derive(Debug, Clone)]
146pub struct Diagnostic(Box<DiagnosticInner>);
147
148/// Boxed payload behind [`Diagnostic`]. Private so the footprint
149/// guarantee and the constructor-per-diagnostic rule cannot drift.
150#[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    /// Outer call-path frames, outermost first. `message()` stays
159    /// pure; `Display` renders frames as a `: `-joined prefix so a
160    /// lone diagnostic reads like the anyhow context chain it
161    /// replaces across `DiagnosticResult` boundaries. Appended
162    /// during unwinding innermost-first, so later (outer) frames
163    /// prepend ahead of earlier (inner) ones.
164    contexts: Vec<String>,
165    /// Snapshot section attached at the failure boundary
166    /// (`error_with_snapshot`). Rendered after the failure text,
167    /// never folded into `message()`. Excluded from equality
168    /// alongside contexts and source.
169    snapshot: Option<String>,
170}
171
172impl Diagnostic {
173    /// Generic transport constructor. Domain crates wrap this in one
174    /// named constructor per diagnostic. Message, field keys and values,
175    /// and hints are sanitized: any [`INTERNAL_SENTINEL`] becomes a
176    /// space. Never panics on untrusted input.
177    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    /// Build a sanitized field map from pairs. Domain constructors use
201    /// this so no `format!` leaks to call sites and no sentinel leaks
202    /// to output.
203    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    /// Stable dotted key, e.g. `dsl.alias.duplicate_on_field`.
212    /// Unused for rendering; tests assert on it so a template reword
213    /// cannot silently fork one call site.
214    pub fn key(&self) -> &'static str {
215        self.0.key
216    }
217
218    /// Whole-sentence rendered message.
219    pub fn message(&self) -> &str {
220        &self.0.message
221    }
222
223    /// Structured fields that built the message.
224    pub fn fields(&self) -> &BTreeMap<String, String> {
225        &self.0.fields
226    }
227
228    /// Optional source span.
229    pub fn span(&self) -> Option<&Span> {
230        self.0.span.as_ref()
231    }
232
233    /// Optional concrete hint with an example.
234    pub fn hint(&self) -> Option<&str> {
235        self.0.hint.as_deref()
236    }
237
238    /// Outer call-path frames, outermost first. Empty until
239    /// a boundary replays anyhow contexts natively (see
240    /// [`Diagnostic::with_contexts`]).
241    pub fn contexts(&self) -> &[String] {
242        &self.0.contexts
243    }
244
245    /// Snapshot section attached at the failure boundary, if any.
246    pub fn snapshot(&self) -> Option<&str> {
247        self.0.snapshot.as_deref()
248    }
249
250    /// Shared handle to the chained source, when one is attached.
251    /// Lets owners re-chain a cause under a new typed node (such as
252    /// an exit code) without dropping it.
253    pub fn shared_source(&self) -> Option<Arc<dyn std::error::Error + Send + Sync>> {
254        self.0.source.clone()
255    }
256
257    /// Attach a source span (builder style).
258    pub fn with_span(mut self, span: Span) -> Self {
259        self.0.span = Some(span);
260        self
261    }
262
263    /// Attach a hint (builder style). Sanitized like the message.
264    pub fn with_hint(mut self, hint: String) -> Self {
265        self.0.hint = Some(sanitize_internal_encoding(&hint));
266        self
267    }
268
269    /// Attach a chained source error (builder style). Preserves error
270    /// chains across I/O, filesystem, process, and network boundaries
271    /// without `anyhow`.
272    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    /// Append outer call-path frames (builder style, outermost
278    /// first). Sanitized like the message. Unwinding attaches
279    /// innermost first, so later (outer) frames prepend ahead of
280    /// earlier (inner) ones and the stored order stays outermost
281    /// first. Lets `DiagnosticResult` boundaries carry the `step N`
282    /// call path without anyhow context layers; `message()` stays
283    /// pure.
284    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    /// Attach the snapshot section (builder style). Sanitized like
293    /// the message. Rendered after the failure text, never folded
294    /// into `message()`.
295    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        // Key, message, fields, span, and hint decide equality.
304        // Sources, call-path frames, and the snapshot section are
305        // provenance, excluded exactly like the source chain (see
306        // `equality_ignores_source_chain`).
307        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            // Failure-boundary rendering: the ordered frame sequence
321            // (outer contexts, own message plus hint, source chain)
322            // folds exactly like the historic flattened renderer, so
323            // `Display` stays byte-identical while the key, span, and
324            // code ride natively. The span block stays out: the
325            // position already reads inline above, and the span
326            // itself stays machine-readable via `span()`.
327            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        // Rendered causes: the common path renders one layer only.
388        // Chain joining belongs to a single owner (`anyhow` `{:#}`
389        // over the source chain, matching the production CLI render
390        // in `oxdock/src/main.rs`): every wrapper keeps its child as
391        // a chained source with a bare message, so `{:#}` prints each
392        // layer exactly once. Walking sources here as well would
393        // print every cause twice (once inline, once joined).
394        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        // Unwinding attaches innermost first: the outer caller adds
488        // its frames afterward, and they must still render first.
489        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}