-
Notifications
You must be signed in to change notification settings - Fork 10.4k
/
Copy pathLexer.cpp
3221 lines (2782 loc) · 109 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 - Swift Language Lexer ---------------------------------===//
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//
//
// This file implements the Lexer and Token interfaces.
//
//===----------------------------------------------------------------------===//
#include "swift/Parse/Lexer.h"
#include "swift/AST/DiagnosticsParse.h"
#include "swift/AST/Identifier.h"
#include "swift/Basic/Assertions.h"
#include "swift/Basic/LangOptions.h"
#include "swift/Basic/SourceManager.h"
#include "swift/Bridging/ASTGen.h"
#include "swift/Parse/Confusables.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/ADT/Twine.h"
#include "llvm/ADT/bit.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/MathExtras.h"
#include "llvm/Support/MemoryBuffer.h"
// FIXME: Figure out if this can be migrated to LLVM.
#include "clang/Basic/CharInfo.h"
#include <limits>
using namespace swift;
// clang::isAsciiIdentifierStart and clang::isAsciiIdentifierContinue are
// deliberately not in this list as a reminder that they are using C rules for
// identifiers. (Admittedly these are the same as Swift's right now.)
using clang::isAlphanumeric;
using clang::isDigit;
using clang::isHexDigit;
using clang::isHorizontalWhitespace;
using clang::isPrintable;
using clang::isWhitespace;
//===----------------------------------------------------------------------===//
// UTF8 Validation/Encoding/Decoding helper functions
//===----------------------------------------------------------------------===//
/// EncodeToUTF8 - Encode the specified code point into a UTF8 stream. Return
/// true if it is an erroneous code point.
static bool EncodeToUTF8(unsigned CharValue,
SmallVectorImpl<char> &Result) {
// Number of bits in the value, ignoring leading zeros.
unsigned NumBits = 32-llvm::countl_zero(CharValue);
// Handle the leading byte, based on the number of bits in the value.
unsigned NumTrailingBytes;
if (NumBits <= 5+6) {
// Encoding is 0x110aaaaa 10bbbbbb
Result.push_back(char(0xC0 | (CharValue >> 6)));
NumTrailingBytes = 1;
} else if (NumBits <= 4+6+6) {
// Encoding is 0x1110aaaa 10bbbbbb 10cccccc
Result.push_back(char(0xE0 | (CharValue >> (6+6))));
NumTrailingBytes = 2;
// UTF-16 surrogate pair values are not valid code points.
if (CharValue >= 0xD800 && CharValue <= 0xDFFF)
return true;
// U+FDD0...U+FDEF are also reserved
if (CharValue >= 0xFDD0 && CharValue <= 0xFDEF)
return true;
} else if (NumBits <= 3+6+6+6) {
// Encoding is 0x11110aaa 10bbbbbb 10cccccc 10dddddd
Result.push_back(char(0xF0 | (CharValue >> (6+6+6))));
NumTrailingBytes = 3;
// Reject over-large code points. These cannot be encoded as UTF-16
// surrogate pairs, so UTF-32 doesn't allow them.
if (CharValue > 0x10FFFF)
return true;
} else {
return true; // UTF8 can encode these, but they aren't valid code points.
}
// Emit all of the trailing bytes.
while (NumTrailingBytes--)
Result.push_back(char(0x80 | (0x3F & (CharValue >> (NumTrailingBytes*6)))));
return false;
}
/// isStartOfUTF8Character - Return true if this isn't a UTF8 continuation
/// character, which will be of the form 0b10XXXXXX
static bool isStartOfUTF8Character(unsigned char C) {
// RFC 2279: The octet values FE and FF never appear.
// RFC 3629: The octet values C0, C1, F5 to FF never appear.
return C < 0x80 || (C >= 0xC2 && C < 0xF5);
}
/// validateUTF8CharacterAndAdvance - Given a pointer to the starting byte of a
/// UTF8 character, validate it and advance the lexer past it. This returns the
/// encoded character or ~0U if the encoding is invalid.
uint32_t swift::validateUTF8CharacterAndAdvance(const char *&Ptr,
const char *End) {
if (Ptr >= End)
return ~0U;
unsigned char CurByte = *Ptr++;
if (CurByte < 0x80)
return CurByte;
// If this is not the start of a UTF8 character,
// then it is either a continuation byte or an invalid UTF8 code point.
if (!isStartOfUTF8Character(CurByte)) {
// Skip until we get the start of another character. This is guaranteed to
// at least stop at the nul at the end of the buffer.
while (Ptr < End && !isStartOfUTF8Character(*Ptr))
++Ptr;
return ~0U;
}
// Read the number of high bits set, which indicates the number of bytes in
// the character.
unsigned char EncodedBytes = llvm::countl_one(CurByte);
assert((EncodedBytes >= 2 && EncodedBytes <= 4));
// Drop the high bits indicating the # bytes of the result.
unsigned CharValue = (unsigned char)(CurByte << EncodedBytes) >> EncodedBytes;
// Read and validate the continuation bytes.
for (unsigned char i = 1; i != EncodedBytes; ++i) {
if (Ptr >= End)
return ~0U;
CurByte = *Ptr;
// If the high bit isn't set or the second bit isn't clear, then this is not
// a continuation byte!
if (CurByte < 0x80 || CurByte >= 0xC0) return ~0U;
// Accumulate our result.
CharValue <<= 6;
CharValue |= CurByte & 0x3F;
++Ptr;
}
// UTF-16 surrogate pair values are not valid code points.
if (CharValue >= 0xD800 && CharValue <= 0xDFFF)
return ~0U;
// If we got here, we read the appropriate number of accumulated bytes.
// Verify that the encoding was actually minimal.
// Number of bits in the value, ignoring leading zeros.
unsigned NumBits = 32-llvm::countl_zero(CharValue);
if (NumBits <= 5+6)
return EncodedBytes == 2 ? CharValue : ~0U;
if (NumBits <= 4+6+6)
return EncodedBytes == 3 ? CharValue : ~0U;
return EncodedBytes == 4 ? CharValue : ~0U;
}
//===----------------------------------------------------------------------===//
// Setup and Helper Methods
//===----------------------------------------------------------------------===//
Lexer::Lexer(const PrincipalTag &, const LangOptions &LangOpts,
const SourceManager &SourceMgr, unsigned BufferID,
DiagnosticEngine *Diags, LexerMode LexMode,
HashbangMode HashbangAllowed,
CommentRetentionMode RetainComments)
: LangOpts(LangOpts), SourceMgr(SourceMgr), BufferID(BufferID),
LexMode(LexMode),
IsHashbangAllowed(HashbangAllowed == HashbangMode::Allowed),
RetainComments(RetainComments) {
if (Diags)
DiagQueue.emplace(*Diags, /*emitOnDestruction*/ false);
}
void Lexer::initialize(unsigned Offset, unsigned EndOffset) {
assert(Offset <= EndOffset);
// Initialize buffer pointers.
StringRef contents =
SourceMgr.extractText(SourceMgr.getRangeForBuffer(BufferID));
BufferStart = contents.data();
BufferEnd = contents.data() + contents.size();
assert(*BufferEnd == 0);
assert(BufferStart + Offset <= BufferEnd);
assert(BufferStart + EndOffset <= BufferEnd);
// Check for Unicode BOM at start of file (Only UTF-8 BOM supported now).
size_t BOMLength = contents.starts_with("\xEF\xBB\xBF") ? 3 : 0;
// Keep information about existence of UTF-8 BOM for transparency source code
// editing with libSyntax.
ContentStart = BufferStart + BOMLength;
// Initialize code completion.
if (BufferID == SourceMgr.getIDEInspectionTargetBufferID()) {
const char *Ptr = BufferStart + SourceMgr.getIDEInspectionTargetOffset();
// If the pointer points to a null byte, it's the null byte that was
// inserted to mark the code completion token. If the IDE inspection offset
// points to a normal character, no code completion token should be
// inserted.
if (Ptr >= BufferStart && Ptr < BufferEnd && *Ptr == '\0') {
CodeCompletionPtr = Ptr;
}
}
ArtificialEOF = BufferStart + EndOffset;
CurPtr = BufferStart + Offset;
assert(NextToken.is(tok::NUM_TOKENS));
lexImpl();
assert((NextToken.isAtStartOfLine() || CurPtr != BufferStart) &&
"The token should be at the beginning of the line, "
"or we should be lexing from the middle of the buffer");
}
Lexer::Lexer(const LangOptions &Options, const SourceManager &SourceMgr,
unsigned BufferID, DiagnosticEngine *Diags, LexerMode LexMode,
HashbangMode HashbangAllowed,
CommentRetentionMode RetainComments)
: Lexer(PrincipalTag(), Options, SourceMgr, BufferID, Diags, LexMode,
HashbangAllowed, RetainComments) {
unsigned EndOffset = SourceMgr.getRangeForBuffer(BufferID).getByteLength();
initialize(/*Offset=*/0, EndOffset);
}
Lexer::Lexer(const LangOptions &Options, const SourceManager &SourceMgr,
unsigned BufferID, DiagnosticEngine *Diags, LexerMode LexMode,
HashbangMode HashbangAllowed, CommentRetentionMode RetainComments,
unsigned Offset, unsigned EndOffset)
: Lexer(PrincipalTag(), Options, SourceMgr, BufferID, Diags, LexMode,
HashbangAllowed, RetainComments) {
initialize(Offset, EndOffset);
}
Lexer::Lexer(const Lexer &Parent, State BeginState, State EndState,
bool EnableDiagnostics)
: Lexer(PrincipalTag(), Parent.LangOpts, Parent.SourceMgr, Parent.BufferID,
EnableDiagnostics ? Parent.getUnderlyingDiags() : nullptr,
Parent.LexMode,
Parent.IsHashbangAllowed
? HashbangMode::Allowed
: HashbangMode::Disallowed,
Parent.RetainComments) {
assert(BufferID == SourceMgr.findBufferContainingLoc(BeginState.Loc) &&
"state for the wrong buffer");
assert(BufferID == SourceMgr.findBufferContainingLoc(EndState.Loc) &&
"state for the wrong buffer");
unsigned Offset = SourceMgr.getLocOffsetInBuffer(BeginState.Loc, BufferID);
unsigned EndOffset = SourceMgr.getLocOffsetInBuffer(EndState.Loc, BufferID);
initialize(Offset, EndOffset);
}
InFlightDiagnostic Lexer::diagnose(const char *Loc, Diagnostic Diag) {
if (auto *Diags = getTokenDiags())
return Diags->diagnose(getSourceLoc(Loc), Diag);
return InFlightDiagnostic();
}
Token Lexer::getTokenAt(SourceLoc Loc) {
assert(BufferID == static_cast<unsigned>(
SourceMgr.findBufferContainingLoc(Loc)) &&
"location from the wrong buffer");
Lexer L(LangOpts, SourceMgr, BufferID, getUnderlyingDiags(), LexMode,
HashbangMode::Allowed, CommentRetentionMode::None);
L.restoreState(State(Loc));
return L.peekNextToken();
}
void Lexer::formToken(tok Kind, const char *TokStart) {
assert(CurPtr >= BufferStart &&
CurPtr <= BufferEnd && "Current pointer out of range!");
// When we are lexing a subrange from the middle of a file buffer, we will
// run past the end of the range, but will stay within the file. Check if
// we are past the imaginary EOF, and synthesize a tok::eof in this case.
if (Kind != tok::eof && TokStart >= ArtificialEOF) {
Kind = tok::eof;
}
unsigned CommentLength = 0;
if (RetainComments == CommentRetentionMode::AttachToNextToken) {
if (CommentStart) {
CommentLength = TokStart - CommentStart;
}
}
StringRef TokenText { TokStart, static_cast<size_t>(CurPtr - TokStart) };
NextToken.setToken(Kind, TokenText, CommentLength);
}
void Lexer::formEscapedIdentifierToken(const char *TokStart) {
assert(CurPtr - TokStart >= 3 && "escaped identifier must be longer than or equal 3 bytes");
assert(TokStart[0] == '`' && "escaped identifier starts with backtick");
assert(CurPtr[-1] == '`' && "escaped identifier ends with backtick");
formToken(tok::identifier, TokStart);
// If this token is at ArtificialEOF, it's forced to be tok::eof. Don't mark
// this as escaped-identifier in this case.
if (NextToken.is(tok::eof))
return;
NextToken.setEscapedIdentifier(true);
}
static void validateMultilineIndents(const Token &Str, DiagnosticEngine *Diags);
void Lexer::formStringLiteralToken(const char *TokStart,
bool IsMultilineString,
unsigned CustomDelimiterLen) {
formToken(tok::string_literal, TokStart);
if (NextToken.is(tok::eof))
return;
NextToken.setStringLiteral(IsMultilineString, CustomDelimiterLen);
auto *Diags = getTokenDiags();
if (IsMultilineString && Diags)
validateMultilineIndents(NextToken, Diags);
}
Lexer::State Lexer::getStateForBeginningOfTokenLoc(SourceLoc Loc) const {
const char *Ptr = getBufferPtrForSourceLoc(Loc);
// Skip whitespace backwards until we hit a newline. This is needed to
// correctly lex the token if it is at the beginning of the line.
while (Ptr >= ContentStart + 1) {
char C = Ptr[-1];
if (C == ' ' || C == '\t') {
--Ptr;
continue;
}
if (C == 0) {
// A NUL character can be either whitespace we diagnose or a code
// completion token.
if (Ptr - 1 == CodeCompletionPtr)
break;
--Ptr;
continue;
}
if (C == '\n' || C == '\r') {
--Ptr;
break;
}
break;
}
return State(SourceLoc(llvm::SMLoc::getFromPointer(Ptr)));
}
//===----------------------------------------------------------------------===//
// Lexer Subroutines
//===----------------------------------------------------------------------===//
static void diagnoseEmbeddedNul(DiagnosticEngine *Diags, const char *Ptr) {
assert(Ptr && "invalid source location");
assert(*Ptr == '\0' && "not an embedded null");
if (!Diags)
return;
SourceLoc NulLoc = Lexer::getSourceLoc(Ptr);
SourceLoc NulEndLoc = Lexer::getSourceLoc(Ptr+1);
Diags->diagnose(NulLoc, diag::lex_nul_character)
.fixItRemoveChars(NulLoc, NulEndLoc);
}
/// Advance \p CurPtr to the end of line or the end of file. Returns \c true
/// if it stopped at the end of line, \c false if it stopped at the end of file.
static bool advanceToEndOfLine(const char *&CurPtr, const char *BufferEnd,
const char *CodeCompletionPtr = nullptr,
DiagnosticEngine *Diags = nullptr) {
while (1) {
switch (*CurPtr++) {
case '\n':
case '\r':
--CurPtr;
return true; // If we found the end of the line, return.
default:
// If this is a "high" UTF-8 character, validate it.
if (Diags && (signed char)(CurPtr[-1]) < 0) {
--CurPtr;
const char *CharStart = CurPtr;
if (validateUTF8CharacterAndAdvance(CurPtr, BufferEnd) == ~0U)
Diags->diagnose(Lexer::getSourceLoc(CharStart),
diag::lex_invalid_utf8);
}
break; // Otherwise, eat other characters.
case 0:
if (CurPtr - 1 != BufferEnd) {
if (Diags && CurPtr - 1 != CodeCompletionPtr) {
// If this is a random nul character in the middle of a buffer, skip
// it as whitespace.
diagnoseEmbeddedNul(Diags, CurPtr - 1);
}
continue;
}
// Otherwise, the last line of the file does not have a newline.
--CurPtr;
return false;
}
}
}
void Lexer::skipToEndOfLine(bool EatNewline) {
bool isEOL =
advanceToEndOfLine(CurPtr, BufferEnd, CodeCompletionPtr, getTokenDiags());
if (EatNewline && isEOL) {
++CurPtr;
NextToken.setAtStartOfLine(true);
}
}
void Lexer::skipSlashSlashComment(bool EatNewline) {
assert(CurPtr[-1] == '/' && CurPtr[0] == '/' && "Not a // comment");
skipToEndOfLine(EatNewline);
}
void Lexer::skipHashbang(bool EatNewline) {
assert(CurPtr == ContentStart && CurPtr[0] == '#' && CurPtr[1] == '!' &&
"Not a hashbang");
skipToEndOfLine(EatNewline);
}
static bool skipToEndOfSlashStarComment(const char *&CurPtr,
const char *BufferEnd,
const char *CodeCompletionPtr = nullptr,
DiagnosticEngine *Diags = nullptr) {
const char *StartPtr = CurPtr-1;
assert(CurPtr[-1] == '/' && CurPtr[0] == '*' && "Not a /* comment");
// Make sure to advance over the * so that we don't incorrectly handle /*/ as
// the beginning and end of the comment.
++CurPtr;
// /**/ comments can be nested, keep track of how deep we've gone.
unsigned Depth = 1;
bool isMultiline = false;
while (1) {
switch (*CurPtr++) {
case '*':
// Check for a '*/'
if (*CurPtr == '/') {
++CurPtr;
if (--Depth == 0)
return isMultiline;
}
break;
case '/':
// Check for a '/*'
if (*CurPtr == '*') {
++CurPtr;
++Depth;
}
break;
case '\n':
case '\r':
isMultiline = true;
break;
default:
// If this is a "high" UTF-8 character, validate it.
if (Diags && (signed char)(CurPtr[-1]) < 0) {
--CurPtr;
const char *CharStart = CurPtr;
if (validateUTF8CharacterAndAdvance(CurPtr, BufferEnd) == ~0U)
Diags->diagnose(Lexer::getSourceLoc(CharStart),
diag::lex_invalid_utf8);
}
break; // Otherwise, eat other characters.
case 0:
if (CurPtr - 1 != BufferEnd) {
if (Diags && CurPtr - 1 != CodeCompletionPtr) {
// If this is a random nul character in the middle of a buffer, skip
// it as whitespace.
diagnoseEmbeddedNul(Diags, CurPtr - 1);
}
continue;
}
// Otherwise, we have an unterminated /* comment.
--CurPtr;
if (Diags) {
// Count how many levels deep we are.
llvm::SmallString<8> Terminator("*/");
while (--Depth != 0)
Terminator += "*/";
const char *EOL = (CurPtr[-1] == '\n') ? (CurPtr - 1) : CurPtr;
Diags
->diagnose(Lexer::getSourceLoc(EOL),
diag::lex_unterminated_block_comment)
.fixItInsert(Lexer::getSourceLoc(EOL), Terminator);
Diags->diagnose(Lexer::getSourceLoc(StartPtr), diag::lex_comment_start);
}
return isMultiline;
}
}
}
/// skipSlashStarComment - /**/ comments are skipped (treated as whitespace).
/// Note that (unlike in C) block comments can be nested.
void Lexer::skipSlashStarComment() {
bool isMultiline = skipToEndOfSlashStarComment(
CurPtr, BufferEnd, CodeCompletionPtr, getTokenDiags());
if (isMultiline)
NextToken.setAtStartOfLine(true);
}
static bool isValidIdentifierContinuationCodePoint(uint32_t c) {
if (c < 0x80)
return clang::isAsciiIdentifierContinue(c, /*dollar*/true);
// N1518: Recommendations for extended identifier characters for C and C++
// Proposed Annex X.1: Ranges of characters allowed
return c == 0x00A8 || c == 0x00AA || c == 0x00AD || c == 0x00AF
|| (c >= 0x00B2 && c <= 0x00B5) || (c >= 0x00B7 && c <= 0x00BA)
|| (c >= 0x00BC && c <= 0x00BE) || (c >= 0x00C0 && c <= 0x00D6)
|| (c >= 0x00D8 && c <= 0x00F6) || (c >= 0x00F8 && c <= 0x00FF)
|| (c >= 0x0100 && c <= 0x167F)
|| (c >= 0x1681 && c <= 0x180D)
|| (c >= 0x180F && c <= 0x1FFF)
|| (c >= 0x200B && c <= 0x200D)
|| (c >= 0x202A && c <= 0x202E)
|| (c >= 0x203F && c <= 0x2040)
|| c == 0x2054
|| (c >= 0x2060 && c <= 0x206F)
|| (c >= 0x2070 && c <= 0x218F)
|| (c >= 0x2460 && c <= 0x24FF)
|| (c >= 0x2776 && c <= 0x2793)
|| (c >= 0x2C00 && c <= 0x2DFF)
|| (c >= 0x2E80 && c <= 0x2FFF)
|| (c >= 0x3004 && c <= 0x3007)
|| (c >= 0x3021 && c <= 0x302F)
|| (c >= 0x3031 && c <= 0x303F)
|| (c >= 0x3040 && c <= 0xD7FF)
|| (c >= 0xF900 && c <= 0xFD3D)
|| (c >= 0xFD40 && c <= 0xFDCF)
|| (c >= 0xFDF0 && c <= 0xFE44)
|| (c >= 0xFE47 && c <= 0xFFF8)
|| (c >= 0x10000 && c <= 0x1FFFD)
|| (c >= 0x20000 && c <= 0x2FFFD)
|| (c >= 0x30000 && c <= 0x3FFFD)
|| (c >= 0x40000 && c <= 0x4FFFD)
|| (c >= 0x50000 && c <= 0x5FFFD)
|| (c >= 0x60000 && c <= 0x6FFFD)
|| (c >= 0x70000 && c <= 0x7FFFD)
|| (c >= 0x80000 && c <= 0x8FFFD)
|| (c >= 0x90000 && c <= 0x9FFFD)
|| (c >= 0xA0000 && c <= 0xAFFFD)
|| (c >= 0xB0000 && c <= 0xBFFFD)
|| (c >= 0xC0000 && c <= 0xCFFFD)
|| (c >= 0xD0000 && c <= 0xDFFFD)
|| (c >= 0xE0000 && c <= 0xEFFFD);
}
static bool isValidIdentifierStartCodePoint(uint32_t c) {
if (!isValidIdentifierContinuationCodePoint(c))
return false;
if (c < 0x80 && (isDigit(c) || c == '$'))
return false;
// N1518: Recommendations for extended identifier characters for C and C++
// Proposed Annex X.2: Ranges of characters disallowed initially
if ((c >= 0x0300 && c <= 0x036F) ||
(c >= 0x1DC0 && c <= 0x1DFF) ||
(c >= 0x20D0 && c <= 0x20FF) ||
(c >= 0xFE20 && c <= 0xFE2F))
return false;
return true;
}
static bool isForbiddenRawIdentifierWhitespace(uint32_t c) {
if ((c >= 0x0009 && c <= 0x000D) ||
c == 0x0085 ||
c == 0x00A0 ||
c == 0x1680 ||
(c >= 0x2000 && c <= 0x200A) ||
(c >= 0x2028 && c <= 0x2029) ||
c == 0x202F ||
c == 0x205F ||
c == 0x3000)
return true;
return false;
}
static bool isPermittedRawIdentifierWhitespace(uint32_t c) {
return c == 0x0020 || c == 0x200E || c == 0x200F;
}
static bool isValidIdentifierEscapedCodePoint(uint32_t c) {
// An escaped identifier is terminated by a backtick, and the backslash is
// reserved for possible future escaping.
if (c == '`' || c == '\\')
return false;
if ((c >= 0x0000 && c <= 0x001F) || c == 0x007F)
return false;
// This is the set of code points satisfying the `White_Space` property,
// excluding the set satisfying the `Pattern_White_Space` property, and
// excluding any other ASCII non-printables and Unicode separators. In
// other words, the only whitespace code points allowed in a raw
// identifier are U+0020, and U+200E/200F (LTR/RTL marks).
if (isForbiddenRawIdentifierWhitespace(c))
return false;
return true;
}
static bool advanceIf(char const *&ptr, char const *end,
bool (*predicate)(uint32_t)) {
char const *next = ptr;
uint32_t c = validateUTF8CharacterAndAdvance(next, end);
if (c == ~0U)
return false;
if (predicate(c)) {
ptr = next;
return true;
}
return false;
}
static bool advanceIfValidStartOfIdentifier(char const *&ptr,
char const *end) {
return advanceIf(ptr, end, isValidIdentifierStartCodePoint);
}
static bool advanceIfValidContinuationOfIdentifier(char const *&ptr,
char const *end) {
return advanceIf(ptr, end, isValidIdentifierContinuationCodePoint);
}
static bool advanceIfValidEscapedIdentifier(char const *&ptr, char const *end) {
return advanceIf(ptr, end, isValidIdentifierEscapedCodePoint);
}
static bool advanceIfValidStartOfOperator(char const *&ptr,
char const *end) {
return advanceIf(ptr, end, Identifier::isOperatorStartCodePoint);
}
static bool advanceIfValidContinuationOfOperator(char const *&ptr,
char const *end) {
return advanceIf(ptr, end, Identifier::isOperatorContinuationCodePoint);
}
/// Returns true if the given string is entirely whitespace (considering only
/// those whitespace code points permitted in raw identifiers).
static bool isEntirelyWhitespace(StringRef string) {
if (string.empty()) return false;
char const *p = string.data(), *end = string.end();
if (!advanceIf(p, end, isPermittedRawIdentifierWhitespace))
return false;
while (p < end && advanceIf(p, end, isPermittedRawIdentifierWhitespace));
return p == end;
}
bool Lexer::isIdentifier(StringRef string) {
if (string.empty()) return false;
char const *p = string.data(), *end = string.end();
if (!advanceIfValidStartOfIdentifier(p, end))
return false;
while (p < end && advanceIfValidContinuationOfIdentifier(p, end));
return p == end;
}
bool Lexer::identifierMustAlwaysBeEscaped(StringRef str) {
if (str.empty())
return false;
bool mustEscape =
!isOperator(str) && !isIdentifier(str) &&
str.front() != '$'; // a property wrapper does not need to be escaped
// dollar sign must be escaped
if (str == "$") {
mustEscape = true;
}
return mustEscape;
}
bool Lexer::isValidAsEscapedIdentifier(StringRef string) {
if (string.empty())
return false;
char const *p = string.data(), *end = string.end();
if (!advanceIfValidEscapedIdentifier(p, end))
return false;
while (p < end && advanceIfValidEscapedIdentifier(p, end))
;
if (p != end)
return false;
return !isEntirelyWhitespace(string);
}
/// Determines if the given string is a valid operator identifier,
/// without escaping characters.
bool Lexer::isOperator(StringRef string) {
if (string.empty()) return false;
char const *p = string.data(), *end = string.end();
if (!advanceIfValidStartOfOperator(p, end))
return false;
while (p < end && advanceIfValidContinuationOfOperator(p, end));
return p == end;
}
tok Lexer::kindOfIdentifier(StringRef Str, bool InSILMode) {
#define SIL_KEYWORD(kw)
#define KEYWORD(kw) if (Str == #kw) return tok::kw_##kw;
#include "swift/AST/TokenKinds.def"
// SIL keywords are only active in SIL mode.
if (InSILMode) {
#define SIL_KEYWORD(kw) if (Str == #kw) return tok::kw_##kw;
#include "swift/AST/TokenKinds.def"
}
return tok::identifier;
}
/// lexIdentifier - Match [a-zA-Z_][a-zA-Z_$0-9]*
void Lexer::lexIdentifier() {
const char *TokStart = CurPtr-1;
CurPtr = TokStart;
bool didStart = advanceIfValidStartOfIdentifier(CurPtr, BufferEnd);
assert(didStart && "Unexpected start");
(void) didStart;
// Lex [a-zA-Z_$0-9[[:XID_Continue:]]]*
while (advanceIfValidContinuationOfIdentifier(CurPtr, BufferEnd));
tok Kind = kindOfIdentifier(StringRef(TokStart, CurPtr-TokStart),
LexMode == LexerMode::SIL);
return formToken(Kind, TokStart);
}
/// lexHash - Handle #], #! for shebangs, and the family of #identifiers.
void Lexer::lexHash() {
const char *TokStart = CurPtr-1;
// Scan for [a-zA-Z]+ to see what we match.
const char *tmpPtr = CurPtr;
if (clang::isAsciiIdentifierStart(*tmpPtr)) {
do {
++tmpPtr;
} while (clang::isAsciiIdentifierContinue(*tmpPtr));
}
// Map the character sequence onto
tok Kind = llvm::StringSwitch<tok>(StringRef(CurPtr, tmpPtr-CurPtr))
#define POUND_KEYWORD(id) \
.Case(#id, tok::pound_##id)
#include "swift/AST/TokenKinds.def"
.Default(tok::pound);
// If we found '#assert' but that experimental feature is not enabled,
// treat it as '#'.
if (Kind == tok::pound_assert && !LangOpts.hasFeature(Feature::StaticAssert))
Kind = tok::pound;
// If we didn't find a match, then just return tok::pound. This is highly
// dubious in terms of error recovery, but is useful for code completion and
// SIL parsing.
if (Kind == tok::pound)
return formToken(tok::pound, TokStart);
// If we found something specific, return it.
CurPtr = tmpPtr;
return formToken(Kind, TokStart);
}
/// Is the operator beginning at the given character "left-bound"?
static bool isLeftBound(const char *tokBegin, const char *bufferBegin) {
// The first character in the file is not left-bound.
if (tokBegin == bufferBegin) return false;
switch (tokBegin[-1]) {
case ' ': case '\r': case '\n': case '\t': // whitespace
case '(': case '[': case '{': // opening delimiters
case ',': case ';': case ':': // expression separators
case '\0': // whitespace / last char in file
return false;
case '/':
if (tokBegin - 1 != bufferBegin && tokBegin[-2] == '*')
return false; // End of a slash-star comment, so whitespace.
else
return true;
case '\xA0':
if (tokBegin - 1 != bufferBegin && tokBegin[-2] == '\xC2')
return false; // Non-breaking whitespace (U+00A0)
else
return true;
default:
return true;
}
}
/// Is the operator ending at the given character (actually one past the end)
/// "right-bound"?
///
/// The code-completion point is considered right-bound.
static bool isRightBound(const char *tokEnd, bool isLeftBound,
const char *codeCompletionPtr) {
switch (*tokEnd) {
case ' ': case '\r': case '\n': case '\t': // whitespace
case ')': case ']': case '}': // closing delimiters
case ',': case ';': case ':': // expression separators
return false;
case '\0':
if (tokEnd == codeCompletionPtr) // code-completion
return true;
return false; // whitespace / last char in file
case '.':
// Prefer the '^' in "x^.y" to be a postfix op, not binary, but the '^' in
// "^.y" to be a prefix op, not binary.
return !isLeftBound;
case '/':
// A following comment counts as whitespace, so this token is not right bound.
if (tokEnd[1] == '/' || tokEnd[1] == '*')
return false;
else
return true;
case '\xC2':
if (tokEnd[1] == '\xA0')
return false; // Non-breaking whitespace (U+00A0)
else
return true;
default:
return true;
}
}
static bool rangeContainsPlaceholderEnd(const char *CurPtr,
const char *End) {
for (auto SubStr = CurPtr; SubStr != End - 1; ++SubStr) {
if (SubStr[0] == '\n') {
return false;
}
if (SubStr[0] == '#' && SubStr[1] == '>') {
return true;
}
}
return false;
}
/// lexOperatorIdentifier - Match identifiers formed out of punctuation.
void Lexer::lexOperatorIdentifier() {
const char *TokStart = CurPtr-1;
CurPtr = TokStart;
bool didStart = advanceIfValidStartOfOperator(CurPtr, BufferEnd);
assert(didStart && "unexpected operator start");
(void) didStart;
do {
if (CurPtr != BufferEnd && InSILBody &&
(*CurPtr == '!' || *CurPtr == '?'))
// When parsing SIL body, '!' and '?' are special token and can't be
// in the middle of an operator.
break;
// '.' cannot appear in the middle of an operator unless the operator
// started with a '.'.
if (*CurPtr == '.' && *TokStart != '.')
break;
if (Identifier::isEditorPlaceholder(StringRef(CurPtr, BufferEnd-CurPtr)) &&
rangeContainsPlaceholderEnd(CurPtr + 2, BufferEnd)) {
break;
}
// If we are lexing a `/.../` regex literal, we don't consider `/` to be an
// operator character.
if (ForwardSlashRegexMode != LexerForwardSlashRegexMode::None &&
*CurPtr == '/') {
break;
}
} while (advanceIfValidContinuationOfOperator(CurPtr, BufferEnd));
if (CurPtr-TokStart > 2) {
// If there is a "//" or "/*" in the middle of an identifier token,
// it starts a comment.
for (auto Ptr = TokStart+1; Ptr != CurPtr-1; ++Ptr) {
if (Ptr[0] == '/' && (Ptr[1] == '/' || Ptr[1] == '*')) {
CurPtr = Ptr;
break;
}
}
}
// Decide between the binary, prefix, and postfix cases.
// It's binary if either both sides are bound or both sides are not bound.
// Otherwise, it's postfix if left-bound and prefix if right-bound.
bool leftBound = isLeftBound(TokStart, ContentStart);
bool rightBound = isRightBound(CurPtr, leftBound, CodeCompletionPtr);
// Match various reserved words.
if (CurPtr-TokStart == 1) {
switch (TokStart[0]) {
case '=':
// Refrain from emitting this message in operator name position.
if (NextToken.isNot(tok::kw_operator) && leftBound != rightBound) {
auto d = diagnose(TokStart, diag::lex_unary_equal);
if (leftBound)
d.fixItInsert(getSourceLoc(TokStart), " ");
else
d.fixItInsert(getSourceLoc(TokStart+1), " ");
}
// always emit 'tok::equal' to avoid trickle down parse errors
return formToken(tok::equal, TokStart);
case '&':
if (leftBound == rightBound || leftBound)
break;
return formToken(tok::amp_prefix, TokStart);
case '.': {
if (leftBound == rightBound)
return formToken(tok::period, TokStart);
if (rightBound)
return formToken(tok::period_prefix, TokStart);
// If left bound but not right bound, handle some likely situations.
// If there is just some horizontal whitespace before the next token, its
// addition is probably incorrect.
const char *AfterHorzWhitespace = CurPtr;
while (*AfterHorzWhitespace == ' ' || *AfterHorzWhitespace == '\t')
++AfterHorzWhitespace;
// First, when we are code completing "x. <ESC>", then make sure to return
// a tok::period, since that is what the user is wanting to know about.
if (*AfterHorzWhitespace == '\0' &&
AfterHorzWhitespace == CodeCompletionPtr) {
diagnose(TokStart, diag::expected_member_name);
return formToken(tok::period, TokStart);
}
if (isRightBound(AfterHorzWhitespace, leftBound, CodeCompletionPtr) &&
// Don't consider comments to be this. A leading slash is probably
// either // or /* and most likely occurs just in our testsuite for
// expected-error lines.
*AfterHorzWhitespace != '/') {
diagnose(TokStart, diag::extra_whitespace_period)
.fixItRemoveChars(getSourceLoc(CurPtr),
getSourceLoc(AfterHorzWhitespace));
return formToken(tok::period, TokStart);
}
// Otherwise, it is probably a missing member.
diagnose(TokStart, diag::expected_member_name);
return formToken(tok::unknown, TokStart);
}
case '?':
if (leftBound)
return formToken(tok::question_postfix, TokStart);
return formToken(tok::question_infix, TokStart);
}
} else if (CurPtr-TokStart == 2) {
switch ((TokStart[0] << 8) | TokStart[1]) {
case ('-' << 8) | '>': // ->
return formToken(tok::arrow, TokStart);
case ('*' << 8) | '/': // */
diagnose(TokStart, diag::lex_unexpected_block_comment_end);
return formToken(tok::unknown, TokStart);
}
} else {
// Verify there is no "*/" in the middle of the identifier token, we reject
// it as potentially ending a block comment.
auto Pos = StringRef(TokStart, CurPtr-TokStart).find("*/");
if (Pos != StringRef::npos) {
diagnose(TokStart+Pos, diag::lex_unexpected_block_comment_end);
return formToken(tok::unknown, TokStart);
}
}
if (leftBound == rightBound)
return formToken(leftBound ? tok::oper_binary_unspaced :
tok::oper_binary_spaced, TokStart);
return formToken(leftBound ? tok::oper_postfix : tok::oper_prefix, TokStart);
}