Skip to main content

lichtung_plot/
errors.rs

1//! Structured diagnostics from actual binding, preparation and publication.
2
3use std::{
4    fmt,
5    path::{Path, PathBuf},
6    sync::Arc,
7};
8
9use crate::{
10    data::{
11        DataDomainRef, DataRole, DataRoleRef, DataValueType, ExactInteger, MemberAddress, RawKey,
12    },
13    elements::{ElementRef, LayerSlot},
14    layout::PanelPath,
15    Error, Result,
16};
17
18pub use crate::font::canonical::GlyphPaint;
19pub use crate::layout::fit::{FitKind, FitReason};
20pub use crate::layout::kernel::{AddressRole, AddressSegment, ComponentAddress};
21
22/// Actual phase of a native operation.
23#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum OperationPhase {
26    /// Binding or editing a declaration.
27    Bind,
28    /// Checking inputs or references.
29    Check,
30    /// Preparing scientific values and resources.
31    Prepare,
32    /// Assigning and measuring layout.
33    Layout,
34    /// Capturing an immutable result.
35    Freeze,
36    /// Beginning an output operation.
37    Begin,
38    /// Writing or encoding an output.
39    Write,
40    /// Completing one output page.
41    EndPage,
42    /// Finishing an output operation.
43    Finish,
44    /// Installing a completed artifact.
45    Install,
46    /// Publishing an immutable result.
47    Publish,
48    /// Presenting a result to a host.
49    Present,
50}
51
52/// An actual UTF-8 source span, with zero-based half-open byte offsets and
53/// one-based line and Unicode-character column.
54#[derive(Debug, Clone, Copy, PartialEq, Eq)]
55pub struct TextSpan {
56    start: usize,
57    end: usize,
58    line: usize,
59    column: usize,
60}
61
62impl TextSpan {
63    /// Locate a valid source range at UTF-8 character boundaries.
64    pub fn new(source: &str, start: usize, end: usize) -> Result<Self> {
65        if start > end
66            || end > source.len()
67            || !source.is_char_boundary(start)
68            || !source.is_char_boundary(end)
69        {
70            return Err(Error::Data(
71                "text span must name a valid UTF-8 byte range".into(),
72            ));
73        }
74        let prefix = &source[..start];
75        let line = prefix.bytes().filter(|&byte| byte == b'\n').count() + 1;
76        let column = prefix
77            .rsplit('\n')
78            .next()
79            .unwrap_or_default()
80            .chars()
81            .count()
82            + 1;
83        Ok(Self {
84            start,
85            end,
86            line,
87            column,
88        })
89    }
90
91    /// First byte offset in the original text.
92    pub const fn start(&self) -> usize {
93        self.start
94    }
95    /// Exclusive ending byte offset in the original text.
96    pub const fn end(&self) -> usize {
97        self.end
98    }
99    /// One-based source line.
100    pub const fn line(&self) -> usize {
101        self.line
102    }
103    /// One-based Unicode character column.
104    pub const fn column(&self) -> usize {
105        self.column
106    }
107}
108
109/// A reference involved in an actual lookup, ambiguity or stale declaration.
110#[derive(Debug, Clone, PartialEq, Eq)]
111#[non_exhaustive]
112pub enum DiagnosticReference {
113    /// A scientific layer or element.
114    Element(ElementRef),
115    /// An actual original input role.
116    Role(DataRoleRef),
117    /// An actual original member domain.
118    Domain(DataDomainRef),
119    /// A logical member in the addressed domain.
120    Member {
121        /// The actual member domain, when one is available.
122        domain: Option<DataDomainRef>,
123        /// Original logical member address.
124        address: MemberAddress,
125    },
126}
127
128/// A measured or admitted resource whose budget was exceeded.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130#[non_exhaustive]
131pub enum BudgetResource {
132    /// Operation-owned memory in bytes.
133    MemoryBytes,
134    /// Explicit producer work units.
135    Work,
136    /// Root layout feedback rounds.
137    LayoutRounds,
138    /// Encoded or parser-input bytes.
139    Bytes,
140    /// Raster pixels.
141    Pixels,
142    /// Maximum raster side length.
143    RasterDimension,
144}
145
146/// Known reason that an iterative process did not finish.
147#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148#[non_exhaustive]
149pub enum NonConvergenceReason {
150    /// An actual observed state repeated before convergence.
151    Cycle,
152    /// The iteration did not meet its stopping criterion.
153    IterationLimit,
154}
155
156/// A concrete required resource that was not available.
157#[derive(Debug, Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub enum MissingResource {
160    /// A reached font request had no admitted candidate.
161    FontFamily {
162        /// The actual prepared font-request ordinal.
163        pair_ordinal: u32,
164        /// The actual requested font stack, when available.
165        requested: Option<crate::text::FontStack>,
166    },
167    /// No admitted face covered a required Unicode scalar.
168    FontGlyph {
169        /// The actual prepared font-request ordinal.
170        pair_ordinal: u32,
171        /// The actual requested font stack, when available.
172        requested: Option<crate::text::FontStack>,
173        /// The required Unicode scalar.
174        scalar: u32,
175    },
176}
177
178/// Exact data and circumstances of a detected failure.
179///
180/// The set grows with the actual supported producers. Message is also
181/// available for caller-authored errors without a native reason.
182#[derive(Debug, Clone, PartialEq, Eq)]
183#[non_exhaustive]
184pub enum DiagnosticKind {
185    /// Caller-authored or general message with no additional typed reason.
186    Message,
187    /// A required key or declaration could not be found.
188    UnknownKey {
189        /// Original key when the lookup used a key; other selectors appear in context.
190        key: Option<RawKey>,
191    },
192    /// An invalid logical position, including addresses outside machine-word range.
193    IndexOutOfBounds {
194        /// Original index, before machine-word conversion.
195        index: Vec<ExactInteger>,
196        /// Actual logical domain shape, when the address has a selected domain.
197        shape: Option<Vec<usize>>,
198    },
199    /// An actual role cannot supply the requested native payload type.
200    WrongType {
201        /// Requested value type.
202        expected: DataValueType,
203        /// Actual value type.
204        actual: DataValueType,
205    },
206    /// A singular query matched multiple declarations or members.
207    Ambiguous {
208        /// All actual matching references or member addresses.
209        candidates: Vec<DiagnosticReference>,
210    },
211    /// A value does not satisfy a declared constraint.
212    InvalidValue {
213        /// The actual value, or None for a missing value.
214        value: Option<RawKey>,
215        /// The constraint imposed by the producer.
216        constraint: String,
217    },
218    /// Actual logical shape differs from the required shape.
219    ShapeMismatch {
220        /// Required shape.
221        expected: Vec<usize>,
222        /// Actual shape.
223        actual: Vec<usize>,
224    },
225    /// An actual previous reference is no longer valid for this owner.
226    StaleReference {
227        /// The requested reference, including its original declaration identity.
228        reference: Box<DiagnosticReference>,
229        /// The current matching declaration, when present.
230        current: Option<Box<DiagnosticReference>>,
231    },
232    /// An attempted operation conflicts with an active operation of the same owner.
233    ReentrantOperation {
234        /// Currently active phase.
235        active: OperationPhase,
236        /// Attempted phase.
237        attempted: OperationPhase,
238    },
239    /// Actual iterative process did not converge.
240    NonConvergence {
241        /// The actual algorithm.
242        algorithm: &'static str,
243        /// Number of iterations executed.
244        iterations: usize,
245        /// Observed termination reason.
246        reason: NonConvergenceReason,
247    },
248    /// A concrete resource or work budget was insufficient.
249    BudgetExceeded {
250        /// The affected resource.
251        resource: BudgetResource,
252        /// Required usage in that resource's units.
253        required: u128,
254        /// Allowed usage in those same units.
255        limit: u128,
256    },
257    /// A measured layout constraint failed at its real component address.
258    LayoutConflict {
259        /// Actual typed fit failure reason and address.
260        reason: FitReason,
261    },
262    /// A selected glyph requires paint that cannot be represented by the native
263    /// outline contract.
264    Unrepresentable {
265        /// Exact identity of the retained font bytes.
266        face_sha256: [u8; 32],
267        /// Actual face in the retained font.
268        face_index: u32,
269        /// Selected glyph index.
270        glyph_id: u16,
271        /// Actual required paint.
272        paint: GlyphPaint,
273    },
274    /// A required resource was unavailable.
275    MissingResource(MissingResource),
276}
277
278impl DiagnosticKind {
279    /// Canonical snake-case identifier for language bindings.
280    #[doc(hidden)]
281    pub const fn as_str(&self) -> &'static str {
282        match self {
283            Self::Message => "message",
284            Self::UnknownKey { .. } => "unknown_key",
285            Self::IndexOutOfBounds { .. } => "index_out_of_bounds",
286            Self::WrongType { .. } => "wrong_type",
287            Self::Ambiguous { .. } => "ambiguous",
288            Self::InvalidValue { .. } => "invalid_value",
289            Self::ShapeMismatch { .. } => "shape_mismatch",
290            Self::StaleReference { .. } => "stale_reference",
291            Self::ReentrantOperation { .. } => "reentrant_operation",
292            Self::NonConvergence { .. } => "non_convergence",
293            Self::BudgetExceeded { .. } => "budget_exceeded",
294            Self::LayoutConflict { .. } => "layout_conflict",
295            Self::Unrepresentable { .. } => "unrepresentable",
296            Self::MissingResource(_) => "missing_resource",
297        }
298    }
299}
300
301/// Context that is known at the actual point of a failure. Absent properties
302/// are not inferred from error message text.
303#[derive(Debug, Clone, Default, PartialEq, Eq)]
304pub struct ErrorContext {
305    operation: Option<OperationPhase>,
306    panel: Option<PanelPath>,
307    layer: Option<LayerSlot>,
308    element: Option<ElementRef>,
309    role: Option<DataRole>,
310    member: Option<MemberAddress>,
311    binding: Option<RawKey>,
312    path: Option<PathBuf>,
313    span: Option<TextSpan>,
314}
315
316impl ErrorContext {
317    /// Empty context.
318    pub fn new() -> Self {
319        Self::default()
320    }
321    /// Attach a known operation phase.
322    #[must_use]
323    pub fn with_operation(mut self, value: OperationPhase) -> Self {
324        self.operation = Some(value);
325        self
326    }
327    /// Attach the actual selected panel address.
328    #[must_use]
329    pub fn with_panel(mut self, value: PanelPath) -> Self {
330        self.panel = Some(value);
331        self
332    }
333    /// Attach the actual layer slot.
334    #[must_use]
335    pub fn with_layer(mut self, value: LayerSlot) -> Self {
336        self.layer = Some(value);
337        self
338    }
339    /// Attach the known owning element and its structural addresses.
340    #[must_use]
341    pub fn with_element(mut self, value: ElementRef) -> Self {
342        self.layer = Some(value.layer_slot());
343        self.panel = Some(value.panel().clone());
344        self.element = Some(value);
345        self
346    }
347    /// Attach the actual scientific input role.
348    #[must_use]
349    pub fn with_role(mut self, value: DataRole) -> Self {
350        self.role = Some(value);
351        self
352    }
353    /// Attach an actual original member address.
354    #[must_use]
355    pub fn with_member(mut self, value: MemberAddress) -> Self {
356        self.member = Some(value);
357        self
358    }
359    /// Attach an original binding field key.
360    #[must_use]
361    pub fn with_binding(mut self, value: RawKey) -> Self {
362        self.binding = Some(value);
363        self
364    }
365    /// Attach an actual file path.
366    #[must_use]
367    pub fn with_path(mut self, value: PathBuf) -> Self {
368        self.path = Some(value);
369        self
370    }
371    /// Attach a source-text span.
372    #[must_use]
373    pub fn with_span(mut self, value: TextSpan) -> Self {
374        self.span = Some(value);
375        self
376    }
377    /// Actual operation phase, when known.
378    pub const fn operation(&self) -> Option<OperationPhase> {
379        self.operation
380    }
381    /// Actual selected panel, when known.
382    pub const fn panel(&self) -> Option<&PanelPath> {
383        self.panel.as_ref()
384    }
385    /// Actual selected layer slot, when known.
386    pub const fn layer(&self) -> Option<LayerSlot> {
387        self.layer
388    }
389    /// Actual owning element, when known.
390    pub const fn element(&self) -> Option<&ElementRef> {
391        self.element.as_ref()
392    }
393    /// Actual scientific role, when known.
394    pub const fn role(&self) -> Option<DataRole> {
395        self.role
396    }
397    /// Actual member address, when known.
398    pub const fn member(&self) -> Option<&MemberAddress> {
399        self.member.as_ref()
400    }
401    /// Original binding field key, when known.
402    pub const fn binding(&self) -> Option<&RawKey> {
403        self.binding.as_ref()
404    }
405    /// Actual file path, when known.
406    pub fn path(&self) -> Option<&Path> {
407        self.path.as_deref()
408    }
409    /// Actual source span, when known.
410    pub const fn span(&self) -> Option<TextSpan> {
411        self.span
412    }
413}
414
415#[derive(Debug, Clone, PartialEq, Eq)]
416struct DiagnosticData {
417    kind: DiagnosticKind,
418    context: ErrorContext,
419    message: String,
420}
421
422/// An immutable native diagnostic that retains its actual typed cause and
423/// context independently of its human-readable message.
424#[derive(Debug, Clone, PartialEq, Eq)]
425pub struct Diagnostic(Arc<DiagnosticData>);
426
427impl Diagnostic {
428    /// Create a diagnostic with a known reason.
429    pub fn new(kind: DiagnosticKind, message: impl Into<String>) -> Self {
430        Self(Arc::new(DiagnosticData {
431            kind,
432            context: ErrorContext::default(),
433            message: message.into(),
434        }))
435    }
436    /// Attach known context.
437    #[must_use]
438    pub fn with_context(mut self, context: ErrorContext) -> Self {
439        Arc::make_mut(&mut self.0).context = context;
440        self
441    }
442    /// Add human-readable context without replacing the typed reason.
443    #[must_use]
444    pub fn with_prefix(mut self, prefix: &str) -> Self {
445        let data = Arc::make_mut(&mut self.0);
446        data.message = format!("{prefix}: {}", data.message);
447        self
448    }
449    pub(crate) fn map_message(mut self, transform: impl FnOnce(&str) -> String) -> Self {
450        let data = Arc::make_mut(&mut self.0);
451        data.message = transform(&data.message);
452        self
453    }
454
455    /// Actual typed cause.
456    pub fn kind(&self) -> &DiagnosticKind {
457        &self.0.kind
458    }
459    /// Actual known failure context.
460    pub fn context(&self) -> &ErrorContext {
461        &self.0.context
462    }
463    /// Human-readable message.
464    pub fn message(&self) -> &str {
465        &self.0.message
466    }
467}
468
469impl From<String> for Diagnostic {
470    fn from(message: String) -> Self {
471        Self::new(DiagnosticKind::Message, message)
472    }
473}
474impl From<&str> for Diagnostic {
475    fn from(message: &str) -> Self {
476        Self::new(DiagnosticKind::Message, message)
477    }
478}
479impl fmt::Display for Diagnostic {
480    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
481        f.write_str(self.message())
482    }
483}
484impl std::error::Error for Diagnostic {}
485
486/// Observable effect of a failed operation at a write or presentation boundary.
487#[derive(Debug, Clone, PartialEq, Eq)]
488#[non_exhaustive]
489pub enum OperationEffect {
490    /// The relevant external target is known not to have changed.
491    Unchanged,
492    /// A stream may contain a partially written prefix.
493    StreamPrefix {
494        /// Number of bytes confirmed written by the writer.
495        confirmed_bytes: u64,
496        /// Whether additional bytes might have been written.
497        may_have_more: bool,
498    },
499    /// The active pixel region may have been partially written.
500    PixelTargetIndeterminate,
501    /// A device may have published a subset of pages.
502    DevicePartial {
503        /// Number of fully completed pages.
504        completed_pages: usize,
505        /// The actual active page, if any.
506        active_page: Option<usize>,
507    },
508}
509
510/// A failure that must also report the actual externally observable effect.
511#[derive(Debug, thiserror::Error)]
512#[error("operation failed during {phase:?}: {cause}")]
513pub struct OperationFailure {
514    phase: OperationPhase,
515    context: ErrorContext,
516    effect: OperationEffect,
517    #[source]
518    cause: Error,
519}
520
521impl OperationFailure {
522    /// Record an actual failure and its observed effect.
523    pub fn new(
524        phase: OperationPhase,
525        context: ErrorContext,
526        effect: OperationEffect,
527        cause: Error,
528    ) -> Self {
529        Self {
530            phase,
531            context,
532            effect,
533            cause,
534        }
535    }
536    /// Actual failing phase.
537    pub const fn phase(&self) -> OperationPhase {
538        self.phase
539    }
540    /// Known context of the failure.
541    pub const fn context(&self) -> &ErrorContext {
542        &self.context
543    }
544    /// Observable effect of the failed action.
545    pub const fn effect(&self) -> &OperationEffect {
546        &self.effect
547    }
548    /// The original error.
549    pub const fn cause(&self) -> &Error {
550        &self.cause
551    }
552    /// Consume this report and return the original error.
553    pub fn into_cause(self) -> Error {
554        self.cause
555    }
556}