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