terminfokit 0.1.0

Terminfo parsing, compilation, formatting, database access, and expansion
Documentation
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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
// SPDX-FileCopyrightText: 2026 Yasunobu Sakashita
//
// SPDX-License-Identifier: MIT OR Apache-2.0

//! Errors and machine-readable diagnostics.

use alloc::boxed::Box;
use alloc::string::String;
use alloc::vec::Vec;
use core::fmt;

/// Stable source-buffer identifier.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct SourceId(u32);

impl SourceId {
    /// Creates an identity from a caller-assigned integer.
    pub const fn new(value: u32) -> Self {
        Self(value)
    }

    /// Returns the caller-assigned integer.
    pub const fn get(self) -> u32 {
        self.0
    }
}

/// A half-open byte range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct TextRange {
    start: usize,
    end: usize,
}

impl TextRange {
    /// Creates a half-open range.
    pub const fn new(start: usize, end: usize) -> Self {
        Self { start, end }
    }

    /// Returns the inclusive start byte offset.
    pub const fn start(self) -> usize {
        self.start
    }

    /// Returns the exclusive end byte offset.
    pub const fn end(self) -> usize {
        self.end
    }

    /// Returns the saturating byte length.
    pub const fn len(self) -> usize {
        self.end.saturating_sub(self.start)
    }

    /// Reports whether both bounds are equal.
    pub const fn is_empty(self) -> bool {
        self.start == self.end
    }
}

/// A source identifier and byte range.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Span {
    source_id: SourceId,
    range: TextRange,
}

impl Span {
    /// Pairs a source identity with a byte range.
    pub const fn new(source_id: SourceId, range: TextRange) -> Self {
        Self { source_id, range }
    }

    /// Creates a span in source zero from offset and length.
    pub const fn at(offset: usize, length: usize) -> Self {
        Self::new(
            SourceId::new(0),
            TextRange::new(offset, offset.saturating_add(length)),
        )
    }

    /// Returns the source identity.
    pub const fn source_id(self) -> SourceId {
        self.source_id
    }

    /// Returns the byte range.
    pub const fn range(self) -> TextRange {
        self.range
    }

    /// Reassigns the source identity while retaining the range.
    pub const fn with_source_id(mut self, value: SourceId) -> Self {
        self.source_id = value;
        self
    }
}

/// Diagnostic severity.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum Severity {
    /// Processing continues, but output may be lossy.
    Warning,
    /// Processing cannot produce the requested result.
    Error,
}

/// A primary or secondary source label.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct DiagnosticLabel {
    span: Span,
    message: Option<String>,
}

impl DiagnosticLabel {
    /// Creates a label with an optional rendered explanation.
    pub fn new(span: Span, message: Option<String>) -> Self {
        Self { span, message }
    }

    /// Returns the labelled span.
    pub const fn span(&self) -> Span {
        self.span
    }

    /// Returns the optional label-specific explanation.
    pub fn message(&self) -> Option<&str> {
        self.message.as_deref()
    }
}

/// A stable, render-independent diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Diagnostic {
    severity: Severity,
    code: &'static str,
    message: String,
    primary: Option<DiagnosticLabel>,
    secondary: Vec<DiagnosticLabel>,
    notes: Vec<String>,
}

impl Diagnostic {
    /// Creates an error diagnostic with an optional primary span.
    pub fn error(code: &'static str, message: impl Into<String>, span: Option<Span>) -> Self {
        Self {
            severity: Severity::Error,
            code,
            message: message.into(),
            primary: span.map(|span| DiagnosticLabel::new(span, None)),
            secondary: Vec::new(),
            notes: Vec::new(),
        }
    }

    /// Creates a warning diagnostic with an optional primary span.
    pub fn warning(code: &'static str, message: impl Into<String>, span: Option<Span>) -> Self {
        Self {
            severity: Severity::Warning,
            code,
            message: message.into(),
            primary: span.map(|span| DiagnosticLabel::new(span, None)),
            secondary: Vec::new(),
            notes: Vec::new(),
        }
    }

    /// Returns diagnostic severity.
    pub const fn severity(&self) -> Severity {
        self.severity
    }

    /// Returns the stable machine-readable code.
    pub const fn code(&self) -> &'static str {
        self.code
    }

    /// Returns the main human-readable message.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Returns the optional primary label.
    pub fn primary(&self) -> Option<&DiagnosticLabel> {
        self.primary.as_ref()
    }

    /// Returns related source labels.
    pub fn secondary(&self) -> &[DiagnosticLabel] {
        &self.secondary
    }

    /// Returns additional explanatory notes.
    pub fn notes(&self) -> &[String] {
        &self.notes
    }

    /// Adds a message to the primary label when present.
    pub fn with_primary_message(mut self, message: impl Into<String>) -> Self {
        if let Some(primary) = &mut self.primary {
            primary.message = Some(message.into());
        }
        self
    }

    /// Adds a related source location.
    pub fn with_secondary(mut self, span: Span, message: impl Into<String>) -> Self {
        self.secondary
            .push(DiagnosticLabel::new(span, Some(message.into())));
        self
    }

    /// Adds a free-form explanatory note.
    pub fn with_note(mut self, note: impl Into<String>) -> Self {
        self.notes.push(note.into());
        self
    }
}

/// Compiled-format decode failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum DecodeErrorKind {
    /// Input ended before the current section was complete.
    Truncated,
    /// Header magic is not a supported terminfo format.
    BadMagic(u16),
    /// A signed section count was negative.
    NegativeSize,
    /// A configured defensive or format size limit was exceeded.
    SizeLimit,
    /// Boolean slot contained an unknown sentinel.
    InvalidBoolean(u8),
    /// Numeric or string slot contained an invalid sentinel.
    InvalidSentinel(i64),
    /// String offset points outside its table.
    InvalidStringOffset,
    /// String table item has no terminating NUL.
    UnterminatedString,
    /// Terminal or extended capability name is invalid.
    InvalidName,
    /// Bytes remain after the final recognized section.
    TrailingData,
}

/// Compiled-format failure and byte offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct DecodeError {
    offset: usize,
    kind: DecodeErrorKind,
}

impl DecodeError {
    pub(crate) const fn new(offset: usize, kind: DecodeErrorKind) -> Self {
        Self { offset, kind }
    }

    /// Returns the byte offset nearest the failure.
    pub const fn offset(&self) -> usize {
        self.offset
    }

    /// Returns the structural failure category.
    pub const fn kind(&self) -> DecodeErrorKind {
        self.kind
    }
}

impl fmt::Display for DecodeErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Truncated => f.write_str("input ended before the section was complete"),
            Self::BadMagic(magic) => write!(f, "unsupported header magic {magic:#06o}"),
            Self::NegativeSize => f.write_str("a section count was negative"),
            Self::SizeLimit => f.write_str("a section exceeded a format or defensive size limit"),
            Self::InvalidBoolean(value) => write!(f, "unknown boolean sentinel {value}"),
            Self::InvalidSentinel(value) => write!(f, "invalid numeric or string sentinel {value}"),
            Self::InvalidStringOffset => f.write_str("a string offset points outside its table"),
            Self::UnterminatedString => f.write_str("a string table item has no terminating NUL"),
            Self::InvalidName => f.write_str("a terminal or capability name is invalid"),
            Self::TrailingData => f.write_str("bytes remain after the final recognized section"),
        }
    }
}

impl fmt::Display for DecodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "invalid compiled terminfo at byte {}: {}",
            self.offset, self.kind
        )
    }
}

/// Logical-entry serialization failure.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum EncodeError {
    /// A named binary section exceeded a count or allocation limit.
    SizeLimit(&'static str),
    /// A number does not fit the requested legacy representation.
    LegacyNumber(i32),
    /// A number is outside the terminfo value domain.
    InvalidNumber(i32),
    /// A terminal or extended capability name is invalid.
    InvalidName(String),
    /// A named string contains an unrepresentable NUL.
    StringContainsNul(String),
}

impl fmt::Display for EncodeError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::SizeLimit(section) => write!(f, "{section} exceeds the compiled-format limit"),
            Self::LegacyNumber(value) => write!(f, "{value} does not fit the legacy number format"),
            Self::InvalidNumber(value) => {
                write!(f, "{value} is not a valid terminfo numeric value")
            }
            Self::InvalidName(name) => write!(f, "invalid terminal or capability name {name:?}"),
            Self::StringContainsNul(name) => write!(f, "capability {name:?} contains a NUL byte"),
        }
    }
}

/// Logical-entry construction or edit failure.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum BuildError {
    /// No primary terminal name was supplied.
    EmptyPrimaryName,
    /// Terminal name is empty, unsafe, or contains a delimiter.
    InvalidName(String),
    /// Alias duplicates the primary name or another alias.
    DuplicateAlias(String),
    /// Extended capability name is empty or unsafe.
    InvalidCapabilityName(String),
    /// Numeric value is negative or too large.
    InvalidNumber(i64),
    /// Named string contains an unrepresentable NUL.
    StringContainsNul(String),
    /// Cancelling an unknown extension requires its type.
    ExtendedKindRequired(String),
}

impl fmt::Display for BuildError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::EmptyPrimaryName => f.write_str("a terminal entry needs a primary name"),
            Self::InvalidName(name) => write!(f, "invalid terminal name {name:?}"),
            Self::DuplicateAlias(name) => write!(f, "duplicate terminal name {name:?}"),
            Self::InvalidCapabilityName(name) => write!(f, "invalid capability name {name:?}"),
            Self::InvalidNumber(value) => {
                write!(f, "{value} is not a valid terminfo numeric value")
            }
            Self::StringContainsNul(name) => {
                write!(f, "capability {name:?} contains a NUL byte")
            }
            Self::ExtendedKindRequired(name) => write!(
                f,
                "cancelling the unknown extension {name:?} requires its capability type"
            ),
        }
    }
}

/// Source parse failure and diagnostic.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct ParseError {
    pub(crate) diagnostic: Box<Diagnostic>,
}

impl ParseError {
    /// Wraps a structured parser diagnostic.
    pub fn new(diagnostic: Diagnostic) -> Self {
        Self {
            diagnostic: Box::new(diagnostic),
        }
    }

    /// Returns the parser diagnostic.
    pub fn diagnostic(&self) -> &Diagnostic {
        &self.diagnostic
    }

    /// Consumes the error and returns its diagnostic.
    pub fn into_diagnostic(self) -> Diagnostic {
        *self.diagnostic
    }
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}: {}", self.diagnostic.code, self.diagnostic.message)
    }
}

/// Stage and category of a compilation failure.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum CompileErrorKind {
    /// Source tokenization or parsing failed.
    Parse,
    /// An inheritance target could not be found.
    MissingUse {
        /// Requested target name.
        name: String,
    },
    /// Inheritance contains a cycle.
    UseCycle {
        /// Complete cycle including the repeated first name.
        chain: Vec<String>,
    },
    /// One user-defined name has conflicting types.
    ExtendedTypeConflict {
        /// Conflicting capability name.
        name: String,
    },
    /// An external entry provider failed.
    Provider {
        /// Requested external name.
        name: String,
        /// Provider-supplied explanation.
        message: String,
    },
    /// Logical entry validation failed.
    Build(BuildError),
    /// Binary serialization failed.
    Encode(EncodeError),
}

/// Compilation failure and diagnostics.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CompileError {
    pub(crate) kind: CompileErrorKind,
    pub(crate) diagnostics: Vec<Diagnostic>,
}

impl CompileError {
    /// Constructs an error from its category and diagnostics.
    pub fn new(kind: CompileErrorKind, diagnostics: Vec<Diagnostic>) -> Self {
        Self { kind, diagnostics }
    }

    /// Returns the compilation failure category.
    pub fn kind(&self) -> &CompileErrorKind {
        &self.kind
    }

    /// Returns structured diagnostics in reporting order.
    pub fn diagnostics(&self) -> &[Diagnostic] {
        &self.diagnostics
    }
}

impl fmt::Display for CompileError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            CompileErrorKind::Parse => f.write_str("terminfo source could not be parsed"),
            CompileErrorKind::MissingUse { name } => write!(f, "unknown use= entry {name:?}"),
            CompileErrorKind::UseCycle { chain } => write!(f, "use= cycle: {}", chain.join(" -> ")),
            CompileErrorKind::ExtendedTypeConflict { name } => write!(
                f,
                "user-defined capability {name:?} is used with conflicting types"
            ),
            CompileErrorKind::Provider { name, message } => {
                write!(f, "entry provider failed for {name:?}: {message}")
            }
            CompileErrorKind::Build(error) => write!(f, "invalid terminfo entry: {error}"),
            CompileErrorKind::Encode(error) => write!(f, "encoding failed: {error}"),
        }
    }
}

/// Parameter-program failure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[non_exhaustive]
pub enum ExpandErrorKind {
    /// An operator is missing required following bytes.
    TruncatedOperator,
    /// An operator needed more stack values.
    StackUnderflow,
    /// A value had the wrong number/string type.
    TypeMismatch,
    /// Parameter index is outside the supported range.
    InvalidParameter,
    /// Variable name is outside the supported range.
    InvalidVariable,
    /// Numeric literal or formatting operand is invalid.
    InvalidNumber,
    /// Division or remainder used a zero divisor.
    DivideByZero,
    /// Conditional markers are unbalanced.
    UnbalancedConditional,
    /// Expanded bytes exceed the configured limit.
    OutputLimit,
    /// Executed operators exceed the configured limit.
    StepLimit,
    /// Stack depth exceeds the configured limit.
    StackLimit,
}

/// Expansion failure and byte offset.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct ExpandError {
    pub(crate) offset: usize,
    pub(crate) kind: ExpandErrorKind,
}

impl ExpandError {
    pub(crate) const fn new(offset: usize, kind: ExpandErrorKind) -> Self {
        Self { offset, kind }
    }

    /// Returns the program byte offset nearest the failure.
    pub const fn offset(&self) -> usize {
        self.offset
    }

    /// Returns the expansion failure category.
    pub const fn kind(&self) -> ExpandErrorKind {
        self.kind
    }
}

/// Terminfo/termcap conversion failure.
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum ConvertError {
    /// Named capability has no representation under a strict profile.
    LossyCapability(String),
    /// Named parameter expression cannot be represented by termcap.
    UnsupportedExpression(String),
    /// Rendered termcap entry exceeds its profile limit.
    EntryTooLong {
        /// Actual rendered byte length.
        length: usize,
        /// Active profile limit.
        limit: usize,
    },
    /// Termcap inheritance compilation failed.
    Compile(CompileError),
}

impl fmt::Display for ConvertError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::LossyCapability(name) => write!(
                f,
                "capability {name:?} has no lossless termcap representation"
            ),
            Self::UnsupportedExpression(name) => write!(
                f,
                "capability {name:?} uses a parameter expression termcap cannot represent"
            ),
            Self::EntryTooLong { length, limit } => {
                write!(f, "termcap entry is {length} bytes (profile limit {limit})")
            }
            Self::Compile(error) => error.fmt(f),
        }
    }
}

impl fmt::Display for ExpandErrorKind {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::TruncatedOperator => f.write_str("an operator is missing required bytes"),
            Self::StackUnderflow => f.write_str("an operator needed more stack values"),
            Self::TypeMismatch => f.write_str("a value had the wrong number or string type"),
            Self::InvalidParameter => f.write_str("parameter index is out of range"),
            Self::InvalidVariable => f.write_str("variable name is out of range"),
            Self::InvalidNumber => {
                f.write_str("a numeric literal or formatting operand is invalid")
            }
            Self::DivideByZero => f.write_str("division or remainder by zero"),
            Self::UnbalancedConditional => f.write_str("conditional markers are unbalanced"),
            Self::OutputLimit => f.write_str("expanded output exceeds the configured limit"),
            Self::StepLimit => f.write_str("executed operators exceed the configured limit"),
            Self::StackLimit => f.write_str("stack depth exceeds the configured limit"),
        }
    }
}

impl fmt::Display for ExpandError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            f,
            "parameter expansion failed at byte {}: {}",
            self.offset, self.kind
        )
    }
}

/// Database access or decode failure.
#[cfg(feature = "std")]
#[derive(Debug)]
#[non_exhaustive]
pub enum DatabaseError {
    /// Requested terminal name is unsafe for filesystem lookup.
    InvalidName(String),
    /// No backend contained the requested terminal.
    NotFound(String),
    /// Selected backend or transport is unsupported or malformed.
    UnsupportedBackend(String),
    /// Decoded entry does not claim the requested name.
    NameMismatch {
        /// Name requested by the caller.
        requested: String,
        /// Primary name found in the decoded entry.
        decoded: String,
    },
    /// Lookup encountered a symlink which is not trusted.
    UntrustedSymlink(std::path::PathBuf),
    /// Compiled bytes were malformed.
    Decode(DecodeError),
    /// Operating-system I/O failed.
    Io(std::io::Error),
}

#[cfg(feature = "std")]
impl fmt::Display for DatabaseError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidName(name) => write!(f, "unsafe terminal name {name:?}"),
            Self::NotFound(name) => write!(f, "terminfo entry {name:?} was not found"),
            Self::UnsupportedBackend(kind) => write!(f, "unsupported terminfo backend: {kind}"),
            Self::NameMismatch { requested, decoded } => write!(
                f,
                "terminfo entry name mismatch: requested {requested:?}, decoded {decoded:?}"
            ),
            Self::UntrustedSymlink(path) => {
                write!(f, "refusing untrusted terminfo symlink {}", path.display())
            }
            Self::Decode(error) => error.fmt(f),
            Self::Io(error) => error.fmt(f),
        }
    }
}

#[cfg(feature = "std")]
impl From<std::io::Error> for DatabaseError {
    fn from(value: std::io::Error) -> Self {
        Self::Io(value)
    }
}

impl core::error::Error for DecodeError {}
impl core::error::Error for EncodeError {}
impl core::error::Error for BuildError {}
impl core::error::Error for ParseError {}
impl core::error::Error for CompileError {}
impl core::error::Error for ExpandError {}
impl core::error::Error for ConvertError {}
#[cfg(feature = "std")]
impl core::error::Error for DatabaseError {}