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