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
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
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
//! Unexpected token error type for parser error reporting.
//!
//! This module provides the [`UnexpectedToken`] type, which represents parser errors
//! when an unexpected token is encountered. It captures both the location of the error,
//! what token was found (if any), and what tokens were expected.
//!
//! # Design Philosophy
//!
//! `UnexpectedToken` is designed to provide rich, actionable error messages:
//! - **Location tracking**: The `span` field pinpoints exactly where the error occurred
//! - **Optional found token**: Distinguishes between unexpected tokens and end-of-input
//! - **Flexible expectations**: Can express single or multiple alternative expected tokens
//! - **Position adjustment**: The `bump()` method allows adjusting error positions when
//!   combining errors from different parsing contexts
//!
//! # Common Patterns
//!
//! ## End of Input Errors
//!
//! When the parser reaches the end of input unexpectedly, use constructors without a found token:
//!
//! ```
//! use tokit::{utils::SimpleSpan, error::UnexpectedToken};
//!
//! // Simple end-of-input error
//! let error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one(
//!     SimpleSpan::new(100, 100),
//!     "}"
//! );
//! assert_eq!(format!("{}", error), "unexpected end of input, expected '}'");
//! ```
//!
//! ## Unexpected Token Errors
//!
//! When a specific token was found but something else was expected:
//!
//! ```
//! use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
//!
//! let error = UnexpectedToken::expected_one_with_found(
//!     SimpleSpan::new(10, 15),
//!     "else",
//!     "if"
//! );
//! assert_eq!(format!("{}", error), "unexpected token 'else', expected 'if'");
//! ```

use core::marker::PhantomData;

use crate::{
  error::token::{Leading, Repeated, Trailing},
  utils::{Expected, SimpleSpan},
};

pub use unexpected_leading::*;
pub use unexpected_repeated::*;
pub use unexpected_trailing::*;

mod unexpected_leading;
mod unexpected_repeated;
mod unexpected_trailing;

/// An error representing an unexpected token encountered during parsing.
///
/// This error type captures the location (span), what token was found (if any),
/// and what token(s) were expected. It's commonly used in parsers to provide
/// detailed error messages when the input doesn't match the expected syntax.
///
/// # Type Parameters
///
/// * `T` - The type of the actual token that was found
/// * `Kind` - The type of the expected token (often an enum of token kinds)
///
/// # Examples
///
/// ```
/// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
///
/// // Error when expecting a specific token but got something else
/// let error = UnexpectedToken::expected_one_with_found(
///     SimpleSpan::new(10, 15),
///     "}",
///     "{"
/// );
/// assert_eq!(error.span(), SimpleSpan::new(10, 15));
/// assert_eq!(format!("{}", error), "unexpected token '}', expected '{'");
///
/// // Error when expecting one of multiple tokens
/// let error = UnexpectedToken::expected_one_of_with_found(
///     SimpleSpan::new(0, 10),
///     "identifier",
///     &["if", "while", "for"]
/// );
/// assert_eq!(
///     format!("{}", error),
///     "unexpected token 'identifier', expected one of: 'if', 'while', 'for'"
/// );
///
/// // Error when reaching end of input unexpectedly
/// let error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one(
///     SimpleSpan::new(100, 100),
///     "}"
/// );
/// assert_eq!(format!("{}", error), "unexpected end of input, expected '}'");
/// ```
#[derive(Copy, Clone, PartialEq, Eq, Hash)]
pub struct UnexpectedToken<'a, T, Kind, S = SimpleSpan, Lang: ?Sized = ()> {
  span: S,
  found: Option<T>,
  expected: Option<Expected<'a, Kind>>,
  _lang: PhantomData<Lang>,
}

// Allow unit to be used as an error sink for tests and no-op emitters.
impl<'a, T, Kind, S, Lang: ?Sized> From<UnexpectedToken<'a, T, Kind, S, Lang>> for () {
  #[cfg_attr(not(tarpaulin), inline(always))]
  fn from(_: UnexpectedToken<'a, T, Kind, S, Lang>) -> Self {}
}

impl<T, Kind, S, Data> UnexpectedToken<'_, T, Kind, S, Trailing<Data>> {
  /// Creates a new `UnexpectedToken` error indicating a trailing token was found.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn trailing(span: S, found: T) -> Self {
    Self::trailing_of(span, found)
  }
}

impl<T, Kind, S, Data> UnexpectedToken<'_, T, Kind, S, Leading<Data>> {
  /// Creates a new `UnexpectedToken` error indicating a trailing token was found.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn leading(span: S, found: T) -> Self {
    Self::leading_of(span, found)
  }
}

impl<T, Kind, S, Data> UnexpectedToken<'_, T, Kind, S, Repeated<Data>> {
  /// Creates a new `UnexpectedToken` error indicating a repeated token was found.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn repeated(span: S, found: T) -> Self {
    Self::repeated_of(span, found)
  }
}

impl<T, Kind, S, Data, Lang: ?Sized> UnexpectedToken<'_, T, Kind, S, Trailing<Data, Lang>> {
  /// Creates a new `UnexpectedToken` error indicating a trailing token was found.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn trailing_of(span: S, found: T) -> Self {
    Self::new_in(span, Some(found), None)
  }
}

impl<T, Kind, S, Data, Lang: ?Sized> UnexpectedToken<'_, T, Kind, S, Leading<Data, Lang>> {
  /// Creates a new `UnexpectedToken` error indicating a trailing token was found.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn leading_of(span: S, found: T) -> Self {
    Self::new_in(span, Some(found), None)
  }
}

impl<T, Kind, S, Data, Lang: ?Sized> UnexpectedToken<'_, T, Kind, S, Repeated<Data, Lang>> {
  /// Creates a new `UnexpectedToken` error indicating a repeated token was found.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn repeated_of(span: S, found: T) -> Self {
    Self::new_in(span, Some(found), None)
  }
}

impl<'a, T, Kind, S> UnexpectedToken<'a, T, Kind, S> {
  /// Creates a new unexpected token error.
  ///
  /// This error indicates that an unexpected token was encountered,
  /// without specifying what token was found or expected.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn new(span: S) -> Self {
    Self::of(span)
  }

  /// Creates an unexpected token error without a found token.
  ///
  /// This is useful when the parser reaches the end of input unexpectedly.
  /// The error will indicate "unexpected end of input" in its display message.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::new(
  ///     SimpleSpan::new(100, 101),
  ///     Expected::one("}")
  /// );
  /// assert!(error.found().is_none());
  /// assert_eq!(error.span(), SimpleSpan::new(100, 101));
  /// assert_eq!(format!("{}", error), "unexpected end of input, expected '}'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_expected(span: S, expected: Expected<'a, Kind>) -> Self {
    Self::with_expected_of(span, expected)
  }

  /// Creates an unexpected token error without a found token.
  ///
  /// This is useful when the parser reaches the end of input unexpectedly.
  /// The error will indicate "unexpected end of input" in its display message.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::maybe_expected_of(
  ///     SimpleSpan::new(100, 101),
  ///     Some(Expected::one("}"))
  /// );
  /// assert!(error.found().is_none());
  /// assert_eq!(error.span(), SimpleSpan::new(100, 101));
  /// assert_eq!(format!("{}", error), "unexpected end of input, expected '}'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn maybe_expected(span: S, expected: Option<Expected<'a, Kind>>) -> Self {
    Self::maybe_expected_of(span, expected)
  }
}

impl<'a, T, Kind, S, Lang: ?Sized> UnexpectedToken<'a, T, Kind, S, Lang> {
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub(super) const fn new_in(
    span: S,
    found: Option<T>,
    expected: Option<Expected<'a, Kind>>,
  ) -> Self {
    Self {
      span,
      found,
      expected,
      _lang: PhantomData,
    }
  }

  /// Creates a new unexpected token error.
  ///
  /// This error indicates that an unexpected token was encountered,
  /// without specifying what token was found or expected.
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn of(span: S) -> Self {
    Self::new_in(span, None, None)
  }

  /// Creates an unexpected token error without a found token.
  ///
  /// This is useful when the parser reaches the end of input unexpectedly.
  /// The error will indicate "unexpected end of input" in its display message.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::new(
  ///     SimpleSpan::new(100, 101),
  ///     Expected::one("}")
  /// );
  /// assert!(error.found().is_none());
  /// assert_eq!(error.span(), SimpleSpan::new(100, 101));
  /// assert_eq!(format!("{}", error), "unexpected end of input, expected '}'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn with_expected_of(span: S, expected: Expected<'a, Kind>) -> Self {
    Self::new_in(span, None, Some(expected))
  }

  /// Creates an unexpected token error without a found token.
  ///
  /// This is useful when the parser reaches the end of input unexpectedly.
  /// The error will indicate "unexpected end of input" in its display message.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::maybe_expected_of(
  ///     SimpleSpan::new(100, 101),
  ///     Some(Expected::one("}"))
  /// );
  /// assert!(error.found().is_none());
  /// assert_eq!(error.span(), SimpleSpan::new(100, 101));
  /// assert_eq!(format!("{}", error), "unexpected end of input, expected '}'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn maybe_expected_of(span: S, expected: Option<Expected<'a, Kind>>) -> Self {
    Self::new_in(span, None, expected)
  }

  /// Creates a new unexpected token error with a single expected token.
  ///
  /// This is a convenience method that combines `new` with `Expected::one`.
  /// The error has no found token, indicating the end of input was reached.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::SimpleSpan, error::UnexpectedToken};
  ///
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one(
  ///     SimpleSpan::new(50, 51),
  ///     ";"
  /// );
  /// assert!(error.found().is_none());
  /// assert_eq!(format!("{}", error), "unexpected end of input, expected ';'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn expected_one(span: S, expected: Kind) -> Self {
    Self::with_expected_of(span, Expected::one(expected))
  }

  /// Creates a new unexpected token error with a single expected token.
  ///
  /// This is a convenience method that combines `new` with `Expected::one`.
  /// The error has no found token, indicating the end of input was reached.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::SimpleSpan, error::UnexpectedToken};
  ///
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one_with_found(
  ///     SimpleSpan::new(50, 51),
  ///     ":",
  ///     ";"
  /// );
  /// assert!(error.found().is_some());
  /// assert_eq!(format!("{}", error), "unexpected token ':', expected ';'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn expected_one_with_found(span: S, found: T, expected: Kind) -> Self {
    Self::new_in(span, Some(found), Some(Expected::one(expected)))
  }

  /// Creates a new unexpected token error with multiple expected tokens.
  ///
  /// This is a convenience method that combines `new` with `Expected::one_of`.
  /// The error has no found token, indicating the end of input was reached.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::SimpleSpan, error::UnexpectedToken};
  ///
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one_of(
  ///     SimpleSpan::new(25, 26),
  ///     &["+", "-", "*", "/"]
  /// );
  /// assert!(error.found().is_none());
  /// assert_eq!(
  ///     format!("{}", error),
  ///     "unexpected end of input, expected one of: '+', '-', '*', '/'"
  /// );
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn expected_one_of(span: S, expected: &'static [Kind]) -> Self {
    Self::with_expected_of(span, Expected::one_of(expected))
  }

  /// Creates a new unexpected token error with multiple expected tokens.
  ///
  /// This is a convenience method that combines `new` with `Expected::one_of`.
  /// The error has no found token, indicating the end of input was reached.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::SimpleSpan, error::UnexpectedToken};
  ///
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one_of_with_found(
  ///     SimpleSpan::new(25, 26),
  ///     ":",
  ///     &["+", "-", "*", "/"]
  /// );
  /// assert!(!error.found().is_none());
  /// assert_eq!(
  ///     format!("{}", error),
  ///     "unexpected token ':', expected one of: '+', '-', '*', '/'"
  /// );
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn expected_one_of_with_found(span: S, found: T, expected: &'static [Kind]) -> Self {
    Self::new_in(span, Some(found), Some(Expected::one_of(expected)))
  }

  /// Creates a new unexpected token error with an optional found token.
  ///
  /// This is the most general constructor. When `found` is `None`, the error
  /// indicates the end of input was reached. When `found` is `Some`, it indicates
  /// an unexpected token was encountered.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// // With a found token
  /// let error = UnexpectedToken::expected_one(
  ///     SimpleSpan::new(10, 14),
  ///     "if"
  /// ).maybe_found(Some("else"));
  /// assert_eq!(error.found(), Some(&"else"));
  /// assert_eq!(format!("{}", error), "unexpected token 'else', expected 'if'");
  ///
  /// // Without a found token (end of input)
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one(
  ///     SimpleSpan::new(50, 50),
  ///     "if"
  /// ).maybe_found(None);
  /// assert_eq!(error.found(), None);
  /// assert_eq!(format!("{}", error), "unexpected end of input, expected 'if'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn maybe_found(mut self, found: Option<T>) -> Self {
    self.found = found;
    self
  }

  /// Creates a new unexpected token error with an optional found token.
  ///
  /// This is the most general constructor. When `found` is `None`, the error
  /// indicates the end of input was reached. When `found` is `Some`, it indicates
  /// an unexpected token was encountered.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// // With a found token
  /// let error = UnexpectedToken::expected_one(
  ///     SimpleSpan::new(10, 14),
  ///     "if"
  /// ).maybe_found_const(Some("else"));
  /// assert_eq!(error.found(), Some(&"else"));
  /// assert_eq!(format!("{}", error), "unexpected token 'else', expected 'if'");
  ///
  /// // Without a found token (end of input)
  /// let error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one(
  ///     SimpleSpan::new(50, 50),
  ///     "if"
  /// ).maybe_found_const(None);
  /// assert_eq!(error.found(), None);
  /// assert_eq!(format!("{}", error), "unexpected end of input, expected 'if'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn maybe_found_const(mut self, found: Option<T>) -> Self
  where
    T: Copy,
  {
    self.found = found;
    self
  }

  /// Creates a new unexpected token error with a found token.
  ///
  /// This indicates that a specific token was encountered when a different
  /// token (or one of several alternative tokens) was expected.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error = UnexpectedToken::expected_one(
  ///     SimpleSpan::new(5, 10),
  ///     "fn"
  /// ).with_found("class");
  /// assert_eq!(error.found(), Some(&"class"));
  /// assert_eq!(format!("{}", error), "unexpected token 'class', expected 'fn'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_found(mut self, found: T) -> Self {
    self.found = Some(found);
    self
  }

  /// Creates a new unexpected token error with a found token.
  ///
  /// This indicates that a specific token was encountered when a different
  /// token (or one of several alternative tokens) was expected.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error = UnexpectedToken::expected_one(
  ///     SimpleSpan::new(5, 10),
  ///     "fn"
  /// ).with_found_const("class");
  /// assert_eq!(error.found(), Some(&"class"));
  /// assert_eq!(format!("{}", error), "unexpected token 'class', expected 'fn'");
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn with_found_const(mut self, found: T) -> Self
  where
    T: Copy,
  {
    self.found = Some(found);
    self
  }

  /// Returns the span of the unexpected token.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error = UnexpectedToken::expected_one_with_found(
  ///     SimpleSpan::new(10, 15),
  ///     "identifier",
  ///     "number"
  /// );
  /// assert_eq!(error.span(), SimpleSpan::new(10, 15));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span(&self) -> S
  where
    S: Copy,
  {
    self.span
  }

  /// Returns the span of the unexpected token.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error = UnexpectedToken::expected_one_with_found(
  ///     SimpleSpan::new(10, 15),
  ///     "identifier",
  ///     "number"
  /// );
  /// assert_eq!(error.span_ref(), &SimpleSpan::new(10, 15));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_ref(&self) -> &S {
    &self.span
  }

  /// Returns a mutable reference to the span of the unexpected token.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let mut error = UnexpectedToken::expected_one_with_found(
  ///    SimpleSpan::new(10, 15),
  ///   "identifier",
  ///   "number"
  /// );
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 20));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn span_mut(&mut self) -> &mut S {
    &mut self.span
  }

  /// Returns a reference to the found token, if any.
  ///
  /// Returns `None` if the error represents an unexpected end of input.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error = UnexpectedToken::expected_one_with_found(
  ///     SimpleSpan::new(0, 10),
  ///     "identifier",
  ///     "number"
  /// );
  /// assert_eq!(error.found(), Some(&"identifier"));
  ///
  /// let eof_error: UnexpectedToken<&str, &str> = UnexpectedToken::expected_one(
  ///     SimpleSpan::new(100, 100),
  ///     "}"
  /// );
  /// assert_eq!(eof_error.found(), None);
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn found(&self) -> Option<&T> {
    self.found.as_ref()
  }

  /// Returns a reference to the expected token(s).
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error = UnexpectedToken::expected_one_with_found(
  ///     SimpleSpan::new(5, 6),
  ///     "}",
  ///     "{"
  /// );
  /// assert_eq!(*error.expected(), Expected::one("{"));
  /// if let Expected::One(value) = error.expected() {
  ///     assert_eq!(*value, "{");
  /// }
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub const fn expected(&self) -> Option<&Expected<'a, Kind>> {
    self.expected.as_ref()
  }

  /// Bumps both the start and end positions of the span by the given offset.
  ///
  /// This is useful when adjusting error positions after processing or
  /// when combining spans from different contexts.
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let mut error = UnexpectedToken::expected_one_with_found(
  ///     SimpleSpan::new(10, 15),
  ///     "}",
  ///     "{"
  /// );
  /// error.bump(5);
  /// assert_eq!(error.span(), SimpleSpan::new(15, 20));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn bump(&mut self, offset: &S::Offset)
  where
    S: crate::lexer::Span,
  {
    self.span.bump(offset);
  }

  /// Maps the expected token(s) using the provided function.
  ///
  /// This is useful for transforming the expected token type while preserving
  /// the rest of the error information.
  ///
  /// ## Examples
  ///
  /// ```
  /// # #[cfg(feature = "std")] {
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error = UnexpectedToken::expected_one_with_found(
  ///    SimpleSpan::new(0, 5),
  ///   "identifier",
  ///   "number"
  /// );
  /// let mapped_error = error.map_expected(|expected| {
  ///     // Transform the expected token type here
  ///     Expected::one(expected.unwrap_one().to_string())
  /// });
  /// # }
  /// ```
  pub fn map_expected<F, Kind2>(self, f: F) -> UnexpectedToken<'a, T, Kind2, S>
  where
    F: FnOnce(Expected<'a, Kind>) -> Expected<'a, Kind2>,
  {
    UnexpectedToken {
      span: self.span,
      found: self.found,
      expected: self.expected.map(f),
      _lang: PhantomData,
    }
  }

  /// Consumes the error and returns its components.
  ///
  /// This method deconstructs the error into its constituent parts:
  /// the span, the found token (if any), and the expected token(s).
  ///
  /// # Examples
  ///
  /// ```
  /// use tokit::{utils::{Expected, SimpleSpan}, error::UnexpectedToken};
  ///
  /// let error = UnexpectedToken::expected_one_with_found(
  ///     SimpleSpan::new(5, 6),
  ///     "}",
  ///     "{"
  /// );
  /// let (span, found, expected) = error.into_components();
  /// assert_eq!(span, SimpleSpan::new(5, 6));
  /// assert_eq!(found, Some("}"));
  /// assert_eq!(expected, Expected::one("{"));
  /// ```
  #[cfg_attr(not(tarpaulin), inline(always))]
  pub fn into_components(self) -> (S, Option<T>, Option<Expected<'a, Kind>>) {
    (self.span, self.found, self.expected)
  }
}

impl<T, Kind, S, Lang: ?Sized> UnexpectedToken<'_, T, Kind, S, Lang>
where
  S: crate::lexer::Span,
{
  /// Creates a debug representation of the unexpected token error.
  pub fn debug_fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result
  where
    T: core::fmt::Debug,
    Kind: core::fmt::Debug,
    S: core::fmt::Debug,
  {
    f.debug_struct("UnexpectedToken")
      .field("span", &self.span)
      .field("found", &self.found)
      .field("expected", &self.expected)
      .finish()
  }

  /// Creates a display representation of the unexpected token error.
  pub fn display_fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result
  where
    T: core::fmt::Display,
    Kind: core::fmt::Display,
  {
    match &self.found {
      Some(found) => match &self.expected {
        Some(expected) => write!(f, "unexpected token '{}', expected {}", found, expected),
        None => write!(f, "unexpected token '{}'", found),
      },
      None => match &self.expected {
        Some(expected) => write!(f, "unexpected token, expected {}", expected),
        None => write!(f, "unexpected token"),
      },
    }
  }
}