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