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