tokit 0.0.0

Blazing fast parser combinators: parse-while-lexing (zero-copy), deterministic LALR-style parsing, no backtracking. Flexible emitters for fail-fast runtime or greedy compiler diagnostics
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
//! Hexadecimal escape sequence error types for lexer error reporting.
//!
//! This module provides error types for handling failures in hexadecimal
//! escape sequences during lexical analysis. It supports the `\xXX` format,
//! which requires exactly 2 hexadecimal digits.
//!
//! # Design Philosophy
//!
//! Hexadecimal escape sequences can fail in two ways:
//! - **Syntax errors**: Invalid hex digits, wrong format
//! - **Incompleteness**: Reaching end-of-input mid-escape (fewer than 2 digits)
//!
//! This module distinguishes between:
//! - **Malformed** syntax (invalid hex digits)
//! - **Incomplete** sequences (unexpected EOF or non-hex character)
//!
//! # Hex Escape Format: `\xXX`
//!
//! Hex escapes require exactly 2 hexadecimal digits and can encode:
//! - Any byte value: `\x00` to `\xFF`
//! - Common examples: `\x0A` (newline), `\x09` (tab), `\x20` (space)
//!
//! Common errors:
//! - `\x` - incomplete (no digits)
//! - `\xA` - incomplete (only 1 digit)
//! - `\xGG` - malformed (invalid hex)
//! - `\xZ9` - malformed (first digit invalid)
//!
//! # Error Type Hierarchy
//!
//! ```text
//! HexEscapeError
//! ├─ Incomplete (IncompleteHexEscape)
//! └─ Malformed (MalformedHexEscape)
//! ```
//!
//! # Examples
//!
//! ## Detecting Incomplete Hex Escapes
//!
//! ```
//! use tokit::error::HexEscapeError;
//! use tokit::utils::{Lexeme, SimpleSpan};
//!
//! // Incomplete: \xA (only 1 digit)
//! let error = HexEscapeError::<char>::incomplete(
//!     SimpleSpan::new(10, 13) // \xA
//! );
//! assert!(error.is_incomplete());
//! ```
//!
//! ## Detecting Malformed Hex Escapes
//!
//! ```
//! use tokit::error::{HexEscapeError, InvalidHexDigits};
//! use tokit::utils::{SimpleSpan, PositionedChar};
//!
//! // Invalid hex digit 'G' at position 12
//! let mut digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_positioned_char(PositionedChar::with_position('G', 12));
//! digits.push(PositionedChar::with_position('G', 13));
//!
//! let error = HexEscapeError::malformed(
//!     digits,
//!     SimpleSpan::new(10, 14) // \xGG
//! );
//! assert!(error.is_malformed());
//! ```

use core::ops::AddAssign;

use crate::{
  error::InvalidHexDigits,
  utils::{SimpleSpan, human_display::DisplayHuman},
};
use derive_more::{From, IsVariant, TryUnwrap, Unwrap};

/// A type alias for invalid hex digits in hex escape sequences.
pub type InvalidHexEscapeDigits<Char, Offset> = InvalidHexDigits<Char, 2, Offset>;

/// An incomplete hex escape sequence error.
///
/// This error occurs when a hex escape (`\xXX`) has fewer than 2 hex digits,
/// typically due to unexpected end-of-input or a non-hex character.
///
/// # Examples
///
/// ```
/// use tokit::error::IncompleteHexEscape;
/// use tokit::utils::SimpleSpan;
///
/// // Incomplete: \xA (only 1 hex digit)
/// let error = IncompleteHexEscape::new(
///     SimpleSpan::new(10, 13)
/// );
/// assert_eq!(error.span(), SimpleSpan::new(10, 13));
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct IncompleteHexEscape<O = usize>(SimpleSpan<O>);

impl<O> core::fmt::Display for IncompleteHexEscape<O>
where
  O: core::fmt::Display,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "incomplete hexadecimal escape sequence at {}, hexadecimal escape must contains exactly two hexadecimal digits",
      self.0
    )
  }
}

impl<O> core::error::Error for IncompleteHexEscape<O> where O: core::fmt::Debug + core::fmt::Display {}

impl<O> IncompleteHexEscape<O> {
  /// Creates a new incomplete hex escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteHexEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = IncompleteHexEscape::new(SimpleSpan::new(10, 12));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(span: SimpleSpan<O>) -> Self {
    Self(span)
  }

  /// Returns the span of the incomplete hex escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteHexEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = IncompleteHexEscape::new(SimpleSpan::new(10, 13));
  /// assert_eq!(error.span(), SimpleSpan::new(10, 13));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> SimpleSpan<O>
  where
    O: Copy,
  {
    self.0
  }

  /// Returns the span of the incomplete hex escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteHexEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = IncompleteHexEscape::new(SimpleSpan::new(10, 13));
  /// assert_eq!(error.span_ref(), SimpleSpan::new(&10, &13));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> SimpleSpan<&O> {
    self.0.as_ref()
  }

  /// Bumps the span or position by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::IncompleteHexEscape;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut error = IncompleteHexEscape::new(SimpleSpan::new(10, 12));
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 17));
  /// ```
  #[inline]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.0.bump(n);
    self
  }
}

/// A malformed hex escape sequence error.
///
/// This error occurs when a hex escape (`\xXX`) contains invalid hexadecimal
/// digits. The error captures both the invalid characters encountered and the
/// span of the malformed escape sequence.
///
/// # Type Parameters
///
/// * `Char` - The character type (typically `char` for UTF-8 or `u8` for bytes)
///
/// # Examples
///
/// ```
/// use tokit::error::{MalformedHexEscape, InvalidHexDigits};
/// use tokit::utils::{SimpleSpan, PositionedChar};
///
/// // Create error for malformed escape like \xGH
/// let mut digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_positioned_char(PositionedChar::with_position('G', 12));
/// digits.push(PositionedChar::with_position('H', 13));
///
/// let error = MalformedHexEscape::new(
///     digits,
///     SimpleSpan::new(10, 14) // \xGH
/// );
///
/// assert_eq!(error.span(), SimpleSpan::new(10, 14));
/// assert!(!error.is_incomplete()); // Only 4 chars total, expected 4 (\xXX)
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct MalformedHexEscape<Char = char, O = usize> {
  digits: InvalidHexEscapeDigits<Char, O>,
  span: SimpleSpan<O>,
}

impl<Char, O> core::fmt::Display for MalformedHexEscape<Char, O>
where
  Char: DisplayHuman,
  O: core::fmt::Display,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    write!(
      f,
      "malformed hexadecimal escape sequence with invalid digits at {}, {}",
      self.span,
      self.digits_ref()
    )
  }
}

impl<Char, O> core::error::Error for MalformedHexEscape<Char, O>
where
  Char: DisplayHuman + core::fmt::Debug,
  O: core::fmt::Debug + core::fmt::Display,
{
}

impl<Char, O> MalformedHexEscape<Char, O> {
  /// Creates a new malformed hex escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedHexEscape, InvalidHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let mut digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_positioned_char(PositionedChar::with_position('Z', 12));
  /// let error = MalformedHexEscape::new(digits, SimpleSpan::new(10, 13));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(digits: InvalidHexEscapeDigits<Char, O>, span: SimpleSpan<O>) -> Self {
    Self { digits, span }
  }

  // /// Returns `true` if the sequence is also incomplete.
  // ///
  // /// A hex escape `\xXX` is 4 characters long total.
  // /// If the span is shorter, it means the escape was cut off mid-sequence.
  // ///
  // /// ## Examples
  // ///
  // /// ```
  // /// use tokit::error::{MalformedHexEscape, InvalidHexDigits};
  // /// use tokit::utils::SimpleSpan;
  // ///
  // /// let digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_char(12, 'G');
  // /// let error = MalformedHexEscape::new(digits, SimpleSpan::new(10, 13));
  // /// assert!(error.is_incomplete()); // Only 3 chars, not 4
  // /// ```
  // #[cfg_attr(not(tarpaulin), inline(always))]
  // pub const fn is_incomplete(&self) -> bool
  // {
  //   self.span.len() < 4 // \x[0-9a-fA-F]{2} is 4 characters long
  // }

  /// Returns the invalid hex digits.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedHexEscape, InvalidHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let mut digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_positioned_char(PositionedChar::with_position('G', 12));
  /// let error = MalformedHexEscape::new(digits, SimpleSpan::new(10, 13));
  /// assert_eq!(error.digits().len(), 1);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn digits(&self) -> InvalidHexEscapeDigits<Char, O>
  where
    Char: Clone,
    O: Clone,
  {
    self.digits.clone()
  }

  /// Returns a reference to the invalid hex digits.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedHexEscape, InvalidHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let mut digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_char(12, 'G');
  /// let error = MalformedHexEscape::new(digits, SimpleSpan::new(10, 13));
  /// assert_eq!(error.digits_ref().len(), 1);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn digits_ref(&self) -> &InvalidHexEscapeDigits<Char, O> {
    &self.digits
  }

  /// Returns a mutable reference to the invalid hex digits.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn digits_mut(&mut self) -> &mut InvalidHexEscapeDigits<Char, O> {
    &mut self.digits
  }

  /// Returns the span of the malformed hex escape.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedHexEscape, InvalidHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let error = MalformedHexEscape::new(
  ///     InvalidHexDigits::from_positioned_char(PositionedChar::with_position('G', 12)),
  ///     SimpleSpan::new(10, 14)
  /// );
  /// assert_eq!(error.span(), SimpleSpan::new(10, 14));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> SimpleSpan<O>
  where
    O: Copy,
  {
    self.span
  }

  /// Returns a reference to the span of the malformed hex escape.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> SimpleSpan<&O> {
    self.span.as_ref()
  }

  /// Returns a mutable reference to the span of the malformed hex escape.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_mut(&mut self) -> SimpleSpan<&mut O> {
    self.span.as_mut()
  }

  /// Bumps the span and all digit positions by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{MalformedHexEscape, InvalidHexDigits};
  /// use tokit::utils::{SimpleSpan, PositionedChar};
  ///
  /// let mut digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_positioned_char(PositionedChar::with_position('G', 12));
  /// let mut error = MalformedHexEscape::new(digits, SimpleSpan::new(10, 14));
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 19));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.span.bump(n);
    self.digits.bump(n);
    self
  }
}

/// An error encountered during lexing for `\xXX` hex escape sequences.
///
/// Hex escapes require exactly 2 hexadecimal digits after `\x`.
/// They can encode any byte value from 0x00 to 0xFF.
///
/// # Variants
///
/// - **Incomplete**: The escape has fewer than 2 hex digits, e.g., `\x`, `\xA`
/// - **Malformed**: The 2 characters are not valid hexadecimal, e.g., `\xGG`, `\xZ9`
///
/// # Examples
///
/// ## Incomplete Escape
///
/// ```
/// use tokit::error::HexEscapeError;
/// use tokit::utils::SimpleSpan;
///
/// // Incomplete: \xA (only 1 digit)
/// let error = HexEscapeError::<char>::incomplete(
///     SimpleSpan::new(10, 13)
/// );
/// assert!(error.is_incomplete());
/// ```
///
/// ## Malformed Escape
///
/// ```
/// use tokit::error::{HexEscapeError, InvalidHexDigits};
/// use tokit::utils::{SimpleSpan, PositionedChar};
///
/// // Invalid hex: \xGG
/// let mut digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_positioned_char(PositionedChar::with_position('G', 12));
/// digits.push(PositionedChar::with_position('G', 13));
///
/// let error = HexEscapeError::malformed(digits, SimpleSpan::new(10, 14));
/// assert!(error.is_malformed());
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Hash, From, IsVariant, TryUnwrap, Unwrap)]
#[unwrap(ref, ref_mut)]
#[try_unwrap(ref, ref_mut)]
#[non_exhaustive]
pub enum HexEscapeError<Char = char, O = usize> {
  /// An incomplete hex escape sequence.
  ///
  /// This occurs when the escape has fewer than 2 hex digits, typically
  /// due to unexpected end-of-input or a non-hex character.
  ///
  /// Examples: `\x`, `\xA`
  Incomplete(IncompleteHexEscape<O>),

  /// A malformed hex escape sequence.
  ///
  /// This occurs when 2 characters follow `\x` but they are not both
  /// valid hexadecimal digits.
  ///
  /// Examples: `\xGG`, `\xZ9`, `\xAZ`
  Malformed(MalformedHexEscape<Char, O>),
}

impl<Char, O> core::fmt::Display for HexEscapeError<Char, O>
where
  Char: DisplayHuman,
  O: core::fmt::Display,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match self {
      Self::Incomplete(err) => err.fmt(f),
      Self::Malformed(malformed) => malformed.fmt(f),
    }
  }
}

impl<Char, O> core::error::Error for HexEscapeError<Char, O>
where
  Char: DisplayHuman + core::fmt::Debug + 'static,
  O: core::fmt::Debug + core::fmt::Display + 'static,
{
  fn source(&self) -> Option<&(dyn core::error::Error + 'static)> {
    match self {
      Self::Incomplete(err) => Some(err),
      Self::Malformed(err) => Some(err),
    }
  }
}

impl<Char, O> HexEscapeError<Char, O> {
  /// Creates an incomplete hex escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::HexEscapeError;
  /// use tokit::utils::{Lexeme, SimpleSpan};
  ///
  /// let error = HexEscapeError::<char>::incomplete(
  ///     SimpleSpan::new(10, 12)
  /// );
  /// assert!(error.is_incomplete());
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn incomplete(span: SimpleSpan<O>) -> Self {
    Self::Incomplete(IncompleteHexEscape::new(span))
  }

  /// Creates a malformed hex escape error.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::{HexEscapeError, InvalidHexDigits};
  /// use tokit::utils::SimpleSpan;
  ///
  /// let mut digits: InvalidHexDigits<char, 2> = InvalidHexDigits::from_char(12, 'G');
  /// let error = HexEscapeError::malformed(digits, SimpleSpan::new(10, 13));
  /// assert!(error.is_malformed());
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn malformed(digits: InvalidHexEscapeDigits<Char, O>, span: SimpleSpan<O>) -> Self {
    Self::Malformed(MalformedHexEscape::new(digits, span))
  }

  /// Returns the span of the hex escape error.
  ///
  /// This returns the span where the error occurred, which could be either
  /// the incomplete sequence or the malformed escape sequence.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::HexEscapeError;
  /// use tokit::utils::SimpleSpan;
  ///
  /// let error = HexEscapeError::<char>::incomplete(SimpleSpan::new(10, 12));
  /// assert_eq!(error.span(), SimpleSpan::new(10, 12));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> SimpleSpan<O>
  where
    O: Copy,
  {
    match self {
      Self::Incomplete(incomplete) => incomplete.span(),
      Self::Malformed(malformed) => malformed.span(),
    }
  }

  /// Bumps the span or position of the error by `n`.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// ## Examples
  ///
  /// ```
  /// use tokit::error::HexEscapeError;
  /// use tokit::utils::{Lexeme, SimpleSpan};
  ///
  /// let mut error = HexEscapeError::<char>::incomplete(
  ///     SimpleSpan::new(10, 12)
  /// );
  /// error.bump(5);
  /// // The span is now adjusted
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    match self {
      Self::Incomplete(incomplete) => {
        incomplete.bump(n);
      }
      Self::Malformed(malformed) => {
        malformed.bump(n);
      }
    }
    self
  }
}