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 LayoutRounds,
134 Bytes,
136 Pixels,
138 RasterDimension,
140}
141
142#[derive(Debug, Clone, Copy, PartialEq, Eq)]
144#[non_exhaustive]
145pub enum NonConvergenceReason {
146 Cycle,
148 IterationLimit,
150}
151
152#[derive(Debug, Clone, PartialEq, Eq)]
154#[non_exhaustive]
155pub enum MissingResource {
156 FontFamily {
158 pair_ordinal: u32,
160 requested: Option<crate::text::FontStack>,
162 },
163 FontGlyph {
165 pair_ordinal: u32,
167 requested: Option<crate::text::FontStack>,
169 scalar: u32,
171 },
172}
173
174#[derive(Debug, Clone, PartialEq, Eq)]
179#[non_exhaustive]
180pub enum DiagnosticKind {
181 Message,
183 UnknownKey {
185 key: Option<RawKey>,
187 },
188 IndexOutOfBounds {
190 index: Vec<ExactInteger>,
192 shape: Option<Vec<usize>>,
194 },
195 WrongType {
197 expected: DataValueType,
199 actual: DataValueType,
201 },
202 Ambiguous {
204 candidates: Vec<DiagnosticReference>,
206 },
207 InvalidValue {
209 value: Option<RawKey>,
211 constraint: String,
213 },
214 ShapeMismatch {
216 expected: Vec<usize>,
218 actual: Vec<usize>,
220 },
221 StaleReference {
223 reference: Box<DiagnosticReference>,
225 current: Option<Box<DiagnosticReference>>,
227 },
228 ReentrantOperation {
230 active: OperationPhase,
232 attempted: OperationPhase,
234 },
235 NonConvergence {
237 algorithm: &'static str,
239 iterations: usize,
241 reason: NonConvergenceReason,
243 },
244 BudgetExceeded {
246 resource: BudgetResource,
248 required: u128,
250 limit: u128,
252 },
253 LayoutConflict {
255 reason: FitReason,
257 },
258 Unrepresentable {
261 face_sha256: [u8; 32],
263 face_index: u32,
265 glyph_id: u16,
267 paint: GlyphPaint,
269 },
270 MissingResource(MissingResource),
272}
273
274impl DiagnosticKind {
275 #[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#[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 pub fn new() -> Self {
315 Self::default()
316 }
317 #[must_use]
319 pub fn with_operation(mut self, value: OperationPhase) -> Self {
320 self.operation = Some(value);
321 self
322 }
323 #[must_use]
325 pub fn with_panel(mut self, value: PanelPath) -> Self {
326 self.panel = Some(value);
327 self
328 }
329 #[must_use]
331 pub fn with_layer(mut self, value: LayerSlot) -> Self {
332 self.layer = Some(value);
333 self
334 }
335 #[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 #[must_use]
345 pub fn with_role(mut self, value: DataRole) -> Self {
346 self.role = Some(value);
347 self
348 }
349 #[must_use]
351 pub fn with_member(mut self, value: MemberAddress) -> Self {
352 self.member = Some(value);
353 self
354 }
355 #[must_use]
357 pub fn with_binding(mut self, value: RawKey) -> Self {
358 self.binding = Some(value);
359 self
360 }
361 #[must_use]
363 pub fn with_path(mut self, value: PathBuf) -> Self {
364 self.path = Some(value);
365 self
366 }
367 #[must_use]
369 pub fn with_span(mut self, value: TextSpan) -> Self {
370 self.span = Some(value);
371 self
372 }
373 pub const fn operation(&self) -> Option<OperationPhase> {
375 self.operation
376 }
377 pub const fn panel(&self) -> Option<&PanelPath> {
379 self.panel.as_ref()
380 }
381 pub const fn layer(&self) -> Option<LayerSlot> {
383 self.layer
384 }
385 pub const fn element(&self) -> Option<&ElementRef> {
387 self.element.as_ref()
388 }
389 pub const fn role(&self) -> Option<DataRole> {
391 self.role
392 }
393 pub const fn member(&self) -> Option<&MemberAddress> {
395 self.member.as_ref()
396 }
397 pub const fn binding(&self) -> Option<&RawKey> {
399 self.binding.as_ref()
400 }
401 pub fn path(&self) -> Option<&Path> {
403 self.path.as_deref()
404 }
405 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#[derive(Debug, Clone, PartialEq, Eq)]
421pub struct Diagnostic(Arc<DiagnosticData>);
422
423impl Diagnostic {
424 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 #[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 #[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 pub fn kind(&self) -> &DiagnosticKind {
453 &self.0.kind
454 }
455 pub fn context(&self) -> &ErrorContext {
457 &self.0.context
458 }
459 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#[derive(Debug, Clone, PartialEq, Eq)]
484#[non_exhaustive]
485pub enum OperationEffect {
486 Unchanged,
488 StreamPrefix {
490 confirmed_bytes: u64,
492 may_have_more: bool,
494 },
495 PixelTargetIndeterminate,
497 DevicePartial {
499 completed_pages: usize,
501 active_page: Option<usize>,
503 },
504}
505
506#[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 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 pub const fn phase(&self) -> OperationPhase {
534 self.phase
535 }
536 pub const fn context(&self) -> &ErrorContext {
538 &self.context
539 }
540 pub const fn effect(&self) -> &OperationEffect {
542 &self.effect
543 }
544 pub const fn cause(&self) -> &Error {
546 &self.cause
547 }
548 pub fn into_cause(self) -> Error {
550 self.cause
551 }
552}