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