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 {
48 if (IdentifierInfo *II = getIdentifierInfo())
49 return II->getObjCKeywordID() == objcKey;
53 /// getObjCKeywordID - Return the ObjC keyword kind.
54 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
56 return tok::objc_not_keyword;
57 IdentifierInfo *specId = getIdentifierInfo();
58 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
61 //===----------------------------------------------------------------------===//
62 // Lexer Class Implementation
63 //===----------------------------------------------------------------------===//
65 void Lexer::anchor() { }
67 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
69 BufferStart = BufStart;
73 assert(BufEnd[0] == 0 &&
74 "We assume that the input buffer has a null character at the end"
75 " to simplify lexing!");
77 // Check whether we have a BOM in the beginning of the buffer. If yes - act
78 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
79 // skip the UTF-8 BOM if it's present.
80 if (BufferStart == BufferPtr) {
81 // Determine the size of the BOM.
82 StringRef Buf(BufferStart, BufferEnd - BufferStart);
83 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
84 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
88 BufferPtr += BOMLength;
91 Is_PragmaLexer = false;
92 CurrentConflictMarkerState = CMK_None;
94 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
96 IsAtPhysicalStartOfLine = true;
98 HasLeadingSpace = false;
99 HasLeadingEmptyMacro = false;
101 // We are not after parsing a #.
102 ParsingPreprocessorDirective = false;
104 // We are not after parsing #include.
105 ParsingFilename = false;
107 // We are not in raw mode. Raw mode disables diagnostics and interpretation
108 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
109 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
110 // or otherwise skipping over tokens.
111 LexingRawMode = false;
113 // Default to not keeping comments.
114 ExtendedTokenMode = 0;
117 /// Lexer constructor - Create a new lexer object for the specified buffer
118 /// with the specified preprocessor managing the lexing process. This lexer
119 /// assumes that the associated file buffer and Preprocessor objects will
120 /// outlive it, so it doesn't take ownership of either of them.
121 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
122 : PreprocessorLexer(&PP, FID),
123 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
124 LangOpts(PP.getLangOpts()) {
126 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
127 InputFile->getBufferEnd());
129 resetExtendedTokenMode();
132 void Lexer::resetExtendedTokenMode() {
133 assert(PP && "Cannot reset token mode without a preprocessor");
134 if (LangOpts.TraditionalCPP)
135 SetKeepWhitespaceMode(true);
137 SetCommentRetentionState(PP->getCommentRetentionState());
140 /// Lexer constructor - Create a new raw lexer object. This object is only
141 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
142 /// range will outlive it, so it doesn't take ownership of it.
143 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
144 const char *BufStart, const char *BufPtr, const char *BufEnd)
145 : FileLoc(fileloc), LangOpts(langOpts) {
147 InitLexer(BufStart, BufPtr, BufEnd);
149 // We *are* in raw mode.
150 LexingRawMode = true;
153 /// Lexer constructor - Create a new raw lexer object. This object is only
154 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
155 /// range will outlive it, so it doesn't take ownership of it.
156 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
157 const SourceManager &SM, const LangOptions &langOpts)
158 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
159 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
161 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
162 /// _Pragma expansion. This has a variety of magic semantics that this method
163 /// sets up. It returns a new'd Lexer that must be delete'd when done.
165 /// On entrance to this routine, TokStartLoc is a macro location which has a
166 /// spelling loc that indicates the bytes to be lexed for the token and an
167 /// expansion location that indicates where all lexed tokens should be
170 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
171 /// normal lexer that remaps tokens as they fly by. This would require making
172 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
173 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
174 /// out of the critical path of the lexer!
176 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
177 SourceLocation ExpansionLocStart,
178 SourceLocation ExpansionLocEnd,
179 unsigned TokLen, Preprocessor &PP) {
180 SourceManager &SM = PP.getSourceManager();
182 // Create the lexer as if we were going to lex the file normally.
183 FileID SpellingFID = SM.getFileID(SpellingLoc);
184 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
185 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
187 // Now that the lexer is created, change the start/end locations so that we
188 // just lex the subsection of the file that we want. This is lexing from a
190 const char *StrData = SM.getCharacterData(SpellingLoc);
192 L->BufferPtr = StrData;
193 L->BufferEnd = StrData+TokLen;
194 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
196 // Set the SourceLocation with the remapping information. This ensures that
197 // GetMappedTokenLoc will remap the tokens as they are lexed.
198 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
200 ExpansionLocEnd, TokLen);
202 // Ensure that the lexer thinks it is inside a directive, so that end \n will
203 // return an EOD token.
204 L->ParsingPreprocessorDirective = true;
206 // This lexer really is for _Pragma.
207 L->Is_PragmaLexer = true;
211 /// Stringify - Convert the specified string into a C string, with surrounding
212 /// ""'s, and with escaped \ and " characters.
213 std::string Lexer::Stringify(StringRef Str, bool Charify) {
214 std::string Result = Str;
215 char Quote = Charify ? '\'' : '"';
216 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
217 if (Result[i] == '\\' || Result[i] == Quote) {
218 Result.insert(Result.begin()+i, '\\');
225 /// Stringify - Convert the specified string into a C string by escaping '\'
226 /// and " characters. This does not add surrounding ""'s to the string.
227 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
228 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
229 if (Str[i] == '\\' || Str[i] == '"') {
230 Str.insert(Str.begin()+i, '\\');
236 //===----------------------------------------------------------------------===//
238 //===----------------------------------------------------------------------===//
240 /// \brief Slow case of getSpelling. Extract the characters comprising the
241 /// spelling of this token from the provided input buffer.
242 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
243 const LangOptions &LangOpts, char *Spelling) {
244 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
247 const char *BufEnd = BufPtr + Tok.getLength();
249 if (tok::isStringLiteral(Tok.getKind())) {
250 // Munch the encoding-prefix and opening double-quote.
251 while (BufPtr < BufEnd) {
253 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
256 if (Spelling[Length - 1] == '"')
260 // Raw string literals need special handling; trigraph expansion and line
261 // splicing do not occur within their d-char-sequence nor within their
264 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
265 // Search backwards from the end of the token to find the matching closing
267 const char *RawEnd = BufEnd;
268 do --RawEnd; while (*RawEnd != '"');
269 size_t RawLength = RawEnd - BufPtr + 1;
271 // Everything between the quotes is included verbatim in the spelling.
272 memcpy(Spelling + Length, BufPtr, RawLength);
276 // The rest of the token is lexed normally.
280 while (BufPtr < BufEnd) {
282 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
286 assert(Length < Tok.getLength() &&
287 "NeedsCleaning flag set on token that didn't need cleaning!");
291 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
292 /// token are the characters used to represent the token in the source file
293 /// after trigraph expansion and escaped-newline folding. In particular, this
294 /// wants to get the true, uncanonicalized, spelling of things like digraphs
296 StringRef Lexer::getSpelling(SourceLocation loc,
297 SmallVectorImpl<char> &buffer,
298 const SourceManager &SM,
299 const LangOptions &options,
301 // Break down the source location.
302 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
304 // Try to the load the file buffer.
305 bool invalidTemp = false;
306 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
308 if (invalid) *invalid = true;
312 const char *tokenBegin = file.data() + locInfo.second;
314 // Lex from the start of the given location.
315 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
316 file.begin(), tokenBegin, file.end());
318 lexer.LexFromRawLexer(token);
320 unsigned length = token.getLength();
322 // Common case: no need for cleaning.
323 if (!token.needsCleaning())
324 return StringRef(tokenBegin, length);
326 // Hard case, we need to relex the characters into the string.
327 buffer.resize(length);
328 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
329 return StringRef(buffer.data(), buffer.size());
332 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
333 /// token are the characters used to represent the token in the source file
334 /// after trigraph expansion and escaped-newline folding. In particular, this
335 /// wants to get the true, uncanonicalized, spelling of things like digraphs
337 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
338 const LangOptions &LangOpts, bool *Invalid) {
339 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
341 bool CharDataInvalid = false;
342 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
345 *Invalid = CharDataInvalid;
347 return std::string();
349 // If this token contains nothing interesting, return it directly.
350 if (!Tok.needsCleaning())
351 return std::string(TokStart, TokStart + Tok.getLength());
354 Result.resize(Tok.getLength());
355 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
359 /// getSpelling - This method is used to get the spelling of a token into a
360 /// preallocated buffer, instead of as an std::string. The caller is required
361 /// to allocate enough space for the token, which is guaranteed to be at least
362 /// Tok.getLength() bytes long. The actual length of the token is returned.
364 /// Note that this method may do two possible things: it may either fill in
365 /// the buffer specified with characters, or it may *change the input pointer*
366 /// to point to a constant buffer with the data already in it (avoiding a
367 /// copy). The caller is not allowed to modify the returned buffer pointer
368 /// if an internal buffer is returned.
369 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
370 const SourceManager &SourceMgr,
371 const LangOptions &LangOpts, bool *Invalid) {
372 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
374 const char *TokStart = nullptr;
375 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
376 if (Tok.is(tok::raw_identifier))
377 TokStart = Tok.getRawIdentifier().data();
378 else if (!Tok.hasUCN()) {
379 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
380 // Just return the string from the identifier table, which is very quick.
381 Buffer = II->getNameStart();
382 return II->getLength();
386 // NOTE: this can be checked even after testing for an IdentifierInfo.
388 TokStart = Tok.getLiteralData();
391 // Compute the start of the token in the input lexer buffer.
392 bool CharDataInvalid = false;
393 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
395 *Invalid = CharDataInvalid;
396 if (CharDataInvalid) {
402 // If this token contains nothing interesting, return it directly.
403 if (!Tok.needsCleaning()) {
405 return Tok.getLength();
408 // Otherwise, hard case, relex the characters into the string.
409 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
412 /// MeasureTokenLength - Relex the token at the specified location and return
413 /// its length in bytes in the input file. If the token needs cleaning (e.g.
414 /// includes a trigraph or an escaped newline) then this count includes bytes
415 /// that are part of that.
416 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
417 const SourceManager &SM,
418 const LangOptions &LangOpts) {
420 if (getRawToken(Loc, TheTok, SM, LangOpts))
422 return TheTok.getLength();
425 /// \brief Relex the token at the specified location.
426 /// \returns true if there was a failure, false on success.
427 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
428 const SourceManager &SM,
429 const LangOptions &LangOpts,
430 bool IgnoreWhiteSpace) {
431 // TODO: this could be special cased for common tokens like identifiers, ')',
432 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
433 // all obviously single-char tokens. This could use
434 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
437 // If this comes from a macro expansion, we really do want the macro name, not
438 // the token this macro expanded to.
439 Loc = SM.getExpansionLoc(Loc);
440 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
441 bool Invalid = false;
442 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
446 const char *StrData = Buffer.data()+LocInfo.second;
448 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
451 // Create a lexer starting at the beginning of this token.
452 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
453 Buffer.begin(), StrData, Buffer.end());
454 TheLexer.SetCommentRetentionState(true);
455 TheLexer.LexFromRawLexer(Result);
459 /// Returns the pointer that points to the beginning of line that contains
460 /// the given offset, or null if the offset if invalid.
461 static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
462 const char *BufStart = Buffer.data();
463 if (Offset >= Buffer.size())
465 const char *StrData = BufStart + Offset;
467 if (StrData[0] == '\n' || StrData[0] == '\r')
470 const char *LexStart = StrData;
471 while (LexStart != BufStart) {
472 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
482 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
483 const SourceManager &SM,
484 const LangOptions &LangOpts) {
485 assert(Loc.isFileID());
486 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
487 if (LocInfo.first.isInvalid())
490 bool Invalid = false;
491 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
495 // Back up from the current location until we hit the beginning of a line
496 // (or the buffer). We'll relex from that point.
497 const char *StrData = Buffer.data() + LocInfo.second;
498 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
499 if (!LexStart || LexStart == StrData)
502 // Create a lexer starting at the beginning of this token.
503 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
504 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
506 TheLexer.SetCommentRetentionState(true);
508 // Lex tokens until we find the token that contains the source location.
511 TheLexer.LexFromRawLexer(TheTok);
513 if (TheLexer.getBufferLocation() > StrData) {
514 // Lexing this token has taken the lexer past the source location we're
515 // looking for. If the current token encompasses our source location,
516 // return the beginning of that token.
517 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
518 return TheTok.getLocation();
520 // We ended up skipping over the source location entirely, which means
521 // that it points into whitespace. We're done here.
524 } while (TheTok.getKind() != tok::eof);
526 // We've passed our source location; just return the original source location.
530 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
531 const SourceManager &SM,
532 const LangOptions &LangOpts) {
534 return getBeginningOfFileToken(Loc, SM, LangOpts);
536 if (!SM.isMacroArgExpansion(Loc))
539 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
540 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
541 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
542 std::pair<FileID, unsigned> BeginFileLocInfo
543 = SM.getDecomposedLoc(BeginFileLoc);
544 assert(FileLocInfo.first == BeginFileLocInfo.first &&
545 FileLocInfo.second >= BeginFileLocInfo.second);
546 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
551 enum PreambleDirectiveKind {
558 } // end anonymous namespace
560 std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
561 const LangOptions &LangOpts,
563 // Create a lexer starting at the beginning of the file. Note that we use a
564 // "fake" file source location at offset 1 so that the lexer will track our
565 // position within the file.
566 const unsigned StartOffset = 1;
567 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
568 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
570 TheLexer.SetCommentRetentionState(true);
572 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
573 SourceLocation StartLoc = TheLexer.getSourceLocation();
575 bool InPreprocessorDirective = false;
578 unsigned IfCount = 0;
579 SourceLocation ActiveCommentLoc;
581 unsigned MaxLineOffset = 0;
583 const char *CurPtr = Buffer.begin();
584 unsigned CurLine = 0;
585 while (CurPtr != Buffer.end()) {
589 if (CurLine == MaxLines)
593 if (CurPtr != Buffer.end())
594 MaxLineOffset = CurPtr - Buffer.begin();
598 TheLexer.LexFromRawLexer(TheTok);
600 if (InPreprocessorDirective) {
601 // If we've hit the end of the file, we're done.
602 if (TheTok.getKind() == tok::eof) {
606 // If we haven't hit the end of the preprocessor directive, skip this
608 if (!TheTok.isAtStartOfLine())
611 // We've passed the end of the preprocessor directive, and will look
612 // at this token again below.
613 InPreprocessorDirective = false;
616 // Keep track of the # of lines in the preamble.
617 if (TheTok.isAtStartOfLine()) {
618 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
620 // If we were asked to limit the number of lines in the preamble,
621 // and we're about to exceed that limit, we're done.
622 if (MaxLineOffset && TokOffset >= MaxLineOffset)
626 // Comments are okay; skip over them.
627 if (TheTok.getKind() == tok::comment) {
628 if (ActiveCommentLoc.isInvalid())
629 ActiveCommentLoc = TheTok.getLocation();
633 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
634 // This is the start of a preprocessor directive.
635 Token HashTok = TheTok;
636 InPreprocessorDirective = true;
637 ActiveCommentLoc = SourceLocation();
639 // Figure out which directive this is. Since we're lexing raw tokens,
640 // we don't have an identifier table available. Instead, just look at
641 // the raw identifier to recognize and categorize preprocessor directives.
642 TheLexer.LexFromRawLexer(TheTok);
643 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
644 StringRef Keyword = TheTok.getRawIdentifier();
645 PreambleDirectiveKind PDK
646 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
647 .Case("include", PDK_Skipped)
648 .Case("__include_macros", PDK_Skipped)
649 .Case("define", PDK_Skipped)
650 .Case("undef", PDK_Skipped)
651 .Case("line", PDK_Skipped)
652 .Case("error", PDK_Skipped)
653 .Case("pragma", PDK_Skipped)
654 .Case("import", PDK_Skipped)
655 .Case("include_next", PDK_Skipped)
656 .Case("warning", PDK_Skipped)
657 .Case("ident", PDK_Skipped)
658 .Case("sccs", PDK_Skipped)
659 .Case("assert", PDK_Skipped)
660 .Case("unassert", PDK_Skipped)
661 .Case("if", PDK_StartIf)
662 .Case("ifdef", PDK_StartIf)
663 .Case("ifndef", PDK_StartIf)
664 .Case("elif", PDK_Skipped)
665 .Case("else", PDK_Skipped)
666 .Case("endif", PDK_EndIf)
667 .Default(PDK_Unknown);
675 IfStartTok = HashTok;
681 // Mismatched #endif. The preamble ends here.
689 // We don't know what this directive is; stop at the '#'.
694 // We only end up here if we didn't recognize the preprocessor
695 // directive or it was one that can't occur in the preamble at this
696 // point. Roll back the current token to the location of the '#'.
697 InPreprocessorDirective = false;
701 // We hit a token that we don't recognize as being in the
702 // "preprocessing only" part of the file, so we're no longer in
709 End = IfStartTok.getLocation();
710 else if (ActiveCommentLoc.isValid())
711 End = ActiveCommentLoc; // don't truncate a decl comment.
713 End = TheTok.getLocation();
715 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
716 IfCount? IfStartTok.isAtStartOfLine()
717 : TheTok.isAtStartOfLine());
720 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
721 /// token, return a new location that specifies a character within the token.
722 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
724 const SourceManager &SM,
725 const LangOptions &LangOpts) {
726 // Figure out how many physical characters away the specified expansion
727 // character is. This needs to take into consideration newlines and
729 bool Invalid = false;
730 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
732 // If they request the first char of the token, we're trivially done.
733 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
736 unsigned PhysOffset = 0;
738 // The usual case is that tokens don't contain anything interesting. Skip
739 // over the uninteresting characters. If a token only consists of simple
740 // chars, this method is extremely fast.
741 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
743 return TokStart.getLocWithOffset(PhysOffset);
749 // If we have a character that may be a trigraph or escaped newline, use a
750 // lexer to parse it correctly.
751 for (; CharNo; --CharNo) {
753 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
758 // Final detail: if we end up on an escaped newline, we want to return the
759 // location of the actual byte of the token. For example foo\<newline>bar
760 // advanced by 3 should return the location of b, not of \\. One compounding
761 // detail of this is that the escape may be made by a trigraph.
762 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
763 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
765 return TokStart.getLocWithOffset(PhysOffset);
768 /// \brief Computes the source location just past the end of the
769 /// token at this source location.
771 /// This routine can be used to produce a source location that
772 /// points just past the end of the token referenced by \p Loc, and
773 /// is generally used when a diagnostic needs to point just after a
774 /// token where it expected something different that it received. If
775 /// the returned source location would not be meaningful (e.g., if
776 /// it points into a macro), this routine returns an invalid
779 /// \param Offset an offset from the end of the token, where the source
780 /// location should refer to. The default offset (0) produces a source
781 /// location pointing just past the end of the token; an offset of 1 produces
782 /// a source location pointing to the last character in the token, etc.
783 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
784 const SourceManager &SM,
785 const LangOptions &LangOpts) {
787 return SourceLocation();
789 if (Loc.isMacroID()) {
790 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
791 return SourceLocation(); // Points inside the macro expansion.
794 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
800 return Loc.getLocWithOffset(Len);
803 /// \brief Returns true if the given MacroID location points at the first
804 /// token of the macro expansion.
805 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
806 const SourceManager &SM,
807 const LangOptions &LangOpts,
808 SourceLocation *MacroBegin) {
809 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
811 SourceLocation expansionLoc;
812 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
815 if (expansionLoc.isFileID()) {
816 // No other macro expansions, this is the first.
818 *MacroBegin = expansionLoc;
822 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
825 /// \brief Returns true if the given MacroID location points at the last
826 /// token of the macro expansion.
827 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
828 const SourceManager &SM,
829 const LangOptions &LangOpts,
830 SourceLocation *MacroEnd) {
831 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
833 SourceLocation spellLoc = SM.getSpellingLoc(loc);
834 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
838 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
839 SourceLocation expansionLoc;
840 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
843 if (expansionLoc.isFileID()) {
844 // No other macro expansions.
846 *MacroEnd = expansionLoc;
850 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
853 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
854 const SourceManager &SM,
855 const LangOptions &LangOpts) {
856 SourceLocation Begin = Range.getBegin();
857 SourceLocation End = Range.getEnd();
858 assert(Begin.isFileID() && End.isFileID());
859 if (Range.isTokenRange()) {
860 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
862 return CharSourceRange();
865 // Break down the source locations.
868 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
870 return CharSourceRange();
873 if (!SM.isInFileID(End, FID, &EndOffs) ||
875 return CharSourceRange();
877 return CharSourceRange::getCharRange(Begin, End);
880 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
881 const SourceManager &SM,
882 const LangOptions &LangOpts) {
883 SourceLocation Begin = Range.getBegin();
884 SourceLocation End = Range.getEnd();
885 if (Begin.isInvalid() || End.isInvalid())
886 return CharSourceRange();
888 if (Begin.isFileID() && End.isFileID())
889 return makeRangeFromFileLocs(Range, SM, LangOpts);
891 if (Begin.isMacroID() && End.isFileID()) {
892 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
893 return CharSourceRange();
894 Range.setBegin(Begin);
895 return makeRangeFromFileLocs(Range, SM, LangOpts);
898 if (Begin.isFileID() && End.isMacroID()) {
899 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
901 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
903 return CharSourceRange();
905 return makeRangeFromFileLocs(Range, SM, LangOpts);
908 assert(Begin.isMacroID() && End.isMacroID());
909 SourceLocation MacroBegin, MacroEnd;
910 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
911 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
913 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
915 Range.setBegin(MacroBegin);
916 Range.setEnd(MacroEnd);
917 return makeRangeFromFileLocs(Range, SM, LangOpts);
920 bool Invalid = false;
921 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
924 return CharSourceRange();
926 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
927 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
930 return CharSourceRange();
932 if (EndEntry.getExpansion().isMacroArgExpansion() &&
933 BeginEntry.getExpansion().getExpansionLocStart() ==
934 EndEntry.getExpansion().getExpansionLocStart()) {
935 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
936 Range.setEnd(SM.getImmediateSpellingLoc(End));
937 return makeFileCharRange(Range, SM, LangOpts);
941 return CharSourceRange();
944 StringRef Lexer::getSourceText(CharSourceRange Range,
945 const SourceManager &SM,
946 const LangOptions &LangOpts,
948 Range = makeFileCharRange(Range, SM, LangOpts);
949 if (Range.isInvalid()) {
950 if (Invalid) *Invalid = true;
954 // Break down the source location.
955 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
956 if (beginInfo.first.isInvalid()) {
957 if (Invalid) *Invalid = true;
962 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
963 beginInfo.second > EndOffs) {
964 if (Invalid) *Invalid = true;
968 // Try to the load the file buffer.
969 bool invalidTemp = false;
970 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
972 if (Invalid) *Invalid = true;
976 if (Invalid) *Invalid = false;
977 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
980 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
981 const SourceManager &SM,
982 const LangOptions &LangOpts) {
983 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
985 // Find the location of the immediate macro expansion.
987 FileID FID = SM.getFileID(Loc);
988 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
989 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
990 Loc = Expansion.getExpansionLocStart();
991 if (!Expansion.isMacroArgExpansion())
994 // For macro arguments we need to check that the argument did not come
995 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
997 // Loc points to the argument id of the macro definition, move to the
999 Loc = SM.getImmediateExpansionRange(Loc).first;
1000 SourceLocation SpellLoc = Expansion.getSpellingLoc();
1001 if (SpellLoc.isFileID())
1002 break; // No inner macro.
1004 // If spelling location resides in the same FileID as macro expansion
1005 // location, it means there is no inner macro.
1006 FileID MacroFID = SM.getFileID(Loc);
1007 if (SM.isInFileID(SpellLoc, MacroFID))
1010 // Argument came from inner macro.
1014 // Find the spelling location of the start of the non-argument expansion
1015 // range. This is where the macro name was spelled in order to begin
1016 // expanding this macro.
1017 Loc = SM.getSpellingLoc(Loc);
1019 // Dig out the buffer where the macro name was spelled and the extents of the
1020 // name so that we can render it into the expansion note.
1021 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1022 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1023 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1024 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1027 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1028 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1029 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1030 // Walk past macro argument expanions.
1031 while (SM.isMacroArgExpansion(Loc))
1032 Loc = SM.getImmediateExpansionRange(Loc).first;
1034 // If the macro's spelling has no FileID, then it's actually a token paste
1035 // or stringization (or similar) and not a macro at all.
1036 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1039 // Find the spelling location of the start of the non-argument expansion
1040 // range. This is where the macro name was spelled in order to begin
1041 // expanding this macro.
1042 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1044 // Dig out the buffer where the macro name was spelled and the extents of the
1045 // name so that we can render it into the expansion note.
1046 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1047 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1048 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1049 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1052 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1053 return isIdentifierBody(c, LangOpts.DollarIdents);
1056 StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1057 const SourceManager &SM) {
1058 if (Loc.isInvalid() || Loc.isMacroID())
1060 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1061 if (LocInfo.first.isInvalid())
1063 bool Invalid = false;
1064 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1067 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1070 StringRef Rest = Buffer.substr(Line - Buffer.data());
1071 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1072 return NumWhitespaceChars == StringRef::npos
1074 : Rest.take_front(NumWhitespaceChars);
1077 //===----------------------------------------------------------------------===//
1078 // Diagnostics forwarding code.
1079 //===----------------------------------------------------------------------===//
1081 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1082 /// lexer buffer was all expanded at a single point, perform the mapping.
1083 /// This is currently only used for _Pragma implementation, so it is the slow
1084 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1085 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1086 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1087 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1088 SourceLocation FileLoc,
1089 unsigned CharNo, unsigned TokLen) {
1090 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1092 // Otherwise, we're lexing "mapped tokens". This is used for things like
1093 // _Pragma handling. Combine the expansion location of FileLoc with the
1094 // spelling location.
1095 SourceManager &SM = PP.getSourceManager();
1097 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1098 // characters come from spelling(FileLoc)+Offset.
1099 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1100 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1102 // Figure out the expansion loc range, which is the range covered by the
1103 // original _Pragma(...) sequence.
1104 std::pair<SourceLocation,SourceLocation> II =
1105 SM.getImmediateExpansionRange(FileLoc);
1107 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1110 /// getSourceLocation - Return a source location identifier for the specified
1111 /// offset in the current file.
1112 SourceLocation Lexer::getSourceLocation(const char *Loc,
1113 unsigned TokLen) const {
1114 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1115 "Location out of range for this buffer!");
1117 // In the normal case, we're just lexing from a simple file buffer, return
1118 // the file id from FileLoc with the offset specified.
1119 unsigned CharNo = Loc-BufferStart;
1120 if (FileLoc.isFileID())
1121 return FileLoc.getLocWithOffset(CharNo);
1123 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1124 // tokens are lexed from where the _Pragma was defined.
1125 assert(PP && "This doesn't work on raw lexers");
1126 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1129 /// Diag - Forwarding function for diagnostics. This translate a source
1130 /// position in the current buffer into a SourceLocation object for rendering.
1131 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1132 return PP->Diag(getSourceLocation(Loc), DiagID);
1135 //===----------------------------------------------------------------------===//
1136 // Trigraph and Escaped Newline Handling Code.
1137 //===----------------------------------------------------------------------===//
1139 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1140 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1141 static char GetTrigraphCharForLetter(char Letter) {
1144 case '=': return '#';
1145 case ')': return ']';
1146 case '(': return '[';
1147 case '!': return '|';
1148 case '\'': return '^';
1149 case '>': return '}';
1150 case '/': return '\\';
1151 case '<': return '{';
1152 case '-': return '~';
1156 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1157 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1158 /// return the result character. Finally, emit a warning about trigraph use
1159 /// whether trigraphs are enabled or not.
1160 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1161 char Res = GetTrigraphCharForLetter(*CP);
1162 if (!Res || !L) return Res;
1164 if (!L->getLangOpts().Trigraphs) {
1165 if (!L->isLexingRawMode())
1166 L->Diag(CP-2, diag::trigraph_ignored);
1170 if (!L->isLexingRawMode())
1171 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1175 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1176 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1177 /// trigraph equivalent on entry to this function.
1178 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1180 while (isWhitespace(Ptr[Size])) {
1183 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1186 // If this is a \r\n or \n\r, skip the other half.
1187 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1188 Ptr[Size-1] != Ptr[Size])
1194 // Not an escaped newline, must be a \t or something else.
1198 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1199 /// them), skip over them and return the first non-escaped-newline found,
1200 /// otherwise return P.
1201 const char *Lexer::SkipEscapedNewLines(const char *P) {
1203 const char *AfterEscape;
1206 } else if (*P == '?') {
1207 // If not a trigraph for escape, bail out.
1208 if (P[1] != '?' || P[2] != '/')
1210 // FIXME: Take LangOpts into account; the language might not
1211 // support trigraphs.
1217 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1218 if (NewLineSize == 0) return P;
1219 P = AfterEscape+NewLineSize;
1223 /// \brief Checks that the given token is the first token that occurs after the
1224 /// given location (this excludes comments and whitespace). Returns the location
1225 /// immediately after the specified token. If the token is not found or the
1226 /// location is inside a macro, the returned source location will be invalid.
1227 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1228 tok::TokenKind TKind,
1229 const SourceManager &SM,
1230 const LangOptions &LangOpts,
1231 bool SkipTrailingWhitespaceAndNewLine) {
1232 if (Loc.isMacroID()) {
1233 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1234 return SourceLocation();
1236 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1238 // Break down the source location.
1239 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1241 // Try to load the file buffer.
1242 bool InvalidTemp = false;
1243 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1245 return SourceLocation();
1247 const char *TokenBegin = File.data() + LocInfo.second;
1249 // Lex from the start of the given location.
1250 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1251 TokenBegin, File.end());
1254 lexer.LexFromRawLexer(Tok);
1255 if (Tok.isNot(TKind))
1256 return SourceLocation();
1257 SourceLocation TokenLoc = Tok.getLocation();
1259 // Calculate how much whitespace needs to be skipped if any.
1260 unsigned NumWhitespaceChars = 0;
1261 if (SkipTrailingWhitespaceAndNewLine) {
1262 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1264 unsigned char C = *TokenEnd;
1265 while (isHorizontalWhitespace(C)) {
1267 NumWhitespaceChars++;
1270 // Skip \r, \n, \r\n, or \n\r
1271 if (C == '\n' || C == '\r') {
1274 NumWhitespaceChars++;
1275 if ((C == '\n' || C == '\r') && C != PrevC)
1276 NumWhitespaceChars++;
1280 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1283 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1284 /// get its size, and return it. This is tricky in several cases:
1285 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1286 /// then either return the trigraph (skipping 3 chars) or the '?',
1287 /// depending on whether trigraphs are enabled or not.
1288 /// 2. If this is an escaped newline (potentially with whitespace between
1289 /// the backslash and newline), implicitly skip the newline and return
1290 /// the char after it.
1292 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1293 /// know that we can accumulate into Size, and that we have already incremented
1294 /// Ptr by Size bytes.
1296 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1297 /// be updated to match.
1299 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1301 // If we have a slash, look for an escaped newline.
1302 if (Ptr[0] == '\\') {
1306 // Common case, backslash-char where the char is not whitespace.
1307 if (!isWhitespace(Ptr[0])) return '\\';
1309 // See if we have optional whitespace characters between the slash and
1311 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1312 // Remember that this token needs to be cleaned.
1313 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1315 // Warn if there was whitespace between the backslash and newline.
1316 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1317 Diag(Ptr, diag::backslash_newline_space);
1319 // Found backslash<whitespace><newline>. Parse the char after it.
1320 Size += EscapedNewLineSize;
1321 Ptr += EscapedNewLineSize;
1323 // Use slow version to accumulate a correct size field.
1324 return getCharAndSizeSlow(Ptr, Size, Tok);
1327 // Otherwise, this is not an escaped newline, just return the slash.
1331 // If this is a trigraph, process it.
1332 if (Ptr[0] == '?' && Ptr[1] == '?') {
1333 // If this is actually a legal trigraph (not something like "??x"), emit
1334 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1335 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1336 // Remember that this token needs to be cleaned.
1337 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1341 if (C == '\\') goto Slash;
1346 // If this is neither, return a single character.
1351 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1352 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1353 /// and that we have already incremented Ptr by Size bytes.
1355 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1356 /// be updated to match.
1357 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1358 const LangOptions &LangOpts) {
1359 // If we have a slash, look for an escaped newline.
1360 if (Ptr[0] == '\\') {
1364 // Common case, backslash-char where the char is not whitespace.
1365 if (!isWhitespace(Ptr[0])) return '\\';
1367 // See if we have optional whitespace characters followed by a newline.
1368 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1369 // Found backslash<whitespace><newline>. Parse the char after it.
1370 Size += EscapedNewLineSize;
1371 Ptr += EscapedNewLineSize;
1373 // Use slow version to accumulate a correct size field.
1374 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1377 // Otherwise, this is not an escaped newline, just return the slash.
1381 // If this is a trigraph, process it.
1382 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1383 // If this is actually a legal trigraph (not something like "??x"), return
1385 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1388 if (C == '\\') goto Slash;
1393 // If this is neither, return a single character.
1398 //===----------------------------------------------------------------------===//
1399 // Helper methods for lexing.
1400 //===----------------------------------------------------------------------===//
1402 /// \brief Routine that indiscriminately skips bytes in the source file.
1403 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1405 if (BufferPtr > BufferEnd)
1406 BufferPtr = BufferEnd;
1407 // FIXME: What exactly does the StartOfLine bit mean? There are two
1408 // possible meanings for the "start" of the line: the first token on the
1409 // unexpanded line, or the first token on the expanded line.
1410 IsAtStartOfLine = StartOfLine;
1411 IsAtPhysicalStartOfLine = StartOfLine;
1414 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1415 if (LangOpts.AsmPreprocessor) {
1417 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1418 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1419 C11AllowedIDCharRanges);
1420 return C11AllowedIDChars.contains(C);
1421 } else if (LangOpts.CPlusPlus) {
1422 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1423 CXX03AllowedIDCharRanges);
1424 return CXX03AllowedIDChars.contains(C);
1426 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1427 C99AllowedIDCharRanges);
1428 return C99AllowedIDChars.contains(C);
1432 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1433 assert(isAllowedIDChar(C, LangOpts));
1434 if (LangOpts.AsmPreprocessor) {
1436 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1437 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1438 C11DisallowedInitialIDCharRanges);
1439 return !C11DisallowedInitialIDChars.contains(C);
1440 } else if (LangOpts.CPlusPlus) {
1443 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1444 C99DisallowedInitialIDCharRanges);
1445 return !C99DisallowedInitialIDChars.contains(C);
1449 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1451 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1452 L.getSourceLocation(End));
1455 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1456 CharSourceRange Range, bool IsFirst) {
1457 // Check C99 compatibility.
1458 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1460 CannotAppearInIdentifier = 0,
1461 CannotStartIdentifier
1464 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1465 C99AllowedIDCharRanges);
1466 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1467 C99DisallowedInitialIDCharRanges);
1468 if (!C99AllowedIDChars.contains(C)) {
1469 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1471 << CannotAppearInIdentifier;
1472 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1473 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1475 << CannotStartIdentifier;
1479 // Check C++98 compatibility.
1480 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1481 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1482 CXX03AllowedIDCharRanges);
1483 if (!CXX03AllowedIDChars.contains(C)) {
1484 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1490 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1492 const char *UCNPtr = CurPtr + Size;
1493 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1494 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1497 if (!isLexingRawMode())
1498 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1499 makeCharRange(*this, CurPtr, UCNPtr),
1502 Result.setFlag(Token::HasUCN);
1503 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1504 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1507 while (CurPtr != UCNPtr)
1508 (void)getAndAdvanceChar(CurPtr, Result);
1512 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1513 const char *UnicodePtr = CurPtr;
1514 llvm::UTF32 CodePoint;
1515 llvm::ConversionResult Result =
1516 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1517 (const llvm::UTF8 *)BufferEnd,
1519 llvm::strictConversion);
1520 if (Result != llvm::conversionOK ||
1521 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1524 if (!isLexingRawMode())
1525 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1526 makeCharRange(*this, CurPtr, UnicodePtr),
1529 CurPtr = UnicodePtr;
1533 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1534 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1536 unsigned char C = *CurPtr++;
1537 while (isIdentifierBody(C))
1540 --CurPtr; // Back up over the skipped character.
1542 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1543 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1545 // TODO: Could merge these checks into an InfoTable flag to make the
1546 // comparison cheaper
1547 if (isASCII(C) && C != '\\' && C != '?' &&
1548 (C != '$' || !LangOpts.DollarIdents)) {
1550 const char *IdStart = BufferPtr;
1551 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1552 Result.setRawIdentifierData(IdStart);
1554 // If we are in raw mode, return this identifier raw. There is no need to
1555 // look up identifier information or attempt to macro expand it.
1559 // Fill in Result.IdentifierInfo and update the token kind,
1560 // looking up the identifier in the identifier table.
1561 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1563 // Finally, now that we know we have an identifier, pass this off to the
1564 // preprocessor, which may macro expand it or something.
1565 if (II->isHandleIdentifierCase())
1566 return PP->HandleIdentifier(Result);
1568 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1569 && II->getPPKeywordID() == tok::pp_not_keyword
1570 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1571 // Return the code-completion token.
1572 Result.setKind(tok::code_completion);
1579 // Otherwise, $,\,? in identifier found. Enter slower path.
1581 C = getCharAndSize(CurPtr, Size);
1584 // If we hit a $ and they are not supported in identifiers, we are done.
1585 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1587 // Otherwise, emit a diagnostic and continue.
1588 if (!isLexingRawMode())
1589 Diag(CurPtr, diag::ext_dollar_in_identifier);
1590 CurPtr = ConsumeChar(CurPtr, Size, Result);
1591 C = getCharAndSize(CurPtr, Size);
1594 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1595 C = getCharAndSize(CurPtr, Size);
1597 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1598 C = getCharAndSize(CurPtr, Size);
1600 } else if (!isIdentifierBody(C)) {
1601 goto FinishIdentifier;
1604 // Otherwise, this character is good, consume it.
1605 CurPtr = ConsumeChar(CurPtr, Size, Result);
1607 C = getCharAndSize(CurPtr, Size);
1608 while (isIdentifierBody(C)) {
1609 CurPtr = ConsumeChar(CurPtr, Size, Result);
1610 C = getCharAndSize(CurPtr, Size);
1615 /// isHexaLiteral - Return true if Start points to a hex constant.
1616 /// in microsoft mode (where this is supposed to be several different tokens).
1617 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1619 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1622 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1623 return (C2 == 'x' || C2 == 'X');
1626 /// LexNumericConstant - Lex the remainder of a integer or floating point
1627 /// constant. From[-1] is the first character lexed. Return the end of the
1629 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1631 char C = getCharAndSize(CurPtr, Size);
1633 while (isPreprocessingNumberBody(C)) {
1634 CurPtr = ConsumeChar(CurPtr, Size, Result);
1636 C = getCharAndSize(CurPtr, Size);
1639 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1640 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1641 // If we are in Microsoft mode, don't continue if the constant is hex.
1642 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1643 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1644 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1647 // If we have a hex FP constant, continue.
1648 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1649 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1650 // not-quite-conforming extension. Only do so if this looks like it's
1651 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1652 bool IsHexFloat = true;
1653 if (!LangOpts.C99) {
1654 if (!isHexaLiteral(BufferPtr, LangOpts))
1656 else if (!getLangOpts().CPlusPlus1z &&
1657 std::find(BufferPtr, CurPtr, '_') != CurPtr)
1661 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1664 // If we have a digit separator, continue.
1665 if (C == '\'' && getLangOpts().CPlusPlus14) {
1667 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1668 if (isIdentifierBody(Next)) {
1669 if (!isLexingRawMode())
1670 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1671 CurPtr = ConsumeChar(CurPtr, Size, Result);
1672 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1673 return LexNumericConstant(Result, CurPtr);
1677 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1678 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1679 return LexNumericConstant(Result, CurPtr);
1680 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1681 return LexNumericConstant(Result, CurPtr);
1683 // Update the location of token as well as BufferPtr.
1684 const char *TokStart = BufferPtr;
1685 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1686 Result.setLiteralData(TokStart);
1690 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1691 /// in C++11, or warn on a ud-suffix in C++98.
1692 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1693 bool IsStringLiteral) {
1694 assert(getLangOpts().CPlusPlus);
1696 // Maximally munch an identifier.
1698 char C = getCharAndSize(CurPtr, Size);
1699 bool Consumed = false;
1701 if (!isIdentifierHead(C)) {
1702 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1704 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1710 if (!getLangOpts().CPlusPlus11) {
1711 if (!isLexingRawMode())
1713 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1714 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1715 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1719 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1720 // that does not start with an underscore is ill-formed. As a conforming
1721 // extension, we treat all such suffixes as if they had whitespace before
1722 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1723 // likely to be a ud-suffix than a macro, however, and accept that.
1725 bool IsUDSuffix = false;
1728 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1729 // In C++1y, we need to look ahead a few characters to see if this is a
1730 // valid suffix for a string literal or a numeric literal (this could be
1731 // the 'operator""if' defining a numeric literal operator).
1732 const unsigned MaxStandardSuffixLength = 3;
1733 char Buffer[MaxStandardSuffixLength] = { C };
1734 unsigned Consumed = Size;
1738 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1740 if (!isIdentifierBody(Next)) {
1741 // End of suffix. Check whether this is on the whitelist.
1742 const StringRef CompleteSuffix(Buffer, Chars);
1743 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1748 if (Chars == MaxStandardSuffixLength)
1749 // Too long: can't be a standard suffix.
1752 Buffer[Chars++] = Next;
1753 Consumed += NextSize;
1758 if (!isLexingRawMode())
1759 Diag(CurPtr, getLangOpts().MSVCCompat
1760 ? diag::ext_ms_reserved_user_defined_literal
1761 : diag::ext_reserved_user_defined_literal)
1762 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1766 CurPtr = ConsumeChar(CurPtr, Size, Result);
1769 Result.setFlag(Token::HasUDSuffix);
1771 C = getCharAndSize(CurPtr, Size);
1772 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1773 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1774 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1781 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1782 /// either " or L" or u8" or u" or U".
1783 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1784 tok::TokenKind Kind) {
1785 // Does this string contain the \0 character?
1786 const char *NulCharacter = nullptr;
1788 if (!isLexingRawMode() &&
1789 (Kind == tok::utf8_string_literal ||
1790 Kind == tok::utf16_string_literal ||
1791 Kind == tok::utf32_string_literal))
1792 Diag(BufferPtr, getLangOpts().CPlusPlus
1793 ? diag::warn_cxx98_compat_unicode_literal
1794 : diag::warn_c99_compat_unicode_literal);
1796 char C = getAndAdvanceChar(CurPtr, Result);
1798 // Skip escaped characters. Escaped newlines will already be processed by
1799 // getAndAdvanceChar.
1801 C = getAndAdvanceChar(CurPtr, Result);
1803 if (C == '\n' || C == '\r' || // Newline.
1804 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1805 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1806 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1807 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1812 if (isCodeCompletionPoint(CurPtr-1)) {
1813 PP->CodeCompleteNaturalLanguage();
1814 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1819 NulCharacter = CurPtr-1;
1821 C = getAndAdvanceChar(CurPtr, Result);
1824 // If we are in C++11, lex the optional ud-suffix.
1825 if (getLangOpts().CPlusPlus)
1826 CurPtr = LexUDSuffix(Result, CurPtr, true);
1828 // If a nul character existed in the string, warn about it.
1829 if (NulCharacter && !isLexingRawMode())
1830 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1832 // Update the location of the token as well as the BufferPtr instance var.
1833 const char *TokStart = BufferPtr;
1834 FormTokenWithChars(Result, CurPtr, Kind);
1835 Result.setLiteralData(TokStart);
1839 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1840 /// having lexed R", LR", u8R", uR", or UR".
1841 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1842 tok::TokenKind Kind) {
1843 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1844 // Between the initial and final double quote characters of the raw string,
1845 // any transformations performed in phases 1 and 2 (trigraphs,
1846 // universal-character-names, and line splicing) are reverted.
1848 if (!isLexingRawMode())
1849 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1851 unsigned PrefixLen = 0;
1853 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1856 // If the last character was not a '(', then we didn't lex a valid delimiter.
1857 if (CurPtr[PrefixLen] != '(') {
1858 if (!isLexingRawMode()) {
1859 const char *PrefixEnd = &CurPtr[PrefixLen];
1860 if (PrefixLen == 16) {
1861 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1863 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1864 << StringRef(PrefixEnd, 1);
1868 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1869 // it's possible the '"' was intended to be part of the raw string, but
1870 // there's not much we can do about that.
1876 if (C == 0 && CurPtr-1 == BufferEnd) {
1882 FormTokenWithChars(Result, CurPtr, tok::unknown);
1886 // Save prefix and move CurPtr past it
1887 const char *Prefix = CurPtr;
1888 CurPtr += PrefixLen + 1; // skip over prefix and '('
1894 // Check for prefix match and closing quote.
1895 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1896 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1899 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1900 if (!isLexingRawMode())
1901 Diag(BufferPtr, diag::err_unterminated_raw_string)
1902 << StringRef(Prefix, PrefixLen);
1903 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1908 // If we are in C++11, lex the optional ud-suffix.
1909 if (getLangOpts().CPlusPlus)
1910 CurPtr = LexUDSuffix(Result, CurPtr, true);
1912 // Update the location of token as well as BufferPtr.
1913 const char *TokStart = BufferPtr;
1914 FormTokenWithChars(Result, CurPtr, Kind);
1915 Result.setLiteralData(TokStart);
1919 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1920 /// after having lexed the '<' character. This is used for #include filenames.
1921 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1922 // Does this string contain the \0 character?
1923 const char *NulCharacter = nullptr;
1924 const char *AfterLessPos = CurPtr;
1925 char C = getAndAdvanceChar(CurPtr, Result);
1927 // Skip escaped characters.
1928 if (C == '\\' && CurPtr < BufferEnd) {
1929 // Skip the escaped character.
1930 getAndAdvanceChar(CurPtr, Result);
1931 } else if (C == '\n' || C == '\r' || // Newline.
1932 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1933 isCodeCompletionPoint(CurPtr-1)))) {
1934 // If the filename is unterminated, then it must just be a lone <
1935 // character. Return this as such.
1936 FormTokenWithChars(Result, AfterLessPos, tok::less);
1938 } else if (C == 0) {
1939 NulCharacter = CurPtr-1;
1941 C = getAndAdvanceChar(CurPtr, Result);
1944 // If a nul character existed in the string, warn about it.
1945 if (NulCharacter && !isLexingRawMode())
1946 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1948 // Update the location of token as well as BufferPtr.
1949 const char *TokStart = BufferPtr;
1950 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1951 Result.setLiteralData(TokStart);
1955 /// LexCharConstant - Lex the remainder of a character constant, after having
1956 /// lexed either ' or L' or u8' or u' or U'.
1957 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1958 tok::TokenKind Kind) {
1959 // Does this character contain the \0 character?
1960 const char *NulCharacter = nullptr;
1962 if (!isLexingRawMode()) {
1963 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1964 Diag(BufferPtr, getLangOpts().CPlusPlus
1965 ? diag::warn_cxx98_compat_unicode_literal
1966 : diag::warn_c99_compat_unicode_literal);
1967 else if (Kind == tok::utf8_char_constant)
1968 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1971 char C = getAndAdvanceChar(CurPtr, Result);
1973 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1974 Diag(BufferPtr, diag::ext_empty_character);
1975 FormTokenWithChars(Result, CurPtr, tok::unknown);
1980 // Skip escaped characters.
1982 C = getAndAdvanceChar(CurPtr, Result);
1984 if (C == '\n' || C == '\r' || // Newline.
1985 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1986 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1987 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
1988 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1993 if (isCodeCompletionPoint(CurPtr-1)) {
1994 PP->CodeCompleteNaturalLanguage();
1995 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
2000 NulCharacter = CurPtr-1;
2002 C = getAndAdvanceChar(CurPtr, Result);
2005 // If we are in C++11, lex the optional ud-suffix.
2006 if (getLangOpts().CPlusPlus)
2007 CurPtr = LexUDSuffix(Result, CurPtr, false);
2009 // If a nul character existed in the character, warn about it.
2010 if (NulCharacter && !isLexingRawMode())
2011 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2013 // Update the location of token as well as BufferPtr.
2014 const char *TokStart = BufferPtr;
2015 FormTokenWithChars(Result, CurPtr, Kind);
2016 Result.setLiteralData(TokStart);
2020 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2021 /// Update BufferPtr to point to the next non-whitespace character and return.
2023 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2025 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2026 bool &TokAtPhysicalStartOfLine) {
2027 // Whitespace - Skip it, then return the token after the whitespace.
2028 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2030 unsigned char Char = *CurPtr;
2032 // Skip consecutive spaces efficiently.
2034 // Skip horizontal whitespace very aggressively.
2035 while (isHorizontalWhitespace(Char))
2038 // Otherwise if we have something other than whitespace, we're done.
2039 if (!isVerticalWhitespace(Char))
2042 if (ParsingPreprocessorDirective) {
2043 // End of preprocessor directive line, let LexTokenInternal handle this.
2048 // OK, but handle newline.
2053 // If the client wants us to return whitespace, return it now.
2054 if (isKeepWhitespaceMode()) {
2055 FormTokenWithChars(Result, CurPtr, tok::unknown);
2057 IsAtStartOfLine = true;
2058 IsAtPhysicalStartOfLine = true;
2060 // FIXME: The next token will not have LeadingSpace set.
2064 // If this isn't immediately after a newline, there is leading space.
2065 char PrevChar = CurPtr[-1];
2066 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2068 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2070 Result.setFlag(Token::StartOfLine);
2071 TokAtPhysicalStartOfLine = true;
2078 /// We have just read the // characters from input. Skip until we find the
2079 /// newline character thats terminate the comment. Then update BufferPtr and
2082 /// If we're in KeepCommentMode or any CommentHandler has inserted
2083 /// some tokens, this will store the first token and return true.
2084 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2085 bool &TokAtPhysicalStartOfLine) {
2086 // If Line comments aren't explicitly enabled for this language, emit an
2087 // extension warning.
2088 if (!LangOpts.LineComment && !isLexingRawMode()) {
2089 Diag(BufferPtr, diag::ext_line_comment);
2091 // Mark them enabled so we only emit one warning for this translation
2093 LangOpts.LineComment = true;
2096 // Scan over the body of the comment. The common case, when scanning, is that
2097 // the comment contains normal ascii characters with nothing interesting in
2098 // them. As such, optimize for this case with the inner loop.
2100 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2101 // character that ends the line comment.
2105 // Skip over characters in the fast loop.
2106 while (C != 0 && // Potentially EOF.
2107 C != '\n' && C != '\r') // Newline or DOS-style newline.
2110 const char *NextLine = CurPtr;
2112 // We found a newline, see if it's escaped.
2113 const char *EscapePtr = CurPtr-1;
2114 bool HasSpace = false;
2115 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2120 if (*EscapePtr == '\\')
2123 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2124 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2125 // Trigraph-escaped newline.
2126 CurPtr = EscapePtr-2;
2128 break; // This is a newline, we're done.
2130 // If there was space between the backslash and newline, warn about it.
2131 if (HasSpace && !isLexingRawMode())
2132 Diag(EscapePtr, diag::backslash_newline_space);
2135 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2136 // properly decode the character. Read it in raw mode to avoid emitting
2137 // diagnostics about things like trigraphs. If we see an escaped newline,
2138 // we'll handle it below.
2139 const char *OldPtr = CurPtr;
2140 bool OldRawMode = isLexingRawMode();
2141 LexingRawMode = true;
2142 C = getAndAdvanceChar(CurPtr, Result);
2143 LexingRawMode = OldRawMode;
2145 // If we only read only one character, then no special handling is needed.
2146 // We're done and can skip forward to the newline.
2147 if (C != 0 && CurPtr == OldPtr+1) {
2152 // If we read multiple characters, and one of those characters was a \r or
2153 // \n, then we had an escaped newline within the comment. Emit diagnostic
2154 // unless the next line is also a // comment.
2155 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2156 for (; OldPtr != CurPtr; ++OldPtr)
2157 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2158 // Okay, we found a // comment that ends in a newline, if the next
2159 // line is also a // comment, but has spaces, don't emit a diagnostic.
2160 if (isWhitespace(C)) {
2161 const char *ForwardPtr = CurPtr;
2162 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2164 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2168 if (!isLexingRawMode())
2169 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2174 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2179 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2180 PP->CodeCompleteNaturalLanguage();
2186 // Found but did not consume the newline. Notify comment handlers about the
2187 // comment unless we're in a #if 0 block.
2188 if (PP && !isLexingRawMode() &&
2189 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2190 getSourceLocation(CurPtr)))) {
2192 return true; // A token has to be returned.
2195 // If we are returning comments as tokens, return this comment as a token.
2196 if (inKeepCommentMode())
2197 return SaveLineComment(Result, CurPtr);
2199 // If we are inside a preprocessor directive and we see the end of line,
2200 // return immediately, so that the lexer can return this as an EOD token.
2201 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2206 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2207 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2208 // contribute to another token), it isn't needed for correctness. Note that
2209 // this is ok even in KeepWhitespaceMode, because we would have returned the
2210 /// comment above in that mode.
2213 // The next returned token is at the start of the line.
2214 Result.setFlag(Token::StartOfLine);
2215 TokAtPhysicalStartOfLine = true;
2216 // No leading whitespace seen so far.
2217 Result.clearFlag(Token::LeadingSpace);
2222 /// If in save-comment mode, package up this Line comment in an appropriate
2223 /// way and return it.
2224 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2225 // If we're not in a preprocessor directive, just return the // comment
2227 FormTokenWithChars(Result, CurPtr, tok::comment);
2229 if (!ParsingPreprocessorDirective || LexingRawMode)
2232 // If this Line-style comment is in a macro definition, transmogrify it into
2233 // a C-style block comment.
2234 bool Invalid = false;
2235 std::string Spelling = PP->getSpelling(Result, &Invalid);
2239 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2240 Spelling[1] = '*'; // Change prefix to "/*".
2241 Spelling += "*/"; // add suffix.
2243 Result.setKind(tok::comment);
2244 PP->CreateString(Spelling, Result,
2245 Result.getLocation(), Result.getLocation());
2249 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2250 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2251 /// a diagnostic if so. We know that the newline is inside of a block comment.
2252 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2254 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2256 // Back up off the newline.
2259 // If this is a two-character newline sequence, skip the other character.
2260 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2261 // \n\n or \r\r -> not escaped newline.
2262 if (CurPtr[0] == CurPtr[1])
2264 // \n\r or \r\n -> skip the newline.
2268 // If we have horizontal whitespace, skip over it. We allow whitespace
2269 // between the slash and newline.
2270 bool HasSpace = false;
2271 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2276 // If we have a slash, we know this is an escaped newline.
2277 if (*CurPtr == '\\') {
2278 if (CurPtr[-1] != '*') return false;
2280 // It isn't a slash, is it the ?? / trigraph?
2281 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2285 // This is the trigraph ending the comment. Emit a stern warning!
2288 // If no trigraphs are enabled, warn that we ignored this trigraph and
2289 // ignore this * character.
2290 if (!L->getLangOpts().Trigraphs) {
2291 if (!L->isLexingRawMode())
2292 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2295 if (!L->isLexingRawMode())
2296 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2299 // Warn about having an escaped newline between the */ characters.
2300 if (!L->isLexingRawMode())
2301 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2303 // If there was space between the backslash and newline, warn about it.
2304 if (HasSpace && !L->isLexingRawMode())
2305 L->Diag(CurPtr, diag::backslash_newline_space);
2311 #include <emmintrin.h>
2313 #include <altivec.h>
2317 /// We have just read from input the / and * characters that started a comment.
2318 /// Read until we find the * and / characters that terminate the comment.
2319 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2320 /// comments, because they cannot cause the comment to end. The only thing
2321 /// that can happen is the comment could end with an escaped newline between
2322 /// the terminating * and /.
2324 /// If we're in KeepCommentMode or any CommentHandler has inserted
2325 /// some tokens, this will store the first token and return true.
2326 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2327 bool &TokAtPhysicalStartOfLine) {
2328 // Scan one character past where we should, looking for a '/' character. Once
2329 // we find it, check to see if it was preceded by a *. This common
2330 // optimization helps people who like to put a lot of * characters in their
2333 // The first character we get with newlines and trigraphs skipped to handle
2334 // the degenerate /*/ case below correctly if the * has an escaped newline
2337 unsigned char C = getCharAndSize(CurPtr, CharSize);
2339 if (C == 0 && CurPtr == BufferEnd+1) {
2340 if (!isLexingRawMode())
2341 Diag(BufferPtr, diag::err_unterminated_block_comment);
2344 // KeepWhitespaceMode should return this broken comment as a token. Since
2345 // it isn't a well formed comment, just return it as an 'unknown' token.
2346 if (isKeepWhitespaceMode()) {
2347 FormTokenWithChars(Result, CurPtr, tok::unknown);
2355 // Check to see if the first character after the '/*' is another /. If so,
2356 // then this slash does not end the block comment, it is part of it.
2361 // Skip over all non-interesting characters until we find end of buffer or a
2362 // (probably ending) '/' character.
2363 if (CurPtr + 24 < BufferEnd &&
2364 // If there is a code-completion point avoid the fast scan because it
2365 // doesn't check for '\0'.
2366 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2367 // While not aligned to a 16-byte boundary.
2368 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2371 if (C == '/') goto FoundSlash;
2374 __m128i Slashes = _mm_set1_epi8('/');
2375 while (CurPtr+16 <= BufferEnd) {
2376 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2379 // Adjust the pointer to point directly after the first slash. It's
2380 // not necessary to set C here, it will be overwritten at the end of
2382 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2388 __vector unsigned char Slashes = {
2389 '/', '/', '/', '/', '/', '/', '/', '/',
2390 '/', '/', '/', '/', '/', '/', '/', '/'
2392 while (CurPtr+16 <= BufferEnd &&
2393 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2396 // Scan for '/' quickly. Many block comments are very large.
2397 while (CurPtr[0] != '/' &&
2401 CurPtr+4 < BufferEnd) {
2406 // It has to be one of the bytes scanned, increment to it and read one.
2410 // Loop to scan the remainder.
2411 while (C != '/' && C != '\0')
2416 if (CurPtr[-2] == '*') // We found the final */. We're done!
2419 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2420 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2421 // We found the final */, though it had an escaped newline between the
2422 // * and /. We're done!
2426 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2427 // If this is a /* inside of the comment, emit a warning. Don't do this
2428 // if this is a /*/, which will end the comment. This misses cases with
2429 // embedded escaped newlines, but oh well.
2430 if (!isLexingRawMode())
2431 Diag(CurPtr-1, diag::warn_nested_block_comment);
2433 } else if (C == 0 && CurPtr == BufferEnd+1) {
2434 if (!isLexingRawMode())
2435 Diag(BufferPtr, diag::err_unterminated_block_comment);
2436 // Note: the user probably forgot a */. We could continue immediately
2437 // after the /*, but this would involve lexing a lot of what really is the
2438 // comment, which surely would confuse the parser.
2441 // KeepWhitespaceMode should return this broken comment as a token. Since
2442 // it isn't a well formed comment, just return it as an 'unknown' token.
2443 if (isKeepWhitespaceMode()) {
2444 FormTokenWithChars(Result, CurPtr, tok::unknown);
2450 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2451 PP->CodeCompleteNaturalLanguage();
2459 // Notify comment handlers about the comment unless we're in a #if 0 block.
2460 if (PP && !isLexingRawMode() &&
2461 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2462 getSourceLocation(CurPtr)))) {
2464 return true; // A token has to be returned.
2467 // If we are returning comments as tokens, return this comment as a token.
2468 if (inKeepCommentMode()) {
2469 FormTokenWithChars(Result, CurPtr, tok::comment);
2473 // It is common for the tokens immediately after a /**/ comment to be
2474 // whitespace. Instead of going through the big switch, handle it
2475 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2476 // have already returned above with the comment as a token.
2477 if (isHorizontalWhitespace(*CurPtr)) {
2478 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2482 // Otherwise, just return so that the next character will be lexed as a token.
2484 Result.setFlag(Token::LeadingSpace);
2488 //===----------------------------------------------------------------------===//
2489 // Primary Lexing Entry Points
2490 //===----------------------------------------------------------------------===//
2492 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2493 /// uninterpreted string. This switches the lexer out of directive mode.
2494 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2495 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2496 "Must be in a preprocessing directive!");
2499 // CurPtr - Cache BufferPtr in an automatic variable.
2500 const char *CurPtr = BufferPtr;
2502 char Char = getAndAdvanceChar(CurPtr, Tmp);
2506 Result->push_back(Char);
2509 // Found end of file?
2510 if (CurPtr-1 != BufferEnd) {
2511 if (isCodeCompletionPoint(CurPtr-1)) {
2512 PP->CodeCompleteNaturalLanguage();
2517 // Nope, normal character, continue.
2519 Result->push_back(Char);
2525 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2526 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2527 BufferPtr = CurPtr-1;
2529 // Next, lex the character, which should handle the EOD transition.
2531 if (Tmp.is(tok::code_completion)) {
2533 PP->CodeCompleteNaturalLanguage();
2536 assert(Tmp.is(tok::eod) && "Unexpected token!");
2538 // Finally, we're done;
2544 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2545 /// condition, reporting diagnostics and handling other edge cases as required.
2546 /// This returns true if Result contains a token, false if PP.Lex should be
2548 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2549 // If we hit the end of the file while parsing a preprocessor directive,
2550 // end the preprocessor directive first. The next token returned will
2551 // then be the end of file.
2552 if (ParsingPreprocessorDirective) {
2553 // Done parsing the "line".
2554 ParsingPreprocessorDirective = false;
2555 // Update the location of token as well as BufferPtr.
2556 FormTokenWithChars(Result, CurPtr, tok::eod);
2558 // Restore comment saving mode, in case it was disabled for directive.
2560 resetExtendedTokenMode();
2561 return true; // Have a token.
2564 // If we are in raw mode, return this event as an EOF token. Let the caller
2565 // that put us in raw mode handle the event.
2566 if (isLexingRawMode()) {
2567 Result.startToken();
2568 BufferPtr = BufferEnd;
2569 FormTokenWithChars(Result, BufferEnd, tok::eof);
2573 // Issue diagnostics for unterminated #if and missing newline.
2575 // If we are in a #if directive, emit an error.
2576 while (!ConditionalStack.empty()) {
2577 if (PP->getCodeCompletionFileLoc() != FileLoc)
2578 PP->Diag(ConditionalStack.back().IfLoc,
2579 diag::err_pp_unterminated_conditional);
2580 ConditionalStack.pop_back();
2583 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2585 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2586 DiagnosticsEngine &Diags = PP->getDiagnostics();
2587 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2590 if (LangOpts.CPlusPlus11) {
2591 // C++11 [lex.phases] 2.2 p2
2592 // Prefer the C++98 pedantic compatibility warning over the generic,
2593 // non-extension, user-requested "missing newline at EOF" warning.
2594 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2595 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2597 DiagID = diag::warn_no_newline_eof;
2600 DiagID = diag::ext_no_newline_eof;
2603 Diag(BufferEnd, DiagID)
2604 << FixItHint::CreateInsertion(EndLoc, "\n");
2609 // Finally, let the preprocessor handle this.
2610 return PP->HandleEndOfFile(Result, isPragmaLexer());
2613 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2614 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2615 /// else and 2 if there are no more tokens in the buffer controlled by the
2617 unsigned Lexer::isNextPPTokenLParen() {
2618 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2620 // Switch to 'skipping' mode. This will ensure that we can lex a token
2621 // without emitting diagnostics, disables macro expansion, and will cause EOF
2622 // to return an EOF token instead of popping the include stack.
2623 LexingRawMode = true;
2625 // Save state that can be changed while lexing so that we can restore it.
2626 const char *TmpBufferPtr = BufferPtr;
2627 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2628 bool atStartOfLine = IsAtStartOfLine;
2629 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2630 bool leadingSpace = HasLeadingSpace;
2635 // Restore state that may have changed.
2636 BufferPtr = TmpBufferPtr;
2637 ParsingPreprocessorDirective = inPPDirectiveMode;
2638 HasLeadingSpace = leadingSpace;
2639 IsAtStartOfLine = atStartOfLine;
2640 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2642 // Restore the lexer back to non-skipping mode.
2643 LexingRawMode = false;
2645 if (Tok.is(tok::eof))
2647 return Tok.is(tok::l_paren);
2650 /// \brief Find the end of a version control conflict marker.
2651 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2652 ConflictMarkerKind CMK) {
2653 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2654 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2655 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2656 size_t Pos = RestOfBuffer.find(Terminator);
2657 while (Pos != StringRef::npos) {
2658 // Must occur at start of line.
2660 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2661 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2662 Pos = RestOfBuffer.find(Terminator);
2665 return RestOfBuffer.data()+Pos;
2670 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2671 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2672 /// and recover nicely. This returns true if it is a conflict marker and false
2674 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2675 // Only a conflict marker if it starts at the beginning of a line.
2676 if (CurPtr != BufferStart &&
2677 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2680 // Check to see if we have <<<<<<< or >>>>.
2681 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2682 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2685 // If we have a situation where we don't care about conflict markers, ignore
2687 if (CurrentConflictMarkerState || isLexingRawMode())
2690 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2692 // Check to see if there is an ending marker somewhere in the buffer at the
2693 // start of a line to terminate this conflict marker.
2694 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2695 // We found a match. We are really in a conflict marker.
2696 // Diagnose this, and ignore to the end of line.
2697 Diag(CurPtr, diag::err_conflict_marker);
2698 CurrentConflictMarkerState = Kind;
2700 // Skip ahead to the end of line. We know this exists because the
2701 // end-of-conflict marker starts with \r or \n.
2702 while (*CurPtr != '\r' && *CurPtr != '\n') {
2703 assert(CurPtr != BufferEnd && "Didn't find end of line");
2710 // No end of conflict marker found.
2714 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2715 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2716 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2717 /// the line. This returns true if it is a conflict marker and false if not.
2718 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2719 // Only a conflict marker if it starts at the beginning of a line.
2720 if (CurPtr != BufferStart &&
2721 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2724 // If we have a situation where we don't care about conflict markers, ignore
2726 if (!CurrentConflictMarkerState || isLexingRawMode())
2729 // Check to see if we have the marker (4 characters in a row).
2730 for (unsigned i = 1; i != 4; ++i)
2731 if (CurPtr[i] != CurPtr[0])
2734 // If we do have it, search for the end of the conflict marker. This could
2735 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2736 // be the end of conflict marker.
2737 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2738 CurrentConflictMarkerState)) {
2741 // Skip ahead to the end of line.
2742 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2747 // No longer in the conflict marker.
2748 CurrentConflictMarkerState = CMK_None;
2755 static const char *findPlaceholderEnd(const char *CurPtr,
2756 const char *BufferEnd) {
2757 if (CurPtr == BufferEnd)
2759 BufferEnd -= 1; // Scan until the second last character.
2760 for (; CurPtr != BufferEnd; ++CurPtr) {
2761 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2767 bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2768 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2769 if (!PP || LexingRawMode)
2771 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2774 const char *Start = CurPtr - 1;
2775 if (!LangOpts.AllowEditorPlaceholders)
2776 Diag(Start, diag::err_placeholder_in_source);
2777 Result.startToken();
2778 FormTokenWithChars(Result, End, tok::raw_identifier);
2779 Result.setRawIdentifierData(Start);
2780 PP->LookUpIdentifierInfo(Result);
2781 Result.setFlag(Token::IsEditorPlaceholder);
2786 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2787 if (PP && PP->isCodeCompletionEnabled()) {
2788 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2789 return Loc == PP->getCodeCompletionLoc();
2795 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2798 char Kind = getCharAndSize(StartPtr, CharSize);
2800 unsigned NumHexDigits;
2803 else if (Kind == 'U')
2808 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2809 if (Result && !isLexingRawMode())
2810 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2814 const char *CurPtr = StartPtr + CharSize;
2815 const char *KindLoc = &CurPtr[-1];
2817 uint32_t CodePoint = 0;
2818 for (unsigned i = 0; i < NumHexDigits; ++i) {
2819 char C = getCharAndSize(CurPtr, CharSize);
2821 unsigned Value = llvm::hexDigitValue(C);
2823 if (Result && !isLexingRawMode()) {
2825 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2826 << StringRef(KindLoc, 1);
2828 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2830 // If the user wrote \U1234, suggest a fixit to \u.
2831 if (i == 4 && NumHexDigits == 8) {
2832 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2833 Diag(KindLoc, diag::note_ucn_four_not_eight)
2834 << FixItHint::CreateReplacement(URange, "u");
2849 Result->setFlag(Token::HasUCN);
2850 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2853 while (StartPtr != CurPtr)
2854 (void)getAndAdvanceChar(StartPtr, *Result);
2859 // Don't apply C family restrictions to UCNs in assembly mode
2860 if (LangOpts.AsmPreprocessor)
2863 // C99 6.4.3p2: A universal character name shall not specify a character whose
2864 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2865 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2866 // C++11 [lex.charset]p2: If the hexadecimal value for a
2867 // universal-character-name corresponds to a surrogate code point (in the
2868 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2869 // if the hexadecimal value for a universal-character-name outside the
2870 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2871 // string literal corresponds to a control character (in either of the
2872 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2873 // basic source character set, the program is ill-formed.
2874 if (CodePoint < 0xA0) {
2875 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2878 // We don't use isLexingRawMode() here because we need to warn about bad
2879 // UCNs even when skipping preprocessing tokens in a #if block.
2881 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2882 Diag(BufferPtr, diag::err_ucn_control_character);
2884 char C = static_cast<char>(CodePoint);
2885 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2891 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2892 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2893 // We don't use isLexingRawMode() here because we need to diagnose bad
2894 // UCNs even when skipping preprocessing tokens in a #if block.
2896 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2897 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2899 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2907 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2908 const char *CurPtr) {
2909 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2910 UnicodeWhitespaceCharRanges);
2911 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2912 UnicodeWhitespaceChars.contains(C)) {
2913 Diag(BufferPtr, diag::ext_unicode_whitespace)
2914 << makeCharRange(*this, BufferPtr, CurPtr);
2916 Result.setFlag(Token::LeadingSpace);
2922 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2923 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2924 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2925 !PP->isPreprocessedOutput()) {
2926 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2927 makeCharRange(*this, BufferPtr, CurPtr),
2932 return LexIdentifier(Result, CurPtr);
2935 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2936 !PP->isPreprocessedOutput() &&
2937 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2938 // Non-ASCII characters tend to creep into source code unintentionally.
2939 // Instead of letting the parser complain about the unknown token,
2940 // just drop the character.
2941 // Note that we can /only/ do this when the non-ASCII character is actually
2942 // spelled as Unicode, not written as a UCN. The standard requires that
2943 // we not throw away any possible preprocessor tokens, but there's a
2944 // loophole in the mapping of Unicode characters to basic character set
2945 // characters that allows us to map these particular characters to, say,
2947 Diag(BufferPtr, diag::err_non_ascii)
2948 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2954 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2957 FormTokenWithChars(Result, CurPtr, tok::unknown);
2961 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2962 IsAtStartOfLine = Result.isAtStartOfLine();
2963 HasLeadingSpace = Result.hasLeadingSpace();
2964 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2965 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2968 bool Lexer::Lex(Token &Result) {
2969 // Start a new token.
2970 Result.startToken();
2972 // Set up misc whitespace flags for LexTokenInternal.
2973 if (IsAtStartOfLine) {
2974 Result.setFlag(Token::StartOfLine);
2975 IsAtStartOfLine = false;
2978 if (HasLeadingSpace) {
2979 Result.setFlag(Token::LeadingSpace);
2980 HasLeadingSpace = false;
2983 if (HasLeadingEmptyMacro) {
2984 Result.setFlag(Token::LeadingEmptyMacro);
2985 HasLeadingEmptyMacro = false;
2988 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2989 IsAtPhysicalStartOfLine = false;
2990 bool isRawLex = isLexingRawMode();
2992 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2993 // (After the LexTokenInternal call, the lexer might be destroyed.)
2994 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2995 return returnedToken;
2998 /// LexTokenInternal - This implements a simple C family lexer. It is an
2999 /// extremely performance critical piece of code. This assumes that the buffer
3000 /// has a null character at the end of the file. This returns a preprocessing
3001 /// token, not a normal token, as such, it is an internal interface. It assumes
3002 /// that the Flags of result have been cleared before calling this.
3003 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3005 // New token, can't need cleaning yet.
3006 Result.clearFlag(Token::NeedsCleaning);
3007 Result.setIdentifierInfo(nullptr);
3009 // CurPtr - Cache BufferPtr in an automatic variable.
3010 const char *CurPtr = BufferPtr;
3012 // Small amounts of horizontal whitespace is very common between tokens.
3013 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3015 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3018 // If we are keeping whitespace and other tokens, just return what we just
3019 // skipped. The next lexer invocation will return the token after the
3021 if (isKeepWhitespaceMode()) {
3022 FormTokenWithChars(Result, CurPtr, tok::unknown);
3023 // FIXME: The next token will not have LeadingSpace set.
3028 Result.setFlag(Token::LeadingSpace);
3031 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
3033 // Read a character, advancing over it.
3034 char Char = getAndAdvanceChar(CurPtr, Result);
3035 tok::TokenKind Kind;
3039 // Found end of file?
3040 if (CurPtr-1 == BufferEnd)
3041 return LexEndOfFile(Result, CurPtr-1);
3043 // Check if we are performing code completion.
3044 if (isCodeCompletionPoint(CurPtr-1)) {
3045 // Return the code-completion token.
3046 Result.startToken();
3047 FormTokenWithChars(Result, CurPtr, tok::code_completion);
3051 if (!isLexingRawMode())
3052 Diag(CurPtr-1, diag::null_in_file);
3053 Result.setFlag(Token::LeadingSpace);
3054 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3055 return true; // KeepWhitespaceMode
3057 // We know the lexer hasn't changed, so just try again with this lexer.
3058 // (We manually eliminate the tail call to avoid recursion.)
3061 case 26: // DOS & CP/M EOF: "^Z".
3062 // If we're in Microsoft extensions mode, treat this as end of file.
3063 if (LangOpts.MicrosoftExt) {
3064 if (!isLexingRawMode())
3065 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3066 return LexEndOfFile(Result, CurPtr-1);
3069 // If Microsoft extensions are disabled, this is just random garbage.
3070 Kind = tok::unknown;
3075 // If we are inside a preprocessor directive and we see the end of line,
3076 // we know we are done with the directive, so return an EOD token.
3077 if (ParsingPreprocessorDirective) {
3078 // Done parsing the "line".
3079 ParsingPreprocessorDirective = false;
3081 // Restore comment saving mode, in case it was disabled for directive.
3083 resetExtendedTokenMode();
3085 // Since we consumed a newline, we are back at the start of a line.
3086 IsAtStartOfLine = true;
3087 IsAtPhysicalStartOfLine = true;
3093 // No leading whitespace seen so far.
3094 Result.clearFlag(Token::LeadingSpace);
3096 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3097 return true; // KeepWhitespaceMode
3099 // We only saw whitespace, so just try again with this lexer.
3100 // (We manually eliminate the tail call to avoid recursion.)
3106 SkipHorizontalWhitespace:
3107 Result.setFlag(Token::LeadingSpace);
3108 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3109 return true; // KeepWhitespaceMode
3114 // If the next token is obviously a // or /* */ comment, skip it efficiently
3115 // too (without going through the big switch stmt).
3116 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3117 LangOpts.LineComment &&
3118 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3119 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3120 return true; // There is a token to return.
3121 goto SkipIgnoredUnits;
3122 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3123 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3124 return true; // There is a token to return.
3125 goto SkipIgnoredUnits;
3126 } else if (isHorizontalWhitespace(*CurPtr)) {
3127 goto SkipHorizontalWhitespace;
3129 // We only saw whitespace, so just try again with this lexer.
3130 // (We manually eliminate the tail call to avoid recursion.)
3133 // C99 6.4.4.1: Integer Constants.
3134 // C99 6.4.4.2: Floating Constants.
3135 case '0': case '1': case '2': case '3': case '4':
3136 case '5': case '6': case '7': case '8': case '9':
3137 // Notify MIOpt that we read a non-whitespace/non-comment token.
3139 return LexNumericConstant(Result, CurPtr);
3141 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3142 // Notify MIOpt that we read a non-whitespace/non-comment token.
3145 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3146 Char = getCharAndSize(CurPtr, SizeTmp);
3148 // UTF-16 string literal
3150 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3151 tok::utf16_string_literal);
3153 // UTF-16 character constant
3155 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3156 tok::utf16_char_constant);
3158 // UTF-16 raw string literal
3159 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3160 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3161 return LexRawStringLiteral(Result,
3162 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3164 tok::utf16_string_literal);
3167 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3169 // UTF-8 string literal
3171 return LexStringLiteral(Result,
3172 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3174 tok::utf8_string_literal);
3175 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3176 return LexCharConstant(
3177 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3179 tok::utf8_char_constant);
3181 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3183 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3184 // UTF-8 raw string literal
3186 return LexRawStringLiteral(Result,
3187 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3190 tok::utf8_string_literal);
3196 // treat u like the start of an identifier.
3197 return LexIdentifier(Result, CurPtr);
3199 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3200 // Notify MIOpt that we read a non-whitespace/non-comment token.
3203 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3204 Char = getCharAndSize(CurPtr, SizeTmp);
3206 // UTF-32 string literal
3208 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3209 tok::utf32_string_literal);
3211 // UTF-32 character constant
3213 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3214 tok::utf32_char_constant);
3216 // UTF-32 raw string literal
3217 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3218 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3219 return LexRawStringLiteral(Result,
3220 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3222 tok::utf32_string_literal);
3225 // treat U like the start of an identifier.
3226 return LexIdentifier(Result, CurPtr);
3228 case 'R': // Identifier or C++0x raw string literal
3229 // Notify MIOpt that we read a non-whitespace/non-comment token.
3232 if (LangOpts.CPlusPlus11) {
3233 Char = getCharAndSize(CurPtr, SizeTmp);
3236 return LexRawStringLiteral(Result,
3237 ConsumeChar(CurPtr, SizeTmp, Result),
3238 tok::string_literal);
3241 // treat R like the start of an identifier.
3242 return LexIdentifier(Result, CurPtr);
3244 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3245 // Notify MIOpt that we read a non-whitespace/non-comment token.
3247 Char = getCharAndSize(CurPtr, SizeTmp);
3249 // Wide string literal.
3251 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3252 tok::wide_string_literal);
3254 // Wide raw string literal.
3255 if (LangOpts.CPlusPlus11 && Char == 'R' &&
3256 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3257 return LexRawStringLiteral(Result,
3258 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3260 tok::wide_string_literal);
3262 // Wide character constant.
3264 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3265 tok::wide_char_constant);
3266 // FALL THROUGH, treating L like the start of an identifier.
3268 // C99 6.4.2: Identifiers.
3269 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3270 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3271 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3272 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3273 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3274 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3275 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3276 case 'v': case 'w': case 'x': case 'y': case 'z':
3278 // Notify MIOpt that we read a non-whitespace/non-comment token.
3280 return LexIdentifier(Result, CurPtr);
3282 case '$': // $ in identifiers.
3283 if (LangOpts.DollarIdents) {
3284 if (!isLexingRawMode())
3285 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3286 // Notify MIOpt that we read a non-whitespace/non-comment token.
3288 return LexIdentifier(Result, CurPtr);
3291 Kind = tok::unknown;
3294 // C99 6.4.4: Character Constants.
3296 // Notify MIOpt that we read a non-whitespace/non-comment token.
3298 return LexCharConstant(Result, CurPtr, tok::char_constant);
3300 // C99 6.4.5: String Literals.
3302 // Notify MIOpt that we read a non-whitespace/non-comment token.
3304 return LexStringLiteral(Result, CurPtr, tok::string_literal);
3306 // C99 6.4.6: Punctuators.
3308 Kind = tok::question;
3311 Kind = tok::l_square;
3314 Kind = tok::r_square;
3317 Kind = tok::l_paren;
3320 Kind = tok::r_paren;
3323 Kind = tok::l_brace;
3326 Kind = tok::r_brace;
3329 Char = getCharAndSize(CurPtr, SizeTmp);
3330 if (Char >= '0' && Char <= '9') {
3331 // Notify MIOpt that we read a non-whitespace/non-comment token.
3334 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3335 } else if (LangOpts.CPlusPlus && Char == '*') {
3336 Kind = tok::periodstar;
3338 } else if (Char == '.' &&
3339 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3340 Kind = tok::ellipsis;
3341 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3348 Char = getCharAndSize(CurPtr, SizeTmp);
3351 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3352 } else if (Char == '=') {
3353 Kind = tok::ampequal;
3354 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3360 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3361 Kind = tok::starequal;
3362 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3368 Char = getCharAndSize(CurPtr, SizeTmp);
3370 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3371 Kind = tok::plusplus;
3372 } else if (Char == '=') {
3373 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3374 Kind = tok::plusequal;
3380 Char = getCharAndSize(CurPtr, SizeTmp);
3381 if (Char == '-') { // --
3382 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3383 Kind = tok::minusminus;
3384 } else if (Char == '>' && LangOpts.CPlusPlus &&
3385 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3386 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3388 Kind = tok::arrowstar;
3389 } else if (Char == '>') { // ->
3390 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3392 } else if (Char == '=') { // -=
3393 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3394 Kind = tok::minusequal;
3403 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3404 Kind = tok::exclaimequal;
3405 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3407 Kind = tok::exclaim;
3412 Char = getCharAndSize(CurPtr, SizeTmp);
3413 if (Char == '/') { // Line comment.
3414 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3415 // want to lex this as a comment. There is one problem with this though,
3416 // that in one particular corner case, this can change the behavior of the
3417 // resultant program. For example, In "foo //**/ bar", C89 would lex
3418 // this as "foo / bar" and langauges with Line comments would lex it as
3419 // "foo". Check to see if the character after the second slash is a '*'.
3420 // If so, we will lex that as a "/" instead of the start of a comment.
3421 // However, we never do this if we are just preprocessing.
3422 bool TreatAsComment = LangOpts.LineComment &&
3423 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3424 if (!TreatAsComment)
3425 if (!(PP && PP->isPreprocessedOutput()))
3426 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3428 if (TreatAsComment) {
3429 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3430 TokAtPhysicalStartOfLine))
3431 return true; // There is a token to return.
3433 // It is common for the tokens immediately after a // comment to be
3434 // whitespace (indentation for the next line). Instead of going through
3435 // the big switch, handle it efficiently now.
3436 goto SkipIgnoredUnits;
3440 if (Char == '*') { // /**/ comment.
3441 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3442 TokAtPhysicalStartOfLine))
3443 return true; // There is a token to return.
3445 // We only saw whitespace, so just try again with this lexer.
3446 // (We manually eliminate the tail call to avoid recursion.)
3451 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3452 Kind = tok::slashequal;
3458 Char = getCharAndSize(CurPtr, SizeTmp);
3460 Kind = tok::percentequal;
3461 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3462 } else if (LangOpts.Digraphs && Char == '>') {
3463 Kind = tok::r_brace; // '%>' -> '}'
3464 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3465 } else if (LangOpts.Digraphs && Char == ':') {
3466 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3467 Char = getCharAndSize(CurPtr, SizeTmp);
3468 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3469 Kind = tok::hashhash; // '%:%:' -> '##'
3470 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3472 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3473 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3474 if (!isLexingRawMode())
3475 Diag(BufferPtr, diag::ext_charize_microsoft);
3477 } else { // '%:' -> '#'
3478 // We parsed a # character. If this occurs at the start of the line,
3479 // it's actually the start of a preprocessing directive. Callback to
3480 // the preprocessor to handle it.
3481 // TODO: -fpreprocessed mode??
3482 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3483 goto HandleDirective;
3488 Kind = tok::percent;
3492 Char = getCharAndSize(CurPtr, SizeTmp);
3493 if (ParsingFilename) {
3494 return LexAngledStringLiteral(Result, CurPtr);
3495 } else if (Char == '<') {
3496 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3498 Kind = tok::lesslessequal;
3499 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3501 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3502 // If this is actually a '<<<<<<<' version control conflict marker,
3503 // recognize it as such and recover nicely.
3505 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3506 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3509 } else if (LangOpts.CUDA && After == '<') {
3510 Kind = tok::lesslessless;
3511 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3514 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3515 Kind = tok::lessless;
3517 } else if (Char == '=') {
3518 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3519 Kind = tok::lessequal;
3520 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3521 if (LangOpts.CPlusPlus11 &&
3522 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3523 // C++0x [lex.pptoken]p3:
3524 // Otherwise, if the next three characters are <:: and the subsequent
3525 // character is neither : nor >, the < is treated as a preprocessor
3526 // token by itself and not as the first character of the alternative
3529 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3530 if (After != ':' && After != '>') {
3532 if (!isLexingRawMode())
3533 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3538 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3539 Kind = tok::l_square;
3540 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3541 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3542 Kind = tok::l_brace;
3543 } else if (Char == '#' && lexEditorPlaceholder(Result, CurPtr)) {
3550 Char = getCharAndSize(CurPtr, SizeTmp);
3552 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3553 Kind = tok::greaterequal;
3554 } else if (Char == '>') {
3555 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3557 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3559 Kind = tok::greatergreaterequal;
3560 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3561 // If this is actually a '>>>>' conflict marker, recognize it as such
3562 // and recover nicely.
3564 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3565 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3567 } else if (LangOpts.CUDA && After == '>') {
3568 Kind = tok::greatergreatergreater;
3569 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3572 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3573 Kind = tok::greatergreater;
3576 Kind = tok::greater;
3580 Char = getCharAndSize(CurPtr, SizeTmp);
3582 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3583 Kind = tok::caretequal;
3584 } else if (LangOpts.OpenCL && Char == '^') {
3585 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3586 Kind = tok::caretcaret;
3592 Char = getCharAndSize(CurPtr, SizeTmp);
3594 Kind = tok::pipeequal;
3595 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3596 } else if (Char == '|') {
3597 // If this is '|||||||' and we're in a conflict marker, ignore it.
3598 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3600 Kind = tok::pipepipe;
3601 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3607 Char = getCharAndSize(CurPtr, SizeTmp);
3608 if (LangOpts.Digraphs && Char == '>') {
3609 Kind = tok::r_square; // ':>' -> ']'
3610 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3611 } else if (LangOpts.CPlusPlus && Char == ':') {
3612 Kind = tok::coloncolon;
3613 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3622 Char = getCharAndSize(CurPtr, SizeTmp);
3624 // If this is '====' and we're in a conflict marker, ignore it.
3625 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3628 Kind = tok::equalequal;
3629 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3638 Char = getCharAndSize(CurPtr, SizeTmp);
3640 Kind = tok::hashhash;
3641 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3642 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3644 if (!isLexingRawMode())
3645 Diag(BufferPtr, diag::ext_charize_microsoft);
3646 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3648 // We parsed a # character. If this occurs at the start of the line,
3649 // it's actually the start of a preprocessing directive. Callback to
3650 // the preprocessor to handle it.
3651 // TODO: -fpreprocessed mode??
3652 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3653 goto HandleDirective;
3660 // Objective C support.
3661 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3664 Kind = tok::unknown;
3667 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3669 if (!LangOpts.AsmPreprocessor) {
3670 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3671 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3672 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3673 return true; // KeepWhitespaceMode
3675 // We only saw whitespace, so just try again with this lexer.
3676 // (We manually eliminate the tail call to avoid recursion.)
3680 return LexUnicode(Result, CodePoint, CurPtr);
3684 Kind = tok::unknown;
3688 if (isASCII(Char)) {
3689 Kind = tok::unknown;
3693 llvm::UTF32 CodePoint;
3695 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3696 // an escaped newline.
3698 llvm::ConversionResult Status =
3699 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3700 (const llvm::UTF8 *)BufferEnd,
3702 llvm::strictConversion);
3703 if (Status == llvm::conversionOK) {
3704 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3705 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3706 return true; // KeepWhitespaceMode
3708 // We only saw whitespace, so just try again with this lexer.
3709 // (We manually eliminate the tail call to avoid recursion.)
3712 return LexUnicode(Result, CodePoint, CurPtr);
3715 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3716 PP->isPreprocessedOutput()) {
3718 Kind = tok::unknown;
3722 // Non-ASCII characters tend to creep into source code unintentionally.
3723 // Instead of letting the parser complain about the unknown token,
3724 // just diagnose the invalid UTF-8, then drop the character.
3725 Diag(CurPtr, diag::err_invalid_utf8);
3727 BufferPtr = CurPtr+1;
3728 // We're pretending the character didn't exist, so just try again with
3730 // (We manually eliminate the tail call to avoid recursion.)
3735 // Notify MIOpt that we read a non-whitespace/non-comment token.
3738 // Update the location of token as well as BufferPtr.
3739 FormTokenWithChars(Result, CurPtr, Kind);
3743 // We parsed a # character and it's the start of a preprocessing directive.
3745 FormTokenWithChars(Result, CurPtr, tok::hash);
3746 PP->HandleDirective(Result);
3748 if (PP->hadModuleLoaderFatalFailure()) {
3749 // With a fatal failure in the module loader, we abort parsing.
3750 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3754 // We parsed the directive; lex a token with the new state.