Bug Summary

File:clang/lib/Lex/Lexer.cpp
Warning:line 1149, column 10
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name Lexer.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -fhalf-no-semantic-interposition -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -mconstructor-aliases -munwind-tables -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Lex -resource-dir /usr/lib/llvm-13/lib/clang/13.0.0 -D CLANG_ROUND_TRIP_CC1_ARGS=ON -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Lex -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Lex -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/include -I /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/llvm/include -D NDEBUG -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/x86_64-linux-gnu/c++/10 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../include/c++/10/backward -internal-isystem /usr/lib/llvm-13/lib/clang/13.0.0/include -internal-isystem /usr/local/include -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/10/../../../../x86_64-linux-gnu/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-class-memaccess -Wno-redundant-move -Wno-pessimizing-move -Wno-noexcept-type -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/build-llvm/tools/clang/lib/Lex -fdebug-prefix-map=/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d=. -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -D__GCC_HAVE_DWARF2_CFI_ASM=1 -o /tmp/scan-build-2021-05-07-005843-9350-1 -x c++ /build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Lex/Lexer.cpp

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/lib/Lex/Lexer.cpp

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

/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Lex/Lexer.h

1//===- Lexer.h - C Language Family Lexer ------------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the Lexer interface.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_LEX_LEXER_H
14#define LLVM_CLANG_LEX_LEXER_H
15
16#include "clang/Basic/LangOptions.h"
17#include "clang/Basic/SourceLocation.h"
18#include "clang/Basic/TokenKinds.h"
19#include "clang/Lex/PreprocessorLexer.h"
20#include "clang/Lex/Token.h"
21#include "llvm/ADT/Optional.h"
22#include "llvm/ADT/SmallVector.h"
23#include "llvm/ADT/StringRef.h"
24#include <cassert>
25#include <cstdint>
26#include <string>
27
28namespace llvm {
29
30class MemoryBufferRef;
31
32} // namespace llvm
33
34namespace clang {
35
36class DiagnosticBuilder;
37class Preprocessor;
38class SourceManager;
39
40/// ConflictMarkerKind - Kinds of conflict marker which the lexer might be
41/// recovering from.
42enum ConflictMarkerKind {
43 /// Not within a conflict marker.
44 CMK_None,
45
46 /// A normal or diff3 conflict marker, initiated by at least 7 "<"s,
47 /// separated by at least 7 "="s or "|"s, and terminated by at least 7 ">"s.
48 CMK_Normal,
49
50 /// A Perforce-style conflict marker, initiated by 4 ">"s,
51 /// separated by 4 "="s, and terminated by 4 "<"s.
52 CMK_Perforce
53};
54
55/// Describes the bounds (start, size) of the preamble and a flag required by
56/// PreprocessorOptions::PrecompiledPreambleBytes.
57/// The preamble includes the BOM, if any.
58struct PreambleBounds {
59 /// Size of the preamble in bytes.
60 unsigned Size;
61
62 /// Whether the preamble ends at the start of a new line.
63 ///
64 /// Used to inform the lexer as to whether it's starting at the beginning of
65 /// a line after skipping the preamble.
66 bool PreambleEndsAtStartOfLine;
67
68 PreambleBounds(unsigned Size, bool PreambleEndsAtStartOfLine)
69 : Size(Size), PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
70};
71
72/// Lexer - This provides a simple interface that turns a text buffer into a
73/// stream of tokens. This provides no support for file reading or buffering,
74/// or buffering/seeking of tokens, only forward lexing is supported. It relies
75/// on the specified Preprocessor object to handle preprocessor directives, etc.
76class Lexer : public PreprocessorLexer {
77 friend class Preprocessor;
78
79 void anchor() override;
80
81 //===--------------------------------------------------------------------===//
82 // Constant configuration values for this lexer.
83
84 // Start of the buffer.
85 const char *BufferStart;
86
87 // End of the buffer.
88 const char *BufferEnd;
89
90 // Location for start of file.
91 SourceLocation FileLoc;
92
93 // LangOpts enabled by this language (cache).
94 LangOptions LangOpts;
95
96 // True if lexer for _Pragma handling.
97 bool Is_PragmaLexer;
98
99 //===--------------------------------------------------------------------===//
100 // Context-specific lexing flags set by the preprocessor.
101 //
102
103 /// ExtendedTokenMode - The lexer can optionally keep comments and whitespace
104 /// and return them as tokens. This is used for -C and -CC modes, and
105 /// whitespace preservation can be useful for some clients that want to lex
106 /// the file in raw mode and get every character from the file.
107 ///
108 /// When this is set to 2 it returns comments and whitespace. When set to 1
109 /// it returns comments, when it is set to 0 it returns normal tokens only.
110 unsigned char ExtendedTokenMode;
111
112 //===--------------------------------------------------------------------===//
113 // Context that changes as the file is lexed.
114 // NOTE: any state that mutates when in raw mode must have save/restore code
115 // in Lexer::isNextPPTokenLParen.
116
117 // BufferPtr - Current pointer into the buffer. This is the next character
118 // to be lexed.
119 const char *BufferPtr;
120
121 // IsAtStartOfLine - True if the next lexed token should get the "start of
122 // line" flag set on it.
123 bool IsAtStartOfLine;
124
125 bool IsAtPhysicalStartOfLine;
126
127 bool HasLeadingSpace;
128
129 bool HasLeadingEmptyMacro;
130
131 // NewLinePtr - A pointer to new line character '\n' being lexed. For '\r\n',
132 // it also points to '\n.'
133 const char *NewLinePtr;
134
135 // CurrentConflictMarkerState - The kind of conflict marker we are handling.
136 ConflictMarkerKind CurrentConflictMarkerState;
137
138 void InitLexer(const char *BufStart, const char *BufPtr, const char *BufEnd);
139
140public:
141 /// Lexer constructor - Create a new lexer object for the specified buffer
142 /// with the specified preprocessor managing the lexing process. This lexer
143 /// assumes that the associated file buffer and Preprocessor objects will
144 /// outlive it, so it doesn't take ownership of either of them.
145 Lexer(FileID FID, const llvm::MemoryBufferRef &InputFile, Preprocessor &PP);
146
147 /// Lexer constructor - Create a new raw lexer object. This object is only
148 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the
149 /// text range will outlive it, so it doesn't take ownership of it.
150 Lexer(SourceLocation FileLoc, const LangOptions &LangOpts,
151 const char *BufStart, const char *BufPtr, const char *BufEnd);
152
153 /// Lexer constructor - Create a new raw lexer object. This object is only
154 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the
155 /// text range will outlive it, so it doesn't take ownership of it.
156 Lexer(FileID FID, const llvm::MemoryBufferRef &FromFile,
157 const SourceManager &SM, const LangOptions &LangOpts);
158
159 Lexer(const Lexer &) = delete;
160 Lexer &operator=(const Lexer &) = delete;
161
162 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
163 /// _Pragma expansion. This has a variety of magic semantics that this method
164 /// sets up. It returns a new'd Lexer that must be delete'd when done.
165 static Lexer *Create_PragmaLexer(SourceLocation SpellingLoc,
166 SourceLocation ExpansionLocStart,
167 SourceLocation ExpansionLocEnd,
168 unsigned TokLen, Preprocessor &PP);
169
170 /// getLangOpts - Return the language features currently enabled.
171 /// NOTE: this lexer modifies features as a file is parsed!
172 const LangOptions &getLangOpts() const { return LangOpts; }
173
174 /// getFileLoc - Return the File Location for the file we are lexing out of.
175 /// The physical location encodes the location where the characters come from,
176 /// the virtual location encodes where we should *claim* the characters came
177 /// from. Currently this is only used by _Pragma handling.
178 SourceLocation getFileLoc() const { return FileLoc; }
179
180private:
181 /// Lex - Return the next token in the file. If this is the end of file, it
182 /// return the tok::eof token. This implicitly involves the preprocessor.
183 bool Lex(Token &Result);
184
185public:
186 /// isPragmaLexer - Returns true if this Lexer is being used to lex a pragma.
187 bool isPragmaLexer() const { return Is_PragmaLexer; }
188
189private:
190 /// IndirectLex - An indirect call to 'Lex' that can be invoked via
191 /// the PreprocessorLexer interface.
192 void IndirectLex(Token &Result) override { Lex(Result); }
193
194public:
195 /// LexFromRawLexer - Lex a token from a designated raw lexer (one with no
196 /// associated preprocessor object. Return true if the 'next character to
197 /// read' pointer points at the end of the lexer buffer, false otherwise.
198 bool LexFromRawLexer(Token &Result) {
199 assert(LexingRawMode && "Not already in raw mode!")(static_cast <bool> (LexingRawMode && "Not already in raw mode!"
) ? void (0) : __assert_fail ("LexingRawMode && \"Not already in raw mode!\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Lex/Lexer.h"
, 199, __extension__ __PRETTY_FUNCTION__))
;
200 Lex(Result);
201 // Note that lexing to the end of the buffer doesn't implicitly delete the
202 // lexer when in raw mode.
203 return BufferPtr == BufferEnd;
204 }
205
206 /// isKeepWhitespaceMode - Return true if the lexer should return tokens for
207 /// every character in the file, including whitespace and comments. This
208 /// should only be used in raw mode, as the preprocessor is not prepared to
209 /// deal with the excess tokens.
210 bool isKeepWhitespaceMode() const {
211 return ExtendedTokenMode > 1;
212 }
213
214 /// SetKeepWhitespaceMode - This method lets clients enable or disable
215 /// whitespace retention mode.
216 void SetKeepWhitespaceMode(bool Val) {
217 assert((!Val || LexingRawMode || LangOpts.TraditionalCPP) &&(static_cast <bool> ((!Val || LexingRawMode || LangOpts
.TraditionalCPP) && "Can only retain whitespace in raw mode or -traditional-cpp"
) ? void (0) : __assert_fail ("(!Val || LexingRawMode || LangOpts.TraditionalCPP) && \"Can only retain whitespace in raw mode or -traditional-cpp\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Lex/Lexer.h"
, 218, __extension__ __PRETTY_FUNCTION__))
218 "Can only retain whitespace in raw mode or -traditional-cpp")(static_cast <bool> ((!Val || LexingRawMode || LangOpts
.TraditionalCPP) && "Can only retain whitespace in raw mode or -traditional-cpp"
) ? void (0) : __assert_fail ("(!Val || LexingRawMode || LangOpts.TraditionalCPP) && \"Can only retain whitespace in raw mode or -traditional-cpp\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Lex/Lexer.h"
, 218, __extension__ __PRETTY_FUNCTION__))
;
219 ExtendedTokenMode = Val ? 2 : 0;
220 }
221
222 /// inKeepCommentMode - Return true if the lexer should return comments as
223 /// tokens.
224 bool inKeepCommentMode() const {
225 return ExtendedTokenMode > 0;
226 }
227
228 /// SetCommentRetentionMode - Change the comment retention mode of the lexer
229 /// to the specified mode. This is really only useful when lexing in raw
230 /// mode, because otherwise the lexer needs to manage this.
231 void SetCommentRetentionState(bool Mode) {
232 assert(!isKeepWhitespaceMode() &&(static_cast <bool> (!isKeepWhitespaceMode() &&
"Can't play with comment retention state when retaining whitespace"
) ? void (0) : __assert_fail ("!isKeepWhitespaceMode() && \"Can't play with comment retention state when retaining whitespace\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Lex/Lexer.h"
, 233, __extension__ __PRETTY_FUNCTION__))
233 "Can't play with comment retention state when retaining whitespace")(static_cast <bool> (!isKeepWhitespaceMode() &&
"Can't play with comment retention state when retaining whitespace"
) ? void (0) : __assert_fail ("!isKeepWhitespaceMode() && \"Can't play with comment retention state when retaining whitespace\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Lex/Lexer.h"
, 233, __extension__ __PRETTY_FUNCTION__))
;
234 ExtendedTokenMode = Mode ? 1 : 0;
235 }
236
237 /// Sets the extended token mode back to its initial value, according to the
238 /// language options and preprocessor. This controls whether the lexer
239 /// produces comment and whitespace tokens.
240 ///
241 /// This requires the lexer to have an associated preprocessor. A standalone
242 /// lexer has nothing to reset to.
243 void resetExtendedTokenMode();
244
245 /// Gets source code buffer.
246 StringRef getBuffer() const {
247 return StringRef(BufferStart, BufferEnd - BufferStart);
248 }
249
250 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
251 /// uninterpreted string. This switches the lexer out of directive mode.
252 void ReadToEndOfLine(SmallVectorImpl<char> *Result = nullptr);
253
254
255 /// Diag - Forwarding function for diagnostics. This translate a source
256 /// position in the current buffer into a SourceLocation object for rendering.
257 DiagnosticBuilder Diag(const char *Loc, unsigned DiagID) const;
258
259 /// getSourceLocation - Return a source location identifier for the specified
260 /// offset in the current file.
261 SourceLocation getSourceLocation(const char *Loc, unsigned TokLen = 1) const;
262
263 /// getSourceLocation - Return a source location for the next character in
264 /// the current file.
265 SourceLocation getSourceLocation() override {
266 return getSourceLocation(BufferPtr);
267 }
268
269 /// Return the current location in the buffer.
270 const char *getBufferLocation() const { return BufferPtr; }
271
272 /// Returns the current lexing offset.
273 unsigned getCurrentBufferOffset() {
274 assert(BufferPtr >= BufferStart && "Invalid buffer state")(static_cast <bool> (BufferPtr >= BufferStart &&
"Invalid buffer state") ? void (0) : __assert_fail ("BufferPtr >= BufferStart && \"Invalid buffer state\""
, "/build/llvm-toolchain-snapshot-13~++20210506100649+6304c0836a4d/clang/include/clang/Lex/Lexer.h"
, 274, __extension__ __PRETTY_FUNCTION__))
;
275 return BufferPtr - BufferStart;
276 }
277
278 /// Skip over \p NumBytes bytes.
279 ///
280 /// If the skip is successful, the next token will be lexed from the new
281 /// offset. The lexer also assumes that we skipped to the start of the line.
282 ///
283 /// \returns true if the skip failed (new offset would have been past the
284 /// end of the buffer), false otherwise.
285 bool skipOver(unsigned NumBytes);
286
287 /// Stringify - Convert the specified string into a C string by i) escaping
288 /// '\\' and " characters and ii) replacing newline character(s) with "\\n".
289 /// If Charify is true, this escapes the ' character instead of ".
290 static std::string Stringify(StringRef Str, bool Charify = false);
291
292 /// Stringify - Convert the specified string into a C string by i) escaping
293 /// '\\' and " characters and ii) replacing newline character(s) with "\\n".
294 static void Stringify(SmallVectorImpl<char> &Str);
295
296 /// getSpelling - This method is used to get the spelling of a token into a
297 /// preallocated buffer, instead of as an std::string. The caller is required
298 /// to allocate enough space for the token, which is guaranteed to be at least
299 /// Tok.getLength() bytes long. The length of the actual result is returned.
300 ///
301 /// Note that this method may do two possible things: it may either fill in
302 /// the buffer specified with characters, or it may *change the input pointer*
303 /// to point to a constant buffer with the data already in it (avoiding a
304 /// copy). The caller is not allowed to modify the returned buffer pointer
305 /// if an internal buffer is returned.
306 static unsigned getSpelling(const Token &Tok, const char *&Buffer,
307 const SourceManager &SourceMgr,
308 const LangOptions &LangOpts,
309 bool *Invalid = nullptr);
310
311 /// getSpelling() - Return the 'spelling' of the Tok token. The spelling of a
312 /// token is the characters used to represent the token in the source file
313 /// after trigraph expansion and escaped-newline folding. In particular, this
314 /// wants to get the true, uncanonicalized, spelling of things like digraphs
315 /// UCNs, etc.
316 static std::string getSpelling(const Token &Tok,
317 const SourceManager &SourceMgr,
318 const LangOptions &LangOpts,
319 bool *Invalid = nullptr);
320
321 /// getSpelling - This method is used to get the spelling of the
322 /// token at the given source location. If, as is usually true, it
323 /// is not necessary to copy any data, then the returned string may
324 /// not point into the provided buffer.
325 ///
326 /// This method lexes at the expansion depth of the given
327 /// location and does not jump to the expansion or spelling
328 /// location.
329 static StringRef getSpelling(SourceLocation loc,
330 SmallVectorImpl<char> &buffer,
331 const SourceManager &SM,
332 const LangOptions &options,
333 bool *invalid = nullptr);
334
335 /// MeasureTokenLength - Relex the token at the specified location and return
336 /// its length in bytes in the input file. If the token needs cleaning (e.g.
337 /// includes a trigraph or an escaped newline) then this count includes bytes
338 /// that are part of that.
339 static unsigned MeasureTokenLength(SourceLocation Loc,
340 const SourceManager &SM,
341 const LangOptions &LangOpts);
342
343 /// Relex the token at the specified location.
344 /// \returns true if there was a failure, false on success.
345 static bool getRawToken(SourceLocation Loc, Token &Result,
346 const SourceManager &SM,
347 const LangOptions &LangOpts,
348 bool IgnoreWhiteSpace = false);
349
350 /// Given a location any where in a source buffer, find the location
351 /// that corresponds to the beginning of the token in which the original
352 /// source location lands.
353 static SourceLocation GetBeginningOfToken(SourceLocation Loc,
354 const SourceManager &SM,
355 const LangOptions &LangOpts);
356
357 /// Get the physical length (including trigraphs and escaped newlines) of the
358 /// first \p Characters characters of the token starting at TokStart.
359 static unsigned getTokenPrefixLength(SourceLocation TokStart,
360 unsigned CharNo,
361 const SourceManager &SM,
362 const LangOptions &LangOpts);
363
364 /// AdvanceToTokenCharacter - If the current SourceLocation specifies a
365 /// location at the start of a token, return a new location that specifies a
366 /// character within the token. This handles trigraphs and escaped newlines.
367 static SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart,
368 unsigned Characters,
369 const SourceManager &SM,
370 const LangOptions &LangOpts) {
371 return TokStart.getLocWithOffset(
372 getTokenPrefixLength(TokStart, Characters, SM, LangOpts));
373 }
374
375 /// Computes the source location just past the end of the
376 /// token at this source location.
377 ///
378 /// This routine can be used to produce a source location that
379 /// points just past the end of the token referenced by \p Loc, and
380 /// is generally used when a diagnostic needs to point just after a
381 /// token where it expected something different that it received. If
382 /// the returned source location would not be meaningful (e.g., if
383 /// it points into a macro), this routine returns an invalid
384 /// source location.
385 ///
386 /// \param Offset an offset from the end of the token, where the source
387 /// location should refer to. The default offset (0) produces a source
388 /// location pointing just past the end of the token; an offset of 1 produces
389 /// a source location pointing to the last character in the token, etc.
390 static SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
391 const SourceManager &SM,
392 const LangOptions &LangOpts);
393
394 /// Given a token range, produce a corresponding CharSourceRange that
395 /// is not a token range. This allows the source range to be used by
396 /// components that don't have access to the lexer and thus can't find the
397 /// end of the range for themselves.
398 static CharSourceRange getAsCharRange(SourceRange Range,
399 const SourceManager &SM,
400 const LangOptions &LangOpts) {
401 SourceLocation End = getLocForEndOfToken(Range.getEnd(), 0, SM, LangOpts);
402 return End.isInvalid() ? CharSourceRange()
403 : CharSourceRange::getCharRange(
404 Range.getBegin(), End);
405 }
406 static CharSourceRange getAsCharRange(CharSourceRange Range,
407 const SourceManager &SM,
408 const LangOptions &LangOpts) {
409 return Range.isTokenRange()
410 ? getAsCharRange(Range.getAsRange(), SM, LangOpts)
411 : Range;
412 }
413
414 /// Returns true if the given MacroID location points at the first
415 /// token of the macro expansion.
416 ///
417 /// \param MacroBegin If non-null and function returns true, it is set to
418 /// begin location of the macro.
419 static bool isAtStartOfMacroExpansion(SourceLocation loc,
420 const SourceManager &SM,
421 const LangOptions &LangOpts,
422 SourceLocation *MacroBegin = nullptr);
423
424 /// Returns true if the given MacroID location points at the last
425 /// token of the macro expansion.
426 ///
427 /// \param MacroEnd If non-null and function returns true, it is set to
428 /// end location of the macro.
429 static bool isAtEndOfMacroExpansion(SourceLocation loc,
430 const SourceManager &SM,
431 const LangOptions &LangOpts,
432 SourceLocation *MacroEnd = nullptr);
433
434 /// Accepts a range and returns a character range with file locations.
435 ///
436 /// Returns a null range if a part of the range resides inside a macro
437 /// expansion or the range does not reside on the same FileID.
438 ///
439 /// This function is trying to deal with macros and return a range based on
440 /// file locations. The cases where it can successfully handle macros are:
441 ///
442 /// -begin or end range lies at the start or end of a macro expansion, in
443 /// which case the location will be set to the expansion point, e.g:
444 /// \#define M 1 2
445 /// a M
446 /// If you have a range [a, 2] (where 2 came from the macro), the function
447 /// will return a range for "a M"
448 /// if you have range [a, 1], the function will fail because the range
449 /// overlaps with only a part of the macro
450 ///
451 /// -The macro is a function macro and the range can be mapped to the macro
452 /// arguments, e.g:
453 /// \#define M 1 2
454 /// \#define FM(x) x
455 /// FM(a b M)
456 /// if you have range [b, 2], the function will return the file range "b M"
457 /// inside the macro arguments.
458 /// if you have range [a, 2], the function will return the file range
459 /// "FM(a b M)" since the range includes all of the macro expansion.
460 static CharSourceRange makeFileCharRange(CharSourceRange Range,
461 const SourceManager &SM,
462 const LangOptions &LangOpts);
463
464 /// Returns a string for the source that the range encompasses.
465 static StringRef getSourceText(CharSourceRange Range,
466 const SourceManager &SM,
467 const LangOptions &LangOpts,
468 bool *Invalid = nullptr);
469
470 /// Retrieve the name of the immediate macro expansion.
471 ///
472 /// This routine starts from a source location, and finds the name of the macro
473 /// responsible for its immediate expansion. It looks through any intervening
474 /// macro argument expansions to compute this. It returns a StringRef which
475 /// refers to the SourceManager-owned buffer of the source where that macro
476 /// name is spelled. Thus, the result shouldn't out-live that SourceManager.
477 static StringRef getImmediateMacroName(SourceLocation Loc,
478 const SourceManager &SM,
479 const LangOptions &LangOpts);
480
481 /// Retrieve the name of the immediate macro expansion.
482 ///
483 /// This routine starts from a source location, and finds the name of the
484 /// macro responsible for its immediate expansion. It looks through any
485 /// intervening macro argument expansions to compute this. It returns a
486 /// StringRef which refers to the SourceManager-owned buffer of the source
487 /// where that macro name is spelled. Thus, the result shouldn't out-live
488 /// that SourceManager.
489 ///
490 /// This differs from Lexer::getImmediateMacroName in that any macro argument
491 /// location will result in the topmost function macro that accepted it.
492 /// e.g.
493 /// \code
494 /// MAC1( MAC2(foo) )
495 /// \endcode
496 /// for location of 'foo' token, this function will return "MAC1" while
497 /// Lexer::getImmediateMacroName will return "MAC2".
498 static StringRef getImmediateMacroNameForDiagnostics(
499 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts);
500
501 /// Compute the preamble of the given file.
502 ///
503 /// The preamble of a file contains the initial comments, include directives,
504 /// and other preprocessor directives that occur before the code in this
505 /// particular file actually begins. The preamble of the main source file is
506 /// a potential prefix header.
507 ///
508 /// \param Buffer The memory buffer containing the file's contents.
509 ///
510 /// \param MaxLines If non-zero, restrict the length of the preamble
511 /// to fewer than this number of lines.
512 ///
513 /// \returns The offset into the file where the preamble ends and the rest
514 /// of the file begins along with a boolean value indicating whether
515 /// the preamble ends at the beginning of a new line.
516 static PreambleBounds ComputePreamble(StringRef Buffer,
517 const LangOptions &LangOpts,
518 unsigned MaxLines = 0);
519
520 /// Finds the token that comes right after the given location.
521 ///
522 /// Returns the next token, or none if the location is inside a macro.
523 static Optional<Token> findNextToken(SourceLocation Loc,
524 const SourceManager &SM,
525 const LangOptions &LangOpts);
526
527 /// Checks that the given token is the first token that occurs after
528 /// the given location (this excludes comments and whitespace). Returns the
529 /// location immediately after the specified token. If the token is not found
530 /// or the location is inside a macro, the returned source location will be
531 /// invalid.
532 static SourceLocation findLocationAfterToken(SourceLocation loc,
533 tok::TokenKind TKind,
534 const SourceManager &SM,
535 const LangOptions &LangOpts,
536 bool SkipTrailingWhitespaceAndNewLine);
537
538 /// Returns true if the given character could appear in an identifier.
539 static bool isIdentifierBodyChar(char c, const LangOptions &LangOpts);
540
541 /// Checks whether new line pointed by Str is preceded by escape
542 /// sequence.
543 static bool isNewLineEscaped(const char *BufferStart, const char *Str);
544
545 /// getCharAndSizeNoWarn - Like the getCharAndSize method, but does not ever
546 /// emit a warning.
547 static inline char getCharAndSizeNoWarn(const char *Ptr, unsigned &Size,
548 const LangOptions &LangOpts) {
549 // If this is not a trigraph and not a UCN or escaped newline, return
550 // quickly.
551 if (isObviouslySimpleCharacter(Ptr[0])) {
552 Size = 1;
553 return *Ptr;
554 }
555
556 Size = 0;
557 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
558 }
559
560 /// Returns the leading whitespace for line that corresponds to the given
561 /// location \p Loc.
562 static StringRef getIndentationForLine(SourceLocation Loc,
563 const SourceManager &SM);
564
565private:
566 //===--------------------------------------------------------------------===//
567 // Internal implementation interfaces.
568
569 /// LexTokenInternal - Internal interface to lex a preprocessing token. Called
570 /// by Lex.
571 ///
572 bool LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine);
573
574 bool CheckUnicodeWhitespace(Token &Result, uint32_t C, const char *CurPtr);
575
576 /// Given that a token begins with the Unicode character \p C, figure out
577 /// what kind of token it is and dispatch to the appropriate lexing helper
578 /// function.
579 bool LexUnicode(Token &Result, uint32_t C, const char *CurPtr);
580
581 /// FormTokenWithChars - When we lex a token, we have identified a span
582 /// starting at BufferPtr, going to TokEnd that forms the token. This method
583 /// takes that range and assigns it to the token as its location and size. In
584 /// addition, since tokens cannot overlap, this also updates BufferPtr to be
585 /// TokEnd.
586 void FormTokenWithChars(Token &Result, const char *TokEnd,
587 tok::TokenKind Kind) {
588 unsigned TokLen = TokEnd-BufferPtr;
589 Result.setLength(TokLen);
590 Result.setLocation(getSourceLocation(BufferPtr, TokLen));
591 Result.setKind(Kind);
592 BufferPtr = TokEnd;
593 }
594
595 /// isNextPPTokenLParen - Return 1 if the next unexpanded token will return a
596 /// tok::l_paren token, 0 if it is something else and 2 if there are no more
597 /// tokens in the buffer controlled by this lexer.
598 unsigned isNextPPTokenLParen();
599
600 //===--------------------------------------------------------------------===//
601 // Lexer character reading interfaces.
602
603 // This lexer is built on two interfaces for reading characters, both of which
604 // automatically provide phase 1/2 translation. getAndAdvanceChar is used
605 // when we know that we will be reading a character from the input buffer and
606 // that this character will be part of the result token. This occurs in (f.e.)
607 // string processing, because we know we need to read until we find the
608 // closing '"' character.
609 //
610 // The second interface is the combination of getCharAndSize with
611 // ConsumeChar. getCharAndSize reads a phase 1/2 translated character,
612 // returning it and its size. If the lexer decides that this character is
613 // part of the current token, it calls ConsumeChar on it. This two stage
614 // approach allows us to emit diagnostics for characters (e.g. warnings about
615 // trigraphs), knowing that they only are emitted if the character is
616 // consumed.
617
618 /// isObviouslySimpleCharacter - Return true if the specified character is
619 /// obviously the same in translation phase 1 and translation phase 3. This
620 /// can return false for characters that end up being the same, but it will
621 /// never return true for something that needs to be mapped.
622 static bool isObviouslySimpleCharacter(char C) {
623 return C != '?' && C != '\\';
624 }
625
626 /// getAndAdvanceChar - Read a single 'character' from the specified buffer,
627 /// advance over it, and return it. This is tricky in several cases. Here we
628 /// just handle the trivial case and fall-back to the non-inlined
629 /// getCharAndSizeSlow method to handle the hard case.
630 inline char getAndAdvanceChar(const char *&Ptr, Token &Tok) {
631 // If this is not a trigraph and not a UCN or escaped newline, return
632 // quickly.
633 if (isObviouslySimpleCharacter(Ptr[0])) return *Ptr++;
634
635 unsigned Size = 0;
636 char C = getCharAndSizeSlow(Ptr, Size, &Tok);
637 Ptr += Size;
638 return C;
639 }
640
641 /// ConsumeChar - When a character (identified by getCharAndSize) is consumed
642 /// and added to a given token, check to see if there are diagnostics that
643 /// need to be emitted or flags that need to be set on the token. If so, do
644 /// it.
645 const char *ConsumeChar(const char *Ptr, unsigned Size, Token &Tok) {
646 // Normal case, we consumed exactly one token. Just return it.
647 if (Size == 1)
648 return Ptr+Size;
649
650 // Otherwise, re-lex the character with a current token, allowing
651 // diagnostics to be emitted and flags to be set.
652 Size = 0;
653 getCharAndSizeSlow(Ptr, Size, &Tok);
654 return Ptr+Size;
655 }
656
657 /// getCharAndSize - Peek a single 'character' from the specified buffer,
658 /// get its size, and return it. This is tricky in several cases. Here we
659 /// just handle the trivial case and fall-back to the non-inlined
660 /// getCharAndSizeSlow method to handle the hard case.
661 inline char getCharAndSize(const char *Ptr, unsigned &Size) {
662 // If this is not a trigraph and not a UCN or escaped newline, return
663 // quickly.
664 if (isObviouslySimpleCharacter(Ptr[0])) {
12
Taking false branch
665 Size = 1;
666 return *Ptr;
667 }
668
669 Size = 0;
670 return getCharAndSizeSlow(Ptr, Size);
13
Value assigned to field 'PP'
671 }
672
673 /// getCharAndSizeSlow - Handle the slow/uncommon case of the getCharAndSize
674 /// method.
675 char getCharAndSizeSlow(const char *Ptr, unsigned &Size,
676 Token *Tok = nullptr);
677
678 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
679 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" on entry
680 /// to this function.
681 static unsigned getEscapedNewLineSize(const char *P);
682
683 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
684 /// them), skip over them and return the first non-escaped-newline found,
685 /// otherwise return P.
686 static const char *SkipEscapedNewLines(const char *P);
687
688 /// getCharAndSizeSlowNoWarn - Same as getCharAndSizeSlow, but never emits a
689 /// diagnostic.
690 static char getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
691 const LangOptions &LangOpts);
692
693 //===--------------------------------------------------------------------===//
694 // Other lexer functions.
695
696 void SetByteOffset(unsigned Offset, bool StartOfLine);
697
698 void PropagateLineStartLeadingSpaceInfo(Token &Result);
699
700 const char *LexUDSuffix(Token &Result, const char *CurPtr,
701 bool IsStringLiteral);
702
703 // Helper functions to lex the remainder of a token of the specific type.
704 bool LexIdentifier (Token &Result, const char *CurPtr);
705 bool LexNumericConstant (Token &Result, const char *CurPtr);
706 bool LexStringLiteral (Token &Result, const char *CurPtr,
707 tok::TokenKind Kind);
708 bool LexRawStringLiteral (Token &Result, const char *CurPtr,
709 tok::TokenKind Kind);
710 bool LexAngledStringLiteral(Token &Result, const char *CurPtr);
711 bool LexCharConstant (Token &Result, const char *CurPtr,
712 tok::TokenKind Kind);
713 bool LexEndOfFile (Token &Result, const char *CurPtr);
714 bool SkipWhitespace (Token &Result, const char *CurPtr,
715 bool &TokAtPhysicalStartOfLine);
716 bool SkipLineComment (Token &Result, const char *CurPtr,
717 bool &TokAtPhysicalStartOfLine);
718 bool SkipBlockComment (Token &Result, const char *CurPtr,
719 bool &TokAtPhysicalStartOfLine);
720 bool SaveLineComment (Token &Result, const char *CurPtr);
721
722 bool IsStartOfConflictMarker(const char *CurPtr);
723 bool HandleEndOfConflictMarker(const char *CurPtr);
724
725 bool lexEditorPlaceholder(Token &Result, const char *CurPtr);
726
727 bool isCodeCompletionPoint(const char *CurPtr) const;
728 void cutOffLexing() { BufferPtr = BufferEnd; }
729
730 bool isHexaLiteral(const char *Start, const LangOptions &LangOpts);
731
732 void codeCompleteIncludedFile(const char *PathStart,
733 const char *CompletionPoint, bool IsAngled);
734
735 /// Read a universal character name.
736 ///
737 /// \param StartPtr The position in the source buffer after the initial '\'.
738 /// If the UCN is syntactically well-formed (but not
739 /// necessarily valid), this parameter will be updated to
740 /// point to the character after the UCN.
741 /// \param SlashLoc The position in the source buffer of the '\'.
742 /// \param Result The token being formed. Pass \c nullptr to suppress
743 /// diagnostics and handle token formation in the caller.
744 ///
745 /// \return The Unicode codepoint specified by the UCN, or 0 if the UCN is
746 /// invalid.
747 uint32_t tryReadUCN(const char *&StartPtr, const char *SlashLoc, Token *Result);
748
749 /// Try to consume a UCN as part of an identifier at the current
750 /// location.
751 /// \param CurPtr Initially points to the range of characters in the source
752 /// buffer containing the '\'. Updated to point past the end of
753 /// the UCN on success.
754 /// \param Size The number of characters occupied by the '\' (including
755 /// trigraphs and escaped newlines).
756 /// \param Result The token being produced. Marked as containing a UCN on
757 /// success.
758 /// \return \c true if a UCN was lexed and it produced an acceptable
759 /// identifier character, \c false otherwise.
760 bool tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
761 Token &Result);
762
763 /// Try to consume an identifier character encoded in UTF-8.
764 /// \param CurPtr Points to the start of the (potential) UTF-8 code unit
765 /// sequence. On success, updated to point past the end of it.
766 /// \return \c true if a UTF-8 sequence mapping to an acceptable identifier
767 /// character was lexed, \c false otherwise.
768 bool tryConsumeIdentifierUTF8Char(const char *&CurPtr);
769};
770
771} // namespace clang
772
773#endif // LLVM_CLANG_LEX_LEXER_H