clang 22.0.0git
Lexer.cpp
Go to the documentation of this file.
1//===- Lexer.cpp - C Language Family Lexer --------------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the Lexer and Token interfaces.
10//
11//===----------------------------------------------------------------------===//
12
13#include "clang/Lex/Lexer.h"
14#include "UnicodeCharSets.h"
18#include "clang/Basic/LLVM.h"
28#include "clang/Lex/Token.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/StringExtras.h"
31#include "llvm/ADT/StringRef.h"
32#include "llvm/ADT/StringSwitch.h"
33#include "llvm/Support/Compiler.h"
34#include "llvm/Support/ConvertUTF.h"
35#include "llvm/Support/MemoryBufferRef.h"
36#include "llvm/Support/NativeFormatting.h"
37#include "llvm/Support/Unicode.h"
38#include "llvm/Support/UnicodeCharRanges.h"
39#include <algorithm>
40#include <cassert>
41#include <cstddef>
42#include <cstdint>
43#include <cstring>
44#include <limits>
45#include <optional>
46#include <string>
47
48#ifdef __SSE4_2__
49#include <nmmintrin.h>
50#endif
51
52using namespace clang;
53
54//===----------------------------------------------------------------------===//
55// Token Class Implementation
56//===----------------------------------------------------------------------===//
57
58/// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
60 if (isAnnotation())
61 return false;
62 if (const IdentifierInfo *II = getIdentifierInfo())
63 return II->getObjCKeywordID() == objcKey;
64 return false;
65}
66
67/// getObjCKeywordID - Return the ObjC keyword kind.
69 if (isAnnotation())
70 return tok::objc_not_keyword;
71 const IdentifierInfo *specId = getIdentifierInfo();
72 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
73}
74
75/// Determine whether the token kind starts a simple-type-specifier.
76bool Token::isSimpleTypeSpecifier(const LangOptions &LangOpts) const {
77 switch (getKind()) {
78 case tok::annot_typename:
79 case tok::annot_decltype:
80 case tok::annot_pack_indexing_type:
81 return true;
82
83 case tok::kw_short:
84 case tok::kw_long:
85 case tok::kw___int64:
86 case tok::kw___int128:
87 case tok::kw_signed:
88 case tok::kw_unsigned:
89 case tok::kw_void:
90 case tok::kw_char:
91 case tok::kw_int:
92 case tok::kw_half:
93 case tok::kw_float:
94 case tok::kw_double:
95 case tok::kw___bf16:
96 case tok::kw__Float16:
97 case tok::kw___float128:
98 case tok::kw___ibm128:
99 case tok::kw_wchar_t:
100 case tok::kw_bool:
101 case tok::kw__Bool:
102 case tok::kw__Accum:
103 case tok::kw__Fract:
104 case tok::kw__Sat:
105#define TRANSFORM_TYPE_TRAIT_DEF(_, Trait) case tok::kw___##Trait:
106#include "clang/Basic/TransformTypeTraits.def"
107 case tok::kw___auto_type:
108 case tok::kw_char16_t:
109 case tok::kw_char32_t:
110 case tok::kw_typeof:
111 case tok::kw_decltype:
112 case tok::kw_char8_t:
113 return getIdentifierInfo()->isKeyword(LangOpts);
114
115 default:
116 return false;
117 }
118}
119
120//===----------------------------------------------------------------------===//
121// Lexer Class Implementation
122//===----------------------------------------------------------------------===//
123
124void Lexer::anchor() {}
125
126void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
127 const char *BufEnd) {
128 BufferStart = BufStart;
129 BufferPtr = BufPtr;
130 BufferEnd = BufEnd;
131
132 assert(BufEnd[0] == 0 &&
133 "We assume that the input buffer has a null character at the end"
134 " to simplify lexing!");
135
136 // Check whether we have a BOM in the beginning of the buffer. If yes - act
137 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
138 // skip the UTF-8 BOM if it's present.
139 if (BufferStart == BufferPtr) {
140 // Determine the size of the BOM.
141 StringRef Buf(BufferStart, BufferEnd - BufferStart);
142 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
143 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
144 .Default(0);
145
146 // Skip the BOM.
147 BufferPtr += BOMLength;
148 }
149
150 Is_PragmaLexer = false;
151 CurrentConflictMarkerState = CMK_None;
152
153 // Start of the file is a start of line.
154 IsAtStartOfLine = true;
155 IsAtPhysicalStartOfLine = true;
156
157 HasLeadingSpace = false;
158 HasLeadingEmptyMacro = false;
159
160 // We are not after parsing a #.
162
163 // We are not after parsing #include.
164 ParsingFilename = false;
165
166 // We are not in raw mode. Raw mode disables diagnostics and interpretation
167 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
168 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
169 // or otherwise skipping over tokens.
170 LexingRawMode = false;
171
172 // Default to not keeping comments.
173 ExtendedTokenMode = 0;
174
175 NewLinePtr = nullptr;
176}
177
178/// Lexer constructor - Create a new lexer object for the specified buffer
179/// with the specified preprocessor managing the lexing process. This lexer
180/// assumes that the associated file buffer and Preprocessor objects will
181/// outlive it, so it doesn't take ownership of either of them.
182Lexer::Lexer(FileID FID, const llvm::MemoryBufferRef &InputFile,
183 Preprocessor &PP, bool IsFirstIncludeOfFile)
185 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
186 LangOpts(PP.getLangOpts()), LineComment(LangOpts.LineComment),
187 IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
188 InitLexer(InputFile.getBufferStart(), InputFile.getBufferStart(),
189 InputFile.getBufferEnd());
190
192}
193
194/// Lexer constructor - Create a new raw lexer object. This object is only
195/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
196/// range will outlive it, so it doesn't take ownership of it.
197Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
198 const char *BufStart, const char *BufPtr, const char *BufEnd,
199 bool IsFirstIncludeOfFile)
200 : FileLoc(fileloc), LangOpts(langOpts), LineComment(LangOpts.LineComment),
201 IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
202 InitLexer(BufStart, BufPtr, BufEnd);
203
204 // We *are* in raw mode.
205 LexingRawMode = true;
206}
207
208/// Lexer constructor - Create a new raw lexer object. This object is only
209/// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
210/// range will outlive it, so it doesn't take ownership of it.
211Lexer::Lexer(FileID FID, const llvm::MemoryBufferRef &FromFile,
212 const SourceManager &SM, const LangOptions &langOpts,
213 bool IsFirstIncludeOfFile)
214 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile.getBufferStart(),
215 FromFile.getBufferStart(), FromFile.getBufferEnd(),
216 IsFirstIncludeOfFile) {}
217
219 assert(PP && "Cannot reset token mode without a preprocessor");
220 if (LangOpts.TraditionalCPP)
222 else
223 SetCommentRetentionState(PP->getCommentRetentionState());
224}
225
226/// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
227/// _Pragma expansion. This has a variety of magic semantics that this method
228/// sets up. It returns a new'd Lexer that must be delete'd when done.
229///
230/// On entrance to this routine, TokStartLoc is a macro location which has a
231/// spelling loc that indicates the bytes to be lexed for the token and an
232/// expansion location that indicates where all lexed tokens should be
233/// "expanded from".
234///
235/// TODO: It would really be nice to make _Pragma just be a wrapper around a
236/// normal lexer that remaps tokens as they fly by. This would require making
237/// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
238/// interface that could handle this stuff. This would pull GetMappedTokenLoc
239/// out of the critical path of the lexer!
240///
242 SourceLocation ExpansionLocStart,
243 SourceLocation ExpansionLocEnd,
244 unsigned TokLen, Preprocessor &PP) {
245 SourceManager &SM = PP.getSourceManager();
246
247 // Create the lexer as if we were going to lex the file normally.
248 FileID SpellingFID = SM.getFileID(SpellingLoc);
249 llvm::MemoryBufferRef InputFile = SM.getBufferOrFake(SpellingFID);
250 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
251
252 // Now that the lexer is created, change the start/end locations so that we
253 // just lex the subsection of the file that we want. This is lexing from a
254 // scratch buffer.
255 const char *StrData = SM.getCharacterData(SpellingLoc);
256
257 L->BufferPtr = StrData;
258 L->BufferEnd = StrData+TokLen;
259 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
260
261 // Set the SourceLocation with the remapping information. This ensures that
262 // GetMappedTokenLoc will remap the tokens as they are lexed.
263 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
264 ExpansionLocStart,
265 ExpansionLocEnd, TokLen);
266
267 // Ensure that the lexer thinks it is inside a directive, so that end \n will
268 // return an EOD token.
270
271 // This lexer really is for _Pragma.
272 L->Is_PragmaLexer = true;
273 return L;
274}
275
276void Lexer::seek(unsigned Offset, bool IsAtStartOfLine) {
277 this->IsAtPhysicalStartOfLine = IsAtStartOfLine;
278 this->IsAtStartOfLine = IsAtStartOfLine;
279 assert((BufferStart + Offset) <= BufferEnd);
280 BufferPtr = BufferStart + Offset;
281}
282
283template <typename T> static void StringifyImpl(T &Str, char Quote) {
284 typename T::size_type i = 0, e = Str.size();
285 while (i < e) {
286 if (Str[i] == '\\' || Str[i] == Quote) {
287 Str.insert(Str.begin() + i, '\\');
288 i += 2;
289 ++e;
290 } else if (Str[i] == '\n' || Str[i] == '\r') {
291 // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
292 if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
293 Str[i] != Str[i + 1]) {
294 Str[i] = '\\';
295 Str[i + 1] = 'n';
296 } else {
297 // Replace '\n' and '\r' to '\\' followed by 'n'.
298 Str[i] = '\\';
299 Str.insert(Str.begin() + i + 1, 'n');
300 ++e;
301 }
302 i += 2;
303 } else
304 ++i;
305 }
306}
307
308std::string Lexer::Stringify(StringRef Str, bool Charify) {
309 std::string Result = std::string(Str);
310 char Quote = Charify ? '\'' : '"';
311 StringifyImpl(Result, Quote);
312 return Result;
313}
314
316
317//===----------------------------------------------------------------------===//
318// Token Spelling
319//===----------------------------------------------------------------------===//
320
321/// Slow case of getSpelling. Extract the characters comprising the
322/// spelling of this token from the provided input buffer.
323static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
324 const LangOptions &LangOpts, char *Spelling) {
325 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
326
327 size_t Length = 0;
328 const char *BufEnd = BufPtr + Tok.getLength();
329
330 if (tok::isStringLiteral(Tok.getKind())) {
331 // Munch the encoding-prefix and opening double-quote.
332 while (BufPtr < BufEnd) {
333 auto CharAndSize = Lexer::getCharAndSizeNoWarn(BufPtr, LangOpts);
334 Spelling[Length++] = CharAndSize.Char;
335 BufPtr += CharAndSize.Size;
336
337 if (Spelling[Length - 1] == '"')
338 break;
339 }
340
341 // Raw string literals need special handling; trigraph expansion and line
342 // splicing do not occur within their d-char-sequence nor within their
343 // r-char-sequence.
344 if (Length >= 2 &&
345 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
346 // Search backwards from the end of the token to find the matching closing
347 // quote.
348 const char *RawEnd = BufEnd;
349 do --RawEnd; while (*RawEnd != '"');
350 size_t RawLength = RawEnd - BufPtr + 1;
351
352 // Everything between the quotes is included verbatim in the spelling.
353 memcpy(Spelling + Length, BufPtr, RawLength);
354 Length += RawLength;
355 BufPtr += RawLength;
356
357 // The rest of the token is lexed normally.
358 }
359 }
360
361 while (BufPtr < BufEnd) {
362 auto CharAndSize = Lexer::getCharAndSizeNoWarn(BufPtr, LangOpts);
363 Spelling[Length++] = CharAndSize.Char;
364 BufPtr += CharAndSize.Size;
365 }
366
367 assert(Length < Tok.getLength() &&
368 "NeedsCleaning flag set on token that didn't need cleaning!");
369 return Length;
370}
371
372/// getSpelling() - Return the 'spelling' of this token. The spelling of a
373/// token are the characters used to represent the token in the source file
374/// after trigraph expansion and escaped-newline folding. In particular, this
375/// wants to get the true, uncanonicalized, spelling of things like digraphs
376/// UCNs, etc.
378 SmallVectorImpl<char> &buffer,
379 const SourceManager &SM,
380 const LangOptions &options,
381 bool *invalid) {
382 // Break down the source location.
383 FileIDAndOffset locInfo = SM.getDecomposedLoc(loc);
384
385 // Try to the load the file buffer.
386 bool invalidTemp = false;
387 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
388 if (invalidTemp) {
389 if (invalid) *invalid = true;
390 return {};
391 }
392
393 const char *tokenBegin = file.data() + locInfo.second;
394
395 // Lex from the start of the given location.
396 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
397 file.begin(), tokenBegin, file.end());
398 Token token;
399 lexer.LexFromRawLexer(token);
400
401 unsigned length = token.getLength();
402
403 // Common case: no need for cleaning.
404 if (!token.needsCleaning())
405 return StringRef(tokenBegin, length);
406
407 // Hard case, we need to relex the characters into the string.
408 buffer.resize(length);
409 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
410 return StringRef(buffer.data(), buffer.size());
411}
412
413/// getSpelling() - Return the 'spelling' of this token. The spelling of a
414/// token are the characters used to represent the token in the source file
415/// after trigraph expansion and escaped-newline folding. In particular, this
416/// wants to get the true, uncanonicalized, spelling of things like digraphs
417/// UCNs, etc.
418std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
419 const LangOptions &LangOpts, bool *Invalid) {
420 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
421
422 bool CharDataInvalid = false;
423 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
424 &CharDataInvalid);
425 if (Invalid)
426 *Invalid = CharDataInvalid;
427 if (CharDataInvalid)
428 return {};
429
430 // If this token contains nothing interesting, return it directly.
431 if (!Tok.needsCleaning())
432 return std::string(TokStart, TokStart + Tok.getLength());
433
434 std::string Result;
435 Result.resize(Tok.getLength());
436 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
437 return Result;
438}
439
440/// getSpelling - This method is used to get the spelling of a token into a
441/// preallocated buffer, instead of as an std::string. The caller is required
442/// to allocate enough space for the token, which is guaranteed to be at least
443/// Tok.getLength() bytes long. The actual length of the token is returned.
444///
445/// Note that this method may do two possible things: it may either fill in
446/// the buffer specified with characters, or it may *change the input pointer*
447/// to point to a constant buffer with the data already in it (avoiding a
448/// copy). The caller is not allowed to modify the returned buffer pointer
449/// if an internal buffer is returned.
450unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
451 const SourceManager &SourceMgr,
452 const LangOptions &LangOpts, bool *Invalid) {
453 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
454
455 const char *TokStart = nullptr;
456 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
457 if (Tok.is(tok::raw_identifier))
458 TokStart = Tok.getRawIdentifier().data();
459 else if (!Tok.hasUCN()) {
460 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
461 // Just return the string from the identifier table, which is very quick.
462 Buffer = II->getNameStart();
463 return II->getLength();
464 }
465 }
466
467 // NOTE: this can be checked even after testing for an IdentifierInfo.
468 if (Tok.isLiteral())
469 TokStart = Tok.getLiteralData();
470
471 if (!TokStart) {
472 // Compute the start of the token in the input lexer buffer.
473 bool CharDataInvalid = false;
474 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
475 if (Invalid)
476 *Invalid = CharDataInvalid;
477 if (CharDataInvalid) {
478 Buffer = "";
479 return 0;
480 }
481 }
482
483 // If this token contains nothing interesting, return it directly.
484 if (!Tok.needsCleaning()) {
485 Buffer = TokStart;
486 return Tok.getLength();
487 }
488
489 // Otherwise, hard case, relex the characters into the string.
490 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
491}
492
493/// MeasureTokenLength - Relex the token at the specified location and return
494/// its length in bytes in the input file. If the token needs cleaning (e.g.
495/// includes a trigraph or an escaped newline) then this count includes bytes
496/// that are part of that.
498 const SourceManager &SM,
499 const LangOptions &LangOpts) {
500 Token TheTok;
501 if (getRawToken(Loc, TheTok, SM, LangOpts))
502 return 0;
503 return TheTok.getLength();
504}
505
506/// Relex the token at the specified location.
507/// \returns true if there was a failure, false on success.
509 const SourceManager &SM,
510 const LangOptions &LangOpts,
511 bool IgnoreWhiteSpace) {
512 // TODO: this could be special cased for common tokens like identifiers, ')',
513 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
514 // all obviously single-char tokens. This could use
515 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
516 // something.
517
518 // If this comes from a macro expansion, we really do want the macro name, not
519 // the token this macro expanded to.
520 Loc = SM.getExpansionLoc(Loc);
521 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
522 bool Invalid = false;
523 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
524 if (Invalid)
525 return true;
526
527 const char *StrData = Buffer.data()+LocInfo.second;
528
529 if (!IgnoreWhiteSpace && isWhitespace(SkipEscapedNewLines(StrData)[0]))
530 return true;
531
532 // Create a lexer starting at the beginning of this token.
533 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
534 Buffer.begin(), StrData, Buffer.end());
535 TheLexer.SetCommentRetentionState(true);
536 TheLexer.LexFromRawLexer(Result);
537 return false;
538}
539
540/// Returns the pointer that points to the beginning of line that contains
541/// the given offset, or null if the offset if invalid.
542static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
543 const char *BufStart = Buffer.data();
544 if (Offset >= Buffer.size())
545 return nullptr;
546
547 const char *LexStart = BufStart + Offset;
548 for (; LexStart != BufStart; --LexStart) {
549 if (isVerticalWhitespace(LexStart[0]) &&
550 !Lexer::isNewLineEscaped(BufStart, LexStart)) {
551 // LexStart should point at first character of logical line.
552 ++LexStart;
553 break;
554 }
555 }
556 return LexStart;
557}
558
560 const SourceManager &SM,
561 const LangOptions &LangOpts) {
562 assert(Loc.isFileID());
563 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
564 if (LocInfo.first.isInvalid())
565 return Loc;
566
567 bool Invalid = false;
568 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
569 if (Invalid)
570 return Loc;
571
572 // Back up from the current location until we hit the beginning of a line
573 // (or the buffer). We'll relex from that point.
574 const char *StrData = Buffer.data() + LocInfo.second;
575 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
576 if (!LexStart || LexStart == StrData)
577 return Loc;
578
579 // Create a lexer starting at the beginning of this token.
580 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
581 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
582 Buffer.end());
583 TheLexer.SetCommentRetentionState(true);
584
585 // Lex tokens until we find the token that contains the source location.
586 Token TheTok;
587 do {
588 TheLexer.LexFromRawLexer(TheTok);
589
590 if (TheLexer.getBufferLocation() > StrData) {
591 // Lexing this token has taken the lexer past the source location we're
592 // looking for. If the current token encompasses our source location,
593 // return the beginning of that token.
594 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
595 return TheTok.getLocation();
596
597 // We ended up skipping over the source location entirely, which means
598 // that it points into whitespace. We're done here.
599 break;
600 }
601 } while (TheTok.getKind() != tok::eof);
602
603 // We've passed our source location; just return the original source location.
604 return Loc;
605}
606
608 const SourceManager &SM,
609 const LangOptions &LangOpts) {
610 if (Loc.isFileID())
611 return getBeginningOfFileToken(Loc, SM, LangOpts);
612
613 if (!SM.isMacroArgExpansion(Loc))
614 return Loc;
615
616 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
617 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
618 FileIDAndOffset FileLocInfo = SM.getDecomposedLoc(FileLoc);
619 FileIDAndOffset BeginFileLocInfo = SM.getDecomposedLoc(BeginFileLoc);
620 assert(FileLocInfo.first == BeginFileLocInfo.first &&
621 FileLocInfo.second >= BeginFileLocInfo.second);
622 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
623}
624
625namespace {
626
627enum PreambleDirectiveKind {
628 PDK_Skipped,
629 PDK_Unknown
630};
631
632} // namespace
633
635 const LangOptions &LangOpts,
636 unsigned MaxLines) {
637 // Create a lexer starting at the beginning of the file. Note that we use a
638 // "fake" file source location at offset 1 so that the lexer will track our
639 // position within the file.
640 const SourceLocation::UIntTy StartOffset = 1;
642 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
643 Buffer.end());
644 TheLexer.SetCommentRetentionState(true);
645
646 bool InPreprocessorDirective = false;
647 Token TheTok;
648 SourceLocation ActiveCommentLoc;
649
650 unsigned MaxLineOffset = 0;
651 if (MaxLines) {
652 const char *CurPtr = Buffer.begin();
653 unsigned CurLine = 0;
654 while (CurPtr != Buffer.end()) {
655 char ch = *CurPtr++;
656 if (ch == '\n') {
657 ++CurLine;
658 if (CurLine == MaxLines)
659 break;
660 }
661 }
662 if (CurPtr != Buffer.end())
663 MaxLineOffset = CurPtr - Buffer.begin();
664 }
665
666 do {
667 TheLexer.LexFromRawLexer(TheTok);
668
669 if (InPreprocessorDirective) {
670 // If we've hit the end of the file, we're done.
671 if (TheTok.getKind() == tok::eof) {
672 break;
673 }
674
675 // If we haven't hit the end of the preprocessor directive, skip this
676 // token.
677 if (!TheTok.isAtStartOfLine())
678 continue;
679
680 // We've passed the end of the preprocessor directive, and will look
681 // at this token again below.
682 InPreprocessorDirective = false;
683 }
684
685 // Keep track of the # of lines in the preamble.
686 if (TheTok.isAtStartOfLine()) {
687 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
688
689 // If we were asked to limit the number of lines in the preamble,
690 // and we're about to exceed that limit, we're done.
691 if (MaxLineOffset && TokOffset >= MaxLineOffset)
692 break;
693 }
694
695 // Comments are okay; skip over them.
696 if (TheTok.getKind() == tok::comment) {
697 if (ActiveCommentLoc.isInvalid())
698 ActiveCommentLoc = TheTok.getLocation();
699 continue;
700 }
701
702 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
703 // This is the start of a preprocessor directive.
704 Token HashTok = TheTok;
705 InPreprocessorDirective = true;
706 ActiveCommentLoc = SourceLocation();
707
708 // Figure out which directive this is. Since we're lexing raw tokens,
709 // we don't have an identifier table available. Instead, just look at
710 // the raw identifier to recognize and categorize preprocessor directives.
711 TheLexer.LexFromRawLexer(TheTok);
712 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
713 StringRef Keyword = TheTok.getRawIdentifier();
714 PreambleDirectiveKind PDK
715 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
716 .Case("include", PDK_Skipped)
717 .Case("__include_macros", PDK_Skipped)
718 .Case("define", PDK_Skipped)
719 .Case("undef", PDK_Skipped)
720 .Case("line", PDK_Skipped)
721 .Case("error", PDK_Skipped)
722 .Case("pragma", PDK_Skipped)
723 .Case("import", PDK_Skipped)
724 .Case("include_next", PDK_Skipped)
725 .Case("warning", PDK_Skipped)
726 .Case("ident", PDK_Skipped)
727 .Case("sccs", PDK_Skipped)
728 .Case("assert", PDK_Skipped)
729 .Case("unassert", PDK_Skipped)
730 .Case("if", PDK_Skipped)
731 .Case("ifdef", PDK_Skipped)
732 .Case("ifndef", PDK_Skipped)
733 .Case("elif", PDK_Skipped)
734 .Case("elifdef", PDK_Skipped)
735 .Case("elifndef", PDK_Skipped)
736 .Case("else", PDK_Skipped)
737 .Case("endif", PDK_Skipped)
738 .Default(PDK_Unknown);
739
740 switch (PDK) {
741 case PDK_Skipped:
742 continue;
743
744 case PDK_Unknown:
745 // We don't know what this directive is; stop at the '#'.
746 break;
747 }
748 }
749
750 // We only end up here if we didn't recognize the preprocessor
751 // directive or it was one that can't occur in the preamble at this
752 // point. Roll back the current token to the location of the '#'.
753 TheTok = HashTok;
754 } else if (TheTok.isAtStartOfLine() &&
755 TheTok.getKind() == tok::raw_identifier &&
756 TheTok.getRawIdentifier() == "module" &&
757 LangOpts.CPlusPlusModules) {
758 // The initial global module fragment introducer "module;" is part of
759 // the preamble, which runs up to the module declaration "module foo;".
760 Token ModuleTok = TheTok;
761 do {
762 TheLexer.LexFromRawLexer(TheTok);
763 } while (TheTok.getKind() == tok::comment);
764 if (TheTok.getKind() != tok::semi) {
765 // Not global module fragment, roll back.
766 TheTok = ModuleTok;
767 break;
768 }
769 continue;
770 }
771
772 // We hit a token that we don't recognize as being in the
773 // "preprocessing only" part of the file, so we're no longer in
774 // the preamble.
775 break;
776 } while (true);
777
778 SourceLocation End;
779 if (ActiveCommentLoc.isValid())
780 End = ActiveCommentLoc; // don't truncate a decl comment.
781 else
782 End = TheTok.getLocation();
783
784 return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
785 TheTok.isAtStartOfLine());
786}
787
788unsigned Lexer::getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo,
789 const SourceManager &SM,
790 const LangOptions &LangOpts) {
791 // Figure out how many physical characters away the specified expansion
792 // character is. This needs to take into consideration newlines and
793 // trigraphs.
794 bool Invalid = false;
795 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
796
797 // If they request the first char of the token, we're trivially done.
798 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
799 return 0;
800
801 unsigned PhysOffset = 0;
802
803 // The usual case is that tokens don't contain anything interesting. Skip
804 // over the uninteresting characters. If a token only consists of simple
805 // chars, this method is extremely fast.
806 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
807 if (CharNo == 0)
808 return PhysOffset;
809 ++TokPtr;
810 --CharNo;
811 ++PhysOffset;
812 }
813
814 // If we have a character that may be a trigraph or escaped newline, use a
815 // lexer to parse it correctly.
816 for (; CharNo; --CharNo) {
817 auto CharAndSize = Lexer::getCharAndSizeNoWarn(TokPtr, LangOpts);
818 TokPtr += CharAndSize.Size;
819 PhysOffset += CharAndSize.Size;
820 }
821
822 // Final detail: if we end up on an escaped newline, we want to return the
823 // location of the actual byte of the token. For example foo<newline>bar
824 // advanced by 3 should return the location of b, not of \\. One compounding
825 // detail of this is that the escape may be made by a trigraph.
826 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
827 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
828
829 return PhysOffset;
830}
831
832/// Computes the source location just past the end of the
833/// token at this source location.
834///
835/// This routine can be used to produce a source location that
836/// points just past the end of the token referenced by \p Loc, and
837/// is generally used when a diagnostic needs to point just after a
838/// token where it expected something different that it received. If
839/// the returned source location would not be meaningful (e.g., if
840/// it points into a macro), this routine returns an invalid
841/// source location.
842///
843/// \param Offset an offset from the end of the token, where the source
844/// location should refer to. The default offset (0) produces a source
845/// location pointing just past the end of the token; an offset of 1 produces
846/// a source location pointing to the last character in the token, etc.
848 const SourceManager &SM,
849 const LangOptions &LangOpts) {
850 if (Loc.isInvalid())
851 return {};
852
853 if (Loc.isMacroID()) {
854 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
855 return {}; // Points inside the macro expansion.
856 }
857
858 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
859 if (Len > Offset)
860 Len = Len - Offset;
861 else
862 return Loc;
863
864 return Loc.getLocWithOffset(Len);
865}
866
867/// Returns true if the given MacroID location points at the first
868/// token of the macro expansion.
870 const SourceManager &SM,
871 const LangOptions &LangOpts,
872 SourceLocation *MacroBegin) {
873 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
874
875 SourceLocation expansionLoc;
876 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
877 return false;
878
879 if (expansionLoc.isFileID()) {
880 // No other macro expansions, this is the first.
881 if (MacroBegin)
882 *MacroBegin = expansionLoc;
883 return true;
884 }
885
886 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
887}
888
889/// Returns true if the given MacroID location points at the last
890/// token of the macro expansion.
892 const SourceManager &SM,
893 const LangOptions &LangOpts,
894 SourceLocation *MacroEnd) {
895 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
896
897 SourceLocation spellLoc = SM.getSpellingLoc(loc);
898 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
899 if (tokLen == 0)
900 return false;
901
902 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
903 SourceLocation expansionLoc;
904 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
905 return false;
906
907 if (expansionLoc.isFileID()) {
908 // No other macro expansions.
909 if (MacroEnd)
910 *MacroEnd = expansionLoc;
911 return true;
912 }
913
914 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
915}
916
918 const SourceManager &SM,
919 const LangOptions &LangOpts) {
920 SourceLocation Begin = Range.getBegin();
921 SourceLocation End = Range.getEnd();
922 assert(Begin.isFileID() && End.isFileID());
923 if (Range.isTokenRange()) {
924 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
925 if (End.isInvalid())
926 return {};
927 }
928
929 // Break down the source locations.
930 auto [FID, BeginOffs] = SM.getDecomposedLoc(Begin);
931 if (FID.isInvalid())
932 return {};
933
934 unsigned EndOffs;
935 if (!SM.isInFileID(End, FID, &EndOffs) ||
936 BeginOffs > EndOffs)
937 return {};
938
939 return CharSourceRange::getCharRange(Begin, End);
940}
941
942// Assumes that `Loc` is in an expansion.
944 const SourceManager &SM) {
945 return SM.getSLocEntry(SM.getFileID(Loc))
946 .getExpansion()
947 .isExpansionTokenRange();
948}
949
951 const SourceManager &SM,
952 const LangOptions &LangOpts) {
953 SourceLocation Begin = Range.getBegin();
954 SourceLocation End = Range.getEnd();
955 if (Begin.isInvalid() || End.isInvalid())
956 return {};
957
958 if (Begin.isFileID() && End.isFileID())
959 return makeRangeFromFileLocs(Range, SM, LangOpts);
960
961 if (Begin.isMacroID() && End.isFileID()) {
962 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
963 return {};
964 Range.setBegin(Begin);
965 return makeRangeFromFileLocs(Range, SM, LangOpts);
966 }
967
968 if (Begin.isFileID() && End.isMacroID()) {
969 if (Range.isTokenRange()) {
970 if (!isAtEndOfMacroExpansion(End, SM, LangOpts, &End))
971 return {};
972 // Use the *original* end, not the expanded one in `End`.
973 Range.setTokenRange(isInExpansionTokenRange(Range.getEnd(), SM));
974 } else if (!isAtStartOfMacroExpansion(End, SM, LangOpts, &End))
975 return {};
976 Range.setEnd(End);
977 return makeRangeFromFileLocs(Range, SM, LangOpts);
978 }
979
980 assert(Begin.isMacroID() && End.isMacroID());
981 SourceLocation MacroBegin, MacroEnd;
982 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
983 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
984 &MacroEnd)) ||
985 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
986 &MacroEnd)))) {
987 Range.setBegin(MacroBegin);
988 Range.setEnd(MacroEnd);
989 // Use the *original* `End`, not the expanded one in `MacroEnd`.
990 if (Range.isTokenRange())
991 Range.setTokenRange(isInExpansionTokenRange(End, SM));
992 return makeRangeFromFileLocs(Range, SM, LangOpts);
993 }
994
995 bool Invalid = false;
996 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
997 &Invalid);
998 if (Invalid)
999 return {};
1000
1001 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
1002 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
1003 &Invalid);
1004 if (Invalid)
1005 return {};
1006
1007 if (EndEntry.getExpansion().isMacroArgExpansion() &&
1008 BeginEntry.getExpansion().getExpansionLocStart() ==
1009 EndEntry.getExpansion().getExpansionLocStart()) {
1010 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
1011 Range.setEnd(SM.getImmediateSpellingLoc(End));
1012 return makeFileCharRange(Range, SM, LangOpts);
1013 }
1014 }
1015
1016 return {};
1017}
1018
1020 const SourceManager &SM,
1021 const LangOptions &LangOpts,
1022 bool *Invalid) {
1023 Range = makeFileCharRange(Range, SM, LangOpts);
1024 if (Range.isInvalid()) {
1025 if (Invalid) *Invalid = true;
1026 return {};
1027 }
1028
1029 // Break down the source location.
1030 FileIDAndOffset beginInfo = SM.getDecomposedLoc(Range.getBegin());
1031 if (beginInfo.first.isInvalid()) {
1032 if (Invalid) *Invalid = true;
1033 return {};
1034 }
1035
1036 unsigned EndOffs;
1037 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
1038 beginInfo.second > EndOffs) {
1039 if (Invalid) *Invalid = true;
1040 return {};
1041 }
1042
1043 // Try to the load the file buffer.
1044 bool invalidTemp = false;
1045 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
1046 if (invalidTemp) {
1047 if (Invalid) *Invalid = true;
1048 return {};
1049 }
1050
1051 if (Invalid) *Invalid = false;
1052 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
1053}
1054
1056 const SourceManager &SM,
1057 const LangOptions &LangOpts) {
1058 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
1059
1060 // Find the location of the immediate macro expansion.
1061 while (true) {
1062 FileID FID = SM.getFileID(Loc);
1063 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
1064 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
1065 Loc = Expansion.getExpansionLocStart();
1066 if (!Expansion.isMacroArgExpansion())
1067 break;
1068
1069 // For macro arguments we need to check that the argument did not come
1070 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
1071
1072 // Loc points to the argument id of the macro definition, move to the
1073 // macro expansion.
1074 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
1075 SourceLocation SpellLoc = Expansion.getSpellingLoc();
1076 if (SpellLoc.isFileID())
1077 break; // No inner macro.
1078
1079 // If spelling location resides in the same FileID as macro expansion
1080 // location, it means there is no inner macro.
1081 FileID MacroFID = SM.getFileID(Loc);
1082 if (SM.isInFileID(SpellLoc, MacroFID))
1083 break;
1084
1085 // Argument came from inner macro.
1086 Loc = SpellLoc;
1087 }
1088
1089 // Find the spelling location of the start of the non-argument expansion
1090 // range. This is where the macro name was spelled in order to begin
1091 // expanding this macro.
1092 Loc = SM.getSpellingLoc(Loc);
1093
1094 // Dig out the buffer where the macro name was spelled and the extents of the
1095 // name so that we can render it into the expansion note.
1096 FileIDAndOffset ExpansionInfo = SM.getDecomposedLoc(Loc);
1097 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1098 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1099 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1100}
1101
1103 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1104 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
1105 // Walk past macro argument expansions.
1106 while (SM.isMacroArgExpansion(Loc))
1107 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
1108
1109 // If the macro's spelling isn't FileID or from scratch space, then it's
1110 // actually a token paste or stringization (or similar) and not a macro at
1111 // all.
1112 SourceLocation SpellLoc = SM.getSpellingLoc(Loc);
1113 if (!SpellLoc.isFileID() || SM.isWrittenInScratchSpace(SpellLoc))
1114 return {};
1115
1116 // Find the spelling location of the start of the non-argument expansion
1117 // range. This is where the macro name was spelled in order to begin
1118 // expanding this macro.
1119 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).getBegin());
1120
1121 // Dig out the buffer where the macro name was spelled and the extents of the
1122 // name so that we can render it into the expansion note.
1123 FileIDAndOffset ExpansionInfo = SM.getDecomposedLoc(Loc);
1124 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1125 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1126 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1127}
1128
1130 return isAsciiIdentifierContinue(c, LangOpts.DollarIdents);
1131}
1132
1133bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1134 assert(isVerticalWhitespace(Str[0]));
1135 if (Str - 1 < BufferStart)
1136 return false;
1137
1138 if ((Str[0] == '\n' && Str[-1] == '\r') ||
1139 (Str[0] == '\r' && Str[-1] == '\n')) {
1140 if (Str - 2 < BufferStart)
1141 return false;
1142 --Str;
1143 }
1144 --Str;
1145
1146 // Rewind to first non-space character:
1147 while (Str > BufferStart && isHorizontalWhitespace(*Str))
1148 --Str;
1149
1150 return *Str == '\\';
1151}
1152
1154 const SourceManager &SM) {
1155 if (Loc.isInvalid() || Loc.isMacroID())
1156 return {};
1157 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
1158 if (LocInfo.first.isInvalid())
1159 return {};
1160 bool Invalid = false;
1161 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1162 if (Invalid)
1163 return {};
1164 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1165 if (!Line)
1166 return {};
1167 StringRef Rest = Buffer.substr(Line - Buffer.data());
1168 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1169 return NumWhitespaceChars == StringRef::npos
1170 ? ""
1171 : Rest.take_front(NumWhitespaceChars);
1172}
1173
1174//===----------------------------------------------------------------------===//
1175// Diagnostics forwarding code.
1176//===----------------------------------------------------------------------===//
1177
1178/// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1179/// lexer buffer was all expanded at a single point, perform the mapping.
1180/// This is currently only used for _Pragma implementation, so it is the slow
1181/// path of the hot getSourceLocation method. Do not allow it to be inlined.
1182static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1183 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1185 SourceLocation FileLoc,
1186 unsigned CharNo, unsigned TokLen) {
1187 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1188
1189 // Otherwise, we're lexing "mapped tokens". This is used for things like
1190 // _Pragma handling. Combine the expansion location of FileLoc with the
1191 // spelling location.
1193
1194 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1195 // characters come from spelling(FileLoc)+Offset.
1196 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1197 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1198
1199 // Figure out the expansion loc range, which is the range covered by the
1200 // original _Pragma(...) sequence.
1201 CharSourceRange II = SM.getImmediateExpansionRange(FileLoc);
1202
1203 return SM.createExpansionLoc(SpellingLoc, II.getBegin(), II.getEnd(), TokLen);
1204}
1205
1206/// getSourceLocation - Return a source location identifier for the specified
1207/// offset in the current file.
1209 unsigned TokLen) const {
1210 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1211 "Location out of range for this buffer!");
1212
1213 // In the normal case, we're just lexing from a simple file buffer, return
1214 // the file id from FileLoc with the offset specified.
1215 unsigned CharNo = Loc-BufferStart;
1216 if (FileLoc.isFileID())
1217 return FileLoc.getLocWithOffset(CharNo);
1218
1219 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1220 // tokens are lexed from where the _Pragma was defined.
1221 assert(PP && "This doesn't work on raw lexers");
1222 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1223}
1224
1225/// Diag - Forwarding function for diagnostics. This translate a source
1226/// position in the current buffer into a SourceLocation object for rendering.
1227DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1228 return PP->Diag(getSourceLocation(Loc), DiagID);
1229}
1230
1231//===----------------------------------------------------------------------===//
1232// Trigraph and Escaped Newline Handling Code.
1233//===----------------------------------------------------------------------===//
1234
1235/// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1236/// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1237static char GetTrigraphCharForLetter(char Letter) {
1238 switch (Letter) {
1239 default: return 0;
1240 case '=': return '#';
1241 case ')': return ']';
1242 case '(': return '[';
1243 case '!': return '|';
1244 case '\'': return '^';
1245 case '>': return '}';
1246 case '/': return '\\';
1247 case '<': return '{';
1248 case '-': return '~';
1249 }
1250}
1251
1252/// DecodeTrigraphChar - If the specified character is a legal trigraph when
1253/// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1254/// return the result character. Finally, emit a warning about trigraph use
1255/// whether trigraphs are enabled or not.
1256static char DecodeTrigraphChar(const char *CP, Lexer *L, bool Trigraphs) {
1257 char Res = GetTrigraphCharForLetter(*CP);
1258 if (!Res)
1259 return Res;
1260
1261 if (!Trigraphs) {
1262 if (L && !L->isLexingRawMode())
1263 L->Diag(CP-2, diag::trigraph_ignored);
1264 return 0;
1265 }
1266
1267 if (L && !L->isLexingRawMode())
1268 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1269 return Res;
1270}
1271
1272/// getEscapedNewLineSize - Return the size of the specified escaped newline,
1273/// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1274/// trigraph equivalent on entry to this function.
1275unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1276 unsigned Size = 0;
1277 while (isWhitespace(Ptr[Size])) {
1278 ++Size;
1279
1280 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1281 continue;
1282
1283 // If this is a \r\n or \n\r, skip the other half.
1284 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1285 Ptr[Size-1] != Ptr[Size])
1286 ++Size;
1287
1288 return Size;
1289 }
1290
1291 // Not an escaped newline, must be a \t or something else.
1292 return 0;
1293}
1294
1295/// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1296/// them), skip over them and return the first non-escaped-newline found,
1297/// otherwise return P.
1298const char *Lexer::SkipEscapedNewLines(const char *P) {
1299 while (true) {
1300 const char *AfterEscape;
1301 if (*P == '\\') {
1302 AfterEscape = P+1;
1303 } else if (*P == '?') {
1304 // If not a trigraph for escape, bail out.
1305 if (P[1] != '?' || P[2] != '/')
1306 return P;
1307 // FIXME: Take LangOpts into account; the language might not
1308 // support trigraphs.
1309 AfterEscape = P+3;
1310 } else {
1311 return P;
1312 }
1313
1314 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1315 if (NewLineSize == 0) return P;
1316 P = AfterEscape+NewLineSize;
1317 }
1318}
1319
1320std::optional<Token> Lexer::findNextToken(SourceLocation Loc,
1321 const SourceManager &SM,
1322 const LangOptions &LangOpts,
1323 bool IncludeComments) {
1324 if (Loc.isMacroID()) {
1325 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1326 return std::nullopt;
1327 }
1328 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1329
1330 // Break down the source location.
1331 FileIDAndOffset LocInfo = SM.getDecomposedLoc(Loc);
1332
1333 // Try to load the file buffer.
1334 bool InvalidTemp = false;
1335 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1336 if (InvalidTemp)
1337 return std::nullopt;
1338
1339 const char *TokenBegin = File.data() + LocInfo.second;
1340
1341 // Lex from the start of the given location.
1342 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1343 TokenBegin, File.end());
1344 lexer.SetCommentRetentionState(IncludeComments);
1345 // Find the token.
1346 Token Tok;
1347 lexer.LexFromRawLexer(Tok);
1348 return Tok;
1349}
1350
1352 const SourceManager &SM,
1353 const LangOptions &LangOpts,
1354 bool IncludeComments) {
1355 const auto StartOfFile = SM.getLocForStartOfFile(SM.getFileID(Loc));
1356 while (Loc != StartOfFile) {
1357 Loc = Loc.getLocWithOffset(-1);
1358 if (Loc.isInvalid())
1359 return std::nullopt;
1360
1361 Loc = GetBeginningOfToken(Loc, SM, LangOpts);
1362 Token Tok;
1363 if (getRawToken(Loc, Tok, SM, LangOpts))
1364 continue; // Not a token, go to prev location.
1365 if (!Tok.is(tok::comment) || IncludeComments) {
1366 return Tok;
1367 }
1368 }
1369 return std::nullopt;
1370}
1371
1372/// Checks that the given token is the first token that occurs after the
1373/// given location (this excludes comments and whitespace). Returns the location
1374/// immediately after the specified token. If the token is not found or the
1375/// location is inside a macro, the returned source location will be invalid.
1377 SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1378 const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1379 std::optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1380 if (!Tok || Tok->isNot(TKind))
1381 return {};
1382 SourceLocation TokenLoc = Tok->getLocation();
1383
1384 // Calculate how much whitespace needs to be skipped if any.
1385 unsigned NumWhitespaceChars = 0;
1386 if (SkipTrailingWhitespaceAndNewLine) {
1387 const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
1388 unsigned char C = *TokenEnd;
1389 while (isHorizontalWhitespace(C)) {
1390 C = *(++TokenEnd);
1391 NumWhitespaceChars++;
1392 }
1393
1394 // Skip \r, \n, \r\n, or \n\r
1395 if (C == '\n' || C == '\r') {
1396 char PrevC = C;
1397 C = *(++TokenEnd);
1398 NumWhitespaceChars++;
1399 if ((C == '\n' || C == '\r') && C != PrevC)
1400 NumWhitespaceChars++;
1401 }
1402 }
1403
1404 return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
1405}
1406
1407/// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1408/// get its size, and return it. This is tricky in several cases:
1409/// 1. If currently at the start of a trigraph, we warn about the trigraph,
1410/// then either return the trigraph (skipping 3 chars) or the '?',
1411/// depending on whether trigraphs are enabled or not.
1412/// 2. If this is an escaped newline (potentially with whitespace between
1413/// the backslash and newline), implicitly skip the newline and return
1414/// the char after it.
1415///
1416/// This handles the slow/uncommon case of the getCharAndSize method. Here we
1417/// know that we can accumulate into Size, and that we have already incremented
1418/// Ptr by Size bytes.
1419///
1420/// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1421/// be updated to match.
1422Lexer::SizedChar Lexer::getCharAndSizeSlow(const char *Ptr, Token *Tok) {
1423 unsigned Size = 0;
1424 // If we have a slash, look for an escaped newline.
1425 if (Ptr[0] == '\\') {
1426 ++Size;
1427 ++Ptr;
1428Slash:
1429 // Common case, backslash-char where the char is not whitespace.
1430 if (!isWhitespace(Ptr[0]))
1431 return {'\\', Size};
1432
1433 // See if we have optional whitespace characters between the slash and
1434 // newline.
1435 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1436 // Remember that this token needs to be cleaned.
1437 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1438
1439 // Warn if there was whitespace between the backslash and newline.
1440 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1441 Diag(Ptr, diag::backslash_newline_space);
1442
1443 // Found backslash<whitespace><newline>. Parse the char after it.
1444 Size += EscapedNewLineSize;
1445 Ptr += EscapedNewLineSize;
1446
1447 // Use slow version to accumulate a correct size field.
1448 auto CharAndSize = getCharAndSizeSlow(Ptr, Tok);
1449 CharAndSize.Size += Size;
1450 return CharAndSize;
1451 }
1452
1453 // Otherwise, this is not an escaped newline, just return the slash.
1454 return {'\\', Size};
1455 }
1456
1457 // If this is a trigraph, process it.
1458 if (Ptr[0] == '?' && Ptr[1] == '?') {
1459 // If this is actually a legal trigraph (not something like "??x"), emit
1460 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1461 if (char C = DecodeTrigraphChar(Ptr + 2, Tok ? this : nullptr,
1462 LangOpts.Trigraphs)) {
1463 // Remember that this token needs to be cleaned.
1465
1466 Ptr += 3;
1467 Size += 3;
1468 if (C == '\\') goto Slash;
1469 return {C, Size};
1470 }
1471 }
1472
1473 // If this is neither, return a single character.
1474 return {*Ptr, Size + 1u};
1475}
1476
1477/// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1478/// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1479/// and that we have already incremented Ptr by Size bytes.
1480///
1481/// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1482/// be updated to match.
1483Lexer::SizedChar Lexer::getCharAndSizeSlowNoWarn(const char *Ptr,
1484 const LangOptions &LangOpts) {
1485
1486 unsigned Size = 0;
1487 // If we have a slash, look for an escaped newline.
1488 if (Ptr[0] == '\\') {
1489 ++Size;
1490 ++Ptr;
1491Slash:
1492 // Common case, backslash-char where the char is not whitespace.
1493 if (!isWhitespace(Ptr[0]))
1494 return {'\\', Size};
1495
1496 // See if we have optional whitespace characters followed by a newline.
1497 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1498 // Found backslash<whitespace><newline>. Parse the char after it.
1499 Size += EscapedNewLineSize;
1500 Ptr += EscapedNewLineSize;
1501
1502 // Use slow version to accumulate a correct size field.
1503 auto CharAndSize = getCharAndSizeSlowNoWarn(Ptr, LangOpts);
1504 CharAndSize.Size += Size;
1505 return CharAndSize;
1506 }
1507
1508 // Otherwise, this is not an escaped newline, just return the slash.
1509 return {'\\', Size};
1510 }
1511
1512 // If this is a trigraph, process it.
1513 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1514 // If this is actually a legal trigraph (not something like "??x"), return
1515 // it.
1516 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1517 Ptr += 3;
1518 Size += 3;
1519 if (C == '\\') goto Slash;
1520 return {C, Size};
1521 }
1522 }
1523
1524 // If this is neither, return a single character.
1525 return {*Ptr, Size + 1u};
1526}
1527
1528//===----------------------------------------------------------------------===//
1529// Helper methods for lexing.
1530//===----------------------------------------------------------------------===//
1531
1532/// Routine that indiscriminately sets the offset into the source file.
1533void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1534 BufferPtr = BufferStart + Offset;
1535 if (BufferPtr > BufferEnd)
1536 BufferPtr = BufferEnd;
1537 // FIXME: What exactly does the StartOfLine bit mean? There are two
1538 // possible meanings for the "start" of the line: the first token on the
1539 // unexpanded line, or the first token on the expanded line.
1540 IsAtStartOfLine = StartOfLine;
1541 IsAtPhysicalStartOfLine = StartOfLine;
1542}
1543
1544static bool isUnicodeWhitespace(uint32_t Codepoint) {
1545 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
1547 return UnicodeWhitespaceChars.contains(Codepoint);
1548}
1549
1551 llvm::SmallString<5> CharBuf;
1552 llvm::raw_svector_ostream CharOS(CharBuf);
1553 llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1554 return CharBuf;
1555}
1556
1557// To mitigate https://github.com/llvm/llvm-project/issues/54732,
1558// we allow "Mathematical Notation Characters" in identifiers.
1559// This is a proposed profile that extends the XID_Start/XID_continue
1560// with mathematical symbols, superscipts and subscripts digits
1561// found in some production software.
1562// https://www.unicode.org/L2/L2022/22230-math-profile.pdf
1563static bool isMathematicalExtensionID(uint32_t C, const LangOptions &LangOpts,
1564 bool IsStart, bool &IsExtension) {
1565 static const llvm::sys::UnicodeCharSet MathStartChars(
1567 static const llvm::sys::UnicodeCharSet MathContinueChars(
1569 if (MathStartChars.contains(C) ||
1570 (!IsStart && MathContinueChars.contains(C))) {
1571 IsExtension = true;
1572 return true;
1573 }
1574 return false;
1575}
1576
1577static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts,
1578 bool &IsExtension) {
1579 if (LangOpts.AsmPreprocessor) {
1580 return false;
1581 } else if (LangOpts.DollarIdents && '$' == C) {
1582 return true;
1583 } else if (LangOpts.CPlusPlus || LangOpts.C23) {
1584 // A non-leading codepoint must have the XID_Continue property.
1585 // XIDContinueRanges doesn't contains characters also in XIDStartRanges,
1586 // so we need to check both tables.
1587 // '_' doesn't have the XID_Continue property but is allowed in C and C++.
1588 static const llvm::sys::UnicodeCharSet XIDStartChars(XIDStartRanges);
1589 static const llvm::sys::UnicodeCharSet XIDContinueChars(XIDContinueRanges);
1590 if (C == '_' || XIDStartChars.contains(C) || XIDContinueChars.contains(C))
1591 return true;
1592 return isMathematicalExtensionID(C, LangOpts, /*IsStart=*/false,
1593 IsExtension);
1594 } else if (LangOpts.C11) {
1595 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1597 return C11AllowedIDChars.contains(C);
1598 } else {
1599 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1601 return C99AllowedIDChars.contains(C);
1602 }
1603}
1604
1605static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts,
1606 bool &IsExtension) {
1607 assert(C > 0x7F && "isAllowedInitiallyIDChar called with an ASCII codepoint");
1608 IsExtension = false;
1609 if (LangOpts.AsmPreprocessor) {
1610 return false;
1611 }
1612 if (LangOpts.CPlusPlus || LangOpts.C23) {
1613 static const llvm::sys::UnicodeCharSet XIDStartChars(XIDStartRanges);
1614 if (XIDStartChars.contains(C))
1615 return true;
1616 return isMathematicalExtensionID(C, LangOpts, /*IsStart=*/true,
1617 IsExtension);
1618 }
1619 if (!isAllowedIDChar(C, LangOpts, IsExtension))
1620 return false;
1621 if (LangOpts.C11) {
1622 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1624 return !C11DisallowedInitialIDChars.contains(C);
1625 }
1626 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1628 return !C99DisallowedInitialIDChars.contains(C);
1629}
1630
1632 CharSourceRange Range) {
1633
1634 static const llvm::sys::UnicodeCharSet MathStartChars(
1636 static const llvm::sys::UnicodeCharSet MathContinueChars(
1638
1639 (void)MathStartChars;
1640 (void)MathContinueChars;
1641 assert((MathStartChars.contains(C) || MathContinueChars.contains(C)) &&
1642 "Unexpected mathematical notation codepoint");
1643 Diags.Report(Range.getBegin(), diag::ext_mathematical_notation)
1644 << codepointAsHexString(C) << Range;
1645}
1646
1647static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1648 const char *End) {
1650 L.getSourceLocation(End));
1651}
1652
1653static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1654 CharSourceRange Range, bool IsFirst) {
1655 // Check C99 compatibility.
1656 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1657 enum {
1658 CannotAppearInIdentifier = 0,
1659 CannotStartIdentifier
1660 };
1661
1662 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1664 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1666 if (!C99AllowedIDChars.contains(C)) {
1667 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1668 << Range
1669 << CannotAppearInIdentifier;
1670 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1671 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1672 << Range
1673 << CannotStartIdentifier;
1674 }
1675 }
1676}
1677
1678/// After encountering UTF-8 character C and interpreting it as an identifier
1679/// character, check whether it's a homoglyph for a common non-identifier
1680/// source character that is unlikely to be an intentional identifier
1681/// character and warn if so.
1683 CharSourceRange Range) {
1684 // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
1685 struct HomoglyphPair {
1686 uint32_t Character;
1687 char LooksLike;
1688 bool operator<(HomoglyphPair R) const { return Character < R.Character; }
1689 };
1690 static constexpr HomoglyphPair SortedHomoglyphs[] = {
1691 {U'\u00ad', 0}, // SOFT HYPHEN
1692 {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1693 {U'\u037e', ';'}, // GREEK QUESTION MARK
1694 {U'\u200b', 0}, // ZERO WIDTH SPACE
1695 {U'\u200c', 0}, // ZERO WIDTH NON-JOINER
1696 {U'\u200d', 0}, // ZERO WIDTH JOINER
1697 {U'\u2060', 0}, // WORD JOINER
1698 {U'\u2061', 0}, // FUNCTION APPLICATION
1699 {U'\u2062', 0}, // INVISIBLE TIMES
1700 {U'\u2063', 0}, // INVISIBLE SEPARATOR
1701 {U'\u2064', 0}, // INVISIBLE PLUS
1702 {U'\u2212', '-'}, // MINUS SIGN
1703 {U'\u2215', '/'}, // DIVISION SLASH
1704 {U'\u2216', '\\'}, // SET MINUS
1705 {U'\u2217', '*'}, // ASTERISK OPERATOR
1706 {U'\u2223', '|'}, // DIVIDES
1707 {U'\u2227', '^'}, // LOGICAL AND
1708 {U'\u2236', ':'}, // RATIO
1709 {U'\u223c', '~'}, // TILDE OPERATOR
1710 {U'\ua789', ':'}, // MODIFIER LETTER COLON
1711 {U'\ufeff', 0}, // ZERO WIDTH NO-BREAK SPACE
1712 {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1713 {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1714 {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1715 {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1716 {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1717 {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1718 {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1719 {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1720 {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1721 {U'\uff0c', ','}, // FULLWIDTH COMMA
1722 {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1723 {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1724 {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1725 {U'\uff1a', ':'}, // FULLWIDTH COLON
1726 {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1727 {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1728 {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1729 {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1730 {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1731 {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1732 {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1733 {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1734 {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1735 {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1736 {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1737 {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1738 {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1739 {U'\uff5e', '~'}, // FULLWIDTH TILDE
1740 {0, 0}
1741 };
1742 auto Homoglyph =
1743 std::lower_bound(std::begin(SortedHomoglyphs),
1744 std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1745 if (Homoglyph->Character == C) {
1746 if (Homoglyph->LooksLike) {
1747 const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1748 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1749 << Range << codepointAsHexString(C) << LooksLikeStr;
1750 } else {
1751 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_zero_width)
1752 << Range << codepointAsHexString(C);
1753 }
1754 }
1755}
1756
1758 DiagnosticsEngine &Diags, const LangOptions &LangOpts, uint32_t CodePoint,
1759 CharSourceRange Range, bool IsFirst) {
1760 if (isASCII(CodePoint))
1761 return;
1762
1763 bool IsExtension;
1764 bool IsIDStart = isAllowedInitiallyIDChar(CodePoint, LangOpts, IsExtension);
1765 bool IsIDContinue =
1766 IsIDStart || isAllowedIDChar(CodePoint, LangOpts, IsExtension);
1767
1768 if ((IsFirst && IsIDStart) || (!IsFirst && IsIDContinue))
1769 return;
1770
1771 bool InvalidOnlyAtStart = IsFirst && !IsIDStart && IsIDContinue;
1772
1773 if (!IsFirst || InvalidOnlyAtStart) {
1774 Diags.Report(Range.getBegin(), diag::err_character_not_allowed_identifier)
1775 << Range << codepointAsHexString(CodePoint) << int(InvalidOnlyAtStart)
1776 << FixItHint::CreateRemoval(Range);
1777 } else {
1778 Diags.Report(Range.getBegin(), diag::err_character_not_allowed)
1779 << Range << codepointAsHexString(CodePoint)
1780 << FixItHint::CreateRemoval(Range);
1781 }
1782}
1783
1784bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1785 Token &Result) {
1786 const char *UCNPtr = CurPtr + Size;
1787 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1788 if (CodePoint == 0) {
1789 return false;
1790 }
1791 bool IsExtension = false;
1792 if (!isAllowedIDChar(CodePoint, LangOpts, IsExtension)) {
1793 if (isASCII(CodePoint) || isUnicodeWhitespace(CodePoint))
1794 return false;
1796 !PP->isPreprocessedOutput())
1798 PP->getDiagnostics(), LangOpts, CodePoint,
1799 makeCharRange(*this, CurPtr, UCNPtr),
1800 /*IsFirst=*/false);
1801
1802 // We got a unicode codepoint that is neither a space nor a
1803 // a valid identifier part.
1804 // Carry on as if the codepoint was valid for recovery purposes.
1805 } else if (!isLexingRawMode()) {
1806 if (IsExtension)
1807 diagnoseExtensionInIdentifier(PP->getDiagnostics(), CodePoint,
1808 makeCharRange(*this, CurPtr, UCNPtr));
1809
1810 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1811 makeCharRange(*this, CurPtr, UCNPtr),
1812 /*IsFirst=*/false);
1813 }
1814
1815 Result.setFlag(Token::HasUCN);
1816 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1817 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1818 CurPtr = UCNPtr;
1819 else
1820 while (CurPtr != UCNPtr)
1821 (void)getAndAdvanceChar(CurPtr, Result);
1822 return true;
1823}
1824
1825bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr, Token &Result) {
1826 llvm::UTF32 CodePoint;
1827
1828 // If a UTF-8 codepoint appears immediately after an escaped new line,
1829 // CurPtr may point to the splicing \ on the preceding line,
1830 // so we need to skip it.
1831 unsigned FirstCodeUnitSize;
1832 getCharAndSize(CurPtr, FirstCodeUnitSize);
1833 const char *CharStart = CurPtr + FirstCodeUnitSize - 1;
1834 const char *UnicodePtr = CharStart;
1835
1836 llvm::ConversionResult ConvResult = llvm::convertUTF8Sequence(
1837 (const llvm::UTF8 **)&UnicodePtr, (const llvm::UTF8 *)BufferEnd,
1838 &CodePoint, llvm::strictConversion);
1839 if (ConvResult != llvm::conversionOK)
1840 return false;
1841
1842 bool IsExtension = false;
1843 if (!isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts,
1844 IsExtension)) {
1845 if (isASCII(CodePoint) || isUnicodeWhitespace(CodePoint))
1846 return false;
1847
1849 !PP->isPreprocessedOutput())
1851 PP->getDiagnostics(), LangOpts, CodePoint,
1852 makeCharRange(*this, CharStart, UnicodePtr), /*IsFirst=*/false);
1853 // We got a unicode codepoint that is neither a space nor a
1854 // a valid identifier part. Carry on as if the codepoint was
1855 // valid for recovery purposes.
1856 } else if (!isLexingRawMode()) {
1857 if (IsExtension)
1859 PP->getDiagnostics(), CodePoint,
1860 makeCharRange(*this, CharStart, UnicodePtr));
1861 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1862 makeCharRange(*this, CharStart, UnicodePtr),
1863 /*IsFirst=*/false);
1864 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
1865 makeCharRange(*this, CharStart, UnicodePtr));
1866 }
1867
1868 // Once we sucessfully parsed some UTF-8,
1869 // calling ConsumeChar ensures the NeedsCleaning flag is set on the token
1870 // being lexed, and that warnings about trailing spaces are emitted.
1871 ConsumeChar(CurPtr, FirstCodeUnitSize, Result);
1872 CurPtr = UnicodePtr;
1873 return true;
1874}
1875
1876bool Lexer::LexUnicodeIdentifierStart(Token &Result, uint32_t C,
1877 const char *CurPtr) {
1878 bool IsExtension = false;
1879 if (isAllowedInitiallyIDChar(C, LangOpts, IsExtension)) {
1881 !PP->isPreprocessedOutput()) {
1882 if (IsExtension)
1883 diagnoseExtensionInIdentifier(PP->getDiagnostics(), C,
1884 makeCharRange(*this, BufferPtr, CurPtr));
1885 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
1886 makeCharRange(*this, BufferPtr, CurPtr),
1887 /*IsFirst=*/true);
1888 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), C,
1889 makeCharRange(*this, BufferPtr, CurPtr));
1890 }
1891
1892 MIOpt.ReadToken();
1893 return LexIdentifierContinue(Result, CurPtr);
1894 }
1895
1897 !PP->isPreprocessedOutput() && !isASCII(*BufferPtr) &&
1899 // Non-ASCII characters tend to creep into source code unintentionally.
1900 // Instead of letting the parser complain about the unknown token,
1901 // just drop the character.
1902 // Note that we can /only/ do this when the non-ASCII character is actually
1903 // spelled as Unicode, not written as a UCN. The standard requires that
1904 // we not throw away any possible preprocessor tokens, but there's a
1905 // loophole in the mapping of Unicode characters to basic character set
1906 // characters that allows us to map these particular characters to, say,
1907 // whitespace.
1909 PP->getDiagnostics(), LangOpts, C,
1910 makeCharRange(*this, BufferPtr, CurPtr), /*IsStart*/ true);
1911 BufferPtr = CurPtr;
1912 return false;
1913 }
1914
1915 // Otherwise, we have an explicit UCN or a character that's unlikely to show
1916 // up by accident.
1917 MIOpt.ReadToken();
1918 FormTokenWithChars(Result, CurPtr, tok::unknown);
1919 return true;
1920}
1921
1922static const char *
1923fastParseASCIIIdentifier(const char *CurPtr,
1924 [[maybe_unused]] const char *BufferEnd) {
1925#ifdef __SSE4_2__
1926 alignas(16) static constexpr char AsciiIdentifierRange[16] = {
1927 '_', '_', 'A', 'Z', 'a', 'z', '0', '9',
1928 };
1929 constexpr ssize_t BytesPerRegister = 16;
1930
1931 __m128i AsciiIdentifierRangeV =
1932 _mm_load_si128((const __m128i *)AsciiIdentifierRange);
1933
1934 while (LLVM_LIKELY(BufferEnd - CurPtr >= BytesPerRegister)) {
1935 __m128i Cv = _mm_loadu_si128((const __m128i *)(CurPtr));
1936
1937 int Consumed = _mm_cmpistri(AsciiIdentifierRangeV, Cv,
1940 CurPtr += Consumed;
1941 if (Consumed == BytesPerRegister)
1942 continue;
1943 return CurPtr;
1944 }
1945#endif
1946
1947 unsigned char C = *CurPtr;
1949 C = *++CurPtr;
1950 return CurPtr;
1951}
1952
1953bool Lexer::LexIdentifierContinue(Token &Result, const char *CurPtr) {
1954 // Match [_A-Za-z0-9]*, we have already matched an identifier start.
1955
1956 while (true) {
1957
1958 CurPtr = fastParseASCIIIdentifier(CurPtr, BufferEnd);
1959
1960 unsigned Size;
1961 // Slow path: handle trigraph, unicode codepoints, UCNs.
1962 unsigned char C = getCharAndSize(CurPtr, Size);
1964 CurPtr = ConsumeChar(CurPtr, Size, Result);
1965 continue;
1966 }
1967 if (C == '$') {
1968 // If we hit a $ and they are not supported in identifiers, we are done.
1969 if (!LangOpts.DollarIdents)
1970 break;
1971 // Otherwise, emit a diagnostic and continue.
1972 if (!isLexingRawMode())
1973 Diag(CurPtr, diag::ext_dollar_in_identifier);
1974 CurPtr = ConsumeChar(CurPtr, Size, Result);
1975 continue;
1976 }
1977 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1978 continue;
1979 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr, Result))
1980 continue;
1981 // Neither an expected Unicode codepoint nor a UCN.
1982 break;
1983 }
1984
1985 const char *IdStart = BufferPtr;
1986 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1987 Result.setRawIdentifierData(IdStart);
1988
1989 // If we are in raw mode, return this identifier raw. There is no need to
1990 // look up identifier information or attempt to macro expand it.
1991 if (LexingRawMode)
1992 return true;
1993
1994 // Fill in Result.IdentifierInfo and update the token kind,
1995 // looking up the identifier in the identifier table.
1996 const IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1997 // Note that we have to call PP->LookUpIdentifierInfo() even for code
1998 // completion, it writes IdentifierInfo into Result, and callers rely on it.
1999
2000 // If the completion point is at the end of an identifier, we want to treat
2001 // the identifier as incomplete even if it resolves to a macro or a keyword.
2002 // This allows e.g. 'class^' to complete to 'classifier'.
2003 if (isCodeCompletionPoint(CurPtr)) {
2004 // Return the code-completion token.
2005 Result.setKind(tok::code_completion);
2006 // Skip the code-completion char and all immediate identifier characters.
2007 // This ensures we get consistent behavior when completing at any point in
2008 // an identifier (i.e. at the start, in the middle, at the end). Note that
2009 // only simple cases (i.e. [a-zA-Z0-9_]) are supported to keep the code
2010 // simpler.
2011 assert(*CurPtr == 0 && "Completion character must be 0");
2012 ++CurPtr;
2013 // Note that code completion token is not added as a separate character
2014 // when the completion point is at the end of the buffer. Therefore, we need
2015 // to check if the buffer has ended.
2016 if (CurPtr < BufferEnd) {
2017 while (isAsciiIdentifierContinue(*CurPtr))
2018 ++CurPtr;
2019 }
2020 BufferPtr = CurPtr;
2021 return true;
2022 }
2023
2024 // Finally, now that we know we have an identifier, pass this off to the
2025 // preprocessor, which may macro expand it or something.
2026 if (II->isHandleIdentifierCase())
2027 return PP->HandleIdentifier(Result);
2028
2029 return true;
2030}
2031
2032/// isHexaLiteral - Return true if Start points to a hex constant.
2033/// in microsoft mode (where this is supposed to be several different tokens).
2034bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
2035 auto CharAndSize1 = Lexer::getCharAndSizeNoWarn(Start, LangOpts);
2036 char C1 = CharAndSize1.Char;
2037 if (C1 != '0')
2038 return false;
2039
2040 auto CharAndSize2 =
2041 Lexer::getCharAndSizeNoWarn(Start + CharAndSize1.Size, LangOpts);
2042 char C2 = CharAndSize2.Char;
2043 return (C2 == 'x' || C2 == 'X');
2044}
2045
2046/// LexNumericConstant - Lex the remainder of a integer or floating point
2047/// constant. From[-1] is the first character lexed. Return the end of the
2048/// constant.
2049bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
2050 unsigned Size;
2051 char C = getCharAndSize(CurPtr, Size);
2052 char PrevCh = 0;
2053 while (isPreprocessingNumberBody(C)) {
2054 CurPtr = ConsumeChar(CurPtr, Size, Result);
2055 PrevCh = C;
2056 if (LangOpts.HLSL && C == '.' && (*CurPtr == 'x' || *CurPtr == 'r')) {
2057 CurPtr -= Size;
2058 break;
2059 }
2060 C = getCharAndSize(CurPtr, Size);
2061 }
2062
2063 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
2064 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
2065 // If we are in Microsoft mode, don't continue if the constant is hex.
2066 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
2067 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
2068 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
2069 }
2070
2071 // If we have a hex FP constant, continue.
2072 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
2073 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
2074 // not-quite-conforming extension. Only do so if this looks like it's
2075 // actually meant to be a hexfloat, and not if it has a ud-suffix.
2076 bool IsHexFloat = true;
2077 if (!LangOpts.C99) {
2078 if (!isHexaLiteral(BufferPtr, LangOpts))
2079 IsHexFloat = false;
2080 else if (!LangOpts.CPlusPlus17 &&
2081 std::find(BufferPtr, CurPtr, '_') != CurPtr)
2082 IsHexFloat = false;
2083 }
2084 if (IsHexFloat)
2085 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
2086 }
2087
2088 // If we have a digit separator, continue.
2089 if (C == '\'' && (LangOpts.CPlusPlus14 || LangOpts.C23)) {
2090 auto [Next, NextSize] = getCharAndSizeNoWarn(CurPtr + Size, LangOpts);
2092 if (!isLexingRawMode())
2093 Diag(CurPtr, LangOpts.CPlusPlus
2094 ? diag::warn_cxx11_compat_digit_separator
2095 : diag::warn_c23_compat_digit_separator);
2096 CurPtr = ConsumeChar(CurPtr, Size, Result);
2097 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
2098 return LexNumericConstant(Result, CurPtr);
2099 }
2100 }
2101
2102 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
2103 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
2104 return LexNumericConstant(Result, CurPtr);
2105 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr, Result))
2106 return LexNumericConstant(Result, CurPtr);
2107
2108 // Update the location of token as well as BufferPtr.
2109 const char *TokStart = BufferPtr;
2110 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
2111 Result.setLiteralData(TokStart);
2112 return true;
2113}
2114
2115/// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
2116/// in C++11, or warn on a ud-suffix in C++98.
2117const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
2118 bool IsStringLiteral) {
2119 assert(LangOpts.CPlusPlus);
2120
2121 // Maximally munch an identifier.
2122 unsigned Size;
2123 char C = getCharAndSize(CurPtr, Size);
2124 bool Consumed = false;
2125
2126 if (!isAsciiIdentifierStart(C)) {
2127 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
2128 Consumed = true;
2129 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr, Result))
2130 Consumed = true;
2131 else
2132 return CurPtr;
2133 }
2134
2135 if (!LangOpts.CPlusPlus11) {
2136 if (!isLexingRawMode())
2137 Diag(CurPtr,
2138 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
2139 : diag::warn_cxx11_compat_reserved_user_defined_literal)
2141 return CurPtr;
2142 }
2143
2144 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
2145 // that does not start with an underscore is ill-formed. As a conforming
2146 // extension, we treat all such suffixes as if they had whitespace before
2147 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
2148 // likely to be a ud-suffix than a macro, however, and accept that.
2149 if (!Consumed) {
2150 bool IsUDSuffix = false;
2151 if (C == '_')
2152 IsUDSuffix = true;
2153 else if (IsStringLiteral && LangOpts.CPlusPlus14) {
2154 // In C++1y, we need to look ahead a few characters to see if this is a
2155 // valid suffix for a string literal or a numeric literal (this could be
2156 // the 'operator""if' defining a numeric literal operator).
2157 const unsigned MaxStandardSuffixLength = 3;
2158 char Buffer[MaxStandardSuffixLength] = { C };
2159 unsigned Consumed = Size;
2160 unsigned Chars = 1;
2161 while (true) {
2162 auto [Next, NextSize] =
2163 getCharAndSizeNoWarn(CurPtr + Consumed, LangOpts);
2165 // End of suffix. Check whether this is on the allowed list.
2166 const StringRef CompleteSuffix(Buffer, Chars);
2167 IsUDSuffix =
2168 StringLiteralParser::isValidUDSuffix(LangOpts, CompleteSuffix);
2169 break;
2170 }
2171
2172 if (Chars == MaxStandardSuffixLength)
2173 // Too long: can't be a standard suffix.
2174 break;
2175
2176 Buffer[Chars++] = Next;
2177 Consumed += NextSize;
2178 }
2179 }
2180
2181 if (!IsUDSuffix) {
2182 if (!isLexingRawMode())
2183 Diag(CurPtr, LangOpts.MSVCCompat
2184 ? diag::ext_ms_reserved_user_defined_literal
2185 : diag::ext_reserved_user_defined_literal)
2187 return CurPtr;
2188 }
2189
2190 CurPtr = ConsumeChar(CurPtr, Size, Result);
2191 }
2192
2193 Result.setFlag(Token::HasUDSuffix);
2194 while (true) {
2195 C = getCharAndSize(CurPtr, Size);
2197 CurPtr = ConsumeChar(CurPtr, Size, Result);
2198 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
2199 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr, Result)) {
2200 } else
2201 break;
2202 }
2203
2204 return CurPtr;
2205}
2206
2207/// LexStringLiteral - Lex the remainder of a string literal, after having lexed
2208/// either " or L" or u8" or u" or U".
2209bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
2210 tok::TokenKind Kind) {
2211 const char *AfterQuote = CurPtr;
2212 // Does this string contain the \0 character?
2213 const char *NulCharacter = nullptr;
2214
2215 if (!isLexingRawMode() &&
2216 (Kind == tok::utf8_string_literal ||
2217 Kind == tok::utf16_string_literal ||
2218 Kind == tok::utf32_string_literal))
2219 Diag(BufferPtr, LangOpts.CPlusPlus ? diag::warn_cxx98_compat_unicode_literal
2220 : diag::warn_c99_compat_unicode_literal);
2221
2222 char C = getAndAdvanceChar(CurPtr, Result);
2223 while (C != '"') {
2224 // Skip escaped characters. Escaped newlines will already be processed by
2225 // getAndAdvanceChar.
2226 if (C == '\\')
2227 C = getAndAdvanceChar(CurPtr, Result);
2228
2229 if (C == '\n' || C == '\r' || // Newline.
2230 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
2231 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2232 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
2233 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2234 return true;
2235 }
2236
2237 if (C == 0) {
2238 if (isCodeCompletionPoint(CurPtr-1)) {
2239 if (ParsingFilename)
2240 codeCompleteIncludedFile(AfterQuote, CurPtr - 1, /*IsAngled=*/false);
2241 else
2242 PP->CodeCompleteNaturalLanguage();
2243 FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
2244 cutOffLexing();
2245 return true;
2246 }
2247
2248 NulCharacter = CurPtr-1;
2249 }
2250 C = getAndAdvanceChar(CurPtr, Result);
2251 }
2252
2253 // If we are in C++11, lex the optional ud-suffix.
2254 if (LangOpts.CPlusPlus)
2255 CurPtr = LexUDSuffix(Result, CurPtr, true);
2256
2257 // If a nul character existed in the string, warn about it.
2258 if (NulCharacter && !isLexingRawMode())
2259 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2260
2261 // Update the location of the token as well as the BufferPtr instance var.
2262 const char *TokStart = BufferPtr;
2263 FormTokenWithChars(Result, CurPtr, Kind);
2264 Result.setLiteralData(TokStart);
2265 return true;
2266}
2267
2268/// LexRawStringLiteral - Lex the remainder of a raw string literal, after
2269/// having lexed R", LR", u8R", uR", or UR".
2270bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
2271 tok::TokenKind Kind) {
2272 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
2273 // Between the initial and final double quote characters of the raw string,
2274 // any transformations performed in phases 1 and 2 (trigraphs,
2275 // universal-character-names, and line splicing) are reverted.
2276
2277 if (!isLexingRawMode())
2278 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
2279
2280 unsigned PrefixLen = 0;
2281
2282 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen])) {
2283 if (!isLexingRawMode() &&
2284 llvm::is_contained({'$', '@', '`'}, CurPtr[PrefixLen])) {
2285 const char *Pos = &CurPtr[PrefixLen];
2286 Diag(Pos, LangOpts.CPlusPlus26
2287 ? diag::warn_cxx26_compat_raw_string_literal_character_set
2288 : diag::ext_cxx26_raw_string_literal_character_set)
2289 << StringRef(Pos, 1);
2290 }
2291 ++PrefixLen;
2292 }
2293
2294 // If the last character was not a '(', then we didn't lex a valid delimiter.
2295 if (CurPtr[PrefixLen] != '(') {
2296 if (!isLexingRawMode()) {
2297 const char *PrefixEnd = &CurPtr[PrefixLen];
2298 if (PrefixLen == 16) {
2299 Diag(PrefixEnd, diag::err_raw_delim_too_long);
2300 } else if (*PrefixEnd == '\n') {
2301 Diag(PrefixEnd, diag::err_invalid_newline_raw_delim);
2302 } else {
2303 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
2304 << StringRef(PrefixEnd, 1);
2305 }
2306 }
2307
2308 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
2309 // it's possible the '"' was intended to be part of the raw string, but
2310 // there's not much we can do about that.
2311 while (true) {
2312 char C = *CurPtr++;
2313
2314 if (C == '"')
2315 break;
2316 if (C == 0 && CurPtr-1 == BufferEnd) {
2317 --CurPtr;
2318 break;
2319 }
2320 }
2321
2322 FormTokenWithChars(Result, CurPtr, tok::unknown);
2323 return true;
2324 }
2325
2326 // Save prefix and move CurPtr past it
2327 const char *Prefix = CurPtr;
2328 CurPtr += PrefixLen + 1; // skip over prefix and '('
2329
2330 while (true) {
2331 char C = *CurPtr++;
2332
2333 if (C == ')') {
2334 // Check for prefix match and closing quote.
2335 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
2336 CurPtr += PrefixLen + 1; // skip over prefix and '"'
2337 break;
2338 }
2339 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
2340 if (!isLexingRawMode())
2341 Diag(BufferPtr, diag::err_unterminated_raw_string)
2342 << StringRef(Prefix, PrefixLen);
2343 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2344 return true;
2345 }
2346 }
2347
2348 // If we are in C++11, lex the optional ud-suffix.
2349 if (LangOpts.CPlusPlus)
2350 CurPtr = LexUDSuffix(Result, CurPtr, true);
2351
2352 // Update the location of token as well as BufferPtr.
2353 const char *TokStart = BufferPtr;
2354 FormTokenWithChars(Result, CurPtr, Kind);
2355 Result.setLiteralData(TokStart);
2356 return true;
2357}
2358
2359/// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2360/// after having lexed the '<' character. This is used for #include filenames.
2361bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
2362 // Does this string contain the \0 character?
2363 const char *NulCharacter = nullptr;
2364 const char *AfterLessPos = CurPtr;
2365 char C = getAndAdvanceChar(CurPtr, Result);
2366 while (C != '>') {
2367 // Skip escaped characters. Escaped newlines will already be processed by
2368 // getAndAdvanceChar.
2369 if (C == '\\')
2370 C = getAndAdvanceChar(CurPtr, Result);
2371
2372 if (isVerticalWhitespace(C) || // Newline.
2373 (C == 0 && (CurPtr - 1 == BufferEnd))) { // End of file.
2374 // If the filename is unterminated, then it must just be a lone <
2375 // character. Return this as such.
2376 FormTokenWithChars(Result, AfterLessPos, tok::less);
2377 return true;
2378 }
2379
2380 if (C == 0) {
2381 if (isCodeCompletionPoint(CurPtr - 1)) {
2382 codeCompleteIncludedFile(AfterLessPos, CurPtr - 1, /*IsAngled=*/true);
2383 cutOffLexing();
2384 FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
2385 return true;
2386 }
2387 NulCharacter = CurPtr-1;
2388 }
2389 C = getAndAdvanceChar(CurPtr, Result);
2390 }
2391
2392 // If a nul character existed in the string, warn about it.
2393 if (NulCharacter && !isLexingRawMode())
2394 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2395
2396 // Update the location of token as well as BufferPtr.
2397 const char *TokStart = BufferPtr;
2398 FormTokenWithChars(Result, CurPtr, tok::header_name);
2399 Result.setLiteralData(TokStart);
2400 return true;
2401}
2402
2403void Lexer::codeCompleteIncludedFile(const char *PathStart,
2404 const char *CompletionPoint,
2405 bool IsAngled) {
2406 // Completion only applies to the filename, after the last slash.
2407 StringRef PartialPath(PathStart, CompletionPoint - PathStart);
2408 llvm::StringRef SlashChars = LangOpts.MSVCCompat ? "/\\" : "/";
2409 auto Slash = PartialPath.find_last_of(SlashChars);
2410 StringRef Dir =
2411 (Slash == StringRef::npos) ? "" : PartialPath.take_front(Slash);
2412 const char *StartOfFilename =
2413 (Slash == StringRef::npos) ? PathStart : PathStart + Slash + 1;
2414 // Code completion filter range is the filename only, up to completion point.
2415 PP->setCodeCompletionIdentifierInfo(&PP->getIdentifierTable().get(
2416 StringRef(StartOfFilename, CompletionPoint - StartOfFilename)));
2417 // We should replace the characters up to the closing quote or closest slash,
2418 // if any.
2419 while (CompletionPoint < BufferEnd) {
2420 char Next = *(CompletionPoint + 1);
2421 if (Next == 0 || Next == '\r' || Next == '\n')
2422 break;
2423 ++CompletionPoint;
2424 if (Next == (IsAngled ? '>' : '"'))
2425 break;
2426 if (SlashChars.contains(Next))
2427 break;
2428 }
2429
2430 PP->setCodeCompletionTokenRange(
2431 FileLoc.getLocWithOffset(StartOfFilename - BufferStart),
2432 FileLoc.getLocWithOffset(CompletionPoint - BufferStart));
2433 PP->CodeCompleteIncludedFile(Dir, IsAngled);
2434}
2435
2436/// LexCharConstant - Lex the remainder of a character constant, after having
2437/// lexed either ' or L' or u8' or u' or U'.
2438bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
2439 tok::TokenKind Kind) {
2440 // Does this character contain the \0 character?
2441 const char *NulCharacter = nullptr;
2442
2443 if (!isLexingRawMode()) {
2444 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
2445 Diag(BufferPtr, LangOpts.CPlusPlus
2446 ? diag::warn_cxx98_compat_unicode_literal
2447 : diag::warn_c99_compat_unicode_literal);
2448 else if (Kind == tok::utf8_char_constant)
2449 Diag(BufferPtr, LangOpts.CPlusPlus
2450 ? diag::warn_cxx14_compat_u8_character_literal
2451 : diag::warn_c17_compat_u8_character_literal);
2452 }
2453
2454 char C = getAndAdvanceChar(CurPtr, Result);
2455 if (C == '\'') {
2456 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2457 Diag(BufferPtr, diag::ext_empty_character);
2458 FormTokenWithChars(Result, CurPtr, tok::unknown);
2459 return true;
2460 }
2461
2462 while (C != '\'') {
2463 // Skip escaped characters.
2464 if (C == '\\')
2465 C = getAndAdvanceChar(CurPtr, Result);
2466
2467 if (C == '\n' || C == '\r' || // Newline.
2468 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
2469 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2470 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
2471 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2472 return true;
2473 }
2474
2475 if (C == 0) {
2476 if (isCodeCompletionPoint(CurPtr-1)) {
2477 PP->CodeCompleteNaturalLanguage();
2478 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2479 cutOffLexing();
2480 return true;
2481 }
2482
2483 NulCharacter = CurPtr-1;
2484 }
2485 C = getAndAdvanceChar(CurPtr, Result);
2486 }
2487
2488 // If we are in C++11, lex the optional ud-suffix.
2489 if (LangOpts.CPlusPlus)
2490 CurPtr = LexUDSuffix(Result, CurPtr, false);
2491
2492 // If a nul character existed in the character, warn about it.
2493 if (NulCharacter && !isLexingRawMode())
2494 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2495
2496 // Update the location of token as well as BufferPtr.
2497 const char *TokStart = BufferPtr;
2498 FormTokenWithChars(Result, CurPtr, Kind);
2499 Result.setLiteralData(TokStart);
2500 return true;
2501}
2502
2503/// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2504/// Update BufferPtr to point to the next non-whitespace character and return.
2505///
2506/// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2507bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2508 bool &TokAtPhysicalStartOfLine) {
2509 // Whitespace - Skip it, then return the token after the whitespace.
2510 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2511
2512 unsigned char Char = *CurPtr;
2513
2514 const char *lastNewLine = nullptr;
2515 auto setLastNewLine = [&](const char *Ptr) {
2516 lastNewLine = Ptr;
2517 if (!NewLinePtr)
2518 NewLinePtr = Ptr;
2519 };
2520 if (SawNewline)
2521 setLastNewLine(CurPtr - 1);
2522
2523 // Skip consecutive spaces efficiently.
2524 while (true) {
2525 // Skip horizontal whitespace very aggressively.
2526 while (isHorizontalWhitespace(Char))
2527 Char = *++CurPtr;
2528
2529 // Otherwise if we have something other than whitespace, we're done.
2530 if (!isVerticalWhitespace(Char))
2531 break;
2532
2534 // End of preprocessor directive line, let LexTokenInternal handle this.
2535 BufferPtr = CurPtr;
2536 return false;
2537 }
2538
2539 // OK, but handle newline.
2540 if (*CurPtr == '\n')
2541 setLastNewLine(CurPtr);
2542 SawNewline = true;
2543 Char = *++CurPtr;
2544 }
2545
2546 // If the client wants us to return whitespace, return it now.
2547 if (isKeepWhitespaceMode()) {
2548 FormTokenWithChars(Result, CurPtr, tok::unknown);
2549 if (SawNewline) {
2550 IsAtStartOfLine = true;
2551 IsAtPhysicalStartOfLine = true;
2552 }
2553 // FIXME: The next token will not have LeadingSpace set.
2554 return true;
2555 }
2556
2557 // If this isn't immediately after a newline, there is leading space.
2558 char PrevChar = CurPtr[-1];
2559 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2560
2561 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2562 if (SawNewline) {
2563 Result.setFlag(Token::StartOfLine);
2564 TokAtPhysicalStartOfLine = true;
2565
2566 if (NewLinePtr && lastNewLine && NewLinePtr != lastNewLine && PP) {
2567 if (auto *Handler = PP->getEmptylineHandler())
2568 Handler->HandleEmptyline(SourceRange(getSourceLocation(NewLinePtr + 1),
2569 getSourceLocation(lastNewLine)));
2570 }
2571 }
2572
2573 BufferPtr = CurPtr;
2574 return false;
2575}
2576
2577/// We have just read the // characters from input. Skip until we find the
2578/// newline character that terminates the comment. Then update BufferPtr and
2579/// return.
2580///
2581/// If we're in KeepCommentMode or any CommentHandler has inserted
2582/// some tokens, this will store the first token and return true.
2583bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2584 bool &TokAtPhysicalStartOfLine) {
2585 // If Line comments aren't explicitly enabled for this language, emit an
2586 // extension warning.
2587 if (!LineComment) {
2588 if (!isLexingRawMode()) // There's no PP in raw mode, so can't emit diags.
2589 Diag(BufferPtr, diag::ext_line_comment);
2590
2591 // Mark them enabled so we only emit one warning for this translation
2592 // unit.
2593 LineComment = true;
2594 }
2595
2596 // Scan over the body of the comment. The common case, when scanning, is that
2597 // the comment contains normal ascii characters with nothing interesting in
2598 // them. As such, optimize for this case with the inner loop.
2599 //
2600 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2601 // character that ends the line comment.
2602
2603 // C++23 [lex.phases] p1
2604 // Diagnose invalid UTF-8 if the corresponding warning is enabled, emitting a
2605 // diagnostic only once per entire ill-formed subsequence to avoid
2606 // emiting to many diagnostics (see http://unicode.org/review/pr-121.html).
2607 bool UnicodeDecodingAlreadyDiagnosed = false;
2608
2609 char C;
2610 while (true) {
2611 C = *CurPtr;
2612 // Skip over characters in the fast loop.
2613 while (isASCII(C) && C != 0 && // Potentially EOF.
2614 C != '\n' && C != '\r') { // Newline or DOS-style newline.
2615 C = *++CurPtr;
2616 UnicodeDecodingAlreadyDiagnosed = false;
2617 }
2618
2619 if (!isASCII(C)) {
2620 unsigned Length = llvm::getUTF8SequenceSize(
2621 (const llvm::UTF8 *)CurPtr, (const llvm::UTF8 *)BufferEnd);
2622 if (Length == 0) {
2623 if (!UnicodeDecodingAlreadyDiagnosed && !isLexingRawMode())
2624 Diag(CurPtr, diag::warn_invalid_utf8_in_comment);
2625 UnicodeDecodingAlreadyDiagnosed = true;
2626 ++CurPtr;
2627 } else {
2628 UnicodeDecodingAlreadyDiagnosed = false;
2629 CurPtr += Length;
2630 }
2631 continue;
2632 }
2633
2634 const char *NextLine = CurPtr;
2635 if (C != 0) {
2636 // We found a newline, see if it's escaped.
2637 const char *EscapePtr = CurPtr-1;
2638 bool HasSpace = false;
2639 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2640 --EscapePtr;
2641 HasSpace = true;
2642 }
2643
2644 if (*EscapePtr == '\\')
2645 // Escaped newline.
2646 CurPtr = EscapePtr;
2647 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2648 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2649 // Trigraph-escaped newline.
2650 CurPtr = EscapePtr-2;
2651 else
2652 break; // This is a newline, we're done.
2653
2654 // If there was space between the backslash and newline, warn about it.
2655 if (HasSpace && !isLexingRawMode())
2656 Diag(EscapePtr, diag::backslash_newline_space);
2657 }
2658
2659 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2660 // properly decode the character. Read it in raw mode to avoid emitting
2661 // diagnostics about things like trigraphs. If we see an escaped newline,
2662 // we'll handle it below.
2663 const char *OldPtr = CurPtr;
2664 bool OldRawMode = isLexingRawMode();
2665 LexingRawMode = true;
2666 C = getAndAdvanceChar(CurPtr, Result);
2667 LexingRawMode = OldRawMode;
2668
2669 // If we only read only one character, then no special handling is needed.
2670 // We're done and can skip forward to the newline.
2671 if (C != 0 && CurPtr == OldPtr+1) {
2672 CurPtr = NextLine;
2673 break;
2674 }
2675
2676 // If we read multiple characters, and one of those characters was a \r or
2677 // \n, then we had an escaped newline within the comment. Emit diagnostic
2678 // unless the next line is also a // comment.
2679 if (CurPtr != OldPtr + 1 && C != '/' &&
2680 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
2681 for (; OldPtr != CurPtr; ++OldPtr)
2682 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2683 // Okay, we found a // comment that ends in a newline, if the next
2684 // line is also a // comment, but has spaces, don't emit a diagnostic.
2685 if (isWhitespace(C)) {
2686 const char *ForwardPtr = CurPtr;
2687 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2688 ++ForwardPtr;
2689 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2690 break;
2691 }
2692
2693 if (!isLexingRawMode())
2694 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2695 break;
2696 }
2697 }
2698
2699 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2700 --CurPtr;
2701 break;
2702 }
2703
2704 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2705 PP->CodeCompleteNaturalLanguage();
2706 cutOffLexing();
2707 return false;
2708 }
2709 }
2710
2711 // Found but did not consume the newline. Notify comment handlers about the
2712 // comment unless we're in a #if 0 block.
2713 if (PP && !isLexingRawMode() &&
2714 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2715 getSourceLocation(CurPtr)))) {
2716 BufferPtr = CurPtr;
2717 return true; // A token has to be returned.
2718 }
2719
2720 // If we are returning comments as tokens, return this comment as a token.
2721 if (inKeepCommentMode())
2722 return SaveLineComment(Result, CurPtr);
2723
2724 // If we are inside a preprocessor directive and we see the end of line,
2725 // return immediately, so that the lexer can return this as an EOD token.
2726 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2727 BufferPtr = CurPtr;
2728 return false;
2729 }
2730
2731 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2732 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2733 // contribute to another token), it isn't needed for correctness. Note that
2734 // this is ok even in KeepWhitespaceMode, because we would have returned the
2735 // comment above in that mode.
2736 NewLinePtr = CurPtr++;
2737
2738 // The next returned token is at the start of the line.
2739 Result.setFlag(Token::StartOfLine);
2740 TokAtPhysicalStartOfLine = true;
2741 // No leading whitespace seen so far.
2742 Result.clearFlag(Token::LeadingSpace);
2743 BufferPtr = CurPtr;
2744 return false;
2745}
2746
2747/// If in save-comment mode, package up this Line comment in an appropriate
2748/// way and return it.
2749bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2750 // If we're not in a preprocessor directive, just return the // comment
2751 // directly.
2752 FormTokenWithChars(Result, CurPtr, tok::comment);
2753
2755 return true;
2756
2757 // If this Line-style comment is in a macro definition, transmogrify it into
2758 // a C-style block comment.
2759 bool Invalid = false;
2760 std::string Spelling = PP->getSpelling(Result, &Invalid);
2761 if (Invalid)
2762 return true;
2763
2764 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2765 Spelling[1] = '*'; // Change prefix to "/*".
2766 Spelling += "*/"; // add suffix.
2767
2768 Result.setKind(tok::comment);
2769 PP->CreateString(Spelling, Result,
2770 Result.getLocation(), Result.getLocation());
2771 return true;
2772}
2773
2774/// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2775/// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2776/// a diagnostic if so. We know that the newline is inside of a block comment.
2777static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L,
2778 bool Trigraphs) {
2779 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2780
2781 // Position of the first trigraph in the ending sequence.
2782 const char *TrigraphPos = nullptr;
2783 // Position of the first whitespace after a '\' in the ending sequence.
2784 const char *SpacePos = nullptr;
2785
2786 while (true) {
2787 // Back up off the newline.
2788 --CurPtr;
2789
2790 // If this is a two-character newline sequence, skip the other character.
2791 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2792 // \n\n or \r\r -> not escaped newline.
2793 if (CurPtr[0] == CurPtr[1])
2794 return false;
2795 // \n\r or \r\n -> skip the newline.
2796 --CurPtr;
2797 }
2798
2799 // If we have horizontal whitespace, skip over it. We allow whitespace
2800 // between the slash and newline.
2801 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2802 SpacePos = CurPtr;
2803 --CurPtr;
2804 }
2805
2806 // If we have a slash, this is an escaped newline.
2807 if (*CurPtr == '\\') {
2808 --CurPtr;
2809 } else if (CurPtr[0] == '/' && CurPtr[-1] == '?' && CurPtr[-2] == '?') {
2810 // This is a trigraph encoding of a slash.
2811 TrigraphPos = CurPtr - 2;
2812 CurPtr -= 3;
2813 } else {
2814 return false;
2815 }
2816
2817 // If the character preceding the escaped newline is a '*', then after line
2818 // splicing we have a '*/' ending the comment.
2819 if (*CurPtr == '*')
2820 break;
2821
2822 if (*CurPtr != '\n' && *CurPtr != '\r')
2823 return false;
2824 }
2825
2826 if (TrigraphPos) {
2827 // If no trigraphs are enabled, warn that we ignored this trigraph and
2828 // ignore this * character.
2829 if (!Trigraphs) {
2830 if (!L->isLexingRawMode())
2831 L->Diag(TrigraphPos, diag::trigraph_ignored_block_comment);
2832 return false;
2833 }
2834 if (!L->isLexingRawMode())
2835 L->Diag(TrigraphPos, diag::trigraph_ends_block_comment);
2836 }
2837
2838 // Warn about having an escaped newline between the */ characters.
2839 if (!L->isLexingRawMode())
2840 L->Diag(CurPtr + 1, diag::escaped_newline_block_comment_end);
2841
2842 // If there was space between the backslash and newline, warn about it.
2843 if (SpacePos && !L->isLexingRawMode())
2844 L->Diag(SpacePos, diag::backslash_newline_space);
2845
2846 return true;
2847}
2848
2849#ifdef __SSE2__
2850#include <emmintrin.h>
2851#elif __ALTIVEC__
2852#include <altivec.h>
2853#undef bool
2854#endif
2855
2856/// We have just read from input the / and * characters that started a comment.
2857/// Read until we find the * and / characters that terminate the comment.
2858/// Note that we don't bother decoding trigraphs or escaped newlines in block
2859/// comments, because they cannot cause the comment to end. The only thing
2860/// that can happen is the comment could end with an escaped newline between
2861/// the terminating * and /.
2862///
2863/// If we're in KeepCommentMode or any CommentHandler has inserted
2864/// some tokens, this will store the first token and return true.
2865bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2866 bool &TokAtPhysicalStartOfLine) {
2867 // Scan one character past where we should, looking for a '/' character. Once
2868 // we find it, check to see if it was preceded by a *. This common
2869 // optimization helps people who like to put a lot of * characters in their
2870 // comments.
2871
2872 // The first character we get with newlines and trigraphs skipped to handle
2873 // the degenerate /*/ case below correctly if the * has an escaped newline
2874 // after it.
2875 unsigned CharSize;
2876 unsigned char C = getCharAndSize(CurPtr, CharSize);
2877 CurPtr += CharSize;
2878 if (C == 0 && CurPtr == BufferEnd+1) {
2879 if (!isLexingRawMode())
2880 Diag(BufferPtr, diag::err_unterminated_block_comment);
2881 --CurPtr;
2882
2883 // KeepWhitespaceMode should return this broken comment as a token. Since
2884 // it isn't a well formed comment, just return it as an 'unknown' token.
2885 if (isKeepWhitespaceMode()) {
2886 FormTokenWithChars(Result, CurPtr, tok::unknown);
2887 return true;
2888 }
2889
2890 BufferPtr = CurPtr;
2891 return false;
2892 }
2893
2894 // Check to see if the first character after the '/*' is another /. If so,
2895 // then this slash does not end the block comment, it is part of it.
2896 if (C == '/')
2897 C = *CurPtr++;
2898
2899 // C++23 [lex.phases] p1
2900 // Diagnose invalid UTF-8 if the corresponding warning is enabled, emitting a
2901 // diagnostic only once per entire ill-formed subsequence to avoid
2902 // emiting to many diagnostics (see http://unicode.org/review/pr-121.html).
2903 bool UnicodeDecodingAlreadyDiagnosed = false;
2904
2905 while (true) {
2906 // Skip over all non-interesting characters until we find end of buffer or a
2907 // (probably ending) '/' character.
2908 if (CurPtr + 24 < BufferEnd &&
2909 // If there is a code-completion point avoid the fast scan because it
2910 // doesn't check for '\0'.
2911 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2912 // While not aligned to a 16-byte boundary.
2913 while (C != '/' && (intptr_t)CurPtr % 16 != 0) {
2914 if (!isASCII(C))
2915 goto MultiByteUTF8;
2916 C = *CurPtr++;
2917 }
2918 if (C == '/') goto FoundSlash;
2919
2920#ifdef __SSE2__
2921 __m128i Slashes = _mm_set1_epi8('/');
2922 while (CurPtr + 16 < BufferEnd) {
2923 int Mask = _mm_movemask_epi8(*(const __m128i *)CurPtr);
2924 if (LLVM_UNLIKELY(Mask != 0)) {
2925 goto MultiByteUTF8;
2926 }
2927 // look for slashes
2928 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2929 Slashes));
2930 if (cmp != 0) {
2931 // Adjust the pointer to point directly after the first slash. It's
2932 // not necessary to set C here, it will be overwritten at the end of
2933 // the outer loop.
2934 CurPtr += llvm::countr_zero<unsigned>(cmp) + 1;
2935 goto FoundSlash;
2936 }
2937 CurPtr += 16;
2938 }
2939#elif __ALTIVEC__
2940 __vector unsigned char LongUTF = {0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
2941 0x80, 0x80, 0x80, 0x80, 0x80, 0x80,
2942 0x80, 0x80, 0x80, 0x80};
2943 __vector unsigned char Slashes = {
2944 '/', '/', '/', '/', '/', '/', '/', '/',
2945 '/', '/', '/', '/', '/', '/', '/', '/'
2946 };
2947 while (CurPtr + 16 < BufferEnd) {
2948 if (LLVM_UNLIKELY(
2949 vec_any_ge(*(const __vector unsigned char *)CurPtr, LongUTF)))
2950 goto MultiByteUTF8;
2951 if (vec_any_eq(*(const __vector unsigned char *)CurPtr, Slashes)) {
2952 break;
2953 }
2954 CurPtr += 16;
2955 }
2956
2957#else
2958 while (CurPtr + 16 < BufferEnd) {
2959 bool HasNonASCII = false;
2960 for (unsigned I = 0; I < 16; ++I)
2961 HasNonASCII |= !isASCII(CurPtr[I]);
2962
2963 if (LLVM_UNLIKELY(HasNonASCII))
2964 goto MultiByteUTF8;
2965
2966 bool HasSlash = false;
2967 for (unsigned I = 0; I < 16; ++I)
2968 HasSlash |= CurPtr[I] == '/';
2969 if (HasSlash)
2970 break;
2971 CurPtr += 16;
2972 }
2973#endif
2974
2975 // It has to be one of the bytes scanned, increment to it and read one.
2976 C = *CurPtr++;
2977 }
2978
2979 // Loop to scan the remainder, warning on invalid UTF-8
2980 // if the corresponding warning is enabled, emitting a diagnostic only once
2981 // per sequence that cannot be decoded.
2982 while (C != '/' && C != '\0') {
2983 if (isASCII(C)) {
2984 UnicodeDecodingAlreadyDiagnosed = false;
2985 C = *CurPtr++;
2986 continue;
2987 }
2988 MultiByteUTF8:
2989 // CurPtr is 1 code unit past C, so to decode
2990 // the codepoint, we need to read from the previous position.
2991 unsigned Length = llvm::getUTF8SequenceSize(
2992 (const llvm::UTF8 *)CurPtr - 1, (const llvm::UTF8 *)BufferEnd);
2993 if (Length == 0) {
2994 if (!UnicodeDecodingAlreadyDiagnosed && !isLexingRawMode())
2995 Diag(CurPtr - 1, diag::warn_invalid_utf8_in_comment);
2996 UnicodeDecodingAlreadyDiagnosed = true;
2997 } else {
2998 UnicodeDecodingAlreadyDiagnosed = false;
2999 CurPtr += Length - 1;
3000 }
3001 C = *CurPtr++;
3002 }
3003
3004 if (C == '/') {
3005 FoundSlash:
3006 if (CurPtr[-2] == '*') // We found the final */. We're done!
3007 break;
3008
3009 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
3010 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr - 2, this,
3011 LangOpts.Trigraphs)) {
3012 // We found the final */, though it had an escaped newline between the
3013 // * and /. We're done!
3014 break;
3015 }
3016 }
3017 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
3018 // If this is a /* inside of the comment, emit a warning. Don't do this
3019 // if this is a /*/, which will end the comment. This misses cases with
3020 // embedded escaped newlines, but oh well.
3021 if (!isLexingRawMode())
3022 Diag(CurPtr-1, diag::warn_nested_block_comment);
3023 }
3024 } else if (C == 0 && CurPtr == BufferEnd+1) {
3025 if (!isLexingRawMode())
3026 Diag(BufferPtr, diag::err_unterminated_block_comment);
3027 // Note: the user probably forgot a */. We could continue immediately
3028 // after the /*, but this would involve lexing a lot of what really is the
3029 // comment, which surely would confuse the parser.
3030 --CurPtr;
3031
3032 // KeepWhitespaceMode should return this broken comment as a token. Since
3033 // it isn't a well formed comment, just return it as an 'unknown' token.
3034 if (isKeepWhitespaceMode()) {
3035 FormTokenWithChars(Result, CurPtr, tok::unknown);
3036 return true;
3037 }
3038
3039 BufferPtr = CurPtr;
3040 return false;
3041 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
3042 PP->CodeCompleteNaturalLanguage();
3043 cutOffLexing();
3044 return false;
3045 }
3046
3047 C = *CurPtr++;
3048 }
3049
3050 // Notify comment handlers about the comment unless we're in a #if 0 block.
3051 if (PP && !isLexingRawMode() &&
3052 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
3053 getSourceLocation(CurPtr)))) {
3054 BufferPtr = CurPtr;
3055 return true; // A token has to be returned.
3056 }
3057
3058 // If we are returning comments as tokens, return this comment as a token.
3059 if (inKeepCommentMode()) {
3060 FormTokenWithChars(Result, CurPtr, tok::comment);
3061 return true;
3062 }
3063
3064 // It is common for the tokens immediately after a /**/ comment to be
3065 // whitespace. Instead of going through the big switch, handle it
3066 // efficiently now. This is safe even in KeepWhitespaceMode because we would
3067 // have already returned above with the comment as a token.
3068 if (isHorizontalWhitespace(*CurPtr)) {
3069 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
3070 return false;
3071 }
3072
3073 // Otherwise, just return so that the next character will be lexed as a token.
3074 BufferPtr = CurPtr;
3075 Result.setFlag(Token::LeadingSpace);
3076 return false;
3077}
3078
3079//===----------------------------------------------------------------------===//
3080// Primary Lexing Entry Points
3081//===----------------------------------------------------------------------===//
3082
3083/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
3084/// uninterpreted string. This switches the lexer out of directive mode.
3086 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
3087 "Must be in a preprocessing directive!");
3088 Token Tmp;
3089 Tmp.startToken();
3090
3091 // CurPtr - Cache BufferPtr in an automatic variable.
3092 const char *CurPtr = BufferPtr;
3093 while (true) {
3094 char Char = getAndAdvanceChar(CurPtr, Tmp);
3095 switch (Char) {
3096 default:
3097 if (Result)
3098 Result->push_back(Char);
3099 break;
3100 case 0: // Null.
3101 // Found end of file?
3102 if (CurPtr-1 != BufferEnd) {
3103 if (isCodeCompletionPoint(CurPtr-1)) {
3104 PP->CodeCompleteNaturalLanguage();
3105 cutOffLexing();
3106 return;
3107 }
3108
3109 // Nope, normal character, continue.
3110 if (Result)
3111 Result->push_back(Char);
3112 break;
3113 }
3114 // FALL THROUGH.
3115 [[fallthrough]];
3116 case '\r':
3117 case '\n':
3118 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
3119 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
3120 BufferPtr = CurPtr-1;
3121
3122 // Next, lex the character, which should handle the EOD transition.
3123 Lex(Tmp);
3124 if (Tmp.is(tok::code_completion)) {
3125 if (PP)
3126 PP->CodeCompleteNaturalLanguage();
3127 Lex(Tmp);
3128 }
3129 assert(Tmp.is(tok::eod) && "Unexpected token!");
3130
3131 // Finally, we're done;
3132 return;
3133 }
3134 }
3135}
3136
3137/// LexEndOfFile - CurPtr points to the end of this file. Handle this
3138/// condition, reporting diagnostics and handling other edge cases as required.
3139/// This returns true if Result contains a token, false if PP.Lex should be
3140/// called again.
3141bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
3142 // If we hit the end of the file while parsing a preprocessor directive,
3143 // end the preprocessor directive first. The next token returned will
3144 // then be the end of file.
3146 // Done parsing the "line".
3148 // Update the location of token as well as BufferPtr.
3149 FormTokenWithChars(Result, CurPtr, tok::eod);
3150
3151 // Restore comment saving mode, in case it was disabled for directive.
3152 if (PP)
3154 return true; // Have a token.
3155 }
3156
3157 // If we are in raw mode, return this event as an EOF token. Let the caller
3158 // that put us in raw mode handle the event.
3159 if (isLexingRawMode()) {
3160 Result.startToken();
3161 BufferPtr = BufferEnd;
3162 FormTokenWithChars(Result, BufferEnd, tok::eof);
3163 return true;
3164 }
3165
3166 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
3167 PP->setRecordedPreambleConditionalStack(ConditionalStack);
3168 // If the preamble cuts off the end of a header guard, consider it guarded.
3169 // The guard is valid for the preamble content itself, and for tools the
3170 // most useful answer is "yes, this file has a header guard".
3171 if (!ConditionalStack.empty())
3172 MIOpt.ExitTopLevelConditional();
3173 ConditionalStack.clear();
3174 }
3175
3176 // Issue diagnostics for unterminated #if and missing newline.
3177
3178 // If we are in a #if directive, emit an error.
3179 while (!ConditionalStack.empty()) {
3180 if (PP->getCodeCompletionFileLoc() != FileLoc)
3181 PP->Diag(ConditionalStack.back().IfLoc,
3182 diag::err_pp_unterminated_conditional);
3183 ConditionalStack.pop_back();
3184 }
3185
3186 // Before C++11 and C2y, a file not ending with a newline was UB. Both
3187 // standards changed this behavior (as a DR or equivalent), but we still have
3188 // an opt-in diagnostic to warn about it.
3189 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
3190 Diag(BufferEnd, diag::warn_no_newline_eof)
3191 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
3192
3193 BufferPtr = CurPtr;
3194
3195 // Finally, let the preprocessor handle this.
3196 return PP->HandleEndOfFile(Result, isPragmaLexer());
3197}
3198
3199/// peekNextPPToken - Return std::nullopt if there are no more tokens in the
3200/// buffer controlled by this lexer, otherwise return the next unexpanded
3201/// token.
3202std::optional<Token> Lexer::peekNextPPToken() {
3203 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
3204
3205 if (isDependencyDirectivesLexer()) {
3206 if (NextDepDirectiveTokenIndex == DepDirectives.front().Tokens.size())
3207 return std::nullopt;
3208 Token Result;
3209 (void)convertDependencyDirectiveToken(
3210 DepDirectives.front().Tokens[NextDepDirectiveTokenIndex], Result);
3211 return Result;
3212 }
3213
3214 // Switch to 'skipping' mode. This will ensure that we can lex a token
3215 // without emitting diagnostics, disables macro expansion, and will cause EOF
3216 // to return an EOF token instead of popping the include stack.
3217 LexingRawMode = true;
3218
3219 // Save state that can be changed while lexing so that we can restore it.
3220 const char *TmpBufferPtr = BufferPtr;
3221 bool inPPDirectiveMode = ParsingPreprocessorDirective;
3222 bool atStartOfLine = IsAtStartOfLine;
3223 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3224 bool leadingSpace = HasLeadingSpace;
3225
3226 Token Tok;
3227 Lex(Tok);
3228
3229 // Restore state that may have changed.
3230 BufferPtr = TmpBufferPtr;
3231 ParsingPreprocessorDirective = inPPDirectiveMode;
3232 HasLeadingSpace = leadingSpace;
3233 IsAtStartOfLine = atStartOfLine;
3234 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
3235 // Restore the lexer back to non-skipping mode.
3236 LexingRawMode = false;
3237
3238 if (Tok.is(tok::eof))
3239 return std::nullopt;
3240 return Tok;
3241}
3242
3243/// Find the end of a version control conflict marker.
3244static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
3245 ConflictMarkerKind CMK) {
3246 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
3247 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
3248 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
3249 size_t Pos = RestOfBuffer.find(Terminator);
3250 while (Pos != StringRef::npos) {
3251 // Must occur at start of line.
3252 if (Pos == 0 ||
3253 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
3254 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
3255 Pos = RestOfBuffer.find(Terminator);
3256 continue;
3257 }
3258 return RestOfBuffer.data()+Pos;
3259 }
3260 return nullptr;
3261}
3262
3263/// IsStartOfConflictMarker - If the specified pointer is the start of a version
3264/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
3265/// and recover nicely. This returns true if it is a conflict marker and false
3266/// if not.
3267bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
3268 // Only a conflict marker if it starts at the beginning of a line.
3269 if (CurPtr != BufferStart &&
3270 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
3271 return false;
3272
3273 // Check to see if we have <<<<<<< or >>>>.
3274 if (!StringRef(CurPtr, BufferEnd - CurPtr).starts_with("<<<<<<<") &&
3275 !StringRef(CurPtr, BufferEnd - CurPtr).starts_with(">>>> "))
3276 return false;
3277
3278 // If we have a situation where we don't care about conflict markers, ignore
3279 // it.
3280 if (CurrentConflictMarkerState || isLexingRawMode())
3281 return false;
3282
3283 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
3284
3285 // Check to see if there is an ending marker somewhere in the buffer at the
3286 // start of a line to terminate this conflict marker.
3287 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
3288 // We found a match. We are really in a conflict marker.
3289 // Diagnose this, and ignore to the end of line.
3290 Diag(CurPtr, diag::err_conflict_marker);
3291 CurrentConflictMarkerState = Kind;
3292
3293 // Skip ahead to the end of line. We know this exists because the
3294 // end-of-conflict marker starts with \r or \n.
3295 while (*CurPtr != '\r' && *CurPtr != '\n') {
3296 assert(CurPtr != BufferEnd && "Didn't find end of line");
3297 ++CurPtr;
3298 }
3299 BufferPtr = CurPtr;
3300 return true;
3301 }
3302
3303 // No end of conflict marker found.
3304 return false;
3305}
3306
3307/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
3308/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
3309/// is the end of a conflict marker. Handle it by ignoring up until the end of
3310/// the line. This returns true if it is a conflict marker and false if not.
3311bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
3312 // Only a conflict marker if it starts at the beginning of a line.
3313 if (CurPtr != BufferStart &&
3314 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
3315 return false;
3316
3317 // If we have a situation where we don't care about conflict markers, ignore
3318 // it.
3319 if (!CurrentConflictMarkerState || isLexingRawMode())
3320 return false;
3321
3322 // Check to see if we have the marker (4 characters in a row).
3323 for (unsigned i = 1; i != 4; ++i)
3324 if (CurPtr[i] != CurPtr[0])
3325 return false;
3326
3327 // If we do have it, search for the end of the conflict marker. This could
3328 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
3329 // be the end of conflict marker.
3330 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
3331 CurrentConflictMarkerState)) {
3332 CurPtr = End;
3333
3334 // Skip ahead to the end of line.
3335 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
3336 ++CurPtr;
3337
3338 BufferPtr = CurPtr;
3339
3340 // No longer in the conflict marker.
3341 CurrentConflictMarkerState = CMK_None;
3342 return true;
3343 }
3344
3345 return false;
3346}
3347
3348static const char *findPlaceholderEnd(const char *CurPtr,
3349 const char *BufferEnd) {
3350 if (CurPtr == BufferEnd)
3351 return nullptr;
3352 BufferEnd -= 1; // Scan until the second last character.
3353 for (; CurPtr != BufferEnd; ++CurPtr) {
3354 if (CurPtr[0] == '#' && CurPtr[1] == '>')
3355 return CurPtr + 2;
3356 }
3357 return nullptr;
3358}
3359
3360bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
3361 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
3362 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
3363 return false;
3364 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
3365 if (!End)
3366 return false;
3367 const char *Start = CurPtr - 1;
3368 if (!LangOpts.AllowEditorPlaceholders)
3369 Diag(Start, diag::err_placeholder_in_source);
3370 Result.startToken();
3371 FormTokenWithChars(Result, End, tok::raw_identifier);
3372 Result.setRawIdentifierData(Start);
3373 PP->LookUpIdentifierInfo(Result);
3375 BufferPtr = End;
3376 return true;
3377}
3378
3379bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
3380 if (PP && PP->isCodeCompletionEnabled()) {
3381 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
3382 return Loc == PP->getCodeCompletionLoc();
3383 }
3384
3385 return false;
3386}
3387
3389 bool Named,
3390 const LangOptions &Opts,
3391 DiagnosticsEngine &Diags) {
3392 unsigned DiagId;
3393 if (Opts.CPlusPlus23)
3394 DiagId = diag::warn_cxx23_delimited_escape_sequence;
3395 else if (Opts.C2y && !Named)
3396 DiagId = diag::warn_c2y_delimited_escape_sequence;
3397 else
3398 DiagId = diag::ext_delimited_escape_sequence;
3399
3400 // The trailing arguments are only used by the extension warning; either this
3401 // is a C2y extension or a C++23 extension, unless it's a named escape
3402 // sequence in C, then it's a Clang extension.
3403 unsigned Ext;
3404 if (!Opts.CPlusPlus)
3405 Ext = Named ? 2 /* Clang extension */ : 1 /* C2y extension */;
3406 else
3407 Ext = 0; // C++23 extension
3408
3409 Diags.Report(Loc, DiagId) << Named << Ext;
3410}
3411
3412std::optional<uint32_t> Lexer::tryReadNumericUCN(const char *&StartPtr,
3413 const char *SlashLoc,
3414 Token *Result) {
3415 unsigned CharSize;
3416 char Kind = getCharAndSize(StartPtr, CharSize);
3417 assert((Kind == 'u' || Kind == 'U') && "expected a UCN");
3418
3419 unsigned NumHexDigits;
3420 if (Kind == 'u')
3421 NumHexDigits = 4;
3422 else if (Kind == 'U')
3423 NumHexDigits = 8;
3424
3425 bool Delimited = false;
3426 bool FoundEndDelimiter = false;
3427 unsigned Count = 0;
3428 bool Diagnose = Result && !isLexingRawMode();
3429
3430 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
3431 if (Diagnose)
3432 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
3433 return std::nullopt;
3434 }
3435
3436 const char *CurPtr = StartPtr + CharSize;
3437 const char *KindLoc = &CurPtr[-1];
3438
3439 uint32_t CodePoint = 0;
3440 while (Count != NumHexDigits || Delimited) {
3441 char C = getCharAndSize(CurPtr, CharSize);
3442 if (!Delimited && Count == 0 && C == '{') {
3443 Delimited = true;
3444 CurPtr += CharSize;
3445 continue;
3446 }
3447
3448 if (Delimited && C == '}') {
3449 CurPtr += CharSize;
3450 FoundEndDelimiter = true;
3451 break;
3452 }
3453
3454 unsigned Value = llvm::hexDigitValue(C);
3455 if (Value == std::numeric_limits<unsigned>::max()) {
3456 if (!Delimited)
3457 break;
3458 if (Diagnose)
3459 Diag(SlashLoc, diag::warn_delimited_ucn_incomplete)
3460 << StringRef(KindLoc, 1);
3461 return std::nullopt;
3462 }
3463
3464 if (CodePoint & 0xF000'0000) {
3465 if (Diagnose)
3466 Diag(KindLoc, diag::err_escape_too_large) << 0;
3467 return std::nullopt;
3468 }
3469
3470 CodePoint <<= 4;
3471 CodePoint |= Value;
3472 CurPtr += CharSize;
3473 Count++;
3474 }
3475
3476 if (Count == 0) {
3477 if (Diagnose)
3478 Diag(SlashLoc, FoundEndDelimiter ? diag::warn_delimited_ucn_empty
3479 : diag::warn_ucn_escape_no_digits)
3480 << StringRef(KindLoc, 1);
3481 return std::nullopt;
3482 }
3483
3484 if (Delimited && Kind == 'U') {
3485 if (Diagnose)
3486 Diag(SlashLoc, diag::err_hex_escape_no_digits) << StringRef(KindLoc, 1);
3487 return std::nullopt;
3488 }
3489
3490 if (!Delimited && Count != NumHexDigits) {
3491 if (Diagnose) {
3492 Diag(SlashLoc, diag::warn_ucn_escape_incomplete);
3493 // If the user wrote \U1234, suggest a fixit to \u.
3494 if (Count == 4 && NumHexDigits == 8) {
3495 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
3496 Diag(KindLoc, diag::note_ucn_four_not_eight)
3497 << FixItHint::CreateReplacement(URange, "u");
3498 }
3499 }
3500 return std::nullopt;
3501 }
3502
3503 if (Delimited && PP)
3505 PP->getLangOpts(),
3506 PP->getDiagnostics());
3507
3508 if (Result) {
3509 Result->setFlag(Token::HasUCN);
3510 // If the UCN contains either a trigraph or a line splicing,
3511 // we need to call getAndAdvanceChar again to set the appropriate flags
3512 // on Result.
3513 if (CurPtr - StartPtr == (ptrdiff_t)(Count + 1 + (Delimited ? 2 : 0)))
3514 StartPtr = CurPtr;
3515 else
3516 while (StartPtr != CurPtr)
3517 (void)getAndAdvanceChar(StartPtr, *Result);
3518 } else {
3519 StartPtr = CurPtr;
3520 }
3521 return CodePoint;
3522}
3523
3524std::optional<uint32_t> Lexer::tryReadNamedUCN(const char *&StartPtr,
3525 const char *SlashLoc,
3526 Token *Result) {
3527 unsigned CharSize;
3528 bool Diagnose = Result && !isLexingRawMode();
3529
3530 char C = getCharAndSize(StartPtr, CharSize);
3531 assert(C == 'N' && "expected \\N{...}");
3532
3533 const char *CurPtr = StartPtr + CharSize;
3534 const char *KindLoc = &CurPtr[-1];
3535
3536 C = getCharAndSize(CurPtr, CharSize);
3537 if (C != '{') {
3538 if (Diagnose)
3539 Diag(SlashLoc, diag::warn_ucn_escape_incomplete);
3540 return std::nullopt;
3541 }
3542 CurPtr += CharSize;
3543 const char *StartName = CurPtr;
3544 bool FoundEndDelimiter = false;
3545 llvm::SmallVector<char, 30> Buffer;
3546 while (C) {
3547 C = getCharAndSize(CurPtr, CharSize);
3548 CurPtr += CharSize;
3549 if (C == '}') {
3550 FoundEndDelimiter = true;
3551 break;
3552 }
3553
3555 break;
3556 Buffer.push_back(C);
3557 }
3558
3559 if (!FoundEndDelimiter || Buffer.empty()) {
3560 if (Diagnose)
3561 Diag(SlashLoc, FoundEndDelimiter ? diag::warn_delimited_ucn_empty
3562 : diag::warn_delimited_ucn_incomplete)
3563 << StringRef(KindLoc, 1);
3564 return std::nullopt;
3565 }
3566
3567 StringRef Name(Buffer.data(), Buffer.size());
3568 std::optional<char32_t> Match =
3569 llvm::sys::unicode::nameToCodepointStrict(Name);
3570 std::optional<llvm::sys::unicode::LooseMatchingResult> LooseMatch;
3571 if (!Match) {
3572 LooseMatch = llvm::sys::unicode::nameToCodepointLooseMatching(Name);
3573 if (Diagnose) {
3574 Diag(StartName, diag::err_invalid_ucn_name)
3575 << StringRef(Buffer.data(), Buffer.size())
3576 << makeCharRange(*this, StartName, CurPtr - CharSize);
3577 if (LooseMatch) {
3578 Diag(StartName, diag::note_invalid_ucn_name_loose_matching)
3580 makeCharRange(*this, StartName, CurPtr - CharSize),
3581 LooseMatch->Name);
3582 }
3583 }
3584 // We do not offer misspelled character names suggestions here
3585 // as the set of what would be a valid suggestion depends on context,
3586 // and we should not make invalid suggestions.
3587 }
3588
3589 if (Diagnose && Match)
3591 PP->getLangOpts(),
3592 PP->getDiagnostics());
3593
3594 // If no diagnostic has been emitted yet, likely because we are doing a
3595 // tentative lexing, we do not want to recover here to make sure the token
3596 // will not be incorrectly considered valid. This function will be called
3597 // again and a diagnostic emitted then.
3598 if (LooseMatch && Diagnose)
3599 Match = LooseMatch->CodePoint;
3600
3601 if (Result) {
3602 Result->setFlag(Token::HasUCN);
3603 // If the UCN contains either a trigraph or a line splicing,
3604 // we need to call getAndAdvanceChar again to set the appropriate flags
3605 // on Result.
3606 if (CurPtr - StartPtr == (ptrdiff_t)(Buffer.size() + 3))
3607 StartPtr = CurPtr;
3608 else
3609 while (StartPtr != CurPtr)
3610 (void)getAndAdvanceChar(StartPtr, *Result);
3611 } else {
3612 StartPtr = CurPtr;
3613 }
3614 return Match ? std::optional<uint32_t>(*Match) : std::nullopt;
3615}
3616
3617uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
3618 Token *Result) {
3619
3620 unsigned CharSize;
3621 std::optional<uint32_t> CodePointOpt;
3622 char Kind = getCharAndSize(StartPtr, CharSize);
3623 if (Kind == 'u' || Kind == 'U')
3624 CodePointOpt = tryReadNumericUCN(StartPtr, SlashLoc, Result);
3625 else if (Kind == 'N')
3626 CodePointOpt = tryReadNamedUCN(StartPtr, SlashLoc, Result);
3627
3628 if (!CodePointOpt)
3629 return 0;
3630
3631 uint32_t CodePoint = *CodePointOpt;
3632
3633 // Don't apply C family restrictions to UCNs in assembly mode
3634 if (LangOpts.AsmPreprocessor)
3635 return CodePoint;
3636
3637 // C23 6.4.3p2: A universal character name shall not designate a code point
3638 // where the hexadecimal value is:
3639 // - in the range D800 through DFFF inclusive; or
3640 // - greater than 10FFFF.
3641 // A universal-character-name outside the c-char-sequence of a character
3642 // constant, or the s-char-sequence of a string-literal shall not designate
3643 // a control character or a character in the basic character set.
3644
3645 // C++11 [lex.charset]p2: If the hexadecimal value for a
3646 // universal-character-name corresponds to a surrogate code point (in the
3647 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
3648 // if the hexadecimal value for a universal-character-name outside the
3649 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
3650 // string literal corresponds to a control character (in either of the
3651 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
3652 // basic source character set, the program is ill-formed.
3653 if (CodePoint < 0xA0) {
3654 // We don't use isLexingRawMode() here because we need to warn about bad
3655 // UCNs even when skipping preprocessing tokens in a #if block.
3656 if (Result && PP) {
3657 if (CodePoint < 0x20 || CodePoint >= 0x7F)
3658 Diag(BufferPtr, diag::err_ucn_control_character);
3659 else {
3660 char C = static_cast<char>(CodePoint);
3661 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
3662 }
3663 }
3664
3665 return 0;
3666 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
3667 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
3668 // We don't use isLexingRawMode() here because we need to diagnose bad
3669 // UCNs even when skipping preprocessing tokens in a #if block.
3670 if (Result && PP) {
3671 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
3672 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
3673 else
3674 Diag(BufferPtr, diag::err_ucn_escape_invalid);
3675 }
3676 return 0;
3677 }
3678
3679 return CodePoint;
3680}
3681
3682bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3683 const char *CurPtr) {
3684 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
3686 Diag(BufferPtr, diag::ext_unicode_whitespace)
3687 << makeCharRange(*this, BufferPtr, CurPtr);
3688
3689 Result.setFlag(Token::LeadingSpace);
3690 return true;
3691 }
3692 return false;
3693}
3694
3695void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3696 IsAtStartOfLine = Result.isAtStartOfLine();
3697 HasLeadingSpace = Result.hasLeadingSpace();
3698 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3699 // Note that this doesn't affect IsAtPhysicalStartOfLine.
3700}
3701
3703 assert(!isDependencyDirectivesLexer());
3704
3705 // Start a new token.
3706 Result.startToken();
3707
3708 // Set up misc whitespace flags for LexTokenInternal.
3709 if (IsAtStartOfLine) {
3710 Result.setFlag(Token::StartOfLine);
3711 IsAtStartOfLine = false;
3712 }
3713
3714 if (HasLeadingSpace) {
3715 Result.setFlag(Token::LeadingSpace);
3716 HasLeadingSpace = false;
3717 }
3718
3719 if (HasLeadingEmptyMacro) {
3721 HasLeadingEmptyMacro = false;
3722 }
3723
3724 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3725 IsAtPhysicalStartOfLine = false;
3726 bool isRawLex = isLexingRawMode();
3727 (void) isRawLex;
3728 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3729 // (After the LexTokenInternal call, the lexer might be destroyed.)
3730 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3731 return returnedToken;
3732}
3733
3734/// LexTokenInternal - This implements a simple C family lexer. It is an
3735/// extremely performance critical piece of code. This assumes that the buffer
3736/// has a null character at the end of the file. This returns a preprocessing
3737/// token, not a normal token, as such, it is an internal interface. It assumes
3738/// that the Flags of result have been cleared before calling this.
3739bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3740LexStart:
3741 assert(!Result.needsCleaning() && "Result needs cleaning");
3742 assert(!Result.hasPtrData() && "Result has not been reset");
3743
3744 // CurPtr - Cache BufferPtr in an automatic variable.
3745 const char *CurPtr = BufferPtr;
3746
3747 // Small amounts of horizontal whitespace is very common between tokens.
3748 if (isHorizontalWhitespace(*CurPtr)) {
3749 do {
3750 ++CurPtr;
3751 } while (isHorizontalWhitespace(*CurPtr));
3752
3753 // If we are keeping whitespace and other tokens, just return what we just
3754 // skipped. The next lexer invocation will return the token after the
3755 // whitespace.
3756 if (isKeepWhitespaceMode()) {
3757 FormTokenWithChars(Result, CurPtr, tok::unknown);
3758 // FIXME: The next token will not have LeadingSpace set.
3759 return true;
3760 }
3761
3762 BufferPtr = CurPtr;
3763 Result.setFlag(Token::LeadingSpace);
3764 }
3765
3766 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
3767
3768 // Read a character, advancing over it.
3769 char Char = getAndAdvanceChar(CurPtr, Result);
3771
3772 if (!isVerticalWhitespace(Char))
3773 NewLinePtr = nullptr;
3774
3775 switch (Char) {
3776 case 0: // Null.
3777 // Found end of file?
3778 if (CurPtr-1 == BufferEnd)
3779 return LexEndOfFile(Result, CurPtr-1);
3780
3781 // Check if we are performing code completion.
3782 if (isCodeCompletionPoint(CurPtr-1)) {
3783 // Return the code-completion token.
3784 Result.startToken();
3785 FormTokenWithChars(Result, CurPtr, tok::code_completion);
3786 return true;
3787 }
3788
3789 if (!isLexingRawMode())
3790 Diag(CurPtr-1, diag::null_in_file);
3791 Result.setFlag(Token::LeadingSpace);
3792 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3793 return true; // KeepWhitespaceMode
3794
3795 // We know the lexer hasn't changed, so just try again with this lexer.
3796 // (We manually eliminate the tail call to avoid recursion.)
3797 goto LexNextToken;
3798
3799 case 26: // DOS & CP/M EOF: "^Z".
3800 // If we're in Microsoft extensions mode, treat this as end of file.
3801 if (LangOpts.MicrosoftExt) {
3802 if (!isLexingRawMode())
3803 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3804 return LexEndOfFile(Result, CurPtr-1);
3805 }
3806
3807 // If Microsoft extensions are disabled, this is just random garbage.
3808 Kind = tok::unknown;
3809 break;
3810
3811 case '\r':
3812 if (CurPtr[0] == '\n')
3813 (void)getAndAdvanceChar(CurPtr, Result);
3814 [[fallthrough]];
3815 case '\n':
3816 // If we are inside a preprocessor directive and we see the end of line,
3817 // we know we are done with the directive, so return an EOD token.
3819 // Done parsing the "line".
3821
3822 // Restore comment saving mode, in case it was disabled for directive.
3823 if (PP)
3825
3826 // Since we consumed a newline, we are back at the start of a line.
3827 IsAtStartOfLine = true;
3828 IsAtPhysicalStartOfLine = true;
3829 NewLinePtr = CurPtr - 1;
3830
3831 Kind = tok::eod;
3832 break;
3833 }
3834
3835 // No leading whitespace seen so far.
3836 Result.clearFlag(Token::LeadingSpace);
3837
3838 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3839 return true; // KeepWhitespaceMode
3840
3841 // We only saw whitespace, so just try again with this lexer.
3842 // (We manually eliminate the tail call to avoid recursion.)
3843 goto LexNextToken;
3844 case ' ':
3845 case '\t':
3846 case '\f':
3847 case '\v':
3848 SkipHorizontalWhitespace:
3849 Result.setFlag(Token::LeadingSpace);
3850 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3851 return true; // KeepWhitespaceMode
3852
3853 SkipIgnoredUnits:
3854 CurPtr = BufferPtr;
3855
3856 // If the next token is obviously a // or /* */ comment, skip it efficiently
3857 // too (without going through the big switch stmt).
3858 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3859 LineComment && (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3860 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3861 return true; // There is a token to return.
3862 goto SkipIgnoredUnits;
3863 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3864 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3865 return true; // There is a token to return.
3866 goto SkipIgnoredUnits;
3867 } else if (isHorizontalWhitespace(*CurPtr)) {
3868 goto SkipHorizontalWhitespace;
3869 }
3870 // We only saw whitespace, so just try again with this lexer.
3871 // (We manually eliminate the tail call to avoid recursion.)
3872 goto LexNextToken;
3873
3874 // C99 6.4.4.1: Integer Constants.
3875 // C99 6.4.4.2: Floating Constants.
3876 case '0': case '1': case '2': case '3': case '4':
3877 case '5': case '6': case '7': case '8': case '9':
3878 // Notify MIOpt that we read a non-whitespace/non-comment token.
3879 MIOpt.ReadToken();
3880 return LexNumericConstant(Result, CurPtr);
3881
3882 // Identifier (e.g., uber), or
3883 // UTF-8 (C23/C++17) or UTF-16 (C11/C++11) character literal, or
3884 // UTF-8 or UTF-16 string literal (C11/C++11).
3885 case 'u':
3886 // Notify MIOpt that we read a non-whitespace/non-comment token.
3887 MIOpt.ReadToken();
3888
3889 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3890 Char = getCharAndSize(CurPtr, SizeTmp);
3891
3892 // UTF-16 string literal
3893 if (Char == '"')
3894 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3895 tok::utf16_string_literal);
3896
3897 // UTF-16 character constant
3898 if (Char == '\'')
3899 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3900 tok::utf16_char_constant);
3901
3902 // UTF-16 raw string literal
3903 if (Char == 'R' && LangOpts.RawStringLiterals &&
3904 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3905 return LexRawStringLiteral(Result,
3906 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3907 SizeTmp2, Result),
3908 tok::utf16_string_literal);
3909
3910 if (Char == '8') {
3911 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3912
3913 // UTF-8 string literal
3914 if (Char2 == '"')
3915 return LexStringLiteral(Result,
3916 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3917 SizeTmp2, Result),
3918 tok::utf8_string_literal);
3919 if (Char2 == '\'' && (LangOpts.CPlusPlus17 || LangOpts.C23))
3920 return LexCharConstant(
3921 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3922 SizeTmp2, Result),
3923 tok::utf8_char_constant);
3924
3925 if (Char2 == 'R' && LangOpts.RawStringLiterals) {
3926 unsigned SizeTmp3;
3927 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3928 // UTF-8 raw string literal
3929 if (Char3 == '"') {
3930 return LexRawStringLiteral(Result,
3931 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3932 SizeTmp2, Result),
3933 SizeTmp3, Result),
3934 tok::utf8_string_literal);
3935 }
3936 }
3937 }
3938 }
3939
3940 // treat u like the start of an identifier.
3941 return LexIdentifierContinue(Result, CurPtr);
3942
3943 case 'U': // Identifier (e.g. Uber) or C11/C++11 UTF-32 string literal
3944 // Notify MIOpt that we read a non-whitespace/non-comment token.
3945 MIOpt.ReadToken();
3946
3947 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3948 Char = getCharAndSize(CurPtr, SizeTmp);
3949
3950 // UTF-32 string literal
3951 if (Char == '"')
3952 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3953 tok::utf32_string_literal);
3954
3955 // UTF-32 character constant
3956 if (Char == '\'')
3957 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3958 tok::utf32_char_constant);
3959
3960 // UTF-32 raw string literal
3961 if (Char == 'R' && LangOpts.RawStringLiterals &&
3962 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3963 return LexRawStringLiteral(Result,
3964 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3965 SizeTmp2, Result),
3966 tok::utf32_string_literal);
3967 }
3968
3969 // treat U like the start of an identifier.
3970 return LexIdentifierContinue(Result, CurPtr);
3971
3972 case 'R': // Identifier or C++0x raw string literal
3973 // Notify MIOpt that we read a non-whitespace/non-comment token.
3974 MIOpt.ReadToken();
3975
3976 if (LangOpts.RawStringLiterals) {
3977 Char = getCharAndSize(CurPtr, SizeTmp);
3978
3979 if (Char == '"')
3980 return LexRawStringLiteral(Result,
3981 ConsumeChar(CurPtr, SizeTmp, Result),
3982 tok::string_literal);
3983 }
3984
3985 // treat R like the start of an identifier.
3986 return LexIdentifierContinue(Result, CurPtr);
3987
3988 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3989 // Notify MIOpt that we read a non-whitespace/non-comment token.
3990 MIOpt.ReadToken();
3991 Char = getCharAndSize(CurPtr, SizeTmp);
3992
3993 // Wide string literal.
3994 if (Char == '"')
3995 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3996 tok::wide_string_literal);
3997
3998 // Wide raw string literal.
3999 if (LangOpts.RawStringLiterals && Char == 'R' &&
4000 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
4001 return LexRawStringLiteral(Result,
4002 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4003 SizeTmp2, Result),
4004 tok::wide_string_literal);
4005
4006 // Wide character constant.
4007 if (Char == '\'')
4008 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4009 tok::wide_char_constant);
4010 // FALL THROUGH, treating L like the start of an identifier.
4011 [[fallthrough]];
4012
4013 // C99 6.4.2: Identifiers.
4014 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
4015 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
4016 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
4017 case 'V': case 'W': case 'X': case 'Y': case 'Z':
4018 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
4019 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
4020 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
4021 case 'v': case 'w': case 'x': case 'y': case 'z':
4022 case '_':
4023 // Notify MIOpt that we read a non-whitespace/non-comment token.
4024 MIOpt.ReadToken();
4025 return LexIdentifierContinue(Result, CurPtr);
4026
4027 case '$': // $ in identifiers.
4028 if (LangOpts.DollarIdents) {
4029 if (!isLexingRawMode())
4030 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
4031 // Notify MIOpt that we read a non-whitespace/non-comment token.
4032 MIOpt.ReadToken();
4033 return LexIdentifierContinue(Result, CurPtr);
4034 }
4035
4036 Kind = tok::unknown;
4037 break;
4038
4039 // C99 6.4.4: Character Constants.
4040 case '\'':
4041 // Notify MIOpt that we read a non-whitespace/non-comment token.
4042 MIOpt.ReadToken();
4043 return LexCharConstant(Result, CurPtr, tok::char_constant);
4044
4045 // C99 6.4.5: String Literals.
4046 case '"':
4047 // Notify MIOpt that we read a non-whitespace/non-comment token.
4048 MIOpt.ReadToken();
4049 return LexStringLiteral(Result, CurPtr,
4050 ParsingFilename ? tok::header_name
4051 : tok::string_literal);
4052
4053 // C99 6.4.6: Punctuators.
4054 case '?':
4055 Kind = tok::question;
4056 break;
4057 case '[':
4058 Kind = tok::l_square;
4059 break;
4060 case ']':
4061 Kind = tok::r_square;
4062 break;
4063 case '(':
4064 Kind = tok::l_paren;
4065 break;
4066 case ')':
4067 Kind = tok::r_paren;
4068 break;
4069 case '{':
4070 Kind = tok::l_brace;
4071 break;
4072 case '}':
4073 Kind = tok::r_brace;
4074 break;
4075 case '.':
4076 Char = getCharAndSize(CurPtr, SizeTmp);
4077 if (Char >= '0' && Char <= '9') {
4078 // Notify MIOpt that we read a non-whitespace/non-comment token.
4079 MIOpt.ReadToken();
4080
4081 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
4082 } else if (LangOpts.CPlusPlus && Char == '*') {
4083 Kind = tok::periodstar;
4084 CurPtr += SizeTmp;
4085 } else if (Char == '.' &&
4086 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
4087 Kind = tok::ellipsis;
4088 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4089 SizeTmp2, Result);
4090 } else {
4091 Kind = tok::period;
4092 }
4093 break;
4094 case '&':
4095 Char = getCharAndSize(CurPtr, SizeTmp);
4096 if (Char == '&') {
4097 Kind = tok::ampamp;
4098 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4099 } else if (Char == '=') {
4100 Kind = tok::ampequal;
4101 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4102 } else {
4103 Kind = tok::amp;
4104 }
4105 break;
4106 case '*':
4107 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
4108 Kind = tok::starequal;
4109 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4110 } else {
4111 Kind = tok::star;
4112 }
4113 break;
4114 case '+':
4115 Char = getCharAndSize(CurPtr, SizeTmp);
4116 if (Char == '+') {
4117 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4118 Kind = tok::plusplus;
4119 } else if (Char == '=') {
4120 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4121 Kind = tok::plusequal;
4122 } else {
4123 Kind = tok::plus;
4124 }
4125 break;
4126 case '-':
4127 Char = getCharAndSize(CurPtr, SizeTmp);
4128 if (Char == '-') { // --
4129 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4130 Kind = tok::minusminus;
4131 } else if (Char == '>' && LangOpts.CPlusPlus &&
4132 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
4133 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4134 SizeTmp2, Result);
4135 Kind = tok::arrowstar;
4136 } else if (Char == '>') { // ->
4137 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4138 Kind = tok::arrow;
4139 } else if (Char == '=') { // -=
4140 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4141 Kind = tok::minusequal;
4142 } else {
4143 Kind = tok::minus;
4144 }
4145 break;
4146 case '~':
4147 Kind = tok::tilde;
4148 break;
4149 case '!':
4150 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
4151 Kind = tok::exclaimequal;
4152 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4153 } else {
4154 Kind = tok::exclaim;
4155 }
4156 break;
4157 case '/':
4158 // 6.4.9: Comments
4159 Char = getCharAndSize(CurPtr, SizeTmp);
4160 if (Char == '/') { // Line comment.
4161 // Even if Line comments are disabled (e.g. in C89 mode), we generally
4162 // want to lex this as a comment. There is one problem with this though,
4163 // that in one particular corner case, this can change the behavior of the
4164 // resultant program. For example, In "foo //**/ bar", C89 would lex
4165 // this as "foo / bar" and languages with Line comments would lex it as
4166 // "foo". Check to see if the character after the second slash is a '*'.
4167 // If so, we will lex that as a "/" instead of the start of a comment.
4168 // However, we never do this if we are just preprocessing.
4169 bool TreatAsComment =
4170 LineComment && (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
4171 if (!TreatAsComment)
4172 if (!(PP && PP->isPreprocessedOutput()))
4173 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
4174
4175 if (TreatAsComment) {
4176 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4177 TokAtPhysicalStartOfLine))
4178 return true; // There is a token to return.
4179
4180 // It is common for the tokens immediately after a // comment to be
4181 // whitespace (indentation for the next line). Instead of going through
4182 // the big switch, handle it efficiently now.
4183 goto SkipIgnoredUnits;
4184 }
4185 }
4186
4187 if (Char == '*') { // /**/ comment.
4188 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4189 TokAtPhysicalStartOfLine))
4190 return true; // There is a token to return.
4191
4192 // We only saw whitespace, so just try again with this lexer.
4193 // (We manually eliminate the tail call to avoid recursion.)
4194 goto LexNextToken;
4195 }
4196
4197 if (Char == '=') {
4198 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4199 Kind = tok::slashequal;
4200 } else {
4201 Kind = tok::slash;
4202 }
4203 break;
4204 case '%':
4205 Char = getCharAndSize(CurPtr, SizeTmp);
4206 if (Char == '=') {
4207 Kind = tok::percentequal;
4208 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4209 } else if (LangOpts.Digraphs && Char == '>') {
4210 Kind = tok::r_brace; // '%>' -> '}'
4211 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4212 } else if (LangOpts.Digraphs && Char == ':') {
4213 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4214 Char = getCharAndSize(CurPtr, SizeTmp);
4215 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
4216 Kind = tok::hashhash; // '%:%:' -> '##'
4217 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4218 SizeTmp2, Result);
4219 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
4220 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4221 if (!isLexingRawMode())
4222 Diag(BufferPtr, diag::ext_charize_microsoft);
4223 Kind = tok::hashat;
4224 } else { // '%:' -> '#'
4225 // We parsed a # character. If this occurs at the start of the line,
4226 // it's actually the start of a preprocessing directive. Callback to
4227 // the preprocessor to handle it.
4228 // TODO: -fpreprocessed mode??
4229 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
4230 goto HandleDirective;
4231
4232 Kind = tok::hash;
4233 }
4234 } else {
4235 Kind = tok::percent;
4236 }
4237 break;
4238 case '<':
4239 Char = getCharAndSize(CurPtr, SizeTmp);
4240 if (ParsingFilename) {
4241 return LexAngledStringLiteral(Result, CurPtr);
4242 } else if (Char == '<') {
4243 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4244 if (After == '=') {
4245 Kind = tok::lesslessequal;
4246 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4247 SizeTmp2, Result);
4248 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
4249 // If this is actually a '<<<<<<<' version control conflict marker,
4250 // recognize it as such and recover nicely.
4251 goto LexNextToken;
4252 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
4253 // If this is '<<<<' and we're in a Perforce-style conflict marker,
4254 // ignore it.
4255 goto LexNextToken;
4256 } else if (LangOpts.CUDA && After == '<') {
4257 Kind = tok::lesslessless;
4258 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4259 SizeTmp2, Result);
4260 } else {
4261 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4262 Kind = tok::lessless;
4263 }
4264 } else if (Char == '=') {
4265 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4266 if (After == '>') {
4267 if (LangOpts.CPlusPlus20) {
4268 if (!isLexingRawMode())
4269 Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
4270 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4271 SizeTmp2, Result);
4272 Kind = tok::spaceship;
4273 break;
4274 }
4275 // Suggest adding a space between the '<=' and the '>' to avoid a
4276 // change in semantics if this turns up in C++ <=17 mode.
4277 if (LangOpts.CPlusPlus && !isLexingRawMode()) {
4278 Diag(BufferPtr, diag::warn_cxx20_compat_spaceship)
4280 getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
4281 }
4282 }
4283 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4284 Kind = tok::lessequal;
4285 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
4286 if (LangOpts.CPlusPlus11 &&
4287 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
4288 // C++0x [lex.pptoken]p3:
4289 // Otherwise, if the next three characters are <:: and the subsequent
4290 // character is neither : nor >, the < is treated as a preprocessor
4291 // token by itself and not as the first character of the alternative
4292 // token <:.
4293 unsigned SizeTmp3;
4294 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
4295 if (After != ':' && After != '>') {
4296 Kind = tok::less;
4297 if (!isLexingRawMode())
4298 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
4299 break;
4300 }
4301 }
4302
4303 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4304 Kind = tok::l_square;
4305 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
4306 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4307 Kind = tok::l_brace;
4308 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
4309 lexEditorPlaceholder(Result, CurPtr)) {
4310 return true;
4311 } else {
4312 Kind = tok::less;
4313 }
4314 break;
4315 case '>':
4316 Char = getCharAndSize(CurPtr, SizeTmp);
4317 if (Char == '=') {
4318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4319 Kind = tok::greaterequal;
4320 } else if (Char == '>') {
4321 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4322 if (After == '=') {
4323 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4324 SizeTmp2, Result);
4325 Kind = tok::greatergreaterequal;
4326 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
4327 // If this is actually a '>>>>' conflict marker, recognize it as such
4328 // and recover nicely.
4329 goto LexNextToken;
4330 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
4331 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
4332 goto LexNextToken;
4333 } else if (LangOpts.CUDA && After == '>') {
4334 Kind = tok::greatergreatergreater;
4335 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4336 SizeTmp2, Result);
4337 } else {
4338 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4339 Kind = tok::greatergreater;
4340 }
4341 } else {
4342 Kind = tok::greater;
4343 }
4344 break;
4345 case '^':
4346 Char = getCharAndSize(CurPtr, SizeTmp);
4347 if (Char == '=') {
4348 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4349 Kind = tok::caretequal;
4350 } else {
4351 if (LangOpts.OpenCL && Char == '^')
4352 Diag(CurPtr, diag::err_opencl_logical_exclusive_or);
4353 Kind = tok::caret;
4354 }
4355 break;
4356 case '|':
4357 Char = getCharAndSize(CurPtr, SizeTmp);
4358 if (Char == '=') {
4359 Kind = tok::pipeequal;
4360 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4361 } else if (Char == '|') {
4362 // If this is '|||||||' and we're in a conflict marker, ignore it.
4363 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
4364 goto LexNextToken;
4365 Kind = tok::pipepipe;
4366 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4367 } else {
4368 Kind = tok::pipe;
4369 }
4370 break;
4371 case ':':
4372 Char = getCharAndSize(CurPtr, SizeTmp);
4373 if (LangOpts.Digraphs && Char == '>') {
4374 Kind = tok::r_square; // ':>' -> ']'
4375 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4376 } else if (Char == ':') {
4377 Kind = tok::coloncolon;
4378 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4379 } else {
4380 Kind = tok::colon;
4381 }
4382 break;
4383 case ';':
4384 Kind = tok::semi;
4385 break;
4386 case '=':
4387 Char = getCharAndSize(CurPtr, SizeTmp);
4388 if (Char == '=') {
4389 // If this is '====' and we're in a conflict marker, ignore it.
4390 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
4391 goto LexNextToken;
4392
4393 Kind = tok::equalequal;
4394 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4395 } else {
4396 Kind = tok::equal;
4397 }
4398 break;
4399 case ',':
4400 Kind = tok::comma;
4401 break;
4402 case '#':
4403 Char = getCharAndSize(CurPtr, SizeTmp);
4404 if (Char == '#') {
4405 Kind = tok::hashhash;
4406 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4407 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
4408 Kind = tok::hashat;
4409 if (!isLexingRawMode())
4410 Diag(BufferPtr, diag::ext_charize_microsoft);
4411 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4412 } else {
4413 // We parsed a # character. If this occurs at the start of the line,
4414 // it's actually the start of a preprocessing directive. Callback to
4415 // the preprocessor to handle it.
4416 // TODO: -fpreprocessed mode??
4417 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
4418 goto HandleDirective;
4419
4420 Kind = tok::hash;
4421 }
4422 break;
4423
4424 case '@':
4425 // Objective C support.
4426 if (CurPtr[-1] == '@' && LangOpts.ObjC)
4427 Kind = tok::at;
4428 else
4429 Kind = tok::unknown;
4430 break;
4431
4432 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
4433 case '\\':
4434 if (!LangOpts.AsmPreprocessor) {
4435 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
4436 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
4437 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
4438 return true; // KeepWhitespaceMode
4439
4440 // We only saw whitespace, so just try again with this lexer.
4441 // (We manually eliminate the tail call to avoid recursion.)
4442 goto LexNextToken;
4443 }
4444
4445 return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
4446 }
4447 }
4448
4449 Kind = tok::unknown;
4450 break;
4451
4452 default: {
4453 if (isASCII(Char)) {
4454 Kind = tok::unknown;
4455 break;
4456 }
4457
4458 llvm::UTF32 CodePoint;
4459
4460 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
4461 // an escaped newline.
4462 --CurPtr;
4463 llvm::ConversionResult Status =
4464 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
4465 (const llvm::UTF8 *)BufferEnd,
4466 &CodePoint,
4467 llvm::strictConversion);
4468 if (Status == llvm::conversionOK) {
4469 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
4470 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
4471 return true; // KeepWhitespaceMode
4472
4473 // We only saw whitespace, so just try again with this lexer.
4474 // (We manually eliminate the tail call to avoid recursion.)
4475 goto LexNextToken;
4476 }
4477 return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
4478 }
4479
4481 PP->isPreprocessedOutput()) {
4482 ++CurPtr;
4483 Kind = tok::unknown;
4484 break;
4485 }
4486
4487 // Non-ASCII characters tend to creep into source code unintentionally.
4488 // Instead of letting the parser complain about the unknown token,
4489 // just diagnose the invalid UTF-8, then drop the character.
4490 Diag(CurPtr, diag::err_invalid_utf8);
4491
4492 BufferPtr = CurPtr+1;
4493 // We're pretending the character didn't exist, so just try again with
4494 // this lexer.
4495 // (We manually eliminate the tail call to avoid recursion.)
4496 goto LexNextToken;
4497 }
4498 }
4499
4500 // Notify MIOpt that we read a non-whitespace/non-comment token.
4501 MIOpt.ReadToken();
4502
4503 // Update the location of token as well as BufferPtr.
4504 FormTokenWithChars(Result, CurPtr, Kind);
4505 return true;
4506
4507HandleDirective:
4508 // We parsed a # character and it's the start of a preprocessing directive.
4509
4510 FormTokenWithChars(Result, CurPtr, tok::hash);
4511 PP->HandleDirective(Result);
4512
4513 if (PP->hadModuleLoaderFatalFailure())
4514 // With a fatal failure in the module loader, we abort parsing.
4515 return true;
4516
4517 // We parsed the directive; lex a token with the new state.
4518 return false;
4519
4520LexNextToken:
4521 Result.clearFlag(Token::NeedsCleaning);
4522 goto LexStart;
4523}
4524
4525const char *Lexer::convertDependencyDirectiveToken(
4527 const char *TokPtr = BufferStart + DDTok.Offset;
4528 Result.startToken();
4529 Result.setLocation(getSourceLocation(TokPtr));
4530 Result.setKind(DDTok.Kind);
4531 Result.setFlag((Token::TokenFlags)DDTok.Flags);
4532 Result.setLength(DDTok.Length);
4533 BufferPtr = TokPtr + DDTok.Length;
4534 return TokPtr;
4535}
4536
4537bool Lexer::LexDependencyDirectiveToken(Token &Result) {
4538 assert(isDependencyDirectivesLexer());
4539
4540 using namespace dependency_directives_scan;
4541
4542 if (BufferPtr == BufferEnd)
4543 return LexEndOfFile(Result, BufferPtr);
4544
4545 while (NextDepDirectiveTokenIndex == DepDirectives.front().Tokens.size()) {
4546 if (DepDirectives.front().Kind == pp_eof)
4547 return LexEndOfFile(Result, BufferEnd);
4548 if (DepDirectives.front().Kind == tokens_present_before_eof)
4549 MIOpt.ReadToken();
4550 NextDepDirectiveTokenIndex = 0;
4551 DepDirectives = DepDirectives.drop_front();
4552 }
4553
4554 const dependency_directives_scan::Token &DDTok =
4555 DepDirectives.front().Tokens[NextDepDirectiveTokenIndex++];
4556 if (NextDepDirectiveTokenIndex > 1 || DDTok.Kind != tok::hash) {
4557 // Read something other than a preprocessor directive hash.
4558 MIOpt.ReadToken();
4559 }
4560
4561 if (ParsingFilename && DDTok.is(tok::less)) {
4562 BufferPtr = BufferStart + DDTok.Offset;
4563 LexAngledStringLiteral(Result, BufferPtr + 1);
4564 if (Result.isNot(tok::header_name))
4565 return true;
4566 // Advance the index of lexed tokens.
4567 while (true) {
4568 const dependency_directives_scan::Token &NextTok =
4569 DepDirectives.front().Tokens[NextDepDirectiveTokenIndex];
4570 if (BufferStart + NextTok.Offset >= BufferPtr)
4571 break;
4572 ++NextDepDirectiveTokenIndex;
4573 }
4574 return true;
4575 }
4576
4577 const char *TokPtr = convertDependencyDirectiveToken(DDTok, Result);
4578
4579 if (Result.is(tok::hash) && Result.isAtStartOfLine()) {
4580 PP->HandleDirective(Result);
4581 if (PP->hadModuleLoaderFatalFailure())
4582 // With a fatal failure in the module loader, we abort parsing.
4583 return true;
4584 return false;
4585 }
4586 if (Result.is(tok::raw_identifier)) {
4587 Result.setRawIdentifierData(TokPtr);
4588 if (!isLexingRawMode()) {
4589 const IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
4590 if (II->isHandleIdentifierCase())
4591 return PP->HandleIdentifier(Result);
4592 }
4593 return true;
4594 }
4595 if (Result.isLiteral()) {
4596 Result.setLiteralData(TokPtr);
4597 return true;
4598 }
4599 if (Result.is(tok::colon)) {
4600 // Convert consecutive colons to 'tok::coloncolon'.
4601 if (*BufferPtr == ':') {
4602 assert(DepDirectives.front().Tokens[NextDepDirectiveTokenIndex].is(
4603 tok::colon));
4604 ++NextDepDirectiveTokenIndex;
4605 Result.setKind(tok::coloncolon);
4606 }
4607 return true;
4608 }
4609 if (Result.is(tok::eod))
4611
4612 return true;
4613}
4614
4615bool Lexer::LexDependencyDirectiveTokenWhileSkipping(Token &Result) {
4616 assert(isDependencyDirectivesLexer());
4617
4618 using namespace dependency_directives_scan;
4619
4620 bool Stop = false;
4621 unsigned NestedIfs = 0;
4622 do {
4623 DepDirectives = DepDirectives.drop_front();
4624 switch (DepDirectives.front().Kind) {
4625 case pp_none:
4626 llvm_unreachable("unexpected 'pp_none'");
4627 case pp_include:
4629 case pp_define:
4630 case pp_undef:
4631 case pp_import:
4632 case pp_pragma_import:
4633 case pp_pragma_once:
4638 case pp_include_next:
4639 case decl_at_import:
4640 case cxx_module_decl:
4641 case cxx_import_decl:
4645 break;
4646 case pp_if:
4647 case pp_ifdef:
4648 case pp_ifndef:
4649 ++NestedIfs;
4650 break;
4651 case pp_elif:
4652 case pp_elifdef:
4653 case pp_elifndef:
4654 case pp_else:
4655 if (!NestedIfs) {
4656 Stop = true;
4657 }
4658 break;
4659 case pp_endif:
4660 if (!NestedIfs) {
4661 Stop = true;
4662 } else {
4663 --NestedIfs;
4664 }
4665 break;
4666 case pp_eof:
4667 NextDepDirectiveTokenIndex = 0;
4668 return LexEndOfFile(Result, BufferEnd);
4669 }
4670 } while (!Stop);
4671
4672 const dependency_directives_scan::Token &DDTok =
4673 DepDirectives.front().Tokens.front();
4674 assert(DDTok.is(tok::hash));
4675 NextDepDirectiveTokenIndex = 1;
4676
4677 convertDependencyDirectiveToken(DDTok, Result);
4678 return false;
4679}
Defines the Diagnostic-related interfaces.
Token Tok
The Token.
unsigned IsFirst
Indicates that this is the first token of the file.
FormatToken * Next
The next token in the unwrapped line.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static bool isInExpansionTokenRange(const SourceLocation Loc, const SourceManager &SM)
Definition Lexer.cpp:943
static bool isMathematicalExtensionID(uint32_t C, const LangOptions &LangOpts, bool IsStart, bool &IsExtension)
Definition Lexer.cpp:1563
static void diagnoseInvalidUnicodeCodepointInIdentifier(DiagnosticsEngine &Diags, const LangOptions &LangOpts, uint32_t CodePoint, CharSourceRange Range, bool IsFirst)
Definition Lexer.cpp:1757
static char DecodeTrigraphChar(const char *CP, Lexer *L, bool Trigraphs)
DecodeTrigraphChar - If the specified character is a legal trigraph when prefixed with ?
Definition Lexer.cpp:1256
static size_t getSpellingSlow(const Token &Tok, const char *BufPtr, const LangOptions &LangOpts, char *Spelling)
Slow case of getSpelling.
Definition Lexer.cpp:323
static const char * FindConflictEnd(const char *CurPtr, const char *BufferEnd, ConflictMarkerKind CMK)
Find the end of a version control conflict marker.
Definition Lexer.cpp:3244
static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C, CharSourceRange Range)
After encountering UTF-8 character C and interpreting it as an identifier character,...
Definition Lexer.cpp:1682
static SourceLocation getBeginningOfFileToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Definition Lexer.cpp:559
static void StringifyImpl(T &Str, char Quote)
Definition Lexer.cpp:283
static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen)
GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the lexer buffer was all exp...
Definition Lexer.cpp:1184
static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts, bool &IsExtension)
Definition Lexer.cpp:1577
static CharSourceRange makeCharRange(Lexer &L, const char *Begin, const char *End)
Definition Lexer.cpp:1647
static bool isUnicodeWhitespace(uint32_t Codepoint)
Definition Lexer.cpp:1544
static void diagnoseExtensionInIdentifier(DiagnosticsEngine &Diags, uint32_t C, CharSourceRange Range)
Definition Lexer.cpp:1631
static const char * findPlaceholderEnd(const char *CurPtr, const char *BufferEnd)
Definition Lexer.cpp:3348
static llvm::SmallString< 5 > codepointAsHexString(uint32_t C)
Definition Lexer.cpp:1550
static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Definition Lexer.cpp:917
static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, Lexer *L, bool Trigraphs)
isBlockCommentEndOfEscapedNewLine - Return true if the specified newline character (either \n or \r) ...
Definition Lexer.cpp:2777
static const char * fastParseASCIIIdentifier(const char *CurPtr, const char *BufferEnd)
Definition Lexer.cpp:1923
static char GetTrigraphCharForLetter(char Letter)
GetTrigraphCharForLetter - Given a character that occurs after a ?
Definition Lexer.cpp:1237
static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts, bool &IsExtension)
Definition Lexer.cpp:1605
static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C, CharSourceRange Range, bool IsFirst)
Definition Lexer.cpp:1653
static const char * findBeginningOfLine(StringRef Buffer, unsigned Offset)
Returns the pointer that points to the beginning of line that contains the given offset,...
Definition Lexer.cpp:542
Defines the MultipleIncludeOpt interface.
#define SM(sm)
Defines the clang::Preprocessor interface.
Defines the clang::SourceLocation class and associated facilities.
Defines the SourceManager interface.
Defines the clang::TokenKind enum and support functions.
static const llvm::sys::UnicodeCharRange C11DisallowedInitialIDCharRanges[]
static const llvm::sys::UnicodeCharRange C99DisallowedInitialIDCharRanges[]
static const llvm::sys::UnicodeCharRange UnicodeWhitespaceCharRanges[]
static const llvm::sys::UnicodeCharRange C99AllowedIDCharRanges[]
static const llvm::sys::UnicodeCharRange C11AllowedIDCharRanges[]
static const llvm::sys::UnicodeCharRange MathematicalNotationProfileIDStartRanges[]
static const llvm::sys::UnicodeCharRange MathematicalNotationProfileIDContinueRanges[]
static const llvm::sys::UnicodeCharRange XIDStartRanges[]
static const llvm::sys::UnicodeCharRange XIDContinueRanges[]
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
__device__ __2f16 float c
__PTRDIFF_TYPE__ ptrdiff_t
A signed integer type that is the result of subtracting two pointers.
static __inline__ int __ATTRS_o_ai vec_any_ge(vector signed char __a, vector signed char __b)
Definition altivec.h:16260
static __inline__ int __ATTRS_o_ai vec_any_eq(vector signed char __a, vector signed char __b)
Definition altivec.h:16052
Represents a character-granular source range.
static CharSourceRange getCharRange(SourceRange R)
SourceLocation getEnd() const
SourceLocation getBegin() const
A little helper class used to produce diagnostics.
Concrete class used by the front-end to report problems and issues.
Definition Diagnostic.h:232
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
bool isIgnored(unsigned DiagID, SourceLocation Loc) const
Determine whether the diagnostic is known to be ignored.
Definition Diagnostic.h:951
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string.
Definition Diagnostic.h:140
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
One of these records is kept for each identifier that is lexed.
bool isHandleIdentifierCase() const
Return true if the Preprocessor::HandleIdentifier must be called on a token of this identifier.
bool isKeyword(const LangOptions &LangOpts) const
Return true if this token is a keyword in the specified language.
tok::ObjCKeywordKind getObjCKeywordID() const
Return the Objective-C keyword ID for the this identifier.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens.
Definition Lexer.h:78
static StringRef getSourceText(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts, bool *Invalid=nullptr)
Returns a string for the source that the range encompasses.
Definition Lexer.cpp:1019
friend class Preprocessor
Definition Lexer.h:79
void SetKeepWhitespaceMode(bool Val)
SetKeepWhitespaceMode - This method lets clients enable or disable whitespace retention mode.
Definition Lexer.h:254
static SourceLocation findLocationAfterToken(SourceLocation loc, tok::TokenKind TKind, const SourceManager &SM, const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine)
Checks that the given token is the first token that occurs after the given location (this excludes co...
Definition Lexer.cpp:1376
bool LexFromRawLexer(Token &Result)
LexFromRawLexer - Lex a token from a designated raw lexer (one with no associated preprocessor object...
Definition Lexer.h:236
static unsigned getEscapedNewLineSize(const char *P)
getEscapedNewLineSize - Return the size of the specified escaped newline, or 0 if it is not an escape...
Definition Lexer.cpp:1275
bool inKeepCommentMode() const
inKeepCommentMode - Return true if the lexer should return comments as tokens.
Definition Lexer.h:262
void SetCommentRetentionState(bool Mode)
SetCommentRetentionMode - Change the comment retention mode of the lexer to the specified mode.
Definition Lexer.h:269
static std::optional< Token > findPreviousToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments)
Finds the token that comes before the given location.
Definition Lexer.cpp:1351
void seek(unsigned Offset, bool IsAtStartOfLine)
Set the lexer's buffer pointer to Offset.
Definition Lexer.cpp:276
static StringRef getImmediateMacroName(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1055
void ReadToEndOfLine(SmallVectorImpl< char > *Result=nullptr)
ReadToEndOfLine - Read the rest of the current preprocessor line as an uninterpreted string.
Definition Lexer.cpp:3085
static bool isAtStartOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroBegin=nullptr)
Returns true if the given MacroID location points at the first token of the macro expansion.
Definition Lexer.cpp:869
DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const
Diag - Forwarding function for diagnostics.
Definition Lexer.cpp:1227
const char * getBufferLocation() const
Return the current location in the buffer.
Definition Lexer.h:308
bool Lex(Token &Result)
Lex - Return the next token in the file.
Definition Lexer.cpp:3702
bool isPragmaLexer() const
isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
Definition Lexer.h:225
static void DiagnoseDelimitedOrNamedEscapeSequence(SourceLocation Loc, bool Named, const LangOptions &Opts, DiagnosticsEngine &Diags)
Diagnose use of a delimited or named escape sequence.
Definition Lexer.cpp:3388
static unsigned getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo, const SourceManager &SM, const LangOptions &LangOpts)
Get the physical length (including trigraphs and escaped newlines) of the first Characters characters...
Definition Lexer.cpp:788
Lexer(FileID FID, const llvm::MemoryBufferRef &InputFile, Preprocessor &PP, bool IsFirstIncludeOfFile=true)
Lexer constructor - Create a new lexer object for the specified buffer with the specified preprocesso...
Definition Lexer.cpp:182
static bool isAtEndOfMacroExpansion(SourceLocation loc, const SourceManager &SM, const LangOptions &LangOpts, SourceLocation *MacroEnd=nullptr)
Returns true if the given MacroID location points at the last token of the macro expansion.
Definition Lexer.cpp:891
SourceLocation getSourceLocation() override
getSourceLocation - Return a source location for the next character in the current file.
Definition Lexer.h:303
static CharSourceRange makeFileCharRange(CharSourceRange Range, const SourceManager &SM, const LangOptions &LangOpts)
Accepts a range and returns a character range with file locations.
Definition Lexer.cpp:950
static bool isNewLineEscaped(const char *BufferStart, const char *Str)
Checks whether new line pointed by Str is preceded by escape sequence.
Definition Lexer.cpp:1133
SourceLocation getSourceLocation(const char *Loc, unsigned TokLen=1) const
getSourceLocation - Return a source location identifier for the specified offset in the current file.
Definition Lexer.cpp:1208
static StringRef getIndentationForLine(SourceLocation Loc, const SourceManager &SM)
Returns the leading whitespace for line that corresponds to the given location Loc.
Definition Lexer.cpp:1153
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer,...
Definition Lexer.cpp:450
bool isKeepWhitespaceMode() const
isKeepWhitespaceMode - Return true if the lexer should return tokens for every character in the file,...
Definition Lexer.h:248
static bool isAsciiIdentifierContinueChar(char c, const LangOptions &LangOpts)
Returns true if the given character could appear in an identifier.
Definition Lexer.cpp:1129
static std::optional< Token > findNextToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts, bool IncludeComments=false)
Finds the token that comes right after the given location.
Definition Lexer.cpp:1320
static unsigned MeasureTokenLength(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
MeasureTokenLength - Relex the token at the specified location and return its length in bytes in the ...
Definition Lexer.cpp:497
static SourceLocation GetBeginningOfToken(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Given a location any where in a source buffer, find the location that corresponds to the beginning of...
Definition Lexer.cpp:607
void resetExtendedTokenMode()
Sets the extended token mode back to its initial value, according to the language options and preproc...
Definition Lexer.cpp:218
static StringRef getImmediateMacroNameForDiagnostics(SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts)
Retrieve the name of the immediate macro expansion.
Definition Lexer.cpp:1102
static Lexer * Create_PragmaLexer(SourceLocation SpellingLoc, SourceLocation ExpansionLocStart, SourceLocation ExpansionLocEnd, unsigned TokLen, Preprocessor &PP)
Create_PragmaLexer: Lexer constructor - Create a new lexer object for _Pragma expansion.
Definition Lexer.cpp:241
static PreambleBounds ComputePreamble(StringRef Buffer, const LangOptions &LangOpts, unsigned MaxLines=0)
Compute the preamble of the given file.
Definition Lexer.cpp:634
static bool getRawToken(SourceLocation Loc, Token &Result, const SourceManager &SM, const LangOptions &LangOpts, bool IgnoreWhiteSpace=false)
Relex the token at the specified location.
Definition Lexer.cpp:508
static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset, const SourceManager &SM, const LangOptions &LangOpts)
Computes the source location just past the end of the token at this source location.
Definition Lexer.cpp:847
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition Lexer.cpp:308
static SizedChar getCharAndSizeNoWarn(const char *Ptr, const LangOptions &LangOpts)
getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever emit a warning.
Definition Lexer.h:604
bool LexingRawMode
True if in raw mode.
SmallVector< PPConditionalInfo, 4 > ConditionalStack
Information about the set of #if/#ifdef/#ifndef blocks we are currently in.
bool ParsingPreprocessorDirective
True when parsing #XXX; turns '\n' into a tok::eod token.
MultipleIncludeOpt MIOpt
A state machine that detects the #ifndef-wrapping a file idiom for the multiple-include optimization.
bool ParsingFilename
True after #include; turns <xx> or "xxx" into a tok::header_name token.
bool isLexingRawMode() const
Return true if this lexer is in raw mode or not.
const FileID FID
The SourceManager FileID corresponding to the file being lexed.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
SourceManager & getSourceManager() const
Encodes a location in the source.
static SourceLocation getFromRawEncoding(UIntTy Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
UIntTy getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it.
This class handles loading and caching of source files into memory.
Each ExpansionInfo encodes the expansion location - where the token was ultimately expanded,...
SourceLocation getExpansionLocStart() const
SourceLocation getSpellingLoc() const
This is a discriminated union of FileInfo and ExpansionInfo.
const ExpansionInfo & getExpansion() const
static bool isValidUDSuffix(const LangOptions &LangOpts, StringRef Suffix)
Determine whether a suffix is a valid ud-suffix.
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:195
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:140
unsigned getLength() const
Definition Token.h:143
tok::ObjCKeywordKind getObjCKeywordID() const
Return the ObjC keyword kind.
Definition Lexer.cpp:68
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
tok::TokenKind getKind() const
Definition Token.h:97
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition Token.h:284
@ IsEditorPlaceholder
Definition Token.h:88
@ LeadingEmptyMacro
Definition Token.h:81
@ LeadingSpace
Definition Token.h:77
@ StartOfLine
Definition Token.h:75
@ HasUDSuffix
Definition Token.h:82
@ NeedsCleaning
Definition Token.h:80
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition Token.h:129
bool isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const
Return true if we have an ObjC keyword identifier.
Definition Lexer.cpp:59
bool isSimpleTypeSpecifier(const LangOptions &LangOpts) const
Determine whether the token kind starts a simple-type-specifier.
Definition Lexer.cpp:76
void startToken()
Reset all flags to cleared.
Definition Token.h:185
bool needsCleaning() const
Return true if this token has trigraphs or escaped newlines in it.
Definition Token.h:303
StringRef getRawIdentifier() const
getRawIdentifier - For a raw identifier token (i.e., an identifier lexed in raw mode),...
Definition Token.h:221
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition Token.h:252
static __inline__ int __DEFAULT_FN_ATTRS_CONSTEXPR _mm_movemask_epi8(__m128i __a)
Copies the values of the most significant bits from each 8-bit element in a 128-bit integer vector of...
Definition emmintrin.h:4284
static __inline__ __m128i __DEFAULT_FN_ATTRS_CONSTEXPR _mm_cmpeq_epi8(__m128i __a, __m128i __b)
Compares each of the corresponding 8-bit values of the 128-bit integer vectors for equality.
Definition emmintrin.h:3087
static __inline__ __m128i __DEFAULT_FN_ATTRS _mm_loadu_si128(__m128i_u const *__p)
Moves packed integer values from an unaligned 128-bit memory location to elements in a 128-bit intege...
Definition emmintrin.h:3456
static __inline__ __m128i __DEFAULT_FN_ATTRS _mm_load_si128(__m128i const *__p)
Moves packed integer values from an aligned 128-bit memory location to elements in a 128-bit integer ...
Definition emmintrin.h:3441
static __inline__ __m128i __DEFAULT_FN_ATTRS_CONSTEXPR _mm_set1_epi8(char __b)
Initializes all values in a 128-bit vector of [16 x i8] with the specified 8-bit value.
Definition emmintrin.h:3744
@ tokens_present_before_eof
Indicates that there are tokens present between the last scanned directive and eof.
@ After
Like System, but searched after the system directories.
bool isStringLiteral(TokenKind K)
Return true if this is a C or C++ string-literal (or C++11 user-defined-string-literal) token.
Definition TokenKinds.h:89
ObjCKeywordKind
Provides a namespace for Objective-C keywords which start with an '@'.
Definition TokenKinds.h:41
TokenKind
Provides a simple uniform namespace for tokens from all C languages.
Definition TokenKinds.h:25
The JSON file list parser is used to communicate input to InstallAPI.
LLVM_READNONE bool isASCII(char c)
Returns true if a byte is an ASCII character.
Definition CharInfo.h:41
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:817
LLVM_READONLY bool isVerticalWhitespace(unsigned char c)
Returns true if this character is vertical ASCII whitespace: '\n', '\r'.
Definition CharInfo.h:99
ConflictMarkerKind
ConflictMarkerKind - Kinds of conflict marker which the lexer might be recovering from.
Definition Lexer.h:44
@ CMK_Perforce
A Perforce-style conflict marker, initiated by 4 ">"s, separated by 4 "="s, and terminated by 4 "<"s.
Definition Lexer.h:54
@ CMK_None
Not within a conflict marker.
Definition Lexer.h:46
@ CMK_Normal
A normal or diff3 conflict marker, initiated by at least 7 "<"s, separated by at least 7 "="s or "|"s...
Definition Lexer.h:50
LLVM_READONLY bool isAsciiIdentifierContinue(unsigned char c)
Definition CharInfo.h:61
std::pair< FileID, unsigned > FileIDAndOffset
bool operator<(DeclarationName LHS, DeclarationName RHS)
Ordering on two declaration names.
LLVM_READONLY bool isHorizontalWhitespace(unsigned char c)
Returns true if this character is horizontal ASCII whitespace: ' ', '\t', '\f', '\v'.
Definition CharInfo.h:91
@ Result
The result type of a method or function.
Definition TypeBase.h:905
const FunctionProtoType * T
LLVM_READONLY bool isRawStringDelimBody(unsigned char c)
Return true if this is the body character of a C++ raw string delimiter.
Definition CharInfo.h:175
LLVM_READONLY bool isWhitespace(unsigned char c)
Return true if this character is horizontal or vertical ASCII whitespace: ' ', '\t',...
Definition CharInfo.h:108
LLVM_READONLY bool isPreprocessingNumberBody(unsigned char c)
Return true if this is the body character of a C preprocessing number, which is [a-zA-Z0-9_.
Definition CharInfo.h:168
@ Keyword
The name has been typo-corrected to a keyword.
Definition Sema.h:561
LLVM_READONLY bool isAsciiIdentifierStart(unsigned char c, bool AllowDollar=false)
Returns true if this is a valid first character of a C identifier, which is [a-zA-Z_].
Definition CharInfo.h:53
unsigned int uint32_t
__INTPTR_TYPE__ intptr_t
A signed integer type with the property that any valid pointer to void can be converted to this type,...
float __ovld __cnfn length(float)
Return the length of vector p, i.e., sqrt(p.x2 + p.y 2 + ...)
#define _SIDD_UBYTE_OPS
Definition smmintrin.h:1549
#define _mm_cmpistri(A, B, M)
Uses the immediate operand M to perform a comparison of string data with implicitly defined lengths t...
Definition smmintrin.h:1681
#define _SIDD_LEAST_SIGNIFICANT
Definition smmintrin.h:1567
#define _SIDD_NEGATIVE_POLARITY
Definition smmintrin.h:1562
#define _SIDD_CMP_RANGES
Definition smmintrin.h:1556
Represents a char and the number of bytes parsed to produce it.
Definition Lexer.h:597
Describes the bounds (start, size) of the preamble and a flag required by PreprocessorOptions::Precom...
Definition Lexer.h:60
Token lexed as part of dependency directive scanning.
unsigned Offset
Offset into the original source input.