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
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
use crate::{
    atom::{trim_bracket_head, Atom},
    visitors::{Visit, VisitMut, Visitor, VisitorMut},
    ShortString,
};

use logos::{Lexer, Logos, Span};
#[cfg(feature = "serde")]
use serde::{Deserialize, Serialize};
use std::{
    cmp::Ordering,
    convert::{TryFrom, TryInto},
    fmt::{self, Display},
};

#[cfg(feature = "roblox")]
use crate::atom::{InterpolatedStringBegin, InterpolatedStringSection};

#[cfg(feature = "roblox")]
pub use crate::tokenizer_luau::InterpolatedStringKind;

#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "serde", serde(rename_all = "lowercase"))]
#[non_exhaustive]
#[allow(missing_docs)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
/// A literal symbol, used for both words important to syntax (like while) and operators (like +)
pub enum Symbol {
    And,
    Break,
    Do,
    Else,
    ElseIf,
    End,
    False,
    For,
    Function,
    If,
    In,
    Local,
    Nil,
    Not,
    Or,
    Repeat,
    Return,
    Then,
    True,
    Until,
    While,

    #[cfg(feature = "lua52")]
    Goto,

    #[cfg_attr(feature = "serde", serde(rename = "+="))]
    PlusEqual,

    #[cfg_attr(feature = "serde", serde(rename = "-="))]
    MinusEqual,

    #[cfg_attr(feature = "serde", serde(rename = "*="))]
    StarEqual,

    #[cfg_attr(feature = "serde", serde(rename = "/="))]
    SlashEqual,

    #[cfg_attr(feature = "serde", serde(rename = "%="))]
    PercentEqual,

    #[cfg_attr(feature = "serde", serde(rename = "^="))]
    CaretEqual,

    #[cfg_attr(feature = "serde", serde(rename = "..="))]
    TwoDotsEqual,

    #[cfg(any(feature = "roblox", feature = "lua53"))]
    #[cfg_attr(feature = "serde", serde(rename = "&"))]
    Ampersand,

    #[cfg(feature = "roblox")]
    #[cfg_attr(feature = "serde", serde(rename = "->"))]
    ThinArrow,

    #[cfg(any(feature = "roblox", feature = "lua52"))]
    #[cfg_attr(feature = "serde", serde(rename = "::"))]
    TwoColons,

    #[cfg_attr(feature = "serde", serde(rename = "^"))]
    Caret,

    #[cfg_attr(feature = "serde", serde(rename = ":"))]
    Colon,

    #[cfg_attr(feature = "serde", serde(rename = ","))]
    Comma,

    #[cfg_attr(feature = "serde", serde(rename = "..."))]
    Ellipse,

    #[cfg_attr(feature = "serde", serde(rename = ".."))]
    TwoDots,

    #[cfg_attr(feature = "serde", serde(rename = "."))]
    Dot,

    #[cfg_attr(feature = "serde", serde(rename = "=="))]
    TwoEqual,

    #[cfg_attr(feature = "serde", serde(rename = "="))]
    Equal,

    #[cfg_attr(feature = "serde", serde(rename = ">="))]
    GreaterThanEqual,

    #[cfg_attr(feature = "serde", serde(rename = ">"))]
    GreaterThan,

    #[cfg(feature = "lua53")]
    #[cfg_attr(feature = "serde", serde(rename = ">>"))]
    DoubleGreaterThan,

    #[cfg_attr(feature = "serde", serde(rename = "#"))]
    Hash,

    #[cfg_attr(feature = "serde", serde(rename = "["))]
    LeftBracket,

    #[cfg_attr(feature = "serde", serde(rename = "{"))]
    LeftBrace,

    #[cfg_attr(feature = "serde", serde(rename = "("))]
    LeftParen,

    #[cfg_attr(feature = "serde", serde(rename = "<="))]
    LessThanEqual,

    #[cfg_attr(feature = "serde", serde(rename = "<"))]
    LessThan,

    #[cfg(feature = "lua53")]
    #[cfg_attr(feature = "serde", serde(rename = "<<"))]
    DoubleLessThan,

    #[cfg_attr(feature = "serde", serde(rename = "-"))]
    Minus,

    #[cfg_attr(feature = "serde", serde(rename = "%"))]
    Percent,

    #[cfg(any(feature = "roblox", feature = "lua53"))]
    #[cfg_attr(feature = "serde", serde(rename = "|"))]
    Pipe,

    #[cfg_attr(feature = "serde", serde(rename = "+"))]
    Plus,

    #[cfg(feature = "roblox")]
    #[cfg_attr(feature = "serde", serde(rename = "?"))]
    QuestionMark,

    #[cfg_attr(feature = "serde", serde(rename = "}"))]
    RightBrace,

    #[cfg_attr(feature = "serde", serde(rename = "]"))]
    RightBracket,

    #[cfg_attr(feature = "serde", serde(rename = ")"))]
    RightParen,

    #[cfg_attr(feature = "serde", serde(rename = ";"))]
    Semicolon,

    #[cfg_attr(feature = "serde", serde(rename = "/"))]
    Slash,

    #[cfg(any(feature = "roblox", feature = "lua53"))]
    #[cfg_attr(feature = "serde", serde(rename = "//"))]
    DoubleSlash,

    #[cfg_attr(feature = "serde", serde(rename = "*"))]
    Star,

    #[cfg(feature = "lua53")]
    #[cfg_attr(feature = "serde", serde(rename = "~"))]
    Tilde,

    #[cfg_attr(feature = "serde", serde(rename = "~="))]
    TildeEqual,
}

impl TryFrom<Atom> for Symbol {
    type Error = ();

    fn try_from(value: Atom) -> Result<Self, Self::Error> {
        Ok(match value {
            Atom::And => Symbol::And,
            Atom::Break => Symbol::Break,
            Atom::Do => Symbol::Do,
            Atom::Else => Symbol::Else,
            Atom::ElseIf => Symbol::ElseIf,
            Atom::End => Symbol::End,
            Atom::False => Symbol::False,
            Atom::For => Symbol::For,
            Atom::Function => Symbol::Function,
            Atom::If => Symbol::If,
            Atom::In => Symbol::In,
            Atom::Local => Symbol::Local,
            Atom::Nil => Symbol::Nil,
            Atom::Not => Symbol::Not,
            Atom::Or => Symbol::Or,
            Atom::Repeat => Symbol::Repeat,
            Atom::Return => Symbol::Return,
            Atom::Then => Symbol::Then,
            Atom::True => Symbol::True,
            Atom::Until => Symbol::Until,
            Atom::While => Symbol::While,
            #[cfg(feature = "lua52")]
            Atom::Goto => Symbol::Goto,
            #[cfg(feature = "roblox")]
            Atom::PlusEqual => Symbol::PlusEqual,
            #[cfg(feature = "roblox")]
            Atom::MinusEqual => Symbol::MinusEqual,
            #[cfg(feature = "roblox")]
            Atom::StarEqual => Symbol::StarEqual,
            #[cfg(feature = "roblox")]
            Atom::SlashEqual => Symbol::SlashEqual,
            #[cfg(feature = "roblox")]
            Atom::PercentEqual => Symbol::PercentEqual,
            #[cfg(feature = "roblox")]
            Atom::CaretEqual => Symbol::CaretEqual,
            #[cfg(feature = "roblox")]
            Atom::TwoDotsEqual => Symbol::TwoDotsEqual,
            Atom::Caret => Symbol::Caret,
            Atom::Colon => Symbol::Colon,
            Atom::Comma => Symbol::Comma,
            Atom::Ellipse => Symbol::Ellipse,
            Atom::TwoDots => Symbol::TwoDots,
            #[cfg(any(feature = "roblox", feature = "lua53"))]
            Atom::Ampersand => Symbol::Ampersand,
            #[cfg(feature = "roblox")]
            Atom::ThinArrow => Symbol::ThinArrow,
            #[cfg(any(feature = "roblox", feature = "lua52"))]
            Atom::TwoColons => Symbol::TwoColons,
            Atom::Dot => Symbol::Dot,
            Atom::TwoEqual => Symbol::TwoEqual,
            Atom::Equal => Symbol::Equal,
            Atom::GreaterThanEqual => Symbol::GreaterThanEqual,
            Atom::GreaterThan => Symbol::GreaterThan,
            Atom::Hash => Symbol::Hash,
            Atom::LeftBracket => Symbol::LeftBracket,
            Atom::LeftBrace => Symbol::LeftBrace,
            Atom::LeftParen => Symbol::LeftParen,
            Atom::LessThanEqual => Symbol::LessThanEqual,
            Atom::LessThan => Symbol::LessThan,
            #[cfg(feature = "lua53")]
            Atom::DoubleLessThan => Symbol::DoubleLessThan,
            Atom::Minus => Symbol::Minus,
            Atom::Percent => Symbol::Percent,
            #[cfg(any(feature = "roblox", feature = "lua53"))]
            Atom::Pipe => Symbol::Pipe,
            #[cfg(feature = "roblox")]
            Atom::QuestionMark => Symbol::QuestionMark,
            Atom::Plus => Symbol::Plus,
            Atom::RightBrace(None) => Symbol::RightBrace,
            Atom::RightBracket => Symbol::RightBracket,
            Atom::RightParen => Symbol::RightParen,
            Atom::Semicolon => Symbol::Semicolon,
            Atom::Slash => Symbol::Slash,
            #[cfg(any(feature = "roblox", feature = "lua53"))]
            Atom::DoubleSlash => Symbol::DoubleSlash,
            Atom::Star => Symbol::Star,
            #[cfg(feature = "lua53")]
            Atom::Tilde => Symbol::Tilde,
            Atom::TildeEqual => Symbol::TildeEqual,
            _ => {
                return Err(());
            }
        })
    }
}

impl Display for Symbol {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let value = match self {
            Symbol::And => "and",
            Symbol::Break => "break",
            Symbol::Do => "do",
            Symbol::Else => "else",
            Symbol::ElseIf => "elseif",
            Symbol::End => "end",
            Symbol::False => "false",
            Symbol::For => "for",
            Symbol::Function => "function",
            Symbol::If => "if",
            Symbol::In => "in",
            Symbol::Local => "local",
            Symbol::Nil => "nil",
            Symbol::Not => "not",
            Symbol::Or => "or",
            Symbol::Repeat => "repeat",
            Symbol::Return => "return",
            Symbol::Then => "then",
            Symbol::True => "true",
            Symbol::Until => "until",
            Symbol::While => "while",
            #[cfg(feature = "lua52")]
            Symbol::Goto => "goto",
            Symbol::PlusEqual => "+=",
            Symbol::MinusEqual => "-=",
            Symbol::StarEqual => "*=",
            Symbol::SlashEqual => "/=",
            Symbol::PercentEqual => "%=",
            Symbol::CaretEqual => "^=",
            Symbol::TwoDotsEqual => "..=",
            #[cfg(any(feature = "roblox", feature = "lua53"))]
            Symbol::Ampersand => "&",
            #[cfg(feature = "roblox")]
            Symbol::ThinArrow => "->",
            #[cfg(any(feature = "roblox", feature = "lua52"))]
            Symbol::TwoColons => "::",
            Symbol::Caret => "^",
            Symbol::Colon => ":",
            Symbol::Comma => ",",
            Symbol::Ellipse => "...",
            Symbol::TwoDots => "..",
            Symbol::Dot => ".",
            Symbol::TwoEqual => "==",
            Symbol::Equal => "=",
            Symbol::GreaterThanEqual => ">=",
            Symbol::GreaterThan => ">",
            #[cfg(feature = "lua53")]
            Symbol::DoubleGreaterThan => ">>",
            Symbol::Hash => "#",
            Symbol::LeftBracket => "[",
            Symbol::LeftBrace => "{",
            Symbol::LeftParen => "(",
            Symbol::LessThanEqual => "<=",
            Symbol::LessThan => "<",
            #[cfg(feature = "lua53")]
            Symbol::DoubleLessThan => "<<",
            Symbol::Minus => "-",
            Symbol::Percent => "%",
            #[cfg(any(feature = "roblox", feature = "lua53"))]
            Symbol::Pipe => "|",
            Symbol::Plus => "+",
            #[cfg(feature = "roblox")]
            Symbol::QuestionMark => "?",
            Symbol::RightBrace => "}",
            Symbol::RightBracket => "]",
            Symbol::RightParen => ")",
            Symbol::Semicolon => ";",
            Symbol::Slash => "/",
            #[cfg(any(feature = "roblox", feature = "lua53"))]
            Symbol::DoubleSlash => "//",
            Symbol::Star => "*",
            #[cfg(feature = "lua53")]
            Symbol::Tilde => "~",
            Symbol::TildeEqual => "~=",
        };

        value.fmt(formatter)
    }
}

/// The possible errors that can happen while tokenizing.
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub enum TokenizerErrorType {
    /// An unclosed multi-line comment was found
    UnclosedComment,
    /// An unclosed string was found
    UnclosedString,
    /// An unexpected #! was found
    UnexpectedShebang,
    /// An unexpected token was found
    UnexpectedToken(char),
    /// Symbol passed is not valid
    /// Returned from [`TokenReference::symbol`]
    InvalidSymbol(String),
}

impl fmt::Display for TokenizerErrorType {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            TokenizerErrorType::UnclosedComment => "unclosed comment".fmt(formatter),
            TokenizerErrorType::UnclosedString => "unclosed string".fmt(formatter),
            TokenizerErrorType::UnexpectedShebang => "unexpected shebang".fmt(formatter),
            TokenizerErrorType::UnexpectedToken(character) => {
                write!(formatter, "unexpected character {character}")
            }
            TokenizerErrorType::InvalidSymbol(symbol) => {
                write!(formatter, "invalid symbol {symbol}")
            }
        }
    }
}

/// The type of tokens in parsed code
#[derive(Clone, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[cfg_attr(feature = "serde", serde(tag = "type"))]
#[non_exhaustive]
pub enum TokenType {
    /// End of file, should always be the very last token
    Eof,

    /// An identifier, such as `foo`
    Identifier {
        /// The identifier itself
        identifier: ShortString,
    },

    /// A multi line comment in the format of `--[[ comment ]]`
    MultiLineComment {
        /// Number of equals signs, if any, for the multi line comment
        /// For example, `--[=[` would have a `blocks` value of `1`
        blocks: usize,
        /// The comment itself, ignoring opening and closing tags
        comment: ShortString,
    },

    /// A literal number, such as `3.3`
    Number {
        /// The text representing the number, includes details such as `0x`
        text: ShortString,
    },

    /// A shebang line
    Shebang {
        /// The shebang line itself
        line: ShortString,
    },

    /// A single line comment, such as `-- comment`
    SingleLineComment {
        /// The comment, ignoring initial `--`
        comment: ShortString,
    },

    /// A literal string, such as "Hello, world"
    StringLiteral {
        /// The literal itself, ignoring quotation marks
        literal: ShortString,
        #[cfg_attr(feature = "serde", serde(skip_serializing_if = "Option::is_none"))]
        /// Number of equals signs used for a multi line string, if it is one
        /// For example, `[=[string]=]` would have a `multi_line` value of Some(1)
        /// `[[string]]` would have a `multi_line` value of Some(0)
        /// A string such as `"string"` would have a `multi_line` value of None
        multi_line: Option<usize>,
        /// The type of quotation mark used to make the string
        quote_type: StringLiteralQuoteType,
    },

    /// A [`Symbol`], such as `local` or `+`
    Symbol {
        /// The symbol itself
        symbol: Symbol,
    },

    /// Whitespace, such as tabs or new lines
    Whitespace {
        /// Characters consisting of the whitespace
        characters: ShortString,
    },

    /// Some form of interpolated string
    #[cfg(feature = "roblox")]
    InterpolatedString {
        /// The literal itself, ignoring backticks
        literal: ShortString,

        /// The kind of interpolated string.
        /// If it is the beginning, middle, end, or a standalone string.
        kind: InterpolatedStringKind,
    },
}

impl TokenType {
    fn new_string(literal: &str, quote_type: StringLiteralQuoteType) -> Self {
        let literal = literal.into();

        Self::StringLiteral {
            literal,
            quote_type,
            multi_line: None,
        }
    }

    /// Can this token type contain new lines?
    fn is_extensive(&self) -> bool {
        #[cfg(feature = "roblox")]
        let is_interpolated_string = matches!(self, TokenType::InterpolatedString { .. });

        #[cfg(not(feature = "roblox"))]
        let is_interpolated_string = false;

        matches!(
            self,
            TokenType::MultiLineComment { .. }
                | TokenType::Shebang { .. }
                | TokenType::StringLiteral { .. }
                | TokenType::Whitespace { .. }
        ) || is_interpolated_string
    }

    /// Returns whether a token can be practically ignored in most cases
    /// Comments and whitespace will return `true`, everything else will return `false`
    pub fn is_trivia(&self) -> bool {
        matches!(
            self,
            TokenType::Shebang { .. }
                | TokenType::SingleLineComment { .. }
                | TokenType::MultiLineComment { .. }
                | TokenType::Whitespace { .. }
        )
    }

    /// Returns the kind of the token type.
    ///
    /// ```rust
    /// use full_moon::{ShortString, tokenizer::{TokenKind, TokenType}};
    ///
    /// assert_eq!(
    ///     TokenType::Identifier {
    ///         identifier: ShortString::new("hello")
    ///     }.kind(),
    ///     TokenKind::Identifier,
    /// );
    /// ```
    pub fn kind(&self) -> TokenKind {
        match self {
            TokenType::Eof => TokenKind::Eof,
            TokenType::Identifier { .. } => TokenKind::Identifier,
            TokenType::MultiLineComment { .. } => TokenKind::MultiLineComment,
            TokenType::Number { .. } => TokenKind::Number,
            TokenType::Shebang { .. } => TokenKind::Shebang,
            TokenType::SingleLineComment { .. } => TokenKind::SingleLineComment,
            TokenType::StringLiteral { .. } => TokenKind::StringLiteral,
            TokenType::Symbol { .. } => TokenKind::Symbol,
            TokenType::Whitespace { .. } => TokenKind::Whitespace,

            #[cfg(feature = "roblox")]
            TokenType::InterpolatedString { .. } => TokenKind::InterpolatedString,
        }
    }

    /// Returns a whitespace `TokenType` consisting of spaces
    pub fn spaces(spaces: usize) -> Self {
        TokenType::Whitespace {
            characters: " ".repeat(spaces).into(),
        }
    }

    /// Returns a whitespace `TokenType` consisting of tabs
    pub fn tabs(tabs: usize) -> Self {
        TokenType::Whitespace {
            characters: "\t".repeat(tabs).into(),
        }
    }
}

/// The kind of token. Contains no additional data.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum TokenKind {
    /// End of file, should always be the very last token
    Eof,
    /// An identifier, such as `foo`
    Identifier,
    /// A multi line comment in the format of `--[[ comment ]]`
    MultiLineComment,
    /// A literal number, such as `3.3`
    Number,
    /// The shebang line
    Shebang,
    /// A single line comment, such as `-- comment`
    SingleLineComment,
    /// A literal string, such as "Hello, world"
    StringLiteral,
    /// A [`Symbol`], such as `local` or `+`
    Symbol,
    /// Whitespace, such as tabs or new lines
    Whitespace,

    #[cfg(feature = "roblox")]
    /// Some form of interpolated string
    InterpolatedString,
}

/// A token such consisting of its [`Position`] and a [`TokenType`]
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Token {
    pub(crate) start_position: Position,
    pub(crate) end_position: Position,
    pub(crate) token_type: TokenType,
}

impl Token {
    /// Creates a token with a zero position
    pub fn new(token_type: TokenType) -> Token {
        Token {
            start_position: Position::default(),
            end_position: Position::default(),
            token_type,
        }
    }

    /// The position a token begins at
    pub fn start_position(&self) -> Position {
        self.start_position
    }

    /// The position a token ends at
    pub fn end_position(&self) -> Position {
        self.end_position
    }

    /// The type of token as well as the data needed to represent it
    /// If you don't need any other information, use [`token_kind`](Token::token_kind) instead.
    pub fn token_type(&self) -> &TokenType {
        &self.token_type
    }

    /// The kind of token with no additional data.
    /// If you need any information such as idenitfier names, use [`token_type`](Token::token_type) instead.
    pub fn token_kind(&self) -> TokenKind {
        self.token_type().kind()
    }
}

impl fmt::Display for Token {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        use self::TokenType::*;

        match self.token_type() {
            Eof => Ok(()),
            Number { text } => text.fmt(formatter),
            Identifier { identifier } => identifier.fmt(formatter),
            MultiLineComment { blocks, comment } => {
                write!(formatter, "--[{0}[{1}]{0}]", "=".repeat(*blocks), comment)
            }
            Shebang { line } => line.fmt(formatter),
            SingleLineComment { comment } => write!(formatter, "--{comment}"),
            StringLiteral {
                literal,
                multi_line,
                quote_type,
            } => {
                if let Some(blocks) = multi_line {
                    write!(formatter, "[{0}[{1}]{0}]", "=".repeat(*blocks), literal)
                } else {
                    write!(formatter, "{quote_type}{literal}{quote_type}")
                }
            }
            Symbol { symbol } => symbol.fmt(formatter),
            Whitespace { characters } => characters.fmt(formatter),

            #[cfg(feature = "roblox")]
            InterpolatedString { literal, kind } => match kind {
                InterpolatedStringKind::Begin => {
                    write!(formatter, "`{literal}{{")
                }

                InterpolatedStringKind::Middle => {
                    write!(formatter, "}}{literal}{{")
                }

                InterpolatedStringKind::End => {
                    write!(formatter, "}}{literal}`")
                }

                InterpolatedStringKind::Simple => {
                    write!(formatter, "`{literal}`")
                }
            },
        }
    }
}

impl PartialEq<Self> for Token {
    fn eq(&self, rhs: &Self) -> bool {
        self.start_position() == rhs.start_position()
            && self.end_position() == rhs.end_position()
            && self.token_type == rhs.token_type
    }
}

impl Eq for Token {}

impl Ord for Token {
    fn cmp(&self, other: &Self) -> Ordering {
        self.start_position().cmp(&other.start_position())
    }
}

impl PartialOrd for Token {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Visit for Token {
    fn visit<V: Visitor>(&self, visitor: &mut V) {
        visitor.visit_token(self);

        match self.token_kind() {
            TokenKind::Eof => {}
            TokenKind::Identifier => visitor.visit_identifier(self),
            TokenKind::MultiLineComment => visitor.visit_multi_line_comment(self),
            TokenKind::Number => visitor.visit_number(self),
            TokenKind::Shebang => {}
            TokenKind::SingleLineComment => visitor.visit_single_line_comment(self),
            TokenKind::StringLiteral => visitor.visit_string_literal(self),
            TokenKind::Symbol => visitor.visit_symbol(self),
            TokenKind::Whitespace => visitor.visit_whitespace(self),

            #[cfg(feature = "roblox")]
            TokenKind::InterpolatedString => visitor.visit_interpolated_string_segment(self),
        }
    }
}

impl VisitMut for Token {
    fn visit_mut<V: VisitorMut>(self, visitor: &mut V) -> Self {
        let token = visitor.visit_token(self);

        match token.token_kind() {
            TokenKind::Eof => token,
            TokenKind::Identifier => visitor.visit_identifier(token),
            TokenKind::MultiLineComment => visitor.visit_multi_line_comment(token),
            TokenKind::Number => visitor.visit_number(token),
            TokenKind::Shebang => token,
            TokenKind::SingleLineComment => visitor.visit_single_line_comment(token),
            TokenKind::StringLiteral => visitor.visit_string_literal(token),
            TokenKind::Symbol => visitor.visit_symbol(token),
            TokenKind::Whitespace => visitor.visit_whitespace(token),

            #[cfg(feature = "roblox")]
            TokenKind::InterpolatedString => visitor.visit_interpolated_string_segment(token),
        }
    }
}

/// A reference to a token used by Ast's.
/// Dereferences to a [`Token`]
#[derive(Clone, Debug)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct TokenReference {
    pub(crate) leading_trivia: Vec<Token>,
    pub(crate) token: Token,
    pub(crate) trailing_trivia: Vec<Token>,
}

impl TokenReference {
    /// Creates a TokenReference from leading/trailing trivia as well as the leading token
    pub fn new(leading_trivia: Vec<Token>, token: Token, trailing_trivia: Vec<Token>) -> Self {
        Self {
            leading_trivia,
            token,
            trailing_trivia,
        }
    }

    /// Returns a symbol with the leading and trailing whitespace
    /// Only whitespace is supported
    /// ```rust
    /// # use full_moon::tokenizer::{Symbol, TokenReference, TokenType, TokenizerErrorType};
    /// # fn main() -> Result<(), Box<TokenizerErrorType>> {
    /// let symbol = TokenReference::symbol("\nreturn ")?;
    /// assert_eq!(symbol.leading_trivia().next().unwrap().to_string(), "\n");
    /// assert_eq!(symbol.token().token_type(), &TokenType::Symbol {
    ///     symbol: Symbol::Return,
    /// });
    /// assert_eq!(symbol.trailing_trivia().next().unwrap().to_string(), " ");
    /// assert!(TokenReference::symbol("isnt whitespace").is_err());
    /// assert!(TokenReference::symbol(" notasymbol ").is_err());
    /// # Ok(())
    /// # }
    /// ```
    pub fn symbol(text: &str) -> Result<Self, TokenizerErrorType> {
        let mut lexer = Atom::lexer(text).spanned().peekable();

        let leading_trivia = lexer
            .next_if(|v| v.0 == Atom::Whitespace)
            .map(|v| text[v.1].into())
            .unwrap_or_default();

        let (atom, span) = lexer.next().unwrap();
        let symbol = atom.try_into().map_err(|_| {
            let text = text[span].to_string();

            TokenizerErrorType::InvalidSymbol(text)
        })?;

        let trailing_trivia = lexer
            .next_if(|v| v.0 == Atom::Whitespace)
            .map(|v| text[v.1].into())
            .unwrap_or_default();

        if let Some(v) = lexer.next() {
            let ch = text[v.1].chars().next().unwrap();

            return Err(TokenizerErrorType::UnexpectedToken(ch));
        }

        Ok(Self {
            leading_trivia: vec![Token::new(TokenType::Whitespace {
                characters: leading_trivia,
            })],
            token: Token::new(TokenType::Symbol { symbol }),
            trailing_trivia: vec![Token::new(TokenType::Whitespace {
                characters: trailing_trivia,
            })],
        })
    }

    /// Returns the inner token.
    pub fn token(&self) -> &Token {
        &self.token
    }

    /// Returns the leading trivia
    pub fn leading_trivia(&self) -> impl Iterator<Item = &Token> {
        self.leading_trivia.iter()
    }

    /// Returns the trailing trivia
    pub fn trailing_trivia(&self) -> impl Iterator<Item = &Token> {
        self.trailing_trivia.iter()
    }

    /// Creates a clone of the current TokenReference with the new inner token, preserving trivia.
    pub fn with_token(&self, token: Token) -> Self {
        Self {
            token,
            leading_trivia: self.leading_trivia.clone(),
            trailing_trivia: self.trailing_trivia.clone(),
        }
    }
}

impl std::borrow::Borrow<Token> for &TokenReference {
    fn borrow(&self) -> &Token {
        self
    }
}

impl std::ops::Deref for TokenReference {
    type Target = Token;

    fn deref(&self) -> &Self::Target {
        &self.token
    }
}

impl fmt::Display for TokenReference {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        for trivia in &self.leading_trivia {
            trivia.fmt(formatter)?;
        }

        self.token.fmt(formatter)?;

        for trivia in &self.trailing_trivia {
            trivia.fmt(formatter)?;
        }

        Ok(())
    }
}

impl PartialEq<Self> for TokenReference {
    fn eq(&self, other: &Self) -> bool {
        (**self).eq(other)
            && self.leading_trivia == other.leading_trivia
            && self.trailing_trivia == other.trailing_trivia
    }
}

impl Eq for TokenReference {}

impl Ord for TokenReference {
    fn cmp(&self, other: &Self) -> Ordering {
        (**self).cmp(&**other)
    }
}

impl PartialOrd for TokenReference {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Visit for TokenReference {
    fn visit<V: Visitor>(&self, visitor: &mut V) {
        visitor.visit_token(self);

        if matches!(self.token().token_kind(), TokenKind::Eof) {
            visitor.visit_eof(self);
        }

        self.leading_trivia.visit(visitor);
        self.token.visit(visitor);
        self.trailing_trivia.visit(visitor);
    }
}

impl VisitMut for TokenReference {
    fn visit_mut<V: VisitorMut>(self, visitor: &mut V) -> Self {
        let mut token_reference = visitor.visit_token_reference(self);

        if matches!(token_reference.token().token_kind(), TokenKind::Eof) {
            token_reference = visitor.visit_eof(token_reference);
        }

        token_reference.leading_trivia = token_reference.leading_trivia.visit_mut(visitor);
        token_reference.token = token_reference.token.visit_mut(visitor);
        token_reference.trailing_trivia = token_reference.trailing_trivia.visit_mut(visitor);
        token_reference
    }
}

/// Used to represent exact positions of tokens in code
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct Position {
    pub(crate) bytes: usize,
    pub(crate) line: usize,
    pub(crate) character: usize,
}

impl Position {
    /// How many bytes, ignoring lines, it would take to find this position
    pub fn bytes(self) -> usize {
        self.bytes
    }

    /// Index of the character on the line for this position
    pub fn character(self) -> usize {
        self.character
    }

    /// Line the position lies on
    pub fn line(self) -> usize {
        self.line
    }
}

impl Ord for Position {
    fn cmp(&self, other: &Self) -> Ordering {
        self.bytes.cmp(&other.bytes)
    }
}

impl PartialOrd for Position {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

/// The types of quotes used in a Lua string
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
#[non_exhaustive]
pub enum StringLiteralQuoteType {
    /// Strings formatted \[\[with brackets\]\]
    Brackets,
    /// Strings formatted "with double quotes"
    Double,
    /// Strings formatted 'with single quotes'
    Single,
}

impl fmt::Display for StringLiteralQuoteType {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        match *self {
            StringLiteralQuoteType::Brackets => unreachable!(),
            StringLiteralQuoteType::Double => "\"".fmt(formatter),
            StringLiteralQuoteType::Single => "'".fmt(formatter),
        }
    }
}

type RawToken = Result<TokenType, TokenizerErrorType>;

impl From<TokenType> for RawToken {
    fn from(token_type: TokenType) -> RawToken {
        Ok(token_type)
    }
}

impl From<TokenizerErrorType> for RawToken {
    fn from(error: TokenizerErrorType) -> RawToken {
        Err(error)
    }
}

fn tokenize(token: Atom, slice: &str) -> RawToken {
    match token {
        Atom::Identifier => {
            let identifier = slice.into();

            Ok(TokenType::Identifier { identifier })
        }

        Atom::Comment => {
            let (comment, blocks) = trim_bracket_head(&slice[2..]);

            match blocks {
                Some(blocks) => Ok(TokenType::MultiLineComment { comment, blocks }),
                None => Ok(TokenType::SingleLineComment { comment }),
            }
        }

        Atom::Number => {
            let text = slice.into();

            Ok(TokenType::Number { text })
        }

        Atom::MultiLineString => {
            let (literal, multi_line) = trim_bracket_head(slice);

            Ok(TokenType::StringLiteral {
                literal,
                multi_line,
                quote_type: StringLiteralQuoteType::Brackets,
            })
        }

        Atom::ApostropheString => Ok(TokenType::new_string(
            &slice[1..slice.len() - 1],
            StringLiteralQuoteType::Single,
        )),

        Atom::QuoteString => Ok(TokenType::new_string(
            &slice[1..slice.len() - 1],
            StringLiteralQuoteType::Double,
        )),

        Atom::Whitespace => {
            let characters = slice.into();

            Ok(TokenType::Whitespace { characters })
        }

        Atom::Bom => Err(TokenizerErrorType::UnexpectedToken('\u{feff}')),

        Atom::Shebang => Err(TokenizerErrorType::UnexpectedShebang),

        #[cfg(feature = "roblox")]
        Atom::InterpolatedStringBegin(InterpolatedStringBegin::Simple)
        | Atom::InterpolatedStringBegin(InterpolatedStringBegin::Formatted)
        | Atom::RightBrace(Some(InterpolatedStringSection::Middle))
        | Atom::RightBrace(Some(InterpolatedStringSection::End)) => {
            Ok(TokenType::InterpolatedString {
                literal: ShortString::new(&slice[1..slice.len() - 1]),
                kind: match token {
                    Atom::InterpolatedStringBegin(InterpolatedStringBegin::Simple) => {
                        InterpolatedStringKind::Simple
                    }

                    Atom::InterpolatedStringBegin(InterpolatedStringBegin::Formatted) => {
                        InterpolatedStringKind::Begin
                    }

                    Atom::RightBrace(Some(InterpolatedStringSection::Middle)) => {
                        InterpolatedStringKind::Middle
                    }

                    Atom::RightBrace(Some(InterpolatedStringSection::End)) => {
                        InterpolatedStringKind::End
                    }

                    _ => unreachable!(),
                },
            })
        }

        Atom::Unknown => {
            let first = slice.chars().next().unwrap();
            let what = match first {
                '`' if cfg!(feature = "roblox") => TokenizerErrorType::UnclosedString,
                '\'' | '"' | '[' => TokenizerErrorType::UnclosedString,
                '-' => TokenizerErrorType::UnclosedComment,
                other => TokenizerErrorType::UnexpectedToken(other),
            };

            Err(what)
        }

        token => Ok(TokenType::Symbol {
            symbol: token.try_into().unwrap(),
        }),
    }
}

fn next_if(lexer: &mut Lexer<Atom>, atom: Atom) -> Option<ShortString> {
    if lexer.clone().next() == Some(atom) {
        lexer.next();

        Some(lexer.slice().into())
    } else {
        None
    }
}

fn tokenize_code(code: &str) -> Vec<(RawToken, Span)> {
    let mut lexer = Atom::lexer(code);
    let mut list = Vec::new();

    if let Some(characters) = next_if(&mut lexer, Atom::Bom) {
        let raw = (Ok(TokenType::Whitespace { characters }), lexer.span());

        list.push(raw);
    }

    if let Some(line) = next_if(&mut lexer, Atom::Shebang) {
        let raw = (Ok(TokenType::Shebang { line }), lexer.span());

        list.push(raw);
    }

    while let Some(atom) = lexer.next() {
        let raw = (tokenize(atom, lexer.slice()), lexer.span());

        list.push(raw);
    }

    list
}

/// Information about an error that occurs while tokenizing
#[derive(Clone, Debug, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(Deserialize, Serialize))]
pub struct TokenizerError {
    /// The type of error
    error: TokenizerErrorType,
    /// The position of the token that caused the error
    position: Position,
}

impl TokenizerError {
    /// The type of error
    pub fn error(&self) -> &TokenizerErrorType {
        &self.error
    }

    /// The position of the token that caused the error
    pub fn position(&self) -> Position {
        self.position
    }
}

impl fmt::Display for TokenizerError {
    fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        write!(
            formatter,
            "{} at line {}, column {}",
            self.error, self.position.line, self.position.character,
        )
    }
}

impl std::error::Error for TokenizerError {}

struct TokenCollector {
    result: Vec<Token>,
}

// Collector
impl TokenCollector {
    fn new() -> Self {
        Self { result: Vec::new() }
    }
    fn push(
        &mut self,
        start_position: Position,
        raw_token: RawToken,
        end_position: Position,
    ) -> Result<(), TokenizerError> {
        match raw_token {
            Ok(token_type) => {
                self.result.push(Token {
                    start_position,
                    end_position,
                    token_type,
                });
                Ok(())
            }
            Err(error) => Err(TokenizerError {
                error,
                position: start_position,
            }),
        }
    }
    fn finish(mut self, eof_position: Position) -> Vec<Token> {
        self.result.push(Token {
            start_position: eof_position,
            end_position: eof_position,
            token_type: TokenType::Eof,
        });
        self.result
    }
}

fn read_position(code: &str, position: &mut Position) -> bool {
    let mut has_newline = false;

    for c in code.chars() {
        if has_newline {
            position.line += 1;
            position.character = 1;

            has_newline = false;
        }

        if c == '\n' {
            has_newline = true;
        } else {
            position.character += 1;
        }
    }

    has_newline
}

/// Returns a list of tokens.
/// You probably want [`parse`](crate::parse) instead.
///
/// # Errors
///
/// If the code passed is malformed from normal Lua expectations,
/// a [`TokenizerError`] will be returned.
///
/// ```rust
/// # use full_moon::tokenizer::tokens;
/// assert!(tokens("local x = 1").is_ok());
/// assert!(tokens("local 4 = end").is_ok()); // tokens does *not* check validity of code, only tokenizing
/// assert!(tokens("--[[ Unclosed comment!").is_err());
/// ```
pub fn tokens(code: &str) -> Result<Vec<Token>, TokenizerError> {
    let mut tokens = TokenCollector::new();

    // Logos provides token start and end information,
    // but not the line or column. We iterate over the
    // characters to retrieve this.
    let mut position = Position {
        bytes: 0,
        line: 1,
        character: 1,
    };

    for (token, span) in tokenize_code(code) {
        let start_position = position;

        position.bytes = span.end;

        if token
            .as_ref()
            .map(TokenType::is_extensive)
            .unwrap_or_default()
        {
            let has_newline = read_position(&code[span.clone()], &mut position);

            tokens.push(start_position, token, position)?;

            if has_newline {
                position.line += 1;
                position.character = 1;
            }
        } else {
            position.character += span.len();

            tokens.push(start_position, token, position)?;
        }
    }

    Ok(tokens.finish(position))
}

#[cfg(test)]
mod tests {
    use crate::tokenizer::*;
    use pretty_assertions::assert_eq;

    macro_rules! test_rule {
        ($code:expr, $result:expr) => {
            let code: &str = $code;
            let result: RawToken = $result.into();

            match result {
                Ok(token) => {
                    let tokens = tokens(code).expect("couldn't tokenize");
                    let first_token = &tokens.get(0).expect("tokenized response is empty");
                    assert_eq!(*first_token.token_type(), token);
                }

                Err(expected) => {
                    if let Err(TokenizerError { error, .. }) = tokens($code) {
                        assert_eq!(error, expected);
                    } else {
                        panic!("tokenization should fail");
                    }
                }
            };
        };
    }

    #[test]
    fn test_rule_comment() {
        test_rule!(
            "-- hello world",
            TokenType::SingleLineComment {
                comment: " hello world".into()
            }
        );

        test_rule!(
            "--[[ hello world ]]",
            TokenType::MultiLineComment {
                blocks: 0,
                comment: " hello world ".into()
            }
        );

        test_rule!(
            "--[=[ hello world ]=]",
            TokenType::MultiLineComment {
                blocks: 1,
                comment: " hello world ".into()
            }
        );
        test_rule!("--", TokenType::SingleLineComment { comment: "".into() });
    }

    #[test]
    fn test_rule_numbers() {
        test_rule!("213", TokenType::Number { text: "213".into() });

        test_rule!("1", TokenType::Number { text: "1".into() });

        test_rule!(
            "123.45",
            TokenType::Number {
                text: "123.45".into(),
            }
        );
    }

    #[test]
    #[cfg_attr(not(feature = "roblox"), ignore)]
    fn test_rule_binary_literals() {
        test_rule!(
            "0b101",
            TokenType::Number {
                text: "0b101".into(),
            }
        );
    }

    #[test]
    fn test_rule_identifier() {
        test_rule!(
            "hello",
            TokenType::Identifier {
                identifier: "hello".into(),
            }
        );

        test_rule!(
            "hello world",
            TokenType::Identifier {
                identifier: "hello".into(),
            }
        );

        test_rule!(
            "hello___",
            TokenType::Identifier {
                identifier: "hello___".into(),
            }
        );
    }

    #[test]
    fn test_rule_symbols() {
        test_rule!(
            "local",
            TokenType::Symbol {
                symbol: Symbol::Local
            }
        );
    }

    #[test]
    fn test_rule_whitespace() {
        test_rule!(
            "\t  \n\t",
            TokenType::Whitespace {
                characters: "\t  \n".into(),
            }
        );

        test_rule!(
            "\thello",
            TokenType::Whitespace {
                characters: "\t".into(),
            }
        );

        test_rule!(
            "\t\t\nhello",
            TokenType::Whitespace {
                characters: "\t\t\n".into(),
            }
        );

        test_rule!(
            "\n\thello",
            TokenType::Whitespace {
                characters: "\n".into(),
            }
        );
    }

    #[test]
    fn test_rule_string_literal() {
        test_rule!(
            "\"hello\"",
            TokenType::StringLiteral {
                literal: "hello".into(),
                multi_line: None,
                quote_type: StringLiteralQuoteType::Double,
            }
        );

        test_rule!(
            "\"hello\\\nworld\"",
            TokenType::StringLiteral {
                literal: "hello\\\nworld".into(),
                multi_line: None,
                quote_type: StringLiteralQuoteType::Double,
            }
        );

        test_rule!(
            "'hello world \\'goodbye\\''",
            TokenType::StringLiteral {
                literal: "hello world \\'goodbye\\'".into(),
                multi_line: None,
                quote_type: StringLiteralQuoteType::Single,
            }
        );

        test_rule!("\"hello", TokenizerErrorType::UnclosedString);
    }

    #[test]
    #[cfg(feature = "lua52")]
    fn test_string_z_escape() {
        test_rule!(
            "'hello \\z\nworld'",
            TokenType::StringLiteral {
                literal: "hello \\z\nworld".into(),
                multi_line: None,
                quote_type: StringLiteralQuoteType::Single,
            }
        );
    }

    #[test]
    fn test_symbols_within_symbols() {
        // "index" should not return "in"
        test_rule!(
            "index",
            TokenType::Identifier {
                identifier: "index".into()
            }
        );

        // "<=" should not return "<"
        test_rule!(
            "<=",
            TokenType::Symbol {
                symbol: Symbol::LessThanEqual,
            }
        );
    }

    #[test]
    fn test_rule_shebang() {
        test_rule!(
            "#!/usr/bin/env lua\n",
            TokenType::Shebang {
                line: "#!/usr/bin/env lua\n".into()
            }
        );
        // Don't recognize with a whitespace.
        test_rule!(
            " #!/usr/bin/env lua\n",
            TokenizerErrorType::UnexpectedShebang
        );
    }

    #[test]
    fn test_rule_bom() {
        let bom = String::from_utf8(b"\xEF\xBB\xBF".to_vec()).unwrap();
        test_rule!(
            &bom,
            TokenType::Whitespace {
                characters: ShortString::new(&bom),
            }
        );
        // Don't recognize if not in the beggining.
        test_rule!(
            &format!("#!/usr/bin/env lua\n {bom}"),
            TokenizerErrorType::UnexpectedToken('\u{feff}')
        );
    }

    #[test]
    fn test_new_line_on_same_line() {
        assert_eq!(
            tokens("\n").unwrap()[0],
            Token {
                start_position: Position {
                    bytes: 0,
                    character: 1,
                    line: 1,
                },

                end_position: Position {
                    bytes: 1,
                    character: 1,
                    line: 1,
                },

                token_type: TokenType::Whitespace {
                    characters: "\n".into()
                },
            }
        );
    }

    #[cfg(feature = "roblox")]
    #[test]
    fn test_string_interpolation_multi_line() {
        let tokens = tokens("`Welcome to \\\n{name}!`").unwrap();
        assert_eq!(tokens[0].to_string(), "`Welcome to \\\n{");
    }

    #[test]
    fn test_fuzzer() {
        let _ = tokens("*ա");
        let _ = tokens("̹(");
        let _ = tokens("¹;");
    }
}