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