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/Traits.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()
1003 .isExpansionTokenRange();
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.
1175 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).getBegin());
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.
1257 CharSourceRange II = SM.getImmediateExpansionRange(FileLoc);
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.
2469bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
2470 // Does this string contain the \0 character?
2471 const char *NulCharacter = nullptr;
2472 const char *AfterLessPos = CurPtr;
2473 char C = getAndAdvanceChar(CurPtr, Result);
2474 while (C != '>') {
2475 // Skip escaped characters. Escaped newlines will already be processed by
2476 // getAndAdvanceChar.
2477 if (C == '\\')
2478 C = getAndAdvanceChar(CurPtr, Result);
2479
2480 if (isVerticalWhitespace(C) || // Newline.
2481 (C == 0 && (CurPtr - 1 == BufferEnd))) { // End of file.
2482 // If the filename is unterminated, then it must just be a lone <
2483 // character. Return this as such.
2484 FormTokenWithChars(Result, AfterLessPos, tok::less);
2485 return true;
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 return true;
3167 }
3168
3169 // It is common for the tokens immediately after a /**/ comment to be
3170 // whitespace. Instead of going through the big switch, handle it
3171 // efficiently now. This is safe even in KeepWhitespaceMode because we would
3172 // have already returned above with the comment as a token.
3173 if (isHorizontalWhitespace(*CurPtr)) {
3174 SkipWhitespace(Result, CurPtr + 1);
3175 return false;
3176 }
3177
3178 // Otherwise, just return so that the next character will be lexed as a token.
3179 BufferPtr = CurPtr;
3180 Result.setFlag(Token::LeadingSpace);
3181 return false;
3182}
3183
3184//===----------------------------------------------------------------------===//
3185// Primary Lexing Entry Points
3186//===----------------------------------------------------------------------===//
3187
3188/// ReadToEndOfLine - Read the rest of the current preprocessor line as an
3189/// uninterpreted string. This switches the lexer out of directive mode.
3191 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
3192 "Must be in a preprocessing directive!");
3193 Token Tmp;
3194 Tmp.startToken();
3195
3196 // CurPtr - Cache BufferPtr in an automatic variable.
3197 const char *CurPtr = BufferPtr;
3198 while (true) {
3199 char Char = getAndAdvanceChar(CurPtr, Tmp);
3200 switch (Char) {
3201 default:
3202 if (Result)
3203 Result->push_back(Char);
3204 break;
3205 case 0: // Null.
3206 // Found end of file?
3207 if (CurPtr-1 != BufferEnd) {
3208 if (isCodeCompletionPoint(CurPtr-1)) {
3209 PP->CodeCompleteNaturalLanguage();
3210 cutOffLexing();
3211 return;
3212 }
3213
3214 // Nope, normal character, continue.
3215 if (Result)
3216 Result->push_back(Char);
3217 break;
3218 }
3219 // FALL THROUGH.
3220 [[fallthrough]];
3221 case '\r':
3222 case '\n':
3223 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
3224 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
3225 BufferPtr = CurPtr-1;
3226
3227 // Next, lex the character, which should handle the EOD transition.
3228 Lex(Tmp);
3229 if (Tmp.is(tok::code_completion)) {
3230 if (PP)
3231 PP->CodeCompleteNaturalLanguage();
3232 Lex(Tmp);
3233 }
3234 assert(Tmp.is(tok::eod) && "Unexpected token!");
3235
3236 // Finally, we're done;
3237 return;
3238 }
3239 }
3240}
3241
3242/// LexEndOfFile - CurPtr points to the end of this file. Handle this
3243/// condition, reporting diagnostics and handling other edge cases as required.
3244/// This returns true if Result contains a token, false if PP.Lex should be
3245/// called again.
3246bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
3247 // If we hit the end of the file while parsing a preprocessor directive,
3248 // end the preprocessor directive first. The next token returned will
3249 // then be the end of file.
3251 // Done parsing the "line".
3253 // Update the location of token as well as BufferPtr.
3254 FormTokenWithChars(Result, CurPtr, tok::eod);
3255
3256 // Restore comment saving mode, in case it was disabled for directive.
3257 if (PP)
3259 return true; // Have a token.
3260 }
3261
3262 // If we are in raw mode, return this event as an EOF token. Let the caller
3263 // that put us in raw mode handle the event.
3264 if (isLexingRawMode()) {
3265 Result.startToken();
3266 BufferPtr = BufferEnd;
3267 FormTokenWithChars(Result, BufferEnd, tok::eof);
3268 return true;
3269 }
3270
3271 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
3272 PP->setRecordedPreambleConditionalStack(ConditionalStack);
3273 // If the preamble cuts off the end of a header guard, consider it guarded.
3274 // The guard is valid for the preamble content itself, and for tools the
3275 // most useful answer is "yes, this file has a header guard".
3276 if (!ConditionalStack.empty())
3277 MIOpt.ExitTopLevelConditional();
3278 ConditionalStack.clear();
3279 }
3280
3281 // Issue diagnostics for unterminated #if and missing newline.
3282
3283 // If we are in a #if directive, emit an error.
3284 while (!ConditionalStack.empty()) {
3285 if (PP->getCodeCompletionFileLoc() != FileLoc)
3286 PP->Diag(ConditionalStack.back().IfLoc,
3287 diag::err_pp_unterminated_conditional);
3288 ConditionalStack.pop_back();
3289 }
3290
3291 // Before C++11 and C2y, a file not ending with a newline was UB. Both
3292 // standards changed this behavior (as a DR or equivalent), but we still have
3293 // an opt-in diagnostic to warn about it.
3294 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
3295 Diag(BufferEnd, diag::warn_no_newline_eof)
3296 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
3297
3298 BufferPtr = CurPtr;
3299
3300 // Finally, let the preprocessor handle this.
3301 return PP->HandleEndOfFile(Result, isPragmaLexer());
3302}
3303
3304/// peekNextPPToken - Return std::nullopt if there are no more tokens in the
3305/// buffer controlled by this lexer, otherwise return the next unexpanded
3306/// token.
3307std::optional<Token> Lexer::peekNextPPToken() {
3308 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
3309
3310 if (isDependencyDirectivesLexer()) {
3311 if (NextDepDirectiveTokenIndex == DepDirectives.front().Tokens.size())
3312 return std::nullopt;
3313 Token Result;
3314 (void)convertDependencyDirectiveToken(
3315 DepDirectives.front().Tokens[NextDepDirectiveTokenIndex], Result);
3316 return Result;
3317 }
3318
3319 // Switch to 'skipping' mode. This will ensure that we can lex a token
3320 // without emitting diagnostics, disables macro expansion, and will cause EOF
3321 // to return an EOF token instead of popping the include stack.
3322 LexingRawMode = true;
3323
3324 // Save state that can be changed while lexing so that we can restore it.
3325 const char *TmpBufferPtr = BufferPtr;
3326 bool inPPDirectiveMode = ParsingPreprocessorDirective;
3327 bool atStartOfLine = IsAtStartOfLine;
3328 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3329 bool leadingSpace = HasLeadingSpace;
3330 MultipleIncludeOpt MIOptState = MIOpt;
3331
3332 Token Tok;
3333 Lex(Tok);
3334
3335 // Restore state that may have changed.
3336 BufferPtr = TmpBufferPtr;
3337 ParsingPreprocessorDirective = inPPDirectiveMode;
3338 HasLeadingSpace = leadingSpace;
3339 IsAtStartOfLine = atStartOfLine;
3340 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
3341 MIOpt = MIOptState;
3342 // Restore the lexer back to non-skipping mode.
3343 LexingRawMode = false;
3344
3345 if (Tok.is(tok::eof))
3346 return std::nullopt;
3347 return Tok;
3348}
3349
3350/// Find the end of a version control conflict marker.
3351static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
3352 ConflictMarkerKind CMK) {
3353 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
3354 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
3355 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
3356 size_t Pos = RestOfBuffer.find(Terminator);
3357 while (Pos != StringRef::npos) {
3358 // Must occur at start of line.
3359 if (Pos == 0 ||
3360 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
3361 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
3362 Pos = RestOfBuffer.find(Terminator);
3363 continue;
3364 }
3365 return RestOfBuffer.data()+Pos;
3366 }
3367 return nullptr;
3368}
3369
3370/// IsStartOfConflictMarker - If the specified pointer is the start of a version
3371/// control conflict marker like '<<<<<<<', recognize it as such, emit an error
3372/// and recover nicely. This returns true if it is a conflict marker and false
3373/// if not.
3374bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
3375 // Only a conflict marker if it starts at the beginning of a line.
3376 if (CurPtr != BufferStart &&
3377 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
3378 return false;
3379
3380 // Check to see if we have <<<<<<< or >>>>.
3381 if (!StringRef(CurPtr, BufferEnd - CurPtr).starts_with("<<<<<<<") &&
3382 !StringRef(CurPtr, BufferEnd - CurPtr).starts_with(">>>> "))
3383 return false;
3384
3385 // If we have a situation where we don't care about conflict markers, ignore
3386 // it.
3387 if (CurrentConflictMarkerState || isLexingRawMode())
3388 return false;
3389
3390 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
3391
3392 // Check to see if there is an ending marker somewhere in the buffer at the
3393 // start of a line to terminate this conflict marker.
3394 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
3395 // We found a match. We are really in a conflict marker.
3396 // Diagnose this, and ignore to the end of line.
3397 Diag(CurPtr, diag::err_conflict_marker);
3398 CurrentConflictMarkerState = Kind;
3399
3400 // Skip ahead to the end of line. We know this exists because the
3401 // end-of-conflict marker starts with \r or \n.
3402 while (*CurPtr != '\r' && *CurPtr != '\n') {
3403 assert(CurPtr != BufferEnd && "Didn't find end of line");
3404 ++CurPtr;
3405 }
3406 BufferPtr = CurPtr;
3407 return true;
3408 }
3409
3410 // No end of conflict marker found.
3411 return false;
3412}
3413
3414/// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
3415/// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
3416/// is the end of a conflict marker. Handle it by ignoring up until the end of
3417/// the line. This returns true if it is a conflict marker and false if not.
3418bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
3419 // Only a conflict marker if it starts at the beginning of a line.
3420 if (CurPtr != BufferStart &&
3421 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
3422 return false;
3423
3424 // If we have a situation where we don't care about conflict markers, ignore
3425 // it.
3426 if (!CurrentConflictMarkerState || isLexingRawMode())
3427 return false;
3428
3429 // Check to see if we have the marker (4 characters in a row).
3430 for (unsigned i = 1; i != 4; ++i)
3431 if (CurPtr[i] != CurPtr[0])
3432 return false;
3433
3434 // If we do have it, search for the end of the conflict marker. This could
3435 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
3436 // be the end of conflict marker.
3437 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
3438 CurrentConflictMarkerState)) {
3439 CurPtr = End;
3440
3441 // Skip ahead to the end of line.
3442 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
3443 ++CurPtr;
3444
3445 BufferPtr = CurPtr;
3446
3447 // No longer in the conflict marker.
3448 CurrentConflictMarkerState = CMK_None;
3449 return true;
3450 }
3451
3452 return false;
3453}
3454
3455static const char *findPlaceholderEnd(const char *CurPtr,
3456 const char *BufferEnd) {
3457 if (CurPtr == BufferEnd)
3458 return nullptr;
3459 BufferEnd -= 1; // Scan until the second last character.
3460 for (; CurPtr != BufferEnd; ++CurPtr) {
3461 if (CurPtr[0] == '#' && CurPtr[1] == '>')
3462 return CurPtr + 2;
3463 }
3464 return nullptr;
3465}
3466
3467bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
3468 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
3469 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
3470 return false;
3471 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
3472 if (!End)
3473 return false;
3474 const char *Start = CurPtr - 1;
3475 if (!LangOpts.AllowEditorPlaceholders)
3476 Diag(Start, diag::err_placeholder_in_source);
3477 Result.startToken();
3478 FormTokenWithChars(Result, End, tok::raw_identifier);
3479 Result.setRawIdentifierData(Start);
3480 PP->LookUpIdentifierInfo(Result);
3482 BufferPtr = End;
3483 return true;
3484}
3485
3486bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
3487 if (PP && PP->isCodeCompletionEnabled()) {
3488 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
3489 return Loc == PP->getCodeCompletionLoc();
3490 }
3491
3492 return false;
3493}
3494
3496 bool Named,
3497 const LangOptions &Opts,
3498 DiagnosticsEngine &Diags) {
3499 unsigned DiagId;
3500 if (Opts.CPlusPlus23)
3501 DiagId = diag::warn_cxx23_delimited_escape_sequence;
3502 else if (Opts.C2y && !Named)
3503 DiagId = diag::warn_c2y_delimited_escape_sequence;
3504 else
3505 DiagId = diag::ext_delimited_escape_sequence;
3506
3507 // The trailing arguments are only used by the extension warning; either this
3508 // is a C2y extension or a C++23 extension, unless it's a named escape
3509 // sequence in C, then it's a Clang extension.
3510 unsigned Ext;
3511 if (!Opts.CPlusPlus)
3512 Ext = Named ? 2 /* Clang extension */ : 1 /* C2y extension */;
3513 else
3514 Ext = 0; // C++23 extension
3515
3516 Diags.Report(Loc, DiagId) << Named << Ext;
3517}
3518
3519std::optional<uint32_t> Lexer::tryReadNumericUCN(const char *&StartPtr,
3520 const char *SlashLoc,
3521 Token *Result) {
3522 unsigned CharSize;
3523 char Kind = getCharAndSize(StartPtr, CharSize);
3524 assert((Kind == 'u' || Kind == 'U') && "expected a UCN");
3525
3526 unsigned NumHexDigits;
3527 if (Kind == 'u')
3528 NumHexDigits = 4;
3529 else if (Kind == 'U')
3530 NumHexDigits = 8;
3531
3532 bool Delimited = false;
3533 bool FoundEndDelimiter = false;
3534 unsigned Count = 0;
3535 bool Diagnose = Result && !isLexingRawMode();
3536
3537 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
3538 if (Diagnose)
3539 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
3540 return std::nullopt;
3541 }
3542
3543 const char *CurPtr = StartPtr + CharSize;
3544 const char *KindLoc = &CurPtr[-1];
3545
3546 uint32_t CodePoint = 0;
3547 while (Count != NumHexDigits || Delimited) {
3548 char C = getCharAndSize(CurPtr, CharSize);
3549 if (!Delimited && Count == 0 && C == '{') {
3550 Delimited = true;
3551 CurPtr += CharSize;
3552 continue;
3553 }
3554
3555 if (Delimited && C == '}') {
3556 CurPtr += CharSize;
3557 FoundEndDelimiter = true;
3558 break;
3559 }
3560
3561 unsigned Value = llvm::hexDigitValue(C);
3562 if (Value == std::numeric_limits<unsigned>::max()) {
3563 if (!Delimited)
3564 break;
3565 if (Diagnose)
3566 Diag(SlashLoc, diag::warn_delimited_ucn_incomplete)
3567 << StringRef(KindLoc, 1);
3568 return std::nullopt;
3569 }
3570
3571 if (CodePoint & 0xF000'0000) {
3572 if (Diagnose)
3573 Diag(KindLoc, diag::err_escape_too_large) << 0;
3574 return std::nullopt;
3575 }
3576
3577 CodePoint <<= 4;
3578 CodePoint |= Value;
3579 CurPtr += CharSize;
3580 Count++;
3581 }
3582
3583 if (Count == 0) {
3584 if (Diagnose)
3585 Diag(SlashLoc, FoundEndDelimiter ? diag::warn_delimited_ucn_empty
3586 : diag::warn_ucn_escape_no_digits)
3587 << StringRef(KindLoc, 1);
3588 return std::nullopt;
3589 }
3590
3591 if (Delimited && Kind == 'U') {
3592 if (Diagnose)
3593 Diag(SlashLoc, diag::err_hex_escape_no_digits) << StringRef(KindLoc, 1);
3594 return std::nullopt;
3595 }
3596
3597 if (!Delimited && Count != NumHexDigits) {
3598 if (Diagnose) {
3599 Diag(SlashLoc, diag::warn_ucn_escape_incomplete);
3600 // If the user wrote \U1234, suggest a fixit to \u.
3601 if (Count == 4 && NumHexDigits == 8) {
3602 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
3603 Diag(KindLoc, diag::note_ucn_four_not_eight)
3604 << FixItHint::CreateReplacement(URange, "u");
3605 }
3606 }
3607 return std::nullopt;
3608 }
3609
3610 if (Delimited && PP)
3612 PP->getLangOpts(),
3613 PP->getDiagnostics());
3614
3615 if (Result) {
3616 Result->setFlag(Token::HasUCN);
3617 // If the UCN contains either a trigraph or a line splicing,
3618 // we need to call getAndAdvanceChar again to set the appropriate flags
3619 // on Result.
3620 if (CurPtr - StartPtr == (ptrdiff_t)(Count + 1 + (Delimited ? 2 : 0)))
3621 StartPtr = CurPtr;
3622 else
3623 while (StartPtr != CurPtr)
3624 (void)getAndAdvanceChar(StartPtr, *Result);
3625 } else {
3626 StartPtr = CurPtr;
3627 }
3628 return CodePoint;
3629}
3630
3631std::optional<uint32_t> Lexer::tryReadNamedUCN(const char *&StartPtr,
3632 const char *SlashLoc,
3633 Token *Result) {
3634 unsigned CharSize;
3635 bool Diagnose = Result && !isLexingRawMode();
3636
3637 char C = getCharAndSize(StartPtr, CharSize);
3638 assert(C == 'N' && "expected \\N{...}");
3639
3640 const char *CurPtr = StartPtr + CharSize;
3641 const char *KindLoc = &CurPtr[-1];
3642
3643 C = getCharAndSize(CurPtr, CharSize);
3644 if (C != '{') {
3645 if (Diagnose)
3646 Diag(SlashLoc, diag::warn_ucn_escape_incomplete);
3647 return std::nullopt;
3648 }
3649 CurPtr += CharSize;
3650 const char *StartName = CurPtr;
3651 bool FoundEndDelimiter = false;
3652 llvm::SmallVector<char, 30> Buffer;
3653 while (C) {
3654 C = getCharAndSize(CurPtr, CharSize);
3655 CurPtr += CharSize;
3656 if (C == '}') {
3657 FoundEndDelimiter = true;
3658 break;
3659 }
3660
3662 break;
3663 Buffer.push_back(C);
3664 }
3665
3666 if (!FoundEndDelimiter || Buffer.empty()) {
3667 if (Diagnose)
3668 Diag(SlashLoc, FoundEndDelimiter ? diag::warn_delimited_ucn_empty
3669 : diag::warn_delimited_ucn_incomplete)
3670 << StringRef(KindLoc, 1);
3671 return std::nullopt;
3672 }
3673
3674 StringRef Name(Buffer.data(), Buffer.size());
3675 std::optional<char32_t> Match =
3676 llvm::sys::unicode::nameToCodepointStrict(Name);
3677 std::optional<llvm::sys::unicode::LooseMatchingResult> LooseMatch;
3678 if (!Match) {
3679 LooseMatch = llvm::sys::unicode::nameToCodepointLooseMatching(Name);
3680 if (Diagnose) {
3681 Diag(StartName, diag::err_invalid_ucn_name)
3682 << StringRef(Buffer.data(), Buffer.size())
3683 << makeCharRange(*this, StartName, CurPtr - CharSize);
3684 if (LooseMatch) {
3685 Diag(StartName, diag::note_invalid_ucn_name_loose_matching)
3687 makeCharRange(*this, StartName, CurPtr - CharSize),
3688 LooseMatch->Name);
3689 }
3690 }
3691 // We do not offer misspelled character names suggestions here
3692 // as the set of what would be a valid suggestion depends on context,
3693 // and we should not make invalid suggestions.
3694 }
3695
3696 if (Diagnose && Match)
3698 PP->getLangOpts(),
3699 PP->getDiagnostics());
3700
3701 // If no diagnostic has been emitted yet, likely because we are doing a
3702 // tentative lexing, we do not want to recover here to make sure the token
3703 // will not be incorrectly considered valid. This function will be called
3704 // again and a diagnostic emitted then.
3705 if (LooseMatch && Diagnose)
3706 Match = LooseMatch->CodePoint;
3707
3708 if (Result) {
3709 Result->setFlag(Token::HasUCN);
3710 // If the UCN contains either a trigraph or a line splicing,
3711 // we need to call getAndAdvanceChar again to set the appropriate flags
3712 // on Result.
3713 if (CurPtr - StartPtr == (ptrdiff_t)(Buffer.size() + 3))
3714 StartPtr = CurPtr;
3715 else
3716 while (StartPtr != CurPtr)
3717 (void)getAndAdvanceChar(StartPtr, *Result);
3718 } else {
3719 StartPtr = CurPtr;
3720 }
3721 return Match ? std::optional<uint32_t>(*Match) : std::nullopt;
3722}
3723
3724uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
3725 Token *Result) {
3726
3727 unsigned CharSize;
3728 std::optional<uint32_t> CodePointOpt;
3729 char Kind = getCharAndSize(StartPtr, CharSize);
3730 if (Kind == 'u' || Kind == 'U')
3731 CodePointOpt = tryReadNumericUCN(StartPtr, SlashLoc, Result);
3732 else if (Kind == 'N')
3733 CodePointOpt = tryReadNamedUCN(StartPtr, SlashLoc, Result);
3734
3735 if (!CodePointOpt)
3736 return 0;
3737
3738 uint32_t CodePoint = *CodePointOpt;
3739
3740 // Don't apply C family restrictions to UCNs in assembly mode
3741 if (LangOpts.AsmPreprocessor)
3742 return CodePoint;
3743
3744 // C23 6.4.3p2: A universal character name shall not designate a code point
3745 // where the hexadecimal value is:
3746 // - in the range D800 through DFFF inclusive; or
3747 // - greater than 10FFFF.
3748 // A universal-character-name outside the c-char-sequence of a character
3749 // constant, or the s-char-sequence of a string-literal shall not designate
3750 // a control character or a character in the basic character set.
3751
3752 // C++11 [lex.charset]p2: If the hexadecimal value for a
3753 // universal-character-name corresponds to a surrogate code point (in the
3754 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
3755 // if the hexadecimal value for a universal-character-name outside the
3756 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
3757 // string literal corresponds to a control character (in either of the
3758 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
3759 // basic source character set, the program is ill-formed.
3760 if (CodePoint < 0xA0) {
3761 // We don't use isLexingRawMode() here because we need to warn about bad
3762 // UCNs even when skipping preprocessing tokens in a #if block.
3763 if (Result && PP) {
3764 if (CodePoint < 0x20 || CodePoint >= 0x7F)
3765 Diag(BufferPtr, diag::err_ucn_control_character);
3766 else {
3767 char C = static_cast<char>(CodePoint);
3768 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
3769 }
3770 }
3771
3772 return 0;
3773 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
3774 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
3775 // We don't use isLexingRawMode() here because we need to diagnose bad
3776 // UCNs even when skipping preprocessing tokens in a #if block.
3777 if (Result && PP) {
3778 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
3779 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
3780 else
3781 Diag(BufferPtr, diag::err_ucn_escape_invalid);
3782 }
3783 return 0;
3784 }
3785
3786 return CodePoint;
3787}
3788
3789bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3790 const char *CurPtr) {
3791 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
3793 Diag(BufferPtr, diag::ext_unicode_whitespace)
3795 << makeCharRange(*this, BufferPtr, CurPtr);
3796
3797 Result.setFlag(Token::LeadingSpace);
3798 return true;
3799 }
3800 return false;
3801}
3802
3803void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3804 IsAtStartOfLine = Result.isAtStartOfLine();
3805 HasLeadingSpace = Result.hasLeadingSpace();
3806 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3807 // Note that this doesn't affect IsAtPhysicalStartOfLine.
3808}
3809
3811 assert(!isDependencyDirectivesLexer());
3812
3813 // Start a new token.
3814 Result.startToken();
3815
3816 // Set up misc whitespace flags for LexTokenInternal.
3817 if (IsAtStartOfLine) {
3818 Result.setFlag(Token::StartOfLine);
3819 IsAtStartOfLine = false;
3820 }
3821
3822 if (IsAtPhysicalStartOfLine) {
3824 IsAtPhysicalStartOfLine = false;
3825 }
3826
3827 if (HasLeadingSpace) {
3828 Result.setFlag(Token::LeadingSpace);
3829 HasLeadingSpace = false;
3830 }
3831
3832 if (HasLeadingEmptyMacro) {
3834 HasLeadingEmptyMacro = false;
3835 }
3836
3837 bool isRawLex = isLexingRawMode();
3838 (void) isRawLex;
3839 bool returnedToken = LexTokenInternal(Result);
3840 // (After the LexTokenInternal call, the lexer might be destroyed.)
3841 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3842 return returnedToken;
3843}
3844
3845/// LexTokenInternal - This implements a simple C family lexer. It is an
3846/// extremely performance critical piece of code. This assumes that the buffer
3847/// has a null character at the end of the file. This returns a preprocessing
3848/// token, not a normal token, as such, it is an internal interface. It assumes
3849/// that the Flags of result have been cleared before calling this.
3850bool Lexer::LexTokenInternal(Token &Result) {
3851LexStart:
3852 assert(!Result.needsCleaning() && "Result needs cleaning");
3853 assert(!Result.hasPtrData() && "Result has not been reset");
3854
3855 // CurPtr - Cache BufferPtr in an automatic variable.
3856 const char *CurPtr = BufferPtr;
3857
3858 // Small amounts of horizontal whitespace is very common between tokens.
3859 // Check for space character separately to skip the expensive
3860 // isHorizontalWhitespace() check
3861 if (*CurPtr == ' ' || isHorizontalWhitespace(*CurPtr)) {
3862 do {
3863 ++CurPtr;
3864 } while (*CurPtr == ' ' || isHorizontalWhitespace(*CurPtr));
3865
3866 // If we are keeping whitespace and other tokens, just return what we just
3867 // skipped. The next lexer invocation will return the token after the
3868 // whitespace.
3869 if (isKeepWhitespaceMode()) {
3870 FormTokenWithChars(Result, CurPtr, tok::unknown);
3871 // FIXME: The next token will not have LeadingSpace set.
3872 return true;
3873 }
3874
3875 BufferPtr = CurPtr;
3876 Result.setFlag(Token::LeadingSpace);
3877 }
3878
3879 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
3880
3881 // Read a character, advancing over it.
3882 char Char = getAndAdvanceChar(CurPtr, Result);
3884
3885 if (!isVerticalWhitespace(Char))
3886 NewLinePtr = nullptr;
3887
3888 switch (Char) {
3889 case 0: // Null.
3890 // Found end of file?
3891 if (CurPtr-1 == BufferEnd)
3892 return LexEndOfFile(Result, CurPtr-1);
3893
3894 // Check if we are performing code completion.
3895 if (isCodeCompletionPoint(CurPtr-1)) {
3896 // Return the code-completion token.
3897 Result.startToken();
3898 FormTokenWithChars(Result, CurPtr, tok::code_completion);
3899 return true;
3900 }
3901
3902 if (!isLexingRawMode())
3903 Diag(CurPtr-1, diag::null_in_file);
3904 Result.setFlag(Token::LeadingSpace);
3905 if (SkipWhitespace(Result, CurPtr))
3906 return true; // KeepWhitespaceMode
3907
3908 // We know the lexer hasn't changed, so just try again with this lexer.
3909 // (We manually eliminate the tail call to avoid recursion.)
3910 goto LexNextToken;
3911
3912 case 26: // DOS & CP/M EOF: "^Z".
3913 // If we're in Microsoft extensions mode, treat this as end of file.
3914 if (LangOpts.MicrosoftExt) {
3915 if (!isLexingRawMode())
3916 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3917 return LexEndOfFile(Result, CurPtr-1);
3918 }
3919
3920 // If Microsoft extensions are disabled, this is just random garbage.
3921 Kind = tok::unknown;
3922 break;
3923
3924 case '\r':
3925 if (CurPtr[0] == '\n')
3926 (void)getAndAdvanceChar(CurPtr, Result);
3927 [[fallthrough]];
3928 case '\n':
3929 // If we are inside a preprocessor directive and we see the end of line,
3930 // we know we are done with the directive, so return an EOD token.
3932 // Done parsing the "line".
3934
3935 // Restore comment saving mode, in case it was disabled for directive.
3936 if (PP)
3938
3939 // Since we consumed a newline, we are back at the start of a line.
3940 IsAtStartOfLine = true;
3941 IsAtPhysicalStartOfLine = true;
3942 NewLinePtr = CurPtr - 1;
3943
3944 Kind = tok::eod;
3945 break;
3946 }
3947
3948 // No leading whitespace seen so far.
3949 Result.clearFlag(Token::LeadingSpace);
3950
3951 if (SkipWhitespace(Result, CurPtr))
3952 return true; // KeepWhitespaceMode
3953
3954 // We only saw whitespace, so just try again with this lexer.
3955 // (We manually eliminate the tail call to avoid recursion.)
3956 goto LexNextToken;
3957 case ' ':
3958 case '\t':
3959 case '\f':
3960 case '\v':
3961 SkipHorizontalWhitespace:
3962 Result.setFlag(Token::LeadingSpace);
3963 if (SkipWhitespace(Result, CurPtr))
3964 return true; // KeepWhitespaceMode
3965
3966 SkipIgnoredUnits:
3967 CurPtr = BufferPtr;
3968
3969 // If the next token is obviously a // or /* */ comment, skip it efficiently
3970 // too (without going through the big switch stmt).
3971 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3972 LineComment && (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3973 if (SkipLineComment(Result, CurPtr + 2))
3974 return true; // There is a token to return.
3975 goto SkipIgnoredUnits;
3976 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3977 if (SkipBlockComment(Result, CurPtr + 2))
3978 return true; // There is a token to return.
3979 goto SkipIgnoredUnits;
3980 } else if (isHorizontalWhitespace(*CurPtr)) {
3981 goto SkipHorizontalWhitespace;
3982 }
3983 // We only saw whitespace, so just try again with this lexer.
3984 // (We manually eliminate the tail call to avoid recursion.)
3985 goto LexNextToken;
3986
3987 // C99 6.4.4.1: Integer Constants.
3988 // C99 6.4.4.2: Floating Constants.
3989 case '0': case '1': case '2': case '3': case '4':
3990 case '5': case '6': case '7': case '8': case '9':
3991 // Notify MIOpt that we read a non-whitespace/non-comment token.
3992 MIOpt.ReadToken();
3993 return LexNumericConstant(Result, CurPtr);
3994
3995 // Identifier (e.g., uber), or
3996 // UTF-8 (C23/C++17) or UTF-16 (C11/C++11) character literal, or
3997 // UTF-8 or UTF-16 string literal (C11/C++11).
3998 case 'u':
3999 // Notify MIOpt that we read a non-whitespace/non-comment token.
4000 MIOpt.ReadToken();
4001
4002 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
4003 Char = getCharAndSize(CurPtr, SizeTmp);
4004
4005 // UTF-16 string literal
4006 if (Char == '"')
4007 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4008 tok::utf16_string_literal);
4009
4010 // UTF-16 character constant
4011 if (Char == '\'')
4012 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4013 tok::utf16_char_constant);
4014
4015 // UTF-16 raw string literal
4016 if (Char == 'R' && LangOpts.RawStringLiterals &&
4017 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
4018 return LexRawStringLiteral(Result,
4019 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4020 SizeTmp2, Result),
4021 tok::utf16_string_literal);
4022
4023 if (Char == '8') {
4024 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
4025
4026 // UTF-8 string literal
4027 if (Char2 == '"')
4028 return LexStringLiteral(Result,
4029 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4030 SizeTmp2, Result),
4031 tok::utf8_string_literal);
4032 if (Char2 == '\'' && (LangOpts.CPlusPlus17 || LangOpts.C23))
4033 return LexCharConstant(
4034 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4035 SizeTmp2, Result),
4036 tok::utf8_char_constant);
4037
4038 if (Char2 == 'R' && LangOpts.RawStringLiterals) {
4039 unsigned SizeTmp3;
4040 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
4041 // UTF-8 raw string literal
4042 if (Char3 == '"') {
4043 return LexRawStringLiteral(Result,
4044 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4045 SizeTmp2, Result),
4046 SizeTmp3, Result),
4047 tok::utf8_string_literal);
4048 }
4049 }
4050 }
4051 }
4052
4053 // treat u like the start of an identifier.
4054 return LexIdentifierContinue(Result, CurPtr);
4055
4056 case 'U': // Identifier (e.g. Uber) or C11/C++11 UTF-32 string literal
4057 // Notify MIOpt that we read a non-whitespace/non-comment token.
4058 MIOpt.ReadToken();
4059
4060 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
4061 Char = getCharAndSize(CurPtr, SizeTmp);
4062
4063 // UTF-32 string literal
4064 if (Char == '"')
4065 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4066 tok::utf32_string_literal);
4067
4068 // UTF-32 character constant
4069 if (Char == '\'')
4070 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4071 tok::utf32_char_constant);
4072
4073 // UTF-32 raw string literal
4074 if (Char == 'R' && LangOpts.RawStringLiterals &&
4075 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
4076 return LexRawStringLiteral(Result,
4077 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4078 SizeTmp2, Result),
4079 tok::utf32_string_literal);
4080 }
4081
4082 // treat U like the start of an identifier.
4083 return LexIdentifierContinue(Result, CurPtr);
4084
4085 case 'R': // Identifier or C++0x raw string literal
4086 // Notify MIOpt that we read a non-whitespace/non-comment token.
4087 MIOpt.ReadToken();
4088
4089 if (LangOpts.RawStringLiterals) {
4090 Char = getCharAndSize(CurPtr, SizeTmp);
4091
4092 if (Char == '"')
4093 return LexRawStringLiteral(Result,
4094 ConsumeChar(CurPtr, SizeTmp, Result),
4095 tok::string_literal);
4096 }
4097
4098 // treat R like the start of an identifier.
4099 return LexIdentifierContinue(Result, CurPtr);
4100
4101 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
4102 // Notify MIOpt that we read a non-whitespace/non-comment token.
4103 MIOpt.ReadToken();
4104 Char = getCharAndSize(CurPtr, SizeTmp);
4105
4106 // Wide string literal.
4107 if (Char == '"')
4108 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4109 tok::wide_string_literal);
4110
4111 // Wide raw string literal.
4112 if (LangOpts.RawStringLiterals && Char == 'R' &&
4113 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
4114 return LexRawStringLiteral(Result,
4115 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4116 SizeTmp2, Result),
4117 tok::wide_string_literal);
4118
4119 // Wide character constant.
4120 if (Char == '\'')
4121 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
4122 tok::wide_char_constant);
4123 // FALL THROUGH, treating L like the start of an identifier.
4124 [[fallthrough]];
4125
4126 // C99 6.4.2: Identifiers.
4127 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
4128 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
4129 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
4130 case 'V': case 'W': case 'X': case 'Y': case 'Z':
4131 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
4132 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
4133 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
4134 case 'v': case 'w': case 'x': case 'y': case 'z':
4135 case '_':
4136 // Notify MIOpt that we read a non-whitespace/non-comment token.
4137 MIOpt.ReadToken();
4138 return LexIdentifierContinue(Result, CurPtr);
4139 case '$': // $ in identifiers.
4140 if (LangOpts.DollarIdents) {
4141 if (!isLexingRawMode())
4142 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
4143 // Notify MIOpt that we read a non-whitespace/non-comment token.
4144 MIOpt.ReadToken();
4145 return LexIdentifierContinue(Result, CurPtr);
4146 }
4147
4148 Kind = tok::unknown;
4149 break;
4150
4151 // C99 6.4.4: Character Constants.
4152 case '\'':
4153 // Notify MIOpt that we read a non-whitespace/non-comment token.
4154 MIOpt.ReadToken();
4155 return LexCharConstant(Result, CurPtr, tok::char_constant);
4156
4157 // C99 6.4.5: String Literals.
4158 case '"':
4159 // Notify MIOpt that we read a non-whitespace/non-comment token.
4160 MIOpt.ReadToken();
4161 return LexStringLiteral(Result, CurPtr,
4162 ParsingFilename ? tok::header_name
4163 : tok::string_literal);
4164
4165 // C99 6.4.6: Punctuators.
4166 case '?':
4167 Kind = tok::question;
4168 break;
4169 case '[':
4170 Kind = tok::l_square;
4171 break;
4172 case ']':
4173 Kind = tok::r_square;
4174 break;
4175 case '(':
4176 Kind = tok::l_paren;
4177 break;
4178 case ')':
4179 Kind = tok::r_paren;
4180 break;
4181 case '{':
4182 Kind = tok::l_brace;
4183 break;
4184 case '}':
4185 Kind = tok::r_brace;
4186 break;
4187 case '.':
4188 Char = getCharAndSize(CurPtr, SizeTmp);
4189 if (Char >= '0' && Char <= '9') {
4190 // Notify MIOpt that we read a non-whitespace/non-comment token.
4191 MIOpt.ReadToken();
4192
4193 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
4194 } else if (LangOpts.CPlusPlus && Char == '*') {
4195 Kind = tok::periodstar;
4196 CurPtr += SizeTmp;
4197 } else if (Char == '.' &&
4198 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
4199 Kind = tok::ellipsis;
4200 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4201 SizeTmp2, Result);
4202 } else {
4203 Kind = tok::period;
4204 }
4205 break;
4206 case '&':
4207 Char = getCharAndSize(CurPtr, SizeTmp);
4208 if (Char == '&') {
4209 Kind = tok::ampamp;
4210 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4211 } else if (Char == '=') {
4212 Kind = tok::ampequal;
4213 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4214 } else {
4215 Kind = tok::amp;
4216 }
4217 break;
4218 case '*':
4219 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
4220 Kind = tok::starequal;
4221 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4222 } else {
4223 Kind = tok::star;
4224 }
4225 break;
4226 case '+':
4227 Char = getCharAndSize(CurPtr, SizeTmp);
4228 if (Char == '+') {
4229 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4230 Kind = tok::plusplus;
4231 } else if (Char == '=') {
4232 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4233 Kind = tok::plusequal;
4234 } else {
4235 Kind = tok::plus;
4236 }
4237 break;
4238 case '-':
4239 Char = getCharAndSize(CurPtr, SizeTmp);
4240 if (Char == '-') { // --
4241 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4242 Kind = tok::minusminus;
4243 } else if (Char == '>' && LangOpts.CPlusPlus &&
4244 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
4245 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4246 SizeTmp2, Result);
4247 Kind = tok::arrowstar;
4248 } else if (Char == '>') { // ->
4249 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4250 Kind = tok::arrow;
4251 } else if (Char == '=') { // -=
4252 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4253 Kind = tok::minusequal;
4254 } else {
4255 Kind = tok::minus;
4256 }
4257 break;
4258 case '~':
4259 Kind = tok::tilde;
4260 break;
4261 case '!':
4262 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
4263 Kind = tok::exclaimequal;
4264 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4265 } else {
4266 Kind = tok::exclaim;
4267 }
4268 break;
4269 case '/':
4270 // 6.4.9: Comments
4271 Char = getCharAndSize(CurPtr, SizeTmp);
4272 if (Char == '/') { // Line comment.
4273 // Even if Line comments are disabled (e.g. in C89 mode), we generally
4274 // want to lex this as a comment. There is one problem with this though,
4275 // that in one particular corner case, this can change the behavior of the
4276 // resultant program. For example, In "foo //**/ bar", C89 would lex
4277 // this as "foo / bar" and languages with Line comments would lex it as
4278 // "foo". Check to see if the character after the second slash is a '*'.
4279 // If so, we will lex that as a "/" instead of the start of a comment.
4280 // However, we never do this if we are just preprocessing.
4281 bool TreatAsComment =
4282 LineComment && (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
4283 if (!TreatAsComment)
4284 if (!(PP && PP->isPreprocessedOutput()))
4285 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
4286
4287 if (TreatAsComment) {
4288 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
4289 return true; // There is a token to return.
4290
4291 // It is common for the tokens immediately after a // comment to be
4292 // whitespace (indentation for the next line). Instead of going through
4293 // the big switch, handle it efficiently now.
4294 goto SkipIgnoredUnits;
4295 }
4296 }
4297
4298 if (Char == '*') { // /**/ comment.
4299 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
4300 return true; // There is a token to return.
4301
4302 // We only saw whitespace, so just try again with this lexer.
4303 // (We manually eliminate the tail call to avoid recursion.)
4304 goto LexNextToken;
4305 }
4306
4307 if (Char == '=') {
4308 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4309 Kind = tok::slashequal;
4310 } else {
4311 Kind = tok::slash;
4312 }
4313 break;
4314 case '%':
4315 Char = getCharAndSize(CurPtr, SizeTmp);
4316 if (Char == '=') {
4317 Kind = tok::percentequal;
4318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4319 } else if (LangOpts.Digraphs && Char == '>') {
4320 Kind = tok::r_brace; // '%>' -> '}'
4321 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4322 } else if (LangOpts.Digraphs && Char == ':') {
4323 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4324 Char = getCharAndSize(CurPtr, SizeTmp);
4325 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
4326 Kind = tok::hashhash; // '%:%:' -> '##'
4327 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4328 SizeTmp2, Result);
4329 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
4330 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4331 if (!isLexingRawMode())
4332 Diag(BufferPtr, diag::ext_charize_microsoft);
4333 Kind = tok::hashat;
4334 } else { // '%:' -> '#'
4335 // We parsed a # character. If this occurs at the start of the line,
4336 // it's actually the start of a preprocessing directive. Callback to
4337 // the preprocessor to handle it.
4338 // TODO: -fpreprocessed mode??
4339 if (Result.isAtPhysicalStartOfLine() && !LexingRawMode &&
4340 !Is_PragmaLexer)
4341 goto HandleDirective;
4342
4343 Kind = tok::hash;
4344 }
4345 } else {
4346 Kind = tok::percent;
4347 }
4348 break;
4349 case '<':
4350 Char = getCharAndSize(CurPtr, SizeTmp);
4351 if (ParsingFilename) {
4352 return LexAngledStringLiteral(Result, CurPtr);
4353 } else if (Char == '<') {
4354 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4355 if (After == '=') {
4356 Kind = tok::lesslessequal;
4357 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4358 SizeTmp2, Result);
4359 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
4360 // If this is actually a '<<<<<<<' version control conflict marker,
4361 // recognize it as such and recover nicely.
4362 goto LexNextToken;
4363 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
4364 // If this is '<<<<' and we're in a Perforce-style conflict marker,
4365 // ignore it.
4366 goto LexNextToken;
4367 } else if (LangOpts.CUDA && After == '<') {
4368 Kind = tok::lesslessless;
4369 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4370 SizeTmp2, Result);
4371 } else {
4372 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4373 Kind = tok::lessless;
4374 }
4375 } else if (Char == '=') {
4376 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4377 if (After == '>') {
4378 if (LangOpts.CPlusPlus20) {
4379 if (!isLexingRawMode())
4380 Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
4381 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4382 SizeTmp2, Result);
4383 Kind = tok::spaceship;
4384 break;
4385 }
4386 // Suggest adding a space between the '<=' and the '>' to avoid a
4387 // change in semantics if this turns up in C++ <=17 mode.
4388 if (LangOpts.CPlusPlus && !isLexingRawMode()) {
4389 Diag(BufferPtr, diag::warn_cxx20_compat_spaceship)
4391 getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
4392 }
4393 }
4394 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4395 Kind = tok::lessequal;
4396 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
4397 if (LangOpts.CPlusPlus11 &&
4398 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
4399 // C++0x [lex.pptoken]p3:
4400 // Otherwise, if the next three characters are <:: and the subsequent
4401 // character is neither : nor >, the < is treated as a preprocessor
4402 // token by itself and not as the first character of the alternative
4403 // token <:.
4404 unsigned SizeTmp3;
4405 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
4406 if (After != ':' && After != '>') {
4407 Kind = tok::less;
4408 if (!isLexingRawMode())
4409 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
4410 break;
4411 }
4412 }
4413
4414 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4415 Kind = tok::l_square;
4416 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
4417 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4418 Kind = tok::l_brace;
4419 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
4420 lexEditorPlaceholder(Result, CurPtr)) {
4421 return true;
4422 } else {
4423 Kind = tok::less;
4424 }
4425 break;
4426 case '>':
4427 Char = getCharAndSize(CurPtr, SizeTmp);
4428 if (Char == '=') {
4429 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4430 Kind = tok::greaterequal;
4431 } else if (Char == '>') {
4432 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
4433 if (After == '=') {
4434 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4435 SizeTmp2, Result);
4436 Kind = tok::greatergreaterequal;
4437 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
4438 // If this is actually a '>>>>' conflict marker, recognize it as such
4439 // and recover nicely.
4440 goto LexNextToken;
4441 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
4442 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
4443 goto LexNextToken;
4444 } else if (LangOpts.CUDA && After == '>') {
4445 Kind = tok::greatergreatergreater;
4446 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
4447 SizeTmp2, Result);
4448 } else {
4449 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4450 Kind = tok::greatergreater;
4451 }
4452 } else {
4453 Kind = tok::greater;
4454 }
4455 break;
4456 case '^':
4457 Char = getCharAndSize(CurPtr, SizeTmp);
4458 if (Char == '=') {
4459 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4460 Kind = tok::caretequal;
4461 } else if (LangOpts.Reflection && Char == '^') {
4462 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4463 Kind = tok::caretcaret;
4464 } else {
4465 if (LangOpts.OpenCL && Char == '^')
4466 Diag(CurPtr, diag::err_opencl_logical_exclusive_or);
4467 Kind = tok::caret;
4468 }
4469 break;
4470 case '|':
4471 Char = getCharAndSize(CurPtr, SizeTmp);
4472 if (Char == '=') {
4473 Kind = tok::pipeequal;
4474 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4475 } else if (Char == '|') {
4476 // If this is '|||||||' and we're in a conflict marker, ignore it.
4477 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
4478 goto LexNextToken;
4479 Kind = tok::pipepipe;
4480 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4481 } else {
4482 Kind = tok::pipe;
4483 }
4484 break;
4485 case ':':
4486 Char = getCharAndSize(CurPtr, SizeTmp);
4487 if (LangOpts.Digraphs && Char == '>') {
4488 Kind = tok::r_square; // ':>' -> ']'
4489 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4490 } else if (Char == ':') {
4491 Kind = tok::coloncolon;
4492 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4493 } else {
4494 Kind = tok::colon;
4495 }
4496 break;
4497 case ';':
4498 Kind = tok::semi;
4499 break;
4500 case '=':
4501 Char = getCharAndSize(CurPtr, SizeTmp);
4502 if (Char == '=') {
4503 // If this is '====' and we're in a conflict marker, ignore it.
4504 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
4505 goto LexNextToken;
4506
4507 Kind = tok::equalequal;
4508 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4509 } else {
4510 Kind = tok::equal;
4511 }
4512 break;
4513 case ',':
4514 Kind = tok::comma;
4515 break;
4516 case '#':
4517 Char = getCharAndSize(CurPtr, SizeTmp);
4518 if (Char == '#') {
4519 Kind = tok::hashhash;
4520 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4521 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
4522 Kind = tok::hashat;
4523 if (!isLexingRawMode())
4524 Diag(BufferPtr, diag::ext_charize_microsoft);
4525 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
4526 } else {
4527 // We parsed a # character. If this occurs at the start of the line,
4528 // it's actually the start of a preprocessing directive. Callback to
4529 // the preprocessor to handle it.
4530 // TODO: -fpreprocessed mode??
4531 if (Result.isAtPhysicalStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
4532 goto HandleDirective;
4533
4534 Kind = tok::hash;
4535 }
4536 break;
4537
4538 case '@':
4539 // Objective C support.
4540 if (CurPtr[-1] == '@' && LangOpts.ObjC) {
4541 FormTokenWithChars(Result, CurPtr, tok::at);
4542 if (PP && Result.isAtPhysicalStartOfLine() && !LexingRawMode &&
4543 !Is_PragmaLexer) {
4544 Token NextPPTok;
4545 NextPPTok.startToken();
4546 {
4547 llvm::SaveAndRestore<bool> SavedParsingPreprocessorDirective(
4548 this->ParsingPreprocessorDirective, true);
4549 auto NextTokOr = peekNextPPToken();
4550 if (NextTokOr.has_value()) {
4551 NextPPTok = *NextTokOr;
4552 }
4553 }
4554 if (NextPPTok.is(tok::raw_identifier) &&
4555 NextPPTok.getRawIdentifier() == "import") {
4556 PP->HandleDirective(Result);
4557 return false;
4558 }
4559 }
4560 return true;
4561 } else
4562 Kind = tok::unknown;
4563 break;
4564
4565 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
4566 case '\\':
4567 if (!LangOpts.AsmPreprocessor) {
4568 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
4569 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
4570 if (SkipWhitespace(Result, CurPtr))
4571 return true; // KeepWhitespaceMode
4572
4573 // We only saw whitespace, so just try again with this lexer.
4574 // (We manually eliminate the tail call to avoid recursion.)
4575 goto LexNextToken;
4576 }
4577
4578 return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
4579 }
4580 }
4581
4582 Kind = tok::unknown;
4583 break;
4584
4585 default: {
4586 if (isASCII(Char)) {
4587 Kind = tok::unknown;
4588 break;
4589 }
4590
4591 llvm::UTF32 CodePoint;
4592
4593 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
4594 // an escaped newline.
4595 --CurPtr;
4596 llvm::ConversionResult Status =
4597 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
4598 (const llvm::UTF8 *)BufferEnd,
4599 &CodePoint,
4600 llvm::strictConversion);
4601 if (Status == llvm::conversionOK) {
4602 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
4603 if (SkipWhitespace(Result, CurPtr))
4604 return true; // KeepWhitespaceMode
4605
4606 // We only saw whitespace, so just try again with this lexer.
4607 // (We manually eliminate the tail call to avoid recursion.)
4608 goto LexNextToken;
4609 }
4610 return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
4611 }
4612
4614 PP->isPreprocessedOutput()) {
4615 ++CurPtr;
4616 Kind = tok::unknown;
4617 break;
4618 }
4619
4620 // Non-ASCII characters tend to creep into source code unintentionally.
4621 // Instead of letting the parser complain about the unknown token,
4622 // just diagnose the invalid UTF-8, then drop the character.
4623 Diag(CurPtr, diag::err_invalid_utf8);
4624
4625 BufferPtr = CurPtr+1;
4626 // We're pretending the character didn't exist, so just try again with
4627 // this lexer.
4628 // (We manually eliminate the tail call to avoid recursion.)
4629 goto LexNextToken;
4630 }
4631 }
4632
4633 // Notify MIOpt that we read a non-whitespace/non-comment token.
4634 MIOpt.ReadToken();
4635
4636 // Update the location of token as well as BufferPtr.
4637 FormTokenWithChars(Result, CurPtr, Kind);
4638 return true;
4639
4640HandleDirective:
4641
4642 // We parsed a # character and it's the start of a preprocessing directive.
4643 FormTokenWithChars(Result, CurPtr, tok::hash);
4644 PP->HandleDirective(Result);
4645
4646 if (PP->hadModuleLoaderFatalFailure())
4647 // With a fatal failure in the module loader, we abort parsing.
4648 return true;
4649
4650 // We parsed the directive; lex a token with the new state.
4651 return false;
4652
4653LexNextToken:
4654 Result.clearFlag(Token::NeedsCleaning);
4655 goto LexStart;
4656}
4657
4658const char *Lexer::convertDependencyDirectiveToken(
4660 const char *TokPtr = BufferStart + DDTok.Offset;
4661 Result.startToken();
4662 Result.setLocation(getSourceLocation(TokPtr));
4663 Result.setKind(DDTok.Kind);
4664 Result.setFlag((Token::TokenFlags)DDTok.Flags);
4665 Result.setLength(DDTok.Length);
4666 if (Result.is(tok::raw_identifier))
4667 Result.setRawIdentifierData(TokPtr);
4668 else if (Result.isLiteral())
4669 Result.setLiteralData(TokPtr);
4670 BufferPtr = TokPtr + DDTok.Length;
4671 return TokPtr;
4672}
4673
4674bool Lexer::LexDependencyDirectiveToken(Token &Result) {
4675 assert(isDependencyDirectivesLexer());
4676
4677 using namespace dependency_directives_scan;
4678
4679 if (BufferPtr == BufferEnd)
4680 return LexEndOfFile(Result, BufferPtr);
4681
4682 while (NextDepDirectiveTokenIndex == DepDirectives.front().Tokens.size()) {
4683 if (DepDirectives.front().Kind == pp_eof)
4684 return LexEndOfFile(Result, BufferEnd);
4685 if (DepDirectives.front().Kind == tokens_present_before_eof)
4686 MIOpt.ReadToken();
4687 NextDepDirectiveTokenIndex = 0;
4688 DepDirectives = DepDirectives.drop_front();
4689 }
4690
4691 const dependency_directives_scan::Token &DDTok =
4692 DepDirectives.front().Tokens[NextDepDirectiveTokenIndex++];
4693 if (NextDepDirectiveTokenIndex > 1 || DDTok.Kind != tok::hash) {
4694 // Read something other than a preprocessor directive hash.
4695 MIOpt.ReadToken();
4696 }
4697
4698 if (ParsingFilename && DDTok.is(tok::less)) {
4699 BufferPtr = BufferStart + DDTok.Offset;
4700 LexAngledStringLiteral(Result, BufferPtr + 1);
4701 if (Result.isNot(tok::header_name))
4702 return true;
4703 // Advance the index of lexed tokens.
4704 while (true) {
4705 const dependency_directives_scan::Token &NextTok =
4706 DepDirectives.front().Tokens[NextDepDirectiveTokenIndex];
4707 if (BufferStart + NextTok.Offset >= BufferPtr)
4708 break;
4709 ++NextDepDirectiveTokenIndex;
4710 }
4711 return true;
4712 }
4713
4714 const char *TokPtr = convertDependencyDirectiveToken(DDTok, Result);
4715
4716 if (Result.is(tok::hash) && Result.isAtStartOfLine()) {
4717 PP->HandleDirective(Result);
4718 if (PP->hadModuleLoaderFatalFailure())
4719 // With a fatal failure in the module loader, we abort parsing.
4720 return true;
4721 return false;
4722 }
4723 if (Result.is(tok::at) && Result.isAtStartOfLine()) {
4724 auto NextTok = peekNextPPToken();
4725 if (NextTok && NextTok->is(tok::raw_identifier) &&
4726 NextTok->getRawIdentifier() == "import") {
4727 PP->HandleDirective(Result);
4728 if (PP->hadModuleLoaderFatalFailure())
4729 return true;
4730 return false;
4731 }
4732 }
4733 if (Result.is(tok::raw_identifier)) {
4734 Result.setRawIdentifierData(TokPtr);
4735 if (!isLexingRawMode()) {
4736 const IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
4737 if (LangOpts.CPlusPlusModules && Result.isModuleContextualKeyword() &&
4738 PP->HandleModuleContextualKeyword(Result)) {
4739 PP->HandleDirective(Result);
4740 return false;
4741 }
4742 if (II->isHandleIdentifierCase())
4743 return PP->HandleIdentifier(Result);
4744 }
4745 return true;
4746 }
4747 if (Result.isLiteral())
4748 return true;
4749 if (Result.is(tok::colon)) {
4750 // Convert consecutive colons to 'tok::coloncolon'.
4751 if (*BufferPtr == ':') {
4752 assert(DepDirectives.front().Tokens[NextDepDirectiveTokenIndex].is(
4753 tok::colon));
4754 ++NextDepDirectiveTokenIndex;
4755 Result.setKind(tok::coloncolon);
4756 }
4757 return true;
4758 }
4759 if (Result.is(tok::eod))
4761
4762 return true;
4763}
4764
4765bool Lexer::LexDependencyDirectiveTokenWhileSkipping(Token &Result) {
4766 assert(isDependencyDirectivesLexer());
4767
4768 using namespace dependency_directives_scan;
4769
4770 bool Stop = false;
4771 unsigned NestedIfs = 0;
4772 do {
4773 DepDirectives = DepDirectives.drop_front();
4774 switch (DepDirectives.front().Kind) {
4775 case pp_none:
4776 llvm_unreachable("unexpected 'pp_none'");
4777 case pp_include:
4779 case pp_define:
4780 case pp_undef:
4781 case pp_import:
4782 case pp_pragma_import:
4783 case pp_pragma_once:
4788 case pp_include_next:
4789 case decl_at_import:
4790 case cxx_module_decl:
4791 case cxx_import_decl:
4795 break;
4796 case pp_if:
4797 case pp_ifdef:
4798 case pp_ifndef:
4799 ++NestedIfs;
4800 break;
4801 case pp_elif:
4802 case pp_elifdef:
4803 case pp_elifndef:
4804 case pp_else:
4805 if (!NestedIfs) {
4806 Stop = true;
4807 }
4808 break;
4809 case pp_endif:
4810 if (!NestedIfs) {
4811 Stop = true;
4812 } else {
4813 --NestedIfs;
4814 }
4815 break;
4816 case pp_eof:
4817 NextDepDirectiveTokenIndex = 0;
4818 return LexEndOfFile(Result, BufferEnd);
4819 }
4820 } while (!Stop);
4821
4822 const dependency_directives_scan::Token &DDTok =
4823 DepDirectives.front().Tokens.front();
4824 assert(DDTok.is(tok::hash));
4825 NextDepDirectiveTokenIndex = 1;
4826
4827 convertDependencyDirectiveToken(DDTok, Result);
4828 return false;
4829}
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:3351
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:3455
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.
#define SM(sm)
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:961
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:3190
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:3810
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:3495
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.
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
The JSON file list parser is used to communicate input to InstallAPI.
LLVM_READNONE bool isASCII(char c)
Returns true if a byte is an ASCII character.
Definition CharInfo.h:41
@ Match
This is not an overload because the signature exactly matches an existing declaration.
Definition Sema.h:829
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:561
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.