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
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
use core::ops::{Add, AddAssign};

use crate::utils::{
  CharLen, Lexeme, PositionedChar, SimpleSpan, human_display::DisplayHuman,
  knowledge::LineTerminator,
};

/// A specialized `UnexpectedLexeme` for line terminators.
///
/// This type represents an unexpected line terminator character
/// encountered during lexing or parsing, along with a hint
/// describing what was expected instead.
pub type UnexpectedLineTerminator<Char, O = usize> = UnexpectedLexeme<Char, LineTerminator, O>;

/// A zero-copy error structure combining an unexpected lexeme with a diagnostic hint.
///
/// `UnexpectedLexeme` pairs a [`Lexeme`] (identifying what went wrong) with a hint
/// (describing what was expected instead). This structure is designed for building
/// rich, informative error messages without allocating strings.
///
/// # Type Parameters
///
/// - **Char**: The character type (typically `char` for UTF-8 or `u8` for bytes)
/// - **Hint**: Any type describing what was expected (often implements `Display`)
///
/// # Design Philosophy
///
/// This type stores:
/// - The **lexeme** of the unexpected fragment ([`Char`](Lexeme::Char) or [`SimpleSpan`](Lexeme::Range))
/// - A **hint** describing what was expected next (any type you choose)
///
/// The hint is left generic and unconstrained so you can carry:
/// - Simple strings: `&'static str`
/// - Token kinds: Your own `TokenKind` enum
/// - Rich structures: Custom diagnostic types with multiple suggestions
///
/// # Deref Behavior
///
/// `UnexpectedLexeme` implements `Deref` to `Lexeme<Char>`, so you can call all
/// `Lexeme` methods directly on an `UnexpectedLexeme` instance.
///
/// # Use Cases
///
/// - **Lexer errors**: Report unexpected characters with "expected" hints
/// - **Parser errors**: Track unexpected tokens with contextual information
/// - **Error recovery**: Store partial error info without allocating
/// - **Diagnostic tools**: Build structured error reports for IDEs
///
/// # Examples
///
/// ## Basic Error with String Hint
///
/// ```rust
/// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
///
/// let error = UnexpectedLexeme::from_positioned_char(
///     PositionedChar::with_position('!', 42),
///     "expected letter or digit"
/// );
///
/// assert!(error.is_char());
/// assert_eq!(error.lexeme().unwrap_char().position(), 42);
/// assert_eq!(*error.hint(), "expected letter or digit");
/// ```
///
/// ## With Token Kind Hint
///
/// ```rust,ignore
/// use tokit::{error::UnexpectedLexeme, utils::SimpleSpan};
///
/// #[derive(Debug, Clone)]
/// enum Expected {
///     Token(TokenKind),
///     OneOf(Vec<TokenKind>),
/// }
///
/// let error = UnexpectedLexeme::from_range(
///     SimpleSpan::new(10, 15),
///     Expected::OneOf(vec![TokenKind::Semicolon, TokenKind::Comma])
/// );
///
/// // Use in error display
/// match error.hint() {
///     Expected::Token(kind) => println!("Expected {:?}", kind),
///     Expected::OneOf(kinds) => println!("Expected one of: {:?}", kinds),
/// }
/// ```
///
/// ## Mapping Hints
///
/// ```rust
/// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
///
/// let error = UnexpectedLexeme::from_positioned_char(
///     PositionedChar::with_position('x', 5),
///     "number"
/// );
///
/// // Transform the hint to a more detailed message
/// let detailed = error.map_hint(|hint| format!("expected {}, found 'x'", hint));
///
/// assert_eq!(detailed.hint(), "expected number, found 'x'");
/// ```
///
/// ## Accessing Lexeme via Deref
///
/// ```rust
/// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
///
/// let error = UnexpectedLexeme::from_positioned_char(
///     PositionedChar::with_position('!', 10),
///     "identifier"
/// );
///
/// // Call Lexeme methods directly
/// assert!(error.is_char());
/// let span = error.span(); // Deref to Lexeme, call span()
/// assert_eq!(span.start(), 10);
/// ```
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub struct UnexpectedLexeme<Char, Hint, O = usize> {
  lexeme: Lexeme<Char, O>,
  hint: Hint,
}

impl<Char, Hint, O> core::fmt::Display for UnexpectedLexeme<Char, Hint, O>
where
  Char: DisplayHuman,
  O: core::fmt::Display,
{
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    match &self.lexeme {
      Lexeme::Char(pc) => write!(
        f,
        "unexpected character '{}' at position {}",
        pc.char_ref().display(),
        pc.position_ref(),
      ),
      Lexeme::Range(span) => write!(f, "unexpected characters at {}", span,),
    }
  }
}

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

impl<Char, Hint, O> core::ops::Deref for UnexpectedLexeme<Char, Hint, O> {
  type Target = Lexeme<Char, O>;

  #[cfg_attr(not(tarpaulin), inline(always))]
  fn deref(&self) -> &Self::Target {
    &self.lexeme
  }
}

impl<Char, Hint, O> core::ops::DerefMut for UnexpectedLexeme<Char, Hint, O> {
  #[cfg_attr(not(tarpaulin), inline(always))]
  fn deref_mut(&mut self) -> &mut Self::Target {
    &mut self.lexeme
  }
}

impl<Char, O> UnexpectedLexeme<Char, LineTerminator, O> {
  /// Creates a new `UnexpectedLineTerminator` from a lexeme and line terminator hint.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::{Lexeme, PositionedChar, knowledge::LineTerminator}};
  ///
  /// let error = UnexpectedLexeme::new_line(5, '\n');
  ///
  /// assert_eq!(*error.hint(), LineTerminator::NewLine);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new_line(pos: O, ch: Char) -> Self {
    Self::from_char(pos, ch, LineTerminator::NewLine)
  }

  /// Creates a new unexpected carriage return error.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::{Lexeme, PositionedChar, knowledge::LineTerminator}};
  ///
  /// let error = UnexpectedLexeme::carriage_return(5, '\r');
  ///
  /// assert_eq!(*error.hint(), LineTerminator::CarriageReturn);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn carriage_return(pos: O, ch: Char) -> Self {
    Self::from_char(pos, ch, LineTerminator::CarriageReturn)
  }

  /// Creates a new unexpected carriage return + newline error.
  ///
  /// ## Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::{SimpleSpan, knowledge::LineTerminator}};
  ///
  /// let error = UnexpectedLexeme::<char, _>::carriage_return_new_line((5..7).into());
  ///
  /// assert_eq!(*error.hint(), LineTerminator::CarriageReturnNewLine);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn carriage_return_new_line(span: SimpleSpan<O>) -> Self {
    Self::from_range_const(span, LineTerminator::CarriageReturnNewLine)
  }
}

impl<Char, Hint, O> UnexpectedLexeme<Char, Hint, O> {
  /// Creates a new `UnexpectedLexeme` from a lexeme and hint.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::{Lexeme, PositionedChar}};
  ///
  /// let lexeme = Lexeme::from(PositionedChar::with_position('!', 5));
  /// let error = UnexpectedLexeme::new(lexeme, "identifier");
  ///
  /// assert_eq!(*error.hint(), "identifier");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(lexeme: Lexeme<Char, O>, hint: Hint) -> Self {
    Self { lexeme, hint }
  }

  /// Constructs an error from a position, character and hint.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::error::UnexpectedLexeme;
  ///
  /// let error = UnexpectedLexeme::from_char(
  ///     42,
  ///     '$',
  ///     "alphanumeric character"
  /// );
  ///
  /// assert!(error.is_char());
  /// assert_eq!(error.unwrap_char().position(), 42);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn from_char(pos: O, ch: Char, hint: Hint) -> Self {
    Self::from_positioned_char(PositionedChar::with_position(ch, pos), hint)
  }

  /// Constructs an error from a positioned character and hint.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('$', 42),
  ///     "alphanumeric character"
  /// );
  ///
  /// assert!(error.is_char());
  /// assert_eq!(error.unwrap_char().position(), 42);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn from_positioned_char(pc: PositionedChar<Char, O>, hint: Hint) -> Self {
    Self::new(Lexeme::Char(pc), hint)
  }

  /// Constructs an error from a byte span and hint (const version).
  ///
  /// Use this in const contexts where `Into<SimpleSpan>` conversions aren't available.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::SimpleSpan};
  ///
  /// let error: UnexpectedLexeme<char, _> = UnexpectedLexeme::from_range_const(
  ///     SimpleSpan::new(10, 15),
  ///     "semicolon"
  /// );
  ///
  /// assert!(error.is_range());
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn from_range_const(span: SimpleSpan<O>, hint: Hint) -> Self {
    Self::new(Lexeme::Range(span), hint)
  }

  /// Constructs an error from a byte span and hint.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::error::UnexpectedLexeme;
  ///
  /// let error: UnexpectedLexeme<char, _> = UnexpectedLexeme::from_range(10..15, "closing brace");
  ///
  /// assert!(error.is_range());
  /// assert_eq!(error.unwrap_range().start(), 10);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn from_range(span: impl Into<SimpleSpan<O>>, hint: Hint) -> Self {
    Self::new(Lexeme::Range(span.into()), hint)
  }

  /// Returns a reference to the lexeme.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('x', 5),
  ///     "digit"
  /// );
  ///
  /// assert!(error.lexeme().is_char());
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn lexeme(&self) -> &Lexeme<Char, O> {
    &self.lexeme
  }

  /// Returns a reference to the hint.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('x', 5),
  ///     "expected digit"
  /// );
  ///
  /// assert_eq!(*error.hint(), "expected digit");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn hint(&self) -> &Hint {
    &self.hint
  }

  /// Returns a mutable reference to the lexeme.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let mut error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('x', 5),
  ///     "digit"
  /// );
  ///
  /// error.lexeme_mut().bump(10);
  /// assert_eq!(error.unwrap_char().position(), 15);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn lexeme_mut(&mut self) -> &mut Lexeme<Char, O> {
    &mut self.lexeme
  }

  /// Returns a mutable reference to the hint.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let mut error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('x', 5),
  ///     String::from("digit")
  /// );
  ///
  /// error.hint_mut().push_str(" or letter");
  /// assert_eq!(error.hint(), "digit or letter");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn hint_mut(&mut self) -> &mut Hint {
    &mut self.hint
  }

  /// Consumes self and returns the lexeme and hint as a tuple.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('!', 10),
  ///     "identifier"
  /// );
  ///
  /// let (lexeme, hint) = error.into_components();
  /// assert!(lexeme.is_char());
  /// assert_eq!(hint, "identifier");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_components(self) -> (Lexeme<Char, O>, Hint) {
    (self.lexeme, self.hint)
  }

  /// Consumes self and returns only the lexeme.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('!', 10),
  ///     "identifier"
  /// );
  ///
  /// let lexeme = error.into_lexeme();
  /// assert!(lexeme.is_char());
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_lexeme(self) -> Lexeme<Char, O> {
    self.lexeme
  }

  /// Consumes self and returns only the hint.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('!', 10),
  ///     "identifier"
  /// );
  ///
  /// let hint = error.into_hint();
  /// assert_eq!(hint, "identifier");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_hint(self) -> Hint {
    self.hint
  }

  /// Returns the byte span covered by this lexeme using a custom length function.
  ///
  /// This delegates to [`Lexeme::span_with`].
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('€', 5),
  ///     "ASCII character"
  /// );
  ///
  /// let span = error.span_with(|c: &char| c.len_utf8());
  /// assert_eq!(span.start(), 5);
  /// assert_eq!(span.end(), 8); // '€' is 3 bytes
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn span_with(&self, len_of: impl FnOnce(&Char) -> usize) -> SimpleSpan<O>
  where
    O: Clone + Ord,
    for<'a> &'a O: Add<usize, Output = O>,
  {
    self.lexeme.span_with(len_of)
  }

  /// Returns the byte span covered by this lexeme.
  ///
  /// This delegates to [`Lexeme::span`].
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::{PositionedChar, SimpleSpan}};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('x', 10),
  ///     "digit"
  /// );
  ///
  /// assert_eq!(error.span(), SimpleSpan::new(10, 11));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn span(&self) -> SimpleSpan<O>
  where
    Char: CharLen,
    O: Clone + Ord,
    for<'a> &'a O: Add<usize, Output = O>,
  {
    self.lexeme.span()
  }

  /// Maps the character type to another type, preserving the hint.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('a', 5),
  ///     "digit"
  /// );
  ///
  /// let upper = error.map_char(|c| c.to_ascii_uppercase());
  /// assert_eq!(upper.unwrap_char().char(), 'A');
  /// assert_eq!(*upper.hint(), "digit");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn map_char<F, NewChar>(self, f: F) -> UnexpectedLexeme<NewChar, Hint, O>
  where
    F: FnMut(Char) -> NewChar,
  {
    UnexpectedLexeme {
      lexeme: self.lexeme.map(f),
      hint: self.hint,
    }
  }

  /// Maps the hint type to another type, preserving the lexeme.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('!', 5),
  ///     "digit"
  /// );
  ///
  /// let detailed = error.map_hint(|h| format!("expected {}", h));
  /// assert_eq!(detailed.hint(), "expected digit");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn map_hint<F, NewHint>(self, f: F) -> UnexpectedLexeme<Char, NewHint, O>
  where
    F: FnOnce(Hint) -> NewHint,
  {
    UnexpectedLexeme {
      lexeme: self.lexeme,
      hint: f(self.hint),
    }
  }

  /// Maps both the character and hint types to other types.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('a', 5),
  ///     "number"
  /// );
  ///
  /// let transformed = error.map(
  ///     |c| c.to_ascii_uppercase(),
  ///     |h| format!("expected {}", h)
  /// );
  ///
  /// assert_eq!(transformed.unwrap_char().char(), 'A');
  /// assert_eq!(transformed.hint(), "expected number");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn map<F, NewChar, G, NewHint>(self, f: F, g: G) -> UnexpectedLexeme<NewChar, NewHint, O>
  where
    F: FnMut(Char) -> NewChar,
    G: FnOnce(Hint) -> NewHint,
  {
    UnexpectedLexeme {
      lexeme: self.lexeme.map(f),
      hint: g(self.hint),
    }
  }

  /// Adjusts the lexeme's position/span by adding `n` bytes.
  ///
  /// Returns a mutable reference to self for method chaining.
  ///
  /// # Example
  ///
  /// ```rust
  /// use tokit::{error::UnexpectedLexeme, utils::PositionedChar};
  ///
  /// let mut error = UnexpectedLexeme::from_positioned_char(
  ///     PositionedChar::with_position('x', 5),
  ///     "digit"
  /// );
  ///
  /// error.bump(10);
  /// assert_eq!(error.unwrap_char().position(), 15);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn bump(&mut self, n: &O) -> &mut Self
  where
    O: for<'a> AddAssign<&'a O> + Clone,
  {
    self.lexeme.bump(n);
    self
  }
}