-
-
Notifications
You must be signed in to change notification settings - Fork 381
Expand file tree
/
Copy pathtokenize.zig
More file actions
2906 lines (2647 loc) · 108 KB
/
Copy pathtokenize.zig
File metadata and controls
2906 lines (2647 loc) · 108 KB
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
//! Tokenization functionality for the Roc parser.
//!
//! This module provides the tokenizer that converts Roc source code into
//! a stream of tokens for parsing. It handles all Roc language tokens including
//! keywords, identifiers, literals, operators, and punctuation, representing
//! them as offsets into the source code with additional metadata.
const std = @import("std");
const Allocator = std.mem.Allocator;
const base = @import("base");
const tracy = @import("tracy");
const DataSpan = base.DataSpan;
const CommonEnv = base.CommonEnv;
/// representation of a token in the source code, like '+', 'foo', '=', '{'
/// these are represented by an offset into the bytes of the source code
/// and an extra field that stores either the length of the token or
/// an index into the string interner
pub const Token = struct {
tag: Tag,
region: base.Region,
extra: Extra,
pub const Extra = union {
interned: base.Ident.Idx,
ident_with_flags: IdentWithFlags,
none: u32,
};
pub const IdentWithFlags = struct {
ident: base.Ident.Idx,
starts_with_underscore: bool,
ends_with_underscore: bool,
};
pub const List = std.MultiArrayList(@This());
pub const Idx = u32;
pub const Span = struct { span: DataSpan };
pub const Tag = enum(u8) {
EndOfFile,
// primitives
Float,
StringStart, // the " that starts a string
StringEnd, // the " that ends a string
MultilineStringStart, // the """ or \\ that starts a multiline string
StringPart,
MalformedStringPart, // malformed, but should be treated similar to a StringPart in the parser
SingleQuote,
MalformedSingleQuote, // malformed, but should be treated similar to a SingleQuote in the parser
Int,
MalformedNumberBadSuffix, // malformed, but should be treated similar to an int in the parser
MalformedNumberUnicodeSuffix, // malformed, but should be treated similar to an int in the parser
MalformedNumberNoDigits, // malformed, but should be treated similar to an int in the parser
MalformedNumberNoExponentDigits, // malformed, but should be treated similar to an int in the parser
// Should be treated as StringPart in the parser, but we forward the error to the ast
MalformedInvalidUnicodeEscapeSequence,
MalformedInvalidEscapeSequence,
UpperIdent,
LowerIdent,
MalformedUnicodeIdent,
Underscore,
DotLowerIdent,
DotInt,
DotUpperIdent,
NoSpaceDotInt,
NoSpaceDotLowerIdent,
NoSpaceDotUpperIdent,
MalformedDotUnicodeIdent,
MalformedNoSpaceDotUnicodeIdent,
NamedUnderscore,
MalformedNamedUnderscoreUnicode,
OpaqueName,
MalformedOpaqueNameUnicode,
MalformedOpaqueNameWithoutName,
OpenRound,
CloseRound,
OpenSquare,
CloseSquare,
OpenCurly,
CloseCurly,
OpenStringInterpolation,
CloseStringInterpolation,
NoSpaceOpenRound,
// NoSpaceOpenCurly,
OpPlus,
OpStar,
OpPizza,
OpAssign,
OpBinaryMinus, // trailing whitespace
OpUnaryMinus, // no trailing whitespace
OpNotEquals,
OpBang,
OpAnd,
OpAmpersand,
OpQuestion,
OpDoubleQuestion,
OpOr,
OpBar,
OpDoubleSlash,
OpSlash,
OpPercent,
OpCaret,
OpGreaterThanOrEq,
OpGreaterThan,
OpLessThanOrEq,
OpBackArrow,
OpLessThan,
OpEquals,
OpColonEqual,
OpDoubleColon,
NoSpaceOpQuestion,
Comma,
Dot,
DoubleDot,
TripleDot,
DotStar,
OpColon,
OpArrow,
OpFatArrow,
OpBackslash,
// Keywords
KwApp,
KwAs,
KwCrash,
KwDbg,
KwElse,
KwExpect,
KwExposes,
KwExposing,
KwFor,
KwGenerates,
KwHas,
KwHosted,
KwIf,
KwImplements,
KwImport,
KwImports,
KwIn,
KwInterface,
KwMatch,
KwModule,
KwPackage,
KwPackages,
KwPlatform,
KwProvides,
KwRequires,
KwReturn,
KwTargets,
KwVar,
KwWhere,
KwWhile,
KwWith,
KwBreak,
MalformedUnknownToken,
/// Returns true if the node is malformed.
pub fn isMalformed(tok: Tag) bool {
// This function explicitly lists all variants to ensure new malformed nodes aren't missed.
return switch (tok) {
.EndOfFile,
.Float,
.StringStart,
.StringEnd,
.MultilineStringStart,
.StringPart,
.SingleQuote,
.Int,
.UpperIdent,
.LowerIdent,
.Underscore,
.DotLowerIdent,
.DotInt,
.DotUpperIdent,
.NoSpaceDotInt,
.NoSpaceDotLowerIdent,
.NoSpaceDotUpperIdent,
.NamedUnderscore,
.OpaqueName,
.OpenRound,
.CloseRound,
.OpenSquare,
.CloseSquare,
.OpenCurly,
.CloseCurly,
.OpenStringInterpolation,
.CloseStringInterpolation,
.NoSpaceOpenRound,
.OpPlus,
.OpStar,
.OpPizza,
.OpAssign,
.OpBinaryMinus,
.OpUnaryMinus,
.OpNotEquals,
.OpBang,
.OpAnd,
.OpAmpersand,
.OpQuestion,
.OpDoubleQuestion,
.OpOr,
.OpBar,
.OpDoubleSlash,
.OpSlash,
.OpPercent,
.OpCaret,
.OpGreaterThanOrEq,
.OpGreaterThan,
.OpLessThanOrEq,
.OpBackArrow,
.OpLessThan,
.OpEquals,
.OpColonEqual,
.OpDoubleColon,
.NoSpaceOpQuestion,
.Comma,
.Dot,
.DoubleDot,
.TripleDot,
.DotStar,
.OpColon,
.OpArrow,
.OpFatArrow,
.OpBackslash,
.KwApp,
.KwAs,
.KwCrash,
.KwDbg,
.KwElse,
.KwExpect,
.KwExposes,
.KwExposing,
.KwFor,
.KwGenerates,
.KwHas,
.KwHosted,
.KwIf,
.KwImplements,
.KwImport,
.KwImports,
.KwIn,
.KwInterface,
.KwMatch,
.KwModule,
.KwPackage,
.KwPackages,
.KwPlatform,
.KwProvides,
.KwRequires,
.KwReturn,
.KwTargets,
.KwVar,
.KwWhere,
.KwWhile,
.KwWith,
.KwBreak,
=> false,
.MalformedDotUnicodeIdent,
.MalformedInvalidEscapeSequence,
.MalformedInvalidUnicodeEscapeSequence,
.MalformedNamedUnderscoreUnicode,
.MalformedNoSpaceDotUnicodeIdent,
.MalformedNumberBadSuffix,
.MalformedNumberNoDigits,
.MalformedNumberNoExponentDigits,
.MalformedNumberUnicodeSuffix,
.MalformedOpaqueNameUnicode,
.MalformedOpaqueNameWithoutName,
.MalformedUnicodeIdent,
.MalformedUnknownToken,
.MalformedSingleQuote,
.MalformedStringPart,
=> true,
};
}
pub fn isInterned(tok: Tag) bool {
return switch (tok) {
.UpperIdent,
.LowerIdent,
.DotLowerIdent,
.DotUpperIdent,
.NoSpaceDotLowerIdent,
.NoSpaceDotUpperIdent,
.NamedUnderscore,
.MalformedNamedUnderscoreUnicode,
.MalformedNoSpaceDotUnicodeIdent,
.MalformedUnicodeIdent,
.MalformedDotUnicodeIdent,
.MalformedOpaqueNameUnicode,
.OpaqueName,
=> true,
else => false,
};
}
pub fn hasUnderscoreFlags(tok: Tag) bool {
return switch (tok) {
.LowerIdent,
.NamedUnderscore,
=> true,
else => false,
};
}
/// Returns true if this token can end an expression, meaning a following
/// minus sign should be treated as a binary operator rather than unary.
/// For example, in `x-1`, the minus after `x` (LowerIdent) should be binary.
pub fn canEndExpression(tok: Tag) bool {
return switch (tok) {
// Identifiers can end expressions
.LowerIdent,
.UpperIdent,
.MalformedUnicodeIdent,
.NamedUnderscore,
.MalformedNamedUnderscoreUnicode,
.OpaqueName,
.MalformedOpaqueNameUnicode,
// Dot access can end expressions
.DotLowerIdent,
.DotUpperIdent,
.DotInt,
.NoSpaceDotLowerIdent,
.NoSpaceDotUpperIdent,
.NoSpaceDotInt,
.MalformedDotUnicodeIdent,
.MalformedNoSpaceDotUnicodeIdent,
// Numbers can end expressions
.Int,
.Float,
.MalformedNumberBadSuffix,
.MalformedNumberUnicodeSuffix,
.MalformedNumberNoDigits,
.MalformedNumberNoExponentDigits,
// Closing brackets can end expressions
.CloseRound,
.CloseSquare,
.CloseCurly,
.CloseStringInterpolation,
// String literals can end expressions
.StringEnd,
.SingleQuote,
.MalformedSingleQuote,
=> true,
else => false,
};
}
/// This function is used to keep around the first malformed node.
/// For example, if an integer has no digits and a bad suffix `0bu22`,
/// we keep the first malformed node that the integer has no digits instead of pointing out the bad suffix.
fn updateIfNotMalformed(tok: Tag, next: Tag) Tag {
if (tok.isMalformed()) {
return tok;
}
return next;
}
};
pub const keywords = std.StaticStringMap(Tag).initComptime(.{
.{ "and", .OpAnd },
.{ "app", .KwApp },
.{ "as", .KwAs },
.{ "crash", .KwCrash },
.{ "dbg", .KwDbg },
.{ "else", .KwElse },
.{ "expect", .KwExpect },
.{ "exposes", .KwExposes },
.{ "exposing", .KwExposing },
.{ "for", .KwFor },
.{ "generates", .KwGenerates },
.{ "has", .KwHas },
.{ "hosted", .KwHosted },
.{ "if", .KwIf },
.{ "implements", .KwImplements },
.{ "import", .KwImport },
.{ "imports", .KwImports },
.{ "in", .KwIn },
.{ "interface", .KwInterface },
.{ "match", .KwMatch },
.{ "module", .KwModule },
.{ "or", .OpOr },
.{ "package", .KwPackage },
.{ "packages", .KwPackages },
.{ "platform", .KwPlatform },
.{ "provides", .KwProvides },
.{ "requires", .KwRequires },
.{ "return", .KwReturn },
.{ "targets", .KwTargets },
.{ "var", .KwVar },
.{ "where", .KwWhere },
.{ "while", .KwWhile },
.{ "with", .KwWith },
.{ "break", .KwBreak },
});
pub const valid_number_suffixes = std.StaticStringMap(void).initComptime(.{
.{ "dec", .{} },
.{ "f32", .{} },
.{ "f64", .{} },
.{ "i128", .{} },
.{ "i16", .{} },
.{ "i32", .{} },
.{ "i64", .{} },
.{ "i8", .{} },
.{ "nat", .{} },
.{ "u128", .{} },
.{ "u16", .{} },
.{ "u32", .{} },
.{ "u64", .{} },
.{ "u8", .{} },
});
};
/// The buffer that accumulates tokens.
pub const TokenizedBuffer = struct {
tokens: Token.List,
env: *CommonEnv,
pub fn initCapacity(env: *CommonEnv, gpa: std.mem.Allocator, capacity: usize) std.mem.Allocator.Error!TokenizedBuffer {
var tokens = Token.List{};
try tokens.ensureTotalCapacity(gpa, capacity);
return TokenizedBuffer{
.tokens = tokens,
.env = env,
};
}
pub fn deinit(self: *TokenizedBuffer, gpa: std.mem.Allocator) void {
self.tokens.deinit(gpa);
}
pub fn resolve(self: *const TokenizedBuffer, idx: usize) base.Region {
return self.tokens.items(.region)[idx];
}
/// Loads the current token if it is an identifier.
/// Otherwise returns null.
pub fn resolveIdentifier(self: *const TokenizedBuffer, token: Token.Idx) ?base.Ident.Idx {
const tag = self.tokens.items(.tag)[@intCast(token)];
const extra = self.tokens.items(.extra)[@intCast(token)];
if (tag.hasUnderscoreFlags()) {
return extra.ident_with_flags.ident;
} else if (tag.isInterned()) {
return extra.interned;
} else {
return null;
}
}
/// Gets underscore flags for identifier tokens.
/// Returns null if token is not an identifier with underscore flags.
pub fn resolveUnderscoreFlags(self: *TokenizedBuffer, token: Token.Idx) ?struct { starts_with_underscore: bool, ends_with_underscore: bool } {
const tag = self.tokens.items(.tag)[@intCast(token)];
if (tag.hasUnderscoreFlags()) {
const extra = self.tokens.items(.extra)[@intCast(token)];
return .{
.starts_with_underscore = extra.ident_with_flags.starts_with_underscore,
.ends_with_underscore = extra.ident_with_flags.ends_with_underscore,
};
} else {
return null;
}
}
};
/// Represents a diagnostic message including its position in the source.
pub const Diagnostic = struct {
tag: Tag,
region: base.Region,
/// Represents the type of diagnostic message.
pub const Tag = enum {
MisplacedCarriageReturn,
AsciiControl,
LeadingZero,
UppercaseBase,
InvalidUnicodeEscapeSequence,
InvalidEscapeSequence,
UnclosedString,
NonPrintableUnicodeInStrLiteral,
InvalidUtf8InSource,
DollarInMiddleOfIdentifier,
SingleQuoteTooLong,
SingleQuoteEmpty,
SingleQuoteUnclosed,
};
};
/// The cursor is our current position in the input text, and it collects messages.
/// Note that instead of allocating its own message list, the caller must pass in a pre-allocated
/// slice of Message. The field `message_count` tracks how many messages have been written.
/// This can grow beyond the length of the slice, and if so, it means there are more messages
/// than the caller has allocated space for. The caller can either ignore these messages or
/// allocate a larger slice and tokenize again.
pub const Cursor = struct {
buf: []const u8,
pos: u32,
messages: []Diagnostic,
message_count: u32,
tab_width: u8 = 4, // TODO: make this configurable
/// Initialize a Cursor with the given input buffer and a pre-allocated messages slice.
pub fn init(buf: []const u8, messages: []Diagnostic) Cursor {
return Cursor{
.buf = buf,
.pos = 0,
.messages = messages,
.message_count = 0,
};
}
fn pushMessageHere(self: *Cursor, tag: Diagnostic.Tag) void {
self.pushMessage(tag, self.pos, self.pos);
}
fn pushMessage(self: *Cursor, tag: Diagnostic.Tag, begin: u32, end: u32) void {
if (self.message_count < self.messages.len) {
self.messages[self.message_count] = Diagnostic{
.tag = tag,
.region = base.Region.from_raw_offsets(begin, end),
};
}
self.message_count += 1;
}
/// Returns the current byte, or null if at the end.
pub fn peek(self: *Cursor) ?u8 {
if (self.pos < self.buf.len) {
return self.buf[self.pos];
}
return null;
}
/// Returns the byte at the given lookahead offset.
pub fn peekAt(self: *Cursor, lookahead: u32) ?u8 {
if (self.pos + lookahead < self.buf.len) {
return self.buf[self.pos + lookahead];
}
return null;
}
pub fn isPeekedCharInRange(self: *Cursor, lookahead: u32, start: u8, end: u8) bool {
const peeked = self.peekAt(lookahead);
return if (peeked) |c|
c >= start and c <= end
else
false;
}
/// Requires that the next byte is `ch`, otherwise pushes a message.
pub fn require(self: *Cursor, ch: u8, tag: Diagnostic.Tag) void {
if (self.peek() == ch) {
self.pos += 1;
} else {
self.pushMessageHere(tag);
}
}
/// Chomps "trivia" (whitespace, comments, etc.).
pub fn chompTrivia(self: *Cursor) void {
while (self.pos < self.buf.len) {
const b = self.buf[self.pos];
if (b == ' ') {
self.pos += 1;
} else if (b == '\t') {
self.pos += 1;
} else if (b == '\n') {
self.pos += 1;
} else if (b == '\r') {
self.pos += 1;
if (self.pos < self.buf.len and self.buf[self.pos] == '\n') {
self.pos += 1;
} else {
self.pushMessageHere(.MisplacedCarriageReturn);
}
} else if (b == '#') {
self.pos += 1;
while (self.pos < self.buf.len and self.buf[self.pos] != '\n' and self.buf[self.pos] != '\r') {
self.pos += 1;
}
} else if (b >= 0 and b <= 31) {
self.pushMessageHere(.AsciiControl);
self.pos += 1;
} else {
break;
}
}
}
pub fn chompNumber(self: *Cursor) Token.Tag {
const initialDigit = self.buf[self.pos];
self.pos += 1;
var tok = Token.Tag.Int;
if (initialDigit == '0') {
while (true) {
const c = self.peek() orelse 0;
switch (c) {
'x', 'X' => {
if (c == 'X') {
self.pushMessageHere(.UppercaseBase);
}
self.pos += 1;
self.chompIntegerBase16() catch {
tok = .MalformedNumberNoDigits;
};
tok = self.chompNumberSuffix(tok);
break;
},
'o', 'O' => {
if (c == 'O') {
self.pushMessageHere(.UppercaseBase);
}
self.pos += 1;
self.chompIntegerBase8() catch {
tok = .MalformedNumberNoDigits;
};
tok = self.chompNumberSuffix(tok);
break;
},
'b', 'B' => {
if (c == 'B') {
self.pushMessageHere(.UppercaseBase);
}
self.pos += 1;
self.chompIntegerBase2() catch {
tok = .MalformedNumberNoDigits;
};
tok = self.chompNumberSuffix(tok);
break;
},
'0'...'9' => {
self.pushMessageHere(.LeadingZero);
tok = self.chompNumberBase10();
tok = self.chompNumberSuffix(tok);
break;
},
'_' => {
self.pos += 1;
continue;
},
'.' => {
self.pos -= 1; // Go back to the initial 0
tok = self.chompNumberBase10();
tok = self.chompNumberSuffix(tok);
break;
},
else => {
tok = self.chompNumberSuffix(tok);
break;
},
}
}
} else {
tok = self.chompNumberBase10();
tok = self.chompNumberSuffix(tok);
}
return tok;
}
/// Chomps an exponent including sign and digits, if one if found.
/// Returns true if an exponent was chomped.
/// Will error if the exponent has no digits.
pub fn chompExponent(self: *Cursor) error{EmptyExponent}!bool {
if (self.peek() orelse 0 == 'e' or self.peek() orelse 0 == 'E') {
self.pos += 1;
// Optional sign
if (self.peek() orelse 0 == '+' or self.peek() orelse 0 == '-') {
self.pos += 1;
}
self.chompIntegerBase10() catch {
return error.EmptyExponent;
};
return true;
}
return false;
}
/// Chomp what's expected to be the suffix of a number.
/// Returns either the original token hypothesis, or a malformed token tag.
pub fn chompNumberSuffix(self: *Cursor, hypothesis: Token.Tag) Token.Tag {
if (self.peek()) |c| {
const is_ident_char = (c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or (c >= '0' and c <= '9') or c == '_' or c == '$' or c >= 0x80;
if (!is_ident_char) {
return hypothesis;
}
} else {
return hypothesis;
}
const start = self.pos;
if (!self.chompIdentGeneral()) {
return hypothesis.updateIfNotMalformed(.MalformedNumberUnicodeSuffix);
}
const suffix = self.buf[start..self.pos];
if (Token.valid_number_suffixes.get(suffix) == null) {
return hypothesis.updateIfNotMalformed(.MalformedNumberBadSuffix);
} else {
return hypothesis;
}
}
/// Chomp a number in base 10. The number can be an int or float.
/// Returns the tag of the number type.
/// Will return a malformed node if the exponent is malformed.
/// Before calling this method, a valid leading digit must have been parsed.
pub fn chompNumberBase10(self: *Cursor) Token.Tag {
var token_type: Token.Tag = .Int;
self.chompIntegerBase10() catch {}; // This is not an issue, have leading digit.
if (self.peek() orelse 0 == '.' and (self.isPeekedCharInRange(1, '0', '9') or self.peekAt(1) == 'e' or self.peekAt(1) == 'E')) {
self.pos += 1;
self.chompIntegerBase10() catch {}; // This is not an issue, guaranteed to have digits before the decimal point.
token_type = .Float;
}
const has_exponent = self.chompExponent() catch {
return .MalformedNumberNoExponentDigits;
};
if (has_exponent) {
token_type = .Float;
}
return token_type;
}
/// Chomp the digits of an integer in base 10.
/// Will error if the integer has no digits.
pub fn chompIntegerBase10(self: *Cursor) error{EmptyInteger}!void {
var contains_digits = false;
while (self.peek()) |c| {
if (c >= '0' and c <= '9') {
contains_digits = true;
self.pos += 1;
} else if (c == '_') {
self.pos += 1;
} else {
break;
}
}
if (!contains_digits) {
return error.EmptyInteger;
}
}
/// Chomp the digits of an integer in base 16.
/// Will error if the integer has no digits.
pub fn chompIntegerBase16(self: *Cursor) error{EmptyInteger}!void {
var contains_digits = false;
while (self.peek()) |c| {
if ((c >= '0' and c <= '9') or (c >= 'a' and c <= 'f') or (c >= 'A' and c <= 'F')) {
contains_digits = true;
self.pos += 1;
} else if (c == '_') {
self.pos += 1;
} else {
break;
}
}
if (!contains_digits) {
return error.EmptyInteger;
}
}
/// Chomp the digits of an integer in base 8.
/// Will error if the integer has no digits.
pub fn chompIntegerBase8(self: *Cursor) error{EmptyInteger}!void {
var contains_digits = false;
while (self.peek()) |c| {
if (c >= '0' and c <= '7') {
contains_digits = true;
self.pos += 1;
} else if (c == '_') {
self.pos += 1;
} else {
break;
}
}
if (!contains_digits) {
return error.EmptyInteger;
}
}
/// Chomp the digits of an integer in base 2.
/// Will error if the integer has no digits.
pub fn chompIntegerBase2(self: *Cursor) error{EmptyInteger}!void {
var contains_digits = false;
while (self.peek()) |c| {
if (c == '0' or c == '1') {
contains_digits = true;
self.pos += 1;
} else if (c == '_') {
self.pos += 1;
} else {
break;
}
}
if (!contains_digits) {
return error.EmptyInteger;
}
}
/// Chomps an identifier starting with a lowercase letter.
/// Also checks if the resulting identifier is a keyword.
/// Returns the token type - LowerIdent or Kw*
pub fn chompIdentLower(self: *Cursor) Token.Tag {
const start = self.pos;
if (!self.chompIdentGeneral()) {
return .MalformedUnicodeIdent;
}
const ident = self.buf[start..self.pos];
const kw = Token.keywords.get(ident);
return kw orelse .LowerIdent;
}
/// Chomps a general identifier - either upper or lower case.
/// Doesn't check if the identifier is a keyword, since we assume the caller already
/// determined that was impossible (e.g. because the first character was uppercase),
/// or otherwise not relevant.
///
/// Returns whether the chomped identifier was valid - i.e. didn't contain any non-ascii characters.
pub fn chompIdentGeneral(self: *Cursor) bool {
var valid = true;
const start_pos = self.pos;
while (self.pos < self.buf.len) {
const c = self.buf[self.pos];
if ((c >= 'a' and c <= 'z') or (c >= 'A' and c <= 'Z') or (c >= '0' and c <= '9') or c == '_' or c == '!' or c == '$') {
// Allow $ as a valid identifier character
if (c == '$' and self.pos > start_pos) {
// But warn if it's not at the start (pos > start_pos means we've moved)
// Use pushMessage to specify the exact location of the $ character
self.pushMessage(.DollarInMiddleOfIdentifier, self.pos, self.pos + 1);
}
self.pos += 1;
} else if (c >= 0x80) {
valid = false;
self.pos += 1;
} else {
break;
}
}
return valid;
}
pub fn chompInteger(self: *Cursor) void {
while (self.pos < self.buf.len) {
const c = self.buf[self.pos];
if (c >= '0' and c <= '9') {
self.pos += 1;
} else {
break;
}
}
}
pub fn chompEscapeSequence(self: *Cursor) error{ InvalidUnicodeEscapeSequence, InvalidEscapeSequence }!void {
return self.chompEscapeSequenceWithQuote(null);
}
pub fn chompEscapeSequenceWithQuote(self: *Cursor, quote_char: ?u8) error{ InvalidUnicodeEscapeSequence, InvalidEscapeSequence }!void {
// Store the start position of the escape sequence (before the backslash)
const escape_start = if (self.pos > 0) self.pos - 1 else self.pos;
switch (self.peek() orelse 0) {
'\\', '"', '\'', 'n', 'r', 't', '$' => {
self.pos += 1;
},
'u' => {
self.pos += 1;
if (self.peek() == '(') {
self.pos += 1;
} else {
self.pushMessage(.InvalidUnicodeEscapeSequence, escape_start, self.pos);
return error.InvalidUnicodeEscapeSequence;
}
const hex_start = self.pos;
while (true) {
if (self.peek() == ')') {
if (self.pos == hex_start) {
// Empty unicode escape sequence
self.pushMessage(.InvalidUnicodeEscapeSequence, escape_start, self.pos + 1);
self.pos += 1;
return error.InvalidUnicodeEscapeSequence;
}
self.pos += 1;
break;
} else if (self.peek() != null) {
const next = self.peek() orelse 0;
if ((next >= '0' and next <= '9') or
(next >= 'a' and next <= 'f') or
(next >= 'A' and next <= 'F'))
{
self.pos += 1;
} else {
// Invalid hex character - advance to the closing paren if possible
// to include the full escape sequence in the error region, but stop
// if we encounter the closing quote or newline
while (self.pos < self.buf.len) {
const next_char = self.peek() orelse 0;
if (next_char == ')' or next_char == '\n') {
break;
}
if (quote_char) |qc| {
if (next_char == qc) {
break;
}
}
self.pos += 1;
}
if (self.pos < self.buf.len and self.peek() == ')') {
self.pos += 1;
}
self.pushMessage(.InvalidUnicodeEscapeSequence, escape_start, self.pos);
return error.InvalidUnicodeEscapeSequence;
}
} else {
self.pushMessage(.InvalidUnicodeEscapeSequence, escape_start, self.pos);
return error.InvalidUnicodeEscapeSequence;
}
}
const hex_code = self.buf[hex_start .. self.pos - 1];
const codepoint = std.fmt.parseInt(u21, hex_code, 16) catch {
self.pushMessage(.InvalidUnicodeEscapeSequence, escape_start, self.pos);
return error.InvalidUnicodeEscapeSequence;
};
if (!std.unicode.utf8ValidCodepoint(codepoint)) {
self.pushMessage(.InvalidUnicodeEscapeSequence, escape_start, self.pos);
return error.InvalidUnicodeEscapeSequence;
}
},
else => {
// Include the character after the backslash in the error region
const end_pos = if (self.peek() != null) self.pos + 1 else self.pos;
self.pushMessage(.InvalidEscapeSequence, escape_start, end_pos);
return error.InvalidEscapeSequence;
},
}
}
pub fn chompSingleQuoteLiteral(self: *Cursor) Token.Tag {
const State = union(enum) {
Empty,
Enough,
TooLong,
Invalid,
};
std.debug.assert(self.peek() == '\'');
const start = self.pos;
// Skip the initial quote.
self.pos += 1;
var state: State = .Empty;
while (self.pos < self.buf.len) {
const c = self.buf[self.pos];
if (c == '\n') {
break;
}
self.pos += 1;
switch (state) {
.Empty => switch (c) {
'\'' => {
self.pushMessage(.SingleQuoteEmpty, start, self.pos);
return .MalformedSingleQuote;
},
'\\' => {
state = .Enough;
self.chompEscapeSequenceWithQuote('\'') catch {
state = .Invalid;
};
},
else => {
self.pos -= 1;
if (self.chompUTF8CodepointWithValidation()) |_| {} else {}
state = .Enough;
},
},
.Enough => switch (c) {
'\'' => {
return .SingleQuote;
},
else => {