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
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
//! A module consists of lexeme utilities
//! which analyze string slices at incremental positions of the input and create tokens.
//!
//! A tokenizer is essential for processing input string or language before feeding into a parser.
//! A parser written using a parser generator, implement a tokenizer which is usually defined based on a regular language.
//! And the parser generator will compile the grammar in the target runtime language.
//! However, this tokenizer implementation is based on lexeme utilities which are responsible to use a regular expression to process and tokenize input string.
//! Moreover, this library is equipped with advanced lexeme utilities that are customizable according to the requirement of language syntax.
//!
//! # Example
//!
//! In this section, we will be implementing a tokenizer to tokenize JSON input.
//!
//! We need to create token types which will be returned alongside the tokenized data.
//! The token type should implement [TokenImpl](crate::TokenImpl) to be used by the [Tokenizer](crate::Tokenizer).
//! Custom implementation for [TokenImpl](crate::TokenImpl) trait has been added to primitive types [i8], [i16], and [isize].
//!
//! However, we will be implementing custom types to return as a stream of tokens.
//!
//! ```
//! use lang_pt::Code;
//! use lang_pt::{
//! lexeme::{Pattern, Punctuations},
//! TokenImpl, Tokenizer,
//! };
//! use lang_pt::{ITokenization, Lex};
//! use std::rc::Rc;
//!
//! #[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Clone, Copy)]
//! enum JSONToken {
//! EOF,
//! String,
//! Space,
//! Colon,
//! Comma,
//! Number,
//! Constant,
//! OpenBrace,
//! CloseBrace,
//! OpenBracket,
//! CloseBracket,
//! }
//!
//! impl TokenImpl for JSONToken {
//! fn eof() -> Self { JSONToken::EOF }
//! fn is_structural(&self) -> bool {
//! match self {
//! JSONToken::Space => false,
//! _ => true,
//! }
//! }
//! }
//! let punctuations = Rc::new(
//! Punctuations::new(vec![
//! ("{", JSONToken::OpenBrace),
//! ("}", JSONToken::CloseBrace),
//! ("[", JSONToken::OpenBracket),
//! ("]", JSONToken::CloseBracket),
//! (",", JSONToken::Comma),
//! (":", JSONToken::Colon),
//! ])
//! .unwrap(),
//! );
//!
//! let dq_string = Rc::new(
//! Pattern::new(
//! JSONToken::String,
//! r#"^"([^"\\\r\n]|(\\[^\S\r\n]*[\r\n][^\S\r\n]*)|\\.)*""#, //["\\bfnrtv]
//! )
//! .unwrap(),
//! );
//!
//! let lex_space = Rc::new(Pattern::new(JSONToken::Space, r"^\s+").unwrap());
//! let number_literal = Rc::new(
//! Pattern::new(JSONToken::Number, r"^([0-9]+)(\.[0-9]+)?([eE][+-]?[0-9]+)?").unwrap(),
//! );
//! let const_literal = Rc::new(Pattern::new(JSONToken::Constant, r"^(true|false|null)").unwrap());
//!
//! let tokenizer = Tokenizer::new(vec![
//! lex_space,
//! punctuations,
//! dq_string,
//! number_literal,
//! const_literal,
//! ]);
//!
//! let tokens1 = tokenizer
//! .tokenize(&Code::from(r#"{"a":34,"b":null}"#))
//! .unwrap();
//!
//! assert_eq!(
//! tokens1,
//! vec![
//! Lex { token: JSONToken::OpenBrace, start: 0, end: 1 },
//! Lex { token: JSONToken::String, start: 1, end: 4 },
//! Lex { token: JSONToken::Colon, start: 4, end: 5 },
//! Lex { token: JSONToken::Number, start: 5, end: 7 },
//! Lex { token: JSONToken::Comma, start: 7, end: 8 },
//! Lex { token: JSONToken::String, start: 8, end: 11 },
//! Lex { token: JSONToken::Colon, start: 11, end: 12 },
//! Lex { token: JSONToken::Constant, start: 12, end: 16 },
//! Lex { token: JSONToken::CloseBrace, start: 16, end: 17 },
//! Lex { token: JSONToken::EOF, start: 17, end: 17 }
//! ]
//! );
//!
//! ```
//!
use crate::;
use OnceCell;
use Regex;
use ;
/// An enum variants to represent tokenization state action.
///
/// [Action] is used by lexeme utilities [StateMixin] and [ThunkStateMixin] to change the stack state
/// so that [CombinedTokenizer](super::CombinedTokenizer) switch to different set of lexeme utilities to tokenize part of the input string.
/// A regular expression based lexeme utility.
///
/// Provided regex expression will be matched at incremental position of the input utf-8 bytes string and return tokenized result.
/// The provided regular expression should be enforce to match string from the beginning i.e. expression should implement start of string (^) match.
///
/// # Example
/// ```
/// use lang_pt::{lexeme::Pattern, Code, ITokenization, Lex, TokenImpl, Tokenizer};
/// use std::rc::Rc;
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
/// enum Token {
/// ID,
/// Space,
/// EOF,
/// }
/// impl TokenImpl for Token {
/// fn eof() -> Self { Self::EOF }
/// fn is_structural(&self) -> bool { self != &Self::Space }
/// }
/// let identifier = Pattern::new(Token::ID, r#"^[_$a-zA-Z][_$\w]*"#).unwrap();
/// let space = Pattern::new(Token::Space, r#"^\s+"#).unwrap();
///
/// let tokenizer = Tokenizer::new(vec![Rc::new(identifier), Rc::new(space)]);
/// let lex_stream = tokenizer.tokenize(&Code::from("abc xy")).unwrap();
/// assert_eq!(
/// lex_stream,
/// vec![
/// Lex { token: Token::ID, start: 0, end: 3 },
/// Lex { token: Token::Space, start: 3, end: 4 },
/// Lex { token: Token::ID, start: 4, end: 6 },
/// Lex { token: Token::EOF, start: 6, end: 6 },
/// ]
/// );
/// ```
/// A lexer utility to match a set of constant values like punctuations, operators etc.
///
/// Match punctuation values at the incremental position of the input and return tokenized result.
/// This lexeme utility will create a tree structure from utf-8 values of the provided punctuation.
/// The input utf-8 values will be match with each node of the tree return associated token value if complete match is found.
///
/// # Example
/// ```
/// use lang_pt::{
/// lexeme::{Pattern, Punctuations},
/// Code,
/// ITokenization, Lex, TokenImpl, Tokenizer,
/// };
/// use std::rc::Rc;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// enum Token {
/// ID,
/// Space,
/// Add,
/// Subtract,
/// PlusPlus,
/// MinusMinus,
/// EOF,
/// }
///
/// impl TokenImpl for Token {
/// fn eof() -> Self { Self::EOF }
/// fn is_structural(&self) -> bool { *self != Self::EOF }
/// }
///
/// let space = Pattern::new(Token::Space, r#"^\s+"#).unwrap();
/// let identifier = Pattern::new(Token::ID, r#"^[_$a-zA-Z][_$\w]*"#).unwrap();
/// let punctuations: Punctuations<Token> = Punctuations::new(vec![
/// ("+", Token::Add),
/// ("++", Token::PlusPlus),
/// ("--", Token::MinusMinus),
/// ("-", Token::Subtract),
/// ])
/// .unwrap();
///
/// let tokenizer = Tokenizer::new(vec![
/// Rc::new(punctuations),
/// Rc::new(space),
/// Rc::new(identifier),
/// ]);
/// let lex = tokenizer.tokenize(&Code::from("a+++b")).unwrap();
/// assert_eq!(
/// lex,
/// vec![
/// Lex { token: Token::ID, start: 0, end: 1 },
/// Lex { token: Token::PlusPlus, start: 1, end: 3 },
/// Lex { token: Token::Add, start: 3, end: 4 },
/// Lex { token: Token::ID, start: 4, end: 5 },
/// Lex { token: Token::EOF, start: 5, end: 5 }
/// ]
/// );
/// let lex = tokenizer.tokenize(&Code::from("a+ ++b")).unwrap();
/// assert_eq!(
/// lex,
/// vec![
/// Lex { token: Token::ID, start: 0, end: 1 },
/// Lex { token: Token::Add, start: 1, end: 2 },
/// Lex { token: Token::Space, start: 2, end: 3 },
/// Lex { token: Token::PlusPlus, start: 3, end: 5 },
/// Lex { token: Token::ID, start: 5, end: 6 },
/// Lex { token: Token::EOF, start: 6, end: 6 }
/// ]
/// );
/// ```
/// A lexer utility to match a set of string values like keywords, and constant values.
///
/// All the provided string values will be matched sequentially with the input string at the incremental positions
/// and the corresponding token value will be returned as token data.
/// A lexical utility that transforms tokenized data based on the mapped string fields.
///
/// The associated lexeme utility will first be matched with the input string.
/// Once the associated lexeme utility successfully obtains token data,
/// it will then look for the appropriate token value for the tokenized string part of the input.
/// If no match is found for the corresponding tokenized string part, the original tokenized data will be returned.
/// # Example
/// ```
/// use lang_pt::{
/// lexeme::{Mapper, Pattern},
/// Code,
/// ITokenization, Lex, TokenImpl, Tokenizer,
/// };
/// use std::rc::Rc;
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// enum Token {
/// ID,
/// IF,
/// ELSE,
/// FOR,
/// Space,
/// True,
/// False,
/// EOF,
/// }
///
/// impl TokenImpl for Token {
/// fn eof() -> Self { Self::EOF }
/// fn is_structural(&self) -> bool { *self != Self::EOF }
/// }
/// let id_lexer: Pattern<Token> = Pattern::new(Token::ID, r#"^[_$a-zA-Z][_$\w]*"#).unwrap();
/// let space = Pattern::new(Token::Space, r#"^\s+"#).unwrap();
///
/// let mapped_lexer = Mapper::new(
/// id_lexer,
/// vec![
/// ("if", Token::IF),
/// ("else", Token::ELSE),
/// ("for", Token::FOR),
/// ("true", Token::True),
/// ("false", Token::False),
/// ],
/// )
/// .unwrap();
///
/// let tokenizer = Tokenizer::new(vec![Rc::new(mapped_lexer), Rc::new(space)]);
/// let lex_stream = tokenizer.tokenize(&Code::from("abc xy")).unwrap();
///
/// assert_eq!(
/// lex_stream,
/// vec![
/// Lex { token: Token::ID, start: 0, end: 3 },
/// Lex { token: Token::Space, start: 3, end: 4 },
/// Lex { token: Token::ID, start: 4, end: 6 },
/// Lex { token: Token::EOF, start: 6, end: 6 }
/// ]
/// );
/// let lex = tokenizer.tokenize(&Code::from("if true")).unwrap();
/// assert_eq!(
/// lex,
/// vec![
/// Lex { token: Token::IF, start: 0, end: 2 },
/// Lex { token: Token::Space, start: 2, end: 3 },
/// Lex { token: Token::True, start: 3, end: 7 },
/// Lex { token: Token::EOF, start: 7, end: 7 }
/// ]
/// );
///
/// ```
/// A lexical utility which transform tokenized data based on the provided closure function.
///
/// It is similar to [Mapper] however, optional transformed token will be received by executing the associated closure function,
/// The tokenizer will received original token if [None] value returned from the closure.
/// # Example
/// ```
/// use lang_pt::{
/// lexeme::{Pattern, ThunkMapper},
/// Code,
/// ITokenization, Lex, TokenImpl, Tokenizer,
/// };
/// use std::{io::BufRead, rc::Rc};
///
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// enum Token {
/// InlineComment,
/// MultilineComment,
/// EOF,
/// }
/// impl TokenImpl for Token {
/// fn eof() -> Self { Self::EOF }
/// fn is_structural(&self) -> bool { *self != Self::EOF }
/// }
/// let comment: Pattern<Token> = Pattern::new(Token::InlineComment, r#"^/\*(.|\n)*?\*/"#).unwrap();
///
/// let comment_variants = ThunkMapper::new(comment, |data, code, _| {
/// if code[data.start..data.end].lines().count() > 1 {
/// Some(Token::MultilineComment)
/// } else {
/// None
/// }
/// });
///
/// let tokenizer = Tokenizer::new(vec![Rc::new(comment_variants)]);
/// let inline_comment = "/*This is inline comment*/";
/// let inline_comment_tokens = tokenizer.tokenize(&Code::from(inline_comment)).unwrap();
/// assert_eq!(
/// inline_comment_tokens,
/// vec![
/// Lex { token: Token::InlineComment, start: 0, end: inline_comment.len() },
/// Lex { token: Token::EOF, start: inline_comment.len(), end: inline_comment.len() }
/// ]
/// );
/// let multiline_comment = "/*This is first line\n.Another line comment*/";
/// let multiline_comment_tokens = tokenizer.tokenize(&Code::from(multiline_comment)).unwrap();
/// assert_eq!(
/// multiline_comment_tokens,
/// vec![
/// Lex { token: Token::MultilineComment, start: 0, end: multiline_comment.len() },
/// Lex { token: Token::EOF, start: multiline_comment.len(), end: multiline_comment.len() }
/// ]
/// );
///
/// ```
/// A lexeme utility which will try to tokenize the input once associated middleware function returns truthy.
///
/// The closure function will be executed before creating token by the associated lexeme utility.
/// # Example
/// ```
/// use lang_pt::{
/// lexeme::{Middleware, Pattern, Punctuations},
/// Code,
/// ITokenization, Lex, TokenImpl, Tokenizer,
/// };
/// use std::rc::Rc;
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// enum Token {
/// RegexLiteral,
/// ID,
/// Number,
/// Add,
/// Mul,
/// Div,
/// Assign,
/// Subtract,
/// EOF,
/// }
/// impl TokenImpl for Token {
/// fn eof() -> Self { Self::EOF }
/// fn is_structural(&self) -> bool { *self != Self::EOF }
/// }
/// let identifier = Rc::new(Pattern::new(Token::ID, r#"^[_$a-zA-Z][_$\w]*"#).unwrap());
/// let number_literal =
/// Rc::new(Pattern::new(Token::Number, r"^(0|[\d--0]\d*)(\.\d+)?([eE][+-]?\d+)?").unwrap());
///
/// let punctuations = Rc::new(
/// Punctuations::new(vec![
/// ("+", Token::Add),
/// ("*", Token::Mul),
/// ("/", Token::Div),
/// ("=", Token::Assign),
/// ("-", Token::Subtract),
/// ])
/// .unwrap(),
/// );
///
/// let regex_literal =
/// Pattern::new(Token::RegexLiteral, r"^/([^\\/\r\n\[]|\\.|\[[^]]+\])+/").unwrap();
///
/// let validated_regex_literal = Rc::new(Middleware::new(regex_literal, |_, lex_stream| {
/// lex_stream.last().map_or(false, |d| match d.token {
/// Token::ID | Token::Number => false,
/// _ => true,
/// })
/// }));
///
/// let tokenizer = Tokenizer::new(vec![
/// identifier,
/// number_literal,
/// validated_regex_literal, // Should appear before punctuation so that regex literal is validated before div '/'.
/// punctuations,
/// ]);
///
/// let lex = tokenizer.tokenize(&Code::from("2/xy/6")).unwrap();
/// assert_eq!(
/// lex,
/// [
/// Lex { token: Token::Number, start: 0, end: 1 },
/// Lex { token: Token::Div, start: 1, end: 2 },
/// Lex { token: Token::ID, start: 2, end: 4 },
/// Lex { token: Token::Div, start: 4, end: 5 },
/// Lex { token: Token::Number, start: 5, end: 6 },
/// Lex { token: Token::EOF, start: 6, end: 6 },
/// ]
/// );
/// let regex_lex = tokenizer.tokenize(&&Code::from("a=/xy/")).unwrap();
/// assert_eq!(
/// regex_lex,
/// [
/// Lex { token: Token::ID, start: 0, end: 1 },
/// Lex { token: Token::Assign, start: 1, end: 2 },
/// Lex { token: Token::RegexLiteral, start: 2, end: 6 },
/// Lex { token: Token::EOF, start: 6, end: 6 },
/// ]
/// );
/// ```
/// A lexeme utility to modify state stack base on the provided [Action] corresponding to the tokens.
///
/// Once the associated lexeme utility create a token,
/// the utility will change the state stack based on [Action] for the state based [tokenizer](crate::CombinedTokenizer).
///
/// # Example
///
/// ```
/// use lang_pt::{
/// lexeme::{Action, Pattern, Punctuations, StateMixin},
/// Code,
/// CombinedTokenizer, ITokenization, Lex, TokenImpl,
/// };
/// use std::rc::Rc;
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// enum Token {
/// ID,
/// Number,
/// Add,
/// Assign,
/// Subtract,
/// EOF,
/// TemplateTick,
/// TemplateExprStart,
/// TemplateString,
/// OpenBrace,
/// CloseBrace,
/// }
/// impl TokenImpl for Token {
/// fn eof() -> Self { Self::EOF }
/// fn is_structural(&self) -> bool { *self != Self::EOF }
/// }
/// const MAIN: u8 = 0;
/// const TEMPLATE: u8 = 1;
/// let identifier = Rc::new(Pattern::new(Token::ID, r#"^[_$a-zA-Z][_$\w]*"#).unwrap());
/// let number_literal =
/// Rc::new(Pattern::new(Token::Number, r"^(0|[\d--0]\d*)(\.\d+)?([eE][+-]?\d+)?").unwrap());
///
/// let expression_punctuation = Punctuations::new(vec![
/// ("+", Token::Add),
/// ("-", Token::Subtract),
/// ("=", Token::Assign),
/// ("{", Token::OpenBrace),
/// ("}", Token::CloseBrace),
/// ("`", Token::TemplateTick),
/// ])
/// .unwrap();
///
/// let expr_punctuation_mixin = Rc::new(StateMixin::new(
/// expression_punctuation,
/// vec![
/// (Token::TemplateTick, Action::append(TEMPLATE, false)), // Encountering a TemplateTick (`) indicates beginning of template literal.
/// // While tokenizing in the template literal expression we are going to augment stack to keep track of open and close brace.
/// (Token::OpenBrace, Action::append(MAIN, false)),
/// (Token::CloseBrace, Action::remove(false)),
/// ],
/// ));
///
/// let lex_template_string: Rc<Pattern<Token>> = Rc::new(
/// Pattern::new(
/// Token::TemplateString,
/// r"^([^`\\$]|\$[^{^`\\$]|\\[${`bfnrtv])+",
/// )
/// .unwrap(),
/// );
///
/// let template_punctuations = Punctuations::new(vec![
/// ("`", Token::TemplateTick),
/// ("${", Token::TemplateExprStart),
/// ])
/// .unwrap();
/// let template_punctuation_mixin = StateMixin::new(
/// template_punctuations,
/// vec![
/// (Token::TemplateTick, Action::remove(false)), // Encountering TemplateTick (`) indicates end of template literal state.
/// (Token::TemplateExprStart, Action::append(MAIN, false)),
/// ],
/// );
///
/// let mut combined_tokenizer = CombinedTokenizer::new(
/// MAIN,
/// vec![identifier, number_literal, expr_punctuation_mixin],
/// );
/// combined_tokenizer.add_state(
/// TEMPLATE,
/// vec![Rc::new(template_punctuation_mixin), lex_template_string],
/// );
///
/// let token_stream = combined_tokenizer
/// .tokenize(&Code::from("d=`Sum is ${a+b}`"))
/// .unwrap();
/// debug_assert_eq!(
/// token_stream,
/// vec![
/// Lex::new(Token::ID, 0, 1),
/// Lex::new(Token::Assign, 1, 2),
/// Lex::new(Token::TemplateTick, 2, 3),
/// Lex::new(Token::TemplateString, 3, 10),
/// Lex::new(Token::TemplateExprStart, 10, 12,),
/// Lex::new(Token::ID, 12, 13),
/// Lex::new(Token::Add, 13, 14),
/// Lex::new(Token::ID, 14, 15),
/// Lex::new(Token::CloseBrace, 15, 16),
/// Lex::new(Token::TemplateTick, 16, 17),
/// Lex::new(Token::EOF, 17, 17),
/// ]
/// );
///
/// ```
/// A lexeme utility to modify state stack based on [Action] received from the closure function.
///
/// This similar to [StateMixin] however, [Action] is received from the closure function.
/// # Example
/// ```
/// use lang_pt::{
/// lexeme::{Action, Pattern, Punctuations, ThunkStateMixin},
/// Code,
/// ITokenization, Lex, TokenImpl, Tokenizer,
/// };
/// use std::rc::Rc;
/// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// enum Token {
/// RegexLiteral,
/// ID,
/// Number,
/// Add,
/// Mul,
/// Div,
/// Assign,
/// Subtract,
/// EOF,
/// }
/// impl TokenImpl for Token {
/// fn eof() -> Self { Self::EOF }
/// fn is_structural(&self) -> bool { *self != Self::EOF }
/// }
/// let identifier = Rc::new(Pattern::new(Token::ID, r#"^[_$a-zA-Z][_$\w]*"#).unwrap());
/// let number_literal =
/// Rc::new(Pattern::new(Token::Number, r"^(0|[\d--0]\d*)(\.\d+)?([eE][+-]?\d+)?").unwrap());
///
/// let punctuations = Punctuations::new(vec![
/// ("+", Token::Add),
/// ("*", Token::Mul),
/// ("/", Token::Div),
/// ("=", Token::Assign),
/// ("-", Token::Subtract),
/// ])
/// .unwrap();
///
/// let punctuation_mixin = Rc::new(ThunkStateMixin::new(
/// punctuations,
/// |lex_data, _code, stream| {
/// if lex_data.token == Token::Div {
/// let is_expr_continuation =
/// stream
/// .last()
/// .map_or(false, |pre_data| match pre_data.token {
/// Token::ID | Token::Number => true,
/// _ => false,
/// });
/// Action::None {
/// discard: !is_expr_continuation,
/// } // If the symbol '/' immediately after id or number it is a div element.
/// // Otherwise discard the lexeme if it is part of regex expression
/// } else {
/// Action::None { discard: false }
/// }
/// },
/// ));
///
/// let regex_literal =
/// Rc::new(Pattern::new(Token::RegexLiteral, r"^/([^\\/\r\n\[]|\\.|\[[^]]+\])+/").unwrap());
///
/// let tokenizer = Tokenizer::new(vec![
/// identifier,
/// number_literal,
/// punctuation_mixin,
/// regex_literal, // Should appear after punctuation so that it will be checked once div '/' is rejected.
/// ]);
///
/// let lex = tokenizer.tokenize(&Code::from("2/xy/6")).unwrap();
/// assert_eq!(
/// lex,
/// [
/// Lex { token: Token::Number, start: 0, end: 1 },
/// Lex { token: Token::Div, start: 1, end: 2 },
/// Lex { token: Token::ID, start: 2, end: 4 },
/// Lex { token: Token::Div, start: 4, end: 5 },
/// Lex { token: Token::Number, start: 5, end: 6 },
/// Lex { token: Token::EOF, start: 6, end: 6 },
/// ]
/// );
/// let regex_lex = tokenizer.tokenize(&Code::from("a=/xy/")).unwrap();
/// assert_eq!(
/// regex_lex,
/// [
/// Lex { token: Token::ID, start: 0, end: 1 },
/// Lex { token: Token::Assign, start: 1, end: 2 },
/// Lex { token: Token::RegexLiteral, start: 2, end: 6 },
/// Lex { token: Token::EOF, start: 6, end: 6 },
/// ]
/// );
///
/// ```
/// A trait implementation utility to convert one lexeme utility to another higher order lexeme utility.
///
/// The trait is implemented for generic [ILexeme] types.
/// Therefore, the associated methods are available for all utilities which implement [ILexeme] trait.