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 // TODO: GCC Diagnostics emitted by the lexer:
15 // PEDWARN: (form feed|vertical tab) in preprocessing directive
17 // Universal characters, unicode, char mapping:
18 // WARNING: `%.*s' is not in NFKC
19 // WARNING: `%.*s' is not in NFC
22 // TODO: Options to support:
23 // -fexec-charset,-fwide-exec-charset
25 //===----------------------------------------------------------------------===//
27 #include "clang/Lex/Lexer.h"
28 #include "clang/Lex/Preprocessor.h"
29 #include "clang/Lex/LexDiagnostic.h"
30 #include "clang/Lex/CodeCompletionHandler.h"
31 #include "clang/Basic/SourceManager.h"
32 #include "llvm/ADT/StringSwitch.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/Support/Compiler.h"
35 #include "llvm/Support/MemoryBuffer.h"
37 using namespace clang;
39 static void InitCharacterInfo();
41 //===----------------------------------------------------------------------===//
42 // Token Class Implementation
43 //===----------------------------------------------------------------------===//
45 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
46 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
47 if (IdentifierInfo *II = getIdentifierInfo())
48 return II->getObjCKeywordID() == objcKey;
52 /// getObjCKeywordID - Return the ObjC keyword kind.
53 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
54 IdentifierInfo *specId = getIdentifierInfo();
55 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
59 //===----------------------------------------------------------------------===//
60 // Lexer Class Implementation
61 //===----------------------------------------------------------------------===//
63 void Lexer::anchor() { }
65 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;
97 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
100 // We are not after parsing #include.
101 ParsingFilename = false;
103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
113 /// Lexer constructor - Create a new lexer object for the specified buffer
114 /// with the specified preprocessor managing the lexing process. This lexer
115 /// assumes that the associated file buffer and Preprocessor objects will
116 /// outlive it, so it doesn't take ownership of either of them.
117 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
120 LangOpts(PP.getLangOpts()) {
122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
125 // Default to keeping comments if the preprocessor wants them.
126 SetCommentRetentionState(PP.getCommentRetentionState());
129 /// Lexer constructor - Create a new raw lexer object. This object is only
130 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text
131 /// range will outlive it, so it doesn't take ownership of it.
132 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
133 const char *BufStart, const char *BufPtr, const char *BufEnd)
134 : FileLoc(fileloc), LangOpts(langOpts) {
136 InitLexer(BufStart, BufPtr, BufEnd);
138 // We *are* in raw mode.
139 LexingRawMode = true;
142 /// Lexer constructor - Create a new raw lexer object. This object is only
143 /// suitable for calls to 'LexRawToken'. This lexer assumes that the text
144 /// range will outlive it, so it doesn't take ownership of it.
145 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
146 const SourceManager &SM, const LangOptions &langOpts)
147 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
149 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
150 FromFile->getBufferEnd());
152 // We *are* in raw mode.
153 LexingRawMode = true;
156 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
157 /// _Pragma expansion. This has a variety of magic semantics that this method
158 /// sets up. It returns a new'd Lexer that must be delete'd when done.
160 /// On entrance to this routine, TokStartLoc is a macro location which has a
161 /// spelling loc that indicates the bytes to be lexed for the token and an
162 /// expansion location that indicates where all lexed tokens should be
165 /// FIXME: It would really be nice to make _Pragma just be a wrapper around a
166 /// normal lexer that remaps tokens as they fly by. This would require making
167 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
168 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
169 /// out of the critical path of the lexer!
171 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
172 SourceLocation ExpansionLocStart,
173 SourceLocation ExpansionLocEnd,
174 unsigned TokLen, Preprocessor &PP) {
175 SourceManager &SM = PP.getSourceManager();
177 // Create the lexer as if we were going to lex the file normally.
178 FileID SpellingFID = SM.getFileID(SpellingLoc);
179 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
180 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
182 // Now that the lexer is created, change the start/end locations so that we
183 // just lex the subsection of the file that we want. This is lexing from a
185 const char *StrData = SM.getCharacterData(SpellingLoc);
187 L->BufferPtr = StrData;
188 L->BufferEnd = StrData+TokLen;
189 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
191 // Set the SourceLocation with the remapping information. This ensures that
192 // GetMappedTokenLoc will remap the tokens as they are lexed.
193 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
195 ExpansionLocEnd, TokLen);
197 // Ensure that the lexer thinks it is inside a directive, so that end \n will
198 // return an EOD token.
199 L->ParsingPreprocessorDirective = true;
201 // This lexer really is for _Pragma.
202 L->Is_PragmaLexer = true;
207 /// Stringify - Convert the specified string into a C string, with surrounding
208 /// ""'s, and with escaped \ and " characters.
209 std::string Lexer::Stringify(const std::string &Str, bool Charify) {
210 std::string Result = Str;
211 char Quote = Charify ? '\'' : '"';
212 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
213 if (Result[i] == '\\' || Result[i] == Quote) {
214 Result.insert(Result.begin()+i, '\\');
221 /// Stringify - Convert the specified string into a C string by escaping '\'
222 /// and " characters. This does not add surrounding ""'s to the string.
223 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
224 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225 if (Str[i] == '\\' || Str[i] == '"') {
226 Str.insert(Str.begin()+i, '\\');
232 //===----------------------------------------------------------------------===//
234 //===----------------------------------------------------------------------===//
236 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
237 /// token are the characters used to represent the token in the source file
238 /// after trigraph expansion and escaped-newline folding. In particular, this
239 /// wants to get the true, uncanonicalized, spelling of things like digraphs
241 StringRef Lexer::getSpelling(SourceLocation loc,
242 SmallVectorImpl<char> &buffer,
243 const SourceManager &SM,
244 const LangOptions &options,
246 // Break down the source location.
247 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
249 // Try to the load the file buffer.
250 bool invalidTemp = false;
251 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
253 if (invalid) *invalid = true;
257 const char *tokenBegin = file.data() + locInfo.second;
259 // Lex from the start of the given location.
260 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
261 file.begin(), tokenBegin, file.end());
263 lexer.LexFromRawLexer(token);
265 unsigned length = token.getLength();
267 // Common case: no need for cleaning.
268 if (!token.needsCleaning())
269 return StringRef(tokenBegin, length);
271 // Hard case, we need to relex the characters into the string.
273 buffer.reserve(length);
275 for (const char *ti = tokenBegin, *te = ti + length; ti != te; ) {
277 buffer.push_back(Lexer::getCharAndSizeNoWarn(ti, charSize, options));
281 return StringRef(buffer.data(), buffer.size());
284 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
285 /// token are the characters used to represent the token in the source file
286 /// after trigraph expansion and escaped-newline folding. In particular, this
287 /// wants to get the true, uncanonicalized, spelling of things like digraphs
289 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
290 const LangOptions &LangOpts, bool *Invalid) {
291 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
293 // If this token contains nothing interesting, return it directly.
294 bool CharDataInvalid = false;
295 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
298 *Invalid = CharDataInvalid;
300 return std::string();
302 if (!Tok.needsCleaning())
303 return std::string(TokStart, TokStart+Tok.getLength());
306 Result.reserve(Tok.getLength());
308 // Otherwise, hard case, relex the characters into the string.
309 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
312 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, LangOpts));
315 assert(Result.size() != unsigned(Tok.getLength()) &&
316 "NeedsCleaning flag set on something that didn't need cleaning!");
320 /// getSpelling - This method is used to get the spelling of a token into a
321 /// preallocated buffer, instead of as an std::string. The caller is required
322 /// to allocate enough space for the token, which is guaranteed to be at least
323 /// Tok.getLength() bytes long. The actual length of the token is returned.
325 /// Note that this method may do two possible things: it may either fill in
326 /// the buffer specified with characters, or it may *change the input pointer*
327 /// to point to a constant buffer with the data already in it (avoiding a
328 /// copy). The caller is not allowed to modify the returned buffer pointer
329 /// if an internal buffer is returned.
330 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
331 const SourceManager &SourceMgr,
332 const LangOptions &LangOpts, bool *Invalid) {
333 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
335 const char *TokStart = 0;
336 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
337 if (Tok.is(tok::raw_identifier))
338 TokStart = Tok.getRawIdentifierData();
339 else if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
340 // Just return the string from the identifier table, which is very quick.
341 Buffer = II->getNameStart();
342 return II->getLength();
345 // NOTE: this can be checked even after testing for an IdentifierInfo.
347 TokStart = Tok.getLiteralData();
350 // Compute the start of the token in the input lexer buffer.
351 bool CharDataInvalid = false;
352 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
354 *Invalid = CharDataInvalid;
355 if (CharDataInvalid) {
361 // If this token contains nothing interesting, return it directly.
362 if (!Tok.needsCleaning()) {
364 return Tok.getLength();
367 // Otherwise, hard case, relex the characters into the string.
368 char *OutBuf = const_cast<char*>(Buffer);
369 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
372 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, LangOpts);
375 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
376 "NeedsCleaning flag set on something that didn't need cleaning!");
378 return OutBuf-Buffer;
383 static bool isWhitespace(unsigned char c);
385 /// MeasureTokenLength - Relex the token at the specified location and return
386 /// its length in bytes in the input file. If the token needs cleaning (e.g.
387 /// includes a trigraph or an escaped newline) then this count includes bytes
388 /// that are part of that.
389 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
390 const SourceManager &SM,
391 const LangOptions &LangOpts) {
392 // TODO: this could be special cased for common tokens like identifiers, ')',
393 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
394 // all obviously single-char tokens. This could use
395 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
398 // If this comes from a macro expansion, we really do want the macro name, not
399 // the token this macro expanded to.
400 Loc = SM.getExpansionLoc(Loc);
401 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
402 bool Invalid = false;
403 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
407 const char *StrData = Buffer.data()+LocInfo.second;
409 if (isWhitespace(StrData[0]))
412 // Create a lexer starting at the beginning of this token.
413 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
414 Buffer.begin(), StrData, Buffer.end());
415 TheLexer.SetCommentRetentionState(true);
417 TheLexer.LexFromRawLexer(TheTok);
418 return TheTok.getLength();
421 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
422 const SourceManager &SM,
423 const LangOptions &LangOpts) {
424 assert(Loc.isFileID());
425 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
426 if (LocInfo.first.isInvalid())
429 bool Invalid = false;
430 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
434 // Back up from the current location until we hit the beginning of a line
435 // (or the buffer). We'll relex from that point.
436 const char *BufStart = Buffer.data();
437 if (LocInfo.second >= Buffer.size())
440 const char *StrData = BufStart+LocInfo.second;
441 if (StrData[0] == '\n' || StrData[0] == '\r')
444 const char *LexStart = StrData;
445 while (LexStart != BufStart) {
446 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
454 // Create a lexer starting at the beginning of this token.
455 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
456 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
457 TheLexer.SetCommentRetentionState(true);
459 // Lex tokens until we find the token that contains the source location.
462 TheLexer.LexFromRawLexer(TheTok);
464 if (TheLexer.getBufferLocation() > StrData) {
465 // Lexing this token has taken the lexer past the source location we're
466 // looking for. If the current token encompasses our source location,
467 // return the beginning of that token.
468 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
469 return TheTok.getLocation();
471 // We ended up skipping over the source location entirely, which means
472 // that it points into whitespace. We're done here.
475 } while (TheTok.getKind() != tok::eof);
477 // We've passed our source location; just return the original source location.
481 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
482 const SourceManager &SM,
483 const LangOptions &LangOpts) {
485 return getBeginningOfFileToken(Loc, SM, LangOpts);
487 if (!SM.isMacroArgExpansion(Loc))
490 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
491 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
492 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
493 std::pair<FileID, unsigned> BeginFileLocInfo
494 = SM.getDecomposedLoc(BeginFileLoc);
495 assert(FileLocInfo.first == BeginFileLocInfo.first &&
496 FileLocInfo.second >= BeginFileLocInfo.second);
497 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
501 enum PreambleDirectiveKind {
509 std::pair<unsigned, bool>
510 Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
511 const LangOptions &LangOpts, unsigned MaxLines) {
512 // Create a lexer starting at the beginning of the file. Note that we use a
513 // "fake" file source location at offset 1 so that the lexer will track our
514 // position within the file.
515 const unsigned StartOffset = 1;
516 SourceLocation StartLoc = SourceLocation::getFromRawEncoding(StartOffset);
517 Lexer TheLexer(StartLoc, LangOpts, Buffer->getBufferStart(),
518 Buffer->getBufferStart(), Buffer->getBufferEnd());
520 bool InPreprocessorDirective = false;
523 unsigned IfCount = 0;
525 unsigned MaxLineOffset = 0;
527 const char *CurPtr = Buffer->getBufferStart();
528 unsigned CurLine = 0;
529 while (CurPtr != Buffer->getBufferEnd()) {
533 if (CurLine == MaxLines)
537 if (CurPtr != Buffer->getBufferEnd())
538 MaxLineOffset = CurPtr - Buffer->getBufferStart();
542 TheLexer.LexFromRawLexer(TheTok);
544 if (InPreprocessorDirective) {
545 // If we've hit the end of the file, we're done.
546 if (TheTok.getKind() == tok::eof) {
547 InPreprocessorDirective = false;
551 // If we haven't hit the end of the preprocessor directive, skip this
553 if (!TheTok.isAtStartOfLine())
556 // We've passed the end of the preprocessor directive, and will look
557 // at this token again below.
558 InPreprocessorDirective = false;
561 // Keep track of the # of lines in the preamble.
562 if (TheTok.isAtStartOfLine()) {
563 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
565 // If we were asked to limit the number of lines in the preamble,
566 // and we're about to exceed that limit, we're done.
567 if (MaxLineOffset && TokOffset >= MaxLineOffset)
571 // Comments are okay; skip over them.
572 if (TheTok.getKind() == tok::comment)
575 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
576 // This is the start of a preprocessor directive.
577 Token HashTok = TheTok;
578 InPreprocessorDirective = true;
580 // Figure out which directive this is. Since we're lexing raw tokens,
581 // we don't have an identifier table available. Instead, just look at
582 // the raw identifier to recognize and categorize preprocessor directives.
583 TheLexer.LexFromRawLexer(TheTok);
584 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
585 StringRef Keyword(TheTok.getRawIdentifierData(),
587 PreambleDirectiveKind PDK
588 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
589 .Case("include", PDK_Skipped)
590 .Case("__include_macros", PDK_Skipped)
591 .Case("define", PDK_Skipped)
592 .Case("undef", PDK_Skipped)
593 .Case("line", PDK_Skipped)
594 .Case("error", PDK_Skipped)
595 .Case("pragma", PDK_Skipped)
596 .Case("import", PDK_Skipped)
597 .Case("include_next", PDK_Skipped)
598 .Case("warning", PDK_Skipped)
599 .Case("ident", PDK_Skipped)
600 .Case("sccs", PDK_Skipped)
601 .Case("assert", PDK_Skipped)
602 .Case("unassert", PDK_Skipped)
603 .Case("if", PDK_StartIf)
604 .Case("ifdef", PDK_StartIf)
605 .Case("ifndef", PDK_StartIf)
606 .Case("elif", PDK_Skipped)
607 .Case("else", PDK_Skipped)
608 .Case("endif", PDK_EndIf)
609 .Default(PDK_Unknown);
617 IfStartTok = HashTok;
623 // Mismatched #endif. The preamble ends here.
631 // We don't know what this directive is; stop at the '#'.
636 // We only end up here if we didn't recognize the preprocessor
637 // directive or it was one that can't occur in the preamble at this
638 // point. Roll back the current token to the location of the '#'.
639 InPreprocessorDirective = false;
643 // We hit a token that we don't recognize as being in the
644 // "preprocessing only" part of the file, so we're no longer in
649 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
650 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
651 IfCount? IfStartTok.isAtStartOfLine()
652 : TheTok.isAtStartOfLine());
656 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
657 /// token, return a new location that specifies a character within the token.
658 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
660 const SourceManager &SM,
661 const LangOptions &LangOpts) {
662 // Figure out how many physical characters away the specified expansion
663 // character is. This needs to take into consideration newlines and
665 bool Invalid = false;
666 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
668 // If they request the first char of the token, we're trivially done.
669 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
672 unsigned PhysOffset = 0;
674 // The usual case is that tokens don't contain anything interesting. Skip
675 // over the uninteresting characters. If a token only consists of simple
676 // chars, this method is extremely fast.
677 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
679 return TokStart.getLocWithOffset(PhysOffset);
680 ++TokPtr, --CharNo, ++PhysOffset;
683 // If we have a character that may be a trigraph or escaped newline, use a
684 // lexer to parse it correctly.
685 for (; CharNo; --CharNo) {
687 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
692 // Final detail: if we end up on an escaped newline, we want to return the
693 // location of the actual byte of the token. For example foo\<newline>bar
694 // advanced by 3 should return the location of b, not of \\. One compounding
695 // detail of this is that the escape may be made by a trigraph.
696 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
697 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
699 return TokStart.getLocWithOffset(PhysOffset);
702 /// \brief Computes the source location just past the end of the
703 /// token at this source location.
705 /// This routine can be used to produce a source location that
706 /// points just past the end of the token referenced by \p Loc, and
707 /// is generally used when a diagnostic needs to point just after a
708 /// token where it expected something different that it received. If
709 /// the returned source location would not be meaningful (e.g., if
710 /// it points into a macro), this routine returns an invalid
713 /// \param Offset an offset from the end of the token, where the source
714 /// location should refer to. The default offset (0) produces a source
715 /// location pointing just past the end of the token; an offset of 1 produces
716 /// a source location pointing to the last character in the token, etc.
717 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
718 const SourceManager &SM,
719 const LangOptions &LangOpts) {
721 return SourceLocation();
723 if (Loc.isMacroID()) {
724 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
725 return SourceLocation(); // Points inside the macro expansion.
728 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
734 return Loc.getLocWithOffset(Len);
737 /// \brief Returns true if the given MacroID location points at the first
738 /// token of the macro expansion.
739 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
740 const SourceManager &SM,
741 const LangOptions &LangOpts,
742 SourceLocation *MacroBegin) {
743 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
745 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
746 // FIXME: If the token comes from the macro token paste operator ('##')
747 // this function will always return false;
748 if (infoLoc.second > 0)
749 return false; // Does not point at the start of token.
751 SourceLocation expansionLoc =
752 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
753 if (expansionLoc.isFileID()) {
754 // No other macro expansions, this is the first.
756 *MacroBegin = expansionLoc;
760 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
763 /// \brief Returns true if the given MacroID location points at the last
764 /// token of the macro expansion.
765 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
766 const SourceManager &SM,
767 const LangOptions &LangOpts,
768 SourceLocation *MacroEnd) {
769 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
771 SourceLocation spellLoc = SM.getSpellingLoc(loc);
772 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
776 FileID FID = SM.getFileID(loc);
777 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
778 if (SM.isInFileID(afterLoc, FID))
779 return false; // Still in the same FileID, does not point to the last token.
781 // FIXME: If the token comes from the macro token paste operator ('##')
782 // or the stringify operator ('#') this function will always return false;
784 SourceLocation expansionLoc =
785 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
786 if (expansionLoc.isFileID()) {
787 // No other macro expansions.
789 *MacroEnd = expansionLoc;
793 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
796 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
797 const SourceManager &SM,
798 const LangOptions &LangOpts) {
799 SourceLocation Begin = Range.getBegin();
800 SourceLocation End = Range.getEnd();
801 assert(Begin.isFileID() && End.isFileID());
802 if (Range.isTokenRange()) {
803 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
805 return CharSourceRange();
808 // Break down the source locations.
811 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
813 return CharSourceRange();
816 if (!SM.isInFileID(End, FID, &EndOffs) ||
818 return CharSourceRange();
820 return CharSourceRange::getCharRange(Begin, End);
823 /// \brief Accepts a range and returns a character range with file locations.
825 /// Returns a null range if a part of the range resides inside a macro
826 /// expansion or the range does not reside on the same FileID.
827 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
828 const SourceManager &SM,
829 const LangOptions &LangOpts) {
830 SourceLocation Begin = Range.getBegin();
831 SourceLocation End = Range.getEnd();
832 if (Begin.isInvalid() || End.isInvalid())
833 return CharSourceRange();
835 if (Begin.isFileID() && End.isFileID())
836 return makeRangeFromFileLocs(Range, SM, LangOpts);
838 if (Begin.isMacroID() && End.isFileID()) {
839 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
840 return CharSourceRange();
841 Range.setBegin(Begin);
842 return makeRangeFromFileLocs(Range, SM, LangOpts);
845 if (Begin.isFileID() && End.isMacroID()) {
846 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
848 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
850 return CharSourceRange();
852 return makeRangeFromFileLocs(Range, SM, LangOpts);
855 assert(Begin.isMacroID() && End.isMacroID());
856 SourceLocation MacroBegin, MacroEnd;
857 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
858 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
860 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
862 Range.setBegin(MacroBegin);
863 Range.setEnd(MacroEnd);
864 return makeRangeFromFileLocs(Range, SM, LangOpts);
869 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
871 return CharSourceRange();
874 if (!SM.isInFileID(End, FID, &EndOffs) ||
876 return CharSourceRange();
878 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
879 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
880 if (Expansion.isMacroArgExpansion() &&
881 Expansion.getSpellingLoc().isFileID()) {
882 SourceLocation SpellLoc = Expansion.getSpellingLoc();
883 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
884 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
885 return makeRangeFromFileLocs(Range, SM, LangOpts);
888 return CharSourceRange();
891 StringRef Lexer::getSourceText(CharSourceRange Range,
892 const SourceManager &SM,
893 const LangOptions &LangOpts,
895 Range = makeFileCharRange(Range, SM, LangOpts);
896 if (Range.isInvalid()) {
897 if (Invalid) *Invalid = true;
901 // Break down the source location.
902 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
903 if (beginInfo.first.isInvalid()) {
904 if (Invalid) *Invalid = true;
909 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
910 beginInfo.second > EndOffs) {
911 if (Invalid) *Invalid = true;
915 // Try to the load the file buffer.
916 bool invalidTemp = false;
917 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
919 if (Invalid) *Invalid = true;
923 if (Invalid) *Invalid = false;
924 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
927 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
928 const SourceManager &SM,
929 const LangOptions &LangOpts) {
930 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
932 // Find the location of the immediate macro expansion.
934 FileID FID = SM.getFileID(Loc);
935 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
936 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
937 Loc = Expansion.getExpansionLocStart();
938 if (!Expansion.isMacroArgExpansion())
941 // For macro arguments we need to check that the argument did not come
942 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
944 // Loc points to the argument id of the macro definition, move to the
946 Loc = SM.getImmediateExpansionRange(Loc).first;
947 SourceLocation SpellLoc = Expansion.getSpellingLoc();
948 if (SpellLoc.isFileID())
949 break; // No inner macro.
951 // If spelling location resides in the same FileID as macro expansion
952 // location, it means there is no inner macro.
953 FileID MacroFID = SM.getFileID(Loc);
954 if (SM.isInFileID(SpellLoc, MacroFID))
957 // Argument came from inner macro.
961 // Find the spelling location of the start of the non-argument expansion
962 // range. This is where the macro name was spelled in order to begin
963 // expanding this macro.
964 Loc = SM.getSpellingLoc(Loc);
966 // Dig out the buffer where the macro name was spelled and the extents of the
967 // name so that we can render it into the expansion note.
968 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
969 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
970 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
971 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
974 //===----------------------------------------------------------------------===//
975 // Character information.
976 //===----------------------------------------------------------------------===//
979 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
980 CHAR_VERT_WS = 0x02, // '\r', '\n'
981 CHAR_LETTER = 0x04, // a-z,A-Z
982 CHAR_NUMBER = 0x08, // 0-9
983 CHAR_UNDER = 0x10, // _
984 CHAR_PERIOD = 0x20, // .
985 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
988 // Statically initialize CharInfo table based on ASCII character set
989 // Reference: FreeBSD 7.2 /usr/share/misc/ascii
990 static const unsigned char CharInfo[256] =
992 // 0 NUL 1 SOH 2 STX 3 ETX
993 // 4 EOT 5 ENQ 6 ACK 7 BEL
996 // 8 BS 9 HT 10 NL 11 VT
997 //12 NP 13 CR 14 SO 15 SI
998 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
999 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
1000 //16 DLE 17 DC1 18 DC2 19 DC3
1001 //20 DC4 21 NAK 22 SYN 23 ETB
1004 //24 CAN 25 EM 26 SUB 27 ESC
1005 //28 FS 29 GS 30 RS 31 US
1008 //32 SP 33 ! 34 " 35 #
1009 //36 $ 37 % 38 & 39 '
1010 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1011 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1012 //40 ( 41 ) 42 * 43 +
1013 //44 , 45 - 46 . 47 /
1014 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
1015 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
1016 //48 0 49 1 50 2 51 3
1017 //52 4 53 5 54 6 55 7
1018 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1019 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1020 //56 8 57 9 58 : 59 ;
1021 //60 < 61 = 62 > 63 ?
1022 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
1023 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1024 //64 @ 65 A 66 B 67 C
1025 //68 D 69 E 70 F 71 G
1026 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1027 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1028 //72 H 73 I 74 J 75 K
1029 //76 L 77 M 78 N 79 O
1030 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1031 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1032 //80 P 81 Q 82 R 83 S
1033 //84 T 85 U 86 V 87 W
1034 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1035 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1036 //88 X 89 Y 90 Z 91 [
1037 //92 \ 93 ] 94 ^ 95 _
1038 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1039 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
1040 //96 ` 97 a 98 b 99 c
1041 //100 d 101 e 102 f 103 g
1042 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1043 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1044 //104 h 105 i 106 j 107 k
1045 //108 l 109 m 110 n 111 o
1046 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1047 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1048 //112 p 113 q 114 r 115 s
1049 //116 t 117 u 118 v 119 w
1050 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1051 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1052 //120 x 121 y 122 z 123 {
1053 //124 | 125 } 126 ~ 127 DEL
1054 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1055 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
1058 static void InitCharacterInfo() {
1059 static bool isInited = false;
1060 if (isInited) return;
1061 // check the statically-initialized CharInfo table
1062 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1063 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1064 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1065 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1066 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1067 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1068 assert(CHAR_UNDER == CharInfo[(int)'_']);
1069 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1070 for (unsigned i = 'a'; i <= 'z'; ++i) {
1071 assert(CHAR_LETTER == CharInfo[i]);
1072 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1074 for (unsigned i = '0'; i <= '9'; ++i)
1075 assert(CHAR_NUMBER == CharInfo[i]);
1081 /// isIdentifierHead - Return true if this is the first character of an
1082 /// identifier, which is [a-zA-Z_].
1083 static inline bool isIdentifierHead(unsigned char c) {
1084 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
1087 /// isIdentifierBody - Return true if this is the body character of an
1088 /// identifier, which is [a-zA-Z0-9_].
1089 static inline bool isIdentifierBody(unsigned char c) {
1090 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
1093 /// isHorizontalWhitespace - Return true if this character is horizontal
1094 /// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'.
1095 static inline bool isHorizontalWhitespace(unsigned char c) {
1096 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
1099 /// isVerticalWhitespace - Return true if this character is vertical
1100 /// whitespace: '\n', '\r'. Note that this returns false for '\0'.
1101 static inline bool isVerticalWhitespace(unsigned char c) {
1102 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1105 /// isWhitespace - Return true if this character is horizontal or vertical
1106 /// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false
1108 static inline bool isWhitespace(unsigned char c) {
1109 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
1112 /// isNumberBody - Return true if this is the body character of an
1113 /// preprocessing number, which is [a-zA-Z0-9_.].
1114 static inline bool isNumberBody(unsigned char c) {
1115 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
1119 /// isRawStringDelimBody - Return true if this is the body character of a
1120 /// raw string delimiter.
1121 static inline bool isRawStringDelimBody(unsigned char c) {
1122 return (CharInfo[c] &
1123 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1128 //===----------------------------------------------------------------------===//
1129 // Diagnostics forwarding code.
1130 //===----------------------------------------------------------------------===//
1132 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1133 /// lexer buffer was all expanded at a single point, perform the mapping.
1134 /// This is currently only used for _Pragma implementation, so it is the slow
1135 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1136 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1137 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1138 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1139 SourceLocation FileLoc,
1140 unsigned CharNo, unsigned TokLen) {
1141 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1143 // Otherwise, we're lexing "mapped tokens". This is used for things like
1144 // _Pragma handling. Combine the expansion location of FileLoc with the
1145 // spelling location.
1146 SourceManager &SM = PP.getSourceManager();
1148 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1149 // characters come from spelling(FileLoc)+Offset.
1150 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1151 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1153 // Figure out the expansion loc range, which is the range covered by the
1154 // original _Pragma(...) sequence.
1155 std::pair<SourceLocation,SourceLocation> II =
1156 SM.getImmediateExpansionRange(FileLoc);
1158 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1161 /// getSourceLocation - Return a source location identifier for the specified
1162 /// offset in the current file.
1163 SourceLocation Lexer::getSourceLocation(const char *Loc,
1164 unsigned TokLen) const {
1165 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1166 "Location out of range for this buffer!");
1168 // In the normal case, we're just lexing from a simple file buffer, return
1169 // the file id from FileLoc with the offset specified.
1170 unsigned CharNo = Loc-BufferStart;
1171 if (FileLoc.isFileID())
1172 return FileLoc.getLocWithOffset(CharNo);
1174 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1175 // tokens are lexed from where the _Pragma was defined.
1176 assert(PP && "This doesn't work on raw lexers");
1177 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1180 /// Diag - Forwarding function for diagnostics. This translate a source
1181 /// position in the current buffer into a SourceLocation object for rendering.
1182 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1183 return PP->Diag(getSourceLocation(Loc), DiagID);
1186 //===----------------------------------------------------------------------===//
1187 // Trigraph and Escaped Newline Handling Code.
1188 //===----------------------------------------------------------------------===//
1190 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1191 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1192 static char GetTrigraphCharForLetter(char Letter) {
1195 case '=': return '#';
1196 case ')': return ']';
1197 case '(': return '[';
1198 case '!': return '|';
1199 case '\'': return '^';
1200 case '>': return '}';
1201 case '/': return '\\';
1202 case '<': return '{';
1203 case '-': return '~';
1207 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1208 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1209 /// return the result character. Finally, emit a warning about trigraph use
1210 /// whether trigraphs are enabled or not.
1211 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1212 char Res = GetTrigraphCharForLetter(*CP);
1213 if (!Res || !L) return Res;
1215 if (!L->getLangOpts().Trigraphs) {
1216 if (!L->isLexingRawMode())
1217 L->Diag(CP-2, diag::trigraph_ignored);
1221 if (!L->isLexingRawMode())
1222 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1226 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1227 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1228 /// trigraph equivalent on entry to this function.
1229 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1231 while (isWhitespace(Ptr[Size])) {
1234 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1237 // If this is a \r\n or \n\r, skip the other half.
1238 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1239 Ptr[Size-1] != Ptr[Size])
1245 // Not an escaped newline, must be a \t or something else.
1249 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1250 /// them), skip over them and return the first non-escaped-newline found,
1251 /// otherwise return P.
1252 const char *Lexer::SkipEscapedNewLines(const char *P) {
1254 const char *AfterEscape;
1257 } else if (*P == '?') {
1258 // If not a trigraph for escape, bail out.
1259 if (P[1] != '?' || P[2] != '/')
1266 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1267 if (NewLineSize == 0) return P;
1268 P = AfterEscape+NewLineSize;
1272 /// \brief Checks that the given token is the first token that occurs after the
1273 /// given location (this excludes comments and whitespace). Returns the location
1274 /// immediately after the specified token. If the token is not found or the
1275 /// location is inside a macro, the returned source location will be invalid.
1276 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1277 tok::TokenKind TKind,
1278 const SourceManager &SM,
1279 const LangOptions &LangOpts,
1280 bool SkipTrailingWhitespaceAndNewLine) {
1281 if (Loc.isMacroID()) {
1282 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1283 return SourceLocation();
1285 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1287 // Break down the source location.
1288 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1290 // Try to load the file buffer.
1291 bool InvalidTemp = false;
1292 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1294 return SourceLocation();
1296 const char *TokenBegin = File.data() + LocInfo.second;
1298 // Lex from the start of the given location.
1299 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1300 TokenBegin, File.end());
1303 lexer.LexFromRawLexer(Tok);
1304 if (Tok.isNot(TKind))
1305 return SourceLocation();
1306 SourceLocation TokenLoc = Tok.getLocation();
1308 // Calculate how much whitespace needs to be skipped if any.
1309 unsigned NumWhitespaceChars = 0;
1310 if (SkipTrailingWhitespaceAndNewLine) {
1311 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1313 unsigned char C = *TokenEnd;
1314 while (isHorizontalWhitespace(C)) {
1316 NumWhitespaceChars++;
1318 if (isVerticalWhitespace(C))
1319 NumWhitespaceChars++;
1322 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1325 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1326 /// get its size, and return it. This is tricky in several cases:
1327 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1328 /// then either return the trigraph (skipping 3 chars) or the '?',
1329 /// depending on whether trigraphs are enabled or not.
1330 /// 2. If this is an escaped newline (potentially with whitespace between
1331 /// the backslash and newline), implicitly skip the newline and return
1332 /// the char after it.
1333 /// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1335 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1336 /// know that we can accumulate into Size, and that we have already incremented
1337 /// Ptr by Size bytes.
1339 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1340 /// be updated to match.
1342 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1344 // If we have a slash, look for an escaped newline.
1345 if (Ptr[0] == '\\') {
1349 // Common case, backslash-char where the char is not whitespace.
1350 if (!isWhitespace(Ptr[0])) return '\\';
1352 // See if we have optional whitespace characters between the slash and
1354 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1355 // Remember that this token needs to be cleaned.
1356 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1358 // Warn if there was whitespace between the backslash and newline.
1359 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1360 Diag(Ptr, diag::backslash_newline_space);
1362 // Found backslash<whitespace><newline>. Parse the char after it.
1363 Size += EscapedNewLineSize;
1364 Ptr += EscapedNewLineSize;
1366 // If the char that we finally got was a \n, then we must have had
1367 // something like \<newline><newline>. We don't want to consume the
1369 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1372 // Use slow version to accumulate a correct size field.
1373 return getCharAndSizeSlow(Ptr, Size, Tok);
1376 // Otherwise, this is not an escaped newline, just return the slash.
1380 // If this is a trigraph, process it.
1381 if (Ptr[0] == '?' && Ptr[1] == '?') {
1382 // If this is actually a legal trigraph (not something like "??x"), emit
1383 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1384 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1385 // Remember that this token needs to be cleaned.
1386 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1390 if (C == '\\') goto Slash;
1395 // If this is neither, return a single character.
1401 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1402 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1403 /// and that we have already incremented Ptr by Size bytes.
1405 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1406 /// be updated to match.
1407 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1408 const LangOptions &LangOpts) {
1409 // If we have a slash, look for an escaped newline.
1410 if (Ptr[0] == '\\') {
1414 // Common case, backslash-char where the char is not whitespace.
1415 if (!isWhitespace(Ptr[0])) return '\\';
1417 // See if we have optional whitespace characters followed by a newline.
1418 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1419 // Found backslash<whitespace><newline>. Parse the char after it.
1420 Size += EscapedNewLineSize;
1421 Ptr += EscapedNewLineSize;
1423 // If the char that we finally got was a \n, then we must have had
1424 // something like \<newline><newline>. We don't want to consume the
1426 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1429 // Use slow version to accumulate a correct size field.
1430 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1433 // Otherwise, this is not an escaped newline, just return the slash.
1437 // If this is a trigraph, process it.
1438 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1439 // If this is actually a legal trigraph (not something like "??x"), return
1441 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1444 if (C == '\\') goto Slash;
1449 // If this is neither, return a single character.
1454 //===----------------------------------------------------------------------===//
1455 // Helper methods for lexing.
1456 //===----------------------------------------------------------------------===//
1458 /// \brief Routine that indiscriminately skips bytes in the source file.
1459 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1461 if (BufferPtr > BufferEnd)
1462 BufferPtr = BufferEnd;
1463 IsAtStartOfLine = StartOfLine;
1466 void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1467 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1469 unsigned char C = *CurPtr++;
1470 while (isIdentifierBody(C))
1473 --CurPtr; // Back up over the skipped character.
1475 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1476 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1479 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1481 if (C != '\\' && C != '?' && (C != '$' || !LangOpts.DollarIdents)) {
1483 const char *IdStart = BufferPtr;
1484 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1485 Result.setRawIdentifierData(IdStart);
1487 // If we are in raw mode, return this identifier raw. There is no need to
1488 // look up identifier information or attempt to macro expand it.
1492 // Fill in Result.IdentifierInfo and update the token kind,
1493 // looking up the identifier in the identifier table.
1494 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1496 // Finally, now that we know we have an identifier, pass this off to the
1497 // preprocessor, which may macro expand it or something.
1498 if (II->isHandleIdentifierCase())
1499 PP->HandleIdentifier(Result);
1504 // Otherwise, $,\,? in identifier found. Enter slower path.
1506 C = getCharAndSize(CurPtr, Size);
1509 // If we hit a $ and they are not supported in identifiers, we are done.
1510 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1512 // Otherwise, emit a diagnostic and continue.
1513 if (!isLexingRawMode())
1514 Diag(CurPtr, diag::ext_dollar_in_identifier);
1515 CurPtr = ConsumeChar(CurPtr, Size, Result);
1516 C = getCharAndSize(CurPtr, Size);
1518 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1519 // Found end of identifier.
1520 goto FinishIdentifier;
1523 // Otherwise, this character is good, consume it.
1524 CurPtr = ConsumeChar(CurPtr, Size, Result);
1526 C = getCharAndSize(CurPtr, Size);
1527 while (isIdentifierBody(C)) { // FIXME: UCNs.
1528 CurPtr = ConsumeChar(CurPtr, Size, Result);
1529 C = getCharAndSize(CurPtr, Size);
1534 /// isHexaLiteral - Return true if Start points to a hex constant.
1535 /// in microsoft mode (where this is supposed to be several different tokens).
1536 static bool isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1538 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1541 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1542 return (C2 == 'x' || C2 == 'X');
1545 /// LexNumericConstant - Lex the remainder of a integer or floating point
1546 /// constant. From[-1] is the first character lexed. Return the end of the
1548 void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1550 char C = getCharAndSize(CurPtr, Size);
1552 while (isNumberBody(C)) { // FIXME: UCNs.
1553 CurPtr = ConsumeChar(CurPtr, Size, Result);
1555 C = getCharAndSize(CurPtr, Size);
1558 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1559 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1560 // If we are in Microsoft mode, don't continue if the constant is hex.
1561 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1562 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1563 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1566 // If we have a hex FP constant, continue.
1567 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p'))
1568 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1570 // Update the location of token as well as BufferPtr.
1571 const char *TokStart = BufferPtr;
1572 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1573 Result.setLiteralData(TokStart);
1576 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1577 /// in C++11, or warn on a ud-suffix in C++98.
1578 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
1579 assert(getLangOpts().CPlusPlus);
1581 // Maximally munch an identifier. FIXME: UCNs.
1583 char C = getCharAndSize(CurPtr, Size);
1584 if (isIdentifierHead(C)) {
1585 if (!getLangOpts().CPlusPlus0x) {
1586 if (!isLexingRawMode())
1588 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1589 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1590 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1594 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1595 // that does not start with an underscore is ill-formed. As a conforming
1596 // extension, we treat all such suffixes as if they had whitespace before
1599 if (!isLexingRawMode())
1600 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1601 diag::ext_ms_reserved_user_defined_literal :
1602 diag::ext_reserved_user_defined_literal)
1603 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1607 Result.setFlag(Token::HasUDSuffix);
1609 CurPtr = ConsumeChar(CurPtr, Size, Result);
1610 C = getCharAndSize(CurPtr, Size);
1611 } while (isIdentifierBody(C));
1616 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1617 /// either " or L" or u8" or u" or U".
1618 void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1619 tok::TokenKind Kind) {
1620 const char *NulCharacter = 0; // Does this string contain the \0 character?
1622 if (!isLexingRawMode() &&
1623 (Kind == tok::utf8_string_literal ||
1624 Kind == tok::utf16_string_literal ||
1625 Kind == tok::utf32_string_literal))
1626 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1628 char C = getAndAdvanceChar(CurPtr, Result);
1630 // Skip escaped characters. Escaped newlines will already be processed by
1631 // getAndAdvanceChar.
1633 C = getAndAdvanceChar(CurPtr, Result);
1635 if (C == '\n' || C == '\r' || // Newline.
1636 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1637 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1638 Diag(BufferPtr, diag::warn_unterminated_string);
1639 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1644 if (isCodeCompletionPoint(CurPtr-1)) {
1645 PP->CodeCompleteNaturalLanguage();
1646 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1647 return cutOffLexing();
1650 NulCharacter = CurPtr-1;
1652 C = getAndAdvanceChar(CurPtr, Result);
1655 // If we are in C++11, lex the optional ud-suffix.
1656 if (getLangOpts().CPlusPlus)
1657 CurPtr = LexUDSuffix(Result, CurPtr);
1659 // If a nul character existed in the string, warn about it.
1660 if (NulCharacter && !isLexingRawMode())
1661 Diag(NulCharacter, diag::null_in_string);
1663 // Update the location of the token as well as the BufferPtr instance var.
1664 const char *TokStart = BufferPtr;
1665 FormTokenWithChars(Result, CurPtr, Kind);
1666 Result.setLiteralData(TokStart);
1669 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1670 /// having lexed R", LR", u8R", uR", or UR".
1671 void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1672 tok::TokenKind Kind) {
1673 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1674 // Between the initial and final double quote characters of the raw string,
1675 // any transformations performed in phases 1 and 2 (trigraphs,
1676 // universal-character-names, and line splicing) are reverted.
1678 if (!isLexingRawMode())
1679 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1681 unsigned PrefixLen = 0;
1683 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1686 // If the last character was not a '(', then we didn't lex a valid delimiter.
1687 if (CurPtr[PrefixLen] != '(') {
1688 if (!isLexingRawMode()) {
1689 const char *PrefixEnd = &CurPtr[PrefixLen];
1690 if (PrefixLen == 16) {
1691 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1693 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1694 << StringRef(PrefixEnd, 1);
1698 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1699 // it's possible the '"' was intended to be part of the raw string, but
1700 // there's not much we can do about that.
1706 if (C == 0 && CurPtr-1 == BufferEnd) {
1712 FormTokenWithChars(Result, CurPtr, tok::unknown);
1716 // Save prefix and move CurPtr past it
1717 const char *Prefix = CurPtr;
1718 CurPtr += PrefixLen + 1; // skip over prefix and '('
1724 // Check for prefix match and closing quote.
1725 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1726 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1729 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1730 if (!isLexingRawMode())
1731 Diag(BufferPtr, diag::err_unterminated_raw_string)
1732 << StringRef(Prefix, PrefixLen);
1733 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1738 // If we are in C++11, lex the optional ud-suffix.
1739 if (getLangOpts().CPlusPlus)
1740 CurPtr = LexUDSuffix(Result, CurPtr);
1742 // Update the location of token as well as BufferPtr.
1743 const char *TokStart = BufferPtr;
1744 FormTokenWithChars(Result, CurPtr, Kind);
1745 Result.setLiteralData(TokStart);
1748 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1749 /// after having lexed the '<' character. This is used for #include filenames.
1750 void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1751 const char *NulCharacter = 0; // Does this string contain the \0 character?
1752 const char *AfterLessPos = CurPtr;
1753 char C = getAndAdvanceChar(CurPtr, Result);
1755 // Skip escaped characters.
1757 // Skip the escaped character.
1758 C = getAndAdvanceChar(CurPtr, Result);
1759 } else if (C == '\n' || C == '\r' || // Newline.
1760 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1761 isCodeCompletionPoint(CurPtr-1)))) {
1762 // If the filename is unterminated, then it must just be a lone <
1763 // character. Return this as such.
1764 FormTokenWithChars(Result, AfterLessPos, tok::less);
1766 } else if (C == 0) {
1767 NulCharacter = CurPtr-1;
1769 C = getAndAdvanceChar(CurPtr, Result);
1772 // If a nul character existed in the string, warn about it.
1773 if (NulCharacter && !isLexingRawMode())
1774 Diag(NulCharacter, diag::null_in_string);
1776 // Update the location of token as well as BufferPtr.
1777 const char *TokStart = BufferPtr;
1778 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1779 Result.setLiteralData(TokStart);
1783 /// LexCharConstant - Lex the remainder of a character constant, after having
1784 /// lexed either ' or L' or u' or U'.
1785 void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1786 tok::TokenKind Kind) {
1787 const char *NulCharacter = 0; // Does this character contain the \0 character?
1789 if (!isLexingRawMode() &&
1790 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1791 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1793 char C = getAndAdvanceChar(CurPtr, Result);
1795 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1796 Diag(BufferPtr, diag::err_empty_character);
1797 FormTokenWithChars(Result, CurPtr, tok::unknown);
1802 // Skip escaped characters.
1804 // Skip the escaped character.
1806 C = getAndAdvanceChar(CurPtr, Result);
1807 } else if (C == '\n' || C == '\r' || // Newline.
1808 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1809 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1810 Diag(BufferPtr, diag::warn_unterminated_char);
1811 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1813 } else if (C == 0) {
1814 if (isCodeCompletionPoint(CurPtr-1)) {
1815 PP->CodeCompleteNaturalLanguage();
1816 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1817 return cutOffLexing();
1820 NulCharacter = CurPtr-1;
1822 C = getAndAdvanceChar(CurPtr, Result);
1825 // If we are in C++11, lex the optional ud-suffix.
1826 if (getLangOpts().CPlusPlus)
1827 CurPtr = LexUDSuffix(Result, CurPtr);
1829 // If a nul character existed in the character, warn about it.
1830 if (NulCharacter && !isLexingRawMode())
1831 Diag(NulCharacter, diag::null_in_char);
1833 // Update the location of token as well as BufferPtr.
1834 const char *TokStart = BufferPtr;
1835 FormTokenWithChars(Result, CurPtr, Kind);
1836 Result.setLiteralData(TokStart);
1839 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1840 /// Update BufferPtr to point to the next non-whitespace character and return.
1842 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1844 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
1845 // Whitespace - Skip it, then return the token after the whitespace.
1846 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1848 // Skip horizontal whitespace very aggressively.
1849 while (isHorizontalWhitespace(Char))
1852 // Otherwise if we have something other than whitespace, we're done.
1853 if (Char != '\n' && Char != '\r')
1856 if (ParsingPreprocessorDirective) {
1857 // End of preprocessor directive line, let LexTokenInternal handle this.
1862 // ok, but handle newline.
1863 // The returned token is at the start of the line.
1864 Result.setFlag(Token::StartOfLine);
1865 // No leading whitespace seen so far.
1866 Result.clearFlag(Token::LeadingSpace);
1870 // If this isn't immediately after a newline, there is leading space.
1871 char PrevChar = CurPtr[-1];
1872 if (PrevChar != '\n' && PrevChar != '\r')
1873 Result.setFlag(Token::LeadingSpace);
1875 // If the client wants us to return whitespace, return it now.
1876 if (isKeepWhitespaceMode()) {
1877 FormTokenWithChars(Result, CurPtr, tok::unknown);
1885 // SkipBCPLComment - We have just read the // characters from input. Skip until
1886 // we find the newline character thats terminate the comment. Then update
1887 /// BufferPtr and return.
1889 /// If we're in KeepCommentMode or any CommentHandler has inserted
1890 /// some tokens, this will store the first token and return true.
1891 bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) {
1892 // If BCPL comments aren't explicitly enabled for this language, emit an
1893 // extension warning.
1894 if (!LangOpts.BCPLComment && !isLexingRawMode()) {
1895 Diag(BufferPtr, diag::ext_bcpl_comment);
1897 // Mark them enabled so we only emit one warning for this translation
1899 LangOpts.BCPLComment = true;
1902 // Scan over the body of the comment. The common case, when scanning, is that
1903 // the comment contains normal ascii characters with nothing interesting in
1904 // them. As such, optimize for this case with the inner loop.
1908 // Skip over characters in the fast loop.
1909 while (C != 0 && // Potentially EOF.
1910 C != '\n' && C != '\r') // Newline or DOS-style newline.
1913 const char *NextLine = CurPtr;
1915 // We found a newline, see if it's escaped.
1916 const char *EscapePtr = CurPtr-1;
1917 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1920 if (*EscapePtr == '\\') // Escaped newline.
1922 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1923 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1924 CurPtr = EscapePtr-2;
1926 break; // This is a newline, we're done.
1931 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
1932 // properly decode the character. Read it in raw mode to avoid emitting
1933 // diagnostics about things like trigraphs. If we see an escaped newline,
1934 // we'll handle it below.
1935 const char *OldPtr = CurPtr;
1936 bool OldRawMode = isLexingRawMode();
1937 LexingRawMode = true;
1938 C = getAndAdvanceChar(CurPtr, Result);
1939 LexingRawMode = OldRawMode;
1941 // If we only read only one character, then no special handling is needed.
1942 // We're done and can skip forward to the newline.
1943 if (C != 0 && CurPtr == OldPtr+1) {
1948 // If we read multiple characters, and one of those characters was a \r or
1949 // \n, then we had an escaped newline within the comment. Emit diagnostic
1950 // unless the next line is also a // comment.
1951 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1952 for (; OldPtr != CurPtr; ++OldPtr)
1953 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1954 // Okay, we found a // comment that ends in a newline, if the next
1955 // line is also a // comment, but has spaces, don't emit a diagnostic.
1956 if (isWhitespace(C)) {
1957 const char *ForwardPtr = CurPtr;
1958 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
1960 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1964 if (!isLexingRawMode())
1965 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment);
1970 if (CurPtr == BufferEnd+1) {
1975 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1976 PP->CodeCompleteNaturalLanguage();
1981 } while (C != '\n' && C != '\r');
1983 // Found but did not consume the newline. Notify comment handlers about the
1984 // comment unless we're in a #if 0 block.
1985 if (PP && !isLexingRawMode() &&
1986 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
1987 getSourceLocation(CurPtr)))) {
1989 return true; // A token has to be returned.
1992 // If we are returning comments as tokens, return this comment as a token.
1993 if (inKeepCommentMode())
1994 return SaveBCPLComment(Result, CurPtr);
1996 // If we are inside a preprocessor directive and we see the end of line,
1997 // return immediately, so that the lexer can return this as an EOD token.
1998 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2003 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2004 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2005 // contribute to another token), it isn't needed for correctness. Note that
2006 // this is ok even in KeepWhitespaceMode, because we would have returned the
2007 /// comment above in that mode.
2010 // The next returned token is at the start of the line.
2011 Result.setFlag(Token::StartOfLine);
2012 // No leading whitespace seen so far.
2013 Result.clearFlag(Token::LeadingSpace);
2018 /// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in
2019 /// an appropriate way and return it.
2020 bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) {
2021 // If we're not in a preprocessor directive, just return the // comment
2023 FormTokenWithChars(Result, CurPtr, tok::comment);
2025 if (!ParsingPreprocessorDirective)
2028 // If this BCPL-style comment is in a macro definition, transmogrify it into
2029 // a C-style block comment.
2030 bool Invalid = false;
2031 std::string Spelling = PP->getSpelling(Result, &Invalid);
2035 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?");
2036 Spelling[1] = '*'; // Change prefix to "/*".
2037 Spelling += "*/"; // add suffix.
2039 Result.setKind(tok::comment);
2040 PP->CreateString(&Spelling[0], Spelling.size(), Result,
2041 Result.getLocation(), Result.getLocation());
2045 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2046 /// character (either \n or \r) is part of an escaped newline sequence. Issue a
2047 /// diagnostic if so. We know that the newline is inside of a block comment.
2048 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2050 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2052 // Back up off the newline.
2055 // If this is a two-character newline sequence, skip the other character.
2056 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2057 // \n\n or \r\r -> not escaped newline.
2058 if (CurPtr[0] == CurPtr[1])
2060 // \n\r or \r\n -> skip the newline.
2064 // If we have horizontal whitespace, skip over it. We allow whitespace
2065 // between the slash and newline.
2066 bool HasSpace = false;
2067 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2072 // If we have a slash, we know this is an escaped newline.
2073 if (*CurPtr == '\\') {
2074 if (CurPtr[-1] != '*') return false;
2076 // It isn't a slash, is it the ?? / trigraph?
2077 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2081 // This is the trigraph ending the comment. Emit a stern warning!
2084 // If no trigraphs are enabled, warn that we ignored this trigraph and
2085 // ignore this * character.
2086 if (!L->getLangOpts().Trigraphs) {
2087 if (!L->isLexingRawMode())
2088 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2091 if (!L->isLexingRawMode())
2092 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2095 // Warn about having an escaped newline between the */ characters.
2096 if (!L->isLexingRawMode())
2097 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2099 // If there was space between the backslash and newline, warn about it.
2100 if (HasSpace && !L->isLexingRawMode())
2101 L->Diag(CurPtr, diag::backslash_newline_space);
2107 #include <emmintrin.h>
2109 #include <altivec.h>
2113 /// SkipBlockComment - We have just read the /* characters from input. Read
2114 /// until we find the */ characters that terminate the comment. Note that we
2115 /// don't bother decoding trigraphs or escaped newlines in block comments,
2116 /// because they cannot cause the comment to end. The only thing that can
2117 /// happen is the comment could end with an escaped newline between the */ end
2120 /// If we're in KeepCommentMode or any CommentHandler has inserted
2121 /// some tokens, this will store the first token and return true.
2122 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
2123 // Scan one character past where we should, looking for a '/' character. Once
2124 // we find it, check to see if it was preceded by a *. This common
2125 // optimization helps people who like to put a lot of * characters in their
2128 // The first character we get with newlines and trigraphs skipped to handle
2129 // the degenerate /*/ case below correctly if the * has an escaped newline
2132 unsigned char C = getCharAndSize(CurPtr, CharSize);
2134 if (C == 0 && CurPtr == BufferEnd+1) {
2135 if (!isLexingRawMode())
2136 Diag(BufferPtr, diag::err_unterminated_block_comment);
2139 // KeepWhitespaceMode should return this broken comment as a token. Since
2140 // it isn't a well formed comment, just return it as an 'unknown' token.
2141 if (isKeepWhitespaceMode()) {
2142 FormTokenWithChars(Result, CurPtr, tok::unknown);
2150 // Check to see if the first character after the '/*' is another /. If so,
2151 // then this slash does not end the block comment, it is part of it.
2156 // Skip over all non-interesting characters until we find end of buffer or a
2157 // (probably ending) '/' character.
2158 if (CurPtr + 24 < BufferEnd &&
2159 // If there is a code-completion point avoid the fast scan because it
2160 // doesn't check for '\0'.
2161 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2162 // While not aligned to a 16-byte boundary.
2163 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2166 if (C == '/') goto FoundSlash;
2169 __m128i Slashes = _mm_set1_epi8('/');
2170 while (CurPtr+16 <= BufferEnd) {
2171 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes));
2173 // Adjust the pointer to point directly after the first slash. It's
2174 // not necessary to set C here, it will be overwritten at the end of
2176 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
2182 __vector unsigned char Slashes = {
2183 '/', '/', '/', '/', '/', '/', '/', '/',
2184 '/', '/', '/', '/', '/', '/', '/', '/'
2186 while (CurPtr+16 <= BufferEnd &&
2187 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2190 // Scan for '/' quickly. Many block comments are very large.
2191 while (CurPtr[0] != '/' &&
2195 CurPtr+4 < BufferEnd) {
2200 // It has to be one of the bytes scanned, increment to it and read one.
2204 // Loop to scan the remainder.
2205 while (C != '/' && C != '\0')
2210 if (CurPtr[-2] == '*') // We found the final */. We're done!
2213 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2214 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2215 // We found the final */, though it had an escaped newline between the
2216 // * and /. We're done!
2220 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2221 // If this is a /* inside of the comment, emit a warning. Don't do this
2222 // if this is a /*/, which will end the comment. This misses cases with
2223 // embedded escaped newlines, but oh well.
2224 if (!isLexingRawMode())
2225 Diag(CurPtr-1, diag::warn_nested_block_comment);
2227 } else if (C == 0 && CurPtr == BufferEnd+1) {
2228 if (!isLexingRawMode())
2229 Diag(BufferPtr, diag::err_unterminated_block_comment);
2230 // Note: the user probably forgot a */. We could continue immediately
2231 // after the /*, but this would involve lexing a lot of what really is the
2232 // comment, which surely would confuse the parser.
2235 // KeepWhitespaceMode should return this broken comment as a token. Since
2236 // it isn't a well formed comment, just return it as an 'unknown' token.
2237 if (isKeepWhitespaceMode()) {
2238 FormTokenWithChars(Result, CurPtr, tok::unknown);
2244 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2245 PP->CodeCompleteNaturalLanguage();
2253 // Notify comment handlers about the comment unless we're in a #if 0 block.
2254 if (PP && !isLexingRawMode() &&
2255 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2256 getSourceLocation(CurPtr)))) {
2258 return true; // A token has to be returned.
2261 // If we are returning comments as tokens, return this comment as a token.
2262 if (inKeepCommentMode()) {
2263 FormTokenWithChars(Result, CurPtr, tok::comment);
2267 // It is common for the tokens immediately after a /**/ comment to be
2268 // whitespace. Instead of going through the big switch, handle it
2269 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2270 // have already returned above with the comment as a token.
2271 if (isHorizontalWhitespace(*CurPtr)) {
2272 Result.setFlag(Token::LeadingSpace);
2273 SkipWhitespace(Result, CurPtr+1);
2277 // Otherwise, just return so that the next character will be lexed as a token.
2279 Result.setFlag(Token::LeadingSpace);
2283 //===----------------------------------------------------------------------===//
2284 // Primary Lexing Entry Points
2285 //===----------------------------------------------------------------------===//
2287 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2288 /// uninterpreted string. This switches the lexer out of directive mode.
2289 std::string Lexer::ReadToEndOfLine() {
2290 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2291 "Must be in a preprocessing directive!");
2295 // CurPtr - Cache BufferPtr in an automatic variable.
2296 const char *CurPtr = BufferPtr;
2298 char Char = getAndAdvanceChar(CurPtr, Tmp);
2304 // Found end of file?
2305 if (CurPtr-1 != BufferEnd) {
2306 if (isCodeCompletionPoint(CurPtr-1)) {
2307 PP->CodeCompleteNaturalLanguage();
2312 // Nope, normal character, continue.
2319 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2320 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2321 BufferPtr = CurPtr-1;
2323 // Next, lex the character, which should handle the EOD transition.
2325 if (Tmp.is(tok::code_completion)) {
2327 PP->CodeCompleteNaturalLanguage();
2330 assert(Tmp.is(tok::eod) && "Unexpected token!");
2332 // Finally, we're done, return the string we found.
2338 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2339 /// condition, reporting diagnostics and handling other edge cases as required.
2340 /// This returns true if Result contains a token, false if PP.Lex should be
2342 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2343 // If we hit the end of the file while parsing a preprocessor directive,
2344 // end the preprocessor directive first. The next token returned will
2345 // then be the end of file.
2346 if (ParsingPreprocessorDirective) {
2347 // Done parsing the "line".
2348 ParsingPreprocessorDirective = false;
2349 // Update the location of token as well as BufferPtr.
2350 FormTokenWithChars(Result, CurPtr, tok::eod);
2352 // Restore comment saving mode, in case it was disabled for directive.
2353 SetCommentRetentionState(PP->getCommentRetentionState());
2354 return true; // Have a token.
2357 // If we are in raw mode, return this event as an EOF token. Let the caller
2358 // that put us in raw mode handle the event.
2359 if (isLexingRawMode()) {
2360 Result.startToken();
2361 BufferPtr = BufferEnd;
2362 FormTokenWithChars(Result, BufferEnd, tok::eof);
2366 // Issue diagnostics for unterminated #if and missing newline.
2368 // If we are in a #if directive, emit an error.
2369 while (!ConditionalStack.empty()) {
2370 if (PP->getCodeCompletionFileLoc() != FileLoc)
2371 PP->Diag(ConditionalStack.back().IfLoc,
2372 diag::err_pp_unterminated_conditional);
2373 ConditionalStack.pop_back();
2376 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2378 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
2379 Diag(BufferEnd, LangOpts.CPlusPlus0x ? // C++11 [lex.phases] 2.2 p2
2380 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2381 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
2385 // Finally, let the preprocessor handle this.
2386 return PP->HandleEndOfFile(Result);
2389 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2390 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2391 /// else and 2 if there are no more tokens in the buffer controlled by the
2393 unsigned Lexer::isNextPPTokenLParen() {
2394 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2396 // Switch to 'skipping' mode. This will ensure that we can lex a token
2397 // without emitting diagnostics, disables macro expansion, and will cause EOF
2398 // to return an EOF token instead of popping the include stack.
2399 LexingRawMode = true;
2401 // Save state that can be changed while lexing so that we can restore it.
2402 const char *TmpBufferPtr = BufferPtr;
2403 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2407 LexTokenInternal(Tok);
2409 // Restore state that may have changed.
2410 BufferPtr = TmpBufferPtr;
2411 ParsingPreprocessorDirective = inPPDirectiveMode;
2413 // Restore the lexer back to non-skipping mode.
2414 LexingRawMode = false;
2416 if (Tok.is(tok::eof))
2418 return Tok.is(tok::l_paren);
2421 /// FindConflictEnd - Find the end of a version control conflict marker.
2422 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2423 ConflictMarkerKind CMK) {
2424 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2425 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2426 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2427 size_t Pos = RestOfBuffer.find(Terminator);
2428 while (Pos != StringRef::npos) {
2429 // Must occur at start of line.
2430 if (RestOfBuffer[Pos-1] != '\r' &&
2431 RestOfBuffer[Pos-1] != '\n') {
2432 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2433 Pos = RestOfBuffer.find(Terminator);
2436 return RestOfBuffer.data()+Pos;
2441 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2442 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2443 /// and recover nicely. This returns true if it is a conflict marker and false
2445 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2446 // Only a conflict marker if it starts at the beginning of a line.
2447 if (CurPtr != BufferStart &&
2448 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2451 // Check to see if we have <<<<<<< or >>>>.
2452 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2453 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
2456 // If we have a situation where we don't care about conflict markers, ignore
2458 if (CurrentConflictMarkerState || isLexingRawMode())
2461 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2463 // Check to see if there is an ending marker somewhere in the buffer at the
2464 // start of a line to terminate this conflict marker.
2465 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2466 // We found a match. We are really in a conflict marker.
2467 // Diagnose this, and ignore to the end of line.
2468 Diag(CurPtr, diag::err_conflict_marker);
2469 CurrentConflictMarkerState = Kind;
2471 // Skip ahead to the end of line. We know this exists because the
2472 // end-of-conflict marker starts with \r or \n.
2473 while (*CurPtr != '\r' && *CurPtr != '\n') {
2474 assert(CurPtr != BufferEnd && "Didn't find end of line");
2481 // No end of conflict marker found.
2486 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2487 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2488 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2489 /// the line. This returns true if it is a conflict marker and false if not.
2490 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2491 // Only a conflict marker if it starts at the beginning of a line.
2492 if (CurPtr != BufferStart &&
2493 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2496 // If we have a situation where we don't care about conflict markers, ignore
2498 if (!CurrentConflictMarkerState || isLexingRawMode())
2501 // Check to see if we have the marker (4 characters in a row).
2502 for (unsigned i = 1; i != 4; ++i)
2503 if (CurPtr[i] != CurPtr[0])
2506 // If we do have it, search for the end of the conflict marker. This could
2507 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2508 // be the end of conflict marker.
2509 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2510 CurrentConflictMarkerState)) {
2513 // Skip ahead to the end of line.
2514 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2519 // No longer in the conflict marker.
2520 CurrentConflictMarkerState = CMK_None;
2527 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2528 if (PP && PP->isCodeCompletionEnabled()) {
2529 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2530 return Loc == PP->getCodeCompletionLoc();
2537 /// LexTokenInternal - This implements a simple C family lexer. It is an
2538 /// extremely performance critical piece of code. This assumes that the buffer
2539 /// has a null character at the end of the file. This returns a preprocessing
2540 /// token, not a normal token, as such, it is an internal interface. It assumes
2541 /// that the Flags of result have been cleared before calling this.
2542 void Lexer::LexTokenInternal(Token &Result) {
2544 // New token, can't need cleaning yet.
2545 Result.clearFlag(Token::NeedsCleaning);
2546 Result.setIdentifierInfo(0);
2548 // CurPtr - Cache BufferPtr in an automatic variable.
2549 const char *CurPtr = BufferPtr;
2551 // Small amounts of horizontal whitespace is very common between tokens.
2552 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2554 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2557 // If we are keeping whitespace and other tokens, just return what we just
2558 // skipped. The next lexer invocation will return the token after the
2560 if (isKeepWhitespaceMode()) {
2561 FormTokenWithChars(Result, CurPtr, tok::unknown);
2566 Result.setFlag(Token::LeadingSpace);
2569 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
2571 // Read a character, advancing over it.
2572 char Char = getAndAdvanceChar(CurPtr, Result);
2573 tok::TokenKind Kind;
2577 // Found end of file?
2578 if (CurPtr-1 == BufferEnd) {
2579 // Read the PP instance variable into an automatic variable, because
2580 // LexEndOfFile will often delete 'this'.
2581 Preprocessor *PPCache = PP;
2582 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2583 return; // Got a token to return.
2584 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2585 return PPCache->Lex(Result);
2588 // Check if we are performing code completion.
2589 if (isCodeCompletionPoint(CurPtr-1)) {
2590 // Return the code-completion token.
2591 Result.startToken();
2592 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2596 if (!isLexingRawMode())
2597 Diag(CurPtr-1, diag::null_in_file);
2598 Result.setFlag(Token::LeadingSpace);
2599 if (SkipWhitespace(Result, CurPtr))
2600 return; // KeepWhitespaceMode
2602 goto LexNextToken; // GCC isn't tail call eliminating.
2604 case 26: // DOS & CP/M EOF: "^Z".
2605 // If we're in Microsoft extensions mode, treat this as end of file.
2606 if (LangOpts.MicrosoftExt) {
2607 // Read the PP instance variable into an automatic variable, because
2608 // LexEndOfFile will often delete 'this'.
2609 Preprocessor *PPCache = PP;
2610 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2611 return; // Got a token to return.
2612 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2613 return PPCache->Lex(Result);
2615 // If Microsoft extensions are disabled, this is just random garbage.
2616 Kind = tok::unknown;
2621 // If we are inside a preprocessor directive and we see the end of line,
2622 // we know we are done with the directive, so return an EOD token.
2623 if (ParsingPreprocessorDirective) {
2624 // Done parsing the "line".
2625 ParsingPreprocessorDirective = false;
2627 // Restore comment saving mode, in case it was disabled for directive.
2628 SetCommentRetentionState(PP->getCommentRetentionState());
2630 // Since we consumed a newline, we are back at the start of a line.
2631 IsAtStartOfLine = true;
2636 // The returned token is at the start of the line.
2637 Result.setFlag(Token::StartOfLine);
2638 // No leading whitespace seen so far.
2639 Result.clearFlag(Token::LeadingSpace);
2641 if (SkipWhitespace(Result, CurPtr))
2642 return; // KeepWhitespaceMode
2643 goto LexNextToken; // GCC isn't tail call eliminating.
2648 SkipHorizontalWhitespace:
2649 Result.setFlag(Token::LeadingSpace);
2650 if (SkipWhitespace(Result, CurPtr))
2651 return; // KeepWhitespaceMode
2656 // If the next token is obviously a // or /* */ comment, skip it efficiently
2657 // too (without going through the big switch stmt).
2658 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
2659 LangOpts.BCPLComment && !LangOpts.TraditionalCPP) {
2660 if (SkipBCPLComment(Result, CurPtr+2))
2661 return; // There is a token to return.
2662 goto SkipIgnoredUnits;
2663 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
2664 if (SkipBlockComment(Result, CurPtr+2))
2665 return; // There is a token to return.
2666 goto SkipIgnoredUnits;
2667 } else if (isHorizontalWhitespace(*CurPtr)) {
2668 goto SkipHorizontalWhitespace;
2670 goto LexNextToken; // GCC isn't tail call eliminating.
2672 // C99 6.4.4.1: Integer Constants.
2673 // C99 6.4.4.2: Floating Constants.
2674 case '0': case '1': case '2': case '3': case '4':
2675 case '5': case '6': case '7': case '8': case '9':
2676 // Notify MIOpt that we read a non-whitespace/non-comment token.
2678 return LexNumericConstant(Result, CurPtr);
2680 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2681 // Notify MIOpt that we read a non-whitespace/non-comment token.
2684 if (LangOpts.CPlusPlus0x) {
2685 Char = getCharAndSize(CurPtr, SizeTmp);
2687 // UTF-16 string literal
2689 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2690 tok::utf16_string_literal);
2692 // UTF-16 character constant
2694 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2695 tok::utf16_char_constant);
2697 // UTF-16 raw string literal
2698 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2699 return LexRawStringLiteral(Result,
2700 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2702 tok::utf16_string_literal);
2705 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2707 // UTF-8 string literal
2709 return LexStringLiteral(Result,
2710 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2712 tok::utf8_string_literal);
2716 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2717 // UTF-8 raw string literal
2719 return LexRawStringLiteral(Result,
2720 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2723 tok::utf8_string_literal);
2729 // treat u like the start of an identifier.
2730 return LexIdentifier(Result, CurPtr);
2732 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2733 // Notify MIOpt that we read a non-whitespace/non-comment token.
2736 if (LangOpts.CPlusPlus0x) {
2737 Char = getCharAndSize(CurPtr, SizeTmp);
2739 // UTF-32 string literal
2741 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2742 tok::utf32_string_literal);
2744 // UTF-32 character constant
2746 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2747 tok::utf32_char_constant);
2749 // UTF-32 raw string literal
2750 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2751 return LexRawStringLiteral(Result,
2752 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2754 tok::utf32_string_literal);
2757 // treat U like the start of an identifier.
2758 return LexIdentifier(Result, CurPtr);
2760 case 'R': // Identifier or C++0x raw string literal
2761 // Notify MIOpt that we read a non-whitespace/non-comment token.
2764 if (LangOpts.CPlusPlus0x) {
2765 Char = getCharAndSize(CurPtr, SizeTmp);
2768 return LexRawStringLiteral(Result,
2769 ConsumeChar(CurPtr, SizeTmp, Result),
2770 tok::string_literal);
2773 // treat R like the start of an identifier.
2774 return LexIdentifier(Result, CurPtr);
2776 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
2777 // Notify MIOpt that we read a non-whitespace/non-comment token.
2779 Char = getCharAndSize(CurPtr, SizeTmp);
2781 // Wide string literal.
2783 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2784 tok::wide_string_literal);
2786 // Wide raw string literal.
2787 if (LangOpts.CPlusPlus0x && Char == 'R' &&
2788 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2789 return LexRawStringLiteral(Result,
2790 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2792 tok::wide_string_literal);
2794 // Wide character constant.
2796 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2797 tok::wide_char_constant);
2798 // FALL THROUGH, treating L like the start of an identifier.
2800 // C99 6.4.2: Identifiers.
2801 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2802 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
2803 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
2804 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2805 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2806 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
2807 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
2808 case 'v': case 'w': case 'x': case 'y': case 'z':
2810 // Notify MIOpt that we read a non-whitespace/non-comment token.
2812 return LexIdentifier(Result, CurPtr);
2814 case '$': // $ in identifiers.
2815 if (LangOpts.DollarIdents) {
2816 if (!isLexingRawMode())
2817 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
2818 // Notify MIOpt that we read a non-whitespace/non-comment token.
2820 return LexIdentifier(Result, CurPtr);
2823 Kind = tok::unknown;
2826 // C99 6.4.4: Character Constants.
2828 // Notify MIOpt that we read a non-whitespace/non-comment token.
2830 return LexCharConstant(Result, CurPtr, tok::char_constant);
2832 // C99 6.4.5: String Literals.
2834 // Notify MIOpt that we read a non-whitespace/non-comment token.
2836 return LexStringLiteral(Result, CurPtr, tok::string_literal);
2838 // C99 6.4.6: Punctuators.
2840 Kind = tok::question;
2843 Kind = tok::l_square;
2846 Kind = tok::r_square;
2849 Kind = tok::l_paren;
2852 Kind = tok::r_paren;
2855 Kind = tok::l_brace;
2858 Kind = tok::r_brace;
2861 Char = getCharAndSize(CurPtr, SizeTmp);
2862 if (Char >= '0' && Char <= '9') {
2863 // Notify MIOpt that we read a non-whitespace/non-comment token.
2866 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2867 } else if (LangOpts.CPlusPlus && Char == '*') {
2868 Kind = tok::periodstar;
2870 } else if (Char == '.' &&
2871 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
2872 Kind = tok::ellipsis;
2873 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2880 Char = getCharAndSize(CurPtr, SizeTmp);
2883 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2884 } else if (Char == '=') {
2885 Kind = tok::ampequal;
2886 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2892 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
2893 Kind = tok::starequal;
2894 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2900 Char = getCharAndSize(CurPtr, SizeTmp);
2902 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2903 Kind = tok::plusplus;
2904 } else if (Char == '=') {
2905 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2906 Kind = tok::plusequal;
2912 Char = getCharAndSize(CurPtr, SizeTmp);
2913 if (Char == '-') { // --
2914 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2915 Kind = tok::minusminus;
2916 } else if (Char == '>' && LangOpts.CPlusPlus &&
2917 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
2918 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2920 Kind = tok::arrowstar;
2921 } else if (Char == '>') { // ->
2922 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2924 } else if (Char == '=') { // -=
2925 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2926 Kind = tok::minusequal;
2935 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
2936 Kind = tok::exclaimequal;
2937 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2939 Kind = tok::exclaim;
2944 Char = getCharAndSize(CurPtr, SizeTmp);
2945 if (Char == '/') { // BCPL comment.
2946 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally
2947 // want to lex this as a comment. There is one problem with this though,
2948 // that in one particular corner case, this can change the behavior of the
2949 // resultant program. For example, In "foo //**/ bar", C89 would lex
2950 // this as "foo / bar" and langauges with BCPL comments would lex it as
2951 // "foo". Check to see if the character after the second slash is a '*'.
2952 // If so, we will lex that as a "/" instead of the start of a comment.
2953 // However, we never do this in -traditional-cpp mode.
2954 if ((LangOpts.BCPLComment ||
2955 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2956 !LangOpts.TraditionalCPP) {
2957 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
2958 return; // There is a token to return.
2960 // It is common for the tokens immediately after a // comment to be
2961 // whitespace (indentation for the next line). Instead of going through
2962 // the big switch, handle it efficiently now.
2963 goto SkipIgnoredUnits;
2967 if (Char == '*') { // /**/ comment.
2968 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
2969 return; // There is a token to return.
2970 goto LexNextToken; // GCC isn't tail call eliminating.
2974 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2975 Kind = tok::slashequal;
2981 Char = getCharAndSize(CurPtr, SizeTmp);
2983 Kind = tok::percentequal;
2984 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2985 } else if (LangOpts.Digraphs && Char == '>') {
2986 Kind = tok::r_brace; // '%>' -> '}'
2987 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2988 } else if (LangOpts.Digraphs && Char == ':') {
2989 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2990 Char = getCharAndSize(CurPtr, SizeTmp);
2991 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
2992 Kind = tok::hashhash; // '%:%:' -> '##'
2993 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2995 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
2996 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2997 if (!isLexingRawMode())
2998 Diag(BufferPtr, diag::ext_charize_microsoft);
3000 } else { // '%:' -> '#'
3001 // We parsed a # character. If this occurs at the start of the line,
3002 // it's actually the start of a preprocessing directive. Callback to
3003 // the preprocessor to handle it.
3004 // FIXME: -fpreprocessed mode??
3005 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
3006 FormTokenWithChars(Result, CurPtr, tok::hash);
3007 PP->HandleDirective(Result);
3009 // As an optimization, if the preprocessor didn't switch lexers, tail
3011 if (PP->isCurrentLexer(this)) {
3012 // Start a new token. If this is a #include or something, the PP may
3013 // want us starting at the beginning of the line again. If so, set
3014 // the StartOfLine flag and clear LeadingSpace.
3015 if (IsAtStartOfLine) {
3016 Result.setFlag(Token::StartOfLine);
3017 Result.clearFlag(Token::LeadingSpace);
3018 IsAtStartOfLine = false;
3020 goto LexNextToken; // GCC isn't tail call eliminating.
3023 return PP->Lex(Result);
3029 Kind = tok::percent;
3033 Char = getCharAndSize(CurPtr, SizeTmp);
3034 if (ParsingFilename) {
3035 return LexAngledStringLiteral(Result, CurPtr);
3036 } else if (Char == '<') {
3037 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3039 Kind = tok::lesslessequal;
3040 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3042 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3043 // If this is actually a '<<<<<<<' version control conflict marker,
3044 // recognize it as such and recover nicely.
3046 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3047 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3050 } else if (LangOpts.CUDA && After == '<') {
3051 Kind = tok::lesslessless;
3052 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3055 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3056 Kind = tok::lessless;
3058 } else if (Char == '=') {
3059 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3060 Kind = tok::lessequal;
3061 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3062 if (LangOpts.CPlusPlus0x &&
3063 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3064 // C++0x [lex.pptoken]p3:
3065 // Otherwise, if the next three characters are <:: and the subsequent
3066 // character is neither : nor >, the < is treated as a preprocessor
3067 // token by itself and not as the first character of the alternative
3070 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3071 if (After != ':' && After != '>') {
3073 if (!isLexingRawMode())
3074 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3079 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3080 Kind = tok::l_square;
3081 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3082 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3083 Kind = tok::l_brace;
3089 Char = getCharAndSize(CurPtr, SizeTmp);
3091 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3092 Kind = tok::greaterequal;
3093 } else if (Char == '>') {
3094 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3096 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3098 Kind = tok::greatergreaterequal;
3099 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3100 // If this is actually a '>>>>' conflict marker, recognize it as such
3101 // and recover nicely.
3103 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3104 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3106 } else if (LangOpts.CUDA && After == '>') {
3107 Kind = tok::greatergreatergreater;
3108 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3111 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3112 Kind = tok::greatergreater;
3116 Kind = tok::greater;
3120 Char = getCharAndSize(CurPtr, SizeTmp);
3122 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3123 Kind = tok::caretequal;
3129 Char = getCharAndSize(CurPtr, SizeTmp);
3131 Kind = tok::pipeequal;
3132 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3133 } else if (Char == '|') {
3134 // If this is '|||||||' and we're in a conflict marker, ignore it.
3135 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3137 Kind = tok::pipepipe;
3138 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3144 Char = getCharAndSize(CurPtr, SizeTmp);
3145 if (LangOpts.Digraphs && Char == '>') {
3146 Kind = tok::r_square; // ':>' -> ']'
3147 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3148 } else if (LangOpts.CPlusPlus && Char == ':') {
3149 Kind = tok::coloncolon;
3150 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3159 Char = getCharAndSize(CurPtr, SizeTmp);
3161 // If this is '====' and we're in a conflict marker, ignore it.
3162 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3165 Kind = tok::equalequal;
3166 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3175 Char = getCharAndSize(CurPtr, SizeTmp);
3177 Kind = tok::hashhash;
3178 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3179 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3181 if (!isLexingRawMode())
3182 Diag(BufferPtr, diag::ext_charize_microsoft);
3183 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3185 // We parsed a # character. If this occurs at the start of the line,
3186 // it's actually the start of a preprocessing directive. Callback to
3187 // the preprocessor to handle it.
3188 // FIXME: -fpreprocessed mode??
3189 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
3190 FormTokenWithChars(Result, CurPtr, tok::hash);
3191 PP->HandleDirective(Result);
3193 // As an optimization, if the preprocessor didn't switch lexers, tail
3195 if (PP->isCurrentLexer(this)) {
3196 // Start a new token. If this is a #include or something, the PP may
3197 // want us starting at the beginning of the line again. If so, set
3198 // the StartOfLine flag and clear LeadingSpace.
3199 if (IsAtStartOfLine) {
3200 Result.setFlag(Token::StartOfLine);
3201 Result.clearFlag(Token::LeadingSpace);
3202 IsAtStartOfLine = false;
3204 goto LexNextToken; // GCC isn't tail call eliminating.
3206 return PP->Lex(Result);
3214 // Objective C support.
3215 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3218 Kind = tok::unknown;
3225 Kind = tok::unknown;
3229 // Notify MIOpt that we read a non-whitespace/non-comment token.
3232 // Update the location of token as well as BufferPtr.
3233 FormTokenWithChars(Result, CurPtr, Kind);