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 concrete resource whose local limit was exceeded.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130#[non_exhaustive]
131pub enum BudgetResource {
132    /// Root layout feedback rounds.
133    LayoutRounds,
134    /// Encoded or parser-input bytes.
135    Bytes,
136    /// Raster pixels.
137    Pixels,
138    /// Maximum raster side length.
139    RasterDimension,
140}
141
142/// Known reason that an iterative process did not finish.
143#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum NonConvergenceReason {
146    /// An actual observed state repeated before convergence.
147    Cycle,
148    /// The iteration did not meet its stopping criterion.
149    IterationLimit,
150}
151
152/// A concrete required resource that was not available.
153#[derive(Debug, Clone, PartialEq, Eq)]
154#[non_exhaustive]
155pub enum MissingResource {
156    /// A reached font request had no admitted candidate.
157    FontFamily {
158        /// The actual prepared font-request ordinal.
159        pair_ordinal: u32,
160        /// The actual requested font stack, when available.
161        requested: Option<crate::text::FontStack>,
162    },
163    /// No admitted face covered a required Unicode scalar.
164    FontGlyph {
165        /// The actual prepared font-request ordinal.
166        pair_ordinal: u32,
167        /// The actual requested font stack, when available.
168        requested: Option<crate::text::FontStack>,
169        /// The required Unicode scalar.
170        scalar: u32,
171    },
172}
173
174/// Exact data and circumstances of a detected failure.
175///
176/// The set grows with the actual supported producers. Message is also
177/// available for caller-authored errors without a native reason.
178#[derive(Debug, Clone, PartialEq, Eq)]
179#[non_exhaustive]
180pub enum DiagnosticKind {
181    /// Caller-authored or general message with no additional typed reason.
182    Message,
183    /// A required key or declaration could not be found.
184    UnknownKey {
185        /// Original key when the lookup used a key; other selectors appear in context.
186        key: Option<RawKey>,
187    },
188    /// An invalid logical position, including addresses outside machine-word range.
189    IndexOutOfBounds {
190        /// Original index, before machine-word conversion.
191        index: Vec<ExactInteger>,
192        /// Actual logical domain shape, when the address has a selected domain.
193        shape: Option<Vec<usize>>,
194    },
195    /// An actual role cannot supply the requested native payload type.
196    WrongType {
197        /// Requested value type.
198        expected: DataValueType,
199        /// Actual value type.
200        actual: DataValueType,
201    },
202    /// A singular query matched multiple declarations or members.
203    Ambiguous {
204        /// All actual matching references or member addresses.
205        candidates: Vec<DiagnosticReference>,
206    },
207    /// A value does not satisfy a declared constraint.
208    InvalidValue {
209        /// The actual value, or None for a missing value.
210        value: Option<RawKey>,
211        /// The constraint imposed by the producer.
212        constraint: String,
213    },
214    /// Actual logical shape differs from the required shape.
215    ShapeMismatch {
216        /// Required shape.
217        expected: Vec<usize>,
218        /// Actual shape.
219        actual: Vec<usize>,
220    },
221    /// An actual previous reference is no longer valid for this owner.
222    StaleReference {
223        /// The requested reference, including its original declaration identity.
224        reference: Box<DiagnosticReference>,
225        /// The current matching declaration, when present.
226        current: Option<Box<DiagnosticReference>>,
227    },
228    /// An attempted operation conflicts with an active operation of the same owner.
229    ReentrantOperation {
230        /// Currently active phase.
231        active: OperationPhase,
232        /// Attempted phase.
233        attempted: OperationPhase,
234    },
235    /// Actual iterative process did not converge.
236    NonConvergence {
237        /// The actual algorithm.
238        algorithm: &'static str,
239        /// Number of iterations executed.
240        iterations: usize,
241        /// Observed termination reason.
242        reason: NonConvergenceReason,
243    },
244    /// A concrete resource or iteration limit was exceeded.
245    BudgetExceeded {
246        /// The affected resource.
247        resource: BudgetResource,
248        /// Required usage in that resource's units.
249        required: u128,
250        /// Allowed usage in those same units.
251        limit: u128,
252    },
253    /// A measured layout constraint failed at its real component address.
254    LayoutConflict {
255        /// Actual typed fit failure reason and address.
256        reason: FitReason,
257    },
258    /// A selected glyph requires paint that cannot be represented by the native
259    /// outline contract.
260    Unrepresentable {
261        /// Exact identity of the retained font bytes.
262        face_sha256: [u8; 32],
263        /// Actual face in the retained font.
264        face_index: u32,
265        /// Selected glyph index.
266        glyph_id: u16,
267        /// Actual required paint.
268        paint: GlyphPaint,
269    },
270    /// A required resource was unavailable.
271    MissingResource(MissingResource),
272}
273
274impl DiagnosticKind {
275    /// Canonical snake-case identifier for language bindings.
276    #[doc(hidden)]
277    pub const fn as_str(&self) -> &'static str {
278        match self {
279            Self::Message => "message",
280            Self::UnknownKey { .. } => "unknown_key",
281            Self::IndexOutOfBounds { .. } => "index_out_of_bounds",
282            Self::WrongType { .. } => "wrong_type",
283            Self::Ambiguous { .. } => "ambiguous",
284            Self::InvalidValue { .. } => "invalid_value",
285            Self::ShapeMismatch { .. } => "shape_mismatch",
286            Self::StaleReference { .. } => "stale_reference",
287            Self::ReentrantOperation { .. } => "reentrant_operation",
288            Self::NonConvergence { .. } => "non_convergence",
289            Self::BudgetExceeded { .. } => "budget_exceeded",
290            Self::LayoutConflict { .. } => "layout_conflict",
291            Self::Unrepresentable { .. } => "unrepresentable",
292            Self::MissingResource(_) => "missing_resource",
293        }
294    }
295}
296
297/// Context that is known at the actual point of a failure. Absent properties
298/// are not inferred from error message text.
299#[derive(Debug, Clone, Default, PartialEq, Eq)]
300pub struct ErrorContext {
301    operation: Option<OperationPhase>,
302    panel: Option<PanelPath>,
303    layer: Option<LayerSlot>,
304    element: Option<ElementRef>,
305    role: Option<DataRole>,
306    member: Option<MemberAddress>,
307    binding: Option<RawKey>,
308    path: Option<PathBuf>,
309    span: Option<TextSpan>,
310}
311
312impl ErrorContext {
313    /// Empty context.
314    pub fn new() -> Self {
315        Self::default()
316    }
317    /// Attach a known operation phase.
318    #[must_use]
319    pub fn with_operation(mut self, value: OperationPhase) -> Self {
320        self.operation = Some(value);
321        self
322    }
323    /// Attach the actual selected panel address.
324    #[must_use]
325    pub fn with_panel(mut self, value: PanelPath) -> Self {
326        self.panel = Some(value);
327        self
328    }
329    /// Attach the actual layer slot.
330    #[must_use]
331    pub fn with_layer(mut self, value: LayerSlot) -> Self {
332        self.layer = Some(value);
333        self
334    }
335    /// Attach the known owning element and its structural addresses.
336    #[must_use]
337    pub fn with_element(mut self, value: ElementRef) -> Self {
338        self.layer = Some(value.layer_slot());
339        self.panel = Some(value.panel().clone());
340        self.element = Some(value);
341        self
342    }
343    /// Attach the actual scientific input role.
344    #[must_use]
345    pub fn with_role(mut self, value: DataRole) -> Self {
346        self.role = Some(value);
347        self
348    }
349    /// Attach an actual original member address.
350    #[must_use]
351    pub fn with_member(mut self, value: MemberAddress) -> Self {
352        self.member = Some(value);
353        self
354    }
355    /// Attach an original binding field key.
356    #[must_use]
357    pub fn with_binding(mut self, value: RawKey) -> Self {
358        self.binding = Some(value);
359        self
360    }
361    /// Attach an actual file path.
362    #[must_use]
363    pub fn with_path(mut self, value: PathBuf) -> Self {
364        self.path = Some(value);
365        self
366    }
367    /// Attach a source-text span.
368    #[must_use]
369    pub fn with_span(mut self, value: TextSpan) -> Self {
370        self.span = Some(value);
371        self
372    }
373    /// Actual operation phase, when known.
374    pub const fn operation(&self) -> Option<OperationPhase> {
375        self.operation
376    }
377    /// Actual selected panel, when known.
378    pub const fn panel(&self) -> Option<&PanelPath> {
379        self.panel.as_ref()
380    }
381    /// Actual selected layer slot, when known.
382    pub const fn layer(&self) -> Option<LayerSlot> {
383        self.layer
384    }
385    /// Actual owning element, when known.
386    pub const fn element(&self) -> Option<&ElementRef> {
387        self.element.as_ref()
388    }
389    /// Actual scientific role, when known.
390    pub const fn role(&self) -> Option<DataRole> {
391        self.role
392    }
393    /// Actual member address, when known.
394    pub const fn member(&self) -> Option<&MemberAddress> {
395        self.member.as_ref()
396    }
397    /// Original binding field key, when known.
398    pub const fn binding(&self) -> Option<&RawKey> {
399        self.binding.as_ref()
400    }
401    /// Actual file path, when known.
402    pub fn path(&self) -> Option<&Path> {
403        self.path.as_deref()
404    }
405    /// Actual source span, when known.
406    pub const fn span(&self) -> Option<TextSpan> {
407        self.span
408    }
409}
410
411#[derive(Debug, Clone, PartialEq, Eq)]
412struct DiagnosticData {
413    kind: DiagnosticKind,
414    context: ErrorContext,
415    message: String,
416}
417
418/// An immutable native diagnostic that retains its actual typed cause and
419/// context independently of its human-readable message.
420#[derive(Debug, Clone, PartialEq, Eq)]
421pub struct Diagnostic(Arc<DiagnosticData>);
422
423impl Diagnostic {
424    /// Create a diagnostic with a known reason.
425    pub fn new(kind: DiagnosticKind, message: impl Into<String>) -> Self {
426        Self(Arc::new(DiagnosticData {
427            kind,
428            context: ErrorContext::default(),
429            message: message.into(),
430        }))
431    }
432    /// Attach known context.
433    #[must_use]
434    pub fn with_context(mut self, context: ErrorContext) -> Self {
435        Arc::make_mut(&mut self.0).context = context;
436        self
437    }
438    /// Add human-readable context without replacing the typed reason.
439    #[must_use]
440    pub fn with_prefix(mut self, prefix: &str) -> Self {
441        let data = Arc::make_mut(&mut self.0);
442        data.message = format!("{prefix}: {}", data.message);
443        self
444    }
445    pub(crate) fn map_message(mut self, transform: impl FnOnce(&str) -> String) -> Self {
446        let data = Arc::make_mut(&mut self.0);
447        data.message = transform(&data.message);
448        self
449    }
450
451    /// Actual typed cause.
452    pub fn kind(&self) -> &DiagnosticKind {
453        &self.0.kind
454    }
455    /// Actual known failure context.
456    pub fn context(&self) -> &ErrorContext {
457        &self.0.context
458    }
459    /// Human-readable message.
460    pub fn message(&self) -> &str {
461        &self.0.message
462    }
463}
464
465impl From<String> for Diagnostic {
466    fn from(message: String) -> Self {
467        Self::new(DiagnosticKind::Message, message)
468    }
469}
470impl From<&str> for Diagnostic {
471    fn from(message: &str) -> Self {
472        Self::new(DiagnosticKind::Message, message)
473    }
474}
475impl fmt::Display for Diagnostic {
476    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
477        f.write_str(self.message())
478    }
479}
480impl std::error::Error for Diagnostic {}
481
482/// Observable effect of a failed operation at a write or presentation boundary.
483#[derive(Debug, Clone, PartialEq, Eq)]
484#[non_exhaustive]
485pub enum OperationEffect {
486    /// The relevant external target is known not to have changed.
487    Unchanged,
488    /// A stream may contain a partially written prefix.
489    StreamPrefix {
490        /// Number of bytes confirmed written by the writer.
491        confirmed_bytes: u64,
492        /// Whether additional bytes might have been written.
493        may_have_more: bool,
494    },
495    /// The active pixel region may have been partially written.
496    PixelTargetIndeterminate,
497    /// A device may have published a subset of pages.
498    DevicePartial {
499        /// Number of fully completed pages.
500        completed_pages: usize,
501        /// The actual active page, if any.
502        active_page: Option<usize>,
503    },
504}
505
506/// A failure that must also report the actual externally observable effect.
507#[derive(Debug, thiserror::Error)]
508#[error("operation failed during {phase:?}: {cause}")]
509pub struct OperationFailure {
510    phase: OperationPhase,
511    context: ErrorContext,
512    effect: OperationEffect,
513    #[source]
514    cause: Error,
515}
516
517impl OperationFailure {
518    /// Record an actual failure and its observed effect.
519    pub fn new(
520        phase: OperationPhase,
521        context: ErrorContext,
522        effect: OperationEffect,
523        cause: Error,
524    ) -> Self {
525        Self {
526            phase,
527            context,
528            effect,
529            cause,
530        }
531    }
532    /// Actual failing phase.
533    pub const fn phase(&self) -> OperationPhase {
534        self.phase
535    }
536    /// Known context of the failure.
537    pub const fn context(&self) -> &ErrorContext {
538        &self.context
539    }
540    /// Observable effect of the failed action.
541    pub const fn effect(&self) -> &OperationEffect {
542        &self.effect
543    }
544    /// The original error.
545    pub const fn cause(&self) -> &Error {
546        &self.cause
547    }
548    /// Consume this report and return the original error.
549    pub fn into_cause(self) -> Error {
550        self.cause
551    }
552}