1 //===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Lexer and Token interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/Lexer.h"
15 #include "UnicodeCharSets.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/ConvertUTF.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/UnicodeCharRanges.h"
38 using namespace clang;
40 //===----------------------------------------------------------------------===//
41 // Token Class Implementation
42 //===----------------------------------------------------------------------===//
44 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
45 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
46 if (IdentifierInfo *II = getIdentifierInfo())
47 return II->getObjCKeywordID() == objcKey;
51 /// getObjCKeywordID - Return the ObjC keyword kind.
52 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
53 IdentifierInfo *specId = getIdentifierInfo();
54 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
57 //===----------------------------------------------------------------------===//
58 // Lexer Class Implementation
59 //===----------------------------------------------------------------------===//
61 void Lexer::anchor() { }
63 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
65 BufferStart = BufStart;
69 assert(BufEnd[0] == 0 &&
70 "We assume that the input buffer has a null character at the end"
71 " to simplify lexing!");
73 // Check whether we have a BOM in the beginning of the buffer. If yes - act
74 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
75 // skip the UTF-8 BOM if it's present.
76 if (BufferStart == BufferPtr) {
77 // Determine the size of the BOM.
78 StringRef Buf(BufferStart, BufferEnd - BufferStart);
79 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
80 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
84 BufferPtr += BOMLength;
87 Is_PragmaLexer = false;
88 CurrentConflictMarkerState = CMK_None;
90 // Start of the file is a start of line.
91 IsAtStartOfLine = true;
92 IsAtPhysicalStartOfLine = true;
94 HasLeadingSpace = false;
95 HasLeadingEmptyMacro = false;
97 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
100 // We are not after parsing #include.
101 ParsingFilename = false;
103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
113 /// Lexer constructor - Create a new lexer object for the specified buffer
114 /// with the specified preprocessor managing the lexing process. This lexer
115 /// assumes that the associated file buffer and Preprocessor objects will
116 /// outlive it, so it doesn't take ownership of either of them.
117 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
120 LangOpts(PP.getLangOpts()) {
122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
125 resetExtendedTokenMode();
128 void Lexer::resetExtendedTokenMode() {
129 assert(PP && "Cannot reset token mode without a preprocessor");
130 if (LangOpts.TraditionalCPP)
131 SetKeepWhitespaceMode(true);
133 SetCommentRetentionState(PP->getCommentRetentionState());
136 /// Lexer constructor - Create a new raw lexer object. This object is only
137 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
138 /// range will outlive it, so it doesn't take ownership of it.
139 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
140 const char *BufStart, const char *BufPtr, const char *BufEnd)
141 : FileLoc(fileloc), LangOpts(langOpts) {
143 InitLexer(BufStart, BufPtr, BufEnd);
145 // We *are* in raw mode.
146 LexingRawMode = true;
149 /// Lexer constructor - Create a new raw lexer object. This object is only
150 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
151 /// range will outlive it, so it doesn't take ownership of it.
152 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
153 const SourceManager &SM, const LangOptions &langOpts)
154 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
155 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
157 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
158 /// _Pragma expansion. This has a variety of magic semantics that this method
159 /// sets up. It returns a new'd Lexer that must be delete'd when done.
161 /// On entrance to this routine, TokStartLoc is a macro location which has a
162 /// spelling loc that indicates the bytes to be lexed for the token and an
163 /// expansion location that indicates where all lexed tokens should be
166 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
167 /// normal lexer that remaps tokens as they fly by. This would require making
168 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
169 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
170 /// out of the critical path of the lexer!
172 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
173 SourceLocation ExpansionLocStart,
174 SourceLocation ExpansionLocEnd,
175 unsigned TokLen, Preprocessor &PP) {
176 SourceManager &SM = PP.getSourceManager();
178 // Create the lexer as if we were going to lex the file normally.
179 FileID SpellingFID = SM.getFileID(SpellingLoc);
180 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
181 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
183 // Now that the lexer is created, change the start/end locations so that we
184 // just lex the subsection of the file that we want. This is lexing from a
186 const char *StrData = SM.getCharacterData(SpellingLoc);
188 L->BufferPtr = StrData;
189 L->BufferEnd = StrData+TokLen;
190 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
192 // Set the SourceLocation with the remapping information. This ensures that
193 // GetMappedTokenLoc will remap the tokens as they are lexed.
194 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
196 ExpansionLocEnd, TokLen);
198 // Ensure that the lexer thinks it is inside a directive, so that end \n will
199 // return an EOD token.
200 L->ParsingPreprocessorDirective = true;
202 // This lexer really is for _Pragma.
203 L->Is_PragmaLexer = true;
207 /// Stringify - Convert the specified string into a C string, with surrounding
208 /// ""'s, and with escaped \ and " characters.
209 std::string Lexer::Stringify(StringRef Str, bool Charify) {
210 std::string Result = Str;
211 char Quote = Charify ? '\'' : '"';
212 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
213 if (Result[i] == '\\' || Result[i] == Quote) {
214 Result.insert(Result.begin()+i, '\\');
221 /// Stringify - Convert the specified string into a C string by escaping '\'
222 /// and " characters. This does not add surrounding ""'s to the string.
223 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
224 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225 if (Str[i] == '\\' || Str[i] == '"') {
226 Str.insert(Str.begin()+i, '\\');
232 //===----------------------------------------------------------------------===//
234 //===----------------------------------------------------------------------===//
236 /// \brief Slow case of getSpelling. Extract the characters comprising the
237 /// spelling of this token from the provided input buffer.
238 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
239 const LangOptions &LangOpts, char *Spelling) {
240 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
243 const char *BufEnd = BufPtr + Tok.getLength();
245 if (tok::isStringLiteral(Tok.getKind())) {
246 // Munch the encoding-prefix and opening double-quote.
247 while (BufPtr < BufEnd) {
249 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
252 if (Spelling[Length - 1] == '"')
256 // Raw string literals need special handling; trigraph expansion and line
257 // splicing do not occur within their d-char-sequence nor within their
260 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
261 // Search backwards from the end of the token to find the matching closing
263 const char *RawEnd = BufEnd;
264 do --RawEnd; while (*RawEnd != '"');
265 size_t RawLength = RawEnd - BufPtr + 1;
267 // Everything between the quotes is included verbatim in the spelling.
268 memcpy(Spelling + Length, BufPtr, RawLength);
272 // The rest of the token is lexed normally.
276 while (BufPtr < BufEnd) {
278 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
282 assert(Length < Tok.getLength() &&
283 "NeedsCleaning flag set on token that didn't need cleaning!");
287 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
288 /// token are the characters used to represent the token in the source file
289 /// after trigraph expansion and escaped-newline folding. In particular, this
290 /// wants to get the true, uncanonicalized, spelling of things like digraphs
292 StringRef Lexer::getSpelling(SourceLocation loc,
293 SmallVectorImpl<char> &buffer,
294 const SourceManager &SM,
295 const LangOptions &options,
297 // Break down the source location.
298 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
300 // Try to the load the file buffer.
301 bool invalidTemp = false;
302 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
304 if (invalid) *invalid = true;
308 const char *tokenBegin = file.data() + locInfo.second;
310 // Lex from the start of the given location.
311 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
312 file.begin(), tokenBegin, file.end());
314 lexer.LexFromRawLexer(token);
316 unsigned length = token.getLength();
318 // Common case: no need for cleaning.
319 if (!token.needsCleaning())
320 return StringRef(tokenBegin, length);
322 // Hard case, we need to relex the characters into the string.
323 buffer.resize(length);
324 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
325 return StringRef(buffer.data(), buffer.size());
328 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
329 /// token are the characters used to represent the token in the source file
330 /// after trigraph expansion and escaped-newline folding. In particular, this
331 /// wants to get the true, uncanonicalized, spelling of things like digraphs
333 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
334 const LangOptions &LangOpts, bool *Invalid) {
335 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
337 bool CharDataInvalid = false;
338 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
341 *Invalid = CharDataInvalid;
343 return std::string();
345 // If this token contains nothing interesting, return it directly.
346 if (!Tok.needsCleaning())
347 return std::string(TokStart, TokStart + Tok.getLength());
350 Result.resize(Tok.getLength());
351 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
355 /// getSpelling - This method is used to get the spelling of a token into a
356 /// preallocated buffer, instead of as an std::string. The caller is required
357 /// to allocate enough space for the token, which is guaranteed to be at least
358 /// Tok.getLength() bytes long. The actual length of the token is returned.
360 /// Note that this method may do two possible things: it may either fill in
361 /// the buffer specified with characters, or it may *change the input pointer*
362 /// to point to a constant buffer with the data already in it (avoiding a
363 /// copy). The caller is not allowed to modify the returned buffer pointer
364 /// if an internal buffer is returned.
365 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
366 const SourceManager &SourceMgr,
367 const LangOptions &LangOpts, bool *Invalid) {
368 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
370 const char *TokStart = nullptr;
371 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
372 if (Tok.is(tok::raw_identifier))
373 TokStart = Tok.getRawIdentifier().data();
374 else if (!Tok.hasUCN()) {
375 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
376 // Just return the string from the identifier table, which is very quick.
377 Buffer = II->getNameStart();
378 return II->getLength();
382 // NOTE: this can be checked even after testing for an IdentifierInfo.
384 TokStart = Tok.getLiteralData();
387 // Compute the start of the token in the input lexer buffer.
388 bool CharDataInvalid = false;
389 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
391 *Invalid = CharDataInvalid;
392 if (CharDataInvalid) {
398 // If this token contains nothing interesting, return it directly.
399 if (!Tok.needsCleaning()) {
401 return Tok.getLength();
404 // Otherwise, hard case, relex the characters into the string.
405 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
408 /// MeasureTokenLength - Relex the token at the specified location and return
409 /// its length in bytes in the input file. If the token needs cleaning (e.g.
410 /// includes a trigraph or an escaped newline) then this count includes bytes
411 /// that are part of that.
412 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
413 const SourceManager &SM,
414 const LangOptions &LangOpts) {
416 if (getRawToken(Loc, TheTok, SM, LangOpts))
418 return TheTok.getLength();
421 /// \brief Relex the token at the specified location.
422 /// \returns true if there was a failure, false on success.
423 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
424 const SourceManager &SM,
425 const LangOptions &LangOpts,
426 bool IgnoreWhiteSpace) {
427 // TODO: this could be special cased for common tokens like identifiers, ')',
428 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
429 // all obviously single-char tokens. This could use
430 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
433 // If this comes from a macro expansion, we really do want the macro name, not
434 // the token this macro expanded to.
435 Loc = SM.getExpansionLoc(Loc);
436 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
437 bool Invalid = false;
438 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
442 const char *StrData = Buffer.data()+LocInfo.second;
444 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
447 // Create a lexer starting at the beginning of this token.
448 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
449 Buffer.begin(), StrData, Buffer.end());
450 TheLexer.SetCommentRetentionState(true);
451 TheLexer.LexFromRawLexer(Result);
455 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
456 const SourceManager &SM,
457 const LangOptions &LangOpts) {
458 assert(Loc.isFileID());
459 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
460 if (LocInfo.first.isInvalid())
463 bool Invalid = false;
464 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
468 // Back up from the current location until we hit the beginning of a line
469 // (or the buffer). We'll relex from that point.
470 const char *BufStart = Buffer.data();
471 if (LocInfo.second >= Buffer.size())
474 const char *StrData = BufStart+LocInfo.second;
475 if (StrData[0] == '\n' || StrData[0] == '\r')
478 const char *LexStart = StrData;
479 while (LexStart != BufStart) {
480 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
488 // Create a lexer starting at the beginning of this token.
489 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
490 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
491 TheLexer.SetCommentRetentionState(true);
493 // Lex tokens until we find the token that contains the source location.
496 TheLexer.LexFromRawLexer(TheTok);
498 if (TheLexer.getBufferLocation() > StrData) {
499 // Lexing this token has taken the lexer past the source location we're
500 // looking for. If the current token encompasses our source location,
501 // return the beginning of that token.
502 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
503 return TheTok.getLocation();
505 // We ended up skipping over the source location entirely, which means
506 // that it points into whitespace. We're done here.
509 } while (TheTok.getKind() != tok::eof);
511 // We've passed our source location; just return the original source location.
515 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
516 const SourceManager &SM,
517 const LangOptions &LangOpts) {
519 return getBeginningOfFileToken(Loc, SM, LangOpts);
521 if (!SM.isMacroArgExpansion(Loc))
524 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
525 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
526 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
527 std::pair<FileID, unsigned> BeginFileLocInfo
528 = SM.getDecomposedLoc(BeginFileLoc);
529 assert(FileLocInfo.first == BeginFileLocInfo.first &&
530 FileLocInfo.second >= BeginFileLocInfo.second);
531 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
536 enum PreambleDirectiveKind {
543 } // end anonymous namespace
545 std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
546 const LangOptions &LangOpts,
548 // Create a lexer starting at the beginning of the file. Note that we use a
549 // "fake" file source location at offset 1 so that the lexer will track our
550 // position within the file.
551 const unsigned StartOffset = 1;
552 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
553 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
555 TheLexer.SetCommentRetentionState(true);
557 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
558 SourceLocation StartLoc = TheLexer.getSourceLocation();
560 bool InPreprocessorDirective = false;
563 unsigned IfCount = 0;
564 SourceLocation ActiveCommentLoc;
566 unsigned MaxLineOffset = 0;
568 const char *CurPtr = Buffer.begin();
569 unsigned CurLine = 0;
570 while (CurPtr != Buffer.end()) {
574 if (CurLine == MaxLines)
578 if (CurPtr != Buffer.end())
579 MaxLineOffset = CurPtr - Buffer.begin();
583 TheLexer.LexFromRawLexer(TheTok);
585 if (InPreprocessorDirective) {
586 // If we've hit the end of the file, we're done.
587 if (TheTok.getKind() == tok::eof) {
591 // If we haven't hit the end of the preprocessor directive, skip this
593 if (!TheTok.isAtStartOfLine())
596 // We've passed the end of the preprocessor directive, and will look
597 // at this token again below.
598 InPreprocessorDirective = false;
601 // Keep track of the # of lines in the preamble.
602 if (TheTok.isAtStartOfLine()) {
603 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
605 // If we were asked to limit the number of lines in the preamble,
606 // and we're about to exceed that limit, we're done.
607 if (MaxLineOffset && TokOffset >= MaxLineOffset)
611 // Comments are okay; skip over them.
612 if (TheTok.getKind() == tok::comment) {
613 if (ActiveCommentLoc.isInvalid())
614 ActiveCommentLoc = TheTok.getLocation();
618 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
619 // This is the start of a preprocessor directive.
620 Token HashTok = TheTok;
621 InPreprocessorDirective = true;
622 ActiveCommentLoc = SourceLocation();
624 // Figure out which directive this is. Since we're lexing raw tokens,
625 // we don't have an identifier table available. Instead, just look at
626 // the raw identifier to recognize and categorize preprocessor directives.
627 TheLexer.LexFromRawLexer(TheTok);
628 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
629 StringRef Keyword = TheTok.getRawIdentifier();
630 PreambleDirectiveKind PDK
631 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
632 .Case("include", PDK_Skipped)
633 .Case("__include_macros", PDK_Skipped)
634 .Case("define", PDK_Skipped)
635 .Case("undef", PDK_Skipped)
636 .Case("line", PDK_Skipped)
637 .Case("error", PDK_Skipped)
638 .Case("pragma", PDK_Skipped)
639 .Case("import", PDK_Skipped)
640 .Case("include_next", PDK_Skipped)
641 .Case("warning", PDK_Skipped)
642 .Case("ident", PDK_Skipped)
643 .Case("sccs", PDK_Skipped)
644 .Case("assert", PDK_Skipped)
645 .Case("unassert", PDK_Skipped)
646 .Case("if", PDK_StartIf)
647 .Case("ifdef", PDK_StartIf)
648 .Case("ifndef", PDK_StartIf)
649 .Case("elif", PDK_Skipped)
650 .Case("else", PDK_Skipped)
651 .Case("endif", PDK_EndIf)
652 .Default(PDK_Unknown);
660 IfStartTok = HashTok;
666 // Mismatched #endif. The preamble ends here.
674 // We don't know what this directive is; stop at the '#'.
679 // We only end up here if we didn't recognize the preprocessor
680 // directive or it was one that can't occur in the preamble at this
681 // point. Roll back the current token to the location of the '#'.
682 InPreprocessorDirective = false;
686 // We hit a token that we don't recognize as being in the
687 // "preprocessing only" part of the file, so we're no longer in
694 End = IfStartTok.getLocation();
695 else if (ActiveCommentLoc.isValid())
696 End = ActiveCommentLoc; // don't truncate a decl comment.
698 End = TheTok.getLocation();
700 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
701 IfCount? IfStartTok.isAtStartOfLine()
702 : TheTok.isAtStartOfLine());
705 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
706 /// token, return a new location that specifies a character within the token.
707 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
709 const SourceManager &SM,
710 const LangOptions &LangOpts) {
711 // Figure out how many physical characters away the specified expansion
712 // character is. This needs to take into consideration newlines and
714 bool Invalid = false;
715 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
717 // If they request the first char of the token, we're trivially done.
718 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
721 unsigned PhysOffset = 0;
723 // The usual case is that tokens don't contain anything interesting. Skip
724 // over the uninteresting characters. If a token only consists of simple
725 // chars, this method is extremely fast.
726 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
728 return TokStart.getLocWithOffset(PhysOffset);
734 // If we have a character that may be a trigraph or escaped newline, use a
735 // lexer to parse it correctly.
736 for (; CharNo; --CharNo) {
738 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
743 // Final detail: if we end up on an escaped newline, we want to return the
744 // location of the actual byte of the token. For example foo\<newline>bar
745 // advanced by 3 should return the location of b, not of \\. One compounding
746 // detail of this is that the escape may be made by a trigraph.
747 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
748 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
750 return TokStart.getLocWithOffset(PhysOffset);
753 /// \brief Computes the source location just past the end of the
754 /// token at this source location.
756 /// This routine can be used to produce a source location that
757 /// points just past the end of the token referenced by \p Loc, and
758 /// is generally used when a diagnostic needs to point just after a
759 /// token where it expected something different that it received. If
760 /// the returned source location would not be meaningful (e.g., if
761 /// it points into a macro), this routine returns an invalid
764 /// \param Offset an offset from the end of the token, where the source
765 /// location should refer to. The default offset (0) produces a source
766 /// location pointing just past the end of the token; an offset of 1 produces
767 /// a source location pointing to the last character in the token, etc.
768 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
769 const SourceManager &SM,
770 const LangOptions &LangOpts) {
772 return SourceLocation();
774 if (Loc.isMacroID()) {
775 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
776 return SourceLocation(); // Points inside the macro expansion.
779 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
785 return Loc.getLocWithOffset(Len);
788 /// \brief Returns true if the given MacroID location points at the first
789 /// token of the macro expansion.
790 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
791 const SourceManager &SM,
792 const LangOptions &LangOpts,
793 SourceLocation *MacroBegin) {
794 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
796 SourceLocation expansionLoc;
797 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
800 if (expansionLoc.isFileID()) {
801 // No other macro expansions, this is the first.
803 *MacroBegin = expansionLoc;
807 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
810 /// \brief Returns true if the given MacroID location points at the last
811 /// token of the macro expansion.
812 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
813 const SourceManager &SM,
814 const LangOptions &LangOpts,
815 SourceLocation *MacroEnd) {
816 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
818 SourceLocation spellLoc = SM.getSpellingLoc(loc);
819 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
823 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
824 SourceLocation expansionLoc;
825 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
828 if (expansionLoc.isFileID()) {
829 // No other macro expansions.
831 *MacroEnd = expansionLoc;
835 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
838 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
839 const SourceManager &SM,
840 const LangOptions &LangOpts) {
841 SourceLocation Begin = Range.getBegin();
842 SourceLocation End = Range.getEnd();
843 assert(Begin.isFileID() && End.isFileID());
844 if (Range.isTokenRange()) {
845 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
847 return CharSourceRange();
850 // Break down the source locations.
853 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
855 return CharSourceRange();
858 if (!SM.isInFileID(End, FID, &EndOffs) ||
860 return CharSourceRange();
862 return CharSourceRange::getCharRange(Begin, End);
865 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
866 const SourceManager &SM,
867 const LangOptions &LangOpts) {
868 SourceLocation Begin = Range.getBegin();
869 SourceLocation End = Range.getEnd();
870 if (Begin.isInvalid() || End.isInvalid())
871 return CharSourceRange();
873 if (Begin.isFileID() && End.isFileID())
874 return makeRangeFromFileLocs(Range, SM, LangOpts);
876 if (Begin.isMacroID() && End.isFileID()) {
877 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
878 return CharSourceRange();
879 Range.setBegin(Begin);
880 return makeRangeFromFileLocs(Range, SM, LangOpts);
883 if (Begin.isFileID() && End.isMacroID()) {
884 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
886 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
888 return CharSourceRange();
890 return makeRangeFromFileLocs(Range, SM, LangOpts);
893 assert(Begin.isMacroID() && End.isMacroID());
894 SourceLocation MacroBegin, MacroEnd;
895 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
896 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
898 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
900 Range.setBegin(MacroBegin);
901 Range.setEnd(MacroEnd);
902 return makeRangeFromFileLocs(Range, SM, LangOpts);
905 bool Invalid = false;
906 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
909 return CharSourceRange();
911 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
912 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
915 return CharSourceRange();
917 if (EndEntry.getExpansion().isMacroArgExpansion() &&
918 BeginEntry.getExpansion().getExpansionLocStart() ==
919 EndEntry.getExpansion().getExpansionLocStart()) {
920 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
921 Range.setEnd(SM.getImmediateSpellingLoc(End));
922 return makeFileCharRange(Range, SM, LangOpts);
926 return CharSourceRange();
929 StringRef Lexer::getSourceText(CharSourceRange Range,
930 const SourceManager &SM,
931 const LangOptions &LangOpts,
933 Range = makeFileCharRange(Range, SM, LangOpts);
934 if (Range.isInvalid()) {
935 if (Invalid) *Invalid = true;
939 // Break down the source location.
940 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
941 if (beginInfo.first.isInvalid()) {
942 if (Invalid) *Invalid = true;
947 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
948 beginInfo.second > EndOffs) {
949 if (Invalid) *Invalid = true;
953 // Try to the load the file buffer.
954 bool invalidTemp = false;
955 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
957 if (Invalid) *Invalid = true;
961 if (Invalid) *Invalid = false;
962 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
965 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
966 const SourceManager &SM,
967 const LangOptions &LangOpts) {
968 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
970 // Find the location of the immediate macro expansion.
972 FileID FID = SM.getFileID(Loc);
973 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
974 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
975 Loc = Expansion.getExpansionLocStart();
976 if (!Expansion.isMacroArgExpansion())
979 // For macro arguments we need to check that the argument did not come
980 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
982 // Loc points to the argument id of the macro definition, move to the
984 Loc = SM.getImmediateExpansionRange(Loc).first;
985 SourceLocation SpellLoc = Expansion.getSpellingLoc();
986 if (SpellLoc.isFileID())
987 break; // No inner macro.
989 // If spelling location resides in the same FileID as macro expansion
990 // location, it means there is no inner macro.
991 FileID MacroFID = SM.getFileID(Loc);
992 if (SM.isInFileID(SpellLoc, MacroFID))
995 // Argument came from inner macro.
999 // Find the spelling location of the start of the non-argument expansion
1000 // range. This is where the macro name was spelled in order to begin
1001 // expanding this macro.
1002 Loc = SM.getSpellingLoc(Loc);
1004 // Dig out the buffer where the macro name was spelled and the extents of the
1005 // name so that we can render it into the expansion note.
1006 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1007 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1008 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1009 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1012 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1013 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1014 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1015 // Walk past macro argument expanions.
1016 while (SM.isMacroArgExpansion(Loc))
1017 Loc = SM.getImmediateExpansionRange(Loc).first;
1019 // If the macro's spelling has no FileID, then it's actually a token paste
1020 // or stringization (or similar) and not a macro at all.
1021 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1024 // Find the spelling location of the start of the non-argument expansion
1025 // range. This is where the macro name was spelled in order to begin
1026 // expanding this macro.
1027 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1029 // Dig out the buffer where the macro name was spelled and the extents of the
1030 // name so that we can render it into the expansion note.
1031 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1032 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1033 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1034 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1037 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1038 return isIdentifierBody(c, LangOpts.DollarIdents);
1041 //===----------------------------------------------------------------------===//
1042 // Diagnostics forwarding code.
1043 //===----------------------------------------------------------------------===//
1045 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1046 /// lexer buffer was all expanded at a single point, perform the mapping.
1047 /// This is currently only used for _Pragma implementation, so it is the slow
1048 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1049 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1050 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1051 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1052 SourceLocation FileLoc,
1053 unsigned CharNo, unsigned TokLen) {
1054 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1056 // Otherwise, we're lexing "mapped tokens". This is used for things like
1057 // _Pragma handling. Combine the expansion location of FileLoc with the
1058 // spelling location.
1059 SourceManager &SM = PP.getSourceManager();
1061 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1062 // characters come from spelling(FileLoc)+Offset.
1063 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1064 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1066 // Figure out the expansion loc range, which is the range covered by the
1067 // original _Pragma(...) sequence.
1068 std::pair<SourceLocation,SourceLocation> II =
1069 SM.getImmediateExpansionRange(FileLoc);
1071 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1074 /// getSourceLocation - Return a source location identifier for the specified
1075 /// offset in the current file.
1076 SourceLocation Lexer::getSourceLocation(const char *Loc,
1077 unsigned TokLen) const {
1078 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1079 "Location out of range for this buffer!");
1081 // In the normal case, we're just lexing from a simple file buffer, return
1082 // the file id from FileLoc with the offset specified.
1083 unsigned CharNo = Loc-BufferStart;
1084 if (FileLoc.isFileID())
1085 return FileLoc.getLocWithOffset(CharNo);
1087 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1088 // tokens are lexed from where the _Pragma was defined.
1089 assert(PP && "This doesn't work on raw lexers");
1090 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1093 /// Diag - Forwarding function for diagnostics. This translate a source
1094 /// position in the current buffer into a SourceLocation object for rendering.
1095 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1096 return PP->Diag(getSourceLocation(Loc), DiagID);
1099 //===----------------------------------------------------------------------===//
1100 // Trigraph and Escaped Newline Handling Code.
1101 //===----------------------------------------------------------------------===//
1103 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1104 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1105 static char GetTrigraphCharForLetter(char Letter) {
1108 case '=': return '#';
1109 case ')': return ']';
1110 case '(': return '[';
1111 case '!': return '|';
1112 case '\'': return '^';
1113 case '>': return '}';
1114 case '/': return '\\';
1115 case '<': return '{';
1116 case '-': return '~';
1120 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1121 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1122 /// return the result character. Finally, emit a warning about trigraph use
1123 /// whether trigraphs are enabled or not.
1124 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1125 char Res = GetTrigraphCharForLetter(*CP);
1126 if (!Res || !L) return Res;
1128 if (!L->getLangOpts().Trigraphs) {
1129 if (!L->isLexingRawMode())
1130 L->Diag(CP-2, diag::trigraph_ignored);
1134 if (!L->isLexingRawMode())
1135 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1139 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1140 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1141 /// trigraph equivalent on entry to this function.
1142 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1144 while (isWhitespace(Ptr[Size])) {
1147 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1150 // If this is a \r\n or \n\r, skip the other half.
1151 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1152 Ptr[Size-1] != Ptr[Size])
1158 // Not an escaped newline, must be a \t or something else.
1162 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1163 /// them), skip over them and return the first non-escaped-newline found,
1164 /// otherwise return P.
1165 const char *Lexer::SkipEscapedNewLines(const char *P) {
1167 const char *AfterEscape;
1170 } else if (*P == '?') {
1171 // If not a trigraph for escape, bail out.
1172 if (P[1] != '?' || P[2] != '/')
1179 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1180 if (NewLineSize == 0) return P;
1181 P = AfterEscape+NewLineSize;
1185 /// \brief Checks that the given token is the first token that occurs after the
1186 /// given location (this excludes comments and whitespace). Returns the location
1187 /// immediately after the specified token. If the token is not found or the
1188 /// location is inside a macro, the returned source location will be invalid.
1189 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1190 tok::TokenKind TKind,
1191 const SourceManager &SM,
1192 const LangOptions &LangOpts,
1193 bool SkipTrailingWhitespaceAndNewLine) {
1194 if (Loc.isMacroID()) {
1195 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1196 return SourceLocation();
1198 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1200 // Break down the source location.
1201 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1203 // Try to load the file buffer.
1204 bool InvalidTemp = false;
1205 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1207 return SourceLocation();
1209 const char *TokenBegin = File.data() + LocInfo.second;
1211 // Lex from the start of the given location.
1212 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1213 TokenBegin, File.end());
1216 lexer.LexFromRawLexer(Tok);
1217 if (Tok.isNot(TKind))
1218 return SourceLocation();
1219 SourceLocation TokenLoc = Tok.getLocation();
1221 // Calculate how much whitespace needs to be skipped if any.
1222 unsigned NumWhitespaceChars = 0;
1223 if (SkipTrailingWhitespaceAndNewLine) {
1224 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1226 unsigned char C = *TokenEnd;
1227 while (isHorizontalWhitespace(C)) {
1229 NumWhitespaceChars++;
1232 // Skip \r, \n, \r\n, or \n\r
1233 if (C == '\n' || C == '\r') {
1236 NumWhitespaceChars++;
1237 if ((C == '\n' || C == '\r') && C != PrevC)
1238 NumWhitespaceChars++;
1242 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1245 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1246 /// get its size, and return it. This is tricky in several cases:
1247 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1248 /// then either return the trigraph (skipping 3 chars) or the '?',
1249 /// depending on whether trigraphs are enabled or not.
1250 /// 2. If this is an escaped newline (potentially with whitespace between
1251 /// the backslash and newline), implicitly skip the newline and return
1252 /// the char after it.
1254 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1255 /// know that we can accumulate into Size, and that we have already incremented
1256 /// Ptr by Size bytes.
1258 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1259 /// be updated to match.
1261 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1263 // If we have a slash, look for an escaped newline.
1264 if (Ptr[0] == '\\') {
1268 // Common case, backslash-char where the char is not whitespace.
1269 if (!isWhitespace(Ptr[0])) return '\\';
1271 // See if we have optional whitespace characters between the slash and
1273 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1274 // Remember that this token needs to be cleaned.
1275 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1277 // Warn if there was whitespace between the backslash and newline.
1278 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1279 Diag(Ptr, diag::backslash_newline_space);
1281 // Found backslash<whitespace><newline>. Parse the char after it.
1282 Size += EscapedNewLineSize;
1283 Ptr += EscapedNewLineSize;
1285 // If the char that we finally got was a \n, then we must have had
1286 // something like \<newline><newline>. We don't want to consume the
1288 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1291 // Use slow version to accumulate a correct size field.
1292 return getCharAndSizeSlow(Ptr, Size, Tok);
1295 // Otherwise, this is not an escaped newline, just return the slash.
1299 // If this is a trigraph, process it.
1300 if (Ptr[0] == '?' && Ptr[1] == '?') {
1301 // If this is actually a legal trigraph (not something like "??x"), emit
1302 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1303 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1304 // Remember that this token needs to be cleaned.
1305 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1309 if (C == '\\') goto Slash;
1314 // If this is neither, return a single character.
1319 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1320 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1321 /// and that we have already incremented Ptr by Size bytes.
1323 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1324 /// be updated to match.
1325 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1326 const LangOptions &LangOpts) {
1327 // If we have a slash, look for an escaped newline.
1328 if (Ptr[0] == '\\') {
1332 // Common case, backslash-char where the char is not whitespace.
1333 if (!isWhitespace(Ptr[0])) return '\\';
1335 // See if we have optional whitespace characters followed by a newline.
1336 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1337 // Found backslash<whitespace><newline>. Parse the char after it.
1338 Size += EscapedNewLineSize;
1339 Ptr += EscapedNewLineSize;
1341 // If the char that we finally got was a \n, then we must have had
1342 // something like \<newline><newline>. We don't want to consume the
1344 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1347 // Use slow version to accumulate a correct size field.
1348 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1351 // Otherwise, this is not an escaped newline, just return the slash.
1355 // If this is a trigraph, process it.
1356 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1357 // If this is actually a legal trigraph (not something like "??x"), return
1359 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1362 if (C == '\\') goto Slash;
1367 // If this is neither, return a single character.
1372 //===----------------------------------------------------------------------===//
1373 // Helper methods for lexing.
1374 //===----------------------------------------------------------------------===//
1376 /// \brief Routine that indiscriminately skips bytes in the source file.
1377 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1379 if (BufferPtr > BufferEnd)
1380 BufferPtr = BufferEnd;
1381 // FIXME: What exactly does the StartOfLine bit mean? There are two
1382 // possible meanings for the "start" of the line: the first token on the
1383 // unexpanded line, or the first token on the expanded line.
1384 IsAtStartOfLine = StartOfLine;
1385 IsAtPhysicalStartOfLine = StartOfLine;
1388 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1389 if (LangOpts.AsmPreprocessor) {
1391 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1392 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1393 C11AllowedIDCharRanges);
1394 return C11AllowedIDChars.contains(C);
1395 } else if (LangOpts.CPlusPlus) {
1396 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1397 CXX03AllowedIDCharRanges);
1398 return CXX03AllowedIDChars.contains(C);
1400 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1401 C99AllowedIDCharRanges);
1402 return C99AllowedIDChars.contains(C);
1406 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1407 assert(isAllowedIDChar(C, LangOpts));
1408 if (LangOpts.AsmPreprocessor) {
1410 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1411 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1412 C11DisallowedInitialIDCharRanges);
1413 return !C11DisallowedInitialIDChars.contains(C);
1414 } else if (LangOpts.CPlusPlus) {
1417 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1418 C99DisallowedInitialIDCharRanges);
1419 return !C99DisallowedInitialIDChars.contains(C);
1423 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1425 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1426 L.getSourceLocation(End));
1429 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1430 CharSourceRange Range, bool IsFirst) {
1431 // Check C99 compatibility.
1432 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1434 CannotAppearInIdentifier = 0,
1435 CannotStartIdentifier
1438 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1439 C99AllowedIDCharRanges);
1440 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1441 C99DisallowedInitialIDCharRanges);
1442 if (!C99AllowedIDChars.contains(C)) {
1443 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1445 << CannotAppearInIdentifier;
1446 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1447 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1449 << CannotStartIdentifier;
1453 // Check C++98 compatibility.
1454 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1455 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1456 CXX03AllowedIDCharRanges);
1457 if (!CXX03AllowedIDChars.contains(C)) {
1458 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1464 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1466 const char *UCNPtr = CurPtr + Size;
1467 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1468 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1471 if (!isLexingRawMode())
1472 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1473 makeCharRange(*this, CurPtr, UCNPtr),
1476 Result.setFlag(Token::HasUCN);
1477 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1478 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1481 while (CurPtr != UCNPtr)
1482 (void)getAndAdvanceChar(CurPtr, Result);
1486 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1487 const char *UnicodePtr = CurPtr;
1488 llvm::UTF32 CodePoint;
1489 llvm::ConversionResult Result =
1490 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1491 (const llvm::UTF8 *)BufferEnd,
1493 llvm::strictConversion);
1494 if (Result != llvm::conversionOK ||
1495 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1498 if (!isLexingRawMode())
1499 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1500 makeCharRange(*this, CurPtr, UnicodePtr),
1503 CurPtr = UnicodePtr;
1507 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1508 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1510 unsigned char C = *CurPtr++;
1511 while (isIdentifierBody(C))
1514 --CurPtr; // Back up over the skipped character.
1516 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1517 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1519 // TODO: Could merge these checks into an InfoTable flag to make the
1520 // comparison cheaper
1521 if (isASCII(C) && C != '\\' && C != '?' &&
1522 (C != '$' || !LangOpts.DollarIdents)) {
1524 const char *IdStart = BufferPtr;
1525 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1526 Result.setRawIdentifierData(IdStart);
1528 // If we are in raw mode, return this identifier raw. There is no need to
1529 // look up identifier information or attempt to macro expand it.
1533 // Fill in Result.IdentifierInfo and update the token kind,
1534 // looking up the identifier in the identifier table.
1535 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1537 // Finally, now that we know we have an identifier, pass this off to the
1538 // preprocessor, which may macro expand it or something.
1539 if (II->isHandleIdentifierCase())
1540 return PP->HandleIdentifier(Result);
1542 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1543 && II->getPPKeywordID() == tok::pp_not_keyword
1544 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1545 // Return the code-completion token.
1546 Result.setKind(tok::code_completion);
1553 // Otherwise, $,\,? in identifier found. Enter slower path.
1555 C = getCharAndSize(CurPtr, Size);
1558 // If we hit a $ and they are not supported in identifiers, we are done.
1559 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1561 // Otherwise, emit a diagnostic and continue.
1562 if (!isLexingRawMode())
1563 Diag(CurPtr, diag::ext_dollar_in_identifier);
1564 CurPtr = ConsumeChar(CurPtr, Size, Result);
1565 C = getCharAndSize(CurPtr, Size);
1568 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1569 C = getCharAndSize(CurPtr, Size);
1571 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1572 C = getCharAndSize(CurPtr, Size);
1574 } else if (!isIdentifierBody(C)) {
1575 goto FinishIdentifier;
1578 // Otherwise, this character is good, consume it.
1579 CurPtr = ConsumeChar(CurPtr, Size, Result);
1581 C = getCharAndSize(CurPtr, Size);
1582 while (isIdentifierBody(C)) {
1583 CurPtr = ConsumeChar(CurPtr, Size, Result);
1584 C = getCharAndSize(CurPtr, Size);
1589 /// isHexaLiteral - Return true if Start points to a hex constant.
1590 /// in microsoft mode (where this is supposed to be several different tokens).
1591 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1593 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1596 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1597 return (C2 == 'x' || C2 == 'X');
1600 /// LexNumericConstant - Lex the remainder of a integer or floating point
1601 /// constant. From[-1] is the first character lexed. Return the end of the
1603 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1605 char C = getCharAndSize(CurPtr, Size);
1607 while (isPreprocessingNumberBody(C)) {
1608 CurPtr = ConsumeChar(CurPtr, Size, Result);
1610 C = getCharAndSize(CurPtr, Size);
1613 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1614 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1615 // If we are in Microsoft mode, don't continue if the constant is hex.
1616 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1617 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1618 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1621 // If we have a hex FP constant, continue.
1622 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1623 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1624 // not-quite-conforming extension. Only do so if this looks like it's
1625 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1626 bool IsHexFloat = true;
1627 if (!LangOpts.C99) {
1628 if (!isHexaLiteral(BufferPtr, LangOpts))
1630 else if (!getLangOpts().CPlusPlus1z &&
1631 std::find(BufferPtr, CurPtr, '_') != CurPtr)
1635 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1638 // If we have a digit separator, continue.
1639 if (C == '\'' && getLangOpts().CPlusPlus14) {
1641 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1642 if (isIdentifierBody(Next)) {
1643 if (!isLexingRawMode())
1644 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1645 CurPtr = ConsumeChar(CurPtr, Size, Result);
1646 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1647 return LexNumericConstant(Result, CurPtr);
1651 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1652 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1653 return LexNumericConstant(Result, CurPtr);
1654 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1655 return LexNumericConstant(Result, CurPtr);
1657 // Update the location of token as well as BufferPtr.
1658 const char *TokStart = BufferPtr;
1659 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1660 Result.setLiteralData(TokStart);
1664 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1665 /// in C++11, or warn on a ud-suffix in C++98.
1666 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1667 bool IsStringLiteral) {
1668 assert(getLangOpts().CPlusPlus);
1670 // Maximally munch an identifier.
1672 char C = getCharAndSize(CurPtr, Size);
1673 bool Consumed = false;
1675 if (!isIdentifierHead(C)) {
1676 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1678 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1684 if (!getLangOpts().CPlusPlus11) {
1685 if (!isLexingRawMode())
1687 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1688 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1689 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1693 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1694 // that does not start with an underscore is ill-formed. As a conforming
1695 // extension, we treat all such suffixes as if they had whitespace before
1696 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1697 // likely to be a ud-suffix than a macro, however, and accept that.
1699 bool IsUDSuffix = false;
1702 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1703 // In C++1y, we need to look ahead a few characters to see if this is a
1704 // valid suffix for a string literal or a numeric literal (this could be
1705 // the 'operator""if' defining a numeric literal operator).
1706 const unsigned MaxStandardSuffixLength = 3;
1707 char Buffer[MaxStandardSuffixLength] = { C };
1708 unsigned Consumed = Size;
1712 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1714 if (!isIdentifierBody(Next)) {
1715 // End of suffix. Check whether this is on the whitelist.
1716 const StringRef CompleteSuffix(Buffer, Chars);
1717 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1722 if (Chars == MaxStandardSuffixLength)
1723 // Too long: can't be a standard suffix.
1726 Buffer[Chars++] = Next;
1727 Consumed += NextSize;
1732 if (!isLexingRawMode())
1733 Diag(CurPtr, getLangOpts().MSVCCompat
1734 ? diag::ext_ms_reserved_user_defined_literal
1735 : diag::ext_reserved_user_defined_literal)
1736 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1740 CurPtr = ConsumeChar(CurPtr, Size, Result);
1743 Result.setFlag(Token::HasUDSuffix);
1745 C = getCharAndSize(CurPtr, Size);
1746 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1747 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1748 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1755 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1756 /// either " or L" or u8" or u" or U".
1757 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1758 tok::TokenKind Kind) {
1759 // Does this string contain the \0 character?
1760 const char *NulCharacter = nullptr;
1762 if (!isLexingRawMode() &&
1763 (Kind == tok::utf8_string_literal ||
1764 Kind == tok::utf16_string_literal ||
1765 Kind == tok::utf32_string_literal))
1766 Diag(BufferPtr, getLangOpts().CPlusPlus
1767 ? diag::warn_cxx98_compat_unicode_literal
1768 : diag::warn_c99_compat_unicode_literal);
1770 char C = getAndAdvanceChar(CurPtr, Result);
1772 // Skip escaped characters. Escaped newlines will already be processed by
1773 // getAndAdvanceChar.
1775 C = getAndAdvanceChar(CurPtr, Result);
1777 if (C == '\n' || C == '\r' || // Newline.
1778 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1779 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1780 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1781 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1786 if (isCodeCompletionPoint(CurPtr-1)) {
1787 PP->CodeCompleteNaturalLanguage();
1788 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1793 NulCharacter = CurPtr-1;
1795 C = getAndAdvanceChar(CurPtr, Result);
1798 // If we are in C++11, lex the optional ud-suffix.
1799 if (getLangOpts().CPlusPlus)
1800 CurPtr = LexUDSuffix(Result, CurPtr, true);
1802 // If a nul character existed in the string, warn about it.
1803 if (NulCharacter && !isLexingRawMode())
1804 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1806 // Update the location of the token as well as the BufferPtr instance var.
1807 const char *TokStart = BufferPtr;
1808 FormTokenWithChars(Result, CurPtr, Kind);
1809 Result.setLiteralData(TokStart);
1813 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1814 /// having lexed R", LR", u8R", uR", or UR".
1815 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1816 tok::TokenKind Kind) {
1817 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1818 // Between the initial and final double quote characters of the raw string,
1819 // any transformations performed in phases 1 and 2 (trigraphs,
1820 // universal-character-names, and line splicing) are reverted.
1822 if (!isLexingRawMode())
1823 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1825 unsigned PrefixLen = 0;
1827 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1830 // If the last character was not a '(', then we didn't lex a valid delimiter.
1831 if (CurPtr[PrefixLen] != '(') {
1832 if (!isLexingRawMode()) {
1833 const char *PrefixEnd = &CurPtr[PrefixLen];
1834 if (PrefixLen == 16) {
1835 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1837 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1838 << StringRef(PrefixEnd, 1);
1842 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1843 // it's possible the '"' was intended to be part of the raw string, but
1844 // there's not much we can do about that.
1850 if (C == 0 && CurPtr-1 == BufferEnd) {
1856 FormTokenWithChars(Result, CurPtr, tok::unknown);
1860 // Save prefix and move CurPtr past it
1861 const char *Prefix = CurPtr;
1862 CurPtr += PrefixLen + 1; // skip over prefix and '('
1868 // Check for prefix match and closing quote.
1869 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1870 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1873 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1874 if (!isLexingRawMode())
1875 Diag(BufferPtr, diag::err_unterminated_raw_string)
1876 << StringRef(Prefix, PrefixLen);
1877 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1882 // If we are in C++11, lex the optional ud-suffix.
1883 if (getLangOpts().CPlusPlus)
1884 CurPtr = LexUDSuffix(Result, CurPtr, true);
1886 // Update the location of token as well as BufferPtr.
1887 const char *TokStart = BufferPtr;
1888 FormTokenWithChars(Result, CurPtr, Kind);
1889 Result.setLiteralData(TokStart);
1893 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1894 /// after having lexed the '<' character. This is used for #include filenames.
1895 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1896 // Does this string contain the \0 character?
1897 const char *NulCharacter = nullptr;
1898 const char *AfterLessPos = CurPtr;
1899 char C = getAndAdvanceChar(CurPtr, Result);
1901 // Skip escaped characters.
1902 if (C == '\\' && CurPtr < BufferEnd) {
1903 // Skip the escaped character.
1904 getAndAdvanceChar(CurPtr, Result);
1905 } else if (C == '\n' || C == '\r' || // Newline.
1906 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1907 isCodeCompletionPoint(CurPtr-1)))) {
1908 // If the filename is unterminated, then it must just be a lone <
1909 // character. Return this as such.
1910 FormTokenWithChars(Result, AfterLessPos, tok::less);
1912 } else if (C == 0) {
1913 NulCharacter = CurPtr-1;
1915 C = getAndAdvanceChar(CurPtr, Result);
1918 // If a nul character existed in the string, warn about it.
1919 if (NulCharacter && !isLexingRawMode())
1920 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1922 // Update the location of token as well as BufferPtr.
1923 const char *TokStart = BufferPtr;
1924 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1925 Result.setLiteralData(TokStart);
1929 /// LexCharConstant - Lex the remainder of a character constant, after having
1930 /// lexed either ' or L' or u8' or u' or U'.
1931 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1932 tok::TokenKind Kind) {
1933 // Does this character contain the \0 character?
1934 const char *NulCharacter = nullptr;
1936 if (!isLexingRawMode()) {
1937 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1938 Diag(BufferPtr, getLangOpts().CPlusPlus
1939 ? diag::warn_cxx98_compat_unicode_literal
1940 : diag::warn_c99_compat_unicode_literal);
1941 else if (Kind == tok::utf8_char_constant)
1942 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1945 char C = getAndAdvanceChar(CurPtr, Result);
1947 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1948 Diag(BufferPtr, diag::ext_empty_character);
1949 FormTokenWithChars(Result, CurPtr, tok::unknown);
1954 // Skip escaped characters.
1956 C = getAndAdvanceChar(CurPtr, Result);
1958 if (C == '\n' || C == '\r' || // Newline.
1959 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1960 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1961 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
1962 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1967 if (isCodeCompletionPoint(CurPtr-1)) {
1968 PP->CodeCompleteNaturalLanguage();
1969 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1974 NulCharacter = CurPtr-1;
1976 C = getAndAdvanceChar(CurPtr, Result);
1979 // If we are in C++11, lex the optional ud-suffix.
1980 if (getLangOpts().CPlusPlus)
1981 CurPtr = LexUDSuffix(Result, CurPtr, false);
1983 // If a nul character existed in the character, warn about it.
1984 if (NulCharacter && !isLexingRawMode())
1985 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
1987 // Update the location of token as well as BufferPtr.
1988 const char *TokStart = BufferPtr;
1989 FormTokenWithChars(Result, CurPtr, Kind);
1990 Result.setLiteralData(TokStart);
1994 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1995 /// Update BufferPtr to point to the next non-whitespace character and return.
1997 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1999 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2000 bool &TokAtPhysicalStartOfLine) {
2001 // Whitespace - Skip it, then return the token after the whitespace.
2002 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2004 unsigned char Char = *CurPtr;
2006 // Skip consecutive spaces efficiently.
2008 // Skip horizontal whitespace very aggressively.
2009 while (isHorizontalWhitespace(Char))
2012 // Otherwise if we have something other than whitespace, we're done.
2013 if (!isVerticalWhitespace(Char))
2016 if (ParsingPreprocessorDirective) {
2017 // End of preprocessor directive line, let LexTokenInternal handle this.
2022 // OK, but handle newline.
2027 // If the client wants us to return whitespace, return it now.
2028 if (isKeepWhitespaceMode()) {
2029 FormTokenWithChars(Result, CurPtr, tok::unknown);
2031 IsAtStartOfLine = true;
2032 IsAtPhysicalStartOfLine = true;
2034 // FIXME: The next token will not have LeadingSpace set.
2038 // If this isn't immediately after a newline, there is leading space.
2039 char PrevChar = CurPtr[-1];
2040 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2042 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2044 Result.setFlag(Token::StartOfLine);
2045 TokAtPhysicalStartOfLine = true;
2052 /// We have just read the // characters from input. Skip until we find the
2053 /// newline character thats terminate the comment. Then update BufferPtr and
2056 /// If we're in KeepCommentMode or any CommentHandler has inserted
2057 /// some tokens, this will store the first token and return true.
2058 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2059 bool &TokAtPhysicalStartOfLine) {
2060 // If Line comments aren't explicitly enabled for this language, emit an
2061 // extension warning.
2062 if (!LangOpts.LineComment && !isLexingRawMode()) {
2063 Diag(BufferPtr, diag::ext_line_comment);
2065 // Mark them enabled so we only emit one warning for this translation
2067 LangOpts.LineComment = true;
2070 // Scan over the body of the comment. The common case, when scanning, is that
2071 // the comment contains normal ascii characters with nothing interesting in
2072 // them. As such, optimize for this case with the inner loop.
2076 // Skip over characters in the fast loop.
2077 while (C != 0 && // Potentially EOF.
2078 C != '\n' && C != '\r') // Newline or DOS-style newline.
2081 const char *NextLine = CurPtr;
2083 // We found a newline, see if it's escaped.
2084 const char *EscapePtr = CurPtr-1;
2085 bool HasSpace = false;
2086 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2091 if (*EscapePtr == '\\') // Escaped newline.
2093 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2094 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2095 CurPtr = EscapePtr-2;
2097 break; // This is a newline, we're done.
2099 // If there was space between the backslash and newline, warn about it.
2100 if (HasSpace && !isLexingRawMode())
2101 Diag(EscapePtr, diag::backslash_newline_space);
2104 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2105 // properly decode the character. Read it in raw mode to avoid emitting
2106 // diagnostics about things like trigraphs. If we see an escaped newline,
2107 // we'll handle it below.
2108 const char *OldPtr = CurPtr;
2109 bool OldRawMode = isLexingRawMode();
2110 LexingRawMode = true;
2111 C = getAndAdvanceChar(CurPtr, Result);
2112 LexingRawMode = OldRawMode;
2114 // If we only read only one character, then no special handling is needed.
2115 // We're done and can skip forward to the newline.
2116 if (C != 0 && CurPtr == OldPtr+1) {
2121 // If we read multiple characters, and one of those characters was a \r or
2122 // \n, then we had an escaped newline within the comment. Emit diagnostic
2123 // unless the next line is also a // comment.
2124 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2125 for (; OldPtr != CurPtr; ++OldPtr)
2126 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2127 // Okay, we found a // comment that ends in a newline, if the next
2128 // line is also a // comment, but has spaces, don't emit a diagnostic.
2129 if (isWhitespace(C)) {
2130 const char *ForwardPtr = CurPtr;
2131 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2133 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2137 if (!isLexingRawMode())
2138 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2143 if (CurPtr == BufferEnd+1) {
2148 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2149 PP->CodeCompleteNaturalLanguage();
2154 } while (C != '\n' && C != '\r');
2156 // Found but did not consume the newline. Notify comment handlers about the
2157 // comment unless we're in a #if 0 block.
2158 if (PP && !isLexingRawMode() &&
2159 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2160 getSourceLocation(CurPtr)))) {
2162 return true; // A token has to be returned.
2165 // If we are returning comments as tokens, return this comment as a token.
2166 if (inKeepCommentMode())
2167 return SaveLineComment(Result, CurPtr);
2169 // If we are inside a preprocessor directive and we see the end of line,
2170 // return immediately, so that the lexer can return this as an EOD token.
2171 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2176 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2177 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2178 // contribute to another token), it isn't needed for correctness. Note that
2179 // this is ok even in KeepWhitespaceMode, because we would have returned the
2180 /// comment above in that mode.
2183 // The next returned token is at the start of the line.
2184 Result.setFlag(Token::StartOfLine);
2185 TokAtPhysicalStartOfLine = true;
2186 // No leading whitespace seen so far.
2187 Result.clearFlag(Token::LeadingSpace);
2192 /// If in save-comment mode, package up this Line comment in an appropriate
2193 /// way and return it.
2194 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2195 // If we're not in a preprocessor directive, just return the // comment
2197 FormTokenWithChars(Result, CurPtr, tok::comment);
2199 if (!ParsingPreprocessorDirective || LexingRawMode)
2202 // If this Line-style comment is in a macro definition, transmogrify it into
2203 // a C-style block comment.
2204 bool Invalid = false;
2205 std::string Spelling = PP->getSpelling(Result, &Invalid);
2209 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2210 Spelling[1] = '*'; // Change prefix to "/*".
2211 Spelling += "*/"; // add suffix.
2213 Result.setKind(tok::comment);
2214 PP->CreateString(Spelling, Result,
2215 Result.getLocation(), Result.getLocation());
2219 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2220 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2221 /// a diagnostic if so. We know that the newline is inside of a block comment.
2222 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2224 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2226 // Back up off the newline.
2229 // If this is a two-character newline sequence, skip the other character.
2230 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2231 // \n\n or \r\r -> not escaped newline.
2232 if (CurPtr[0] == CurPtr[1])
2234 // \n\r or \r\n -> skip the newline.
2238 // If we have horizontal whitespace, skip over it. We allow whitespace
2239 // between the slash and newline.
2240 bool HasSpace = false;
2241 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2246 // If we have a slash, we know this is an escaped newline.
2247 if (*CurPtr == '\\') {
2248 if (CurPtr[-1] != '*') return false;
2250 // It isn't a slash, is it the ?? / trigraph?
2251 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2255 // This is the trigraph ending the comment. Emit a stern warning!
2258 // If no trigraphs are enabled, warn that we ignored this trigraph and
2259 // ignore this * character.
2260 if (!L->getLangOpts().Trigraphs) {
2261 if (!L->isLexingRawMode())
2262 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2265 if (!L->isLexingRawMode())
2266 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2269 // Warn about having an escaped newline between the */ characters.
2270 if (!L->isLexingRawMode())
2271 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2273 // If there was space between the backslash and newline, warn about it.
2274 if (HasSpace && !L->isLexingRawMode())
2275 L->Diag(CurPtr, diag::backslash_newline_space);
2281 #include <emmintrin.h>
2283 #include <altivec.h>
2287 /// We have just read from input the / and * characters that started a comment.
2288 /// Read until we find the * and / characters that terminate the comment.
2289 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2290 /// comments, because they cannot cause the comment to end. The only thing
2291 /// that can happen is the comment could end with an escaped newline between
2292 /// the terminating * and /.
2294 /// If we're in KeepCommentMode or any CommentHandler has inserted
2295 /// some tokens, this will store the first token and return true.
2296 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2297 bool &TokAtPhysicalStartOfLine) {
2298 // Scan one character past where we should, looking for a '/' character. Once
2299 // we find it, check to see if it was preceded by a *. This common
2300 // optimization helps people who like to put a lot of * characters in their
2303 // The first character we get with newlines and trigraphs skipped to handle
2304 // the degenerate /*/ case below correctly if the * has an escaped newline
2307 unsigned char C = getCharAndSize(CurPtr, CharSize);
2309 if (C == 0 && CurPtr == BufferEnd+1) {
2310 if (!isLexingRawMode())
2311 Diag(BufferPtr, diag::err_unterminated_block_comment);
2314 // KeepWhitespaceMode should return this broken comment as a token. Since
2315 // it isn't a well formed comment, just return it as an 'unknown' token.
2316 if (isKeepWhitespaceMode()) {
2317 FormTokenWithChars(Result, CurPtr, tok::unknown);
2325 // Check to see if the first character after the '/*' is another /. If so,
2326 // then this slash does not end the block comment, it is part of it.
2331 // Skip over all non-interesting characters until we find end of buffer or a
2332 // (probably ending) '/' character.
2333 if (CurPtr + 24 < BufferEnd &&
2334 // If there is a code-completion point avoid the fast scan because it
2335 // doesn't check for '\0'.
2336 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2337 // While not aligned to a 16-byte boundary.
2338 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2341 if (C == '/') goto FoundSlash;
2344 __m128i Slashes = _mm_set1_epi8('/');
2345 while (CurPtr+16 <= BufferEnd) {
2346 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2349 // Adjust the pointer to point directly after the first slash. It's
2350 // not necessary to set C here, it will be overwritten at the end of
2352 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2358 __vector unsigned char Slashes = {
2359 '/', '/', '/', '/', '/', '/', '/', '/',
2360 '/', '/', '/', '/', '/', '/', '/', '/'
2362 while (CurPtr+16 <= BufferEnd &&
2363 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2366 // Scan for '/' quickly. Many block comments are very large.
2367 while (CurPtr[0] != '/' &&
2371 CurPtr+4 < BufferEnd) {
2376 // It has to be one of the bytes scanned, increment to it and read one.
2380 // Loop to scan the remainder.
2381 while (C != '/' && C != '\0')
2386 if (CurPtr[-2] == '*') // We found the final */. We're done!
2389 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2390 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2391 // We found the final */, though it had an escaped newline between the
2392 // * and /. We're done!
2396 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2397 // If this is a /* inside of the comment, emit a warning. Don't do this
2398 // if this is a /*/, which will end the comment. This misses cases with
2399 // embedded escaped newlines, but oh well.
2400 if (!isLexingRawMode())
2401 Diag(CurPtr-1, diag::warn_nested_block_comment);
2403 } else if (C == 0 && CurPtr == BufferEnd+1) {
2404 if (!isLexingRawMode())
2405 Diag(BufferPtr, diag::err_unterminated_block_comment);
2406 // Note: the user probably forgot a */. We could continue immediately
2407 // after the /*, but this would involve lexing a lot of what really is the
2408 // comment, which surely would confuse the parser.
2411 // KeepWhitespaceMode should return this broken comment as a token. Since
2412 // it isn't a well formed comment, just return it as an 'unknown' token.
2413 if (isKeepWhitespaceMode()) {
2414 FormTokenWithChars(Result, CurPtr, tok::unknown);
2420 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2421 PP->CodeCompleteNaturalLanguage();
2429 // Notify comment handlers about the comment unless we're in a #if 0 block.
2430 if (PP && !isLexingRawMode() &&
2431 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2432 getSourceLocation(CurPtr)))) {
2434 return true; // A token has to be returned.
2437 // If we are returning comments as tokens, return this comment as a token.
2438 if (inKeepCommentMode()) {
2439 FormTokenWithChars(Result, CurPtr, tok::comment);
2443 // It is common for the tokens immediately after a /**/ comment to be
2444 // whitespace. Instead of going through the big switch, handle it
2445 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2446 // have already returned above with the comment as a token.
2447 if (isHorizontalWhitespace(*CurPtr)) {
2448 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2452 // Otherwise, just return so that the next character will be lexed as a token.
2454 Result.setFlag(Token::LeadingSpace);
2458 //===----------------------------------------------------------------------===//
2459 // Primary Lexing Entry Points
2460 //===----------------------------------------------------------------------===//
2462 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2463 /// uninterpreted string. This switches the lexer out of directive mode.
2464 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2465 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2466 "Must be in a preprocessing directive!");
2469 // CurPtr - Cache BufferPtr in an automatic variable.
2470 const char *CurPtr = BufferPtr;
2472 char Char = getAndAdvanceChar(CurPtr, Tmp);
2476 Result->push_back(Char);
2479 // Found end of file?
2480 if (CurPtr-1 != BufferEnd) {
2481 if (isCodeCompletionPoint(CurPtr-1)) {
2482 PP->CodeCompleteNaturalLanguage();
2487 // Nope, normal character, continue.
2489 Result->push_back(Char);
2495 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2496 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2497 BufferPtr = CurPtr-1;
2499 // Next, lex the character, which should handle the EOD transition.
2501 if (Tmp.is(tok::code_completion)) {
2503 PP->CodeCompleteNaturalLanguage();
2506 assert(Tmp.is(tok::eod) && "Unexpected token!");
2508 // Finally, we're done;
2514 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2515 /// condition, reporting diagnostics and handling other edge cases as required.
2516 /// This returns true if Result contains a token, false if PP.Lex should be
2518 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2519 // If we hit the end of the file while parsing a preprocessor directive,
2520 // end the preprocessor directive first. The next token returned will
2521 // then be the end of file.
2522 if (ParsingPreprocessorDirective) {
2523 // Done parsing the "line".
2524 ParsingPreprocessorDirective = false;
2525 // Update the location of token as well as BufferPtr.
2526 FormTokenWithChars(Result, CurPtr, tok::eod);
2528 // Restore comment saving mode, in case it was disabled for directive.
2530 resetExtendedTokenMode();
2531 return true; // Have a token.
2534 // If we are in raw mode, return this event as an EOF token. Let the caller
2535 // that put us in raw mode handle the event.
2536 if (isLexingRawMode()) {
2537 Result.startToken();
2538 BufferPtr = BufferEnd;
2539 FormTokenWithChars(Result, BufferEnd, tok::eof);
2543 // Issue diagnostics for unterminated #if and missing newline.
2545 // If we are in a #if directive, emit an error.
2546 while (!ConditionalStack.empty()) {
2547 if (PP->getCodeCompletionFileLoc() != FileLoc)
2548 PP->Diag(ConditionalStack.back().IfLoc,
2549 diag::err_pp_unterminated_conditional);
2550 ConditionalStack.pop_back();
2553 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2555 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2556 DiagnosticsEngine &Diags = PP->getDiagnostics();
2557 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2560 if (LangOpts.CPlusPlus11) {
2561 // C++11 [lex.phases] 2.2 p2
2562 // Prefer the C++98 pedantic compatibility warning over the generic,
2563 // non-extension, user-requested "missing newline at EOF" warning.
2564 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2565 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2567 DiagID = diag::warn_no_newline_eof;
2570 DiagID = diag::ext_no_newline_eof;
2573 Diag(BufferEnd, DiagID)
2574 << FixItHint::CreateInsertion(EndLoc, "\n");
2579 // Finally, let the preprocessor handle this.
2580 return PP->HandleEndOfFile(Result, isPragmaLexer());
2583 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2584 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2585 /// else and 2 if there are no more tokens in the buffer controlled by the
2587 unsigned Lexer::isNextPPTokenLParen() {
2588 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2590 // Switch to 'skipping' mode. This will ensure that we can lex a token
2591 // without emitting diagnostics, disables macro expansion, and will cause EOF
2592 // to return an EOF token instead of popping the include stack.
2593 LexingRawMode = true;
2595 // Save state that can be changed while lexing so that we can restore it.
2596 const char *TmpBufferPtr = BufferPtr;
2597 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2598 bool atStartOfLine = IsAtStartOfLine;
2599 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2600 bool leadingSpace = HasLeadingSpace;
2605 // Restore state that may have changed.
2606 BufferPtr = TmpBufferPtr;
2607 ParsingPreprocessorDirective = inPPDirectiveMode;
2608 HasLeadingSpace = leadingSpace;
2609 IsAtStartOfLine = atStartOfLine;
2610 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2612 // Restore the lexer back to non-skipping mode.
2613 LexingRawMode = false;
2615 if (Tok.is(tok::eof))
2617 return Tok.is(tok::l_paren);
2620 /// \brief Find the end of a version control conflict marker.
2621 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2622 ConflictMarkerKind CMK) {
2623 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2624 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2625 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2626 size_t Pos = RestOfBuffer.find(Terminator);
2627 while (Pos != StringRef::npos) {
2628 // Must occur at start of line.
2630 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2631 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2632 Pos = RestOfBuffer.find(Terminator);
2635 return RestOfBuffer.data()+Pos;
2640 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2641 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2642 /// and recover nicely. This returns true if it is a conflict marker and false
2644 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2645 // Only a conflict marker if it starts at the beginning of a line.
2646 if (CurPtr != BufferStart &&
2647 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2650 // Check to see if we have <<<<<<< or >>>>.
2651 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2652 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2655 // If we have a situation where we don't care about conflict markers, ignore
2657 if (CurrentConflictMarkerState || isLexingRawMode())
2660 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2662 // Check to see if there is an ending marker somewhere in the buffer at the
2663 // start of a line to terminate this conflict marker.
2664 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2665 // We found a match. We are really in a conflict marker.
2666 // Diagnose this, and ignore to the end of line.
2667 Diag(CurPtr, diag::err_conflict_marker);
2668 CurrentConflictMarkerState = Kind;
2670 // Skip ahead to the end of line. We know this exists because the
2671 // end-of-conflict marker starts with \r or \n.
2672 while (*CurPtr != '\r' && *CurPtr != '\n') {
2673 assert(CurPtr != BufferEnd && "Didn't find end of line");
2680 // No end of conflict marker found.
2684 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2685 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2686 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2687 /// the line. This returns true if it is a conflict marker and false if not.
2688 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2689 // Only a conflict marker if it starts at the beginning of a line.
2690 if (CurPtr != BufferStart &&
2691 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2694 // If we have a situation where we don't care about conflict markers, ignore
2696 if (!CurrentConflictMarkerState || isLexingRawMode())
2699 // Check to see if we have the marker (4 characters in a row).
2700 for (unsigned i = 1; i != 4; ++i)
2701 if (CurPtr[i] != CurPtr[0])
2704 // If we do have it, search for the end of the conflict marker. This could
2705 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2706 // be the end of conflict marker.
2707 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2708 CurrentConflictMarkerState)) {
2711 // Skip ahead to the end of line.
2712 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2717 // No longer in the conflict marker.
2718 CurrentConflictMarkerState = CMK_None;
2725 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2726 if (PP && PP->isCodeCompletionEnabled()) {
2727 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2728 return Loc == PP->getCodeCompletionLoc();
2734 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2737 char Kind = getCharAndSize(StartPtr, CharSize);
2739 unsigned NumHexDigits;
2742 else if (Kind == 'U')
2747 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2748 if (Result && !isLexingRawMode())
2749 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2753 const char *CurPtr = StartPtr + CharSize;
2754 const char *KindLoc = &CurPtr[-1];
2756 uint32_t CodePoint = 0;
2757 for (unsigned i = 0; i < NumHexDigits; ++i) {
2758 char C = getCharAndSize(CurPtr, CharSize);
2760 unsigned Value = llvm::hexDigitValue(C);
2762 if (Result && !isLexingRawMode()) {
2764 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2765 << StringRef(KindLoc, 1);
2767 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2769 // If the user wrote \U1234, suggest a fixit to \u.
2770 if (i == 4 && NumHexDigits == 8) {
2771 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2772 Diag(KindLoc, diag::note_ucn_four_not_eight)
2773 << FixItHint::CreateReplacement(URange, "u");
2788 Result->setFlag(Token::HasUCN);
2789 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2792 while (StartPtr != CurPtr)
2793 (void)getAndAdvanceChar(StartPtr, *Result);
2798 // Don't apply C family restrictions to UCNs in assembly mode
2799 if (LangOpts.AsmPreprocessor)
2802 // C99 6.4.3p2: A universal character name shall not specify a character whose
2803 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2804 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2805 // C++11 [lex.charset]p2: If the hexadecimal value for a
2806 // universal-character-name corresponds to a surrogate code point (in the
2807 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2808 // if the hexadecimal value for a universal-character-name outside the
2809 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2810 // string literal corresponds to a control character (in either of the
2811 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2812 // basic source character set, the program is ill-formed.
2813 if (CodePoint < 0xA0) {
2814 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2817 // We don't use isLexingRawMode() here because we need to warn about bad
2818 // UCNs even when skipping preprocessing tokens in a #if block.
2820 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2821 Diag(BufferPtr, diag::err_ucn_control_character);
2823 char C = static_cast<char>(CodePoint);
2824 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2830 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2831 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2832 // We don't use isLexingRawMode() here because we need to diagnose bad
2833 // UCNs even when skipping preprocessing tokens in a #if block.
2835 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2836 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2838 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2846 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2847 const char *CurPtr) {
2848 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2849 UnicodeWhitespaceCharRanges);
2850 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2851 UnicodeWhitespaceChars.contains(C)) {
2852 Diag(BufferPtr, diag::ext_unicode_whitespace)
2853 << makeCharRange(*this, BufferPtr, CurPtr);
2855 Result.setFlag(Token::LeadingSpace);
2861 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2862 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2863 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2864 !PP->isPreprocessedOutput()) {
2865 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2866 makeCharRange(*this, BufferPtr, CurPtr),
2871 return LexIdentifier(Result, CurPtr);
2874 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2875 !PP->isPreprocessedOutput() &&
2876 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2877 // Non-ASCII characters tend to creep into source code unintentionally.
2878 // Instead of letting the parser complain about the unknown token,
2879 // just drop the character.
2880 // Note that we can /only/ do this when the non-ASCII character is actually
2881 // spelled as Unicode, not written as a UCN. The standard requires that
2882 // we not throw away any possible preprocessor tokens, but there's a
2883 // loophole in the mapping of Unicode characters to basic character set
2884 // characters that allows us to map these particular characters to, say,
2886 Diag(BufferPtr, diag::err_non_ascii)
2887 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2893 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2896 FormTokenWithChars(Result, CurPtr, tok::unknown);
2900 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2901 IsAtStartOfLine = Result.isAtStartOfLine();
2902 HasLeadingSpace = Result.hasLeadingSpace();
2903 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2904 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2907 bool Lexer::Lex(Token &Result) {
2908 // Start a new token.
2909 Result.startToken();
2911 // Set up misc whitespace flags for LexTokenInternal.
2912 if (IsAtStartOfLine) {
2913 Result.setFlag(Token::StartOfLine);
2914 IsAtStartOfLine = false;
2917 if (HasLeadingSpace) {
2918 Result.setFlag(Token::LeadingSpace);
2919 HasLeadingSpace = false;
2922 if (HasLeadingEmptyMacro) {
2923 Result.setFlag(Token::LeadingEmptyMacro);
2924 HasLeadingEmptyMacro = false;
2927 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2928 IsAtPhysicalStartOfLine = false;
2929 bool isRawLex = isLexingRawMode();
2931 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2932 // (After the LexTokenInternal call, the lexer might be destroyed.)
2933 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2934 return returnedToken;
2937 /// LexTokenInternal - This implements a simple C family lexer. It is an
2938 /// extremely performance critical piece of code. This assumes that the buffer
2939 /// has a null character at the end of the file. This returns a preprocessing
2940 /// token, not a normal token, as such, it is an internal interface. It assumes
2941 /// that the Flags of result have been cleared before calling this.
2942 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
2944 // New token, can't need cleaning yet.
2945 Result.clearFlag(Token::NeedsCleaning);
2946 Result.setIdentifierInfo(nullptr);
2948 // CurPtr - Cache BufferPtr in an automatic variable.
2949 const char *CurPtr = BufferPtr;
2951 // Small amounts of horizontal whitespace is very common between tokens.
2952 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2954 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2957 // If we are keeping whitespace and other tokens, just return what we just
2958 // skipped. The next lexer invocation will return the token after the
2960 if (isKeepWhitespaceMode()) {
2961 FormTokenWithChars(Result, CurPtr, tok::unknown);
2962 // FIXME: The next token will not have LeadingSpace set.
2967 Result.setFlag(Token::LeadingSpace);
2970 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
2972 // Read a character, advancing over it.
2973 char Char = getAndAdvanceChar(CurPtr, Result);
2974 tok::TokenKind Kind;
2978 // Found end of file?
2979 if (CurPtr-1 == BufferEnd)
2980 return LexEndOfFile(Result, CurPtr-1);
2982 // Check if we are performing code completion.
2983 if (isCodeCompletionPoint(CurPtr-1)) {
2984 // Return the code-completion token.
2985 Result.startToken();
2986 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2990 if (!isLexingRawMode())
2991 Diag(CurPtr-1, diag::null_in_file);
2992 Result.setFlag(Token::LeadingSpace);
2993 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2994 return true; // KeepWhitespaceMode
2996 // We know the lexer hasn't changed, so just try again with this lexer.
2997 // (We manually eliminate the tail call to avoid recursion.)
3000 case 26: // DOS & CP/M EOF: "^Z".
3001 // If we're in Microsoft extensions mode, treat this as end of file.
3002 if (LangOpts.MicrosoftExt) {
3003 if (!isLexingRawMode())
3004 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3005 return LexEndOfFile(Result, CurPtr-1);
3008 // If Microsoft extensions are disabled, this is just random garbage.
3009 Kind = tok::unknown;
3014 // If we are inside a preprocessor directive and we see the end of line,
3015 // we know we are done with the directive, so return an EOD token.
3016 if (ParsingPreprocessorDirective) {
3017 // Done parsing the "line".
3018 ParsingPreprocessorDirective = false;
3020 // Restore comment saving mode, in case it was disabled for directive.
3022 resetExtendedTokenMode();
3024 // Since we consumed a newline, we are back at the start of a line.
3025 IsAtStartOfLine = true;
3026 IsAtPhysicalStartOfLine = true;
3032 // No leading whitespace seen so far.
3033 Result.clearFlag(Token::LeadingSpace);
3035 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3036 return true; // KeepWhitespaceMode
3038 // We only saw whitespace, so just try again with this lexer.
3039 // (We manually eliminate the tail call to avoid recursion.)
3045 SkipHorizontalWhitespace:
3046 Result.setFlag(Token::LeadingSpace);
3047 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3048 return true; // KeepWhitespaceMode
3053 // If the next token is obviously a // or /* */ comment, skip it efficiently
3054 // too (without going through the big switch stmt).
3055 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3056 LangOpts.LineComment &&
3057 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3058 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3059 return true; // There is a token to return.
3060 goto SkipIgnoredUnits;
3061 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3062 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3063 return true; // There is a token to return.
3064 goto SkipIgnoredUnits;
3065 } else if (isHorizontalWhitespace(*CurPtr)) {
3066 goto SkipHorizontalWhitespace;
3068 // We only saw whitespace, so just try again with this lexer.
3069 // (We manually eliminate the tail call to avoid recursion.)
3072 // C99 6.4.4.1: Integer Constants.
3073 // C99 6.4.4.2: Floating Constants.
3074 case '0': case '1': case '2': case '3': case '4':
3075 case '5': case '6': case '7': case '8': case '9':
3076 // Notify MIOpt that we read a non-whitespace/non-comment token.
3078 return LexNumericConstant(Result, CurPtr);
3080 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3081 // Notify MIOpt that we read a non-whitespace/non-comment token.
3084 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3085 Char = getCharAndSize(CurPtr, SizeTmp);
3087 // UTF-16 string literal
3089 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3090 tok::utf16_string_literal);
3092 // UTF-16 character constant
3094 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3095 tok::utf16_char_constant);
3097 // UTF-16 raw string literal
3098 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3099 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3100 return LexRawStringLiteral(Result,
3101 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3103 tok::utf16_string_literal);
3106 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3108 // UTF-8 string literal
3110 return LexStringLiteral(Result,
3111 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3113 tok::utf8_string_literal);
3114 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3115 return LexCharConstant(
3116 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3118 tok::utf8_char_constant);
3120 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3122 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3123 // UTF-8 raw string literal
3125 return LexRawStringLiteral(Result,
3126 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3129 tok::utf8_string_literal);
3135 // treat u like the start of an identifier.
3136 return LexIdentifier(Result, CurPtr);
3138 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3139 // Notify MIOpt that we read a non-whitespace/non-comment token.
3142 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3143 Char = getCharAndSize(CurPtr, SizeTmp);
3145 // UTF-32 string literal
3147 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3148 tok::utf32_string_literal);
3150 // UTF-32 character constant
3152 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3153 tok::utf32_char_constant);
3155 // UTF-32 raw string literal
3156 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3157 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3158 return LexRawStringLiteral(Result,
3159 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3161 tok::utf32_string_literal);
3164 // treat U like the start of an identifier.
3165 return LexIdentifier(Result, CurPtr);
3167 case 'R': // Identifier or C++0x raw string literal
3168 // Notify MIOpt that we read a non-whitespace/non-comment token.
3171 if (LangOpts.CPlusPlus11) {
3172 Char = getCharAndSize(CurPtr, SizeTmp);
3175 return LexRawStringLiteral(Result,
3176 ConsumeChar(CurPtr, SizeTmp, Result),
3177 tok::string_literal);
3180 // treat R like the start of an identifier.
3181 return LexIdentifier(Result, CurPtr);
3183 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3184 // Notify MIOpt that we read a non-whitespace/non-comment token.
3186 Char = getCharAndSize(CurPtr, SizeTmp);
3188 // Wide string literal.
3190 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3191 tok::wide_string_literal);
3193 // Wide raw string literal.
3194 if (LangOpts.CPlusPlus11 && Char == 'R' &&
3195 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3196 return LexRawStringLiteral(Result,
3197 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3199 tok::wide_string_literal);
3201 // Wide character constant.
3203 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3204 tok::wide_char_constant);
3205 // FALL THROUGH, treating L like the start of an identifier.
3207 // C99 6.4.2: Identifiers.
3208 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3209 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3210 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3211 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3212 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3213 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3214 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3215 case 'v': case 'w': case 'x': case 'y': case 'z':
3217 // Notify MIOpt that we read a non-whitespace/non-comment token.
3219 return LexIdentifier(Result, CurPtr);
3221 case '$': // $ in identifiers.
3222 if (LangOpts.DollarIdents) {
3223 if (!isLexingRawMode())
3224 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3225 // Notify MIOpt that we read a non-whitespace/non-comment token.
3227 return LexIdentifier(Result, CurPtr);
3230 Kind = tok::unknown;
3233 // C99 6.4.4: Character Constants.
3235 // Notify MIOpt that we read a non-whitespace/non-comment token.
3237 return LexCharConstant(Result, CurPtr, tok::char_constant);
3239 // C99 6.4.5: String Literals.
3241 // Notify MIOpt that we read a non-whitespace/non-comment token.
3243 return LexStringLiteral(Result, CurPtr, tok::string_literal);
3245 // C99 6.4.6: Punctuators.
3247 Kind = tok::question;
3250 Kind = tok::l_square;
3253 Kind = tok::r_square;
3256 Kind = tok::l_paren;
3259 Kind = tok::r_paren;
3262 Kind = tok::l_brace;
3265 Kind = tok::r_brace;
3268 Char = getCharAndSize(CurPtr, SizeTmp);
3269 if (Char >= '0' && Char <= '9') {
3270 // Notify MIOpt that we read a non-whitespace/non-comment token.
3273 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3274 } else if (LangOpts.CPlusPlus && Char == '*') {
3275 Kind = tok::periodstar;
3277 } else if (Char == '.' &&
3278 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3279 Kind = tok::ellipsis;
3280 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3287 Char = getCharAndSize(CurPtr, SizeTmp);
3290 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3291 } else if (Char == '=') {
3292 Kind = tok::ampequal;
3293 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3299 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3300 Kind = tok::starequal;
3301 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3307 Char = getCharAndSize(CurPtr, SizeTmp);
3309 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3310 Kind = tok::plusplus;
3311 } else if (Char == '=') {
3312 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3313 Kind = tok::plusequal;
3319 Char = getCharAndSize(CurPtr, SizeTmp);
3320 if (Char == '-') { // --
3321 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3322 Kind = tok::minusminus;
3323 } else if (Char == '>' && LangOpts.CPlusPlus &&
3324 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3325 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3327 Kind = tok::arrowstar;
3328 } else if (Char == '>') { // ->
3329 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3331 } else if (Char == '=') { // -=
3332 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3333 Kind = tok::minusequal;
3342 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3343 Kind = tok::exclaimequal;
3344 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3346 Kind = tok::exclaim;
3351 Char = getCharAndSize(CurPtr, SizeTmp);
3352 if (Char == '/') { // Line comment.
3353 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3354 // want to lex this as a comment. There is one problem with this though,
3355 // that in one particular corner case, this can change the behavior of the
3356 // resultant program. For example, In "foo //**/ bar", C89 would lex
3357 // this as "foo / bar" and langauges with Line comments would lex it as
3358 // "foo". Check to see if the character after the second slash is a '*'.
3359 // If so, we will lex that as a "/" instead of the start of a comment.
3360 // However, we never do this if we are just preprocessing.
3361 bool TreatAsComment = LangOpts.LineComment &&
3362 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3363 if (!TreatAsComment)
3364 if (!(PP && PP->isPreprocessedOutput()))
3365 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3367 if (TreatAsComment) {
3368 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3369 TokAtPhysicalStartOfLine))
3370 return true; // There is a token to return.
3372 // It is common for the tokens immediately after a // comment to be
3373 // whitespace (indentation for the next line). Instead of going through
3374 // the big switch, handle it efficiently now.
3375 goto SkipIgnoredUnits;
3379 if (Char == '*') { // /**/ comment.
3380 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3381 TokAtPhysicalStartOfLine))
3382 return true; // There is a token to return.
3384 // We only saw whitespace, so just try again with this lexer.
3385 // (We manually eliminate the tail call to avoid recursion.)
3390 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3391 Kind = tok::slashequal;
3397 Char = getCharAndSize(CurPtr, SizeTmp);
3399 Kind = tok::percentequal;
3400 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3401 } else if (LangOpts.Digraphs && Char == '>') {
3402 Kind = tok::r_brace; // '%>' -> '}'
3403 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3404 } else if (LangOpts.Digraphs && Char == ':') {
3405 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3406 Char = getCharAndSize(CurPtr, SizeTmp);
3407 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3408 Kind = tok::hashhash; // '%:%:' -> '##'
3409 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3411 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3412 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3413 if (!isLexingRawMode())
3414 Diag(BufferPtr, diag::ext_charize_microsoft);
3416 } else { // '%:' -> '#'
3417 // We parsed a # character. If this occurs at the start of the line,
3418 // it's actually the start of a preprocessing directive. Callback to
3419 // the preprocessor to handle it.
3420 // TODO: -fpreprocessed mode??
3421 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3422 goto HandleDirective;
3427 Kind = tok::percent;
3431 Char = getCharAndSize(CurPtr, SizeTmp);
3432 if (ParsingFilename) {
3433 return LexAngledStringLiteral(Result, CurPtr);
3434 } else if (Char == '<') {
3435 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3437 Kind = tok::lesslessequal;
3438 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3440 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3441 // If this is actually a '<<<<<<<' version control conflict marker,
3442 // recognize it as such and recover nicely.
3444 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3445 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3448 } else if (LangOpts.CUDA && After == '<') {
3449 Kind = tok::lesslessless;
3450 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3453 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3454 Kind = tok::lessless;
3456 } else if (Char == '=') {
3457 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3458 Kind = tok::lessequal;
3459 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3460 if (LangOpts.CPlusPlus11 &&
3461 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3462 // C++0x [lex.pptoken]p3:
3463 // Otherwise, if the next three characters are <:: and the subsequent
3464 // character is neither : nor >, the < is treated as a preprocessor
3465 // token by itself and not as the first character of the alternative
3468 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3469 if (After != ':' && After != '>') {
3471 if (!isLexingRawMode())
3472 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3477 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3478 Kind = tok::l_square;
3479 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3480 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3481 Kind = tok::l_brace;
3487 Char = getCharAndSize(CurPtr, SizeTmp);
3489 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3490 Kind = tok::greaterequal;
3491 } else if (Char == '>') {
3492 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3494 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3496 Kind = tok::greatergreaterequal;
3497 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3498 // If this is actually a '>>>>' conflict marker, recognize it as such
3499 // and recover nicely.
3501 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3502 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3504 } else if (LangOpts.CUDA && After == '>') {
3505 Kind = tok::greatergreatergreater;
3506 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3509 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3510 Kind = tok::greatergreater;
3513 Kind = tok::greater;
3517 Char = getCharAndSize(CurPtr, SizeTmp);
3519 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3520 Kind = tok::caretequal;
3521 } else if (LangOpts.OpenCL && Char == '^') {
3522 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3523 Kind = tok::caretcaret;
3529 Char = getCharAndSize(CurPtr, SizeTmp);
3531 Kind = tok::pipeequal;
3532 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3533 } else if (Char == '|') {
3534 // If this is '|||||||' and we're in a conflict marker, ignore it.
3535 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3537 Kind = tok::pipepipe;
3538 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3544 Char = getCharAndSize(CurPtr, SizeTmp);
3545 if (LangOpts.Digraphs && Char == '>') {
3546 Kind = tok::r_square; // ':>' -> ']'
3547 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3548 } else if (LangOpts.CPlusPlus && Char == ':') {
3549 Kind = tok::coloncolon;
3550 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3559 Char = getCharAndSize(CurPtr, SizeTmp);
3561 // If this is '====' and we're in a conflict marker, ignore it.
3562 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3565 Kind = tok::equalequal;
3566 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3575 Char = getCharAndSize(CurPtr, SizeTmp);
3577 Kind = tok::hashhash;
3578 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3579 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3581 if (!isLexingRawMode())
3582 Diag(BufferPtr, diag::ext_charize_microsoft);
3583 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3585 // We parsed a # character. If this occurs at the start of the line,
3586 // it's actually the start of a preprocessing directive. Callback to
3587 // the preprocessor to handle it.
3588 // TODO: -fpreprocessed mode??
3589 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3590 goto HandleDirective;
3597 // Objective C support.
3598 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3601 Kind = tok::unknown;
3604 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3606 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3607 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3608 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3609 return true; // KeepWhitespaceMode
3611 // We only saw whitespace, so just try again with this lexer.
3612 // (We manually eliminate the tail call to avoid recursion.)
3616 return LexUnicode(Result, CodePoint, CurPtr);
3619 Kind = tok::unknown;
3623 if (isASCII(Char)) {
3624 Kind = tok::unknown;
3628 llvm::UTF32 CodePoint;
3630 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3631 // an escaped newline.
3633 llvm::ConversionResult Status =
3634 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3635 (const llvm::UTF8 *)BufferEnd,
3637 llvm::strictConversion);
3638 if (Status == llvm::conversionOK) {
3639 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3640 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3641 return true; // KeepWhitespaceMode
3643 // We only saw whitespace, so just try again with this lexer.
3644 // (We manually eliminate the tail call to avoid recursion.)
3647 return LexUnicode(Result, CodePoint, CurPtr);
3650 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3651 PP->isPreprocessedOutput()) {
3653 Kind = tok::unknown;
3657 // Non-ASCII characters tend to creep into source code unintentionally.
3658 // Instead of letting the parser complain about the unknown token,
3659 // just diagnose the invalid UTF-8, then drop the character.
3660 Diag(CurPtr, diag::err_invalid_utf8);
3662 BufferPtr = CurPtr+1;
3663 // We're pretending the character didn't exist, so just try again with
3665 // (We manually eliminate the tail call to avoid recursion.)
3670 // Notify MIOpt that we read a non-whitespace/non-comment token.
3673 // Update the location of token as well as BufferPtr.
3674 FormTokenWithChars(Result, CurPtr, Kind);
3678 // We parsed a # character and it's the start of a preprocessing directive.
3680 FormTokenWithChars(Result, CurPtr, tok::hash);
3681 PP->HandleDirective(Result);
3683 if (PP->hadModuleLoaderFatalFailure()) {
3684 // With a fatal failure in the module loader, we abort parsing.
3685 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3689 // We parsed the directive; lex a token with the new state.