1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24#[non_exhaustive]
25pub enum OperationPhase {
26 Bind,
28 Check,
30 Prepare,
32 Layout,
34 Freeze,
36 Begin,
38 Write,
40 EndPage,
42 Finish,
44 Install,
46 Publish,
48 Present,
50}
51
52#[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 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 pub const fn start(&self) -> usize {
93 self.start
94 }
95 pub const fn end(&self) -> usize {
97 self.end
98 }
99 pub const fn line(&self) -> usize {
101 self.line
102 }
103 pub const fn column(&self) -> usize {
105 self.column
106 }
107}
108
109#[derive(Debug, Clone, PartialEq, Eq)]
111#[non_exhaustive]
112pub enum DiagnosticReference {
113 Element(ElementRef),
115 Role(DataRoleRef),
117 Domain(DataDomainRef),
119 Member {
121 domain: Option<DataDomainRef>,
123 address: MemberAddress,
125 },
126}
127
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130#[non_exhaustive]
131pub enum BudgetResource {
132 MemoryBytes,
134 Work,
136 LayoutRounds,
138 Bytes,
140 Pixels,
142 RasterDimension,
144}
145
146#[derive(Debug, Clone, Copy, PartialEq, Eq)]
148#[non_exhaustive]
149pub enum NonConvergenceReason {
150 Cycle,
152 IterationLimit,
154}
155
156#[derive(Debug, Clone, PartialEq, Eq)]
158#[non_exhaustive]
159pub enum MissingResource {
160 FontFamily {
162 pair_ordinal: u32,
164 requested: Option<crate::text::FontStack>,
166 },
167 FontGlyph {
169 pair_ordinal: u32,
171 requested: Option<crate::text::FontStack>,
173 scalar: u32,
175 },
176}
177
178#[derive(Debug, Clone, PartialEq, Eq)]
183#[non_exhaustive]
184pub enum DiagnosticKind {
185 Message,
187 UnknownKey {
189 key: Option<RawKey>,
191 },
192 IndexOutOfBounds {
194 index: Vec<ExactInteger>,
196 shape: Option<Vec<usize>>,
198 },
199 WrongType {
201 expected: DataValueType,
203 actual: DataValueType,
205 },
206 Ambiguous {
208 candidates: Vec<DiagnosticReference>,
210 },
211 InvalidValue {
213 value: Option<RawKey>,
215 constraint: String,
217 },
218 ShapeMismatch {
220 expected: Vec<usize>,
222 actual: Vec<usize>,
224 },
225 StaleReference {
227 reference: Box<DiagnosticReference>,
229 current: Option<Box<DiagnosticReference>>,
231 },
232 ReentrantOperation {
234 active: OperationPhase,
236 attempted: OperationPhase,
238 },
239 NonConvergence {
241 algorithm: &'static str,
243 iterations: usize,
245 reason: NonConvergenceReason,
247 },
248 BudgetExceeded {
250 resource: BudgetResource,
252 required: u128,
254 limit: u128,
256 },
257 LayoutConflict {
259 reason: FitReason,
261 },
262 Unrepresentable {
265 face_sha256: [u8; 32],
267 face_index: u32,
269 glyph_id: u16,
271 paint: GlyphPaint,
273 },
274 MissingResource(MissingResource),
276}
277
278impl DiagnosticKind {
279 #[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#[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 pub fn new() -> Self {
319 Self::default()
320 }
321 #[must_use]
323 pub fn with_operation(mut self, value: OperationPhase) -> Self {
324 self.operation = Some(value);
325 self
326 }
327 #[must_use]
329 pub fn with_panel(mut self, value: PanelPath) -> Self {
330 self.panel = Some(value);
331 self
332 }
333 #[must_use]
335 pub fn with_layer(mut self, value: LayerSlot) -> Self {
336 self.layer = Some(value);
337 self
338 }
339 #[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 #[must_use]
349 pub fn with_role(mut self, value: DataRole) -> Self {
350 self.role = Some(value);
351 self
352 }
353 #[must_use]
355 pub fn with_member(mut self, value: MemberAddress) -> Self {
356 self.member = Some(value);
357 self
358 }
359 #[must_use]
361 pub fn with_binding(mut self, value: RawKey) -> Self {
362 self.binding = Some(value);
363 self
364 }
365 #[must_use]
367 pub fn with_path(mut self, value: PathBuf) -> Self {
368 self.path = Some(value);
369 self
370 }
371 #[must_use]
373 pub fn with_span(mut self, value: TextSpan) -> Self {
374 self.span = Some(value);
375 self
376 }
377 pub const fn operation(&self) -> Option<OperationPhase> {
379 self.operation
380 }
381 pub const fn panel(&self) -> Option<&PanelPath> {
383 self.panel.as_ref()
384 }
385 pub const fn layer(&self) -> Option<LayerSlot> {
387 self.layer
388 }
389 pub const fn element(&self) -> Option<&ElementRef> {
391 self.element.as_ref()
392 }
393 pub const fn role(&self) -> Option<DataRole> {
395 self.role
396 }
397 pub const fn member(&self) -> Option<&MemberAddress> {
399 self.member.as_ref()
400 }
401 pub const fn binding(&self) -> Option<&RawKey> {
403 self.binding.as_ref()
404 }
405 pub fn path(&self) -> Option<&Path> {
407 self.path.as_deref()
408 }
409 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#[derive(Debug, Clone, PartialEq, Eq)]
425pub struct Diagnostic(Arc<DiagnosticData>);
426
427impl Diagnostic {
428 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 #[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 #[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 pub fn kind(&self) -> &DiagnosticKind {
457 &self.0.kind
458 }
459 pub fn context(&self) -> &ErrorContext {
461 &self.0.context
462 }
463 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#[derive(Debug, Clone, PartialEq, Eq)]
488#[non_exhaustive]
489pub enum OperationEffect {
490 Unchanged,
492 StreamPrefix {
494 confirmed_bytes: u64,
496 may_have_more: bool,
498 },
499 PixelTargetIndeterminate,
501 DevicePartial {
503 completed_pages: usize,
505 active_page: Option<usize>,
507 },
508}
509
510#[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 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 pub const fn phase(&self) -> OperationPhase {
538 self.phase
539 }
540 pub const fn context(&self) -> &ErrorContext {
542 &self.context
543 }
544 pub const fn effect(&self) -> &OperationEffect {
546 &self.effect
547 }
548 pub const fn cause(&self) -> &Error {
550 &self.cause
551 }
552 pub fn into_cause(self) -> Error {
554 self.cause
555 }
556}