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