1 //===- Lexer.cpp - C Language Family Lexer --------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Lexer and Token interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/Lexer.h"
15 #include "UnicodeCharSets.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TokenKinds.h"
22 #include "clang/Lex/LexDiagnostic.h"
23 #include "clang/Lex/LiteralSupport.h"
24 #include "clang/Lex/MultipleIncludeOpt.h"
25 #include "clang/Lex/Preprocessor.h"
26 #include "clang/Lex/PreprocessorOptions.h"
27 #include "clang/Lex/Token.h"
28 #include "clang/Basic/Diagnostic.h"
29 #include "clang/Basic/LLVM.h"
30 #include "clang/Basic/TokenKinds.h"
31 #include "llvm/ADT/None.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/ADT/StringExtras.h"
34 #include "llvm/ADT/StringSwitch.h"
35 #include "llvm/ADT/StringRef.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/ConvertUTF.h"
38 #include "llvm/Support/MathExtras.h"
39 #include "llvm/Support/MemoryBuffer.h"
40 #include "llvm/Support/NativeFormatting.h"
41 #include "llvm/Support/UnicodeCharRanges.h"
51 using namespace clang;
53 //===----------------------------------------------------------------------===//
54 // Token Class Implementation
55 //===----------------------------------------------------------------------===//
57 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
58 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
61 if (IdentifierInfo *II = getIdentifierInfo())
62 return II->getObjCKeywordID() == objcKey;
66 /// getObjCKeywordID - Return the ObjC keyword kind.
67 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
69 return tok::objc_not_keyword;
70 IdentifierInfo *specId = getIdentifierInfo();
71 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
74 //===----------------------------------------------------------------------===//
75 // Lexer Class Implementation
76 //===----------------------------------------------------------------------===//
78 void Lexer::anchor() {}
80 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
82 BufferStart = BufStart;
86 assert(BufEnd[0] == 0 &&
87 "We assume that the input buffer has a null character at the end"
88 " to simplify lexing!");
90 // Check whether we have a BOM in the beginning of the buffer. If yes - act
91 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
92 // skip the UTF-8 BOM if it's present.
93 if (BufferStart == BufferPtr) {
94 // Determine the size of the BOM.
95 StringRef Buf(BufferStart, BufferEnd - BufferStart);
96 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
97 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
101 BufferPtr += BOMLength;
104 Is_PragmaLexer = false;
105 CurrentConflictMarkerState = CMK_None;
107 // Start of the file is a start of line.
108 IsAtStartOfLine = true;
109 IsAtPhysicalStartOfLine = true;
111 HasLeadingSpace = false;
112 HasLeadingEmptyMacro = false;
114 // We are not after parsing a #.
115 ParsingPreprocessorDirective = false;
117 // We are not after parsing #include.
118 ParsingFilename = false;
120 // We are not in raw mode. Raw mode disables diagnostics and interpretation
121 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
122 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
123 // or otherwise skipping over tokens.
124 LexingRawMode = false;
126 // Default to not keeping comments.
127 ExtendedTokenMode = 0;
130 /// Lexer constructor - Create a new lexer object for the specified buffer
131 /// with the specified preprocessor managing the lexing process. This lexer
132 /// assumes that the associated file buffer and Preprocessor objects will
133 /// outlive it, so it doesn't take ownership of either of them.
134 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
135 : PreprocessorLexer(&PP, FID),
136 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
137 LangOpts(PP.getLangOpts()) {
138 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
139 InputFile->getBufferEnd());
141 resetExtendedTokenMode();
144 /// Lexer constructor - Create a new raw lexer object. This object is only
145 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
146 /// range will outlive it, so it doesn't take ownership of it.
147 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
148 const char *BufStart, const char *BufPtr, const char *BufEnd)
149 : FileLoc(fileloc), LangOpts(langOpts) {
150 InitLexer(BufStart, BufPtr, BufEnd);
152 // We *are* in raw mode.
153 LexingRawMode = true;
156 /// Lexer constructor - Create a new raw lexer object. This object is only
157 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
158 /// range will outlive it, so it doesn't take ownership of it.
159 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
160 const SourceManager &SM, const LangOptions &langOpts)
161 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
162 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
164 void Lexer::resetExtendedTokenMode() {
165 assert(PP && "Cannot reset token mode without a preprocessor");
166 if (LangOpts.TraditionalCPP)
167 SetKeepWhitespaceMode(true);
169 SetCommentRetentionState(PP->getCommentRetentionState());
172 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
173 /// _Pragma expansion. This has a variety of magic semantics that this method
174 /// sets up. It returns a new'd Lexer that must be delete'd when done.
176 /// On entrance to this routine, TokStartLoc is a macro location which has a
177 /// spelling loc that indicates the bytes to be lexed for the token and an
178 /// expansion location that indicates where all lexed tokens should be
181 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
182 /// normal lexer that remaps tokens as they fly by. This would require making
183 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
184 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
185 /// out of the critical path of the lexer!
187 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
188 SourceLocation ExpansionLocStart,
189 SourceLocation ExpansionLocEnd,
190 unsigned TokLen, Preprocessor &PP) {
191 SourceManager &SM = PP.getSourceManager();
193 // Create the lexer as if we were going to lex the file normally.
194 FileID SpellingFID = SM.getFileID(SpellingLoc);
195 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
196 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
198 // Now that the lexer is created, change the start/end locations so that we
199 // just lex the subsection of the file that we want. This is lexing from a
201 const char *StrData = SM.getCharacterData(SpellingLoc);
203 L->BufferPtr = StrData;
204 L->BufferEnd = StrData+TokLen;
205 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
207 // Set the SourceLocation with the remapping information. This ensures that
208 // GetMappedTokenLoc will remap the tokens as they are lexed.
209 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
211 ExpansionLocEnd, TokLen);
213 // Ensure that the lexer thinks it is inside a directive, so that end \n will
214 // return an EOD token.
215 L->ParsingPreprocessorDirective = true;
217 // This lexer really is for _Pragma.
218 L->Is_PragmaLexer = true;
222 template <typename T> static void StringifyImpl(T &Str, char Quote) {
223 typename T::size_type i = 0, e = Str.size();
225 if (Str[i] == '\\' || Str[i] == Quote) {
226 Str.insert(Str.begin() + i, '\\');
229 } else if (Str[i] == '\n' || Str[i] == '\r') {
230 // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
231 if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
232 Str[i] != Str[i + 1]) {
236 // Replace '\n' and '\r' to '\\' followed by 'n'.
238 Str.insert(Str.begin() + i + 1, 'n');
247 std::string Lexer::Stringify(StringRef Str, bool Charify) {
248 std::string Result = Str;
249 char Quote = Charify ? '\'' : '"';
250 StringifyImpl(Result, Quote);
254 void Lexer::Stringify(SmallVectorImpl<char> &Str) { StringifyImpl(Str, '"'); }
256 //===----------------------------------------------------------------------===//
258 //===----------------------------------------------------------------------===//
260 /// \brief Slow case of getSpelling. Extract the characters comprising the
261 /// spelling of this token from the provided input buffer.
262 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
263 const LangOptions &LangOpts, char *Spelling) {
264 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
267 const char *BufEnd = BufPtr + Tok.getLength();
269 if (tok::isStringLiteral(Tok.getKind())) {
270 // Munch the encoding-prefix and opening double-quote.
271 while (BufPtr < BufEnd) {
273 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
276 if (Spelling[Length - 1] == '"')
280 // Raw string literals need special handling; trigraph expansion and line
281 // splicing do not occur within their d-char-sequence nor within their
284 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
285 // Search backwards from the end of the token to find the matching closing
287 const char *RawEnd = BufEnd;
288 do --RawEnd; while (*RawEnd != '"');
289 size_t RawLength = RawEnd - BufPtr + 1;
291 // Everything between the quotes is included verbatim in the spelling.
292 memcpy(Spelling + Length, BufPtr, RawLength);
296 // The rest of the token is lexed normally.
300 while (BufPtr < BufEnd) {
302 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
306 assert(Length < Tok.getLength() &&
307 "NeedsCleaning flag set on token that didn't need cleaning!");
311 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
312 /// token are the characters used to represent the token in the source file
313 /// after trigraph expansion and escaped-newline folding. In particular, this
314 /// wants to get the true, uncanonicalized, spelling of things like digraphs
316 StringRef Lexer::getSpelling(SourceLocation loc,
317 SmallVectorImpl<char> &buffer,
318 const SourceManager &SM,
319 const LangOptions &options,
321 // Break down the source location.
322 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
324 // Try to the load the file buffer.
325 bool invalidTemp = false;
326 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
328 if (invalid) *invalid = true;
332 const char *tokenBegin = file.data() + locInfo.second;
334 // Lex from the start of the given location.
335 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
336 file.begin(), tokenBegin, file.end());
338 lexer.LexFromRawLexer(token);
340 unsigned length = token.getLength();
342 // Common case: no need for cleaning.
343 if (!token.needsCleaning())
344 return StringRef(tokenBegin, length);
346 // Hard case, we need to relex the characters into the string.
347 buffer.resize(length);
348 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
349 return StringRef(buffer.data(), buffer.size());
352 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
353 /// token are the characters used to represent the token in the source file
354 /// after trigraph expansion and escaped-newline folding. In particular, this
355 /// wants to get the true, uncanonicalized, spelling of things like digraphs
357 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
358 const LangOptions &LangOpts, bool *Invalid) {
359 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
361 bool CharDataInvalid = false;
362 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
365 *Invalid = CharDataInvalid;
369 // If this token contains nothing interesting, return it directly.
370 if (!Tok.needsCleaning())
371 return std::string(TokStart, TokStart + Tok.getLength());
374 Result.resize(Tok.getLength());
375 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
379 /// getSpelling - This method is used to get the spelling of a token into a
380 /// preallocated buffer, instead of as an std::string. The caller is required
381 /// to allocate enough space for the token, which is guaranteed to be at least
382 /// Tok.getLength() bytes long. The actual length of the token is returned.
384 /// Note that this method may do two possible things: it may either fill in
385 /// the buffer specified with characters, or it may *change the input pointer*
386 /// to point to a constant buffer with the data already in it (avoiding a
387 /// copy). The caller is not allowed to modify the returned buffer pointer
388 /// if an internal buffer is returned.
389 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
390 const SourceManager &SourceMgr,
391 const LangOptions &LangOpts, bool *Invalid) {
392 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
394 const char *TokStart = nullptr;
395 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
396 if (Tok.is(tok::raw_identifier))
397 TokStart = Tok.getRawIdentifier().data();
398 else if (!Tok.hasUCN()) {
399 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
400 // Just return the string from the identifier table, which is very quick.
401 Buffer = II->getNameStart();
402 return II->getLength();
406 // NOTE: this can be checked even after testing for an IdentifierInfo.
408 TokStart = Tok.getLiteralData();
411 // Compute the start of the token in the input lexer buffer.
412 bool CharDataInvalid = false;
413 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
415 *Invalid = CharDataInvalid;
416 if (CharDataInvalid) {
422 // If this token contains nothing interesting, return it directly.
423 if (!Tok.needsCleaning()) {
425 return Tok.getLength();
428 // Otherwise, hard case, relex the characters into the string.
429 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
432 /// MeasureTokenLength - Relex the token at the specified location and return
433 /// its length in bytes in the input file. If the token needs cleaning (e.g.
434 /// includes a trigraph or an escaped newline) then this count includes bytes
435 /// that are part of that.
436 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
437 const SourceManager &SM,
438 const LangOptions &LangOpts) {
440 if (getRawToken(Loc, TheTok, SM, LangOpts))
442 return TheTok.getLength();
445 /// \brief Relex the token at the specified location.
446 /// \returns true if there was a failure, false on success.
447 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
448 const SourceManager &SM,
449 const LangOptions &LangOpts,
450 bool IgnoreWhiteSpace) {
451 // TODO: this could be special cased for common tokens like identifiers, ')',
452 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
453 // all obviously single-char tokens. This could use
454 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
457 // If this comes from a macro expansion, we really do want the macro name, not
458 // the token this macro expanded to.
459 Loc = SM.getExpansionLoc(Loc);
460 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
461 bool Invalid = false;
462 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
466 const char *StrData = Buffer.data()+LocInfo.second;
468 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
471 // Create a lexer starting at the beginning of this token.
472 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
473 Buffer.begin(), StrData, Buffer.end());
474 TheLexer.SetCommentRetentionState(true);
475 TheLexer.LexFromRawLexer(Result);
479 /// Returns the pointer that points to the beginning of line that contains
480 /// the given offset, or null if the offset if invalid.
481 static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
482 const char *BufStart = Buffer.data();
483 if (Offset >= Buffer.size())
486 const char *LexStart = BufStart + Offset;
487 for (; LexStart != BufStart; --LexStart) {
488 if (isVerticalWhitespace(LexStart[0]) &&
489 !Lexer::isNewLineEscaped(BufStart, LexStart)) {
490 // LexStart should point at first character of logical line.
498 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
499 const SourceManager &SM,
500 const LangOptions &LangOpts) {
501 assert(Loc.isFileID());
502 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
503 if (LocInfo.first.isInvalid())
506 bool Invalid = false;
507 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
511 // Back up from the current location until we hit the beginning of a line
512 // (or the buffer). We'll relex from that point.
513 const char *StrData = Buffer.data() + LocInfo.second;
514 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
515 if (!LexStart || LexStart == StrData)
518 // Create a lexer starting at the beginning of this token.
519 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
520 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
522 TheLexer.SetCommentRetentionState(true);
524 // Lex tokens until we find the token that contains the source location.
527 TheLexer.LexFromRawLexer(TheTok);
529 if (TheLexer.getBufferLocation() > StrData) {
530 // Lexing this token has taken the lexer past the source location we're
531 // looking for. If the current token encompasses our source location,
532 // return the beginning of that token.
533 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
534 return TheTok.getLocation();
536 // We ended up skipping over the source location entirely, which means
537 // that it points into whitespace. We're done here.
540 } while (TheTok.getKind() != tok::eof);
542 // We've passed our source location; just return the original source location.
546 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
547 const SourceManager &SM,
548 const LangOptions &LangOpts) {
550 return getBeginningOfFileToken(Loc, SM, LangOpts);
552 if (!SM.isMacroArgExpansion(Loc))
555 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
556 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
557 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
558 std::pair<FileID, unsigned> BeginFileLocInfo =
559 SM.getDecomposedLoc(BeginFileLoc);
560 assert(FileLocInfo.first == BeginFileLocInfo.first &&
561 FileLocInfo.second >= BeginFileLocInfo.second);
562 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
567 enum PreambleDirectiveKind {
574 PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
575 const LangOptions &LangOpts,
577 // Create a lexer starting at the beginning of the file. Note that we use a
578 // "fake" file source location at offset 1 so that the lexer will track our
579 // position within the file.
580 const unsigned StartOffset = 1;
581 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
582 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
584 TheLexer.SetCommentRetentionState(true);
586 bool InPreprocessorDirective = false;
588 SourceLocation ActiveCommentLoc;
590 unsigned MaxLineOffset = 0;
592 const char *CurPtr = Buffer.begin();
593 unsigned CurLine = 0;
594 while (CurPtr != Buffer.end()) {
598 if (CurLine == MaxLines)
602 if (CurPtr != Buffer.end())
603 MaxLineOffset = CurPtr - Buffer.begin();
607 TheLexer.LexFromRawLexer(TheTok);
609 if (InPreprocessorDirective) {
610 // If we've hit the end of the file, we're done.
611 if (TheTok.getKind() == tok::eof) {
615 // If we haven't hit the end of the preprocessor directive, skip this
617 if (!TheTok.isAtStartOfLine())
620 // We've passed the end of the preprocessor directive, and will look
621 // at this token again below.
622 InPreprocessorDirective = false;
625 // Keep track of the # of lines in the preamble.
626 if (TheTok.isAtStartOfLine()) {
627 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
629 // If we were asked to limit the number of lines in the preamble,
630 // and we're about to exceed that limit, we're done.
631 if (MaxLineOffset && TokOffset >= MaxLineOffset)
635 // Comments are okay; skip over them.
636 if (TheTok.getKind() == tok::comment) {
637 if (ActiveCommentLoc.isInvalid())
638 ActiveCommentLoc = TheTok.getLocation();
642 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
643 // This is the start of a preprocessor directive.
644 Token HashTok = TheTok;
645 InPreprocessorDirective = true;
646 ActiveCommentLoc = SourceLocation();
648 // Figure out which directive this is. Since we're lexing raw tokens,
649 // we don't have an identifier table available. Instead, just look at
650 // the raw identifier to recognize and categorize preprocessor directives.
651 TheLexer.LexFromRawLexer(TheTok);
652 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
653 StringRef Keyword = TheTok.getRawIdentifier();
654 PreambleDirectiveKind PDK
655 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
656 .Case("include", PDK_Skipped)
657 .Case("__include_macros", PDK_Skipped)
658 .Case("define", PDK_Skipped)
659 .Case("undef", PDK_Skipped)
660 .Case("line", PDK_Skipped)
661 .Case("error", PDK_Skipped)
662 .Case("pragma", PDK_Skipped)
663 .Case("import", PDK_Skipped)
664 .Case("include_next", PDK_Skipped)
665 .Case("warning", PDK_Skipped)
666 .Case("ident", PDK_Skipped)
667 .Case("sccs", PDK_Skipped)
668 .Case("assert", PDK_Skipped)
669 .Case("unassert", PDK_Skipped)
670 .Case("if", PDK_Skipped)
671 .Case("ifdef", PDK_Skipped)
672 .Case("ifndef", PDK_Skipped)
673 .Case("elif", PDK_Skipped)
674 .Case("else", PDK_Skipped)
675 .Case("endif", PDK_Skipped)
676 .Default(PDK_Unknown);
683 // We don't know what this directive is; stop at the '#'.
688 // We only end up here if we didn't recognize the preprocessor
689 // directive or it was one that can't occur in the preamble at this
690 // point. Roll back the current token to the location of the '#'.
691 InPreprocessorDirective = false;
695 // We hit a token that we don't recognize as being in the
696 // "preprocessing only" part of the file, so we're no longer in
702 if (ActiveCommentLoc.isValid())
703 End = ActiveCommentLoc; // don't truncate a decl comment.
705 End = TheTok.getLocation();
707 return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
708 TheTok.isAtStartOfLine());
711 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
712 /// token, return a new location that specifies a character within the token.
713 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
715 const SourceManager &SM,
716 const LangOptions &LangOpts) {
717 // Figure out how many physical characters away the specified expansion
718 // character is. This needs to take into consideration newlines and
720 bool Invalid = false;
721 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
723 // If they request the first char of the token, we're trivially done.
724 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
727 unsigned PhysOffset = 0;
729 // The usual case is that tokens don't contain anything interesting. Skip
730 // over the uninteresting characters. If a token only consists of simple
731 // chars, this method is extremely fast.
732 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
734 return TokStart.getLocWithOffset(PhysOffset);
740 // If we have a character that may be a trigraph or escaped newline, use a
741 // lexer to parse it correctly.
742 for (; CharNo; --CharNo) {
744 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
749 // Final detail: if we end up on an escaped newline, we want to return the
750 // location of the actual byte of the token. For example foo\<newline>bar
751 // advanced by 3 should return the location of b, not of \\. One compounding
752 // detail of this is that the escape may be made by a trigraph.
753 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
754 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
756 return TokStart.getLocWithOffset(PhysOffset);
759 /// \brief Computes the source location just past the end of the
760 /// token at this source location.
762 /// This routine can be used to produce a source location that
763 /// points just past the end of the token referenced by \p Loc, and
764 /// is generally used when a diagnostic needs to point just after a
765 /// token where it expected something different that it received. If
766 /// the returned source location would not be meaningful (e.g., if
767 /// it points into a macro), this routine returns an invalid
770 /// \param Offset an offset from the end of the token, where the source
771 /// location should refer to. The default offset (0) produces a source
772 /// location pointing just past the end of the token; an offset of 1 produces
773 /// a source location pointing to the last character in the token, etc.
774 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
775 const SourceManager &SM,
776 const LangOptions &LangOpts) {
780 if (Loc.isMacroID()) {
781 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
782 return {}; // Points inside the macro expansion.
785 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
791 return Loc.getLocWithOffset(Len);
794 /// \brief Returns true if the given MacroID location points at the first
795 /// token of the macro expansion.
796 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
797 const SourceManager &SM,
798 const LangOptions &LangOpts,
799 SourceLocation *MacroBegin) {
800 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
802 SourceLocation expansionLoc;
803 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
806 if (expansionLoc.isFileID()) {
807 // No other macro expansions, this is the first.
809 *MacroBegin = expansionLoc;
813 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
816 /// \brief Returns true if the given MacroID location points at the last
817 /// token of the macro expansion.
818 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
819 const SourceManager &SM,
820 const LangOptions &LangOpts,
821 SourceLocation *MacroEnd) {
822 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
824 SourceLocation spellLoc = SM.getSpellingLoc(loc);
825 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
829 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
830 SourceLocation expansionLoc;
831 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
834 if (expansionLoc.isFileID()) {
835 // No other macro expansions.
837 *MacroEnd = expansionLoc;
841 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
844 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
845 const SourceManager &SM,
846 const LangOptions &LangOpts) {
847 SourceLocation Begin = Range.getBegin();
848 SourceLocation End = Range.getEnd();
849 assert(Begin.isFileID() && End.isFileID());
850 if (Range.isTokenRange()) {
851 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
856 // Break down the source locations.
859 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
864 if (!SM.isInFileID(End, FID, &EndOffs) ||
868 return CharSourceRange::getCharRange(Begin, End);
871 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
872 const SourceManager &SM,
873 const LangOptions &LangOpts) {
874 SourceLocation Begin = Range.getBegin();
875 SourceLocation End = Range.getEnd();
876 if (Begin.isInvalid() || End.isInvalid())
879 if (Begin.isFileID() && End.isFileID())
880 return makeRangeFromFileLocs(Range, SM, LangOpts);
882 if (Begin.isMacroID() && End.isFileID()) {
883 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
885 Range.setBegin(Begin);
886 return makeRangeFromFileLocs(Range, SM, LangOpts);
889 if (Begin.isFileID() && End.isMacroID()) {
890 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
892 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
896 return makeRangeFromFileLocs(Range, SM, LangOpts);
899 assert(Begin.isMacroID() && End.isMacroID());
900 SourceLocation MacroBegin, MacroEnd;
901 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
902 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
904 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
906 Range.setBegin(MacroBegin);
907 Range.setEnd(MacroEnd);
908 return makeRangeFromFileLocs(Range, SM, LangOpts);
911 bool Invalid = false;
912 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
917 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
918 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
923 if (EndEntry.getExpansion().isMacroArgExpansion() &&
924 BeginEntry.getExpansion().getExpansionLocStart() ==
925 EndEntry.getExpansion().getExpansionLocStart()) {
926 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
927 Range.setEnd(SM.getImmediateSpellingLoc(End));
928 return makeFileCharRange(Range, SM, LangOpts);
935 StringRef Lexer::getSourceText(CharSourceRange Range,
936 const SourceManager &SM,
937 const LangOptions &LangOpts,
939 Range = makeFileCharRange(Range, SM, LangOpts);
940 if (Range.isInvalid()) {
941 if (Invalid) *Invalid = true;
945 // Break down the source location.
946 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
947 if (beginInfo.first.isInvalid()) {
948 if (Invalid) *Invalid = true;
953 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
954 beginInfo.second > EndOffs) {
955 if (Invalid) *Invalid = true;
959 // Try to the load the file buffer.
960 bool invalidTemp = false;
961 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
963 if (Invalid) *Invalid = true;
967 if (Invalid) *Invalid = false;
968 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
971 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
972 const SourceManager &SM,
973 const LangOptions &LangOpts) {
974 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
976 // Find the location of the immediate macro expansion.
978 FileID FID = SM.getFileID(Loc);
979 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
980 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
981 Loc = Expansion.getExpansionLocStart();
982 if (!Expansion.isMacroArgExpansion())
985 // For macro arguments we need to check that the argument did not come
986 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
988 // Loc points to the argument id of the macro definition, move to the
990 Loc = SM.getImmediateExpansionRange(Loc).first;
991 SourceLocation SpellLoc = Expansion.getSpellingLoc();
992 if (SpellLoc.isFileID())
993 break; // No inner macro.
995 // If spelling location resides in the same FileID as macro expansion
996 // location, it means there is no inner macro.
997 FileID MacroFID = SM.getFileID(Loc);
998 if (SM.isInFileID(SpellLoc, MacroFID))
1001 // Argument came from inner macro.
1005 // Find the spelling location of the start of the non-argument expansion
1006 // range. This is where the macro name was spelled in order to begin
1007 // expanding this macro.
1008 Loc = SM.getSpellingLoc(Loc);
1010 // Dig out the buffer where the macro name was spelled and the extents of the
1011 // name so that we can render it into the expansion note.
1012 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1013 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1014 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1015 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1018 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1019 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1020 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1021 // Walk past macro argument expanions.
1022 while (SM.isMacroArgExpansion(Loc))
1023 Loc = SM.getImmediateExpansionRange(Loc).first;
1025 // If the macro's spelling has no FileID, then it's actually a token paste
1026 // or stringization (or similar) and not a macro at all.
1027 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1030 // Find the spelling location of the start of the non-argument expansion
1031 // range. This is where the macro name was spelled in order to begin
1032 // expanding this macro.
1033 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1035 // Dig out the buffer where the macro name was spelled and the extents of the
1036 // name so that we can render it into the expansion note.
1037 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1038 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1039 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1040 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1043 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1044 return isIdentifierBody(c, LangOpts.DollarIdents);
1047 bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1048 assert(isVerticalWhitespace(Str[0]));
1049 if (Str - 1 < BufferStart)
1052 if ((Str[0] == '\n' && Str[-1] == '\r') ||
1053 (Str[0] == '\r' && Str[-1] == '\n')) {
1054 if (Str - 2 < BufferStart)
1060 // Rewind to first non-space character:
1061 while (Str > BufferStart && isHorizontalWhitespace(*Str))
1064 return *Str == '\\';
1067 StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1068 const SourceManager &SM) {
1069 if (Loc.isInvalid() || Loc.isMacroID())
1071 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1072 if (LocInfo.first.isInvalid())
1074 bool Invalid = false;
1075 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1078 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1081 StringRef Rest = Buffer.substr(Line - Buffer.data());
1082 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1083 return NumWhitespaceChars == StringRef::npos
1085 : Rest.take_front(NumWhitespaceChars);
1088 //===----------------------------------------------------------------------===//
1089 // Diagnostics forwarding code.
1090 //===----------------------------------------------------------------------===//
1092 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1093 /// lexer buffer was all expanded at a single point, perform the mapping.
1094 /// This is currently only used for _Pragma implementation, so it is the slow
1095 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1096 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1097 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1098 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1099 SourceLocation FileLoc,
1100 unsigned CharNo, unsigned TokLen) {
1101 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1103 // Otherwise, we're lexing "mapped tokens". This is used for things like
1104 // _Pragma handling. Combine the expansion location of FileLoc with the
1105 // spelling location.
1106 SourceManager &SM = PP.getSourceManager();
1108 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1109 // characters come from spelling(FileLoc)+Offset.
1110 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1111 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1113 // Figure out the expansion loc range, which is the range covered by the
1114 // original _Pragma(...) sequence.
1115 std::pair<SourceLocation,SourceLocation> II =
1116 SM.getImmediateExpansionRange(FileLoc);
1118 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1121 /// getSourceLocation - Return a source location identifier for the specified
1122 /// offset in the current file.
1123 SourceLocation Lexer::getSourceLocation(const char *Loc,
1124 unsigned TokLen) const {
1125 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1126 "Location out of range for this buffer!");
1128 // In the normal case, we're just lexing from a simple file buffer, return
1129 // the file id from FileLoc with the offset specified.
1130 unsigned CharNo = Loc-BufferStart;
1131 if (FileLoc.isFileID())
1132 return FileLoc.getLocWithOffset(CharNo);
1134 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1135 // tokens are lexed from where the _Pragma was defined.
1136 assert(PP && "This doesn't work on raw lexers");
1137 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1140 /// Diag - Forwarding function for diagnostics. This translate a source
1141 /// position in the current buffer into a SourceLocation object for rendering.
1142 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1143 return PP->Diag(getSourceLocation(Loc), DiagID);
1146 //===----------------------------------------------------------------------===//
1147 // Trigraph and Escaped Newline Handling Code.
1148 //===----------------------------------------------------------------------===//
1150 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1151 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1152 static char GetTrigraphCharForLetter(char Letter) {
1155 case '=': return '#';
1156 case ')': return ']';
1157 case '(': return '[';
1158 case '!': return '|';
1159 case '\'': return '^';
1160 case '>': return '}';
1161 case '/': return '\\';
1162 case '<': return '{';
1163 case '-': return '~';
1167 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1168 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1169 /// return the result character. Finally, emit a warning about trigraph use
1170 /// whether trigraphs are enabled or not.
1171 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1172 char Res = GetTrigraphCharForLetter(*CP);
1173 if (!Res || !L) return Res;
1175 if (!L->getLangOpts().Trigraphs) {
1176 if (!L->isLexingRawMode())
1177 L->Diag(CP-2, diag::trigraph_ignored);
1181 if (!L->isLexingRawMode())
1182 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1186 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1187 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1188 /// trigraph equivalent on entry to this function.
1189 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1191 while (isWhitespace(Ptr[Size])) {
1194 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1197 // If this is a \r\n or \n\r, skip the other half.
1198 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1199 Ptr[Size-1] != Ptr[Size])
1205 // Not an escaped newline, must be a \t or something else.
1209 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1210 /// them), skip over them and return the first non-escaped-newline found,
1211 /// otherwise return P.
1212 const char *Lexer::SkipEscapedNewLines(const char *P) {
1214 const char *AfterEscape;
1217 } else if (*P == '?') {
1218 // If not a trigraph for escape, bail out.
1219 if (P[1] != '?' || P[2] != '/')
1221 // FIXME: Take LangOpts into account; the language might not
1222 // support trigraphs.
1228 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1229 if (NewLineSize == 0) return P;
1230 P = AfterEscape+NewLineSize;
1234 Optional<Token> Lexer::findNextToken(SourceLocation Loc,
1235 const SourceManager &SM,
1236 const LangOptions &LangOpts) {
1237 if (Loc.isMacroID()) {
1238 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1241 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1243 // Break down the source location.
1244 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1246 // Try to load the file buffer.
1247 bool InvalidTemp = false;
1248 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1252 const char *TokenBegin = File.data() + LocInfo.second;
1254 // Lex from the start of the given location.
1255 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1256 TokenBegin, File.end());
1259 lexer.LexFromRawLexer(Tok);
1263 /// \brief Checks that the given token is the first token that occurs after the
1264 /// given location (this excludes comments and whitespace). Returns the location
1265 /// immediately after the specified token. If the token is not found or the
1266 /// location is inside a macro, the returned source location will be invalid.
1267 SourceLocation Lexer::findLocationAfterToken(
1268 SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1269 const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1270 Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1271 if (!Tok || Tok->isNot(TKind))
1273 SourceLocation TokenLoc = Tok->getLocation();
1275 // Calculate how much whitespace needs to be skipped if any.
1276 unsigned NumWhitespaceChars = 0;
1277 if (SkipTrailingWhitespaceAndNewLine) {
1278 const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
1279 unsigned char C = *TokenEnd;
1280 while (isHorizontalWhitespace(C)) {
1282 NumWhitespaceChars++;
1285 // Skip \r, \n, \r\n, or \n\r
1286 if (C == '\n' || C == '\r') {
1289 NumWhitespaceChars++;
1290 if ((C == '\n' || C == '\r') && C != PrevC)
1291 NumWhitespaceChars++;
1295 return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
1298 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1299 /// get its size, and return it. This is tricky in several cases:
1300 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1301 /// then either return the trigraph (skipping 3 chars) or the '?',
1302 /// depending on whether trigraphs are enabled or not.
1303 /// 2. If this is an escaped newline (potentially with whitespace between
1304 /// the backslash and newline), implicitly skip the newline and return
1305 /// the char after it.
1307 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1308 /// know that we can accumulate into Size, and that we have already incremented
1309 /// Ptr by Size bytes.
1311 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1312 /// be updated to match.
1313 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1315 // If we have a slash, look for an escaped newline.
1316 if (Ptr[0] == '\\') {
1320 // Common case, backslash-char where the char is not whitespace.
1321 if (!isWhitespace(Ptr[0])) return '\\';
1323 // See if we have optional whitespace characters between the slash and
1325 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1326 // Remember that this token needs to be cleaned.
1327 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1329 // Warn if there was whitespace between the backslash and newline.
1330 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1331 Diag(Ptr, diag::backslash_newline_space);
1333 // Found backslash<whitespace><newline>. Parse the char after it.
1334 Size += EscapedNewLineSize;
1335 Ptr += EscapedNewLineSize;
1337 // Use slow version to accumulate a correct size field.
1338 return getCharAndSizeSlow(Ptr, Size, Tok);
1341 // Otherwise, this is not an escaped newline, just return the slash.
1345 // If this is a trigraph, process it.
1346 if (Ptr[0] == '?' && Ptr[1] == '?') {
1347 // If this is actually a legal trigraph (not something like "??x"), emit
1348 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1349 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1350 // Remember that this token needs to be cleaned.
1351 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1355 if (C == '\\') goto Slash;
1360 // If this is neither, return a single character.
1365 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1366 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1367 /// and that we have already incremented Ptr by Size bytes.
1369 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1370 /// be updated to match.
1371 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1372 const LangOptions &LangOpts) {
1373 // If we have a slash, look for an escaped newline.
1374 if (Ptr[0] == '\\') {
1378 // Common case, backslash-char where the char is not whitespace.
1379 if (!isWhitespace(Ptr[0])) return '\\';
1381 // See if we have optional whitespace characters followed by a newline.
1382 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1383 // Found backslash<whitespace><newline>. Parse the char after it.
1384 Size += EscapedNewLineSize;
1385 Ptr += EscapedNewLineSize;
1387 // Use slow version to accumulate a correct size field.
1388 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1391 // Otherwise, this is not an escaped newline, just return the slash.
1395 // If this is a trigraph, process it.
1396 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1397 // If this is actually a legal trigraph (not something like "??x"), return
1399 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1402 if (C == '\\') goto Slash;
1407 // If this is neither, return a single character.
1412 //===----------------------------------------------------------------------===//
1413 // Helper methods for lexing.
1414 //===----------------------------------------------------------------------===//
1416 /// \brief Routine that indiscriminately sets the offset into the source file.
1417 void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1418 BufferPtr = BufferStart + Offset;
1419 if (BufferPtr > BufferEnd)
1420 BufferPtr = BufferEnd;
1421 // FIXME: What exactly does the StartOfLine bit mean? There are two
1422 // possible meanings for the "start" of the line: the first token on the
1423 // unexpanded line, or the first token on the expanded line.
1424 IsAtStartOfLine = StartOfLine;
1425 IsAtPhysicalStartOfLine = StartOfLine;
1428 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1429 if (LangOpts.AsmPreprocessor) {
1431 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1432 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1433 C11AllowedIDCharRanges);
1434 return C11AllowedIDChars.contains(C);
1435 } else if (LangOpts.CPlusPlus) {
1436 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1437 CXX03AllowedIDCharRanges);
1438 return CXX03AllowedIDChars.contains(C);
1440 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1441 C99AllowedIDCharRanges);
1442 return C99AllowedIDChars.contains(C);
1446 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1447 assert(isAllowedIDChar(C, LangOpts));
1448 if (LangOpts.AsmPreprocessor) {
1450 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1451 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1452 C11DisallowedInitialIDCharRanges);
1453 return !C11DisallowedInitialIDChars.contains(C);
1454 } else if (LangOpts.CPlusPlus) {
1457 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1458 C99DisallowedInitialIDCharRanges);
1459 return !C99DisallowedInitialIDChars.contains(C);
1463 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1465 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1466 L.getSourceLocation(End));
1469 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1470 CharSourceRange Range, bool IsFirst) {
1471 // Check C99 compatibility.
1472 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1474 CannotAppearInIdentifier = 0,
1475 CannotStartIdentifier
1478 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1479 C99AllowedIDCharRanges);
1480 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1481 C99DisallowedInitialIDCharRanges);
1482 if (!C99AllowedIDChars.contains(C)) {
1483 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1485 << CannotAppearInIdentifier;
1486 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1487 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1489 << CannotStartIdentifier;
1493 // Check C++98 compatibility.
1494 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1495 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1496 CXX03AllowedIDCharRanges);
1497 if (!CXX03AllowedIDChars.contains(C)) {
1498 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1504 /// After encountering UTF-8 character C and interpreting it as an identifier
1505 /// character, check whether it's a homoglyph for a common non-identifier
1506 /// source character that is unlikely to be an intentional identifier
1507 /// character and warn if so.
1508 static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C,
1509 CharSourceRange Range) {
1510 // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
1511 struct HomoglyphPair {
1514 bool operator<(HomoglyphPair R) const { return Character < R.Character; }
1516 static constexpr HomoglyphPair SortedHomoglyphs[] = {
1517 {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1518 {U'\u037e', ';'}, // GREEK QUESTION MARK
1519 {U'\u2212', '-'}, // MINUS SIGN
1520 {U'\u2215', '/'}, // DIVISION SLASH
1521 {U'\u2216', '\\'}, // SET MINUS
1522 {U'\u2217', '*'}, // ASTERISK OPERATOR
1523 {U'\u2223', '|'}, // DIVIDES
1524 {U'\u2227', '^'}, // LOGICAL AND
1525 {U'\u2236', ':'}, // RATIO
1526 {U'\u223c', '~'}, // TILDE OPERATOR
1527 {U'\ua789', ':'}, // MODIFIER LETTER COLON
1528 {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1529 {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1530 {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1531 {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1532 {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1533 {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1534 {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1535 {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1536 {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1537 {U'\uff0c', ','}, // FULLWIDTH COMMA
1538 {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1539 {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1540 {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1541 {U'\uff1a', ':'}, // FULLWIDTH COLON
1542 {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1543 {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1544 {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1545 {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1546 {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1547 {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1548 {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1549 {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1550 {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1551 {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1552 {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1553 {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1554 {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1555 {U'\uff5e', '~'}, // FULLWIDTH TILDE
1559 std::lower_bound(std::begin(SortedHomoglyphs),
1560 std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1561 if (Homoglyph->Character == C) {
1562 llvm::SmallString<5> CharBuf;
1564 llvm::raw_svector_ostream CharOS(CharBuf);
1565 llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1567 const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1568 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1569 << Range << CharBuf << LooksLikeStr;
1573 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1575 const char *UCNPtr = CurPtr + Size;
1576 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1577 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1580 if (!isLexingRawMode())
1581 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1582 makeCharRange(*this, CurPtr, UCNPtr),
1585 Result.setFlag(Token::HasUCN);
1586 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1587 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1590 while (CurPtr != UCNPtr)
1591 (void)getAndAdvanceChar(CurPtr, Result);
1595 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1596 const char *UnicodePtr = CurPtr;
1597 llvm::UTF32 CodePoint;
1598 llvm::ConversionResult Result =
1599 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1600 (const llvm::UTF8 *)BufferEnd,
1602 llvm::strictConversion);
1603 if (Result != llvm::conversionOK ||
1604 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1607 if (!isLexingRawMode()) {
1608 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1609 makeCharRange(*this, CurPtr, UnicodePtr),
1611 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
1612 makeCharRange(*this, CurPtr, UnicodePtr));
1615 CurPtr = UnicodePtr;
1619 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1620 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1622 unsigned char C = *CurPtr++;
1623 while (isIdentifierBody(C))
1626 --CurPtr; // Back up over the skipped character.
1628 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1629 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1631 // TODO: Could merge these checks into an InfoTable flag to make the
1632 // comparison cheaper
1633 if (isASCII(C) && C != '\\' && C != '?' &&
1634 (C != '$' || !LangOpts.DollarIdents)) {
1636 const char *IdStart = BufferPtr;
1637 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1638 Result.setRawIdentifierData(IdStart);
1640 // If we are in raw mode, return this identifier raw. There is no need to
1641 // look up identifier information or attempt to macro expand it.
1645 // Fill in Result.IdentifierInfo and update the token kind,
1646 // looking up the identifier in the identifier table.
1647 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1649 // Finally, now that we know we have an identifier, pass this off to the
1650 // preprocessor, which may macro expand it or something.
1651 if (II->isHandleIdentifierCase())
1652 return PP->HandleIdentifier(Result);
1654 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1655 && II->getPPKeywordID() == tok::pp_not_keyword
1656 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1657 // Return the code-completion token.
1658 Result.setKind(tok::code_completion);
1665 // Otherwise, $,\,? in identifier found. Enter slower path.
1667 C = getCharAndSize(CurPtr, Size);
1670 // If we hit a $ and they are not supported in identifiers, we are done.
1671 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1673 // Otherwise, emit a diagnostic and continue.
1674 if (!isLexingRawMode())
1675 Diag(CurPtr, diag::ext_dollar_in_identifier);
1676 CurPtr = ConsumeChar(CurPtr, Size, Result);
1677 C = getCharAndSize(CurPtr, Size);
1679 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1680 C = getCharAndSize(CurPtr, Size);
1682 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1683 C = getCharAndSize(CurPtr, Size);
1685 } else if (!isIdentifierBody(C)) {
1686 goto FinishIdentifier;
1689 // Otherwise, this character is good, consume it.
1690 CurPtr = ConsumeChar(CurPtr, Size, Result);
1692 C = getCharAndSize(CurPtr, Size);
1693 while (isIdentifierBody(C)) {
1694 CurPtr = ConsumeChar(CurPtr, Size, Result);
1695 C = getCharAndSize(CurPtr, Size);
1700 /// isHexaLiteral - Return true if Start points to a hex constant.
1701 /// in microsoft mode (where this is supposed to be several different tokens).
1702 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1704 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1707 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1708 return (C2 == 'x' || C2 == 'X');
1711 /// LexNumericConstant - Lex the remainder of a integer or floating point
1712 /// constant. From[-1] is the first character lexed. Return the end of the
1714 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1716 char C = getCharAndSize(CurPtr, Size);
1718 while (isPreprocessingNumberBody(C)) {
1719 CurPtr = ConsumeChar(CurPtr, Size, Result);
1721 C = getCharAndSize(CurPtr, Size);
1724 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1725 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1726 // If we are in Microsoft mode, don't continue if the constant is hex.
1727 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1728 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1729 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1732 // If we have a hex FP constant, continue.
1733 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1734 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1735 // not-quite-conforming extension. Only do so if this looks like it's
1736 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1737 bool IsHexFloat = true;
1738 if (!LangOpts.C99) {
1739 if (!isHexaLiteral(BufferPtr, LangOpts))
1741 else if (!getLangOpts().CPlusPlus17 &&
1742 std::find(BufferPtr, CurPtr, '_') != CurPtr)
1746 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1749 // If we have a digit separator, continue.
1750 if (C == '\'' && getLangOpts().CPlusPlus14) {
1752 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1753 if (isIdentifierBody(Next)) {
1754 if (!isLexingRawMode())
1755 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1756 CurPtr = ConsumeChar(CurPtr, Size, Result);
1757 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1758 return LexNumericConstant(Result, CurPtr);
1762 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1763 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1764 return LexNumericConstant(Result, CurPtr);
1765 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1766 return LexNumericConstant(Result, CurPtr);
1768 // Update the location of token as well as BufferPtr.
1769 const char *TokStart = BufferPtr;
1770 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1771 Result.setLiteralData(TokStart);
1775 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1776 /// in C++11, or warn on a ud-suffix in C++98.
1777 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1778 bool IsStringLiteral) {
1779 assert(getLangOpts().CPlusPlus);
1781 // Maximally munch an identifier.
1783 char C = getCharAndSize(CurPtr, Size);
1784 bool Consumed = false;
1786 if (!isIdentifierHead(C)) {
1787 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1789 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1795 if (!getLangOpts().CPlusPlus11) {
1796 if (!isLexingRawMode())
1798 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1799 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1800 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1804 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1805 // that does not start with an underscore is ill-formed. As a conforming
1806 // extension, we treat all such suffixes as if they had whitespace before
1807 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1808 // likely to be a ud-suffix than a macro, however, and accept that.
1810 bool IsUDSuffix = false;
1813 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1814 // In C++1y, we need to look ahead a few characters to see if this is a
1815 // valid suffix for a string literal or a numeric literal (this could be
1816 // the 'operator""if' defining a numeric literal operator).
1817 const unsigned MaxStandardSuffixLength = 3;
1818 char Buffer[MaxStandardSuffixLength] = { C };
1819 unsigned Consumed = Size;
1823 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1825 if (!isIdentifierBody(Next)) {
1826 // End of suffix. Check whether this is on the whitelist.
1827 const StringRef CompleteSuffix(Buffer, Chars);
1828 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1833 if (Chars == MaxStandardSuffixLength)
1834 // Too long: can't be a standard suffix.
1837 Buffer[Chars++] = Next;
1838 Consumed += NextSize;
1843 if (!isLexingRawMode())
1844 Diag(CurPtr, getLangOpts().MSVCCompat
1845 ? diag::ext_ms_reserved_user_defined_literal
1846 : diag::ext_reserved_user_defined_literal)
1847 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1851 CurPtr = ConsumeChar(CurPtr, Size, Result);
1854 Result.setFlag(Token::HasUDSuffix);
1856 C = getCharAndSize(CurPtr, Size);
1857 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1858 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1859 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1866 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1867 /// either " or L" or u8" or u" or U".
1868 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1869 tok::TokenKind Kind) {
1870 // Does this string contain the \0 character?
1871 const char *NulCharacter = nullptr;
1873 if (!isLexingRawMode() &&
1874 (Kind == tok::utf8_string_literal ||
1875 Kind == tok::utf16_string_literal ||
1876 Kind == tok::utf32_string_literal))
1877 Diag(BufferPtr, getLangOpts().CPlusPlus
1878 ? diag::warn_cxx98_compat_unicode_literal
1879 : diag::warn_c99_compat_unicode_literal);
1881 char C = getAndAdvanceChar(CurPtr, Result);
1883 // Skip escaped characters. Escaped newlines will already be processed by
1884 // getAndAdvanceChar.
1886 C = getAndAdvanceChar(CurPtr, Result);
1888 if (C == '\n' || C == '\r' || // Newline.
1889 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1890 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1891 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1892 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1897 if (isCodeCompletionPoint(CurPtr-1)) {
1898 PP->CodeCompleteNaturalLanguage();
1899 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1904 NulCharacter = CurPtr-1;
1906 C = getAndAdvanceChar(CurPtr, Result);
1909 // If we are in C++11, lex the optional ud-suffix.
1910 if (getLangOpts().CPlusPlus)
1911 CurPtr = LexUDSuffix(Result, CurPtr, true);
1913 // If a nul character existed in the string, warn about it.
1914 if (NulCharacter && !isLexingRawMode())
1915 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1917 // Update the location of the token as well as the BufferPtr instance var.
1918 const char *TokStart = BufferPtr;
1919 FormTokenWithChars(Result, CurPtr, Kind);
1920 Result.setLiteralData(TokStart);
1924 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1925 /// having lexed R", LR", u8R", uR", or UR".
1926 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1927 tok::TokenKind Kind) {
1928 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1929 // Between the initial and final double quote characters of the raw string,
1930 // any transformations performed in phases 1 and 2 (trigraphs,
1931 // universal-character-names, and line splicing) are reverted.
1933 if (!isLexingRawMode())
1934 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1936 unsigned PrefixLen = 0;
1938 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1941 // If the last character was not a '(', then we didn't lex a valid delimiter.
1942 if (CurPtr[PrefixLen] != '(') {
1943 if (!isLexingRawMode()) {
1944 const char *PrefixEnd = &CurPtr[PrefixLen];
1945 if (PrefixLen == 16) {
1946 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1948 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1949 << StringRef(PrefixEnd, 1);
1953 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1954 // it's possible the '"' was intended to be part of the raw string, but
1955 // there's not much we can do about that.
1961 if (C == 0 && CurPtr-1 == BufferEnd) {
1967 FormTokenWithChars(Result, CurPtr, tok::unknown);
1971 // Save prefix and move CurPtr past it
1972 const char *Prefix = CurPtr;
1973 CurPtr += PrefixLen + 1; // skip over prefix and '('
1979 // Check for prefix match and closing quote.
1980 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1981 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1984 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1985 if (!isLexingRawMode())
1986 Diag(BufferPtr, diag::err_unterminated_raw_string)
1987 << StringRef(Prefix, PrefixLen);
1988 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1993 // If we are in C++11, lex the optional ud-suffix.
1994 if (getLangOpts().CPlusPlus)
1995 CurPtr = LexUDSuffix(Result, CurPtr, true);
1997 // Update the location of token as well as BufferPtr.
1998 const char *TokStart = BufferPtr;
1999 FormTokenWithChars(Result, CurPtr, Kind);
2000 Result.setLiteralData(TokStart);
2004 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2005 /// after having lexed the '<' character. This is used for #include filenames.
2006 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
2007 // Does this string contain the \0 character?
2008 const char *NulCharacter = nullptr;
2009 const char *AfterLessPos = CurPtr;
2010 char C = getAndAdvanceChar(CurPtr, Result);
2012 // Skip escaped characters. Escaped newlines will already be processed by
2013 // getAndAdvanceChar.
2015 C = getAndAdvanceChar(CurPtr, Result);
2017 if (C == '\n' || C == '\r' || // Newline.
2018 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
2019 isCodeCompletionPoint(CurPtr-1)))) {
2020 // If the filename is unterminated, then it must just be a lone <
2021 // character. Return this as such.
2022 FormTokenWithChars(Result, AfterLessPos, tok::less);
2027 NulCharacter = CurPtr-1;
2029 C = getAndAdvanceChar(CurPtr, Result);
2032 // If a nul character existed in the string, warn about it.
2033 if (NulCharacter && !isLexingRawMode())
2034 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2036 // Update the location of token as well as BufferPtr.
2037 const char *TokStart = BufferPtr;
2038 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
2039 Result.setLiteralData(TokStart);
2043 /// LexCharConstant - Lex the remainder of a character constant, after having
2044 /// lexed either ' or L' or u8' or u' or U'.
2045 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
2046 tok::TokenKind Kind) {
2047 // Does this character contain the \0 character?
2048 const char *NulCharacter = nullptr;
2050 if (!isLexingRawMode()) {
2051 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
2052 Diag(BufferPtr, getLangOpts().CPlusPlus
2053 ? diag::warn_cxx98_compat_unicode_literal
2054 : diag::warn_c99_compat_unicode_literal);
2055 else if (Kind == tok::utf8_char_constant)
2056 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
2059 char C = getAndAdvanceChar(CurPtr, Result);
2061 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2062 Diag(BufferPtr, diag::ext_empty_character);
2063 FormTokenWithChars(Result, CurPtr, tok::unknown);
2068 // Skip escaped characters.
2070 C = getAndAdvanceChar(CurPtr, Result);
2072 if (C == '\n' || C == '\r' || // Newline.
2073 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
2074 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2075 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
2076 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2081 if (isCodeCompletionPoint(CurPtr-1)) {
2082 PP->CodeCompleteNaturalLanguage();
2083 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2088 NulCharacter = CurPtr-1;
2090 C = getAndAdvanceChar(CurPtr, Result);
2093 // If we are in C++11, lex the optional ud-suffix.
2094 if (getLangOpts().CPlusPlus)
2095 CurPtr = LexUDSuffix(Result, CurPtr, false);
2097 // If a nul character existed in the character, warn about it.
2098 if (NulCharacter && !isLexingRawMode())
2099 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2101 // Update the location of token as well as BufferPtr.
2102 const char *TokStart = BufferPtr;
2103 FormTokenWithChars(Result, CurPtr, Kind);
2104 Result.setLiteralData(TokStart);
2108 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2109 /// Update BufferPtr to point to the next non-whitespace character and return.
2111 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2112 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2113 bool &TokAtPhysicalStartOfLine) {
2114 // Whitespace - Skip it, then return the token after the whitespace.
2115 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2117 unsigned char Char = *CurPtr;
2119 // Skip consecutive spaces efficiently.
2121 // Skip horizontal whitespace very aggressively.
2122 while (isHorizontalWhitespace(Char))
2125 // Otherwise if we have something other than whitespace, we're done.
2126 if (!isVerticalWhitespace(Char))
2129 if (ParsingPreprocessorDirective) {
2130 // End of preprocessor directive line, let LexTokenInternal handle this.
2135 // OK, but handle newline.
2140 // If the client wants us to return whitespace, return it now.
2141 if (isKeepWhitespaceMode()) {
2142 FormTokenWithChars(Result, CurPtr, tok::unknown);
2144 IsAtStartOfLine = true;
2145 IsAtPhysicalStartOfLine = true;
2147 // FIXME: The next token will not have LeadingSpace set.
2151 // If this isn't immediately after a newline, there is leading space.
2152 char PrevChar = CurPtr[-1];
2153 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2155 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2157 Result.setFlag(Token::StartOfLine);
2158 TokAtPhysicalStartOfLine = true;
2165 /// We have just read the // characters from input. Skip until we find the
2166 /// newline character thats terminate the comment. Then update BufferPtr and
2169 /// If we're in KeepCommentMode or any CommentHandler has inserted
2170 /// some tokens, this will store the first token and return true.
2171 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2172 bool &TokAtPhysicalStartOfLine) {
2173 // If Line comments aren't explicitly enabled for this language, emit an
2174 // extension warning.
2175 if (!LangOpts.LineComment && !isLexingRawMode()) {
2176 Diag(BufferPtr, diag::ext_line_comment);
2178 // Mark them enabled so we only emit one warning for this translation
2180 LangOpts.LineComment = true;
2183 // Scan over the body of the comment. The common case, when scanning, is that
2184 // the comment contains normal ascii characters with nothing interesting in
2185 // them. As such, optimize for this case with the inner loop.
2187 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2188 // character that ends the line comment.
2192 // Skip over characters in the fast loop.
2193 while (C != 0 && // Potentially EOF.
2194 C != '\n' && C != '\r') // Newline or DOS-style newline.
2197 const char *NextLine = CurPtr;
2199 // We found a newline, see if it's escaped.
2200 const char *EscapePtr = CurPtr-1;
2201 bool HasSpace = false;
2202 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2207 if (*EscapePtr == '\\')
2210 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2211 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2212 // Trigraph-escaped newline.
2213 CurPtr = EscapePtr-2;
2215 break; // This is a newline, we're done.
2217 // If there was space between the backslash and newline, warn about it.
2218 if (HasSpace && !isLexingRawMode())
2219 Diag(EscapePtr, diag::backslash_newline_space);
2222 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2223 // properly decode the character. Read it in raw mode to avoid emitting
2224 // diagnostics about things like trigraphs. If we see an escaped newline,
2225 // we'll handle it below.
2226 const char *OldPtr = CurPtr;
2227 bool OldRawMode = isLexingRawMode();
2228 LexingRawMode = true;
2229 C = getAndAdvanceChar(CurPtr, Result);
2230 LexingRawMode = OldRawMode;
2232 // If we only read only one character, then no special handling is needed.
2233 // We're done and can skip forward to the newline.
2234 if (C != 0 && CurPtr == OldPtr+1) {
2239 // If we read multiple characters, and one of those characters was a \r or
2240 // \n, then we had an escaped newline within the comment. Emit diagnostic
2241 // unless the next line is also a // comment.
2242 if (CurPtr != OldPtr + 1 && C != '/' &&
2243 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
2244 for (; OldPtr != CurPtr; ++OldPtr)
2245 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2246 // Okay, we found a // comment that ends in a newline, if the next
2247 // line is also a // comment, but has spaces, don't emit a diagnostic.
2248 if (isWhitespace(C)) {
2249 const char *ForwardPtr = CurPtr;
2250 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2252 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2256 if (!isLexingRawMode())
2257 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2262 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2267 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2268 PP->CodeCompleteNaturalLanguage();
2274 // Found but did not consume the newline. Notify comment handlers about the
2275 // comment unless we're in a #if 0 block.
2276 if (PP && !isLexingRawMode() &&
2277 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2278 getSourceLocation(CurPtr)))) {
2280 return true; // A token has to be returned.
2283 // If we are returning comments as tokens, return this comment as a token.
2284 if (inKeepCommentMode())
2285 return SaveLineComment(Result, CurPtr);
2287 // If we are inside a preprocessor directive and we see the end of line,
2288 // return immediately, so that the lexer can return this as an EOD token.
2289 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2294 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2295 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2296 // contribute to another token), it isn't needed for correctness. Note that
2297 // this is ok even in KeepWhitespaceMode, because we would have returned the
2298 /// comment above in that mode.
2301 // The next returned token is at the start of the line.
2302 Result.setFlag(Token::StartOfLine);
2303 TokAtPhysicalStartOfLine = true;
2304 // No leading whitespace seen so far.
2305 Result.clearFlag(Token::LeadingSpace);
2310 /// If in save-comment mode, package up this Line comment in an appropriate
2311 /// way and return it.
2312 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2313 // If we're not in a preprocessor directive, just return the // comment
2315 FormTokenWithChars(Result, CurPtr, tok::comment);
2317 if (!ParsingPreprocessorDirective || LexingRawMode)
2320 // If this Line-style comment is in a macro definition, transmogrify it into
2321 // a C-style block comment.
2322 bool Invalid = false;
2323 std::string Spelling = PP->getSpelling(Result, &Invalid);
2327 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2328 Spelling[1] = '*'; // Change prefix to "/*".
2329 Spelling += "*/"; // add suffix.
2331 Result.setKind(tok::comment);
2332 PP->CreateString(Spelling, Result,
2333 Result.getLocation(), Result.getLocation());
2337 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2338 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2339 /// a diagnostic if so. We know that the newline is inside of a block comment.
2340 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2342 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2344 // Back up off the newline.
2347 // If this is a two-character newline sequence, skip the other character.
2348 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2349 // \n\n or \r\r -> not escaped newline.
2350 if (CurPtr[0] == CurPtr[1])
2352 // \n\r or \r\n -> skip the newline.
2356 // If we have horizontal whitespace, skip over it. We allow whitespace
2357 // between the slash and newline.
2358 bool HasSpace = false;
2359 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2364 // If we have a slash, we know this is an escaped newline.
2365 if (*CurPtr == '\\') {
2366 if (CurPtr[-1] != '*') return false;
2368 // It isn't a slash, is it the ?? / trigraph?
2369 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2373 // This is the trigraph ending the comment. Emit a stern warning!
2376 // If no trigraphs are enabled, warn that we ignored this trigraph and
2377 // ignore this * character.
2378 if (!L->getLangOpts().Trigraphs) {
2379 if (!L->isLexingRawMode())
2380 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2383 if (!L->isLexingRawMode())
2384 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2387 // Warn about having an escaped newline between the */ characters.
2388 if (!L->isLexingRawMode())
2389 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2391 // If there was space between the backslash and newline, warn about it.
2392 if (HasSpace && !L->isLexingRawMode())
2393 L->Diag(CurPtr, diag::backslash_newline_space);
2399 #include <emmintrin.h>
2401 #include <altivec.h>
2405 /// We have just read from input the / and * characters that started a comment.
2406 /// Read until we find the * and / characters that terminate the comment.
2407 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2408 /// comments, because they cannot cause the comment to end. The only thing
2409 /// that can happen is the comment could end with an escaped newline between
2410 /// the terminating * and /.
2412 /// If we're in KeepCommentMode or any CommentHandler has inserted
2413 /// some tokens, this will store the first token and return true.
2414 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2415 bool &TokAtPhysicalStartOfLine) {
2416 // Scan one character past where we should, looking for a '/' character. Once
2417 // we find it, check to see if it was preceded by a *. This common
2418 // optimization helps people who like to put a lot of * characters in their
2421 // The first character we get with newlines and trigraphs skipped to handle
2422 // the degenerate /*/ case below correctly if the * has an escaped newline
2425 unsigned char C = getCharAndSize(CurPtr, CharSize);
2427 if (C == 0 && CurPtr == BufferEnd+1) {
2428 if (!isLexingRawMode())
2429 Diag(BufferPtr, diag::err_unterminated_block_comment);
2432 // KeepWhitespaceMode should return this broken comment as a token. Since
2433 // it isn't a well formed comment, just return it as an 'unknown' token.
2434 if (isKeepWhitespaceMode()) {
2435 FormTokenWithChars(Result, CurPtr, tok::unknown);
2443 // Check to see if the first character after the '/*' is another /. If so,
2444 // then this slash does not end the block comment, it is part of it.
2449 // Skip over all non-interesting characters until we find end of buffer or a
2450 // (probably ending) '/' character.
2451 if (CurPtr + 24 < BufferEnd &&
2452 // If there is a code-completion point avoid the fast scan because it
2453 // doesn't check for '\0'.
2454 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2455 // While not aligned to a 16-byte boundary.
2456 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2459 if (C == '/') goto FoundSlash;
2462 __m128i Slashes = _mm_set1_epi8('/');
2463 while (CurPtr+16 <= BufferEnd) {
2464 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2467 // Adjust the pointer to point directly after the first slash. It's
2468 // not necessary to set C here, it will be overwritten at the end of
2470 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2476 __vector unsigned char Slashes = {
2477 '/', '/', '/', '/', '/', '/', '/', '/',
2478 '/', '/', '/', '/', '/', '/', '/', '/'
2480 while (CurPtr+16 <= BufferEnd &&
2481 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2484 // Scan for '/' quickly. Many block comments are very large.
2485 while (CurPtr[0] != '/' &&
2489 CurPtr+4 < BufferEnd) {
2494 // It has to be one of the bytes scanned, increment to it and read one.
2498 // Loop to scan the remainder.
2499 while (C != '/' && C != '\0')
2504 if (CurPtr[-2] == '*') // We found the final */. We're done!
2507 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2508 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2509 // We found the final */, though it had an escaped newline between the
2510 // * and /. We're done!
2514 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2515 // If this is a /* inside of the comment, emit a warning. Don't do this
2516 // if this is a /*/, which will end the comment. This misses cases with
2517 // embedded escaped newlines, but oh well.
2518 if (!isLexingRawMode())
2519 Diag(CurPtr-1, diag::warn_nested_block_comment);
2521 } else if (C == 0 && CurPtr == BufferEnd+1) {
2522 if (!isLexingRawMode())
2523 Diag(BufferPtr, diag::err_unterminated_block_comment);
2524 // Note: the user probably forgot a */. We could continue immediately
2525 // after the /*, but this would involve lexing a lot of what really is the
2526 // comment, which surely would confuse the parser.
2529 // KeepWhitespaceMode should return this broken comment as a token. Since
2530 // it isn't a well formed comment, just return it as an 'unknown' token.
2531 if (isKeepWhitespaceMode()) {
2532 FormTokenWithChars(Result, CurPtr, tok::unknown);
2538 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2539 PP->CodeCompleteNaturalLanguage();
2547 // Notify comment handlers about the comment unless we're in a #if 0 block.
2548 if (PP && !isLexingRawMode() &&
2549 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2550 getSourceLocation(CurPtr)))) {
2552 return true; // A token has to be returned.
2555 // If we are returning comments as tokens, return this comment as a token.
2556 if (inKeepCommentMode()) {
2557 FormTokenWithChars(Result, CurPtr, tok::comment);
2561 // It is common for the tokens immediately after a /**/ comment to be
2562 // whitespace. Instead of going through the big switch, handle it
2563 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2564 // have already returned above with the comment as a token.
2565 if (isHorizontalWhitespace(*CurPtr)) {
2566 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2570 // Otherwise, just return so that the next character will be lexed as a token.
2572 Result.setFlag(Token::LeadingSpace);
2576 //===----------------------------------------------------------------------===//
2577 // Primary Lexing Entry Points
2578 //===----------------------------------------------------------------------===//
2580 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2581 /// uninterpreted string. This switches the lexer out of directive mode.
2582 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2583 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2584 "Must be in a preprocessing directive!");
2587 // CurPtr - Cache BufferPtr in an automatic variable.
2588 const char *CurPtr = BufferPtr;
2590 char Char = getAndAdvanceChar(CurPtr, Tmp);
2594 Result->push_back(Char);
2597 // Found end of file?
2598 if (CurPtr-1 != BufferEnd) {
2599 if (isCodeCompletionPoint(CurPtr-1)) {
2600 PP->CodeCompleteNaturalLanguage();
2605 // Nope, normal character, continue.
2607 Result->push_back(Char);
2614 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2615 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2616 BufferPtr = CurPtr-1;
2618 // Next, lex the character, which should handle the EOD transition.
2620 if (Tmp.is(tok::code_completion)) {
2622 PP->CodeCompleteNaturalLanguage();
2625 assert(Tmp.is(tok::eod) && "Unexpected token!");
2627 // Finally, we're done;
2633 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2634 /// condition, reporting diagnostics and handling other edge cases as required.
2635 /// This returns true if Result contains a token, false if PP.Lex should be
2637 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2638 // If we hit the end of the file while parsing a preprocessor directive,
2639 // end the preprocessor directive first. The next token returned will
2640 // then be the end of file.
2641 if (ParsingPreprocessorDirective) {
2642 // Done parsing the "line".
2643 ParsingPreprocessorDirective = false;
2644 // Update the location of token as well as BufferPtr.
2645 FormTokenWithChars(Result, CurPtr, tok::eod);
2647 // Restore comment saving mode, in case it was disabled for directive.
2649 resetExtendedTokenMode();
2650 return true; // Have a token.
2653 // If we are in raw mode, return this event as an EOF token. Let the caller
2654 // that put us in raw mode handle the event.
2655 if (isLexingRawMode()) {
2656 Result.startToken();
2657 BufferPtr = BufferEnd;
2658 FormTokenWithChars(Result, BufferEnd, tok::eof);
2662 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
2663 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2664 ConditionalStack.clear();
2667 // Issue diagnostics for unterminated #if and missing newline.
2669 // If we are in a #if directive, emit an error.
2670 while (!ConditionalStack.empty()) {
2671 if (PP->getCodeCompletionFileLoc() != FileLoc)
2672 PP->Diag(ConditionalStack.back().IfLoc,
2673 diag::err_pp_unterminated_conditional);
2674 ConditionalStack.pop_back();
2677 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2679 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2680 DiagnosticsEngine &Diags = PP->getDiagnostics();
2681 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2684 if (LangOpts.CPlusPlus11) {
2685 // C++11 [lex.phases] 2.2 p2
2686 // Prefer the C++98 pedantic compatibility warning over the generic,
2687 // non-extension, user-requested "missing newline at EOF" warning.
2688 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2689 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2691 DiagID = diag::warn_no_newline_eof;
2694 DiagID = diag::ext_no_newline_eof;
2697 Diag(BufferEnd, DiagID)
2698 << FixItHint::CreateInsertion(EndLoc, "\n");
2703 // Finally, let the preprocessor handle this.
2704 return PP->HandleEndOfFile(Result, isPragmaLexer());
2707 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2708 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2709 /// else and 2 if there are no more tokens in the buffer controlled by the
2711 unsigned Lexer::isNextPPTokenLParen() {
2712 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2714 // Switch to 'skipping' mode. This will ensure that we can lex a token
2715 // without emitting diagnostics, disables macro expansion, and will cause EOF
2716 // to return an EOF token instead of popping the include stack.
2717 LexingRawMode = true;
2719 // Save state that can be changed while lexing so that we can restore it.
2720 const char *TmpBufferPtr = BufferPtr;
2721 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2722 bool atStartOfLine = IsAtStartOfLine;
2723 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2724 bool leadingSpace = HasLeadingSpace;
2729 // Restore state that may have changed.
2730 BufferPtr = TmpBufferPtr;
2731 ParsingPreprocessorDirective = inPPDirectiveMode;
2732 HasLeadingSpace = leadingSpace;
2733 IsAtStartOfLine = atStartOfLine;
2734 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2736 // Restore the lexer back to non-skipping mode.
2737 LexingRawMode = false;
2739 if (Tok.is(tok::eof))
2741 return Tok.is(tok::l_paren);
2744 /// \brief Find the end of a version control conflict marker.
2745 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2746 ConflictMarkerKind CMK) {
2747 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2748 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2749 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2750 size_t Pos = RestOfBuffer.find(Terminator);
2751 while (Pos != StringRef::npos) {
2752 // Must occur at start of line.
2754 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2755 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2756 Pos = RestOfBuffer.find(Terminator);
2759 return RestOfBuffer.data()+Pos;
2764 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2765 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2766 /// and recover nicely. This returns true if it is a conflict marker and false
2768 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2769 // Only a conflict marker if it starts at the beginning of a line.
2770 if (CurPtr != BufferStart &&
2771 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2774 // Check to see if we have <<<<<<< or >>>>.
2775 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2776 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2779 // If we have a situation where we don't care about conflict markers, ignore
2781 if (CurrentConflictMarkerState || isLexingRawMode())
2784 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2786 // Check to see if there is an ending marker somewhere in the buffer at the
2787 // start of a line to terminate this conflict marker.
2788 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2789 // We found a match. We are really in a conflict marker.
2790 // Diagnose this, and ignore to the end of line.
2791 Diag(CurPtr, diag::err_conflict_marker);
2792 CurrentConflictMarkerState = Kind;
2794 // Skip ahead to the end of line. We know this exists because the
2795 // end-of-conflict marker starts with \r or \n.
2796 while (*CurPtr != '\r' && *CurPtr != '\n') {
2797 assert(CurPtr != BufferEnd && "Didn't find end of line");
2804 // No end of conflict marker found.
2808 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2809 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2810 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2811 /// the line. This returns true if it is a conflict marker and false if not.
2812 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2813 // Only a conflict marker if it starts at the beginning of a line.
2814 if (CurPtr != BufferStart &&
2815 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2818 // If we have a situation where we don't care about conflict markers, ignore
2820 if (!CurrentConflictMarkerState || isLexingRawMode())
2823 // Check to see if we have the marker (4 characters in a row).
2824 for (unsigned i = 1; i != 4; ++i)
2825 if (CurPtr[i] != CurPtr[0])
2828 // If we do have it, search for the end of the conflict marker. This could
2829 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2830 // be the end of conflict marker.
2831 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2832 CurrentConflictMarkerState)) {
2835 // Skip ahead to the end of line.
2836 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2841 // No longer in the conflict marker.
2842 CurrentConflictMarkerState = CMK_None;
2849 static const char *findPlaceholderEnd(const char *CurPtr,
2850 const char *BufferEnd) {
2851 if (CurPtr == BufferEnd)
2853 BufferEnd -= 1; // Scan until the second last character.
2854 for (; CurPtr != BufferEnd; ++CurPtr) {
2855 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2861 bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2862 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2863 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
2865 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2868 const char *Start = CurPtr - 1;
2869 if (!LangOpts.AllowEditorPlaceholders)
2870 Diag(Start, diag::err_placeholder_in_source);
2871 Result.startToken();
2872 FormTokenWithChars(Result, End, tok::raw_identifier);
2873 Result.setRawIdentifierData(Start);
2874 PP->LookUpIdentifierInfo(Result);
2875 Result.setFlag(Token::IsEditorPlaceholder);
2880 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2881 if (PP && PP->isCodeCompletionEnabled()) {
2882 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2883 return Loc == PP->getCodeCompletionLoc();
2889 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2892 char Kind = getCharAndSize(StartPtr, CharSize);
2894 unsigned NumHexDigits;
2897 else if (Kind == 'U')
2902 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2903 if (Result && !isLexingRawMode())
2904 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2908 const char *CurPtr = StartPtr + CharSize;
2909 const char *KindLoc = &CurPtr[-1];
2911 uint32_t CodePoint = 0;
2912 for (unsigned i = 0; i < NumHexDigits; ++i) {
2913 char C = getCharAndSize(CurPtr, CharSize);
2915 unsigned Value = llvm::hexDigitValue(C);
2917 if (Result && !isLexingRawMode()) {
2919 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2920 << StringRef(KindLoc, 1);
2922 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2924 // If the user wrote \U1234, suggest a fixit to \u.
2925 if (i == 4 && NumHexDigits == 8) {
2926 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2927 Diag(KindLoc, diag::note_ucn_four_not_eight)
2928 << FixItHint::CreateReplacement(URange, "u");
2943 Result->setFlag(Token::HasUCN);
2944 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2947 while (StartPtr != CurPtr)
2948 (void)getAndAdvanceChar(StartPtr, *Result);
2953 // Don't apply C family restrictions to UCNs in assembly mode
2954 if (LangOpts.AsmPreprocessor)
2957 // C99 6.4.3p2: A universal character name shall not specify a character whose
2958 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2959 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2960 // C++11 [lex.charset]p2: If the hexadecimal value for a
2961 // universal-character-name corresponds to a surrogate code point (in the
2962 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2963 // if the hexadecimal value for a universal-character-name outside the
2964 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2965 // string literal corresponds to a control character (in either of the
2966 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2967 // basic source character set, the program is ill-formed.
2968 if (CodePoint < 0xA0) {
2969 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2972 // We don't use isLexingRawMode() here because we need to warn about bad
2973 // UCNs even when skipping preprocessing tokens in a #if block.
2975 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2976 Diag(BufferPtr, diag::err_ucn_control_character);
2978 char C = static_cast<char>(CodePoint);
2979 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2984 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2985 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2986 // We don't use isLexingRawMode() here because we need to diagnose bad
2987 // UCNs even when skipping preprocessing tokens in a #if block.
2989 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2990 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2992 Diag(BufferPtr, diag::err_ucn_escape_invalid);
3000 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3001 const char *CurPtr) {
3002 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
3003 UnicodeWhitespaceCharRanges);
3004 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
3005 UnicodeWhitespaceChars.contains(C)) {
3006 Diag(BufferPtr, diag::ext_unicode_whitespace)
3007 << makeCharRange(*this, BufferPtr, CurPtr);
3009 Result.setFlag(Token::LeadingSpace);
3015 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
3016 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
3017 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3018 !PP->isPreprocessedOutput()) {
3019 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
3020 makeCharRange(*this, BufferPtr, CurPtr),
3025 return LexIdentifier(Result, CurPtr);
3028 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3029 !PP->isPreprocessedOutput() &&
3030 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
3031 // Non-ASCII characters tend to creep into source code unintentionally.
3032 // Instead of letting the parser complain about the unknown token,
3033 // just drop the character.
3034 // Note that we can /only/ do this when the non-ASCII character is actually
3035 // spelled as Unicode, not written as a UCN. The standard requires that
3036 // we not throw away any possible preprocessor tokens, but there's a
3037 // loophole in the mapping of Unicode characters to basic character set
3038 // characters that allows us to map these particular characters to, say,
3040 Diag(BufferPtr, diag::err_non_ascii)
3041 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
3047 // Otherwise, we have an explicit UCN or a character that's unlikely to show
3050 FormTokenWithChars(Result, CurPtr, tok::unknown);
3054 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3055 IsAtStartOfLine = Result.isAtStartOfLine();
3056 HasLeadingSpace = Result.hasLeadingSpace();
3057 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3058 // Note that this doesn't affect IsAtPhysicalStartOfLine.
3061 bool Lexer::Lex(Token &Result) {
3062 // Start a new token.
3063 Result.startToken();
3065 // Set up misc whitespace flags for LexTokenInternal.
3066 if (IsAtStartOfLine) {
3067 Result.setFlag(Token::StartOfLine);
3068 IsAtStartOfLine = false;
3071 if (HasLeadingSpace) {
3072 Result.setFlag(Token::LeadingSpace);
3073 HasLeadingSpace = false;
3076 if (HasLeadingEmptyMacro) {
3077 Result.setFlag(Token::LeadingEmptyMacro);
3078 HasLeadingEmptyMacro = false;
3081 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3082 IsAtPhysicalStartOfLine = false;
3083 bool isRawLex = isLexingRawMode();
3085 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3086 // (After the LexTokenInternal call, the lexer might be destroyed.)
3087 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3088 return returnedToken;
3091 /// LexTokenInternal - This implements a simple C family lexer. It is an
3092 /// extremely performance critical piece of code. This assumes that the buffer
3093 /// has a null character at the end of the file. This returns a preprocessing
3094 /// token, not a normal token, as such, it is an internal interface. It assumes
3095 /// that the Flags of result have been cleared before calling this.
3096 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3098 // New token, can't need cleaning yet.
3099 Result.clearFlag(Token::NeedsCleaning);
3100 Result.setIdentifierInfo(nullptr);
3102 // CurPtr - Cache BufferPtr in an automatic variable.
3103 const char *CurPtr = BufferPtr;
3105 // Small amounts of horizontal whitespace is very common between tokens.
3106 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3108 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3111 // If we are keeping whitespace and other tokens, just return what we just
3112 // skipped. The next lexer invocation will return the token after the
3114 if (isKeepWhitespaceMode()) {
3115 FormTokenWithChars(Result, CurPtr, tok::unknown);
3116 // FIXME: The next token will not have LeadingSpace set.
3121 Result.setFlag(Token::LeadingSpace);
3124 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
3126 // Read a character, advancing over it.
3127 char Char = getAndAdvanceChar(CurPtr, Result);
3128 tok::TokenKind Kind;
3132 // Found end of file?
3133 if (CurPtr-1 == BufferEnd)
3134 return LexEndOfFile(Result, CurPtr-1);
3136 // Check if we are performing code completion.
3137 if (isCodeCompletionPoint(CurPtr-1)) {
3138 // Return the code-completion token.
3139 Result.startToken();
3140 FormTokenWithChars(Result, CurPtr, tok::code_completion);
3144 if (!isLexingRawMode())
3145 Diag(CurPtr-1, diag::null_in_file);
3146 Result.setFlag(Token::LeadingSpace);
3147 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3148 return true; // KeepWhitespaceMode
3150 // We know the lexer hasn't changed, so just try again with this lexer.
3151 // (We manually eliminate the tail call to avoid recursion.)
3154 case 26: // DOS & CP/M EOF: "^Z".
3155 // If we're in Microsoft extensions mode, treat this as end of file.
3156 if (LangOpts.MicrosoftExt) {
3157 if (!isLexingRawMode())
3158 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3159 return LexEndOfFile(Result, CurPtr-1);
3162 // If Microsoft extensions are disabled, this is just random garbage.
3163 Kind = tok::unknown;
3167 if (CurPtr[0] == '\n')
3168 Char = getAndAdvanceChar(CurPtr, Result);
3171 // If we are inside a preprocessor directive and we see the end of line,
3172 // we know we are done with the directive, so return an EOD token.
3173 if (ParsingPreprocessorDirective) {
3174 // Done parsing the "line".
3175 ParsingPreprocessorDirective = false;
3177 // Restore comment saving mode, in case it was disabled for directive.
3179 resetExtendedTokenMode();
3181 // Since we consumed a newline, we are back at the start of a line.
3182 IsAtStartOfLine = true;
3183 IsAtPhysicalStartOfLine = true;
3189 // No leading whitespace seen so far.
3190 Result.clearFlag(Token::LeadingSpace);
3192 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3193 return true; // KeepWhitespaceMode
3195 // We only saw whitespace, so just try again with this lexer.
3196 // (We manually eliminate the tail call to avoid recursion.)
3202 SkipHorizontalWhitespace:
3203 Result.setFlag(Token::LeadingSpace);
3204 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3205 return true; // KeepWhitespaceMode
3210 // If the next token is obviously a // or /* */ comment, skip it efficiently
3211 // too (without going through the big switch stmt).
3212 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3213 LangOpts.LineComment &&
3214 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3215 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3216 return true; // There is a token to return.
3217 goto SkipIgnoredUnits;
3218 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3219 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3220 return true; // There is a token to return.
3221 goto SkipIgnoredUnits;
3222 } else if (isHorizontalWhitespace(*CurPtr)) {
3223 goto SkipHorizontalWhitespace;
3225 // We only saw whitespace, so just try again with this lexer.
3226 // (We manually eliminate the tail call to avoid recursion.)
3229 // C99 6.4.4.1: Integer Constants.
3230 // C99 6.4.4.2: Floating Constants.
3231 case '0': case '1': case '2': case '3': case '4':
3232 case '5': case '6': case '7': case '8': case '9':
3233 // Notify MIOpt that we read a non-whitespace/non-comment token.
3235 return LexNumericConstant(Result, CurPtr);
3237 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3238 // Notify MIOpt that we read a non-whitespace/non-comment token.
3241 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3242 Char = getCharAndSize(CurPtr, SizeTmp);
3244 // UTF-16 string literal
3246 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3247 tok::utf16_string_literal);
3249 // UTF-16 character constant
3251 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3252 tok::utf16_char_constant);
3254 // UTF-16 raw string literal
3255 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3256 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3257 return LexRawStringLiteral(Result,
3258 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3260 tok::utf16_string_literal);
3263 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3265 // UTF-8 string literal
3267 return LexStringLiteral(Result,
3268 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3270 tok::utf8_string_literal);
3271 if (Char2 == '\'' && LangOpts.CPlusPlus17)
3272 return LexCharConstant(
3273 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3275 tok::utf8_char_constant);
3277 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3279 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3280 // UTF-8 raw string literal
3282 return LexRawStringLiteral(Result,
3283 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3286 tok::utf8_string_literal);
3292 // treat u like the start of an identifier.
3293 return LexIdentifier(Result, CurPtr);
3295 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3296 // Notify MIOpt that we read a non-whitespace/non-comment token.
3299 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3300 Char = getCharAndSize(CurPtr, SizeTmp);
3302 // UTF-32 string literal
3304 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3305 tok::utf32_string_literal);
3307 // UTF-32 character constant
3309 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3310 tok::utf32_char_constant);
3312 // UTF-32 raw string literal
3313 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3314 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3315 return LexRawStringLiteral(Result,
3316 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3318 tok::utf32_string_literal);
3321 // treat U like the start of an identifier.
3322 return LexIdentifier(Result, CurPtr);
3324 case 'R': // Identifier or C++0x raw string literal
3325 // Notify MIOpt that we read a non-whitespace/non-comment token.
3328 if (LangOpts.CPlusPlus11) {
3329 Char = getCharAndSize(CurPtr, SizeTmp);
3332 return LexRawStringLiteral(Result,
3333 ConsumeChar(CurPtr, SizeTmp, Result),
3334 tok::string_literal);
3337 // treat R like the start of an identifier.
3338 return LexIdentifier(Result, CurPtr);
3340 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3341 // Notify MIOpt that we read a non-whitespace/non-comment token.
3343 Char = getCharAndSize(CurPtr, SizeTmp);
3345 // Wide string literal.
3347 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3348 tok::wide_string_literal);
3350 // Wide raw string literal.
3351 if (LangOpts.CPlusPlus11 && Char == 'R' &&
3352 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3353 return LexRawStringLiteral(Result,
3354 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3356 tok::wide_string_literal);
3358 // Wide character constant.
3360 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3361 tok::wide_char_constant);
3362 // FALL THROUGH, treating L like the start of an identifier.
3365 // C99 6.4.2: Identifiers.
3366 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3367 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3368 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3369 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3370 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3371 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3372 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3373 case 'v': case 'w': case 'x': case 'y': case 'z':
3375 // Notify MIOpt that we read a non-whitespace/non-comment token.
3377 return LexIdentifier(Result, CurPtr);
3379 case '$': // $ in identifiers.
3380 if (LangOpts.DollarIdents) {
3381 if (!isLexingRawMode())
3382 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3383 // Notify MIOpt that we read a non-whitespace/non-comment token.
3385 return LexIdentifier(Result, CurPtr);
3388 Kind = tok::unknown;
3391 // C99 6.4.4: Character Constants.
3393 // Notify MIOpt that we read a non-whitespace/non-comment token.
3395 return LexCharConstant(Result, CurPtr, tok::char_constant);
3397 // C99 6.4.5: String Literals.
3399 // Notify MIOpt that we read a non-whitespace/non-comment token.
3401 return LexStringLiteral(Result, CurPtr, tok::string_literal);
3403 // C99 6.4.6: Punctuators.
3405 Kind = tok::question;
3408 Kind = tok::l_square;
3411 Kind = tok::r_square;
3414 Kind = tok::l_paren;
3417 Kind = tok::r_paren;
3420 Kind = tok::l_brace;
3423 Kind = tok::r_brace;
3426 Char = getCharAndSize(CurPtr, SizeTmp);
3427 if (Char >= '0' && Char <= '9') {
3428 // Notify MIOpt that we read a non-whitespace/non-comment token.
3431 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3432 } else if (LangOpts.CPlusPlus && Char == '*') {
3433 Kind = tok::periodstar;
3435 } else if (Char == '.' &&
3436 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3437 Kind = tok::ellipsis;
3438 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3445 Char = getCharAndSize(CurPtr, SizeTmp);
3448 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3449 } else if (Char == '=') {
3450 Kind = tok::ampequal;
3451 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3457 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3458 Kind = tok::starequal;
3459 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3465 Char = getCharAndSize(CurPtr, SizeTmp);
3467 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3468 Kind = tok::plusplus;
3469 } else if (Char == '=') {
3470 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3471 Kind = tok::plusequal;
3477 Char = getCharAndSize(CurPtr, SizeTmp);
3478 if (Char == '-') { // --
3479 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3480 Kind = tok::minusminus;
3481 } else if (Char == '>' && LangOpts.CPlusPlus &&
3482 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3483 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3485 Kind = tok::arrowstar;
3486 } else if (Char == '>') { // ->
3487 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3489 } else if (Char == '=') { // -=
3490 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3491 Kind = tok::minusequal;
3500 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3501 Kind = tok::exclaimequal;
3502 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3504 Kind = tok::exclaim;
3509 Char = getCharAndSize(CurPtr, SizeTmp);
3510 if (Char == '/') { // Line comment.
3511 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3512 // want to lex this as a comment. There is one problem with this though,
3513 // that in one particular corner case, this can change the behavior of the
3514 // resultant program. For example, In "foo //**/ bar", C89 would lex
3515 // this as "foo / bar" and langauges with Line comments would lex it as
3516 // "foo". Check to see if the character after the second slash is a '*'.
3517 // If so, we will lex that as a "/" instead of the start of a comment.
3518 // However, we never do this if we are just preprocessing.
3519 bool TreatAsComment = LangOpts.LineComment &&
3520 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3521 if (!TreatAsComment)
3522 if (!(PP && PP->isPreprocessedOutput()))
3523 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3525 if (TreatAsComment) {
3526 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3527 TokAtPhysicalStartOfLine))
3528 return true; // There is a token to return.
3530 // It is common for the tokens immediately after a // comment to be
3531 // whitespace (indentation for the next line). Instead of going through
3532 // the big switch, handle it efficiently now.
3533 goto SkipIgnoredUnits;
3537 if (Char == '*') { // /**/ comment.
3538 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3539 TokAtPhysicalStartOfLine))
3540 return true; // There is a token to return.
3542 // We only saw whitespace, so just try again with this lexer.
3543 // (We manually eliminate the tail call to avoid recursion.)
3548 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3549 Kind = tok::slashequal;
3555 Char = getCharAndSize(CurPtr, SizeTmp);
3557 Kind = tok::percentequal;
3558 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3559 } else if (LangOpts.Digraphs && Char == '>') {
3560 Kind = tok::r_brace; // '%>' -> '}'
3561 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3562 } else if (LangOpts.Digraphs && Char == ':') {
3563 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3564 Char = getCharAndSize(CurPtr, SizeTmp);
3565 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3566 Kind = tok::hashhash; // '%:%:' -> '##'
3567 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3569 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3570 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3571 if (!isLexingRawMode())
3572 Diag(BufferPtr, diag::ext_charize_microsoft);
3574 } else { // '%:' -> '#'
3575 // We parsed a # character. If this occurs at the start of the line,
3576 // it's actually the start of a preprocessing directive. Callback to
3577 // the preprocessor to handle it.
3578 // TODO: -fpreprocessed mode??
3579 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3580 goto HandleDirective;
3585 Kind = tok::percent;
3589 Char = getCharAndSize(CurPtr, SizeTmp);
3590 if (ParsingFilename) {
3591 return LexAngledStringLiteral(Result, CurPtr);
3592 } else if (Char == '<') {
3593 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3595 Kind = tok::lesslessequal;
3596 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3598 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3599 // If this is actually a '<<<<<<<' version control conflict marker,
3600 // recognize it as such and recover nicely.
3602 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3603 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3606 } else if (LangOpts.CUDA && After == '<') {
3607 Kind = tok::lesslessless;
3608 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3611 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3612 Kind = tok::lessless;
3614 } else if (Char == '=') {
3615 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3617 if (getLangOpts().CPlusPlus2a) {
3618 if (!isLexingRawMode())
3619 Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
3620 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3622 Kind = tok::spaceship;
3625 // Suggest adding a space between the '<=' and the '>' to avoid a
3626 // change in semantics if this turns up in C++ <=17 mode.
3627 if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
3628 Diag(BufferPtr, diag::warn_cxx2a_compat_spaceship)
3629 << FixItHint::CreateInsertion(
3630 getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
3633 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3634 Kind = tok::lessequal;
3635 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3636 if (LangOpts.CPlusPlus11 &&
3637 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3638 // C++0x [lex.pptoken]p3:
3639 // Otherwise, if the next three characters are <:: and the subsequent
3640 // character is neither : nor >, the < is treated as a preprocessor
3641 // token by itself and not as the first character of the alternative
3644 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3645 if (After != ':' && After != '>') {
3647 if (!isLexingRawMode())
3648 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3653 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3654 Kind = tok::l_square;
3655 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3656 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3657 Kind = tok::l_brace;
3658 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3659 lexEditorPlaceholder(Result, CurPtr)) {
3666 Char = getCharAndSize(CurPtr, SizeTmp);
3668 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3669 Kind = tok::greaterequal;
3670 } else if (Char == '>') {
3671 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3673 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3675 Kind = tok::greatergreaterequal;
3676 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3677 // If this is actually a '>>>>' conflict marker, recognize it as such
3678 // and recover nicely.
3680 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3681 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3683 } else if (LangOpts.CUDA && After == '>') {
3684 Kind = tok::greatergreatergreater;
3685 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3688 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3689 Kind = tok::greatergreater;
3692 Kind = tok::greater;
3696 Char = getCharAndSize(CurPtr, SizeTmp);
3698 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3699 Kind = tok::caretequal;
3700 } else if (LangOpts.OpenCL && Char == '^') {
3701 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3702 Kind = tok::caretcaret;
3708 Char = getCharAndSize(CurPtr, SizeTmp);
3710 Kind = tok::pipeequal;
3711 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3712 } else if (Char == '|') {
3713 // If this is '|||||||' and we're in a conflict marker, ignore it.
3714 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3716 Kind = tok::pipepipe;
3717 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3723 Char = getCharAndSize(CurPtr, SizeTmp);
3724 if (LangOpts.Digraphs && Char == '>') {
3725 Kind = tok::r_square; // ':>' -> ']'
3726 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3727 } else if ((LangOpts.CPlusPlus ||
3728 LangOpts.DoubleSquareBracketAttributes) &&
3730 Kind = tok::coloncolon;
3731 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3740 Char = getCharAndSize(CurPtr, SizeTmp);
3742 // If this is '====' and we're in a conflict marker, ignore it.
3743 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3746 Kind = tok::equalequal;
3747 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3756 Char = getCharAndSize(CurPtr, SizeTmp);
3758 Kind = tok::hashhash;
3759 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3760 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3762 if (!isLexingRawMode())
3763 Diag(BufferPtr, diag::ext_charize_microsoft);
3764 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3766 // We parsed a # character. If this occurs at the start of the line,
3767 // it's actually the start of a preprocessing directive. Callback to
3768 // the preprocessor to handle it.
3769 // TODO: -fpreprocessed mode??
3770 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3771 goto HandleDirective;
3778 // Objective C support.
3779 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3782 Kind = tok::unknown;
3785 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3787 if (!LangOpts.AsmPreprocessor) {
3788 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3789 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3790 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3791 return true; // KeepWhitespaceMode
3793 // We only saw whitespace, so just try again with this lexer.
3794 // (We manually eliminate the tail call to avoid recursion.)
3798 return LexUnicode(Result, CodePoint, CurPtr);
3802 Kind = tok::unknown;
3806 if (isASCII(Char)) {
3807 Kind = tok::unknown;
3811 llvm::UTF32 CodePoint;
3813 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3814 // an escaped newline.
3816 const char *UTF8StartPtr = CurPtr;
3817 llvm::ConversionResult Status =
3818 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3819 (const llvm::UTF8 *)BufferEnd,
3821 llvm::strictConversion);
3822 if (Status == llvm::conversionOK) {
3823 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3824 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3825 return true; // KeepWhitespaceMode
3827 // We only saw whitespace, so just try again with this lexer.
3828 // (We manually eliminate the tail call to avoid recursion.)
3831 if (!isLexingRawMode())
3832 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
3833 makeCharRange(*this, UTF8StartPtr, CurPtr));
3834 return LexUnicode(Result, CodePoint, CurPtr);
3837 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3838 PP->isPreprocessedOutput()) {
3840 Kind = tok::unknown;
3844 // Non-ASCII characters tend to creep into source code unintentionally.
3845 // Instead of letting the parser complain about the unknown token,
3846 // just diagnose the invalid UTF-8, then drop the character.
3847 Diag(CurPtr, diag::err_invalid_utf8);
3849 BufferPtr = CurPtr+1;
3850 // We're pretending the character didn't exist, so just try again with
3852 // (We manually eliminate the tail call to avoid recursion.)
3857 // Notify MIOpt that we read a non-whitespace/non-comment token.
3860 // Update the location of token as well as BufferPtr.
3861 FormTokenWithChars(Result, CurPtr, Kind);
3865 // We parsed a # character and it's the start of a preprocessing directive.
3867 FormTokenWithChars(Result, CurPtr, tok::hash);
3868 PP->HandleDirective(Result);
3870 if (PP->hadModuleLoaderFatalFailure()) {
3871 // With a fatal failure in the module loader, we abort parsing.
3872 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3876 // We parsed the directive; lex a token with the new state.