-
Notifications
You must be signed in to change notification settings - Fork 144
/
Copy pathLexer.cpp
1612 lines (1448 loc) · 52.3 KB
/
Lexer.cpp
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
//------------------------------------------------------------------------------
// Lexer.cpp
// Source file lexer
//
// SPDX-FileCopyrightText: Michael Popoloski
// SPDX-License-Identifier: MIT
//------------------------------------------------------------------------------
#include "slang/parsing/Lexer.h"
#include <cmath>
#include <fmt/core.h>
#include "slang/diagnostics/LexerDiags.h"
#include "slang/diagnostics/NumericDiags.h"
#include "slang/diagnostics/PreprocessorDiags.h"
#include "slang/syntax/SyntaxKind.h"
#include "slang/text/CharInfo.h"
#include "slang/text/SourceManager.h"
#include "slang/util/BumpAllocator.h"
#include "slang/util/ScopeGuard.h"
#include "slang/util/String.h"
static_assert(std::numeric_limits<double>::is_iec559, "SystemVerilog requires IEEE 754");
static const double BitsPerDecimal = log2(10.0);
namespace slang::parsing {
using namespace syntax;
using LF = LexerFacts;
Lexer::Lexer(SourceBuffer buffer, BumpAllocator& alloc, Diagnostics& diagnostics,
SourceManager& sourceManager, LexerOptions options) :
Lexer(buffer.id, buffer.data, buffer.data.data(), alloc, diagnostics, sourceManager,
std::move(options)) {
library = buffer.library;
}
Lexer::Lexer(BufferID bufferId, std::string_view source, const char* startPtr, BumpAllocator& alloc,
Diagnostics& diagnostics, SourceManager& sourceManager, LexerOptions options) :
alloc(alloc), diagnostics(diagnostics), options(std::move(options)), bufferId(bufferId),
originalBegin(source.data()), sourceBuffer(startPtr),
sourceEnd(source.data() + source.length()), marker(nullptr), sourceManager(sourceManager) {
ptrdiff_t count = sourceEnd - sourceBuffer;
SLANG_ASSERT(count);
SLANG_ASSERT(sourceEnd[-1] == '\0');
// detect BOMs so we can give nice errors for invalid encoding
if (count >= 2) {
const unsigned char* ubuf = reinterpret_cast<const unsigned char*>(sourceBuffer);
if ((ubuf[0] == 0xFF && ubuf[1] == 0xFE) || (ubuf[0] == 0xFE && ubuf[1] == 0xFF)) {
errorCount++;
addDiag(diag::UnicodeBOM, 0);
advance(2);
}
else if (count >= 3) {
// Silently skip the UTF8 BOM.
if (ubuf[0] == 0xEF && ubuf[1] == 0xBB && ubuf[2] == 0xBF)
advance(3);
}
}
}
Token Lexer::concatenateTokens(BumpAllocator& alloc, SourceManager& sourceManager, Token left,
Token right) {
auto location = left.location();
auto trivia = left.trivia();
// if either side is empty, we have an error; the user tried to concatenate some weird kind of
// token
auto leftText = left.rawText();
auto rightText = right.rawText();
if (leftText.empty() || rightText.empty())
return Token();
// combine the text for both sides; make sure to include room for a null
size_t newLength = leftText.length() + rightText.length() + 1;
char* mem = (char*)alloc.allocate(newLength, 1);
leftText.copy(mem, leftText.length());
rightText.copy(mem + leftText.length(), rightText.length());
mem[newLength - 1] = '\0';
std::string_view combined{mem, newLength};
Diagnostics unused;
Lexer lexer{BufferID::getPlaceholder(),
combined,
combined.data(),
alloc,
unused,
sourceManager,
LexerOptions{}};
auto token = lexer.lex();
if (token.kind == TokenKind::Unknown || token.rawText().empty())
return Token();
// make sure the next token is an EoF, otherwise the tokens were unable to
// be combined and should be left alone
if (lexer.lex().kind != TokenKind::EndOfFile)
return Token();
return token.clone(alloc, trivia, token.rawText(), location);
}
Token Lexer::stringify(Lexer& parentLexer, Token startToken, std::span<Token> bodyTokens,
Token endToken) {
SmallVector<char> text;
text.push_back('"');
const bool tripleQuoted = startToken.kind == TokenKind::MacroTripleQuote;
if (tripleQuoted) {
text.push_back('"');
text.push_back('"');
}
auto addTrivia = [&](Token cur) {
for (const Trivia& t : cur.trivia()) {
if (t.kind == TriviaKind::Whitespace ||
(tripleQuoted && t.kind == TriviaKind::EndOfLine)) {
text.append_range(t.getRawText());
}
}
};
for (auto cur : bodyTokens) {
addTrivia(cur);
if (cur.kind == TokenKind::MacroEscapedQuote) {
text.push_back('\\');
text.push_back('"');
}
else if (cur.kind == TokenKind::StringLiteral) {
auto raw = cur.rawText();
const bool nestedHasTriple = raw.starts_with("\"\"\""sv);
if (nestedHasTriple) {
text.append_range(R"(\"\"\")"sv);
raw = raw.substr(3, raw.size() - 6);
}
else {
text.append_range(R"(\")"sv);
raw = raw.substr(1, raw.size() - 2);
}
text.append_range(raw);
if (nestedHasTriple)
text.append_range(R"(\"\"\")"sv);
else
text.append_range(R"(\")"sv);
}
else if (cur.kind != TokenKind::EmptyMacroArgument) {
text.append_range(cur.rawText());
}
}
if (endToken)
addTrivia(endToken);
if (tripleQuoted) {
text.push_back('"');
text.push_back('"');
}
text.push_back('"');
text.push_back('\0');
std::string_view raw = toStringView(text.copy(parentLexer.alloc));
Diagnostics unused;
Lexer lexer{BufferID::getPlaceholder(), raw, raw.data(),
parentLexer.alloc, unused, parentLexer.sourceManager,
parentLexer.options};
auto token = lexer.lex();
SLANG_ASSERT(token.kind == TokenKind::StringLiteral);
SLANG_ASSERT(lexer.lex().kind == TokenKind::EndOfFile);
return token.clone(parentLexer.alloc, startToken.trivia(), raw.substr(0, raw.length() - 1),
startToken.location());
}
Trivia Lexer::commentify(BumpAllocator& alloc, SourceManager& sourceManager,
std::span<Token> tokens) {
SmallVector<char> text;
for (auto cur : tokens) {
for (const Trivia& t : cur.trivia())
text.append_range(t.getRawText());
if (cur.kind != TokenKind::EmptyMacroArgument)
text.append_range(cur.rawText());
}
text.push_back('\0');
std::string_view raw = toStringView(text.copy(alloc));
Diagnostics unused;
Lexer lexer{
BufferID::getPlaceholder(), raw, raw.data(), alloc, unused, sourceManager, LexerOptions{}};
auto token = lexer.lex();
SLANG_ASSERT(token.kind == TokenKind::EndOfFile);
SLANG_ASSERT(token.trivia().size() == 1);
return token.trivia()[0];
}
void Lexer::splitTokens(BumpAllocator& alloc, Diagnostics& diagnostics,
SourceManager& sourceManager, Token sourceToken, size_t offset,
KeywordVersion keywordVersion, SmallVectorBase<Token>& results) {
auto loc = sourceToken.location();
if (sourceManager.isMacroLoc(loc))
loc = sourceManager.getOriginalLoc(loc);
auto sourceText = sourceManager.getSourceText(loc.buffer());
SLANG_ASSERT(!sourceText.empty());
Lexer lexer{loc.buffer(), sourceText, sourceToken.rawText().substr(offset).data(),
alloc, diagnostics, sourceManager,
LexerOptions{}};
size_t endOffset = loc.offset() + sourceToken.rawText().length();
while (true) {
Token token = lexer.lex(keywordVersion);
if (token.kind == TokenKind::EndOfFile || token.location().buffer() != loc.buffer() ||
token.location().offset() >= endOffset)
break;
results.push_back(token);
}
}
Token Lexer::lex() {
return lex(LF::getDefaultKeywordVersion(options.languageVersion));
}
Token Lexer::lex(KeywordVersion keywordVersion) {
triviaBuffer.clear();
lexTrivia<false>();
// lex the next token
mark();
Token token = lexToken(keywordVersion);
if (token.kind != TokenKind::EndOfFile && errorCount > options.maxErrors) {
// Stop any further lexing by claiming to be at the end of the buffer.
addDiag(diag::TooManyLexerErrors, currentOffset());
sourceBuffer = sourceEnd - 1;
triviaBuffer.push_back(Trivia(TriviaKind::DisabledText, lexeme()));
return Token(alloc, TokenKind::EndOfFile, triviaBuffer.copy(alloc), token.rawText(),
token.location());
}
return token;
}
bool Lexer::isNextTokenOnSameLine() {
auto guard = ScopeGuard([this, currBuff = sourceBuffer] { sourceBuffer = currBuff; });
while (true) {
switch (peek()) {
case ' ':
case '\t':
case '\v':
case '\f':
advance();
break;
case '/':
switch (peek(1)) {
case '/':
return false;
case '*':
advance(2);
while (true) {
if (consume('*') && consume('/'))
break;
if (peek() == '\0' && reallyAtEnd())
return false;
advance();
}
break;
default:
return true;
}
break;
case '\0':
case '\r':
case '\n':
return false;
default:
return true;
}
}
}
Token Lexer::lexEncodedText(ProtectEncoding encoding, uint32_t expectedBytes, bool singleLine,
bool legacyProtectedMode) {
triviaBuffer.clear();
lexTrivia<true>();
mark();
scanEncodedText(encoding, expectedBytes, singleLine, legacyProtectedMode);
return create(TokenKind::Unknown);
}
Token Lexer::lexToken(KeywordVersion keywordVersion) {
char c = peek();
advance();
switch (c) {
case '\0':
// check if we're not really at the end
// we back up one character here so that if the user calls lex() again and again,
// he'll just keep getting back EndOfFile tokens over and over
sourceBuffer--;
if (!reallyAtEnd()) {
errorCount++;
addDiag(diag::EmbeddedNull, currentOffset());
advance();
return create(TokenKind::Unknown);
}
// otherwise, end of file
return create(TokenKind::EndOfFile);
case '!':
if (consume('=')) {
switch (peek()) {
case '=':
advance();
return create(TokenKind::ExclamationDoubleEquals);
case '?':
advance();
return create(TokenKind::ExclamationEqualsQuestion);
default:
return create(TokenKind::ExclamationEquals);
}
}
return create(TokenKind::Exclamation);
case '"':
return lexStringLiteral();
case '#':
switch (peek()) {
case '#':
advance();
return create(TokenKind::DoubleHash);
case '-':
if (peek(1) == '#') {
advance(2);
return create(TokenKind::HashMinusHash);
}
// #- isn't a token, so just return a hash
return create(TokenKind::Hash);
case '=':
if (peek(1) == '#') {
advance(2);
return create(TokenKind::HashEqualsHash);
}
// #= isn't a token, so just return a hash
return create(TokenKind::Hash);
}
return create(TokenKind::Hash);
case '$':
return lexDollarSign();
case '%':
if (consume('='))
return create(TokenKind::PercentEqual);
return create(TokenKind::Percent);
case '&':
switch (peek()) {
case '&':
advance();
if (consume('&'))
return create(TokenKind::TripleAnd);
else
return create(TokenKind::DoubleAnd);
case '=':
advance();
return create(TokenKind::AndEqual);
}
return create(TokenKind::And);
case '\'':
if (consume('{'))
return create(TokenKind::ApostropheOpenBrace);
else
return lexApostrophe();
case '(':
return create(TokenKind::OpenParenthesis);
case ')':
return create(TokenKind::CloseParenthesis);
case '*':
switch (peek()) {
case '*':
advance();
return create(TokenKind::DoubleStar);
case '=':
advance();
return create(TokenKind::StarEqual);
case '>':
advance();
return create(TokenKind::StarArrow);
}
return create(TokenKind::Star);
case '+':
switch (peek()) {
case '+':
advance();
return create(TokenKind::DoublePlus);
case '=':
advance();
return create(TokenKind::PlusEqual);
case ':':
advance();
return create(TokenKind::PlusColon);
case '/':
if (peek(1) == '-') {
advance(2);
return create(TokenKind::PlusDivMinus);
}
break;
case '%':
if (peek(1) == '-') {
advance(2);
return create(TokenKind::PlusModMinus);
}
break;
}
return create(TokenKind::Plus);
case ',':
return create(TokenKind::Comma);
case '-':
switch (peek()) {
case '-':
advance();
return create(TokenKind::DoubleMinus);
case '=':
advance();
return create(TokenKind::MinusEqual);
case ':':
advance();
return create(TokenKind::MinusColon);
case '>':
advance();
if (consume('>'))
return create(TokenKind::MinusDoubleArrow);
else
return create(TokenKind::MinusArrow);
}
return create(TokenKind::Minus);
case '.':
return create(TokenKind::Dot);
case '/':
if (consume('='))
return create(TokenKind::SlashEqual);
else
return create(TokenKind::Slash);
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
// back up so that lexNumericLiteral can look at this digit again
sourceBuffer--;
return lexNumericLiteral();
case ':':
switch (peek()) {
case '=':
advance();
return create(TokenKind::ColonEquals);
case '/':
switch (peek(1)) {
case '/':
case '*':
return create(TokenKind::Colon);
}
advance();
return create(TokenKind::ColonSlash);
case ':':
advance();
return create(TokenKind::DoubleColon);
}
return create(TokenKind::Colon);
case ';':
return create(TokenKind::Semicolon);
case '<':
switch (peek()) {
case '=':
advance();
return create(TokenKind::LessThanEquals);
case '-':
if (peek(1) == '>') {
advance(2);
return create(TokenKind::LessThanMinusArrow);
}
return create(TokenKind::LessThan);
case '<':
advance();
switch (peek()) {
case '<':
if (peek(1) == '=') {
advance(2);
return create(TokenKind::TripleLeftShiftEqual);
}
else {
advance();
return create(TokenKind::TripleLeftShift);
}
case '=':
advance();
return create(TokenKind::LeftShiftEqual);
}
return create(TokenKind::LeftShift);
}
return create(TokenKind::LessThan);
case '=':
switch (peek()) {
case '=':
advance();
switch (peek()) {
case '=':
advance();
return create(TokenKind::TripleEquals);
case '?':
advance();
return create(TokenKind::DoubleEqualsQuestion);
}
return create(TokenKind::DoubleEquals);
case '>':
advance();
return create(TokenKind::EqualsArrow);
}
return create(TokenKind::Equals);
case '>':
switch (peek()) {
case '=':
advance();
return create(TokenKind::GreaterThanEquals);
case '>':
advance();
switch (peek()) {
case '>':
if (peek(1) == '=') {
advance(2);
return create(TokenKind::TripleRightShiftEqual);
}
else {
advance();
return create(TokenKind::TripleRightShift);
}
case '=':
advance();
return create(TokenKind::RightShiftEqual);
}
return create(TokenKind::RightShift);
}
return create(TokenKind::GreaterThan);
case '?':
return create(TokenKind::Question);
case '@':
switch (peek()) {
case '@':
advance();
return create(TokenKind::DoubleAt);
default:
return create(TokenKind::At);
}
// clang-format off
case 'A': case 'B': case 'C': case 'D':
case 'E': case 'F': case 'G': case 'H':
case 'I': case 'J': case 'L': case 'K':
case 'M': case 'N': case 'O': case 'P':
case 'Q': case 'R': case 'S': case 'T':
case 'U': case 'V': case 'W': case 'X':
case 'Y': case 'Z':
case 'a': case 'b': case 'c': case 'd':
case 'e': case 'f': case 'g': case 'h':
case 'i': case 'j': case 'k': case 'l':
case 'm': case 'n': case 'o': case 'p':
case 'q': case 'r': case 's': case 't':
case 'u': case 'v': case 'w': case 'x':
case 'y': case 'z':
case '_': {
// clang-format on
scanIdentifier();
// might be a keyword
auto table = LF::getKeywordTable(keywordVersion);
SLANG_ASSERT(table);
if (auto it = table->find(lexeme()); it != table->end())
return create(it->second);
return create(TokenKind::Identifier);
}
case '[':
return create(TokenKind::OpenBracket);
case '\\':
return lexEscapeSequence(false);
case ']':
return create(TokenKind::CloseBracket);
case '^':
switch (peek()) {
case '~':
advance();
return create(TokenKind::XorTilde);
case '=':
advance();
return create(TokenKind::XorEqual);
}
return create(TokenKind::Xor);
case '`':
switch (peek()) {
case '"':
advance();
if (peek() == '"' && peek(1) == '"') {
advance(2);
return create(TokenKind::MacroTripleQuote);
}
else {
return create(TokenKind::MacroQuote);
}
case '`':
advance();
return create(TokenKind::MacroPaste);
case '\\':
if (peek(1) == '`' && peek(2) == '"') {
advance(3);
return create(TokenKind::MacroEscapedQuote);
}
return lexDirective();
}
return lexDirective();
case '{':
return create(TokenKind::OpenBrace);
case '|':
switch (peek()) {
case '|':
advance();
return create(TokenKind::DoubleOr);
case '-':
if (peek(1) == '>') {
advance(2);
return create(TokenKind::OrMinusArrow);
}
return create(TokenKind::Or);
case '=':
if (peek(1) == '>') {
advance(2);
return create(TokenKind::OrEqualsArrow);
}
else {
advance();
return create(TokenKind::OrEqual);
}
}
return create(TokenKind::Or);
case '}':
return create(TokenKind::CloseBrace);
case '~':
switch (peek()) {
case '&':
advance();
return create(TokenKind::TildeAnd);
case '|':
advance();
return create(TokenKind::TildeOr);
case '^':
advance();
return create(TokenKind::TildeXor);
}
return create(TokenKind::Tilde);
default:
errorCount++;
if (isASCII(c)) {
addDiag(diag::NonPrintableChar, currentOffset() - 1);
}
else {
sourceBuffer--;
addDiag(diag::UTF8Char, currentOffset());
bool sawUTF8Error = false;
do {
sawUTF8Error |= !scanUTF8Char(sawUTF8Error);
} while (!isASCII(peek()));
}
return create(TokenKind::Unknown);
}
}
Token Lexer::lexStringLiteral() {
bool tripleQuoted = false;
if (peek() == '"' && peek(1) == '"') {
// New in v1800-2023: triple quoted string literals
if (options.languageVersion < LanguageVersion::v1800_2023) {
addDiag(diag::WrongLanguageVersion, currentOffset() - 1)
<< toString(options.languageVersion);
}
tripleQuoted = true;
advance(2);
}
stringBuffer.clear();
bool sawUTF8Error = false;
while (true) {
size_t offset = currentOffset();
char c = peek();
if (c == '\\') {
advance();
c = peek();
advance();
uint32_t charCode;
switch (c) {
// clang-format off
case 'n': stringBuffer.push_back('\n'); break;
case 't': stringBuffer.push_back('\t'); break;
case '\\': stringBuffer.push_back('\\'); break;
case '"': stringBuffer.push_back('"'); break;
case 'v': stringBuffer.push_back('\v'); break;
case 'f': stringBuffer.push_back('\f'); break;
case 'a': stringBuffer.push_back('\a'); break;
case '\n': break;
case '\r': consume('\n'); break;
case '0': case '1': case '2': case '3':
case '4': case '5': case '6': case '7':
// clang-format on
// octal character code
charCode = getDigitValue(c);
if (isOctalDigit(c = peek())) {
advance();
charCode = (charCode * 8) + getDigitValue(c);
if (isOctalDigit(c = peek())) {
advance();
charCode = (charCode * 8) + getDigitValue(c);
if (charCode > 255) {
addDiag(diag::OctalEscapeCodeTooBig, offset);
break;
}
}
}
stringBuffer.push_back((char)charCode);
break;
case 'x':
c = peek();
if (!isHexDigit(c)) {
addDiag(diag::InvalidHexEscapeCode, offset);
stringBuffer.push_back('x');
}
else {
advance();
charCode = getHexDigitValue(c);
if (isHexDigit(c = peek())) {
advance();
charCode = (charCode * 16) + getHexDigitValue(c);
}
stringBuffer.push_back((char)charCode);
}
break;
default: {
auto curr = --sourceBuffer;
uint32_t unicodeChar;
int unicodeLen;
if (scanUTF8Char(sawUTF8Error, &unicodeChar, unicodeLen)) {
if (isPrintableUnicode(unicodeChar)) {
// '\%' is not an actual escape code but other tools silently allow it
// and major UVM headers use it, so we'll issue a (fairly quiet) warning
// about it. Otherwise issue a louder warning (on by default).
DiagCode code = c == '%' ? diag::NonstandardEscapeCode
: diag::UnknownEscapeCode;
addDiag(code, offset) << std::string_view(curr, (size_t)unicodeLen);
}
}
else {
sawUTF8Error = true;
}
// Back up so that we handle this character as a normal char in the outer loop,
// regardless of whether it's valid or not.
sourceBuffer = curr;
break;
}
}
}
else if (c == '"') {
if (tripleQuoted) {
if (peek(1) == '"' && peek(2) == '"') {
advance(3);
break;
}
else {
advance();
stringBuffer.push_back(c);
sawUTF8Error = false;
}
}
else {
advance();
break;
}
}
else if (isNewline(c) && !tripleQuoted) {
addDiag(diag::ExpectedClosingQuote, offset);
break;
}
else if (c == '\0') {
if (reallyAtEnd()) {
addDiag(diag::ExpectedClosingQuote, offset);
break;
}
// otherwise just error and ignore
errorCount++;
addDiag(diag::EmbeddedNull, offset);
advance();
}
else if (isASCII(c)) {
advance();
stringBuffer.push_back(c);
sawUTF8Error = false;
}
else {
auto curr = sourceBuffer;
uint32_t unused;
int unicodeLen;
sawUTF8Error |= !scanUTF8Char(sawUTF8Error, &unused, unicodeLen);
// Regardless of whether the character sequence was valid or not
// we want to add the bytes to the string, to allow for cases where
// the source is actually something like latin-1 encoded. Ignoring the
// warning and carrying on will do the right thing for them.
for (int i = 0; i < unicodeLen; i++)
stringBuffer.push_back(curr[i]);
}
}
return create(TokenKind::StringLiteral, toStringView(stringBuffer.copy(alloc)));
}
Token Lexer::lexEscapeSequence(bool isMacroName) {
char c = peek();
if (isWhitespace(c) || c == '\0') {
// Check for a line continuation sequence.
if (isNewline(c)) {
advance();
if (c == '\r' && peek() == '\n')
advance();
return create(TokenKind::LineContinuation);
}
// Error issued in the Preprocessor
return create(TokenKind::Unknown);
}
while (isPrintableASCII(c)) {
advance();
c = peek();
if (isWhitespace(c))
break;
}
if (isMacroName)
return create(TokenKind::Directive, SyntaxKind::MacroUsage);
return create(TokenKind::Identifier);
}
Token Lexer::lexDollarSign() {
scanIdentifier();
// if length is 1, we just have a dollar sign operator
if (lexemeLength() == 1)
return create(TokenKind::Dollar);
// otherwise, we have a system identifier
// check for system keywords
TokenKind kind = LF::getSystemKeywordKind(lexeme());
if (kind != TokenKind::Unknown)
return create(kind);
return create(TokenKind::SystemIdentifier);
}
Token Lexer::lexDirective() {
if (peek() == '\\') {
// Handle escaped macro names as well.
advance();
return lexEscapeSequence(true);
}
scanIdentifier();
// if length is 1, we just have a grave character on its own, which is an error
if (lexemeLength() == 1) {
// Error issued in the Preprocessor
return create(TokenKind::Unknown);
}
SyntaxKind directive = LF::getDirectiveKind(lexeme().substr(1), options.enableLegacyProtect);
return create(TokenKind::Directive, directive);
}
Token Lexer::lexNumericLiteral() {
// have to check for the "1step" magic keyword
static const char OneStepText[] = "1step";
for (int i = 0; i < (int)sizeof(OneStepText) - 1; i++) {
if (peek(i) != OneStepText[i])
break;
if (i == sizeof(OneStepText) - 2) {
advance(sizeof(OneStepText) - 1);
return create(TokenKind::OneStep);
}
}
// scan past leading zeros
while (peek() == '0')
advance();
// Keep track of digits as we iterate through them; convert them
// into logic_t to pass into the SVInt parsing method. If it turns out
// that this is actually a float, we'll go back and populate `floatChars`
// instead. Since we expect many more ints than floats, it makes sense to
// not waste time populating that array up front.
size_t startOfNum = currentOffset();
SmallVector<logic_t> digits;
SmallVector<char> floatChars;
while (true) {
char c = peek();
if (c == '_')
advance();
else if (!isDecimalDigit(c))
break;
else {
digits.push_back(logic_t(getDigitValue(c)));
advance();
}
}
auto populateChars = [&]() {
if (digits.empty())
floatChars.push_back('0');
else {
for (auto d : digits)
floatChars.push_back(char((char)d.value + '0'));
}
};
// Check for fractional digits.
if (peek() == '.') {
advance();
populateChars();
floatChars.push_back('.');
bool any = false;
while (true) {
char c = peek();
if (c == '_')
advance();
else if (!isDecimalDigit(c))
break;
else {
any = true;
floatChars.push_back(c);
advance();
}
}
if (!any)
floatChars.push_back('0');
}
// Check for an exponent. Note that this case can be indistinguishable from
// the vector digits for a hex literal, so we can't issue any errors here if
// we don't have a decimal point (from above).
//
// Consider this nasty case we need to support:
// `FOO 3e+2
// If `FOO is defined to be 'h this represents an expression: 62 + 2
// Otherwise, this represents a real literal: 300.0
std::optional<TimeUnit> timeSuffix;
char c = peek();
if (c == 'e' || c == 'E') {
bool hasDecimal = !floatChars.empty();
if (!hasDecimal)
populateChars();
floatChars.push_back('e');
// skip over leading sign
int index = 1;
c = peek(index);
if (c == '+' || c == '-') {
floatChars.push_back(c);