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 'LexFromRawLexer'. 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 'LexFromRawLexer'. 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 FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
517 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
518 Buffer->getBufferStart(), Buffer->getBufferEnd());
520 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
521 SourceLocation StartLoc = TheLexer.getSourceLocation();
523 bool InPreprocessorDirective = false;
526 unsigned IfCount = 0;
528 unsigned MaxLineOffset = 0;
530 const char *CurPtr = Buffer->getBufferStart();
531 unsigned CurLine = 0;
532 while (CurPtr != Buffer->getBufferEnd()) {
536 if (CurLine == MaxLines)
540 if (CurPtr != Buffer->getBufferEnd())
541 MaxLineOffset = CurPtr - Buffer->getBufferStart();
545 TheLexer.LexFromRawLexer(TheTok);
547 if (InPreprocessorDirective) {
548 // If we've hit the end of the file, we're done.
549 if (TheTok.getKind() == tok::eof) {
553 // If we haven't hit the end of the preprocessor directive, skip this
555 if (!TheTok.isAtStartOfLine())
558 // We've passed the end of the preprocessor directive, and will look
559 // at this token again below.
560 InPreprocessorDirective = false;
563 // Keep track of the # of lines in the preamble.
564 if (TheTok.isAtStartOfLine()) {
565 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
567 // If we were asked to limit the number of lines in the preamble,
568 // and we're about to exceed that limit, we're done.
569 if (MaxLineOffset && TokOffset >= MaxLineOffset)
573 // Comments are okay; skip over them.
574 if (TheTok.getKind() == tok::comment)
577 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
578 // This is the start of a preprocessor directive.
579 Token HashTok = TheTok;
580 InPreprocessorDirective = true;
582 // Figure out which directive this is. Since we're lexing raw tokens,
583 // we don't have an identifier table available. Instead, just look at
584 // the raw identifier to recognize and categorize preprocessor directives.
585 TheLexer.LexFromRawLexer(TheTok);
586 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
587 StringRef Keyword(TheTok.getRawIdentifierData(),
589 PreambleDirectiveKind PDK
590 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
591 .Case("include", PDK_Skipped)
592 .Case("__include_macros", PDK_Skipped)
593 .Case("define", PDK_Skipped)
594 .Case("undef", PDK_Skipped)
595 .Case("line", PDK_Skipped)
596 .Case("error", PDK_Skipped)
597 .Case("pragma", PDK_Skipped)
598 .Case("import", PDK_Skipped)
599 .Case("include_next", PDK_Skipped)
600 .Case("warning", PDK_Skipped)
601 .Case("ident", PDK_Skipped)
602 .Case("sccs", PDK_Skipped)
603 .Case("assert", PDK_Skipped)
604 .Case("unassert", PDK_Skipped)
605 .Case("if", PDK_StartIf)
606 .Case("ifdef", PDK_StartIf)
607 .Case("ifndef", PDK_StartIf)
608 .Case("elif", PDK_Skipped)
609 .Case("else", PDK_Skipped)
610 .Case("endif", PDK_EndIf)
611 .Default(PDK_Unknown);
619 IfStartTok = HashTok;
625 // Mismatched #endif. The preamble ends here.
633 // We don't know what this directive is; stop at the '#'.
638 // We only end up here if we didn't recognize the preprocessor
639 // directive or it was one that can't occur in the preamble at this
640 // point. Roll back the current token to the location of the '#'.
641 InPreprocessorDirective = false;
645 // We hit a token that we don't recognize as being in the
646 // "preprocessing only" part of the file, so we're no longer in
651 SourceLocation End = IfCount? IfStartTok.getLocation() : TheTok.getLocation();
652 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
653 IfCount? IfStartTok.isAtStartOfLine()
654 : TheTok.isAtStartOfLine());
658 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
659 /// token, return a new location that specifies a character within the token.
660 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
662 const SourceManager &SM,
663 const LangOptions &LangOpts) {
664 // Figure out how many physical characters away the specified expansion
665 // character is. This needs to take into consideration newlines and
667 bool Invalid = false;
668 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
670 // If they request the first char of the token, we're trivially done.
671 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
674 unsigned PhysOffset = 0;
676 // The usual case is that tokens don't contain anything interesting. Skip
677 // over the uninteresting characters. If a token only consists of simple
678 // chars, this method is extremely fast.
679 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
681 return TokStart.getLocWithOffset(PhysOffset);
682 ++TokPtr, --CharNo, ++PhysOffset;
685 // If we have a character that may be a trigraph or escaped newline, use a
686 // lexer to parse it correctly.
687 for (; CharNo; --CharNo) {
689 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
694 // Final detail: if we end up on an escaped newline, we want to return the
695 // location of the actual byte of the token. For example foo\<newline>bar
696 // advanced by 3 should return the location of b, not of \\. One compounding
697 // detail of this is that the escape may be made by a trigraph.
698 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
699 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
701 return TokStart.getLocWithOffset(PhysOffset);
704 /// \brief Computes the source location just past the end of the
705 /// token at this source location.
707 /// This routine can be used to produce a source location that
708 /// points just past the end of the token referenced by \p Loc, and
709 /// is generally used when a diagnostic needs to point just after a
710 /// token where it expected something different that it received. If
711 /// the returned source location would not be meaningful (e.g., if
712 /// it points into a macro), this routine returns an invalid
715 /// \param Offset an offset from the end of the token, where the source
716 /// location should refer to. The default offset (0) produces a source
717 /// location pointing just past the end of the token; an offset of 1 produces
718 /// a source location pointing to the last character in the token, etc.
719 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
720 const SourceManager &SM,
721 const LangOptions &LangOpts) {
723 return SourceLocation();
725 if (Loc.isMacroID()) {
726 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
727 return SourceLocation(); // Points inside the macro expansion.
730 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
736 return Loc.getLocWithOffset(Len);
739 /// \brief Returns true if the given MacroID location points at the first
740 /// token of the macro expansion.
741 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
742 const SourceManager &SM,
743 const LangOptions &LangOpts,
744 SourceLocation *MacroBegin) {
745 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
747 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
748 // FIXME: If the token comes from the macro token paste operator ('##')
749 // this function will always return false;
750 if (infoLoc.second > 0)
751 return false; // Does not point at the start of token.
753 SourceLocation expansionLoc =
754 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
755 if (expansionLoc.isFileID()) {
756 // No other macro expansions, this is the first.
758 *MacroBegin = expansionLoc;
762 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
765 /// \brief Returns true if the given MacroID location points at the last
766 /// token of the macro expansion.
767 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
768 const SourceManager &SM,
769 const LangOptions &LangOpts,
770 SourceLocation *MacroEnd) {
771 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
773 SourceLocation spellLoc = SM.getSpellingLoc(loc);
774 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
778 FileID FID = SM.getFileID(loc);
779 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
780 if (SM.isInFileID(afterLoc, FID))
781 return false; // Still in the same FileID, does not point to the last token.
783 // FIXME: If the token comes from the macro token paste operator ('##')
784 // or the stringify operator ('#') this function will always return false;
786 SourceLocation expansionLoc =
787 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
788 if (expansionLoc.isFileID()) {
789 // No other macro expansions.
791 *MacroEnd = expansionLoc;
795 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
798 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
799 const SourceManager &SM,
800 const LangOptions &LangOpts) {
801 SourceLocation Begin = Range.getBegin();
802 SourceLocation End = Range.getEnd();
803 assert(Begin.isFileID() && End.isFileID());
804 if (Range.isTokenRange()) {
805 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
807 return CharSourceRange();
810 // Break down the source locations.
813 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
815 return CharSourceRange();
818 if (!SM.isInFileID(End, FID, &EndOffs) ||
820 return CharSourceRange();
822 return CharSourceRange::getCharRange(Begin, End);
825 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
826 const SourceManager &SM,
827 const LangOptions &LangOpts) {
828 SourceLocation Begin = Range.getBegin();
829 SourceLocation End = Range.getEnd();
830 if (Begin.isInvalid() || End.isInvalid())
831 return CharSourceRange();
833 if (Begin.isFileID() && End.isFileID())
834 return makeRangeFromFileLocs(Range, SM, LangOpts);
836 if (Begin.isMacroID() && End.isFileID()) {
837 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
838 return CharSourceRange();
839 Range.setBegin(Begin);
840 return makeRangeFromFileLocs(Range, SM, LangOpts);
843 if (Begin.isFileID() && End.isMacroID()) {
844 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
846 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
848 return CharSourceRange();
850 return makeRangeFromFileLocs(Range, SM, LangOpts);
853 assert(Begin.isMacroID() && End.isMacroID());
854 SourceLocation MacroBegin, MacroEnd;
855 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
856 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
858 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
860 Range.setBegin(MacroBegin);
861 Range.setEnd(MacroEnd);
862 return makeRangeFromFileLocs(Range, SM, LangOpts);
867 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
869 return CharSourceRange();
872 if (!SM.isInFileID(End, FID, &EndOffs) ||
874 return CharSourceRange();
876 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
877 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
878 if (Expansion.isMacroArgExpansion() &&
879 Expansion.getSpellingLoc().isFileID()) {
880 SourceLocation SpellLoc = Expansion.getSpellingLoc();
881 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
882 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
883 return makeRangeFromFileLocs(Range, SM, LangOpts);
886 return CharSourceRange();
889 StringRef Lexer::getSourceText(CharSourceRange Range,
890 const SourceManager &SM,
891 const LangOptions &LangOpts,
893 Range = makeFileCharRange(Range, SM, LangOpts);
894 if (Range.isInvalid()) {
895 if (Invalid) *Invalid = true;
899 // Break down the source location.
900 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
901 if (beginInfo.first.isInvalid()) {
902 if (Invalid) *Invalid = true;
907 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
908 beginInfo.second > EndOffs) {
909 if (Invalid) *Invalid = true;
913 // Try to the load the file buffer.
914 bool invalidTemp = false;
915 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
917 if (Invalid) *Invalid = true;
921 if (Invalid) *Invalid = false;
922 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
925 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
926 const SourceManager &SM,
927 const LangOptions &LangOpts) {
928 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
930 // Find the location of the immediate macro expansion.
932 FileID FID = SM.getFileID(Loc);
933 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
934 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
935 Loc = Expansion.getExpansionLocStart();
936 if (!Expansion.isMacroArgExpansion())
939 // For macro arguments we need to check that the argument did not come
940 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
942 // Loc points to the argument id of the macro definition, move to the
944 Loc = SM.getImmediateExpansionRange(Loc).first;
945 SourceLocation SpellLoc = Expansion.getSpellingLoc();
946 if (SpellLoc.isFileID())
947 break; // No inner macro.
949 // If spelling location resides in the same FileID as macro expansion
950 // location, it means there is no inner macro.
951 FileID MacroFID = SM.getFileID(Loc);
952 if (SM.isInFileID(SpellLoc, MacroFID))
955 // Argument came from inner macro.
959 // Find the spelling location of the start of the non-argument expansion
960 // range. This is where the macro name was spelled in order to begin
961 // expanding this macro.
962 Loc = SM.getSpellingLoc(Loc);
964 // Dig out the buffer where the macro name was spelled and the extents of the
965 // name so that we can render it into the expansion note.
966 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
967 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
968 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
969 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
972 //===----------------------------------------------------------------------===//
973 // Character information.
974 //===----------------------------------------------------------------------===//
977 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0'
978 CHAR_VERT_WS = 0x02, // '\r', '\n'
979 CHAR_LETTER = 0x04, // a-z,A-Z
980 CHAR_NUMBER = 0x08, // 0-9
981 CHAR_UNDER = 0x10, // _
982 CHAR_PERIOD = 0x20, // .
983 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"'
986 // Statically initialize CharInfo table based on ASCII character set
987 // Reference: FreeBSD 7.2 /usr/share/misc/ascii
988 static const unsigned char CharInfo[256] =
990 // 0 NUL 1 SOH 2 STX 3 ETX
991 // 4 EOT 5 ENQ 6 ACK 7 BEL
994 // 8 BS 9 HT 10 NL 11 VT
995 //12 NP 13 CR 14 SO 15 SI
996 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS,
997 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 ,
998 //16 DLE 17 DC1 18 DC2 19 DC3
999 //20 DC4 21 NAK 22 SYN 23 ETB
1002 //24 CAN 25 EM 26 SUB 27 ESC
1003 //28 FS 29 GS 30 RS 31 US
1006 //32 SP 33 ! 34 " 35 #
1007 //36 $ 37 % 38 & 39 '
1008 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1009 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1010 //40 ( 41 ) 42 * 43 +
1011 //44 , 45 - 46 . 47 /
1012 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL ,
1013 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL ,
1014 //48 0 49 1 50 2 51 3
1015 //52 4 53 5 54 6 55 7
1016 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1017 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER ,
1018 //56 8 57 9 58 : 59 ;
1019 //60 < 61 = 62 > 63 ?
1020 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL ,
1021 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL ,
1022 //64 @ 65 A 66 B 67 C
1023 //68 D 69 E 70 F 71 G
1024 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1025 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1026 //72 H 73 I 74 J 75 K
1027 //76 L 77 M 78 N 79 O
1028 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1029 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1030 //80 P 81 Q 82 R 83 S
1031 //84 T 85 U 86 V 87 W
1032 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1033 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1034 //88 X 89 Y 90 Z 91 [
1035 //92 \ 93 ] 94 ^ 95 _
1036 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1037 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER ,
1038 //96 ` 97 a 98 b 99 c
1039 //100 d 101 e 102 f 103 g
1040 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1041 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1042 //104 h 105 i 106 j 107 k
1043 //108 l 109 m 110 n 111 o
1044 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1045 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1046 //112 p 113 q 114 r 115 s
1047 //116 t 117 u 118 v 119 w
1048 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1049 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER ,
1050 //120 x 121 y 122 z 123 {
1051 //124 | 125 } 126 ~ 127 DEL
1052 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL ,
1053 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0
1056 static void InitCharacterInfo() {
1057 static bool isInited = false;
1058 if (isInited) return;
1059 // check the statically-initialized CharInfo table
1060 assert(CHAR_HORZ_WS == CharInfo[(int)' ']);
1061 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']);
1062 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']);
1063 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']);
1064 assert(CHAR_VERT_WS == CharInfo[(int)'\n']);
1065 assert(CHAR_VERT_WS == CharInfo[(int)'\r']);
1066 assert(CHAR_UNDER == CharInfo[(int)'_']);
1067 assert(CHAR_PERIOD == CharInfo[(int)'.']);
1068 for (unsigned i = 'a'; i <= 'z'; ++i) {
1069 assert(CHAR_LETTER == CharInfo[i]);
1070 assert(CHAR_LETTER == CharInfo[i+'A'-'a']);
1072 for (unsigned i = '0'; i <= '9'; ++i)
1073 assert(CHAR_NUMBER == CharInfo[i]);
1079 /// isIdentifierHead - Return true if this is the first character of an
1080 /// identifier, which is [a-zA-Z_].
1081 static inline bool isIdentifierHead(unsigned char c) {
1082 return (CharInfo[c] & (CHAR_LETTER|CHAR_UNDER)) ? true : false;
1085 /// isIdentifierBody - Return true if this is the body character of an
1086 /// identifier, which is [a-zA-Z0-9_].
1087 static inline bool isIdentifierBody(unsigned char c) {
1088 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false;
1091 /// isHorizontalWhitespace - Return true if this character is horizontal
1092 /// whitespace: ' ', '\\t', '\\f', '\\v'. Note that this returns false for
1094 static inline bool isHorizontalWhitespace(unsigned char c) {
1095 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false;
1098 /// isVerticalWhitespace - Return true if this character is vertical
1099 /// whitespace: '\\n', '\\r'. Note that this returns false for '\\0'.
1100 static inline bool isVerticalWhitespace(unsigned char c) {
1101 return (CharInfo[c] & CHAR_VERT_WS) ? true : false;
1104 /// isWhitespace - Return true if this character is horizontal or vertical
1105 /// whitespace: ' ', '\\t', '\\f', '\\v', '\\n', '\\r'. Note that this returns
1106 /// false for '\\0'.
1107 static inline bool isWhitespace(unsigned char c) {
1108 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false;
1111 /// isNumberBody - Return true if this is the body character of an
1112 /// preprocessing number, which is [a-zA-Z0-9_.].
1113 static inline bool isNumberBody(unsigned char c) {
1114 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ?
1118 /// isRawStringDelimBody - Return true if this is the body character of a
1119 /// raw string delimiter.
1120 static inline bool isRawStringDelimBody(unsigned char c) {
1121 return (CharInfo[c] &
1122 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ?
1126 // Allow external clients to make use of CharInfo.
1127 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1128 return isIdentifierBody(c) || (c == '$' && LangOpts.DollarIdents);
1132 //===----------------------------------------------------------------------===//
1133 // Diagnostics forwarding code.
1134 //===----------------------------------------------------------------------===//
1136 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1137 /// lexer buffer was all expanded at a single point, perform the mapping.
1138 /// This is currently only used for _Pragma implementation, so it is the slow
1139 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1140 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1141 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1142 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1143 SourceLocation FileLoc,
1144 unsigned CharNo, unsigned TokLen) {
1145 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1147 // Otherwise, we're lexing "mapped tokens". This is used for things like
1148 // _Pragma handling. Combine the expansion location of FileLoc with the
1149 // spelling location.
1150 SourceManager &SM = PP.getSourceManager();
1152 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1153 // characters come from spelling(FileLoc)+Offset.
1154 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1155 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1157 // Figure out the expansion loc range, which is the range covered by the
1158 // original _Pragma(...) sequence.
1159 std::pair<SourceLocation,SourceLocation> II =
1160 SM.getImmediateExpansionRange(FileLoc);
1162 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1165 /// getSourceLocation - Return a source location identifier for the specified
1166 /// offset in the current file.
1167 SourceLocation Lexer::getSourceLocation(const char *Loc,
1168 unsigned TokLen) const {
1169 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1170 "Location out of range for this buffer!");
1172 // In the normal case, we're just lexing from a simple file buffer, return
1173 // the file id from FileLoc with the offset specified.
1174 unsigned CharNo = Loc-BufferStart;
1175 if (FileLoc.isFileID())
1176 return FileLoc.getLocWithOffset(CharNo);
1178 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1179 // tokens are lexed from where the _Pragma was defined.
1180 assert(PP && "This doesn't work on raw lexers");
1181 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1184 /// Diag - Forwarding function for diagnostics. This translate a source
1185 /// position in the current buffer into a SourceLocation object for rendering.
1186 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1187 return PP->Diag(getSourceLocation(Loc), DiagID);
1190 //===----------------------------------------------------------------------===//
1191 // Trigraph and Escaped Newline Handling Code.
1192 //===----------------------------------------------------------------------===//
1194 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1195 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1196 static char GetTrigraphCharForLetter(char Letter) {
1199 case '=': return '#';
1200 case ')': return ']';
1201 case '(': return '[';
1202 case '!': return '|';
1203 case '\'': return '^';
1204 case '>': return '}';
1205 case '/': return '\\';
1206 case '<': return '{';
1207 case '-': return '~';
1211 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1212 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1213 /// return the result character. Finally, emit a warning about trigraph use
1214 /// whether trigraphs are enabled or not.
1215 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1216 char Res = GetTrigraphCharForLetter(*CP);
1217 if (!Res || !L) return Res;
1219 if (!L->getLangOpts().Trigraphs) {
1220 if (!L->isLexingRawMode())
1221 L->Diag(CP-2, diag::trigraph_ignored);
1225 if (!L->isLexingRawMode())
1226 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1230 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1231 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1232 /// trigraph equivalent on entry to this function.
1233 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1235 while (isWhitespace(Ptr[Size])) {
1238 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1241 // If this is a \r\n or \n\r, skip the other half.
1242 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1243 Ptr[Size-1] != Ptr[Size])
1249 // Not an escaped newline, must be a \t or something else.
1253 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1254 /// them), skip over them and return the first non-escaped-newline found,
1255 /// otherwise return P.
1256 const char *Lexer::SkipEscapedNewLines(const char *P) {
1258 const char *AfterEscape;
1261 } else if (*P == '?') {
1262 // If not a trigraph for escape, bail out.
1263 if (P[1] != '?' || P[2] != '/')
1270 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1271 if (NewLineSize == 0) return P;
1272 P = AfterEscape+NewLineSize;
1276 /// \brief Checks that the given token is the first token that occurs after the
1277 /// given location (this excludes comments and whitespace). Returns the location
1278 /// immediately after the specified token. If the token is not found or the
1279 /// location is inside a macro, the returned source location will be invalid.
1280 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1281 tok::TokenKind TKind,
1282 const SourceManager &SM,
1283 const LangOptions &LangOpts,
1284 bool SkipTrailingWhitespaceAndNewLine) {
1285 if (Loc.isMacroID()) {
1286 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1287 return SourceLocation();
1289 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1291 // Break down the source location.
1292 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1294 // Try to load the file buffer.
1295 bool InvalidTemp = false;
1296 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1298 return SourceLocation();
1300 const char *TokenBegin = File.data() + LocInfo.second;
1302 // Lex from the start of the given location.
1303 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1304 TokenBegin, File.end());
1307 lexer.LexFromRawLexer(Tok);
1308 if (Tok.isNot(TKind))
1309 return SourceLocation();
1310 SourceLocation TokenLoc = Tok.getLocation();
1312 // Calculate how much whitespace needs to be skipped if any.
1313 unsigned NumWhitespaceChars = 0;
1314 if (SkipTrailingWhitespaceAndNewLine) {
1315 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1317 unsigned char C = *TokenEnd;
1318 while (isHorizontalWhitespace(C)) {
1320 NumWhitespaceChars++;
1322 if (isVerticalWhitespace(C))
1323 NumWhitespaceChars++;
1326 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1329 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1330 /// get its size, and return it. This is tricky in several cases:
1331 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1332 /// then either return the trigraph (skipping 3 chars) or the '?',
1333 /// depending on whether trigraphs are enabled or not.
1334 /// 2. If this is an escaped newline (potentially with whitespace between
1335 /// the backslash and newline), implicitly skip the newline and return
1336 /// the char after it.
1337 /// 3. If this is a UCN, return it. FIXME: C++ UCN's?
1339 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1340 /// know that we can accumulate into Size, and that we have already incremented
1341 /// Ptr by Size bytes.
1343 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1344 /// be updated to match.
1346 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1348 // If we have a slash, look for an escaped newline.
1349 if (Ptr[0] == '\\') {
1353 // Common case, backslash-char where the char is not whitespace.
1354 if (!isWhitespace(Ptr[0])) return '\\';
1356 // See if we have optional whitespace characters between the slash and
1358 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1359 // Remember that this token needs to be cleaned.
1360 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1362 // Warn if there was whitespace between the backslash and newline.
1363 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1364 Diag(Ptr, diag::backslash_newline_space);
1366 // Found backslash<whitespace><newline>. Parse the char after it.
1367 Size += EscapedNewLineSize;
1368 Ptr += EscapedNewLineSize;
1370 // If the char that we finally got was a \n, then we must have had
1371 // something like \<newline><newline>. We don't want to consume the
1373 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1376 // Use slow version to accumulate a correct size field.
1377 return getCharAndSizeSlow(Ptr, Size, Tok);
1380 // Otherwise, this is not an escaped newline, just return the slash.
1384 // If this is a trigraph, process it.
1385 if (Ptr[0] == '?' && Ptr[1] == '?') {
1386 // If this is actually a legal trigraph (not something like "??x"), emit
1387 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1388 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1389 // Remember that this token needs to be cleaned.
1390 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1394 if (C == '\\') goto Slash;
1399 // If this is neither, return a single character.
1405 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1406 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1407 /// and that we have already incremented Ptr by Size bytes.
1409 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1410 /// be updated to match.
1411 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1412 const LangOptions &LangOpts) {
1413 // If we have a slash, look for an escaped newline.
1414 if (Ptr[0] == '\\') {
1418 // Common case, backslash-char where the char is not whitespace.
1419 if (!isWhitespace(Ptr[0])) return '\\';
1421 // See if we have optional whitespace characters followed by a newline.
1422 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1423 // Found backslash<whitespace><newline>. Parse the char after it.
1424 Size += EscapedNewLineSize;
1425 Ptr += EscapedNewLineSize;
1427 // If the char that we finally got was a \n, then we must have had
1428 // something like \<newline><newline>. We don't want to consume the
1430 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1433 // Use slow version to accumulate a correct size field.
1434 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1437 // Otherwise, this is not an escaped newline, just return the slash.
1441 // If this is a trigraph, process it.
1442 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1443 // If this is actually a legal trigraph (not something like "??x"), return
1445 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1448 if (C == '\\') goto Slash;
1453 // If this is neither, return a single character.
1458 //===----------------------------------------------------------------------===//
1459 // Helper methods for lexing.
1460 //===----------------------------------------------------------------------===//
1462 /// \brief Routine that indiscriminately skips bytes in the source file.
1463 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1465 if (BufferPtr > BufferEnd)
1466 BufferPtr = BufferEnd;
1467 IsAtStartOfLine = StartOfLine;
1470 void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1471 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1473 unsigned char C = *CurPtr++;
1474 while (isIdentifierBody(C))
1477 --CurPtr; // Back up over the skipped character.
1479 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1480 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1483 // TODO: Could merge these checks into a CharInfo flag to make the comparison
1485 if (C != '\\' && C != '?' && (C != '$' || !LangOpts.DollarIdents)) {
1487 const char *IdStart = BufferPtr;
1488 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1489 Result.setRawIdentifierData(IdStart);
1491 // If we are in raw mode, return this identifier raw. There is no need to
1492 // look up identifier information or attempt to macro expand it.
1496 // Fill in Result.IdentifierInfo and update the token kind,
1497 // looking up the identifier in the identifier table.
1498 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1500 // Finally, now that we know we have an identifier, pass this off to the
1501 // preprocessor, which may macro expand it or something.
1502 if (II->isHandleIdentifierCase())
1503 PP->HandleIdentifier(Result);
1508 // Otherwise, $,\,? in identifier found. Enter slower path.
1510 C = getCharAndSize(CurPtr, Size);
1513 // If we hit a $ and they are not supported in identifiers, we are done.
1514 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1516 // Otherwise, emit a diagnostic and continue.
1517 if (!isLexingRawMode())
1518 Diag(CurPtr, diag::ext_dollar_in_identifier);
1519 CurPtr = ConsumeChar(CurPtr, Size, Result);
1520 C = getCharAndSize(CurPtr, Size);
1522 } else if (!isIdentifierBody(C)) { // FIXME: UCNs.
1523 // Found end of identifier.
1524 goto FinishIdentifier;
1527 // Otherwise, this character is good, consume it.
1528 CurPtr = ConsumeChar(CurPtr, Size, Result);
1530 C = getCharAndSize(CurPtr, Size);
1531 while (isIdentifierBody(C)) { // FIXME: UCNs.
1532 CurPtr = ConsumeChar(CurPtr, Size, Result);
1533 C = getCharAndSize(CurPtr, Size);
1538 /// isHexaLiteral - Return true if Start points to a hex constant.
1539 /// in microsoft mode (where this is supposed to be several different tokens).
1540 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1542 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1545 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1546 return (C2 == 'x' || C2 == 'X');
1549 /// LexNumericConstant - Lex the remainder of a integer or floating point
1550 /// constant. From[-1] is the first character lexed. Return the end of the
1552 void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1554 char C = getCharAndSize(CurPtr, Size);
1556 while (isNumberBody(C)) { // FIXME: UCNs.
1557 CurPtr = ConsumeChar(CurPtr, Size, Result);
1559 C = getCharAndSize(CurPtr, Size);
1562 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1563 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1564 // If we are in Microsoft mode, don't continue if the constant is hex.
1565 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1566 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1567 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1570 // If we have a hex FP constant, continue.
1571 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1572 // Outside C99, we accept hexadecimal floating point numbers as a
1573 // not-quite-conforming extension. Only do so if this looks like it's
1574 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1575 bool IsHexFloat = true;
1576 if (!LangOpts.C99) {
1577 if (!isHexaLiteral(BufferPtr, LangOpts))
1579 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1583 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1586 // Update the location of token as well as BufferPtr.
1587 const char *TokStart = BufferPtr;
1588 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1589 Result.setLiteralData(TokStart);
1592 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1593 /// in C++11, or warn on a ud-suffix in C++98.
1594 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
1595 assert(getLangOpts().CPlusPlus);
1597 // Maximally munch an identifier. FIXME: UCNs.
1599 char C = getCharAndSize(CurPtr, Size);
1600 if (isIdentifierHead(C)) {
1601 if (!getLangOpts().CPlusPlus0x) {
1602 if (!isLexingRawMode())
1604 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1605 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1606 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1610 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1611 // that does not start with an underscore is ill-formed. As a conforming
1612 // extension, we treat all such suffixes as if they had whitespace before
1615 if (!isLexingRawMode())
1616 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1617 diag::ext_ms_reserved_user_defined_literal :
1618 diag::ext_reserved_user_defined_literal)
1619 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1623 Result.setFlag(Token::HasUDSuffix);
1625 CurPtr = ConsumeChar(CurPtr, Size, Result);
1626 C = getCharAndSize(CurPtr, Size);
1627 } while (isIdentifierBody(C));
1632 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1633 /// either " or L" or u8" or u" or U".
1634 void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1635 tok::TokenKind Kind) {
1636 const char *NulCharacter = 0; // Does this string contain the \0 character?
1638 if (!isLexingRawMode() &&
1639 (Kind == tok::utf8_string_literal ||
1640 Kind == tok::utf16_string_literal ||
1641 Kind == tok::utf32_string_literal))
1642 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1644 char C = getAndAdvanceChar(CurPtr, Result);
1646 // Skip escaped characters. Escaped newlines will already be processed by
1647 // getAndAdvanceChar.
1649 C = getAndAdvanceChar(CurPtr, Result);
1651 if (C == '\n' || C == '\r' || // Newline.
1652 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1653 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1654 Diag(BufferPtr, diag::ext_unterminated_string);
1655 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1660 if (isCodeCompletionPoint(CurPtr-1)) {
1661 PP->CodeCompleteNaturalLanguage();
1662 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1663 return cutOffLexing();
1666 NulCharacter = CurPtr-1;
1668 C = getAndAdvanceChar(CurPtr, Result);
1671 // If we are in C++11, lex the optional ud-suffix.
1672 if (getLangOpts().CPlusPlus)
1673 CurPtr = LexUDSuffix(Result, CurPtr);
1675 // If a nul character existed in the string, warn about it.
1676 if (NulCharacter && !isLexingRawMode())
1677 Diag(NulCharacter, diag::null_in_string);
1679 // Update the location of the token as well as the BufferPtr instance var.
1680 const char *TokStart = BufferPtr;
1681 FormTokenWithChars(Result, CurPtr, Kind);
1682 Result.setLiteralData(TokStart);
1685 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1686 /// having lexed R", LR", u8R", uR", or UR".
1687 void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1688 tok::TokenKind Kind) {
1689 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1690 // Between the initial and final double quote characters of the raw string,
1691 // any transformations performed in phases 1 and 2 (trigraphs,
1692 // universal-character-names, and line splicing) are reverted.
1694 if (!isLexingRawMode())
1695 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1697 unsigned PrefixLen = 0;
1699 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1702 // If the last character was not a '(', then we didn't lex a valid delimiter.
1703 if (CurPtr[PrefixLen] != '(') {
1704 if (!isLexingRawMode()) {
1705 const char *PrefixEnd = &CurPtr[PrefixLen];
1706 if (PrefixLen == 16) {
1707 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1709 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1710 << StringRef(PrefixEnd, 1);
1714 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1715 // it's possible the '"' was intended to be part of the raw string, but
1716 // there's not much we can do about that.
1722 if (C == 0 && CurPtr-1 == BufferEnd) {
1728 FormTokenWithChars(Result, CurPtr, tok::unknown);
1732 // Save prefix and move CurPtr past it
1733 const char *Prefix = CurPtr;
1734 CurPtr += PrefixLen + 1; // skip over prefix and '('
1740 // Check for prefix match and closing quote.
1741 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1742 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1745 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1746 if (!isLexingRawMode())
1747 Diag(BufferPtr, diag::err_unterminated_raw_string)
1748 << StringRef(Prefix, PrefixLen);
1749 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1754 // If we are in C++11, lex the optional ud-suffix.
1755 if (getLangOpts().CPlusPlus)
1756 CurPtr = LexUDSuffix(Result, CurPtr);
1758 // Update the location of token as well as BufferPtr.
1759 const char *TokStart = BufferPtr;
1760 FormTokenWithChars(Result, CurPtr, Kind);
1761 Result.setLiteralData(TokStart);
1764 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1765 /// after having lexed the '<' character. This is used for #include filenames.
1766 void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1767 const char *NulCharacter = 0; // Does this string contain the \0 character?
1768 const char *AfterLessPos = CurPtr;
1769 char C = getAndAdvanceChar(CurPtr, Result);
1771 // Skip escaped characters.
1773 // Skip the escaped character.
1774 getAndAdvanceChar(CurPtr, Result);
1775 } else if (C == '\n' || C == '\r' || // Newline.
1776 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1777 isCodeCompletionPoint(CurPtr-1)))) {
1778 // If the filename is unterminated, then it must just be a lone <
1779 // character. Return this as such.
1780 FormTokenWithChars(Result, AfterLessPos, tok::less);
1782 } else if (C == 0) {
1783 NulCharacter = CurPtr-1;
1785 C = getAndAdvanceChar(CurPtr, Result);
1788 // If a nul character existed in the string, warn about it.
1789 if (NulCharacter && !isLexingRawMode())
1790 Diag(NulCharacter, diag::null_in_string);
1792 // Update the location of token as well as BufferPtr.
1793 const char *TokStart = BufferPtr;
1794 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1795 Result.setLiteralData(TokStart);
1799 /// LexCharConstant - Lex the remainder of a character constant, after having
1800 /// lexed either ' or L' or u' or U'.
1801 void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1802 tok::TokenKind Kind) {
1803 const char *NulCharacter = 0; // Does this character contain the \0 character?
1805 if (!isLexingRawMode() &&
1806 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1807 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal);
1809 char C = getAndAdvanceChar(CurPtr, Result);
1811 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1812 Diag(BufferPtr, diag::ext_empty_character);
1813 FormTokenWithChars(Result, CurPtr, tok::unknown);
1818 // Skip escaped characters.
1820 C = getAndAdvanceChar(CurPtr, Result);
1822 if (C == '\n' || C == '\r' || // Newline.
1823 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1824 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1825 Diag(BufferPtr, diag::ext_unterminated_char);
1826 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1831 if (isCodeCompletionPoint(CurPtr-1)) {
1832 PP->CodeCompleteNaturalLanguage();
1833 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1834 return cutOffLexing();
1837 NulCharacter = CurPtr-1;
1839 C = getAndAdvanceChar(CurPtr, Result);
1842 // If we are in C++11, lex the optional ud-suffix.
1843 if (getLangOpts().CPlusPlus)
1844 CurPtr = LexUDSuffix(Result, CurPtr);
1846 // If a nul character existed in the character, warn about it.
1847 if (NulCharacter && !isLexingRawMode())
1848 Diag(NulCharacter, diag::null_in_char);
1850 // Update the location of token as well as BufferPtr.
1851 const char *TokStart = BufferPtr;
1852 FormTokenWithChars(Result, CurPtr, Kind);
1853 Result.setLiteralData(TokStart);
1856 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1857 /// Update BufferPtr to point to the next non-whitespace character and return.
1859 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1861 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
1862 // Whitespace - Skip it, then return the token after the whitespace.
1863 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1865 // Skip horizontal whitespace very aggressively.
1866 while (isHorizontalWhitespace(Char))
1869 // Otherwise if we have something other than whitespace, we're done.
1870 if (Char != '\n' && Char != '\r')
1873 if (ParsingPreprocessorDirective) {
1874 // End of preprocessor directive line, let LexTokenInternal handle this.
1879 // ok, but handle newline.
1880 // The returned token is at the start of the line.
1881 Result.setFlag(Token::StartOfLine);
1882 // No leading whitespace seen so far.
1883 Result.clearFlag(Token::LeadingSpace);
1887 // If this isn't immediately after a newline, there is leading space.
1888 char PrevChar = CurPtr[-1];
1889 if (PrevChar != '\n' && PrevChar != '\r')
1890 Result.setFlag(Token::LeadingSpace);
1892 // If the client wants us to return whitespace, return it now.
1893 if (isKeepWhitespaceMode()) {
1894 FormTokenWithChars(Result, CurPtr, tok::unknown);
1902 /// We have just read the // characters from input. Skip until we find the
1903 /// newline character thats terminate the comment. Then update BufferPtr and
1906 /// If we're in KeepCommentMode or any CommentHandler has inserted
1907 /// some tokens, this will store the first token and return true.
1908 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1909 // If Line comments aren't explicitly enabled for this language, emit an
1910 // extension warning.
1911 if (!LangOpts.LineComment && !isLexingRawMode()) {
1912 Diag(BufferPtr, diag::ext_line_comment);
1914 // Mark them enabled so we only emit one warning for this translation
1916 LangOpts.LineComment = true;
1919 // Scan over the body of the comment. The common case, when scanning, is that
1920 // the comment contains normal ascii characters with nothing interesting in
1921 // them. As such, optimize for this case with the inner loop.
1925 // Skip over characters in the fast loop.
1926 while (C != 0 && // Potentially EOF.
1927 C != '\n' && C != '\r') // Newline or DOS-style newline.
1930 const char *NextLine = CurPtr;
1932 // We found a newline, see if it's escaped.
1933 const char *EscapePtr = CurPtr-1;
1934 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1937 if (*EscapePtr == '\\') // Escaped newline.
1939 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1940 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1941 CurPtr = EscapePtr-2;
1943 break; // This is a newline, we're done.
1946 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
1947 // properly decode the character. Read it in raw mode to avoid emitting
1948 // diagnostics about things like trigraphs. If we see an escaped newline,
1949 // we'll handle it below.
1950 const char *OldPtr = CurPtr;
1951 bool OldRawMode = isLexingRawMode();
1952 LexingRawMode = true;
1953 C = getAndAdvanceChar(CurPtr, Result);
1954 LexingRawMode = OldRawMode;
1956 // If we only read only one character, then no special handling is needed.
1957 // We're done and can skip forward to the newline.
1958 if (C != 0 && CurPtr == OldPtr+1) {
1963 // If we read multiple characters, and one of those characters was a \r or
1964 // \n, then we had an escaped newline within the comment. Emit diagnostic
1965 // unless the next line is also a // comment.
1966 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1967 for (; OldPtr != CurPtr; ++OldPtr)
1968 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1969 // Okay, we found a // comment that ends in a newline, if the next
1970 // line is also a // comment, but has spaces, don't emit a diagnostic.
1971 if (isWhitespace(C)) {
1972 const char *ForwardPtr = CurPtr;
1973 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
1975 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1979 if (!isLexingRawMode())
1980 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
1985 if (CurPtr == BufferEnd+1) {
1990 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
1991 PP->CodeCompleteNaturalLanguage();
1996 } while (C != '\n' && C != '\r');
1998 // Found but did not consume the newline. Notify comment handlers about the
1999 // comment unless we're in a #if 0 block.
2000 if (PP && !isLexingRawMode() &&
2001 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2002 getSourceLocation(CurPtr)))) {
2004 return true; // A token has to be returned.
2007 // If we are returning comments as tokens, return this comment as a token.
2008 if (inKeepCommentMode())
2009 return SaveLineComment(Result, CurPtr);
2011 // If we are inside a preprocessor directive and we see the end of line,
2012 // return immediately, so that the lexer can return this as an EOD token.
2013 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2018 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2019 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2020 // contribute to another token), it isn't needed for correctness. Note that
2021 // this is ok even in KeepWhitespaceMode, because we would have returned the
2022 /// comment above in that mode.
2025 // The next returned token is at the start of the line.
2026 Result.setFlag(Token::StartOfLine);
2027 // No leading whitespace seen so far.
2028 Result.clearFlag(Token::LeadingSpace);
2033 /// If in save-comment mode, package up this Line comment in an appropriate
2034 /// way and return it.
2035 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2036 // If we're not in a preprocessor directive, just return the // comment
2038 FormTokenWithChars(Result, CurPtr, tok::comment);
2040 if (!ParsingPreprocessorDirective || LexingRawMode)
2043 // If this Line-style comment is in a macro definition, transmogrify it into
2044 // a C-style block comment.
2045 bool Invalid = false;
2046 std::string Spelling = PP->getSpelling(Result, &Invalid);
2050 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2051 Spelling[1] = '*'; // Change prefix to "/*".
2052 Spelling += "*/"; // add suffix.
2054 Result.setKind(tok::comment);
2055 PP->CreateString(Spelling, Result,
2056 Result.getLocation(), Result.getLocation());
2060 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2061 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2062 /// a diagnostic if so. We know that the newline is inside of a block comment.
2063 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2065 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2067 // Back up off the newline.
2070 // If this is a two-character newline sequence, skip the other character.
2071 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2072 // \n\n or \r\r -> not escaped newline.
2073 if (CurPtr[0] == CurPtr[1])
2075 // \n\r or \r\n -> skip the newline.
2079 // If we have horizontal whitespace, skip over it. We allow whitespace
2080 // between the slash and newline.
2081 bool HasSpace = false;
2082 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2087 // If we have a slash, we know this is an escaped newline.
2088 if (*CurPtr == '\\') {
2089 if (CurPtr[-1] != '*') return false;
2091 // It isn't a slash, is it the ?? / trigraph?
2092 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2096 // This is the trigraph ending the comment. Emit a stern warning!
2099 // If no trigraphs are enabled, warn that we ignored this trigraph and
2100 // ignore this * character.
2101 if (!L->getLangOpts().Trigraphs) {
2102 if (!L->isLexingRawMode())
2103 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2106 if (!L->isLexingRawMode())
2107 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2110 // Warn about having an escaped newline between the */ characters.
2111 if (!L->isLexingRawMode())
2112 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2114 // If there was space between the backslash and newline, warn about it.
2115 if (HasSpace && !L->isLexingRawMode())
2116 L->Diag(CurPtr, diag::backslash_newline_space);
2122 #include <emmintrin.h>
2124 #include <altivec.h>
2128 /// We have just read from input the / and * characters that started a comment.
2129 /// Read until we find the * and / characters that terminate the comment.
2130 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2131 /// comments, because they cannot cause the comment to end. The only thing
2132 /// that can happen is the comment could end with an escaped newline between
2133 /// the terminating * and /.
2135 /// If we're in KeepCommentMode or any CommentHandler has inserted
2136 /// some tokens, this will store the first token and return true.
2137 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
2138 // Scan one character past where we should, looking for a '/' character. Once
2139 // we find it, check to see if it was preceded by a *. This common
2140 // optimization helps people who like to put a lot of * characters in their
2143 // The first character we get with newlines and trigraphs skipped to handle
2144 // the degenerate /*/ case below correctly if the * has an escaped newline
2147 unsigned char C = getCharAndSize(CurPtr, CharSize);
2149 if (C == 0 && CurPtr == BufferEnd+1) {
2150 if (!isLexingRawMode())
2151 Diag(BufferPtr, diag::err_unterminated_block_comment);
2154 // KeepWhitespaceMode should return this broken comment as a token. Since
2155 // it isn't a well formed comment, just return it as an 'unknown' token.
2156 if (isKeepWhitespaceMode()) {
2157 FormTokenWithChars(Result, CurPtr, tok::unknown);
2165 // Check to see if the first character after the '/*' is another /. If so,
2166 // then this slash does not end the block comment, it is part of it.
2171 // Skip over all non-interesting characters until we find end of buffer or a
2172 // (probably ending) '/' character.
2173 if (CurPtr + 24 < BufferEnd &&
2174 // If there is a code-completion point avoid the fast scan because it
2175 // doesn't check for '\0'.
2176 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2177 // While not aligned to a 16-byte boundary.
2178 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2181 if (C == '/') goto FoundSlash;
2184 __m128i Slashes = _mm_set1_epi8('/');
2185 while (CurPtr+16 <= BufferEnd) {
2186 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2189 // Adjust the pointer to point directly after the first slash. It's
2190 // not necessary to set C here, it will be overwritten at the end of
2192 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
2198 __vector unsigned char Slashes = {
2199 '/', '/', '/', '/', '/', '/', '/', '/',
2200 '/', '/', '/', '/', '/', '/', '/', '/'
2202 while (CurPtr+16 <= BufferEnd &&
2203 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2206 // Scan for '/' quickly. Many block comments are very large.
2207 while (CurPtr[0] != '/' &&
2211 CurPtr+4 < BufferEnd) {
2216 // It has to be one of the bytes scanned, increment to it and read one.
2220 // Loop to scan the remainder.
2221 while (C != '/' && C != '\0')
2226 if (CurPtr[-2] == '*') // We found the final */. We're done!
2229 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2230 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2231 // We found the final */, though it had an escaped newline between the
2232 // * and /. We're done!
2236 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2237 // If this is a /* inside of the comment, emit a warning. Don't do this
2238 // if this is a /*/, which will end the comment. This misses cases with
2239 // embedded escaped newlines, but oh well.
2240 if (!isLexingRawMode())
2241 Diag(CurPtr-1, diag::warn_nested_block_comment);
2243 } else if (C == 0 && CurPtr == BufferEnd+1) {
2244 if (!isLexingRawMode())
2245 Diag(BufferPtr, diag::err_unterminated_block_comment);
2246 // Note: the user probably forgot a */. We could continue immediately
2247 // after the /*, but this would involve lexing a lot of what really is the
2248 // comment, which surely would confuse the parser.
2251 // KeepWhitespaceMode should return this broken comment as a token. Since
2252 // it isn't a well formed comment, just return it as an 'unknown' token.
2253 if (isKeepWhitespaceMode()) {
2254 FormTokenWithChars(Result, CurPtr, tok::unknown);
2260 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2261 PP->CodeCompleteNaturalLanguage();
2269 // Notify comment handlers about the comment unless we're in a #if 0 block.
2270 if (PP && !isLexingRawMode() &&
2271 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2272 getSourceLocation(CurPtr)))) {
2274 return true; // A token has to be returned.
2277 // If we are returning comments as tokens, return this comment as a token.
2278 if (inKeepCommentMode()) {
2279 FormTokenWithChars(Result, CurPtr, tok::comment);
2283 // It is common for the tokens immediately after a /**/ comment to be
2284 // whitespace. Instead of going through the big switch, handle it
2285 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2286 // have already returned above with the comment as a token.
2287 if (isHorizontalWhitespace(*CurPtr)) {
2288 Result.setFlag(Token::LeadingSpace);
2289 SkipWhitespace(Result, CurPtr+1);
2293 // Otherwise, just return so that the next character will be lexed as a token.
2295 Result.setFlag(Token::LeadingSpace);
2299 //===----------------------------------------------------------------------===//
2300 // Primary Lexing Entry Points
2301 //===----------------------------------------------------------------------===//
2303 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2304 /// uninterpreted string. This switches the lexer out of directive mode.
2305 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2306 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2307 "Must be in a preprocessing directive!");
2310 // CurPtr - Cache BufferPtr in an automatic variable.
2311 const char *CurPtr = BufferPtr;
2313 char Char = getAndAdvanceChar(CurPtr, Tmp);
2317 Result->push_back(Char);
2320 // Found end of file?
2321 if (CurPtr-1 != BufferEnd) {
2322 if (isCodeCompletionPoint(CurPtr-1)) {
2323 PP->CodeCompleteNaturalLanguage();
2328 // Nope, normal character, continue.
2330 Result->push_back(Char);
2336 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2337 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2338 BufferPtr = CurPtr-1;
2340 // Next, lex the character, which should handle the EOD transition.
2342 if (Tmp.is(tok::code_completion)) {
2344 PP->CodeCompleteNaturalLanguage();
2347 assert(Tmp.is(tok::eod) && "Unexpected token!");
2349 // Finally, we're done;
2355 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2356 /// condition, reporting diagnostics and handling other edge cases as required.
2357 /// This returns true if Result contains a token, false if PP.Lex should be
2359 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2360 // If we hit the end of the file while parsing a preprocessor directive,
2361 // end the preprocessor directive first. The next token returned will
2362 // then be the end of file.
2363 if (ParsingPreprocessorDirective) {
2364 // Done parsing the "line".
2365 ParsingPreprocessorDirective = false;
2366 // Update the location of token as well as BufferPtr.
2367 FormTokenWithChars(Result, CurPtr, tok::eod);
2369 // Restore comment saving mode, in case it was disabled for directive.
2370 SetCommentRetentionState(PP->getCommentRetentionState());
2371 return true; // Have a token.
2374 // If we are in raw mode, return this event as an EOF token. Let the caller
2375 // that put us in raw mode handle the event.
2376 if (isLexingRawMode()) {
2377 Result.startToken();
2378 BufferPtr = BufferEnd;
2379 FormTokenWithChars(Result, BufferEnd, tok::eof);
2383 // Issue diagnostics for unterminated #if and missing newline.
2385 // If we are in a #if directive, emit an error.
2386 while (!ConditionalStack.empty()) {
2387 if (PP->getCodeCompletionFileLoc() != FileLoc)
2388 PP->Diag(ConditionalStack.back().IfLoc,
2389 diag::err_pp_unterminated_conditional);
2390 ConditionalStack.pop_back();
2393 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2395 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
2396 Diag(BufferEnd, LangOpts.CPlusPlus0x ? // C++11 [lex.phases] 2.2 p2
2397 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2398 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
2402 // Finally, let the preprocessor handle this.
2403 return PP->HandleEndOfFile(Result, isPragmaLexer());
2406 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2407 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2408 /// else and 2 if there are no more tokens in the buffer controlled by the
2410 unsigned Lexer::isNextPPTokenLParen() {
2411 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2413 // Switch to 'skipping' mode. This will ensure that we can lex a token
2414 // without emitting diagnostics, disables macro expansion, and will cause EOF
2415 // to return an EOF token instead of popping the include stack.
2416 LexingRawMode = true;
2418 // Save state that can be changed while lexing so that we can restore it.
2419 const char *TmpBufferPtr = BufferPtr;
2420 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2424 LexTokenInternal(Tok);
2426 // Restore state that may have changed.
2427 BufferPtr = TmpBufferPtr;
2428 ParsingPreprocessorDirective = inPPDirectiveMode;
2430 // Restore the lexer back to non-skipping mode.
2431 LexingRawMode = false;
2433 if (Tok.is(tok::eof))
2435 return Tok.is(tok::l_paren);
2438 /// \brief Find the end of a version control conflict marker.
2439 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2440 ConflictMarkerKind CMK) {
2441 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2442 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2443 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2444 size_t Pos = RestOfBuffer.find(Terminator);
2445 while (Pos != StringRef::npos) {
2446 // Must occur at start of line.
2447 if (RestOfBuffer[Pos-1] != '\r' &&
2448 RestOfBuffer[Pos-1] != '\n') {
2449 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2450 Pos = RestOfBuffer.find(Terminator);
2453 return RestOfBuffer.data()+Pos;
2458 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2459 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2460 /// and recover nicely. This returns true if it is a conflict marker and false
2462 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2463 // Only a conflict marker if it starts at the beginning of a line.
2464 if (CurPtr != BufferStart &&
2465 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2468 // Check to see if we have <<<<<<< or >>>>.
2469 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2470 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
2473 // If we have a situation where we don't care about conflict markers, ignore
2475 if (CurrentConflictMarkerState || isLexingRawMode())
2478 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2480 // Check to see if there is an ending marker somewhere in the buffer at the
2481 // start of a line to terminate this conflict marker.
2482 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2483 // We found a match. We are really in a conflict marker.
2484 // Diagnose this, and ignore to the end of line.
2485 Diag(CurPtr, diag::err_conflict_marker);
2486 CurrentConflictMarkerState = Kind;
2488 // Skip ahead to the end of line. We know this exists because the
2489 // end-of-conflict marker starts with \r or \n.
2490 while (*CurPtr != '\r' && *CurPtr != '\n') {
2491 assert(CurPtr != BufferEnd && "Didn't find end of line");
2498 // No end of conflict marker found.
2503 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2504 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2505 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2506 /// the line. This returns true if it is a conflict marker and false if not.
2507 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2508 // Only a conflict marker if it starts at the beginning of a line.
2509 if (CurPtr != BufferStart &&
2510 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2513 // If we have a situation where we don't care about conflict markers, ignore
2515 if (!CurrentConflictMarkerState || isLexingRawMode())
2518 // Check to see if we have the marker (4 characters in a row).
2519 for (unsigned i = 1; i != 4; ++i)
2520 if (CurPtr[i] != CurPtr[0])
2523 // If we do have it, search for the end of the conflict marker. This could
2524 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2525 // be the end of conflict marker.
2526 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2527 CurrentConflictMarkerState)) {
2530 // Skip ahead to the end of line.
2531 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2536 // No longer in the conflict marker.
2537 CurrentConflictMarkerState = CMK_None;
2544 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2545 if (PP && PP->isCodeCompletionEnabled()) {
2546 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2547 return Loc == PP->getCodeCompletionLoc();
2554 /// LexTokenInternal - This implements a simple C family lexer. It is an
2555 /// extremely performance critical piece of code. This assumes that the buffer
2556 /// has a null character at the end of the file. This returns a preprocessing
2557 /// token, not a normal token, as such, it is an internal interface. It assumes
2558 /// that the Flags of result have been cleared before calling this.
2559 void Lexer::LexTokenInternal(Token &Result) {
2561 // New token, can't need cleaning yet.
2562 Result.clearFlag(Token::NeedsCleaning);
2563 Result.setIdentifierInfo(0);
2565 // CurPtr - Cache BufferPtr in an automatic variable.
2566 const char *CurPtr = BufferPtr;
2568 // Small amounts of horizontal whitespace is very common between tokens.
2569 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2571 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2574 // If we are keeping whitespace and other tokens, just return what we just
2575 // skipped. The next lexer invocation will return the token after the
2577 if (isKeepWhitespaceMode()) {
2578 FormTokenWithChars(Result, CurPtr, tok::unknown);
2583 Result.setFlag(Token::LeadingSpace);
2586 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
2588 // Read a character, advancing over it.
2589 char Char = getAndAdvanceChar(CurPtr, Result);
2590 tok::TokenKind Kind;
2594 // Found end of file?
2595 if (CurPtr-1 == BufferEnd) {
2596 // Read the PP instance variable into an automatic variable, because
2597 // LexEndOfFile will often delete 'this'.
2598 Preprocessor *PPCache = PP;
2599 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2600 return; // Got a token to return.
2601 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2602 return PPCache->Lex(Result);
2605 // Check if we are performing code completion.
2606 if (isCodeCompletionPoint(CurPtr-1)) {
2607 // Return the code-completion token.
2608 Result.startToken();
2609 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2613 if (!isLexingRawMode())
2614 Diag(CurPtr-1, diag::null_in_file);
2615 Result.setFlag(Token::LeadingSpace);
2616 if (SkipWhitespace(Result, CurPtr))
2617 return; // KeepWhitespaceMode
2619 goto LexNextToken; // GCC isn't tail call eliminating.
2621 case 26: // DOS & CP/M EOF: "^Z".
2622 // If we're in Microsoft extensions mode, treat this as end of file.
2623 if (LangOpts.MicrosoftExt) {
2624 // Read the PP instance variable into an automatic variable, because
2625 // LexEndOfFile will often delete 'this'.
2626 Preprocessor *PPCache = PP;
2627 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2628 return; // Got a token to return.
2629 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2630 return PPCache->Lex(Result);
2632 // If Microsoft extensions are disabled, this is just random garbage.
2633 Kind = tok::unknown;
2638 // If we are inside a preprocessor directive and we see the end of line,
2639 // we know we are done with the directive, so return an EOD token.
2640 if (ParsingPreprocessorDirective) {
2641 // Done parsing the "line".
2642 ParsingPreprocessorDirective = false;
2644 // Restore comment saving mode, in case it was disabled for directive.
2646 SetCommentRetentionState(PP->getCommentRetentionState());
2648 // Since we consumed a newline, we are back at the start of a line.
2649 IsAtStartOfLine = true;
2654 // The returned token is at the start of the line.
2655 Result.setFlag(Token::StartOfLine);
2656 // No leading whitespace seen so far.
2657 Result.clearFlag(Token::LeadingSpace);
2659 if (SkipWhitespace(Result, CurPtr))
2660 return; // KeepWhitespaceMode
2661 goto LexNextToken; // GCC isn't tail call eliminating.
2666 SkipHorizontalWhitespace:
2667 Result.setFlag(Token::LeadingSpace);
2668 if (SkipWhitespace(Result, CurPtr))
2669 return; // KeepWhitespaceMode
2674 // If the next token is obviously a // or /* */ comment, skip it efficiently
2675 // too (without going through the big switch stmt).
2676 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
2677 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2678 if (SkipLineComment(Result, CurPtr+2))
2679 return; // There is a token to return.
2680 goto SkipIgnoredUnits;
2681 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
2682 if (SkipBlockComment(Result, CurPtr+2))
2683 return; // There is a token to return.
2684 goto SkipIgnoredUnits;
2685 } else if (isHorizontalWhitespace(*CurPtr)) {
2686 goto SkipHorizontalWhitespace;
2688 goto LexNextToken; // GCC isn't tail call eliminating.
2690 // C99 6.4.4.1: Integer Constants.
2691 // C99 6.4.4.2: Floating Constants.
2692 case '0': case '1': case '2': case '3': case '4':
2693 case '5': case '6': case '7': case '8': case '9':
2694 // Notify MIOpt that we read a non-whitespace/non-comment token.
2696 return LexNumericConstant(Result, CurPtr);
2698 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal
2699 // Notify MIOpt that we read a non-whitespace/non-comment token.
2702 if (LangOpts.CPlusPlus0x) {
2703 Char = getCharAndSize(CurPtr, SizeTmp);
2705 // UTF-16 string literal
2707 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2708 tok::utf16_string_literal);
2710 // UTF-16 character constant
2712 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2713 tok::utf16_char_constant);
2715 // UTF-16 raw string literal
2716 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2717 return LexRawStringLiteral(Result,
2718 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2720 tok::utf16_string_literal);
2723 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2725 // UTF-8 string literal
2727 return LexStringLiteral(Result,
2728 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2730 tok::utf8_string_literal);
2734 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2735 // UTF-8 raw string literal
2737 return LexRawStringLiteral(Result,
2738 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2741 tok::utf8_string_literal);
2747 // treat u like the start of an identifier.
2748 return LexIdentifier(Result, CurPtr);
2750 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal
2751 // Notify MIOpt that we read a non-whitespace/non-comment token.
2754 if (LangOpts.CPlusPlus0x) {
2755 Char = getCharAndSize(CurPtr, SizeTmp);
2757 // UTF-32 string literal
2759 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2760 tok::utf32_string_literal);
2762 // UTF-32 character constant
2764 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2765 tok::utf32_char_constant);
2767 // UTF-32 raw string literal
2768 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2769 return LexRawStringLiteral(Result,
2770 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2772 tok::utf32_string_literal);
2775 // treat U like the start of an identifier.
2776 return LexIdentifier(Result, CurPtr);
2778 case 'R': // Identifier or C++0x raw string literal
2779 // Notify MIOpt that we read a non-whitespace/non-comment token.
2782 if (LangOpts.CPlusPlus0x) {
2783 Char = getCharAndSize(CurPtr, SizeTmp);
2786 return LexRawStringLiteral(Result,
2787 ConsumeChar(CurPtr, SizeTmp, Result),
2788 tok::string_literal);
2791 // treat R like the start of an identifier.
2792 return LexIdentifier(Result, CurPtr);
2794 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
2795 // Notify MIOpt that we read a non-whitespace/non-comment token.
2797 Char = getCharAndSize(CurPtr, SizeTmp);
2799 // Wide string literal.
2801 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2802 tok::wide_string_literal);
2804 // Wide raw string literal.
2805 if (LangOpts.CPlusPlus0x && Char == 'R' &&
2806 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2807 return LexRawStringLiteral(Result,
2808 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2810 tok::wide_string_literal);
2812 // Wide character constant.
2814 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2815 tok::wide_char_constant);
2816 // FALL THROUGH, treating L like the start of an identifier.
2818 // C99 6.4.2: Identifiers.
2819 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2820 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
2821 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
2822 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2823 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2824 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
2825 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
2826 case 'v': case 'w': case 'x': case 'y': case 'z':
2828 // Notify MIOpt that we read a non-whitespace/non-comment token.
2830 return LexIdentifier(Result, CurPtr);
2832 case '$': // $ in identifiers.
2833 if (LangOpts.DollarIdents) {
2834 if (!isLexingRawMode())
2835 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
2836 // Notify MIOpt that we read a non-whitespace/non-comment token.
2838 return LexIdentifier(Result, CurPtr);
2841 Kind = tok::unknown;
2844 // C99 6.4.4: Character Constants.
2846 // Notify MIOpt that we read a non-whitespace/non-comment token.
2848 return LexCharConstant(Result, CurPtr, tok::char_constant);
2850 // C99 6.4.5: String Literals.
2852 // Notify MIOpt that we read a non-whitespace/non-comment token.
2854 return LexStringLiteral(Result, CurPtr, tok::string_literal);
2856 // C99 6.4.6: Punctuators.
2858 Kind = tok::question;
2861 Kind = tok::l_square;
2864 Kind = tok::r_square;
2867 Kind = tok::l_paren;
2870 Kind = tok::r_paren;
2873 Kind = tok::l_brace;
2876 Kind = tok::r_brace;
2879 Char = getCharAndSize(CurPtr, SizeTmp);
2880 if (Char >= '0' && Char <= '9') {
2881 // Notify MIOpt that we read a non-whitespace/non-comment token.
2884 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
2885 } else if (LangOpts.CPlusPlus && Char == '*') {
2886 Kind = tok::periodstar;
2888 } else if (Char == '.' &&
2889 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
2890 Kind = tok::ellipsis;
2891 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2898 Char = getCharAndSize(CurPtr, SizeTmp);
2901 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2902 } else if (Char == '=') {
2903 Kind = tok::ampequal;
2904 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2910 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
2911 Kind = tok::starequal;
2912 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2918 Char = getCharAndSize(CurPtr, SizeTmp);
2920 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2921 Kind = tok::plusplus;
2922 } else if (Char == '=') {
2923 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2924 Kind = tok::plusequal;
2930 Char = getCharAndSize(CurPtr, SizeTmp);
2931 if (Char == '-') { // --
2932 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2933 Kind = tok::minusminus;
2934 } else if (Char == '>' && LangOpts.CPlusPlus &&
2935 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
2936 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2938 Kind = tok::arrowstar;
2939 } else if (Char == '>') { // ->
2940 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2942 } else if (Char == '=') { // -=
2943 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2944 Kind = tok::minusequal;
2953 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
2954 Kind = tok::exclaimequal;
2955 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2957 Kind = tok::exclaim;
2962 Char = getCharAndSize(CurPtr, SizeTmp);
2963 if (Char == '/') { // Line comment.
2964 // Even if Line comments are disabled (e.g. in C89 mode), we generally
2965 // want to lex this as a comment. There is one problem with this though,
2966 // that in one particular corner case, this can change the behavior of the
2967 // resultant program. For example, In "foo //**/ bar", C89 would lex
2968 // this as "foo / bar" and langauges with Line comments would lex it as
2969 // "foo". Check to see if the character after the second slash is a '*'.
2970 // If so, we will lex that as a "/" instead of the start of a comment.
2971 // However, we never do this in -traditional-cpp mode.
2972 if ((LangOpts.LineComment ||
2973 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') &&
2974 !LangOpts.TraditionalCPP) {
2975 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
2976 return; // There is a token to return.
2978 // It is common for the tokens immediately after a // comment to be
2979 // whitespace (indentation for the next line). Instead of going through
2980 // the big switch, handle it efficiently now.
2981 goto SkipIgnoredUnits;
2985 if (Char == '*') { // /**/ comment.
2986 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
2987 return; // There is a token to return.
2988 goto LexNextToken; // GCC isn't tail call eliminating.
2992 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
2993 Kind = tok::slashequal;
2999 Char = getCharAndSize(CurPtr, SizeTmp);
3001 Kind = tok::percentequal;
3002 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3003 } else if (LangOpts.Digraphs && Char == '>') {
3004 Kind = tok::r_brace; // '%>' -> '}'
3005 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3006 } else if (LangOpts.Digraphs && Char == ':') {
3007 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3008 Char = getCharAndSize(CurPtr, SizeTmp);
3009 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3010 Kind = tok::hashhash; // '%:%:' -> '##'
3011 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3013 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3014 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3015 if (!isLexingRawMode())
3016 Diag(BufferPtr, diag::ext_charize_microsoft);
3018 } else { // '%:' -> '#'
3019 // We parsed a # character. If this occurs at the start of the line,
3020 // it's actually the start of a preprocessing directive. Callback to
3021 // the preprocessor to handle it.
3022 // FIXME: -fpreprocessed mode??
3023 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
3024 FormTokenWithChars(Result, CurPtr, tok::hash);
3025 PP->HandleDirective(Result);
3027 // As an optimization, if the preprocessor didn't switch lexers, tail
3029 if (PP->isCurrentLexer(this)) {
3030 // Start a new token. If this is a #include or something, the PP may
3031 // want us starting at the beginning of the line again. If so, set
3032 // the StartOfLine flag and clear LeadingSpace.
3033 if (IsAtStartOfLine) {
3034 Result.setFlag(Token::StartOfLine);
3035 Result.clearFlag(Token::LeadingSpace);
3036 IsAtStartOfLine = false;
3038 goto LexNextToken; // GCC isn't tail call eliminating.
3041 return PP->Lex(Result);
3047 Kind = tok::percent;
3051 Char = getCharAndSize(CurPtr, SizeTmp);
3052 if (ParsingFilename) {
3053 return LexAngledStringLiteral(Result, CurPtr);
3054 } else if (Char == '<') {
3055 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3057 Kind = tok::lesslessequal;
3058 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3060 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3061 // If this is actually a '<<<<<<<' version control conflict marker,
3062 // recognize it as such and recover nicely.
3064 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3065 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3068 } else if (LangOpts.CUDA && After == '<') {
3069 Kind = tok::lesslessless;
3070 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3073 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3074 Kind = tok::lessless;
3076 } else if (Char == '=') {
3077 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3078 Kind = tok::lessequal;
3079 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3080 if (LangOpts.CPlusPlus0x &&
3081 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3082 // C++0x [lex.pptoken]p3:
3083 // Otherwise, if the next three characters are <:: and the subsequent
3084 // character is neither : nor >, the < is treated as a preprocessor
3085 // token by itself and not as the first character of the alternative
3088 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3089 if (After != ':' && After != '>') {
3091 if (!isLexingRawMode())
3092 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3097 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3098 Kind = tok::l_square;
3099 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3100 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3101 Kind = tok::l_brace;
3107 Char = getCharAndSize(CurPtr, SizeTmp);
3109 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3110 Kind = tok::greaterequal;
3111 } else if (Char == '>') {
3112 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3114 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3116 Kind = tok::greatergreaterequal;
3117 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3118 // If this is actually a '>>>>' conflict marker, recognize it as such
3119 // and recover nicely.
3121 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3122 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3124 } else if (LangOpts.CUDA && After == '>') {
3125 Kind = tok::greatergreatergreater;
3126 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3129 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3130 Kind = tok::greatergreater;
3134 Kind = tok::greater;
3138 Char = getCharAndSize(CurPtr, SizeTmp);
3140 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3141 Kind = tok::caretequal;
3147 Char = getCharAndSize(CurPtr, SizeTmp);
3149 Kind = tok::pipeequal;
3150 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3151 } else if (Char == '|') {
3152 // If this is '|||||||' and we're in a conflict marker, ignore it.
3153 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3155 Kind = tok::pipepipe;
3156 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3162 Char = getCharAndSize(CurPtr, SizeTmp);
3163 if (LangOpts.Digraphs && Char == '>') {
3164 Kind = tok::r_square; // ':>' -> ']'
3165 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3166 } else if (LangOpts.CPlusPlus && Char == ':') {
3167 Kind = tok::coloncolon;
3168 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3177 Char = getCharAndSize(CurPtr, SizeTmp);
3179 // If this is '====' and we're in a conflict marker, ignore it.
3180 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3183 Kind = tok::equalequal;
3184 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3193 Char = getCharAndSize(CurPtr, SizeTmp);
3195 Kind = tok::hashhash;
3196 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3197 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3199 if (!isLexingRawMode())
3200 Diag(BufferPtr, diag::ext_charize_microsoft);
3201 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3203 // We parsed a # character. If this occurs at the start of the line,
3204 // it's actually the start of a preprocessing directive. Callback to
3205 // the preprocessor to handle it.
3206 // FIXME: -fpreprocessed mode??
3207 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) {
3208 FormTokenWithChars(Result, CurPtr, tok::hash);
3209 PP->HandleDirective(Result);
3211 // As an optimization, if the preprocessor didn't switch lexers, tail
3213 if (PP->isCurrentLexer(this)) {
3214 // Start a new token. If this is a #include or something, the PP may
3215 // want us starting at the beginning of the line again. If so, set
3216 // the StartOfLine flag and clear LeadingSpace.
3217 if (IsAtStartOfLine) {
3218 Result.setFlag(Token::StartOfLine);
3219 Result.clearFlag(Token::LeadingSpace);
3220 IsAtStartOfLine = false;
3222 goto LexNextToken; // GCC isn't tail call eliminating.
3224 return PP->Lex(Result);
3232 // Objective C support.
3233 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3236 Kind = tok::unknown;
3243 Kind = tok::unknown;
3247 // Notify MIOpt that we read a non-whitespace/non-comment token.
3250 // Update the location of token as well as BufferPtr.
3251 FormTokenWithChars(Result, CurPtr, Kind);