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