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