Bug Summary

File:clang/lib/Lex/Lexer.cpp
Warning:line 1168, 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 -clear-ast-before-backend -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 -mframe-pointer=none -relaxed-aliasing -fmath-errno -ffp-contract=on -fno-rounding-math -mconstructor-aliases -funwind-tables=2 -target-cpu x86-64 -tune-cpu generic -debugger-tuning=gdb -ffunction-sections -fdata-sections -fcoverage-compilation-dir=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm -resource-dir /usr/lib/llvm-14/lib/clang/14.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I tools/clang/lib/Lex -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/lib/Lex -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/include -I tools/clang/include -I include -I /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/llvm/include -D _FORTIFY_SOURCE=2 -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-14/lib/clang/14.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 -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fmacro-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fcoverage-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -O3 -Wno-unused-command-line-argument -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-14~++20220119111520+da61cb019eb2/build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/build-llvm=build-llvm -fdebug-prefix-map=/build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/= -ferror-limit 19 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -fcolor-diagnostics -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-2022-01-19-134126-35450-1 -x c++ /build/llvm-toolchain-snapshot-14~++20220119111520+da61cb019eb2/clang/lib/Lex/Lexer.cpp

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

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