1 //===- Lexer.cpp - C Language Family Lexer --------------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file implements the Lexer and Token interfaces.
11 //===----------------------------------------------------------------------===//
13 #include "clang/Lex/Lexer.h"
14 #include "UnicodeCharSets.h"
15 #include "clang/Basic/CharInfo.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/SourceLocation.h"
19 #include "clang/Basic/SourceManager.h"
20 #include "clang/Basic/TokenKinds.h"
21 #include "clang/Lex/LexDiagnostic.h"
22 #include "clang/Lex/LiteralSupport.h"
23 #include "clang/Lex/MultipleIncludeOpt.h"
24 #include "clang/Lex/Preprocessor.h"
25 #include "clang/Lex/PreprocessorOptions.h"
26 #include "clang/Lex/Token.h"
27 #include "clang/Basic/Diagnostic.h"
28 #include "clang/Basic/LLVM.h"
29 #include "clang/Basic/TokenKinds.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/ADT/StringExtras.h"
33 #include "llvm/ADT/StringSwitch.h"
34 #include "llvm/ADT/StringRef.h"
35 #include "llvm/Support/Compiler.h"
36 #include "llvm/Support/ConvertUTF.h"
37 #include "llvm/Support/MathExtras.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "llvm/Support/NativeFormatting.h"
40 #include "llvm/Support/UnicodeCharRanges.h"
50 using namespace clang;
52 //===----------------------------------------------------------------------===//
53 // Token Class Implementation
54 //===----------------------------------------------------------------------===//
56 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
57 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
60 if (IdentifierInfo *II = getIdentifierInfo())
61 return II->getObjCKeywordID() == objcKey;
65 /// getObjCKeywordID - Return the ObjC keyword kind.
66 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
68 return tok::objc_not_keyword;
69 IdentifierInfo *specId = getIdentifierInfo();
70 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
73 //===----------------------------------------------------------------------===//
74 // Lexer Class Implementation
75 //===----------------------------------------------------------------------===//
77 void Lexer::anchor() {}
79 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
81 BufferStart = BufStart;
85 assert(BufEnd[0] == 0 &&
86 "We assume that the input buffer has a null character at the end"
87 " to simplify lexing!");
89 // Check whether we have a BOM in the beginning of the buffer. If yes - act
90 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
91 // skip the UTF-8 BOM if it's present.
92 if (BufferStart == BufferPtr) {
93 // Determine the size of the BOM.
94 StringRef Buf(BufferStart, BufferEnd - BufferStart);
95 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
96 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
100 BufferPtr += BOMLength;
103 Is_PragmaLexer = false;
104 CurrentConflictMarkerState = CMK_None;
106 // Start of the file is a start of line.
107 IsAtStartOfLine = true;
108 IsAtPhysicalStartOfLine = true;
110 HasLeadingSpace = false;
111 HasLeadingEmptyMacro = false;
113 // We are not after parsing a #.
114 ParsingPreprocessorDirective = false;
116 // We are not after parsing #include.
117 ParsingFilename = false;
119 // We are not in raw mode. Raw mode disables diagnostics and interpretation
120 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
121 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
122 // or otherwise skipping over tokens.
123 LexingRawMode = false;
125 // Default to not keeping comments.
126 ExtendedTokenMode = 0;
129 /// Lexer constructor - Create a new lexer object for the specified buffer
130 /// with the specified preprocessor managing the lexing process. This lexer
131 /// assumes that the associated file buffer and Preprocessor objects will
132 /// outlive it, so it doesn't take ownership of either of them.
133 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
134 : PreprocessorLexer(&PP, FID),
135 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
136 LangOpts(PP.getLangOpts()) {
137 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
138 InputFile->getBufferEnd());
140 resetExtendedTokenMode();
143 /// Lexer constructor - Create a new raw lexer object. This object is only
144 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
145 /// range will outlive it, so it doesn't take ownership of it.
146 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
147 const char *BufStart, const char *BufPtr, const char *BufEnd)
148 : FileLoc(fileloc), LangOpts(langOpts) {
149 InitLexer(BufStart, BufPtr, BufEnd);
151 // We *are* in raw mode.
152 LexingRawMode = true;
155 /// Lexer constructor - Create a new raw lexer object. This object is only
156 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
157 /// range will outlive it, so it doesn't take ownership of it.
158 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
159 const SourceManager &SM, const LangOptions &langOpts)
160 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
161 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
163 void Lexer::resetExtendedTokenMode() {
164 assert(PP && "Cannot reset token mode without a preprocessor");
165 if (LangOpts.TraditionalCPP)
166 SetKeepWhitespaceMode(true);
168 SetCommentRetentionState(PP->getCommentRetentionState());
171 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
172 /// _Pragma expansion. This has a variety of magic semantics that this method
173 /// sets up. It returns a new'd Lexer that must be delete'd when done.
175 /// On entrance to this routine, TokStartLoc is a macro location which has a
176 /// spelling loc that indicates the bytes to be lexed for the token and an
177 /// expansion location that indicates where all lexed tokens should be
180 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
181 /// normal lexer that remaps tokens as they fly by. This would require making
182 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
183 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
184 /// out of the critical path of the lexer!
186 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
187 SourceLocation ExpansionLocStart,
188 SourceLocation ExpansionLocEnd,
189 unsigned TokLen, Preprocessor &PP) {
190 SourceManager &SM = PP.getSourceManager();
192 // Create the lexer as if we were going to lex the file normally.
193 FileID SpellingFID = SM.getFileID(SpellingLoc);
194 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
195 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
197 // Now that the lexer is created, change the start/end locations so that we
198 // just lex the subsection of the file that we want. This is lexing from a
200 const char *StrData = SM.getCharacterData(SpellingLoc);
202 L->BufferPtr = StrData;
203 L->BufferEnd = StrData+TokLen;
204 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
206 // Set the SourceLocation with the remapping information. This ensures that
207 // GetMappedTokenLoc will remap the tokens as they are lexed.
208 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
210 ExpansionLocEnd, TokLen);
212 // Ensure that the lexer thinks it is inside a directive, so that end \n will
213 // return an EOD token.
214 L->ParsingPreprocessorDirective = true;
216 // This lexer really is for _Pragma.
217 L->Is_PragmaLexer = true;
221 template <typename T> static void StringifyImpl(T &Str, char Quote) {
222 typename T::size_type i = 0, e = Str.size();
224 if (Str[i] == '\\' || Str[i] == Quote) {
225 Str.insert(Str.begin() + i, '\\');
228 } else if (Str[i] == '\n' || Str[i] == '\r') {
229 // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
230 if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
231 Str[i] != Str[i + 1]) {
235 // Replace '\n' and '\r' to '\\' followed by 'n'.
237 Str.insert(Str.begin() + i + 1, 'n');
246 std::string Lexer::Stringify(StringRef Str, bool Charify) {
247 std::string Result = Str;
248 char Quote = Charify ? '\'' : '"';
249 StringifyImpl(Result, Quote);
253 void Lexer::Stringify(SmallVectorImpl<char> &Str) { StringifyImpl(Str, '"'); }
255 //===----------------------------------------------------------------------===//
257 //===----------------------------------------------------------------------===//
259 /// Slow case of getSpelling. Extract the characters comprising the
260 /// spelling of this token from the provided input buffer.
261 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
262 const LangOptions &LangOpts, char *Spelling) {
263 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
266 const char *BufEnd = BufPtr + Tok.getLength();
268 if (tok::isStringLiteral(Tok.getKind())) {
269 // Munch the encoding-prefix and opening double-quote.
270 while (BufPtr < BufEnd) {
272 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
275 if (Spelling[Length - 1] == '"')
279 // Raw string literals need special handling; trigraph expansion and line
280 // splicing do not occur within their d-char-sequence nor within their
283 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
284 // Search backwards from the end of the token to find the matching closing
286 const char *RawEnd = BufEnd;
287 do --RawEnd; while (*RawEnd != '"');
288 size_t RawLength = RawEnd - BufPtr + 1;
290 // Everything between the quotes is included verbatim in the spelling.
291 memcpy(Spelling + Length, BufPtr, RawLength);
295 // The rest of the token is lexed normally.
299 while (BufPtr < BufEnd) {
301 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
305 assert(Length < Tok.getLength() &&
306 "NeedsCleaning flag set on token that didn't need cleaning!");
310 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
311 /// token are the characters used to represent the token in the source file
312 /// after trigraph expansion and escaped-newline folding. In particular, this
313 /// wants to get the true, uncanonicalized, spelling of things like digraphs
315 StringRef Lexer::getSpelling(SourceLocation loc,
316 SmallVectorImpl<char> &buffer,
317 const SourceManager &SM,
318 const LangOptions &options,
320 // Break down the source location.
321 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
323 // Try to the load the file buffer.
324 bool invalidTemp = false;
325 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
327 if (invalid) *invalid = true;
331 const char *tokenBegin = file.data() + locInfo.second;
333 // Lex from the start of the given location.
334 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
335 file.begin(), tokenBegin, file.end());
337 lexer.LexFromRawLexer(token);
339 unsigned length = token.getLength();
341 // Common case: no need for cleaning.
342 if (!token.needsCleaning())
343 return StringRef(tokenBegin, length);
345 // Hard case, we need to relex the characters into the string.
346 buffer.resize(length);
347 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
348 return StringRef(buffer.data(), buffer.size());
351 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
352 /// token are the characters used to represent the token in the source file
353 /// after trigraph expansion and escaped-newline folding. In particular, this
354 /// wants to get the true, uncanonicalized, spelling of things like digraphs
356 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
357 const LangOptions &LangOpts, bool *Invalid) {
358 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
360 bool CharDataInvalid = false;
361 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
364 *Invalid = CharDataInvalid;
368 // If this token contains nothing interesting, return it directly.
369 if (!Tok.needsCleaning())
370 return std::string(TokStart, TokStart + Tok.getLength());
373 Result.resize(Tok.getLength());
374 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
378 /// getSpelling - This method is used to get the spelling of a token into a
379 /// preallocated buffer, instead of as an std::string. The caller is required
380 /// to allocate enough space for the token, which is guaranteed to be at least
381 /// Tok.getLength() bytes long. The actual length of the token is returned.
383 /// Note that this method may do two possible things: it may either fill in
384 /// the buffer specified with characters, or it may *change the input pointer*
385 /// to point to a constant buffer with the data already in it (avoiding a
386 /// copy). The caller is not allowed to modify the returned buffer pointer
387 /// if an internal buffer is returned.
388 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
389 const SourceManager &SourceMgr,
390 const LangOptions &LangOpts, bool *Invalid) {
391 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
393 const char *TokStart = nullptr;
394 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
395 if (Tok.is(tok::raw_identifier))
396 TokStart = Tok.getRawIdentifier().data();
397 else if (!Tok.hasUCN()) {
398 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
399 // Just return the string from the identifier table, which is very quick.
400 Buffer = II->getNameStart();
401 return II->getLength();
405 // NOTE: this can be checked even after testing for an IdentifierInfo.
407 TokStart = Tok.getLiteralData();
410 // Compute the start of the token in the input lexer buffer.
411 bool CharDataInvalid = false;
412 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
414 *Invalid = CharDataInvalid;
415 if (CharDataInvalid) {
421 // If this token contains nothing interesting, return it directly.
422 if (!Tok.needsCleaning()) {
424 return Tok.getLength();
427 // Otherwise, hard case, relex the characters into the string.
428 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
431 /// MeasureTokenLength - Relex the token at the specified location and return
432 /// its length in bytes in the input file. If the token needs cleaning (e.g.
433 /// includes a trigraph or an escaped newline) then this count includes bytes
434 /// that are part of that.
435 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
436 const SourceManager &SM,
437 const LangOptions &LangOpts) {
439 if (getRawToken(Loc, TheTok, SM, LangOpts))
441 return TheTok.getLength();
444 /// Relex the token at the specified location.
445 /// \returns true if there was a failure, false on success.
446 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
447 const SourceManager &SM,
448 const LangOptions &LangOpts,
449 bool IgnoreWhiteSpace) {
450 // TODO: this could be special cased for common tokens like identifiers, ')',
451 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
452 // all obviously single-char tokens. This could use
453 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
456 // If this comes from a macro expansion, we really do want the macro name, not
457 // the token this macro expanded to.
458 Loc = SM.getExpansionLoc(Loc);
459 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
460 bool Invalid = false;
461 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
465 const char *StrData = Buffer.data()+LocInfo.second;
467 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
470 // Create a lexer starting at the beginning of this token.
471 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
472 Buffer.begin(), StrData, Buffer.end());
473 TheLexer.SetCommentRetentionState(true);
474 TheLexer.LexFromRawLexer(Result);
478 /// Returns the pointer that points to the beginning of line that contains
479 /// the given offset, or null if the offset if invalid.
480 static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
481 const char *BufStart = Buffer.data();
482 if (Offset >= Buffer.size())
485 const char *LexStart = BufStart + Offset;
486 for (; LexStart != BufStart; --LexStart) {
487 if (isVerticalWhitespace(LexStart[0]) &&
488 !Lexer::isNewLineEscaped(BufStart, LexStart)) {
489 // LexStart should point at first character of logical line.
497 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
498 const SourceManager &SM,
499 const LangOptions &LangOpts) {
500 assert(Loc.isFileID());
501 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
502 if (LocInfo.first.isInvalid())
505 bool Invalid = false;
506 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
510 // Back up from the current location until we hit the beginning of a line
511 // (or the buffer). We'll relex from that point.
512 const char *StrData = Buffer.data() + LocInfo.second;
513 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
514 if (!LexStart || LexStart == StrData)
517 // Create a lexer starting at the beginning of this token.
518 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
519 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
521 TheLexer.SetCommentRetentionState(true);
523 // Lex tokens until we find the token that contains the source location.
526 TheLexer.LexFromRawLexer(TheTok);
528 if (TheLexer.getBufferLocation() > StrData) {
529 // Lexing this token has taken the lexer past the source location we're
530 // looking for. If the current token encompasses our source location,
531 // return the beginning of that token.
532 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
533 return TheTok.getLocation();
535 // We ended up skipping over the source location entirely, which means
536 // that it points into whitespace. We're done here.
539 } while (TheTok.getKind() != tok::eof);
541 // We've passed our source location; just return the original source location.
545 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
546 const SourceManager &SM,
547 const LangOptions &LangOpts) {
549 return getBeginningOfFileToken(Loc, SM, LangOpts);
551 if (!SM.isMacroArgExpansion(Loc))
554 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
555 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
556 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
557 std::pair<FileID, unsigned> BeginFileLocInfo =
558 SM.getDecomposedLoc(BeginFileLoc);
559 assert(FileLocInfo.first == BeginFileLocInfo.first &&
560 FileLocInfo.second >= BeginFileLocInfo.second);
561 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
566 enum PreambleDirectiveKind {
573 PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
574 const LangOptions &LangOpts,
576 // Create a lexer starting at the beginning of the file. Note that we use a
577 // "fake" file source location at offset 1 so that the lexer will track our
578 // position within the file.
579 const unsigned StartOffset = 1;
580 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
581 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
583 TheLexer.SetCommentRetentionState(true);
585 bool InPreprocessorDirective = false;
587 SourceLocation ActiveCommentLoc;
589 unsigned MaxLineOffset = 0;
591 const char *CurPtr = Buffer.begin();
592 unsigned CurLine = 0;
593 while (CurPtr != Buffer.end()) {
597 if (CurLine == MaxLines)
601 if (CurPtr != Buffer.end())
602 MaxLineOffset = CurPtr - Buffer.begin();
606 TheLexer.LexFromRawLexer(TheTok);
608 if (InPreprocessorDirective) {
609 // If we've hit the end of the file, we're done.
610 if (TheTok.getKind() == tok::eof) {
614 // If we haven't hit the end of the preprocessor directive, skip this
616 if (!TheTok.isAtStartOfLine())
619 // We've passed the end of the preprocessor directive, and will look
620 // at this token again below.
621 InPreprocessorDirective = false;
624 // Keep track of the # of lines in the preamble.
625 if (TheTok.isAtStartOfLine()) {
626 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
628 // If we were asked to limit the number of lines in the preamble,
629 // and we're about to exceed that limit, we're done.
630 if (MaxLineOffset && TokOffset >= MaxLineOffset)
634 // Comments are okay; skip over them.
635 if (TheTok.getKind() == tok::comment) {
636 if (ActiveCommentLoc.isInvalid())
637 ActiveCommentLoc = TheTok.getLocation();
641 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
642 // This is the start of a preprocessor directive.
643 Token HashTok = TheTok;
644 InPreprocessorDirective = true;
645 ActiveCommentLoc = SourceLocation();
647 // Figure out which directive this is. Since we're lexing raw tokens,
648 // we don't have an identifier table available. Instead, just look at
649 // the raw identifier to recognize and categorize preprocessor directives.
650 TheLexer.LexFromRawLexer(TheTok);
651 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
652 StringRef Keyword = TheTok.getRawIdentifier();
653 PreambleDirectiveKind PDK
654 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
655 .Case("include", PDK_Skipped)
656 .Case("__include_macros", PDK_Skipped)
657 .Case("define", PDK_Skipped)
658 .Case("undef", PDK_Skipped)
659 .Case("line", PDK_Skipped)
660 .Case("error", PDK_Skipped)
661 .Case("pragma", PDK_Skipped)
662 .Case("import", PDK_Skipped)
663 .Case("include_next", PDK_Skipped)
664 .Case("warning", PDK_Skipped)
665 .Case("ident", PDK_Skipped)
666 .Case("sccs", PDK_Skipped)
667 .Case("assert", PDK_Skipped)
668 .Case("unassert", PDK_Skipped)
669 .Case("if", PDK_Skipped)
670 .Case("ifdef", PDK_Skipped)
671 .Case("ifndef", PDK_Skipped)
672 .Case("elif", PDK_Skipped)
673 .Case("else", PDK_Skipped)
674 .Case("endif", PDK_Skipped)
675 .Default(PDK_Unknown);
682 // We don't know what this directive is; stop at the '#'.
687 // We only end up here if we didn't recognize the preprocessor
688 // directive or it was one that can't occur in the preamble at this
689 // point. Roll back the current token to the location of the '#'.
693 // We hit a token that we don't recognize as being in the
694 // "preprocessing only" part of the file, so we're no longer in
700 if (ActiveCommentLoc.isValid())
701 End = ActiveCommentLoc; // don't truncate a decl comment.
703 End = TheTok.getLocation();
705 return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
706 TheTok.isAtStartOfLine());
709 unsigned Lexer::getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo,
710 const SourceManager &SM,
711 const LangOptions &LangOpts) {
712 // Figure out how many physical characters away the specified expansion
713 // character is. This needs to take into consideration newlines and
715 bool Invalid = false;
716 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
718 // If they request the first char of the token, we're trivially done.
719 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
722 unsigned PhysOffset = 0;
724 // The usual case is that tokens don't contain anything interesting. Skip
725 // over the uninteresting characters. If a token only consists of simple
726 // chars, this method is extremely fast.
727 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
735 // If we have a character that may be a trigraph or escaped newline, use a
736 // lexer to parse it correctly.
737 for (; CharNo; --CharNo) {
739 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
744 // Final detail: if we end up on an escaped newline, we want to return the
745 // location of the actual byte of the token. For example foo\<newline>bar
746 // advanced by 3 should return the location of b, not of \\. One compounding
747 // detail of this is that the escape may be made by a trigraph.
748 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
749 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
754 /// Computes the source location just past the end of the
755 /// token at this source location.
757 /// This routine can be used to produce a source location that
758 /// points just past the end of the token referenced by \p Loc, and
759 /// is generally used when a diagnostic needs to point just after a
760 /// token where it expected something different that it received. If
761 /// the returned source location would not be meaningful (e.g., if
762 /// it points into a macro), this routine returns an invalid
765 /// \param Offset an offset from the end of the token, where the source
766 /// location should refer to. The default offset (0) produces a source
767 /// location pointing just past the end of the token; an offset of 1 produces
768 /// a source location pointing to the last character in the token, etc.
769 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
770 const SourceManager &SM,
771 const LangOptions &LangOpts) {
775 if (Loc.isMacroID()) {
776 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
777 return {}; // Points inside the macro expansion.
780 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
786 return Loc.getLocWithOffset(Len);
789 /// Returns true if the given MacroID location points at the first
790 /// token of the macro expansion.
791 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
792 const SourceManager &SM,
793 const LangOptions &LangOpts,
794 SourceLocation *MacroBegin) {
795 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
797 SourceLocation expansionLoc;
798 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
801 if (expansionLoc.isFileID()) {
802 // No other macro expansions, this is the first.
804 *MacroBegin = expansionLoc;
808 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
811 /// Returns true if the given MacroID location points at the last
812 /// token of the macro expansion.
813 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
814 const SourceManager &SM,
815 const LangOptions &LangOpts,
816 SourceLocation *MacroEnd) {
817 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
819 SourceLocation spellLoc = SM.getSpellingLoc(loc);
820 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
824 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
825 SourceLocation expansionLoc;
826 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
829 if (expansionLoc.isFileID()) {
830 // No other macro expansions.
832 *MacroEnd = expansionLoc;
836 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
839 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
840 const SourceManager &SM,
841 const LangOptions &LangOpts) {
842 SourceLocation Begin = Range.getBegin();
843 SourceLocation End = Range.getEnd();
844 assert(Begin.isFileID() && End.isFileID());
845 if (Range.isTokenRange()) {
846 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
851 // Break down the source locations.
854 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
859 if (!SM.isInFileID(End, FID, &EndOffs) ||
863 return CharSourceRange::getCharRange(Begin, End);
866 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
867 const SourceManager &SM,
868 const LangOptions &LangOpts) {
869 SourceLocation Begin = Range.getBegin();
870 SourceLocation End = Range.getEnd();
871 if (Begin.isInvalid() || End.isInvalid())
874 if (Begin.isFileID() && End.isFileID())
875 return makeRangeFromFileLocs(Range, SM, LangOpts);
877 if (Begin.isMacroID() && End.isFileID()) {
878 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
880 Range.setBegin(Begin);
881 return makeRangeFromFileLocs(Range, SM, LangOpts);
884 if (Begin.isFileID() && End.isMacroID()) {
885 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
887 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
891 return makeRangeFromFileLocs(Range, SM, LangOpts);
894 assert(Begin.isMacroID() && End.isMacroID());
895 SourceLocation MacroBegin, MacroEnd;
896 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
897 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
899 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
901 Range.setBegin(MacroBegin);
902 Range.setEnd(MacroEnd);
903 return makeRangeFromFileLocs(Range, SM, LangOpts);
906 bool Invalid = false;
907 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
912 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
913 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
918 if (EndEntry.getExpansion().isMacroArgExpansion() &&
919 BeginEntry.getExpansion().getExpansionLocStart() ==
920 EndEntry.getExpansion().getExpansionLocStart()) {
921 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
922 Range.setEnd(SM.getImmediateSpellingLoc(End));
923 return makeFileCharRange(Range, SM, LangOpts);
930 StringRef Lexer::getSourceText(CharSourceRange Range,
931 const SourceManager &SM,
932 const LangOptions &LangOpts,
934 Range = makeFileCharRange(Range, SM, LangOpts);
935 if (Range.isInvalid()) {
936 if (Invalid) *Invalid = true;
940 // Break down the source location.
941 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
942 if (beginInfo.first.isInvalid()) {
943 if (Invalid) *Invalid = true;
948 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
949 beginInfo.second > EndOffs) {
950 if (Invalid) *Invalid = true;
954 // Try to the load the file buffer.
955 bool invalidTemp = false;
956 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
958 if (Invalid) *Invalid = true;
962 if (Invalid) *Invalid = false;
963 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
966 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
967 const SourceManager &SM,
968 const LangOptions &LangOpts) {
969 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
971 // Find the location of the immediate macro expansion.
973 FileID FID = SM.getFileID(Loc);
974 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
975 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
976 Loc = Expansion.getExpansionLocStart();
977 if (!Expansion.isMacroArgExpansion())
980 // For macro arguments we need to check that the argument did not come
981 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
983 // Loc points to the argument id of the macro definition, move to the
985 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
986 SourceLocation SpellLoc = Expansion.getSpellingLoc();
987 if (SpellLoc.isFileID())
988 break; // No inner macro.
990 // If spelling location resides in the same FileID as macro expansion
991 // location, it means there is no inner macro.
992 FileID MacroFID = SM.getFileID(Loc);
993 if (SM.isInFileID(SpellLoc, MacroFID))
996 // Argument came from inner macro.
1000 // Find the spelling location of the start of the non-argument expansion
1001 // range. This is where the macro name was spelled in order to begin
1002 // expanding this macro.
1003 Loc = SM.getSpellingLoc(Loc);
1005 // Dig out the buffer where the macro name was spelled and the extents of the
1006 // name so that we can render it into the expansion note.
1007 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1008 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1009 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1010 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1013 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1014 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1015 assert(Loc.isMacroID() && "Only reasonable to call this on macros");
1016 // Walk past macro argument expansions.
1017 while (SM.isMacroArgExpansion(Loc))
1018 Loc = SM.getImmediateExpansionRange(Loc).getBegin();
1020 // If the macro's spelling has no FileID, then it's actually a token paste
1021 // or stringization (or similar) and not a macro at all.
1022 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1025 // Find the spelling location of the start of the non-argument expansion
1026 // range. This is where the macro name was spelled in order to begin
1027 // expanding this macro.
1028 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).getBegin());
1030 // Dig out the buffer where the macro name was spelled and the extents of the
1031 // name so that we can render it into the expansion note.
1032 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1033 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1034 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1035 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1038 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1039 return isIdentifierBody(c, LangOpts.DollarIdents);
1042 bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
1043 assert(isVerticalWhitespace(Str[0]));
1044 if (Str - 1 < BufferStart)
1047 if ((Str[0] == '\n' && Str[-1] == '\r') ||
1048 (Str[0] == '\r' && Str[-1] == '\n')) {
1049 if (Str - 2 < BufferStart)
1055 // Rewind to first non-space character:
1056 while (Str > BufferStart && isHorizontalWhitespace(*Str))
1059 return *Str == '\\';
1062 StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1063 const SourceManager &SM) {
1064 if (Loc.isInvalid() || Loc.isMacroID())
1066 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1067 if (LocInfo.first.isInvalid())
1069 bool Invalid = false;
1070 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1073 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1076 StringRef Rest = Buffer.substr(Line - Buffer.data());
1077 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1078 return NumWhitespaceChars == StringRef::npos
1080 : Rest.take_front(NumWhitespaceChars);
1083 //===----------------------------------------------------------------------===//
1084 // Diagnostics forwarding code.
1085 //===----------------------------------------------------------------------===//
1087 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1088 /// lexer buffer was all expanded at a single point, perform the mapping.
1089 /// This is currently only used for _Pragma implementation, so it is the slow
1090 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1091 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1092 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1093 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1094 SourceLocation FileLoc,
1095 unsigned CharNo, unsigned TokLen) {
1096 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1098 // Otherwise, we're lexing "mapped tokens". This is used for things like
1099 // _Pragma handling. Combine the expansion location of FileLoc with the
1100 // spelling location.
1101 SourceManager &SM = PP.getSourceManager();
1103 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1104 // characters come from spelling(FileLoc)+Offset.
1105 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1106 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1108 // Figure out the expansion loc range, which is the range covered by the
1109 // original _Pragma(...) sequence.
1110 CharSourceRange II = SM.getImmediateExpansionRange(FileLoc);
1112 return SM.createExpansionLoc(SpellingLoc, II.getBegin(), II.getEnd(), TokLen);
1115 /// getSourceLocation - Return a source location identifier for the specified
1116 /// offset in the current file.
1117 SourceLocation Lexer::getSourceLocation(const char *Loc,
1118 unsigned TokLen) const {
1119 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1120 "Location out of range for this buffer!");
1122 // In the normal case, we're just lexing from a simple file buffer, return
1123 // the file id from FileLoc with the offset specified.
1124 unsigned CharNo = Loc-BufferStart;
1125 if (FileLoc.isFileID())
1126 return FileLoc.getLocWithOffset(CharNo);
1128 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1129 // tokens are lexed from where the _Pragma was defined.
1130 assert(PP && "This doesn't work on raw lexers");
1131 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1134 /// Diag - Forwarding function for diagnostics. This translate a source
1135 /// position in the current buffer into a SourceLocation object for rendering.
1136 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1137 return PP->Diag(getSourceLocation(Loc), DiagID);
1140 //===----------------------------------------------------------------------===//
1141 // Trigraph and Escaped Newline Handling Code.
1142 //===----------------------------------------------------------------------===//
1144 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1145 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1146 static char GetTrigraphCharForLetter(char Letter) {
1149 case '=': return '#';
1150 case ')': return ']';
1151 case '(': return '[';
1152 case '!': return '|';
1153 case '\'': return '^';
1154 case '>': return '}';
1155 case '/': return '\\';
1156 case '<': return '{';
1157 case '-': return '~';
1161 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1162 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1163 /// return the result character. Finally, emit a warning about trigraph use
1164 /// whether trigraphs are enabled or not.
1165 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1166 char Res = GetTrigraphCharForLetter(*CP);
1167 if (!Res || !L) return Res;
1169 if (!L->getLangOpts().Trigraphs) {
1170 if (!L->isLexingRawMode())
1171 L->Diag(CP-2, diag::trigraph_ignored);
1175 if (!L->isLexingRawMode())
1176 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1180 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1181 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1182 /// trigraph equivalent on entry to this function.
1183 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1185 while (isWhitespace(Ptr[Size])) {
1188 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1191 // If this is a \r\n or \n\r, skip the other half.
1192 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1193 Ptr[Size-1] != Ptr[Size])
1199 // Not an escaped newline, must be a \t or something else.
1203 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1204 /// them), skip over them and return the first non-escaped-newline found,
1205 /// otherwise return P.
1206 const char *Lexer::SkipEscapedNewLines(const char *P) {
1208 const char *AfterEscape;
1211 } else if (*P == '?') {
1212 // If not a trigraph for escape, bail out.
1213 if (P[1] != '?' || P[2] != '/')
1215 // FIXME: Take LangOpts into account; the language might not
1216 // support trigraphs.
1222 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1223 if (NewLineSize == 0) return P;
1224 P = AfterEscape+NewLineSize;
1228 Optional<Token> Lexer::findNextToken(SourceLocation Loc,
1229 const SourceManager &SM,
1230 const LangOptions &LangOpts) {
1231 if (Loc.isMacroID()) {
1232 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1235 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1237 // Break down the source location.
1238 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1240 // Try to load the file buffer.
1241 bool InvalidTemp = false;
1242 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1246 const char *TokenBegin = File.data() + LocInfo.second;
1248 // Lex from the start of the given location.
1249 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1250 TokenBegin, File.end());
1253 lexer.LexFromRawLexer(Tok);
1257 /// Checks that the given token is the first token that occurs after the
1258 /// given location (this excludes comments and whitespace). Returns the location
1259 /// immediately after the specified token. If the token is not found or the
1260 /// location is inside a macro, the returned source location will be invalid.
1261 SourceLocation Lexer::findLocationAfterToken(
1262 SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
1263 const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
1264 Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
1265 if (!Tok || Tok->isNot(TKind))
1267 SourceLocation TokenLoc = Tok->getLocation();
1269 // Calculate how much whitespace needs to be skipped if any.
1270 unsigned NumWhitespaceChars = 0;
1271 if (SkipTrailingWhitespaceAndNewLine) {
1272 const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
1273 unsigned char C = *TokenEnd;
1274 while (isHorizontalWhitespace(C)) {
1276 NumWhitespaceChars++;
1279 // Skip \r, \n, \r\n, or \n\r
1280 if (C == '\n' || C == '\r') {
1283 NumWhitespaceChars++;
1284 if ((C == '\n' || C == '\r') && C != PrevC)
1285 NumWhitespaceChars++;
1289 return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
1292 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1293 /// get its size, and return it. This is tricky in several cases:
1294 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1295 /// then either return the trigraph (skipping 3 chars) or the '?',
1296 /// depending on whether trigraphs are enabled or not.
1297 /// 2. If this is an escaped newline (potentially with whitespace between
1298 /// the backslash and newline), implicitly skip the newline and return
1299 /// the char after it.
1301 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1302 /// know that we can accumulate into Size, and that we have already incremented
1303 /// Ptr by Size bytes.
1305 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1306 /// be updated to match.
1307 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1309 // If we have a slash, look for an escaped newline.
1310 if (Ptr[0] == '\\') {
1314 // Common case, backslash-char where the char is not whitespace.
1315 if (!isWhitespace(Ptr[0])) return '\\';
1317 // See if we have optional whitespace characters between the slash and
1319 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1320 // Remember that this token needs to be cleaned.
1321 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1323 // Warn if there was whitespace between the backslash and newline.
1324 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1325 Diag(Ptr, diag::backslash_newline_space);
1327 // Found backslash<whitespace><newline>. Parse the char after it.
1328 Size += EscapedNewLineSize;
1329 Ptr += EscapedNewLineSize;
1331 // Use slow version to accumulate a correct size field.
1332 return getCharAndSizeSlow(Ptr, Size, Tok);
1335 // Otherwise, this is not an escaped newline, just return the slash.
1339 // If this is a trigraph, process it.
1340 if (Ptr[0] == '?' && Ptr[1] == '?') {
1341 // If this is actually a legal trigraph (not something like "??x"), emit
1342 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1343 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1344 // Remember that this token needs to be cleaned.
1345 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1349 if (C == '\\') goto Slash;
1354 // If this is neither, return a single character.
1359 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1360 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1361 /// and that we have already incremented Ptr by Size bytes.
1363 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1364 /// be updated to match.
1365 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1366 const LangOptions &LangOpts) {
1367 // If we have a slash, look for an escaped newline.
1368 if (Ptr[0] == '\\') {
1372 // Common case, backslash-char where the char is not whitespace.
1373 if (!isWhitespace(Ptr[0])) return '\\';
1375 // See if we have optional whitespace characters followed by a newline.
1376 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1377 // Found backslash<whitespace><newline>. Parse the char after it.
1378 Size += EscapedNewLineSize;
1379 Ptr += EscapedNewLineSize;
1381 // Use slow version to accumulate a correct size field.
1382 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1385 // Otherwise, this is not an escaped newline, just return the slash.
1389 // If this is a trigraph, process it.
1390 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1391 // If this is actually a legal trigraph (not something like "??x"), return
1393 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1396 if (C == '\\') goto Slash;
1401 // If this is neither, return a single character.
1406 //===----------------------------------------------------------------------===//
1407 // Helper methods for lexing.
1408 //===----------------------------------------------------------------------===//
1410 /// Routine that indiscriminately sets the offset into the source file.
1411 void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
1412 BufferPtr = BufferStart + Offset;
1413 if (BufferPtr > BufferEnd)
1414 BufferPtr = BufferEnd;
1415 // FIXME: What exactly does the StartOfLine bit mean? There are two
1416 // possible meanings for the "start" of the line: the first token on the
1417 // unexpanded line, or the first token on the expanded line.
1418 IsAtStartOfLine = StartOfLine;
1419 IsAtPhysicalStartOfLine = StartOfLine;
1422 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1423 if (LangOpts.AsmPreprocessor) {
1425 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1426 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1427 C11AllowedIDCharRanges);
1428 return C11AllowedIDChars.contains(C);
1429 } else if (LangOpts.CPlusPlus) {
1430 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1431 CXX03AllowedIDCharRanges);
1432 return CXX03AllowedIDChars.contains(C);
1434 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1435 C99AllowedIDCharRanges);
1436 return C99AllowedIDChars.contains(C);
1440 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1441 assert(isAllowedIDChar(C, LangOpts));
1442 if (LangOpts.AsmPreprocessor) {
1444 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1445 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1446 C11DisallowedInitialIDCharRanges);
1447 return !C11DisallowedInitialIDChars.contains(C);
1448 } else if (LangOpts.CPlusPlus) {
1451 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1452 C99DisallowedInitialIDCharRanges);
1453 return !C99DisallowedInitialIDChars.contains(C);
1457 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1459 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1460 L.getSourceLocation(End));
1463 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1464 CharSourceRange Range, bool IsFirst) {
1465 // Check C99 compatibility.
1466 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1468 CannotAppearInIdentifier = 0,
1469 CannotStartIdentifier
1472 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1473 C99AllowedIDCharRanges);
1474 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1475 C99DisallowedInitialIDCharRanges);
1476 if (!C99AllowedIDChars.contains(C)) {
1477 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1479 << CannotAppearInIdentifier;
1480 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1481 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1483 << CannotStartIdentifier;
1487 // Check C++98 compatibility.
1488 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1489 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1490 CXX03AllowedIDCharRanges);
1491 if (!CXX03AllowedIDChars.contains(C)) {
1492 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1498 /// After encountering UTF-8 character C and interpreting it as an identifier
1499 /// character, check whether it's a homoglyph for a common non-identifier
1500 /// source character that is unlikely to be an intentional identifier
1501 /// character and warn if so.
1502 static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C,
1503 CharSourceRange Range) {
1504 // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
1505 struct HomoglyphPair {
1508 bool operator<(HomoglyphPair R) const { return Character < R.Character; }
1510 static constexpr HomoglyphPair SortedHomoglyphs[] = {
1511 {U'\u00ad', 0}, // SOFT HYPHEN
1512 {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
1513 {U'\u037e', ';'}, // GREEK QUESTION MARK
1514 {U'\u200b', 0}, // ZERO WIDTH SPACE
1515 {U'\u200c', 0}, // ZERO WIDTH NON-JOINER
1516 {U'\u200d', 0}, // ZERO WIDTH JOINER
1517 {U'\u2060', 0}, // WORD JOINER
1518 {U'\u2061', 0}, // FUNCTION APPLICATION
1519 {U'\u2062', 0}, // INVISIBLE TIMES
1520 {U'\u2063', 0}, // INVISIBLE SEPARATOR
1521 {U'\u2064', 0}, // INVISIBLE PLUS
1522 {U'\u2212', '-'}, // MINUS SIGN
1523 {U'\u2215', '/'}, // DIVISION SLASH
1524 {U'\u2216', '\\'}, // SET MINUS
1525 {U'\u2217', '*'}, // ASTERISK OPERATOR
1526 {U'\u2223', '|'}, // DIVIDES
1527 {U'\u2227', '^'}, // LOGICAL AND
1528 {U'\u2236', ':'}, // RATIO
1529 {U'\u223c', '~'}, // TILDE OPERATOR
1530 {U'\ua789', ':'}, // MODIFIER LETTER COLON
1531 {U'\ufeff', 0}, // ZERO WIDTH NO-BREAK SPACE
1532 {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
1533 {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
1534 {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
1535 {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
1536 {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
1537 {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
1538 {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
1539 {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
1540 {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
1541 {U'\uff0c', ','}, // FULLWIDTH COMMA
1542 {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
1543 {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
1544 {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
1545 {U'\uff1a', ':'}, // FULLWIDTH COLON
1546 {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
1547 {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
1548 {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
1549 {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
1550 {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
1551 {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
1552 {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
1553 {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
1554 {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
1555 {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
1556 {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
1557 {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
1558 {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
1559 {U'\uff5e', '~'}, // FULLWIDTH TILDE
1563 std::lower_bound(std::begin(SortedHomoglyphs),
1564 std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
1565 if (Homoglyph->Character == C) {
1566 llvm::SmallString<5> CharBuf;
1568 llvm::raw_svector_ostream CharOS(CharBuf);
1569 llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
1571 if (Homoglyph->LooksLike) {
1572 const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
1573 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
1574 << Range << CharBuf << LooksLikeStr;
1576 Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_zero_width)
1577 << Range << CharBuf;
1582 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1584 const char *UCNPtr = CurPtr + Size;
1585 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1586 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1589 if (!isLexingRawMode())
1590 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1591 makeCharRange(*this, CurPtr, UCNPtr),
1594 Result.setFlag(Token::HasUCN);
1595 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1596 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1599 while (CurPtr != UCNPtr)
1600 (void)getAndAdvanceChar(CurPtr, Result);
1604 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1605 const char *UnicodePtr = CurPtr;
1606 llvm::UTF32 CodePoint;
1607 llvm::ConversionResult Result =
1608 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1609 (const llvm::UTF8 *)BufferEnd,
1611 llvm::strictConversion);
1612 if (Result != llvm::conversionOK ||
1613 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1616 if (!isLexingRawMode()) {
1617 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1618 makeCharRange(*this, CurPtr, UnicodePtr),
1620 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
1621 makeCharRange(*this, CurPtr, UnicodePtr));
1624 CurPtr = UnicodePtr;
1628 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1629 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1631 unsigned char C = *CurPtr++;
1632 while (isIdentifierBody(C))
1635 --CurPtr; // Back up over the skipped character.
1637 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1638 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1640 // TODO: Could merge these checks into an InfoTable flag to make the
1641 // comparison cheaper
1642 if (isASCII(C) && C != '\\' && C != '?' &&
1643 (C != '$' || !LangOpts.DollarIdents)) {
1645 const char *IdStart = BufferPtr;
1646 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1647 Result.setRawIdentifierData(IdStart);
1649 // If we are in raw mode, return this identifier raw. There is no need to
1650 // look up identifier information or attempt to macro expand it.
1654 // Fill in Result.IdentifierInfo and update the token kind,
1655 // looking up the identifier in the identifier table.
1656 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1657 // Note that we have to call PP->LookUpIdentifierInfo() even for code
1658 // completion, it writes IdentifierInfo into Result, and callers rely on it.
1660 // If the completion point is at the end of an identifier, we want to treat
1661 // the identifier as incomplete even if it resolves to a macro or a keyword.
1662 // This allows e.g. 'class^' to complete to 'classifier'.
1663 if (isCodeCompletionPoint(CurPtr)) {
1664 // Return the code-completion token.
1665 Result.setKind(tok::code_completion);
1666 // Skip the code-completion char and all immediate identifier characters.
1667 // This ensures we get consistent behavior when completing at any point in
1668 // an identifier (i.e. at the start, in the middle, at the end). Note that
1669 // only simple cases (i.e. [a-zA-Z0-9_]) are supported to keep the code
1671 assert(*CurPtr == 0 && "Completion character must be 0");
1673 // Note that code completion token is not added as a separate character
1674 // when the completion point is at the end of the buffer. Therefore, we need
1675 // to check if the buffer has ended.
1676 if (CurPtr < BufferEnd) {
1677 while (isIdentifierBody(*CurPtr))
1684 // Finally, now that we know we have an identifier, pass this off to the
1685 // preprocessor, which may macro expand it or something.
1686 if (II->isHandleIdentifierCase())
1687 return PP->HandleIdentifier(Result);
1692 // Otherwise, $,\,? in identifier found. Enter slower path.
1694 C = getCharAndSize(CurPtr, Size);
1697 // If we hit a $ and they are not supported in identifiers, we are done.
1698 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1700 // Otherwise, emit a diagnostic and continue.
1701 if (!isLexingRawMode())
1702 Diag(CurPtr, diag::ext_dollar_in_identifier);
1703 CurPtr = ConsumeChar(CurPtr, Size, Result);
1704 C = getCharAndSize(CurPtr, Size);
1706 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1707 C = getCharAndSize(CurPtr, Size);
1709 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1710 C = getCharAndSize(CurPtr, Size);
1712 } else if (!isIdentifierBody(C)) {
1713 goto FinishIdentifier;
1716 // Otherwise, this character is good, consume it.
1717 CurPtr = ConsumeChar(CurPtr, Size, Result);
1719 C = getCharAndSize(CurPtr, Size);
1720 while (isIdentifierBody(C)) {
1721 CurPtr = ConsumeChar(CurPtr, Size, Result);
1722 C = getCharAndSize(CurPtr, Size);
1727 /// isHexaLiteral - Return true if Start points to a hex constant.
1728 /// in microsoft mode (where this is supposed to be several different tokens).
1729 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1731 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1734 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1735 return (C2 == 'x' || C2 == 'X');
1738 /// LexNumericConstant - Lex the remainder of a integer or floating point
1739 /// constant. From[-1] is the first character lexed. Return the end of the
1741 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1743 char C = getCharAndSize(CurPtr, Size);
1745 while (isPreprocessingNumberBody(C)) {
1746 CurPtr = ConsumeChar(CurPtr, Size, Result);
1748 C = getCharAndSize(CurPtr, Size);
1751 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1752 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1753 // If we are in Microsoft mode, don't continue if the constant is hex.
1754 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1755 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1756 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1759 // If we have a hex FP constant, continue.
1760 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1761 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1762 // not-quite-conforming extension. Only do so if this looks like it's
1763 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1764 bool IsHexFloat = true;
1765 if (!LangOpts.C99) {
1766 if (!isHexaLiteral(BufferPtr, LangOpts))
1768 else if (!getLangOpts().CPlusPlus17 &&
1769 std::find(BufferPtr, CurPtr, '_') != CurPtr)
1773 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1776 // If we have a digit separator, continue.
1777 if (C == '\'' && getLangOpts().CPlusPlus14) {
1779 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1780 if (isIdentifierBody(Next)) {
1781 if (!isLexingRawMode())
1782 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1783 CurPtr = ConsumeChar(CurPtr, Size, Result);
1784 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1785 return LexNumericConstant(Result, CurPtr);
1789 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1790 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1791 return LexNumericConstant(Result, CurPtr);
1792 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1793 return LexNumericConstant(Result, CurPtr);
1795 // Update the location of token as well as BufferPtr.
1796 const char *TokStart = BufferPtr;
1797 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1798 Result.setLiteralData(TokStart);
1802 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1803 /// in C++11, or warn on a ud-suffix in C++98.
1804 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1805 bool IsStringLiteral) {
1806 assert(getLangOpts().CPlusPlus);
1808 // Maximally munch an identifier.
1810 char C = getCharAndSize(CurPtr, Size);
1811 bool Consumed = false;
1813 if (!isIdentifierHead(C)) {
1814 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1816 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1822 if (!getLangOpts().CPlusPlus11) {
1823 if (!isLexingRawMode())
1825 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1826 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1827 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1831 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1832 // that does not start with an underscore is ill-formed. As a conforming
1833 // extension, we treat all such suffixes as if they had whitespace before
1834 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1835 // likely to be a ud-suffix than a macro, however, and accept that.
1837 bool IsUDSuffix = false;
1840 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1841 // In C++1y, we need to look ahead a few characters to see if this is a
1842 // valid suffix for a string literal or a numeric literal (this could be
1843 // the 'operator""if' defining a numeric literal operator).
1844 const unsigned MaxStandardSuffixLength = 3;
1845 char Buffer[MaxStandardSuffixLength] = { C };
1846 unsigned Consumed = Size;
1850 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1852 if (!isIdentifierBody(Next)) {
1853 // End of suffix. Check whether this is on the whitelist.
1854 const StringRef CompleteSuffix(Buffer, Chars);
1855 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1860 if (Chars == MaxStandardSuffixLength)
1861 // Too long: can't be a standard suffix.
1864 Buffer[Chars++] = Next;
1865 Consumed += NextSize;
1870 if (!isLexingRawMode())
1871 Diag(CurPtr, getLangOpts().MSVCCompat
1872 ? diag::ext_ms_reserved_user_defined_literal
1873 : diag::ext_reserved_user_defined_literal)
1874 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1878 CurPtr = ConsumeChar(CurPtr, Size, Result);
1881 Result.setFlag(Token::HasUDSuffix);
1883 C = getCharAndSize(CurPtr, Size);
1884 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1885 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1886 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1893 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1894 /// either " or L" or u8" or u" or U".
1895 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1896 tok::TokenKind Kind) {
1897 const char *AfterQuote = CurPtr;
1898 // Does this string contain the \0 character?
1899 const char *NulCharacter = nullptr;
1901 if (!isLexingRawMode() &&
1902 (Kind == tok::utf8_string_literal ||
1903 Kind == tok::utf16_string_literal ||
1904 Kind == tok::utf32_string_literal))
1905 Diag(BufferPtr, getLangOpts().CPlusPlus
1906 ? diag::warn_cxx98_compat_unicode_literal
1907 : diag::warn_c99_compat_unicode_literal);
1909 char C = getAndAdvanceChar(CurPtr, Result);
1911 // Skip escaped characters. Escaped newlines will already be processed by
1912 // getAndAdvanceChar.
1914 C = getAndAdvanceChar(CurPtr, Result);
1916 if (C == '\n' || C == '\r' || // Newline.
1917 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1918 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1919 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1920 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1925 if (isCodeCompletionPoint(CurPtr-1)) {
1926 if (ParsingFilename)
1927 codeCompleteIncludedFile(AfterQuote, CurPtr - 1, /*IsAngled=*/false);
1929 PP->CodeCompleteNaturalLanguage();
1930 FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
1935 NulCharacter = CurPtr-1;
1937 C = getAndAdvanceChar(CurPtr, Result);
1940 // If we are in C++11, lex the optional ud-suffix.
1941 if (getLangOpts().CPlusPlus)
1942 CurPtr = LexUDSuffix(Result, CurPtr, true);
1944 // If a nul character existed in the string, warn about it.
1945 if (NulCharacter && !isLexingRawMode())
1946 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1948 // Update the location of the token as well as the BufferPtr instance var.
1949 const char *TokStart = BufferPtr;
1950 FormTokenWithChars(Result, CurPtr, Kind);
1951 Result.setLiteralData(TokStart);
1955 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1956 /// having lexed R", LR", u8R", uR", or UR".
1957 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1958 tok::TokenKind Kind) {
1959 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1960 // Between the initial and final double quote characters of the raw string,
1961 // any transformations performed in phases 1 and 2 (trigraphs,
1962 // universal-character-names, and line splicing) are reverted.
1964 if (!isLexingRawMode())
1965 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1967 unsigned PrefixLen = 0;
1969 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1972 // If the last character was not a '(', then we didn't lex a valid delimiter.
1973 if (CurPtr[PrefixLen] != '(') {
1974 if (!isLexingRawMode()) {
1975 const char *PrefixEnd = &CurPtr[PrefixLen];
1976 if (PrefixLen == 16) {
1977 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1979 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1980 << StringRef(PrefixEnd, 1);
1984 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1985 // it's possible the '"' was intended to be part of the raw string, but
1986 // there's not much we can do about that.
1992 if (C == 0 && CurPtr-1 == BufferEnd) {
1998 FormTokenWithChars(Result, CurPtr, tok::unknown);
2002 // Save prefix and move CurPtr past it
2003 const char *Prefix = CurPtr;
2004 CurPtr += PrefixLen + 1; // skip over prefix and '('
2010 // Check for prefix match and closing quote.
2011 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
2012 CurPtr += PrefixLen + 1; // skip over prefix and '"'
2015 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
2016 if (!isLexingRawMode())
2017 Diag(BufferPtr, diag::err_unterminated_raw_string)
2018 << StringRef(Prefix, PrefixLen);
2019 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2024 // If we are in C++11, lex the optional ud-suffix.
2025 if (getLangOpts().CPlusPlus)
2026 CurPtr = LexUDSuffix(Result, CurPtr, true);
2028 // Update the location of token as well as BufferPtr.
2029 const char *TokStart = BufferPtr;
2030 FormTokenWithChars(Result, CurPtr, Kind);
2031 Result.setLiteralData(TokStart);
2035 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
2036 /// after having lexed the '<' character. This is used for #include filenames.
2037 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
2038 // Does this string contain the \0 character?
2039 const char *NulCharacter = nullptr;
2040 const char *AfterLessPos = CurPtr;
2041 char C = getAndAdvanceChar(CurPtr, Result);
2043 // Skip escaped characters. Escaped newlines will already be processed by
2044 // getAndAdvanceChar.
2046 C = getAndAdvanceChar(CurPtr, Result);
2048 if (C == '\n' || C == '\r' || // Newline.
2049 (C == 0 && (CurPtr - 1 == BufferEnd))) { // End of file.
2050 // If the filename is unterminated, then it must just be a lone <
2051 // character. Return this as such.
2052 FormTokenWithChars(Result, AfterLessPos, tok::less);
2057 if (isCodeCompletionPoint(CurPtr - 1)) {
2058 codeCompleteIncludedFile(AfterLessPos, CurPtr - 1, /*IsAngled=*/true);
2060 FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
2063 NulCharacter = CurPtr-1;
2065 C = getAndAdvanceChar(CurPtr, Result);
2068 // If a nul character existed in the string, warn about it.
2069 if (NulCharacter && !isLexingRawMode())
2070 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
2072 // Update the location of token as well as BufferPtr.
2073 const char *TokStart = BufferPtr;
2074 FormTokenWithChars(Result, CurPtr, tok::header_name);
2075 Result.setLiteralData(TokStart);
2079 void Lexer::codeCompleteIncludedFile(const char *PathStart,
2080 const char *CompletionPoint,
2082 // Completion only applies to the filename, after the last slash.
2083 StringRef PartialPath(PathStart, CompletionPoint - PathStart);
2084 auto Slash = PartialPath.find_last_of(LangOpts.MSVCCompat ? "/\\" : "/");
2086 (Slash == StringRef::npos) ? "" : PartialPath.take_front(Slash);
2087 const char *StartOfFilename =
2088 (Slash == StringRef::npos) ? PathStart : PathStart + Slash + 1;
2089 // Code completion filter range is the filename only, up to completion point.
2090 PP->setCodeCompletionIdentifierInfo(&PP->getIdentifierTable().get(
2091 StringRef(StartOfFilename, CompletionPoint - StartOfFilename)));
2092 // We should replace the characters up to the closing quote, if any.
2093 while (CompletionPoint < BufferEnd) {
2094 char Next = *(CompletionPoint + 1);
2095 if (Next == 0 || Next == '\r' || Next == '\n')
2098 if (Next == (IsAngled ? '>' : '"'))
2101 PP->setCodeCompletionTokenRange(
2102 FileLoc.getLocWithOffset(StartOfFilename - BufferStart),
2103 FileLoc.getLocWithOffset(CompletionPoint - BufferStart));
2104 PP->CodeCompleteIncludedFile(Dir, IsAngled);
2107 /// LexCharConstant - Lex the remainder of a character constant, after having
2108 /// lexed either ' or L' or u8' or u' or U'.
2109 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
2110 tok::TokenKind Kind) {
2111 // Does this character contain the \0 character?
2112 const char *NulCharacter = nullptr;
2114 if (!isLexingRawMode()) {
2115 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
2116 Diag(BufferPtr, getLangOpts().CPlusPlus
2117 ? diag::warn_cxx98_compat_unicode_literal
2118 : diag::warn_c99_compat_unicode_literal);
2119 else if (Kind == tok::utf8_char_constant)
2120 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
2123 char C = getAndAdvanceChar(CurPtr, Result);
2125 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2126 Diag(BufferPtr, diag::ext_empty_character);
2127 FormTokenWithChars(Result, CurPtr, tok::unknown);
2132 // Skip escaped characters.
2134 C = getAndAdvanceChar(CurPtr, Result);
2136 if (C == '\n' || C == '\r' || // Newline.
2137 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
2138 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
2139 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
2140 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2145 if (isCodeCompletionPoint(CurPtr-1)) {
2146 PP->CodeCompleteNaturalLanguage();
2147 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2152 NulCharacter = CurPtr-1;
2154 C = getAndAdvanceChar(CurPtr, Result);
2157 // If we are in C++11, lex the optional ud-suffix.
2158 if (getLangOpts().CPlusPlus)
2159 CurPtr = LexUDSuffix(Result, CurPtr, false);
2161 // If a nul character existed in the character, warn about it.
2162 if (NulCharacter && !isLexingRawMode())
2163 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2165 // Update the location of token as well as BufferPtr.
2166 const char *TokStart = BufferPtr;
2167 FormTokenWithChars(Result, CurPtr, Kind);
2168 Result.setLiteralData(TokStart);
2172 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2173 /// Update BufferPtr to point to the next non-whitespace character and return.
2175 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2176 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2177 bool &TokAtPhysicalStartOfLine) {
2178 // Whitespace - Skip it, then return the token after the whitespace.
2179 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2181 unsigned char Char = *CurPtr;
2183 // Skip consecutive spaces efficiently.
2185 // Skip horizontal whitespace very aggressively.
2186 while (isHorizontalWhitespace(Char))
2189 // Otherwise if we have something other than whitespace, we're done.
2190 if (!isVerticalWhitespace(Char))
2193 if (ParsingPreprocessorDirective) {
2194 // End of preprocessor directive line, let LexTokenInternal handle this.
2199 // OK, but handle newline.
2204 // If the client wants us to return whitespace, return it now.
2205 if (isKeepWhitespaceMode()) {
2206 FormTokenWithChars(Result, CurPtr, tok::unknown);
2208 IsAtStartOfLine = true;
2209 IsAtPhysicalStartOfLine = true;
2211 // FIXME: The next token will not have LeadingSpace set.
2215 // If this isn't immediately after a newline, there is leading space.
2216 char PrevChar = CurPtr[-1];
2217 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2219 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2221 Result.setFlag(Token::StartOfLine);
2222 TokAtPhysicalStartOfLine = true;
2229 /// We have just read the // characters from input. Skip until we find the
2230 /// newline character that terminates the comment. Then update BufferPtr and
2233 /// If we're in KeepCommentMode or any CommentHandler has inserted
2234 /// some tokens, this will store the first token and return true.
2235 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2236 bool &TokAtPhysicalStartOfLine) {
2237 // If Line comments aren't explicitly enabled for this language, emit an
2238 // extension warning.
2239 if (!LangOpts.LineComment && !isLexingRawMode()) {
2240 Diag(BufferPtr, diag::ext_line_comment);
2242 // Mark them enabled so we only emit one warning for this translation
2244 LangOpts.LineComment = true;
2247 // Scan over the body of the comment. The common case, when scanning, is that
2248 // the comment contains normal ascii characters with nothing interesting in
2249 // them. As such, optimize for this case with the inner loop.
2251 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2252 // character that ends the line comment.
2256 // Skip over characters in the fast loop.
2257 while (C != 0 && // Potentially EOF.
2258 C != '\n' && C != '\r') // Newline or DOS-style newline.
2261 const char *NextLine = CurPtr;
2263 // We found a newline, see if it's escaped.
2264 const char *EscapePtr = CurPtr-1;
2265 bool HasSpace = false;
2266 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2271 if (*EscapePtr == '\\')
2274 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2275 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2276 // Trigraph-escaped newline.
2277 CurPtr = EscapePtr-2;
2279 break; // This is a newline, we're done.
2281 // If there was space between the backslash and newline, warn about it.
2282 if (HasSpace && !isLexingRawMode())
2283 Diag(EscapePtr, diag::backslash_newline_space);
2286 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2287 // properly decode the character. Read it in raw mode to avoid emitting
2288 // diagnostics about things like trigraphs. If we see an escaped newline,
2289 // we'll handle it below.
2290 const char *OldPtr = CurPtr;
2291 bool OldRawMode = isLexingRawMode();
2292 LexingRawMode = true;
2293 C = getAndAdvanceChar(CurPtr, Result);
2294 LexingRawMode = OldRawMode;
2296 // If we only read only one character, then no special handling is needed.
2297 // We're done and can skip forward to the newline.
2298 if (C != 0 && CurPtr == OldPtr+1) {
2303 // If we read multiple characters, and one of those characters was a \r or
2304 // \n, then we had an escaped newline within the comment. Emit diagnostic
2305 // unless the next line is also a // comment.
2306 if (CurPtr != OldPtr + 1 && C != '/' &&
2307 (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
2308 for (; OldPtr != CurPtr; ++OldPtr)
2309 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2310 // Okay, we found a // comment that ends in a newline, if the next
2311 // line is also a // comment, but has spaces, don't emit a diagnostic.
2312 if (isWhitespace(C)) {
2313 const char *ForwardPtr = CurPtr;
2314 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2316 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2320 if (!isLexingRawMode())
2321 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2326 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2331 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2332 PP->CodeCompleteNaturalLanguage();
2338 // Found but did not consume the newline. Notify comment handlers about the
2339 // comment unless we're in a #if 0 block.
2340 if (PP && !isLexingRawMode() &&
2341 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2342 getSourceLocation(CurPtr)))) {
2344 return true; // A token has to be returned.
2347 // If we are returning comments as tokens, return this comment as a token.
2348 if (inKeepCommentMode())
2349 return SaveLineComment(Result, CurPtr);
2351 // If we are inside a preprocessor directive and we see the end of line,
2352 // return immediately, so that the lexer can return this as an EOD token.
2353 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2358 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2359 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2360 // contribute to another token), it isn't needed for correctness. Note that
2361 // this is ok even in KeepWhitespaceMode, because we would have returned the
2362 /// comment above in that mode.
2365 // The next returned token is at the start of the line.
2366 Result.setFlag(Token::StartOfLine);
2367 TokAtPhysicalStartOfLine = true;
2368 // No leading whitespace seen so far.
2369 Result.clearFlag(Token::LeadingSpace);
2374 /// If in save-comment mode, package up this Line comment in an appropriate
2375 /// way and return it.
2376 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2377 // If we're not in a preprocessor directive, just return the // comment
2379 FormTokenWithChars(Result, CurPtr, tok::comment);
2381 if (!ParsingPreprocessorDirective || LexingRawMode)
2384 // If this Line-style comment is in a macro definition, transmogrify it into
2385 // a C-style block comment.
2386 bool Invalid = false;
2387 std::string Spelling = PP->getSpelling(Result, &Invalid);
2391 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2392 Spelling[1] = '*'; // Change prefix to "/*".
2393 Spelling += "*/"; // add suffix.
2395 Result.setKind(tok::comment);
2396 PP->CreateString(Spelling, Result,
2397 Result.getLocation(), Result.getLocation());
2401 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2402 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2403 /// a diagnostic if so. We know that the newline is inside of a block comment.
2404 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2406 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2408 // Back up off the newline.
2411 // If this is a two-character newline sequence, skip the other character.
2412 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2413 // \n\n or \r\r -> not escaped newline.
2414 if (CurPtr[0] == CurPtr[1])
2416 // \n\r or \r\n -> skip the newline.
2420 // If we have horizontal whitespace, skip over it. We allow whitespace
2421 // between the slash and newline.
2422 bool HasSpace = false;
2423 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2428 // If we have a slash, we know this is an escaped newline.
2429 if (*CurPtr == '\\') {
2430 if (CurPtr[-1] != '*') return false;
2432 // It isn't a slash, is it the ?? / trigraph?
2433 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2437 // This is the trigraph ending the comment. Emit a stern warning!
2440 // If no trigraphs are enabled, warn that we ignored this trigraph and
2441 // ignore this * character.
2442 if (!L->getLangOpts().Trigraphs) {
2443 if (!L->isLexingRawMode())
2444 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2447 if (!L->isLexingRawMode())
2448 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2451 // Warn about having an escaped newline between the */ characters.
2452 if (!L->isLexingRawMode())
2453 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2455 // If there was space between the backslash and newline, warn about it.
2456 if (HasSpace && !L->isLexingRawMode())
2457 L->Diag(CurPtr, diag::backslash_newline_space);
2463 #include <emmintrin.h>
2465 #include <altivec.h>
2469 /// We have just read from input the / and * characters that started a comment.
2470 /// Read until we find the * and / characters that terminate the comment.
2471 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2472 /// comments, because they cannot cause the comment to end. The only thing
2473 /// that can happen is the comment could end with an escaped newline between
2474 /// the terminating * and /.
2476 /// If we're in KeepCommentMode or any CommentHandler has inserted
2477 /// some tokens, this will store the first token and return true.
2478 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2479 bool &TokAtPhysicalStartOfLine) {
2480 // Scan one character past where we should, looking for a '/' character. Once
2481 // we find it, check to see if it was preceded by a *. This common
2482 // optimization helps people who like to put a lot of * characters in their
2485 // The first character we get with newlines and trigraphs skipped to handle
2486 // the degenerate /*/ case below correctly if the * has an escaped newline
2489 unsigned char C = getCharAndSize(CurPtr, CharSize);
2491 if (C == 0 && CurPtr == BufferEnd+1) {
2492 if (!isLexingRawMode())
2493 Diag(BufferPtr, diag::err_unterminated_block_comment);
2496 // KeepWhitespaceMode should return this broken comment as a token. Since
2497 // it isn't a well formed comment, just return it as an 'unknown' token.
2498 if (isKeepWhitespaceMode()) {
2499 FormTokenWithChars(Result, CurPtr, tok::unknown);
2507 // Check to see if the first character after the '/*' is another /. If so,
2508 // then this slash does not end the block comment, it is part of it.
2513 // Skip over all non-interesting characters until we find end of buffer or a
2514 // (probably ending) '/' character.
2515 if (CurPtr + 24 < BufferEnd &&
2516 // If there is a code-completion point avoid the fast scan because it
2517 // doesn't check for '\0'.
2518 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2519 // While not aligned to a 16-byte boundary.
2520 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2523 if (C == '/') goto FoundSlash;
2526 __m128i Slashes = _mm_set1_epi8('/');
2527 while (CurPtr+16 <= BufferEnd) {
2528 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2531 // Adjust the pointer to point directly after the first slash. It's
2532 // not necessary to set C here, it will be overwritten at the end of
2534 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2540 __vector unsigned char Slashes = {
2541 '/', '/', '/', '/', '/', '/', '/', '/',
2542 '/', '/', '/', '/', '/', '/', '/', '/'
2544 while (CurPtr+16 <= BufferEnd &&
2545 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2548 // Scan for '/' quickly. Many block comments are very large.
2549 while (CurPtr[0] != '/' &&
2553 CurPtr+4 < BufferEnd) {
2558 // It has to be one of the bytes scanned, increment to it and read one.
2562 // Loop to scan the remainder.
2563 while (C != '/' && C != '\0')
2568 if (CurPtr[-2] == '*') // We found the final */. We're done!
2571 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2572 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2573 // We found the final */, though it had an escaped newline between the
2574 // * and /. We're done!
2578 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2579 // If this is a /* inside of the comment, emit a warning. Don't do this
2580 // if this is a /*/, which will end the comment. This misses cases with
2581 // embedded escaped newlines, but oh well.
2582 if (!isLexingRawMode())
2583 Diag(CurPtr-1, diag::warn_nested_block_comment);
2585 } else if (C == 0 && CurPtr == BufferEnd+1) {
2586 if (!isLexingRawMode())
2587 Diag(BufferPtr, diag::err_unterminated_block_comment);
2588 // Note: the user probably forgot a */. We could continue immediately
2589 // after the /*, but this would involve lexing a lot of what really is the
2590 // comment, which surely would confuse the parser.
2593 // KeepWhitespaceMode should return this broken comment as a token. Since
2594 // it isn't a well formed comment, just return it as an 'unknown' token.
2595 if (isKeepWhitespaceMode()) {
2596 FormTokenWithChars(Result, CurPtr, tok::unknown);
2602 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2603 PP->CodeCompleteNaturalLanguage();
2611 // Notify comment handlers about the comment unless we're in a #if 0 block.
2612 if (PP && !isLexingRawMode() &&
2613 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2614 getSourceLocation(CurPtr)))) {
2616 return true; // A token has to be returned.
2619 // If we are returning comments as tokens, return this comment as a token.
2620 if (inKeepCommentMode()) {
2621 FormTokenWithChars(Result, CurPtr, tok::comment);
2625 // It is common for the tokens immediately after a /**/ comment to be
2626 // whitespace. Instead of going through the big switch, handle it
2627 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2628 // have already returned above with the comment as a token.
2629 if (isHorizontalWhitespace(*CurPtr)) {
2630 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2634 // Otherwise, just return so that the next character will be lexed as a token.
2636 Result.setFlag(Token::LeadingSpace);
2640 //===----------------------------------------------------------------------===//
2641 // Primary Lexing Entry Points
2642 //===----------------------------------------------------------------------===//
2644 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2645 /// uninterpreted string. This switches the lexer out of directive mode.
2646 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2647 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2648 "Must be in a preprocessing directive!");
2651 // CurPtr - Cache BufferPtr in an automatic variable.
2652 const char *CurPtr = BufferPtr;
2654 char Char = getAndAdvanceChar(CurPtr, Tmp);
2658 Result->push_back(Char);
2661 // Found end of file?
2662 if (CurPtr-1 != BufferEnd) {
2663 if (isCodeCompletionPoint(CurPtr-1)) {
2664 PP->CodeCompleteNaturalLanguage();
2669 // Nope, normal character, continue.
2671 Result->push_back(Char);
2678 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2679 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2680 BufferPtr = CurPtr-1;
2682 // Next, lex the character, which should handle the EOD transition.
2684 if (Tmp.is(tok::code_completion)) {
2686 PP->CodeCompleteNaturalLanguage();
2689 assert(Tmp.is(tok::eod) && "Unexpected token!");
2691 // Finally, we're done;
2697 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2698 /// condition, reporting diagnostics and handling other edge cases as required.
2699 /// This returns true if Result contains a token, false if PP.Lex should be
2701 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2702 // If we hit the end of the file while parsing a preprocessor directive,
2703 // end the preprocessor directive first. The next token returned will
2704 // then be the end of file.
2705 if (ParsingPreprocessorDirective) {
2706 // Done parsing the "line".
2707 ParsingPreprocessorDirective = false;
2708 // Update the location of token as well as BufferPtr.
2709 FormTokenWithChars(Result, CurPtr, tok::eod);
2711 // Restore comment saving mode, in case it was disabled for directive.
2713 resetExtendedTokenMode();
2714 return true; // Have a token.
2717 // If we are in raw mode, return this event as an EOF token. Let the caller
2718 // that put us in raw mode handle the event.
2719 if (isLexingRawMode()) {
2720 Result.startToken();
2721 BufferPtr = BufferEnd;
2722 FormTokenWithChars(Result, BufferEnd, tok::eof);
2726 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
2727 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2728 ConditionalStack.clear();
2731 // Issue diagnostics for unterminated #if and missing newline.
2733 // If we are in a #if directive, emit an error.
2734 while (!ConditionalStack.empty()) {
2735 if (PP->getCodeCompletionFileLoc() != FileLoc)
2736 PP->Diag(ConditionalStack.back().IfLoc,
2737 diag::err_pp_unterminated_conditional);
2738 ConditionalStack.pop_back();
2741 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2743 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2744 DiagnosticsEngine &Diags = PP->getDiagnostics();
2745 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2748 if (LangOpts.CPlusPlus11) {
2749 // C++11 [lex.phases] 2.2 p2
2750 // Prefer the C++98 pedantic compatibility warning over the generic,
2751 // non-extension, user-requested "missing newline at EOF" warning.
2752 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2753 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2755 DiagID = diag::warn_no_newline_eof;
2758 DiagID = diag::ext_no_newline_eof;
2761 Diag(BufferEnd, DiagID)
2762 << FixItHint::CreateInsertion(EndLoc, "\n");
2767 // Finally, let the preprocessor handle this.
2768 return PP->HandleEndOfFile(Result, isPragmaLexer());
2771 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2772 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2773 /// else and 2 if there are no more tokens in the buffer controlled by the
2775 unsigned Lexer::isNextPPTokenLParen() {
2776 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2778 // Switch to 'skipping' mode. This will ensure that we can lex a token
2779 // without emitting diagnostics, disables macro expansion, and will cause EOF
2780 // to return an EOF token instead of popping the include stack.
2781 LexingRawMode = true;
2783 // Save state that can be changed while lexing so that we can restore it.
2784 const char *TmpBufferPtr = BufferPtr;
2785 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2786 bool atStartOfLine = IsAtStartOfLine;
2787 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2788 bool leadingSpace = HasLeadingSpace;
2793 // Restore state that may have changed.
2794 BufferPtr = TmpBufferPtr;
2795 ParsingPreprocessorDirective = inPPDirectiveMode;
2796 HasLeadingSpace = leadingSpace;
2797 IsAtStartOfLine = atStartOfLine;
2798 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2800 // Restore the lexer back to non-skipping mode.
2801 LexingRawMode = false;
2803 if (Tok.is(tok::eof))
2805 return Tok.is(tok::l_paren);
2808 /// Find the end of a version control conflict marker.
2809 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2810 ConflictMarkerKind CMK) {
2811 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2812 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2813 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2814 size_t Pos = RestOfBuffer.find(Terminator);
2815 while (Pos != StringRef::npos) {
2816 // Must occur at start of line.
2818 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2819 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2820 Pos = RestOfBuffer.find(Terminator);
2823 return RestOfBuffer.data()+Pos;
2828 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2829 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2830 /// and recover nicely. This returns true if it is a conflict marker and false
2832 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2833 // Only a conflict marker if it starts at the beginning of a line.
2834 if (CurPtr != BufferStart &&
2835 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2838 // Check to see if we have <<<<<<< or >>>>.
2839 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2840 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2843 // If we have a situation where we don't care about conflict markers, ignore
2845 if (CurrentConflictMarkerState || isLexingRawMode())
2848 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2850 // Check to see if there is an ending marker somewhere in the buffer at the
2851 // start of a line to terminate this conflict marker.
2852 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2853 // We found a match. We are really in a conflict marker.
2854 // Diagnose this, and ignore to the end of line.
2855 Diag(CurPtr, diag::err_conflict_marker);
2856 CurrentConflictMarkerState = Kind;
2858 // Skip ahead to the end of line. We know this exists because the
2859 // end-of-conflict marker starts with \r or \n.
2860 while (*CurPtr != '\r' && *CurPtr != '\n') {
2861 assert(CurPtr != BufferEnd && "Didn't find end of line");
2868 // No end of conflict marker found.
2872 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2873 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2874 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2875 /// the line. This returns true if it is a conflict marker and false if not.
2876 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2877 // Only a conflict marker if it starts at the beginning of a line.
2878 if (CurPtr != BufferStart &&
2879 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2882 // If we have a situation where we don't care about conflict markers, ignore
2884 if (!CurrentConflictMarkerState || isLexingRawMode())
2887 // Check to see if we have the marker (4 characters in a row).
2888 for (unsigned i = 1; i != 4; ++i)
2889 if (CurPtr[i] != CurPtr[0])
2892 // If we do have it, search for the end of the conflict marker. This could
2893 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2894 // be the end of conflict marker.
2895 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2896 CurrentConflictMarkerState)) {
2899 // Skip ahead to the end of line.
2900 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2905 // No longer in the conflict marker.
2906 CurrentConflictMarkerState = CMK_None;
2913 static const char *findPlaceholderEnd(const char *CurPtr,
2914 const char *BufferEnd) {
2915 if (CurPtr == BufferEnd)
2917 BufferEnd -= 1; // Scan until the second last character.
2918 for (; CurPtr != BufferEnd; ++CurPtr) {
2919 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2925 bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2926 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2927 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
2929 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2932 const char *Start = CurPtr - 1;
2933 if (!LangOpts.AllowEditorPlaceholders)
2934 Diag(Start, diag::err_placeholder_in_source);
2935 Result.startToken();
2936 FormTokenWithChars(Result, End, tok::raw_identifier);
2937 Result.setRawIdentifierData(Start);
2938 PP->LookUpIdentifierInfo(Result);
2939 Result.setFlag(Token::IsEditorPlaceholder);
2944 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2945 if (PP && PP->isCodeCompletionEnabled()) {
2946 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2947 return Loc == PP->getCodeCompletionLoc();
2953 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2956 char Kind = getCharAndSize(StartPtr, CharSize);
2958 unsigned NumHexDigits;
2961 else if (Kind == 'U')
2966 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2967 if (Result && !isLexingRawMode())
2968 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2972 const char *CurPtr = StartPtr + CharSize;
2973 const char *KindLoc = &CurPtr[-1];
2975 uint32_t CodePoint = 0;
2976 for (unsigned i = 0; i < NumHexDigits; ++i) {
2977 char C = getCharAndSize(CurPtr, CharSize);
2979 unsigned Value = llvm::hexDigitValue(C);
2981 if (Result && !isLexingRawMode()) {
2983 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2984 << StringRef(KindLoc, 1);
2986 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2988 // If the user wrote \U1234, suggest a fixit to \u.
2989 if (i == 4 && NumHexDigits == 8) {
2990 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2991 Diag(KindLoc, diag::note_ucn_four_not_eight)
2992 << FixItHint::CreateReplacement(URange, "u");
3007 Result->setFlag(Token::HasUCN);
3008 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
3011 while (StartPtr != CurPtr)
3012 (void)getAndAdvanceChar(StartPtr, *Result);
3017 // Don't apply C family restrictions to UCNs in assembly mode
3018 if (LangOpts.AsmPreprocessor)
3021 // C99 6.4.3p2: A universal character name shall not specify a character whose
3022 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
3023 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
3024 // C++11 [lex.charset]p2: If the hexadecimal value for a
3025 // universal-character-name corresponds to a surrogate code point (in the
3026 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
3027 // if the hexadecimal value for a universal-character-name outside the
3028 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
3029 // string literal corresponds to a control character (in either of the
3030 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
3031 // basic source character set, the program is ill-formed.
3032 if (CodePoint < 0xA0) {
3033 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
3036 // We don't use isLexingRawMode() here because we need to warn about bad
3037 // UCNs even when skipping preprocessing tokens in a #if block.
3039 if (CodePoint < 0x20 || CodePoint >= 0x7F)
3040 Diag(BufferPtr, diag::err_ucn_control_character);
3042 char C = static_cast<char>(CodePoint);
3043 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
3048 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
3049 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
3050 // We don't use isLexingRawMode() here because we need to diagnose bad
3051 // UCNs even when skipping preprocessing tokens in a #if block.
3053 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
3054 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
3056 Diag(BufferPtr, diag::err_ucn_escape_invalid);
3064 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
3065 const char *CurPtr) {
3066 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
3067 UnicodeWhitespaceCharRanges);
3068 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
3069 UnicodeWhitespaceChars.contains(C)) {
3070 Diag(BufferPtr, diag::ext_unicode_whitespace)
3071 << makeCharRange(*this, BufferPtr, CurPtr);
3073 Result.setFlag(Token::LeadingSpace);
3079 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
3080 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
3081 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3082 !PP->isPreprocessedOutput()) {
3083 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
3084 makeCharRange(*this, BufferPtr, CurPtr),
3086 maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), C,
3087 makeCharRange(*this, BufferPtr, CurPtr));
3091 return LexIdentifier(Result, CurPtr);
3094 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
3095 !PP->isPreprocessedOutput() &&
3096 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
3097 // Non-ASCII characters tend to creep into source code unintentionally.
3098 // Instead of letting the parser complain about the unknown token,
3099 // just drop the character.
3100 // Note that we can /only/ do this when the non-ASCII character is actually
3101 // spelled as Unicode, not written as a UCN. The standard requires that
3102 // we not throw away any possible preprocessor tokens, but there's a
3103 // loophole in the mapping of Unicode characters to basic character set
3104 // characters that allows us to map these particular characters to, say,
3106 Diag(BufferPtr, diag::err_non_ascii)
3107 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
3113 // Otherwise, we have an explicit UCN or a character that's unlikely to show
3116 FormTokenWithChars(Result, CurPtr, tok::unknown);
3120 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
3121 IsAtStartOfLine = Result.isAtStartOfLine();
3122 HasLeadingSpace = Result.hasLeadingSpace();
3123 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
3124 // Note that this doesn't affect IsAtPhysicalStartOfLine.
3127 bool Lexer::Lex(Token &Result) {
3128 // Start a new token.
3129 Result.startToken();
3131 // Set up misc whitespace flags for LexTokenInternal.
3132 if (IsAtStartOfLine) {
3133 Result.setFlag(Token::StartOfLine);
3134 IsAtStartOfLine = false;
3137 if (HasLeadingSpace) {
3138 Result.setFlag(Token::LeadingSpace);
3139 HasLeadingSpace = false;
3142 if (HasLeadingEmptyMacro) {
3143 Result.setFlag(Token::LeadingEmptyMacro);
3144 HasLeadingEmptyMacro = false;
3147 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
3148 IsAtPhysicalStartOfLine = false;
3149 bool isRawLex = isLexingRawMode();
3151 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
3152 // (After the LexTokenInternal call, the lexer might be destroyed.)
3153 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
3154 return returnedToken;
3157 /// LexTokenInternal - This implements a simple C family lexer. It is an
3158 /// extremely performance critical piece of code. This assumes that the buffer
3159 /// has a null character at the end of the file. This returns a preprocessing
3160 /// token, not a normal token, as such, it is an internal interface. It assumes
3161 /// that the Flags of result have been cleared before calling this.
3162 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3164 // New token, can't need cleaning yet.
3165 Result.clearFlag(Token::NeedsCleaning);
3166 Result.setIdentifierInfo(nullptr);
3168 // CurPtr - Cache BufferPtr in an automatic variable.
3169 const char *CurPtr = BufferPtr;
3171 // Small amounts of horizontal whitespace is very common between tokens.
3172 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3174 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3177 // If we are keeping whitespace and other tokens, just return what we just
3178 // skipped. The next lexer invocation will return the token after the
3180 if (isKeepWhitespaceMode()) {
3181 FormTokenWithChars(Result, CurPtr, tok::unknown);
3182 // FIXME: The next token will not have LeadingSpace set.
3187 Result.setFlag(Token::LeadingSpace);
3190 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
3192 // Read a character, advancing over it.
3193 char Char = getAndAdvanceChar(CurPtr, Result);
3194 tok::TokenKind Kind;
3198 // Found end of file?
3199 if (CurPtr-1 == BufferEnd)
3200 return LexEndOfFile(Result, CurPtr-1);
3202 // Check if we are performing code completion.
3203 if (isCodeCompletionPoint(CurPtr-1)) {
3204 // Return the code-completion token.
3205 Result.startToken();
3206 FormTokenWithChars(Result, CurPtr, tok::code_completion);
3210 if (!isLexingRawMode())
3211 Diag(CurPtr-1, diag::null_in_file);
3212 Result.setFlag(Token::LeadingSpace);
3213 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3214 return true; // KeepWhitespaceMode
3216 // We know the lexer hasn't changed, so just try again with this lexer.
3217 // (We manually eliminate the tail call to avoid recursion.)
3220 case 26: // DOS & CP/M EOF: "^Z".
3221 // If we're in Microsoft extensions mode, treat this as end of file.
3222 if (LangOpts.MicrosoftExt) {
3223 if (!isLexingRawMode())
3224 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3225 return LexEndOfFile(Result, CurPtr-1);
3228 // If Microsoft extensions are disabled, this is just random garbage.
3229 Kind = tok::unknown;
3233 if (CurPtr[0] == '\n')
3234 (void)getAndAdvanceChar(CurPtr, Result);
3237 // If we are inside a preprocessor directive and we see the end of line,
3238 // we know we are done with the directive, so return an EOD token.
3239 if (ParsingPreprocessorDirective) {
3240 // Done parsing the "line".
3241 ParsingPreprocessorDirective = false;
3243 // Restore comment saving mode, in case it was disabled for directive.
3245 resetExtendedTokenMode();
3247 // Since we consumed a newline, we are back at the start of a line.
3248 IsAtStartOfLine = true;
3249 IsAtPhysicalStartOfLine = true;
3255 // No leading whitespace seen so far.
3256 Result.clearFlag(Token::LeadingSpace);
3258 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3259 return true; // KeepWhitespaceMode
3261 // We only saw whitespace, so just try again with this lexer.
3262 // (We manually eliminate the tail call to avoid recursion.)
3268 SkipHorizontalWhitespace:
3269 Result.setFlag(Token::LeadingSpace);
3270 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3271 return true; // KeepWhitespaceMode
3276 // If the next token is obviously a // or /* */ comment, skip it efficiently
3277 // too (without going through the big switch stmt).
3278 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3279 LangOpts.LineComment &&
3280 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3281 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3282 return true; // There is a token to return.
3283 goto SkipIgnoredUnits;
3284 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3285 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3286 return true; // There is a token to return.
3287 goto SkipIgnoredUnits;
3288 } else if (isHorizontalWhitespace(*CurPtr)) {
3289 goto SkipHorizontalWhitespace;
3291 // We only saw whitespace, so just try again with this lexer.
3292 // (We manually eliminate the tail call to avoid recursion.)
3295 // C99 6.4.4.1: Integer Constants.
3296 // C99 6.4.4.2: Floating Constants.
3297 case '0': case '1': case '2': case '3': case '4':
3298 case '5': case '6': case '7': case '8': case '9':
3299 // Notify MIOpt that we read a non-whitespace/non-comment token.
3301 return LexNumericConstant(Result, CurPtr);
3303 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3304 // Notify MIOpt that we read a non-whitespace/non-comment token.
3307 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3308 Char = getCharAndSize(CurPtr, SizeTmp);
3310 // UTF-16 string literal
3312 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3313 tok::utf16_string_literal);
3315 // UTF-16 character constant
3317 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3318 tok::utf16_char_constant);
3320 // UTF-16 raw string literal
3321 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3322 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3323 return LexRawStringLiteral(Result,
3324 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3326 tok::utf16_string_literal);
3329 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3331 // UTF-8 string literal
3333 return LexStringLiteral(Result,
3334 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3336 tok::utf8_string_literal);
3337 if (Char2 == '\'' && LangOpts.CPlusPlus17)
3338 return LexCharConstant(
3339 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3341 tok::utf8_char_constant);
3343 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3345 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3346 // UTF-8 raw string literal
3348 return LexRawStringLiteral(Result,
3349 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3352 tok::utf8_string_literal);
3358 // treat u like the start of an identifier.
3359 return LexIdentifier(Result, CurPtr);
3361 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3362 // Notify MIOpt that we read a non-whitespace/non-comment token.
3365 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3366 Char = getCharAndSize(CurPtr, SizeTmp);
3368 // UTF-32 string literal
3370 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3371 tok::utf32_string_literal);
3373 // UTF-32 character constant
3375 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3376 tok::utf32_char_constant);
3378 // UTF-32 raw string literal
3379 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3380 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3381 return LexRawStringLiteral(Result,
3382 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3384 tok::utf32_string_literal);
3387 // treat U like the start of an identifier.
3388 return LexIdentifier(Result, CurPtr);
3390 case 'R': // Identifier or C++0x raw string literal
3391 // Notify MIOpt that we read a non-whitespace/non-comment token.
3394 if (LangOpts.CPlusPlus11) {
3395 Char = getCharAndSize(CurPtr, SizeTmp);
3398 return LexRawStringLiteral(Result,
3399 ConsumeChar(CurPtr, SizeTmp, Result),
3400 tok::string_literal);
3403 // treat R like the start of an identifier.
3404 return LexIdentifier(Result, CurPtr);
3406 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3407 // Notify MIOpt that we read a non-whitespace/non-comment token.
3409 Char = getCharAndSize(CurPtr, SizeTmp);
3411 // Wide string literal.
3413 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3414 tok::wide_string_literal);
3416 // Wide raw string literal.
3417 if (LangOpts.CPlusPlus11 && Char == 'R' &&
3418 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3419 return LexRawStringLiteral(Result,
3420 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3422 tok::wide_string_literal);
3424 // Wide character constant.
3426 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3427 tok::wide_char_constant);
3428 // FALL THROUGH, treating L like the start of an identifier.
3431 // C99 6.4.2: Identifiers.
3432 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3433 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3434 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3435 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3436 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3437 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3438 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3439 case 'v': case 'w': case 'x': case 'y': case 'z':
3441 // Notify MIOpt that we read a non-whitespace/non-comment token.
3443 return LexIdentifier(Result, CurPtr);
3445 case '$': // $ in identifiers.
3446 if (LangOpts.DollarIdents) {
3447 if (!isLexingRawMode())
3448 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3449 // Notify MIOpt that we read a non-whitespace/non-comment token.
3451 return LexIdentifier(Result, CurPtr);
3454 Kind = tok::unknown;
3457 // C99 6.4.4: Character Constants.
3459 // Notify MIOpt that we read a non-whitespace/non-comment token.
3461 return LexCharConstant(Result, CurPtr, tok::char_constant);
3463 // C99 6.4.5: String Literals.
3465 // Notify MIOpt that we read a non-whitespace/non-comment token.
3467 return LexStringLiteral(Result, CurPtr,
3468 ParsingFilename ? tok::header_name
3469 : tok::string_literal);
3471 // C99 6.4.6: Punctuators.
3473 Kind = tok::question;
3476 Kind = tok::l_square;
3479 Kind = tok::r_square;
3482 Kind = tok::l_paren;
3485 Kind = tok::r_paren;
3488 Kind = tok::l_brace;
3491 Kind = tok::r_brace;
3494 Char = getCharAndSize(CurPtr, SizeTmp);
3495 if (Char >= '0' && Char <= '9') {
3496 // Notify MIOpt that we read a non-whitespace/non-comment token.
3499 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3500 } else if (LangOpts.CPlusPlus && Char == '*') {
3501 Kind = tok::periodstar;
3503 } else if (Char == '.' &&
3504 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3505 Kind = tok::ellipsis;
3506 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3513 Char = getCharAndSize(CurPtr, SizeTmp);
3516 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3517 } else if (Char == '=') {
3518 Kind = tok::ampequal;
3519 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3525 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3526 Kind = tok::starequal;
3527 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3533 Char = getCharAndSize(CurPtr, SizeTmp);
3535 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3536 Kind = tok::plusplus;
3537 } else if (Char == '=') {
3538 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3539 Kind = tok::plusequal;
3545 Char = getCharAndSize(CurPtr, SizeTmp);
3546 if (Char == '-') { // --
3547 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3548 Kind = tok::minusminus;
3549 } else if (Char == '>' && LangOpts.CPlusPlus &&
3550 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3551 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3553 Kind = tok::arrowstar;
3554 } else if (Char == '>') { // ->
3555 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3557 } else if (Char == '=') { // -=
3558 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3559 Kind = tok::minusequal;
3568 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3569 Kind = tok::exclaimequal;
3570 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3572 Kind = tok::exclaim;
3577 Char = getCharAndSize(CurPtr, SizeTmp);
3578 if (Char == '/') { // Line comment.
3579 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3580 // want to lex this as a comment. There is one problem with this though,
3581 // that in one particular corner case, this can change the behavior of the
3582 // resultant program. For example, In "foo //**/ bar", C89 would lex
3583 // this as "foo / bar" and languages with Line comments would lex it as
3584 // "foo". Check to see if the character after the second slash is a '*'.
3585 // If so, we will lex that as a "/" instead of the start of a comment.
3586 // However, we never do this if we are just preprocessing.
3587 bool TreatAsComment = LangOpts.LineComment &&
3588 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3589 if (!TreatAsComment)
3590 if (!(PP && PP->isPreprocessedOutput()))
3591 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3593 if (TreatAsComment) {
3594 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3595 TokAtPhysicalStartOfLine))
3596 return true; // There is a token to return.
3598 // It is common for the tokens immediately after a // comment to be
3599 // whitespace (indentation for the next line). Instead of going through
3600 // the big switch, handle it efficiently now.
3601 goto SkipIgnoredUnits;
3605 if (Char == '*') { // /**/ comment.
3606 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3607 TokAtPhysicalStartOfLine))
3608 return true; // There is a token to return.
3610 // We only saw whitespace, so just try again with this lexer.
3611 // (We manually eliminate the tail call to avoid recursion.)
3616 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3617 Kind = tok::slashequal;
3623 Char = getCharAndSize(CurPtr, SizeTmp);
3625 Kind = tok::percentequal;
3626 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3627 } else if (LangOpts.Digraphs && Char == '>') {
3628 Kind = tok::r_brace; // '%>' -> '}'
3629 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3630 } else if (LangOpts.Digraphs && Char == ':') {
3631 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3632 Char = getCharAndSize(CurPtr, SizeTmp);
3633 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3634 Kind = tok::hashhash; // '%:%:' -> '##'
3635 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3637 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3638 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3639 if (!isLexingRawMode())
3640 Diag(BufferPtr, diag::ext_charize_microsoft);
3642 } else { // '%:' -> '#'
3643 // We parsed a # character. If this occurs at the start of the line,
3644 // it's actually the start of a preprocessing directive. Callback to
3645 // the preprocessor to handle it.
3646 // TODO: -fpreprocessed mode??
3647 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3648 goto HandleDirective;
3653 Kind = tok::percent;
3657 Char = getCharAndSize(CurPtr, SizeTmp);
3658 if (ParsingFilename) {
3659 return LexAngledStringLiteral(Result, CurPtr);
3660 } else if (Char == '<') {
3661 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3663 Kind = tok::lesslessequal;
3664 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3666 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3667 // If this is actually a '<<<<<<<' version control conflict marker,
3668 // recognize it as such and recover nicely.
3670 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3671 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3674 } else if (LangOpts.CUDA && After == '<') {
3675 Kind = tok::lesslessless;
3676 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3679 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3680 Kind = tok::lessless;
3682 } else if (Char == '=') {
3683 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3685 if (getLangOpts().CPlusPlus2a) {
3686 if (!isLexingRawMode())
3687 Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
3688 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3690 Kind = tok::spaceship;
3693 // Suggest adding a space between the '<=' and the '>' to avoid a
3694 // change in semantics if this turns up in C++ <=17 mode.
3695 if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
3696 Diag(BufferPtr, diag::warn_cxx2a_compat_spaceship)
3697 << FixItHint::CreateInsertion(
3698 getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
3701 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3702 Kind = tok::lessequal;
3703 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3704 if (LangOpts.CPlusPlus11 &&
3705 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3706 // C++0x [lex.pptoken]p3:
3707 // Otherwise, if the next three characters are <:: and the subsequent
3708 // character is neither : nor >, the < is treated as a preprocessor
3709 // token by itself and not as the first character of the alternative
3712 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3713 if (After != ':' && After != '>') {
3715 if (!isLexingRawMode())
3716 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3721 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3722 Kind = tok::l_square;
3723 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3724 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3725 Kind = tok::l_brace;
3726 } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
3727 lexEditorPlaceholder(Result, CurPtr)) {
3734 Char = getCharAndSize(CurPtr, SizeTmp);
3736 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3737 Kind = tok::greaterequal;
3738 } else if (Char == '>') {
3739 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3741 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3743 Kind = tok::greatergreaterequal;
3744 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3745 // If this is actually a '>>>>' conflict marker, recognize it as such
3746 // and recover nicely.
3748 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3749 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3751 } else if (LangOpts.CUDA && After == '>') {
3752 Kind = tok::greatergreatergreater;
3753 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3756 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3757 Kind = tok::greatergreater;
3760 Kind = tok::greater;
3764 Char = getCharAndSize(CurPtr, SizeTmp);
3766 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3767 Kind = tok::caretequal;
3768 } else if (LangOpts.OpenCL && Char == '^') {
3769 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3770 Kind = tok::caretcaret;
3776 Char = getCharAndSize(CurPtr, SizeTmp);
3778 Kind = tok::pipeequal;
3779 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3780 } else if (Char == '|') {
3781 // If this is '|||||||' and we're in a conflict marker, ignore it.
3782 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3784 Kind = tok::pipepipe;
3785 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3791 Char = getCharAndSize(CurPtr, SizeTmp);
3792 if (LangOpts.Digraphs && Char == '>') {
3793 Kind = tok::r_square; // ':>' -> ']'
3794 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3795 } else if ((LangOpts.CPlusPlus ||
3796 LangOpts.DoubleSquareBracketAttributes) &&
3798 Kind = tok::coloncolon;
3799 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3808 Char = getCharAndSize(CurPtr, SizeTmp);
3810 // If this is '====' and we're in a conflict marker, ignore it.
3811 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3814 Kind = tok::equalequal;
3815 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3824 Char = getCharAndSize(CurPtr, SizeTmp);
3826 Kind = tok::hashhash;
3827 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3828 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3830 if (!isLexingRawMode())
3831 Diag(BufferPtr, diag::ext_charize_microsoft);
3832 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3834 // We parsed a # character. If this occurs at the start of the line,
3835 // it's actually the start of a preprocessing directive. Callback to
3836 // the preprocessor to handle it.
3837 // TODO: -fpreprocessed mode??
3838 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3839 goto HandleDirective;
3846 // Objective C support.
3847 if (CurPtr[-1] == '@' && LangOpts.ObjC)
3850 Kind = tok::unknown;
3853 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3855 if (!LangOpts.AsmPreprocessor) {
3856 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3857 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3858 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3859 return true; // KeepWhitespaceMode
3861 // We only saw whitespace, so just try again with this lexer.
3862 // (We manually eliminate the tail call to avoid recursion.)
3866 return LexUnicode(Result, CodePoint, CurPtr);
3870 Kind = tok::unknown;
3874 if (isASCII(Char)) {
3875 Kind = tok::unknown;
3879 llvm::UTF32 CodePoint;
3881 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3882 // an escaped newline.
3884 llvm::ConversionResult Status =
3885 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3886 (const llvm::UTF8 *)BufferEnd,
3888 llvm::strictConversion);
3889 if (Status == llvm::conversionOK) {
3890 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3891 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3892 return true; // KeepWhitespaceMode
3894 // We only saw whitespace, so just try again with this lexer.
3895 // (We manually eliminate the tail call to avoid recursion.)
3898 return LexUnicode(Result, CodePoint, CurPtr);
3901 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3902 PP->isPreprocessedOutput()) {
3904 Kind = tok::unknown;
3908 // Non-ASCII characters tend to creep into source code unintentionally.
3909 // Instead of letting the parser complain about the unknown token,
3910 // just diagnose the invalid UTF-8, then drop the character.
3911 Diag(CurPtr, diag::err_invalid_utf8);
3913 BufferPtr = CurPtr+1;
3914 // We're pretending the character didn't exist, so just try again with
3916 // (We manually eliminate the tail call to avoid recursion.)
3921 // Notify MIOpt that we read a non-whitespace/non-comment token.
3924 // Update the location of token as well as BufferPtr.
3925 FormTokenWithChars(Result, CurPtr, Kind);
3929 // We parsed a # character and it's the start of a preprocessing directive.
3931 FormTokenWithChars(Result, CurPtr, tok::hash);
3932 PP->HandleDirective(Result);
3934 if (PP->hadModuleLoaderFatalFailure()) {
3935 // With a fatal failure in the module loader, we abort parsing.
3936 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3940 // We parsed the directive; lex a token with the new state.