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
//! This module defines the [`Lexer`] and [`Token`] traits that lay the
//! groundwork for parsing with Gramatika. In this documentation, we'll look at
//! some less trivial `Token` examples and explore how the generated lexer
//! tokenizes input.
//!
//! ## Defining a token
//!
//! Each variant of your `Token` enum should be a tuple variant wrapping a
//! [`Substr`] and [`Span`]:
//! ```
//! #[macro_use]
//! extern crate gramatika;
//!
//! # fn main() {
//! use gramatika::{Span, Substr};
//!
//! #[derive(Token, Lexer, PartialEq)]
//! enum Token {
//! #    #[discard]
//! #    #[pattern = "//.*"]
//! #    LineComment(Substr, Span),
//! #
//! #    #[discard]
//! #    #[multiline]
//! #    #[pattern = r"/\*.*?\*/"]
//! #    BlockComment(Substr, Span),
//! #
//! #    #[subset_of(Ident)]
//! #    #[pattern = "if|else|switch|case|break|for|while|var|print"]
//! #    Keyword(Substr, Span),
//! #
//! #    #[pattern = "[a-zA-Z_][a-zA-Z_0-9]*"]
//!     Ident(Substr, Span),
//! #
//! #    #[pattern = r"[(){}\[\]]"]
//! #    Brace(Substr, Span),
//! #
//! #    #[pattern = "[,.;]"]
//! #    Punct(Substr, Span),
//! #
//! #    #[pattern = "[=!<>]=?"]
//! #    #[pattern = "[-+*/]"]
//! #    Operator(Substr, Span),
//! #
//! #    #[pattern = "(0[xb])?[0-9A-Fa-f][0-9A-Fa-f.]*"]
//! #    NumLiteral(Substr, Span),
//! #
//! #    #[pattern = r#""[^"]+""#]
//! #    StrLiteral(Substr, Span),
//! }
//! # }
//! ```
//! * The [`Substr`] portion (which we'll refer to as the _lexeme_) is an atomic
//!   reference-counted view into the original source string, provided by the
//!   [`arcstr`] crate. These can be `clone`d for very little cost, because only
//!   the pointer to the original string is copied, not the underlying string
//!   itself.
//!
//!   ```
//!   # use gramatika::{ArcStr, Substr};
//!   let source = ArcStr::from("foo bar baz");
//!   {
//!       let foo = source.substr(..3);
//!       let baz = source.substr(8..);
//!
//!       assert_eq!(foo, "foo");
//!       assert_eq!(baz, "baz");
//!       assert!(ArcStr::ptr_eq(foo.parent(), baz.parent()));
//!       assert_eq!(ArcStr::strong_count(&source), Some(3));
//!   }
//!   assert_eq!(ArcStr::strong_count(&source), Some(1));
//!   ```
//!
//! * The [`Span`] indicates the token's location in the original source
//!   document by line and character number.
//!
//!   It's important to note that while the actual values stored in the `Span`
//!   are zero-indexed, printing the `Span` with the `Debug` trait will display
//!   _one-indexed_ values to match the conventions of most code and text
//!   editors.
//!
//!   ```
//!   # use gramatika::Span;
//!   let span = Span::new((0, 0), (0, 4));
//!   let printed = format!("{span:?}");
//!   assert_eq!(printed, "1:1..1:5");
//!   ```
//!
//! When the `Token` and [`Spanned`] traits are in scope, the lexeme and span
//! can be extracted from a `Token` without needing to pattern-match. You can
//! also grab them both in one go with the generated `as_inner` method.
//!
//! ```
//! #[macro_use]
//! extern crate gramatika;
//!
//! # fn main() {
//! use gramatika::{Span, Spanned, Substr, Token as _, span};
//!
//! #[derive(Token, Lexer, PartialEq)]
//! enum Token {
//!     Ident(Substr, Span),
//! }
//!
//! let my_ident = Token::Ident("foo".into(), span![1:1..1:4]);
//!
//! assert_eq!(my_ident.lexeme(), "foo");
//! assert_eq!(my_ident.span(), span![1:1..1:4]);
//!
//! let (lexeme, span) = my_ident.as_inner();
//! assert_eq!(lexeme, my_ident.lexeme());
//! assert_eq!(span, my_ident.span());
//! # }
//! ```
//!
//! ### Debug and Display
//!
//! It's a good idea to derive [`DebugLispToken`] for the enum, and implement
//! both [`Debug`](core::fmt::Debug) and [`Display`](core::fmt::Display):
//!
//! ```
//! #[macro_use]
//! extern crate gramatika;
//!
//! # fn main() {
//! use core::fmt;
//! use gramatika::{Span, Spanned, Substr, Token as _, span};
//!
//! #[derive(Token, Lexer, DebugLispToken, PartialEq)]
//! enum Token {
//!     Ident(Substr, Span),
//! }
//!
//! impl fmt::Display for Token {
//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//!         write!(f, "{}", self.lexeme())
//!     }
//! }
//!
//! impl fmt::Debug for Token {
//!     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//!         <Self as gramatika::DebugLisp>::fmt(self, f, 0)
//!     }
//! }
//!
//! let my_ident = Token::Ident("foo".into(), span![1:1..1:4]);
//!
//! let display = format!("{my_ident}");
//! assert_eq!(display, "foo");
//!
//! let debug = format!("{my_ident:?}");
//! assert_eq!(debug, "`foo` (Ident (1:1..1:4))");
//! # }
//! ```
//! [`DebugLispToken`]: gramatika_macro::DebugLispToken
//!
//! ## Configuring the Lexer
//!
//! The real power of Gramatika comes from its lexer generator. Let's define a
//! pattern for our identifier token:
//!
//! ```
//! # #[macro_use]
//! # extern crate gramatika;
//! #
//! # fn main() {
//! # use core::fmt;
//! # use gramatika::{Span, Spanned, Substr, Token as _, span};
//! #
//! // ...
//! #[derive(Token, Lexer, DebugLispToken, PartialEq)]
//! enum Token {
//!     #[pattern = "[a-zA-Z_][a-zA-Z_0-9]*"]
//!     Ident(Substr, Span),
//! }
//! #
//! # impl fmt::Display for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         write!(f, "{}", self.lexeme())
//! #     }
//! # }
//! #
//! # impl fmt::Debug for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         <Self as gramatika::DebugLisp>::fmt(self, f, 0)
//! #     }
//! # }
//!
//! let input = "
//!     foo bar baz
//!     foobar
//!     loremIpsum
//!     dolor_sit_amet
//! ";
//! let mut lexer = Lexer::new(input.into());
//! let tokens = lexer.scan();
//!
//! assert_eq!(tokens.len(), 6);
//! assert_eq!(&tokens[0], &Token::Ident("foo".into(), span![2:5..2:8]));
//! assert_eq!(&tokens[5], &Token::Ident("dolor_sit_amet".into(), span![5:5..5:19]));
//! # }
//! ```
//!
//! The `#[pattern]` attribute accepts the same syntax and features as the Rust
//! [`regex` crate]. Those patterns are compiled to [deterministic finite automata]
//!  and used by the generated lexer to find token matches in an input string.
//!
//! [`regex` crate]: https://docs.rs/regex/latest/regex/
//! [deterministic finite automata]: https://swtch.com/~rsc/regexp/regexp1.html
//!
//! ### Unrecognized input
//!
//! If the lexer receives any input that it doesn't know how to handle, it
//! panics. That's not ideal, so to avoid that we'll define a catch-all
//! `Unrecognized` token that eats up all non-whitespace characters. Our
//! [`Parse`] implementations can then handle those gracefully by emitting a
//! useful error message for the user.
//!
//! [`Parse`]: crate::Parse
//!
//! ```
//! # #[macro_use]
//! # extern crate gramatika;
//! #
//! # fn main() {
//! # use core::fmt;
//! # use gramatika::{Span, Spanned, Substr, Token as _, span};
//! #
//! // ...
//! #[derive(Token, Lexer, DebugLispToken, PartialEq)]
//! enum Token {
//!     #[pattern = "[a-zA-Z_][a-zA-Z_0-9]*"]
//!     Ident(Substr, Span),
//!
//!     #[pattern = r"\S+"]
//!     Unrecognized(Substr, Span),
//! }
//! #
//! # impl fmt::Display for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         write!(f, "{}", self.lexeme())
//! #     }
//! # }
//! #
//! # impl fmt::Debug for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         <Self as gramatika::DebugLisp>::fmt(self, f, 0)
//! #     }
//! # }
//!
//! let input = "foo 42";
//! let mut lexer = Lexer::new(input.into());
//! let tokens = lexer.scan();
//!
//! assert_eq!(tokens.len(), 2);
//! assert_eq!(&tokens[0], &Token::Ident("foo".into(), span![1:1..1:4]));
//! assert_eq!(&tokens[1], &Token::Unrecognized("42".into(), span![1:5..1:7]));
//! # }
//! ```
//!
//! ### Discarding input
//!
//! Often we want to _recognize_ some input, especially input that might be
//! valid at any location in a source file, without needing to manually deal
//! with those tokens in our [`Parse`] implementations. Essentially, we want to
//! _discard_ that input. The lexer automatically does thie by default for
//! whitespace characters, but we can expand that functionality to any other
//! syntax that we want to ignore completely:
//!
//! ```
//! # #[macro_use]
//! # extern crate gramatika;
//! #
//! # fn main() {
//! # use core::fmt;
//! # use gramatika::{Span, Spanned, Substr, Token as _, span};
//! #
//! // ...
//! #[derive(Token, Lexer, DebugLispToken, PartialEq)]
//! enum Token {
//!     #[discard]
//!     #[pattern = "//.*"]
//!     Comment(Substr, Span),
//!     // ...
//! #     #[pattern = "[a-zA-Z_][a-zA-Z_0-9]*"]
//! #     Ident(Substr, Span),
//! #     #[pattern = r"\S+"]
//! #     Unrecognized(Substr, Span),
//! }
//! #
//! # impl fmt::Display for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         write!(f, "{}", self.lexeme())
//! #     }
//! # }
//! #
//! # impl fmt::Debug for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         <Self as gramatika::DebugLisp>::fmt(self, f, 0)
//! #     }
//! # }
//!
//! let input = "
//!     // Here's a comment
//!     foo // Here's another one
//! ";
//!
//! let mut lexer = Lexer::new(input.into());
//! let tokens = lexer.scan();
//!
//! assert_eq!(tokens.len(), 1);
//! assert_eq!(&tokens[0], &Token::Ident("foo".into(), span![3:5..3:8]));
//! # }
//! ```
//!
//! ### Matching tokens across multiple lines
//!
//! We may also want to define some tokens that can span multiple lines, but by
//! default a regular expression's `.` doesn't match newline characters. We can
//! change that by adding the `#[multiline]` attribute:
//!
//! ```
//! # #[macro_use]
//! # extern crate gramatika;
//! #
//! # fn main() {
//! # use core::fmt;
//! # use gramatika::{Span, Spanned, Substr, Token as _, span};
//! #
//! // ...
//! #[derive(Token, Lexer, DebugLispToken, PartialEq)]
//! enum Token {
//!     #[discard]
//!     #[multiline]
//!     #[pattern = r"/\*.*?\*/"]
//!     BlockComment(Substr, Span),
//!
//!     #[discard]
//!     #[pattern = "//.*"]
//!     LineComment(Substr, Span),
//!     // ...
//! #     #[pattern = "[a-zA-Z_][a-zA-Z_0-9]*"]
//! #     Ident(Substr, Span),
//! #     #[pattern = r"\S+"]
//! #     Unrecognized(Substr, Span),
//! }
//! #
//! # impl fmt::Display for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         write!(f, "{}", self.lexeme())
//! #     }
//! # }
//! #
//! # impl fmt::Debug for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         <Self as gramatika::DebugLisp>::fmt(self, f, 0)
//! #     }
//! # }
//!
//! let input = "
//!     /*
//!     Here's a block comment.
//!     It can span as many lines as we please!
//!     */
//!     foo // Here's a line comment
//! ";
//!
//! let mut lexer = Lexer::new(input.into());
//! let tokens = lexer.scan();
//!
//! assert_eq!(tokens.len(), 1);
//! assert_eq!(&tokens[0], &Token::Ident("foo".into(), span![6:5..6:8]));
//! # }
//! ```
//! ### Matching keywords
//!
//! Keywords are a tricky thing, because they will almost certainly overlap with
//! your language's "identifier" token. The matching of tokens is prioritized by
//! declaration order from top to bottom, so you might think we could just
//! declare our `Keyword` token first, but that has an unfortunate consequence:
//!
//! ```
//! # #[macro_use]
//! # extern crate gramatika;
//! #
//! # fn main() {
//! # use core::fmt;
//! # use gramatika::{Span, Spanned, Substr, Token as _, span};
//! #
//! // ...
//! #[derive(Token, Lexer, DebugLispToken, PartialEq)]
//! enum Token {
//!     #[pattern = "if|else|for|in|switch|case|break"]
//!     Keyword(Substr, Span),
//!
//!     #[pattern = "[a-zA-Z_][a-zA-Z_0-9]*"]
//!     Ident(Substr, Span),
//! #
//! #     #[pattern = r"\S+"]
//! #     Unrecognized(Substr, Span),
//! }
//! #
//! # impl fmt::Display for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         write!(f, "{}", self.lexeme())
//! #     }
//! # }
//! #
//! # impl fmt::Debug for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         <Self as gramatika::DebugLisp>::fmt(self, f, 0)
//! #     }
//! # }
//!
//! let input = "
//!     for foo in bar
//!         intent
//! ";
//!
//! let mut lexer = Lexer::new(input.into());
//! let tokens = lexer.scan();
//!
//! assert_eq!(tokens, vec![
//!     Token::Keyword("for".into(), span![2:5..2:8]),
//!     Token::Ident("foo".into(),   span![2:9..2:12]),
//!     Token::Keyword("in".into(),  span![2:13..2:15]),
//!     Token::Ident("bar".into(),   span![2:16..2:19]),
//!     // Wait a minute, this is not what we wanted!
//!     Token::Keyword("in".into(),  span![3:9..3:11]),
//!     Token::Ident("tent".into(),  span![3:11..3:15]),
//! ]);
//! # }
//! ```
//!
//! To fix that, we can use the `#[subset_of(Other)]` attribute to specify that
//! a token's pattern overlaps with `Other`'s pattern, and should only match if
//! `Other`'s _entire lexeme_ is _also_ a match for the subset.
//!
//! ```
//! # #[macro_use]
//! # extern crate gramatika;
//! #
//! # fn main() {
//! # use core::fmt;
//! # use gramatika::{Span, Spanned, Substr, Token as _, span};
//! #
//! // ...
//! #[derive(Token, Lexer, DebugLispToken, PartialEq)]
//! enum Token {
//!     #[subset_of(Ident)]
//!     #[pattern = "if|else|for|in|switch|case|break"]
//!     Keyword(Substr, Span),
//!
//!     #[pattern = "[a-zA-Z_][a-zA-Z_0-9]*"]
//!     Ident(Substr, Span),
//! #
//! #     #[pattern = r"\S+"]
//! #     Unrecognized(Substr, Span),
//! }
//! #
//! # impl fmt::Display for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         write!(f, "{}", self.lexeme())
//! #     }
//! # }
//! #
//! # impl fmt::Debug for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         <Self as gramatika::DebugLisp>::fmt(self, f, 0)
//! #     }
//! # }
//!
//! let input = "
//!     for foo in bar
//!         intent
//! ";
//!
//! let mut lexer = Lexer::new(input.into());
//! let tokens = lexer.scan();
//!
//! assert_eq!(tokens, vec![
//!     Token::Keyword("for".into(),  span![2:5..2:8]),
//!     Token::Ident("foo".into(),    span![2:9..2:12]),
//!     Token::Keyword("in".into(),   span![2:13..2:15]),
//!     Token::Ident("bar".into(),    span![2:16..2:19]),
//!     // That's better!
//!     Token::Ident("intent".into(), span![3:9..3:15]),
//! ]);
//! # }
//! ```
//!
//! ### Composing complex patterns
//!
//! Regular expressions are not known for their readability in the best of
//! circumstances, but that's especially true for long patterns with lots of
//! "or" branches. We can define multiple `#[pattern]` attributes for a single
//! token to _compose_ those patterns into a single regular expression:
//!
//! ```
//! # #[macro_use]
//! # extern crate gramatika;
//! #
//! # fn main() {
//! # use core::fmt;
//! # use gramatika::{Span, Spanned, Substr, Token as _, span};
//! #
//! // ...
//! #[derive(Token, Lexer, DebugLispToken, PartialEq)]
//! enum Token {
//!     #[pattern = r"[0-9]*\.[0-9]+"]
//!     #[pattern = r"[0-9]+\.[0-9]*"]
//!     FloatLiteral(Substr, Span),
//! #
//! #     #[pattern = r"\S+"]
//! #     Unrecognized(Substr, Span),
//! }
//! #
//! # impl fmt::Display for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         write!(f, "{}", self.lexeme())
//! #     }
//! # }
//! #
//! # impl fmt::Debug for Token {
//! #     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
//! #         <Self as gramatika::DebugLisp>::fmt(self, f, 0)
//! #     }
//! # }
//!
//! let input = "
//!     3.141
//!     .25
//!     50.
//! ";
//!
//! let mut lexer = Lexer::new(input.into());
//! let tokens = lexer.scan();
//!
//! assert_eq!(tokens, vec![
//!     Token::FloatLiteral("3.141".into(), span![2:5..2:10]),
//!     Token::FloatLiteral(".25".into(),   span![3:5..3:8]),
//!     Token::FloatLiteral("50.".into(),   span![4:5..4:8]),
//! ]);
//! # }
//! ```
//! The pattern above is exactly equivalent to `[0-9]*\.[0-9]+|[0-9]+\.[0-9]*`,
//! but by putting them on separate lines we can more easily tell the difference
//! between them (the first makes the digits _before_ the `.` optional, while
//! the second does the same for digits _after_ the `.`).
//!

use std::fmt;

use arcstr::{ArcStr, Substr};

use crate::{Span, Spanned};

/// A lexer (AKA scanner, AKA tokenizer) is the piece of the parsing toolchain
/// that takes raw input (e.g., the text of a source file) and "scans" it into
/// discrete chunks of meaningful information (i.e., [tokens]).
///
/// In Gramatika, [parsing] is usually performed on a stream of tokens that are
/// scanned on-demand by a compile-time-generated type implementing this trait.
/// Except perhaps for unit-testing, you should rarely need to interact with the
/// lexer directly.
///
/// [tokens]: crate::Token
/// [parsing]: crate::parse
pub trait Lexer {
	/// The concrete type of [`Token`] this lexer should scan.
	type Output: Token;

	/// Create a new lexer that can scan the provided `input` to a stream of
	/// [`Output`] tokens.
	///
	/// [`Output`]: Lexer::Output
	fn new(input: ArcStr) -> Self;

	/// Experimental
	#[doc(hidden)]
	#[allow(unused_variables)]
	fn with_runtime_matcher<F>(self, matcher: F) -> Self
	where
		Self: Sized,
		F: Fn(&str) -> Option<(usize, <Self::Output as Token>::Kind)> + 'static,
	{
		self
	}

	/// Returns an owned copy of the input [`ArcStr`] this lexer is scanning.
	fn source(&self) -> ArcStr;

	/// Scans a single token from the input.
	///
	/// The implementation generated by the [`derive macro`] does this lazily,
	/// only checking the input for a match when this method is called, and
	/// stopping as soon as the first match is (or isn't) found.
	///
	/// [`derive macro`]: gramatika_macro::Lexer
	fn scan_token(&mut self) -> Option<Self::Output>;

	/// Eagerly scans the entire input to an array of tokens.
	///
	/// Most of the time you'll want to use [`scan_token`] instead to _stream_
	/// tokens from the input on an as-needed basis.
	///
	/// [`scan_token`]: Lexer::scan_token
	fn scan(&mut self) -> Vec<Self::Output> {
		let mut result = vec![];
		while let Some(token) = self.scan_token() {
			result.push(token);
		}
		result
	}
}

/// In the parlance of language parsing, "tokens" are the smallest discrete
/// chunks of meaningful information that can be extracted from some raw input,
/// like the text of a source file.
///
/// If the individual characters of that text are thought of as _atoms_, then
/// its "tokens" could be considered the _molecules_: words, punctuation marks,
/// mathematical operators, etc.
///
/// In Gramatika, this trait is usually [derived] (along with its [`Lexer`]) for
/// some user-defined enum type, with regular-expression patterns specifying
/// the forms that can be taken by each of its variants. See the
/// [module-level documentation] for (much) more detail.
///
/// [derived]: gramatika_macro::Token
/// [module-level documentation]: crate::lexer
pub trait Token
where Self: Clone + Spanned
{
	type Kind: fmt::Debug + PartialEq;

	/// Returns the actual text content of a token.
	///
	/// ```
	/// #[macro_use]
	/// extern crate gramatika;
	///
	/// use gramatika::{
	///     arcstr::literal_substr,
	///     Substr, Span, Token as _,
	/// };
	///
	/// # fn main() {
	/// #[derive(Token, Lexer)]
	/// enum Token {
	///     #[subset_of(Ident)]
	///     #[pattern = "var"]
	///     Keyword(Substr, Span),
	///
	///     #[pattern = "[a-zA-Z_][a-zA-Z0-9_]*"]
	///     Ident(Substr, Span),
	///
	///     #[pattern = "[0-9]+"]
	///     IntLiteral(Substr, Span),
	///
	///     #[pattern = "="]
	///     Operator(Substr, Span),
	///
	///     #[pattern = ";"]
	///     Punct(Substr, Span),
	/// }
	///
	/// let src = "var the_answer = 42;";
	/// let tokens = Lexer::new(src.into()).scan();
	///
	/// assert_eq!(tokens[1].lexeme(), literal_substr!("the_answer"));
	/// # }
	/// ```
	fn lexeme(&self) -> Substr;

	/// Returns the [`Kind`] of this token. Used in [`ParseStreamer`] methods like
	/// [`check_kind`] and [`consume_kind`]. Effectively a more user-friendly version of
	/// [`std::mem::discriminant`].
	///
	/// [`Kind`]: Token::Kind
	/// [`ParseStreamer`]: crate::parse::ParseStreamer
	/// [`check_kind`]: crate::parse::ParseStreamer::check_kind
	/// [`consume_kind`]: crate::parse::ParseStreamer::consume_kind
	///
	/// ```
	/// #[macro_use]
	/// extern crate gramatika;
	///
	/// use gramatika::{Substr, Span, Token as _};
	///
	/// # fn main() {
	/// #[derive(Token, Lexer)]
	/// enum Token {
	///     #[pattern = "[a-zA-Z_][a-zA-Z0-9_]*"]
	///     Ident(Substr, Span),
	/// }
	///
	/// let input = "foo";
	/// let token = Lexer::new(input.into())
	///     .scan_token()
	///     .expect("Expected to match Ident `foo`");
	///
	/// assert_eq!(token.kind(), TokenKind::Ident);
	/// # }
	/// ```
	fn kind(&self) -> Self::Kind;

	/// Decomposes the token into its constituent [`Kind`], [`lexeme`] and
	/// [`Span`]) parts, with the `lexeme` as a [`&str`] slice for compatibility
	/// with pattern matching.
	///
	/// [`Kind`]: Token::Kind
	/// [`lexeme`]: Token::lexeme
	/// [`span`]: crate::Span
	/// [`&str`]: prim@str
	///
	/// ```
	/// #[macro_use]
	/// extern crate gramatika;
	///
	/// use gramatika::{Substr, Span, Token as _};
	///
	/// # fn main() {
	/// #[derive(Token, Lexer)]
	/// enum Token {
	///     #[pattern = "[a-zA-Z_][a-zA-Z0-9_]*"]
	///     Ident(Substr, Span),
	/// }
	///
	/// let input = "foo";
	/// let token = Lexer::new(input.into())
	///     .scan_token()
	///     .expect("Expected to match Ident `foo`");
	///
	/// assert!(matches!(token.as_matchable(), (TokenKind::Ident, "foo", _)));
	/// # }
	/// ```
	fn as_matchable(&self) -> (Self::Kind, &str, Span);
}