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/Basic/CharInfo.h"
29 #include "clang/Basic/SourceManager.h"
30 #include "clang/Lex/CodeCompletionHandler.h"
31 #include "clang/Lex/LexDiagnostic.h"
32 #include "clang/Lex/Preprocessor.h"
33 #include "llvm/ADT/STLExtras.h"
34 #include "llvm/ADT/StringExtras.h"
35 #include "llvm/ADT/StringSwitch.h"
36 #include "llvm/Support/Compiler.h"
37 #include "llvm/Support/ConvertUTF.h"
38 #include "llvm/Support/MemoryBuffer.h"
39 #include "UnicodeCharSets.h"
41 using namespace clang;
43 //===----------------------------------------------------------------------===//
44 // Token Class Implementation
45 //===----------------------------------------------------------------------===//
47 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
48 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
49 if (IdentifierInfo *II = getIdentifierInfo())
50 return II->getObjCKeywordID() == objcKey;
54 /// getObjCKeywordID - Return the ObjC keyword kind.
55 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
56 IdentifierInfo *specId = getIdentifierInfo();
57 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
61 //===----------------------------------------------------------------------===//
62 // Lexer Class Implementation
63 //===----------------------------------------------------------------------===//
65 void Lexer::anchor() { }
67 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
69 BufferStart = BufStart;
73 assert(BufEnd[0] == 0 &&
74 "We assume that the input buffer has a null character at the end"
75 " to simplify lexing!");
77 // Check whether we have a BOM in the beginning of the buffer. If yes - act
78 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
79 // skip the UTF-8 BOM if it's present.
80 if (BufferStart == BufferPtr) {
81 // Determine the size of the BOM.
82 StringRef Buf(BufferStart, BufferEnd - BufferStart);
83 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
84 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
88 BufferPtr += BOMLength;
91 Is_PragmaLexer = false;
92 CurrentConflictMarkerState = CMK_None;
94 // Start of the file is a start of line.
95 IsAtStartOfLine = true;
97 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
100 // We are not after parsing #include.
101 ParsingFilename = false;
103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
113 /// Lexer constructor - Create a new lexer object for the specified buffer
114 /// with the specified preprocessor managing the lexing process. This lexer
115 /// assumes that the associated file buffer and Preprocessor objects will
116 /// outlive it, so it doesn't take ownership of either of them.
117 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
120 LangOpts(PP.getLangOpts()) {
122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
125 resetExtendedTokenMode();
128 void Lexer::resetExtendedTokenMode() {
129 assert(PP && "Cannot reset token mode without a preprocessor");
130 if (LangOpts.TraditionalCPP)
131 SetKeepWhitespaceMode(true);
133 SetCommentRetentionState(PP->getCommentRetentionState());
136 /// Lexer constructor - Create a new raw lexer object. This object is only
137 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
138 /// range will outlive it, so it doesn't take ownership of it.
139 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
140 const char *BufStart, const char *BufPtr, const char *BufEnd)
141 : FileLoc(fileloc), LangOpts(langOpts) {
143 InitLexer(BufStart, BufPtr, BufEnd);
145 // We *are* in raw mode.
146 LexingRawMode = true;
149 /// Lexer constructor - Create a new raw lexer object. This object is only
150 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
151 /// range will outlive it, so it doesn't take ownership of it.
152 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
153 const SourceManager &SM, const LangOptions &langOpts)
154 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
156 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
157 FromFile->getBufferEnd());
159 // We *are* in raw mode.
160 LexingRawMode = true;
163 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
164 /// _Pragma expansion. This has a variety of magic semantics that this method
165 /// sets up. It returns a new'd Lexer that must be delete'd when done.
167 /// On entrance to this routine, TokStartLoc is a macro location which has a
168 /// spelling loc that indicates the bytes to be lexed for the token and an
169 /// expansion location that indicates where all lexed tokens should be
172 /// FIXME: It would really be nice to make _Pragma just be a wrapper around a
173 /// normal lexer that remaps tokens as they fly by. This would require making
174 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
175 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
176 /// out of the critical path of the lexer!
178 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
179 SourceLocation ExpansionLocStart,
180 SourceLocation ExpansionLocEnd,
181 unsigned TokLen, Preprocessor &PP) {
182 SourceManager &SM = PP.getSourceManager();
184 // Create the lexer as if we were going to lex the file normally.
185 FileID SpellingFID = SM.getFileID(SpellingLoc);
186 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
187 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
189 // Now that the lexer is created, change the start/end locations so that we
190 // just lex the subsection of the file that we want. This is lexing from a
192 const char *StrData = SM.getCharacterData(SpellingLoc);
194 L->BufferPtr = StrData;
195 L->BufferEnd = StrData+TokLen;
196 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
198 // Set the SourceLocation with the remapping information. This ensures that
199 // GetMappedTokenLoc will remap the tokens as they are lexed.
200 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
202 ExpansionLocEnd, TokLen);
204 // Ensure that the lexer thinks it is inside a directive, so that end \n will
205 // return an EOD token.
206 L->ParsingPreprocessorDirective = true;
208 // This lexer really is for _Pragma.
209 L->Is_PragmaLexer = true;
214 /// Stringify - Convert the specified string into a C string, with surrounding
215 /// ""'s, and with escaped \ and " characters.
216 std::string Lexer::Stringify(const std::string &Str, bool Charify) {
217 std::string Result = Str;
218 char Quote = Charify ? '\'' : '"';
219 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
220 if (Result[i] == '\\' || Result[i] == Quote) {
221 Result.insert(Result.begin()+i, '\\');
228 /// Stringify - Convert the specified string into a C string by escaping '\'
229 /// and " characters. This does not add surrounding ""'s to the string.
230 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
231 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
232 if (Str[i] == '\\' || Str[i] == '"') {
233 Str.insert(Str.begin()+i, '\\');
239 //===----------------------------------------------------------------------===//
241 //===----------------------------------------------------------------------===//
243 /// \brief Slow case of getSpelling. Extract the characters comprising the
244 /// spelling of this token from the provided input buffer.
245 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
246 const LangOptions &LangOpts, char *Spelling) {
247 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
250 const char *BufEnd = BufPtr + Tok.getLength();
252 if (Tok.is(tok::string_literal)) {
253 // Munch the encoding-prefix and opening double-quote.
254 while (BufPtr < BufEnd) {
256 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
259 if (Spelling[Length - 1] == '"')
263 // Raw string literals need special handling; trigraph expansion and line
264 // splicing do not occur within their d-char-sequence nor within their
267 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
268 // Search backwards from the end of the token to find the matching closing
270 const char *RawEnd = BufEnd;
271 do --RawEnd; while (*RawEnd != '"');
272 size_t RawLength = RawEnd - BufPtr + 1;
274 // Everything between the quotes is included verbatim in the spelling.
275 memcpy(Spelling + Length, BufPtr, RawLength);
279 // The rest of the token is lexed normally.
283 while (BufPtr < BufEnd) {
285 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
289 assert(Length < Tok.getLength() &&
290 "NeedsCleaning flag set on token that didn't need cleaning!");
294 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
295 /// token are the characters used to represent the token in the source file
296 /// after trigraph expansion and escaped-newline folding. In particular, this
297 /// wants to get the true, uncanonicalized, spelling of things like digraphs
299 StringRef Lexer::getSpelling(SourceLocation loc,
300 SmallVectorImpl<char> &buffer,
301 const SourceManager &SM,
302 const LangOptions &options,
304 // Break down the source location.
305 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
307 // Try to the load the file buffer.
308 bool invalidTemp = false;
309 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
311 if (invalid) *invalid = true;
315 const char *tokenBegin = file.data() + locInfo.second;
317 // Lex from the start of the given location.
318 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
319 file.begin(), tokenBegin, file.end());
321 lexer.LexFromRawLexer(token);
323 unsigned length = token.getLength();
325 // Common case: no need for cleaning.
326 if (!token.needsCleaning())
327 return StringRef(tokenBegin, length);
329 // Hard case, we need to relex the characters into the string.
330 buffer.resize(length);
331 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
332 return StringRef(buffer.data(), buffer.size());
335 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
336 /// token are the characters used to represent the token in the source file
337 /// after trigraph expansion and escaped-newline folding. In particular, this
338 /// wants to get the true, uncanonicalized, spelling of things like digraphs
340 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
341 const LangOptions &LangOpts, bool *Invalid) {
342 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
344 bool CharDataInvalid = false;
345 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
348 *Invalid = CharDataInvalid;
350 return std::string();
352 // If this token contains nothing interesting, return it directly.
353 if (!Tok.needsCleaning())
354 return std::string(TokStart, TokStart + Tok.getLength());
357 Result.resize(Tok.getLength());
358 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
362 /// getSpelling - This method is used to get the spelling of a token into a
363 /// preallocated buffer, instead of as an std::string. The caller is required
364 /// to allocate enough space for the token, which is guaranteed to be at least
365 /// Tok.getLength() bytes long. The actual length of the token is returned.
367 /// Note that this method may do two possible things: it may either fill in
368 /// the buffer specified with characters, or it may *change the input pointer*
369 /// to point to a constant buffer with the data already in it (avoiding a
370 /// copy). The caller is not allowed to modify the returned buffer pointer
371 /// if an internal buffer is returned.
372 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
373 const SourceManager &SourceMgr,
374 const LangOptions &LangOpts, bool *Invalid) {
375 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
377 const char *TokStart = 0;
378 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
379 if (Tok.is(tok::raw_identifier))
380 TokStart = Tok.getRawIdentifierData();
381 else if (!Tok.hasUCN()) {
382 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
383 // Just return the string from the identifier table, which is very quick.
384 Buffer = II->getNameStart();
385 return II->getLength();
389 // NOTE: this can be checked even after testing for an IdentifierInfo.
391 TokStart = Tok.getLiteralData();
394 // Compute the start of the token in the input lexer buffer.
395 bool CharDataInvalid = false;
396 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
398 *Invalid = CharDataInvalid;
399 if (CharDataInvalid) {
405 // If this token contains nothing interesting, return it directly.
406 if (!Tok.needsCleaning()) {
408 return Tok.getLength();
411 // Otherwise, hard case, relex the characters into the string.
412 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
416 /// MeasureTokenLength - Relex the token at the specified location and return
417 /// its length in bytes in the input file. If the token needs cleaning (e.g.
418 /// includes a trigraph or an escaped newline) then this count includes bytes
419 /// that are part of that.
420 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
421 const SourceManager &SM,
422 const LangOptions &LangOpts) {
424 if (getRawToken(Loc, TheTok, SM, LangOpts))
426 return TheTok.getLength();
429 /// \brief Relex the token at the specified location.
430 /// \returns true if there was a failure, false on success.
431 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
432 const SourceManager &SM,
433 const LangOptions &LangOpts) {
434 // TODO: this could be special cased for common tokens like identifiers, ')',
435 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
436 // all obviously single-char tokens. This could use
437 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
440 // If this comes from a macro expansion, we really do want the macro name, not
441 // the token this macro expanded to.
442 Loc = SM.getExpansionLoc(Loc);
443 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
444 bool Invalid = false;
445 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
449 const char *StrData = Buffer.data()+LocInfo.second;
451 if (isWhitespace(StrData[0]))
454 // Create a lexer starting at the beginning of this token.
455 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
456 Buffer.begin(), StrData, Buffer.end());
457 TheLexer.SetCommentRetentionState(true);
458 TheLexer.LexFromRawLexer(Result);
462 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
463 const SourceManager &SM,
464 const LangOptions &LangOpts) {
465 assert(Loc.isFileID());
466 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
467 if (LocInfo.first.isInvalid())
470 bool Invalid = false;
471 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
475 // Back up from the current location until we hit the beginning of a line
476 // (or the buffer). We'll relex from that point.
477 const char *BufStart = Buffer.data();
478 if (LocInfo.second >= Buffer.size())
481 const char *StrData = BufStart+LocInfo.second;
482 if (StrData[0] == '\n' || StrData[0] == '\r')
485 const char *LexStart = StrData;
486 while (LexStart != BufStart) {
487 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
495 // Create a lexer starting at the beginning of this token.
496 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
497 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
498 TheLexer.SetCommentRetentionState(true);
500 // Lex tokens until we find the token that contains the source location.
503 TheLexer.LexFromRawLexer(TheTok);
505 if (TheLexer.getBufferLocation() > StrData) {
506 // Lexing this token has taken the lexer past the source location we're
507 // looking for. If the current token encompasses our source location,
508 // return the beginning of that token.
509 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
510 return TheTok.getLocation();
512 // We ended up skipping over the source location entirely, which means
513 // that it points into whitespace. We're done here.
516 } while (TheTok.getKind() != tok::eof);
518 // We've passed our source location; just return the original source location.
522 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
523 const SourceManager &SM,
524 const LangOptions &LangOpts) {
526 return getBeginningOfFileToken(Loc, SM, LangOpts);
528 if (!SM.isMacroArgExpansion(Loc))
531 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
532 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
533 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
534 std::pair<FileID, unsigned> BeginFileLocInfo
535 = SM.getDecomposedLoc(BeginFileLoc);
536 assert(FileLocInfo.first == BeginFileLocInfo.first &&
537 FileLocInfo.second >= BeginFileLocInfo.second);
538 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
542 enum PreambleDirectiveKind {
550 std::pair<unsigned, bool>
551 Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
552 const LangOptions &LangOpts, unsigned MaxLines) {
553 // Create a lexer starting at the beginning of the file. Note that we use a
554 // "fake" file source location at offset 1 so that the lexer will track our
555 // position within the file.
556 const unsigned StartOffset = 1;
557 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
558 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
559 Buffer->getBufferStart(), Buffer->getBufferEnd());
560 TheLexer.SetCommentRetentionState(true);
562 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
563 SourceLocation StartLoc = TheLexer.getSourceLocation();
565 bool InPreprocessorDirective = false;
568 unsigned IfCount = 0;
569 SourceLocation ActiveCommentLoc;
571 unsigned MaxLineOffset = 0;
573 const char *CurPtr = Buffer->getBufferStart();
574 unsigned CurLine = 0;
575 while (CurPtr != Buffer->getBufferEnd()) {
579 if (CurLine == MaxLines)
583 if (CurPtr != Buffer->getBufferEnd())
584 MaxLineOffset = CurPtr - Buffer->getBufferStart();
588 TheLexer.LexFromRawLexer(TheTok);
590 if (InPreprocessorDirective) {
591 // If we've hit the end of the file, we're done.
592 if (TheTok.getKind() == tok::eof) {
596 // If we haven't hit the end of the preprocessor directive, skip this
598 if (!TheTok.isAtStartOfLine())
601 // We've passed the end of the preprocessor directive, and will look
602 // at this token again below.
603 InPreprocessorDirective = false;
606 // Keep track of the # of lines in the preamble.
607 if (TheTok.isAtStartOfLine()) {
608 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
610 // If we were asked to limit the number of lines in the preamble,
611 // and we're about to exceed that limit, we're done.
612 if (MaxLineOffset && TokOffset >= MaxLineOffset)
616 // Comments are okay; skip over them.
617 if (TheTok.getKind() == tok::comment) {
618 if (ActiveCommentLoc.isInvalid())
619 ActiveCommentLoc = TheTok.getLocation();
623 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
624 // This is the start of a preprocessor directive.
625 Token HashTok = TheTok;
626 InPreprocessorDirective = true;
627 ActiveCommentLoc = SourceLocation();
629 // Figure out which directive this is. Since we're lexing raw tokens,
630 // we don't have an identifier table available. Instead, just look at
631 // the raw identifier to recognize and categorize preprocessor directives.
632 TheLexer.LexFromRawLexer(TheTok);
633 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
634 StringRef Keyword(TheTok.getRawIdentifierData(),
636 PreambleDirectiveKind PDK
637 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
638 .Case("include", PDK_Skipped)
639 .Case("__include_macros", PDK_Skipped)
640 .Case("define", PDK_Skipped)
641 .Case("undef", PDK_Skipped)
642 .Case("line", PDK_Skipped)
643 .Case("error", PDK_Skipped)
644 .Case("pragma", PDK_Skipped)
645 .Case("import", PDK_Skipped)
646 .Case("include_next", PDK_Skipped)
647 .Case("warning", PDK_Skipped)
648 .Case("ident", PDK_Skipped)
649 .Case("sccs", PDK_Skipped)
650 .Case("assert", PDK_Skipped)
651 .Case("unassert", PDK_Skipped)
652 .Case("if", PDK_StartIf)
653 .Case("ifdef", PDK_StartIf)
654 .Case("ifndef", PDK_StartIf)
655 .Case("elif", PDK_Skipped)
656 .Case("else", PDK_Skipped)
657 .Case("endif", PDK_EndIf)
658 .Default(PDK_Unknown);
666 IfStartTok = HashTok;
672 // Mismatched #endif. The preamble ends here.
680 // We don't know what this directive is; stop at the '#'.
685 // We only end up here if we didn't recognize the preprocessor
686 // directive or it was one that can't occur in the preamble at this
687 // point. Roll back the current token to the location of the '#'.
688 InPreprocessorDirective = false;
692 // We hit a token that we don't recognize as being in the
693 // "preprocessing only" part of the file, so we're no longer in
700 End = IfStartTok.getLocation();
701 else if (ActiveCommentLoc.isValid())
702 End = ActiveCommentLoc; // don't truncate a decl comment.
704 End = TheTok.getLocation();
706 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
707 IfCount? IfStartTok.isAtStartOfLine()
708 : TheTok.isAtStartOfLine());
712 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
713 /// token, return a new location that specifies a character within the token.
714 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
716 const SourceManager &SM,
717 const LangOptions &LangOpts) {
718 // Figure out how many physical characters away the specified expansion
719 // character is. This needs to take into consideration newlines and
721 bool Invalid = false;
722 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
724 // If they request the first char of the token, we're trivially done.
725 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
728 unsigned PhysOffset = 0;
730 // The usual case is that tokens don't contain anything interesting. Skip
731 // over the uninteresting characters. If a token only consists of simple
732 // chars, this method is extremely fast.
733 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
735 return TokStart.getLocWithOffset(PhysOffset);
736 ++TokPtr, --CharNo, ++PhysOffset;
739 // If we have a character that may be a trigraph or escaped newline, use a
740 // lexer to parse it correctly.
741 for (; CharNo; --CharNo) {
743 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
748 // Final detail: if we end up on an escaped newline, we want to return the
749 // location of the actual byte of the token. For example foo\<newline>bar
750 // advanced by 3 should return the location of b, not of \\. One compounding
751 // detail of this is that the escape may be made by a trigraph.
752 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
753 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
755 return TokStart.getLocWithOffset(PhysOffset);
758 /// \brief Computes the source location just past the end of the
759 /// token at this source location.
761 /// This routine can be used to produce a source location that
762 /// points just past the end of the token referenced by \p Loc, and
763 /// is generally used when a diagnostic needs to point just after a
764 /// token where it expected something different that it received. If
765 /// the returned source location would not be meaningful (e.g., if
766 /// it points into a macro), this routine returns an invalid
769 /// \param Offset an offset from the end of the token, where the source
770 /// location should refer to. The default offset (0) produces a source
771 /// location pointing just past the end of the token; an offset of 1 produces
772 /// a source location pointing to the last character in the token, etc.
773 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
774 const SourceManager &SM,
775 const LangOptions &LangOpts) {
777 return SourceLocation();
779 if (Loc.isMacroID()) {
780 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
781 return SourceLocation(); // Points inside the macro expansion.
784 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
790 return Loc.getLocWithOffset(Len);
793 /// \brief Returns true if the given MacroID location points at the first
794 /// token of the macro expansion.
795 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
796 const SourceManager &SM,
797 const LangOptions &LangOpts,
798 SourceLocation *MacroBegin) {
799 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
801 std::pair<FileID, unsigned> infoLoc = SM.getDecomposedLoc(loc);
802 // FIXME: If the token comes from the macro token paste operator ('##')
803 // this function will always return false;
804 if (infoLoc.second > 0)
805 return false; // Does not point at the start of token.
807 SourceLocation expansionLoc =
808 SM.getSLocEntry(infoLoc.first).getExpansion().getExpansionLocStart();
809 if (expansionLoc.isFileID()) {
810 // No other macro expansions, this is the first.
812 *MacroBegin = expansionLoc;
816 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
819 /// \brief Returns true if the given MacroID location points at the last
820 /// token of the macro expansion.
821 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
822 const SourceManager &SM,
823 const LangOptions &LangOpts,
824 SourceLocation *MacroEnd) {
825 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
827 SourceLocation spellLoc = SM.getSpellingLoc(loc);
828 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
832 FileID FID = SM.getFileID(loc);
833 SourceLocation afterLoc = loc.getLocWithOffset(tokLen+1);
834 if (SM.isInFileID(afterLoc, FID))
835 return false; // Still in the same FileID, does not point to the last token.
837 // FIXME: If the token comes from the macro token paste operator ('##')
838 // or the stringify operator ('#') this function will always return false;
840 SourceLocation expansionLoc =
841 SM.getSLocEntry(FID).getExpansion().getExpansionLocEnd();
842 if (expansionLoc.isFileID()) {
843 // No other macro expansions.
845 *MacroEnd = expansionLoc;
849 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
852 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
853 const SourceManager &SM,
854 const LangOptions &LangOpts) {
855 SourceLocation Begin = Range.getBegin();
856 SourceLocation End = Range.getEnd();
857 assert(Begin.isFileID() && End.isFileID());
858 if (Range.isTokenRange()) {
859 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
861 return CharSourceRange();
864 // Break down the source locations.
867 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
869 return CharSourceRange();
872 if (!SM.isInFileID(End, FID, &EndOffs) ||
874 return CharSourceRange();
876 return CharSourceRange::getCharRange(Begin, End);
879 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
880 const SourceManager &SM,
881 const LangOptions &LangOpts) {
882 SourceLocation Begin = Range.getBegin();
883 SourceLocation End = Range.getEnd();
884 if (Begin.isInvalid() || End.isInvalid())
885 return CharSourceRange();
887 if (Begin.isFileID() && End.isFileID())
888 return makeRangeFromFileLocs(Range, SM, LangOpts);
890 if (Begin.isMacroID() && End.isFileID()) {
891 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
892 return CharSourceRange();
893 Range.setBegin(Begin);
894 return makeRangeFromFileLocs(Range, SM, LangOpts);
897 if (Begin.isFileID() && End.isMacroID()) {
898 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
900 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
902 return CharSourceRange();
904 return makeRangeFromFileLocs(Range, SM, LangOpts);
907 assert(Begin.isMacroID() && End.isMacroID());
908 SourceLocation MacroBegin, MacroEnd;
909 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
910 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
912 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
914 Range.setBegin(MacroBegin);
915 Range.setEnd(MacroEnd);
916 return makeRangeFromFileLocs(Range, SM, LangOpts);
921 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
923 return CharSourceRange();
926 if (!SM.isInFileID(End, FID, &EndOffs) ||
928 return CharSourceRange();
930 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
931 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
932 if (Expansion.isMacroArgExpansion() &&
933 Expansion.getSpellingLoc().isFileID()) {
934 SourceLocation SpellLoc = Expansion.getSpellingLoc();
935 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs));
936 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs));
937 return makeRangeFromFileLocs(Range, SM, LangOpts);
940 return CharSourceRange();
943 StringRef Lexer::getSourceText(CharSourceRange Range,
944 const SourceManager &SM,
945 const LangOptions &LangOpts,
947 Range = makeFileCharRange(Range, SM, LangOpts);
948 if (Range.isInvalid()) {
949 if (Invalid) *Invalid = true;
953 // Break down the source location.
954 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
955 if (beginInfo.first.isInvalid()) {
956 if (Invalid) *Invalid = true;
961 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
962 beginInfo.second > EndOffs) {
963 if (Invalid) *Invalid = true;
967 // Try to the load the file buffer.
968 bool invalidTemp = false;
969 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
971 if (Invalid) *Invalid = true;
975 if (Invalid) *Invalid = false;
976 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
979 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
980 const SourceManager &SM,
981 const LangOptions &LangOpts) {
982 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
984 // Find the location of the immediate macro expansion.
986 FileID FID = SM.getFileID(Loc);
987 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
988 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
989 Loc = Expansion.getExpansionLocStart();
990 if (!Expansion.isMacroArgExpansion())
993 // For macro arguments we need to check that the argument did not come
994 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
996 // Loc points to the argument id of the macro definition, move to the
998 Loc = SM.getImmediateExpansionRange(Loc).first;
999 SourceLocation SpellLoc = Expansion.getSpellingLoc();
1000 if (SpellLoc.isFileID())
1001 break; // No inner macro.
1003 // If spelling location resides in the same FileID as macro expansion
1004 // location, it means there is no inner macro.
1005 FileID MacroFID = SM.getFileID(Loc);
1006 if (SM.isInFileID(SpellLoc, MacroFID))
1009 // Argument came from inner macro.
1013 // Find the spelling location of the start of the non-argument expansion
1014 // range. This is where the macro name was spelled in order to begin
1015 // expanding this macro.
1016 Loc = SM.getSpellingLoc(Loc);
1018 // Dig out the buffer where the macro name was spelled and the extents of the
1019 // name so that we can render it into the expansion note.
1020 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1021 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1022 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1023 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1026 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1027 return isIdentifierBody(c, LangOpts.DollarIdents);
1031 //===----------------------------------------------------------------------===//
1032 // Diagnostics forwarding code.
1033 //===----------------------------------------------------------------------===//
1035 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1036 /// lexer buffer was all expanded at a single point, perform the mapping.
1037 /// This is currently only used for _Pragma implementation, so it is the slow
1038 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1039 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1040 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1041 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1042 SourceLocation FileLoc,
1043 unsigned CharNo, unsigned TokLen) {
1044 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1046 // Otherwise, we're lexing "mapped tokens". This is used for things like
1047 // _Pragma handling. Combine the expansion location of FileLoc with the
1048 // spelling location.
1049 SourceManager &SM = PP.getSourceManager();
1051 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1052 // characters come from spelling(FileLoc)+Offset.
1053 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1054 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1056 // Figure out the expansion loc range, which is the range covered by the
1057 // original _Pragma(...) sequence.
1058 std::pair<SourceLocation,SourceLocation> II =
1059 SM.getImmediateExpansionRange(FileLoc);
1061 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1064 /// getSourceLocation - Return a source location identifier for the specified
1065 /// offset in the current file.
1066 SourceLocation Lexer::getSourceLocation(const char *Loc,
1067 unsigned TokLen) const {
1068 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1069 "Location out of range for this buffer!");
1071 // In the normal case, we're just lexing from a simple file buffer, return
1072 // the file id from FileLoc with the offset specified.
1073 unsigned CharNo = Loc-BufferStart;
1074 if (FileLoc.isFileID())
1075 return FileLoc.getLocWithOffset(CharNo);
1077 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1078 // tokens are lexed from where the _Pragma was defined.
1079 assert(PP && "This doesn't work on raw lexers");
1080 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1083 /// Diag - Forwarding function for diagnostics. This translate a source
1084 /// position in the current buffer into a SourceLocation object for rendering.
1085 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1086 return PP->Diag(getSourceLocation(Loc), DiagID);
1089 //===----------------------------------------------------------------------===//
1090 // Trigraph and Escaped Newline Handling Code.
1091 //===----------------------------------------------------------------------===//
1093 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1094 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1095 static char GetTrigraphCharForLetter(char Letter) {
1098 case '=': return '#';
1099 case ')': return ']';
1100 case '(': return '[';
1101 case '!': return '|';
1102 case '\'': return '^';
1103 case '>': return '}';
1104 case '/': return '\\';
1105 case '<': return '{';
1106 case '-': return '~';
1110 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1111 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1112 /// return the result character. Finally, emit a warning about trigraph use
1113 /// whether trigraphs are enabled or not.
1114 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1115 char Res = GetTrigraphCharForLetter(*CP);
1116 if (!Res || !L) return Res;
1118 if (!L->getLangOpts().Trigraphs) {
1119 if (!L->isLexingRawMode())
1120 L->Diag(CP-2, diag::trigraph_ignored);
1124 if (!L->isLexingRawMode())
1125 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1129 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1130 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1131 /// trigraph equivalent on entry to this function.
1132 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1134 while (isWhitespace(Ptr[Size])) {
1137 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1140 // If this is a \r\n or \n\r, skip the other half.
1141 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1142 Ptr[Size-1] != Ptr[Size])
1148 // Not an escaped newline, must be a \t or something else.
1152 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1153 /// them), skip over them and return the first non-escaped-newline found,
1154 /// otherwise return P.
1155 const char *Lexer::SkipEscapedNewLines(const char *P) {
1157 const char *AfterEscape;
1160 } else if (*P == '?') {
1161 // If not a trigraph for escape, bail out.
1162 if (P[1] != '?' || P[2] != '/')
1169 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1170 if (NewLineSize == 0) return P;
1171 P = AfterEscape+NewLineSize;
1175 /// \brief Checks that the given token is the first token that occurs after the
1176 /// given location (this excludes comments and whitespace). Returns the location
1177 /// immediately after the specified token. If the token is not found or the
1178 /// location is inside a macro, the returned source location will be invalid.
1179 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1180 tok::TokenKind TKind,
1181 const SourceManager &SM,
1182 const LangOptions &LangOpts,
1183 bool SkipTrailingWhitespaceAndNewLine) {
1184 if (Loc.isMacroID()) {
1185 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1186 return SourceLocation();
1188 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1190 // Break down the source location.
1191 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1193 // Try to load the file buffer.
1194 bool InvalidTemp = false;
1195 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1197 return SourceLocation();
1199 const char *TokenBegin = File.data() + LocInfo.second;
1201 // Lex from the start of the given location.
1202 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1203 TokenBegin, File.end());
1206 lexer.LexFromRawLexer(Tok);
1207 if (Tok.isNot(TKind))
1208 return SourceLocation();
1209 SourceLocation TokenLoc = Tok.getLocation();
1211 // Calculate how much whitespace needs to be skipped if any.
1212 unsigned NumWhitespaceChars = 0;
1213 if (SkipTrailingWhitespaceAndNewLine) {
1214 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1216 unsigned char C = *TokenEnd;
1217 while (isHorizontalWhitespace(C)) {
1219 NumWhitespaceChars++;
1222 // Skip \r, \n, \r\n, or \n\r
1223 if (C == '\n' || C == '\r') {
1226 NumWhitespaceChars++;
1227 if ((C == '\n' || C == '\r') && C != PrevC)
1228 NumWhitespaceChars++;
1232 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1235 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1236 /// get its size, and return it. This is tricky in several cases:
1237 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1238 /// then either return the trigraph (skipping 3 chars) or the '?',
1239 /// depending on whether trigraphs are enabled or not.
1240 /// 2. If this is an escaped newline (potentially with whitespace between
1241 /// the backslash and newline), implicitly skip the newline and return
1242 /// the char after it.
1244 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1245 /// know that we can accumulate into Size, and that we have already incremented
1246 /// Ptr by Size bytes.
1248 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1249 /// be updated to match.
1251 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1253 // If we have a slash, look for an escaped newline.
1254 if (Ptr[0] == '\\') {
1258 // Common case, backslash-char where the char is not whitespace.
1259 if (!isWhitespace(Ptr[0])) return '\\';
1261 // See if we have optional whitespace characters between the slash and
1263 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1264 // Remember that this token needs to be cleaned.
1265 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1267 // Warn if there was whitespace between the backslash and newline.
1268 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1269 Diag(Ptr, diag::backslash_newline_space);
1271 // Found backslash<whitespace><newline>. Parse the char after it.
1272 Size += EscapedNewLineSize;
1273 Ptr += EscapedNewLineSize;
1275 // If the char that we finally got was a \n, then we must have had
1276 // something like \<newline><newline>. We don't want to consume the
1278 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1281 // Use slow version to accumulate a correct size field.
1282 return getCharAndSizeSlow(Ptr, Size, Tok);
1285 // Otherwise, this is not an escaped newline, just return the slash.
1289 // If this is a trigraph, process it.
1290 if (Ptr[0] == '?' && Ptr[1] == '?') {
1291 // If this is actually a legal trigraph (not something like "??x"), emit
1292 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1293 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) {
1294 // Remember that this token needs to be cleaned.
1295 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1299 if (C == '\\') goto Slash;
1304 // If this is neither, return a single character.
1310 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1311 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1312 /// and that we have already incremented Ptr by Size bytes.
1314 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1315 /// be updated to match.
1316 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1317 const LangOptions &LangOpts) {
1318 // If we have a slash, look for an escaped newline.
1319 if (Ptr[0] == '\\') {
1323 // Common case, backslash-char where the char is not whitespace.
1324 if (!isWhitespace(Ptr[0])) return '\\';
1326 // See if we have optional whitespace characters followed by a newline.
1327 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1328 // Found backslash<whitespace><newline>. Parse the char after it.
1329 Size += EscapedNewLineSize;
1330 Ptr += EscapedNewLineSize;
1332 // If the char that we finally got was a \n, then we must have had
1333 // something like \<newline><newline>. We don't want to consume the
1335 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1338 // Use slow version to accumulate a correct size field.
1339 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1342 // Otherwise, this is not an escaped newline, just return the slash.
1346 // If this is a trigraph, process it.
1347 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1348 // If this is actually a legal trigraph (not something like "??x"), return
1350 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1353 if (C == '\\') goto Slash;
1358 // If this is neither, return a single character.
1363 //===----------------------------------------------------------------------===//
1364 // Helper methods for lexing.
1365 //===----------------------------------------------------------------------===//
1367 /// \brief Routine that indiscriminately skips bytes in the source file.
1368 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1370 if (BufferPtr > BufferEnd)
1371 BufferPtr = BufferEnd;
1372 IsAtStartOfLine = StartOfLine;
1375 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1376 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1377 return isCharInSet(C, C11AllowedIDChars);
1378 else if (LangOpts.CPlusPlus)
1379 return isCharInSet(C, CXX03AllowedIDChars);
1381 return isCharInSet(C, C99AllowedIDChars);
1384 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1385 assert(isAllowedIDChar(C, LangOpts));
1386 if (LangOpts.CPlusPlus11 || LangOpts.C11)
1387 return !isCharInSet(C, C11DisallowedInitialIDChars);
1388 else if (LangOpts.CPlusPlus)
1391 return !isCharInSet(C, C99DisallowedInitialIDChars);
1394 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1396 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1397 L.getSourceLocation(End));
1400 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1401 CharSourceRange Range, bool IsFirst) {
1402 // Check C99 compatibility.
1403 if (Diags.getDiagnosticLevel(diag::warn_c99_compat_unicode_id,
1404 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1406 CannotAppearInIdentifier = 0,
1407 CannotStartIdentifier
1410 if (!isCharInSet(C, C99AllowedIDChars)) {
1411 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1413 << CannotAppearInIdentifier;
1414 } else if (IsFirst && isCharInSet(C, C99DisallowedInitialIDChars)) {
1415 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1417 << CannotStartIdentifier;
1421 // Check C++98 compatibility.
1422 if (Diags.getDiagnosticLevel(diag::warn_cxx98_compat_unicode_id,
1423 Range.getBegin()) > DiagnosticsEngine::Ignored) {
1424 if (!isCharInSet(C, CXX03AllowedIDChars)) {
1425 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1431 void Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1432 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1434 unsigned char C = *CurPtr++;
1435 while (isIdentifierBody(C))
1438 --CurPtr; // Back up over the skipped character.
1440 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1441 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1443 // TODO: Could merge these checks into an InfoTable flag to make the
1444 // comparison cheaper
1445 if (isASCII(C) && C != '\\' && C != '?' &&
1446 (C != '$' || !LangOpts.DollarIdents)) {
1448 const char *IdStart = BufferPtr;
1449 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1450 Result.setRawIdentifierData(IdStart);
1452 // If we are in raw mode, return this identifier raw. There is no need to
1453 // look up identifier information or attempt to macro expand it.
1457 // Fill in Result.IdentifierInfo and update the token kind,
1458 // looking up the identifier in the identifier table.
1459 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1461 // Finally, now that we know we have an identifier, pass this off to the
1462 // preprocessor, which may macro expand it or something.
1463 if (II->isHandleIdentifierCase())
1464 PP->HandleIdentifier(Result);
1469 // Otherwise, $,\,? in identifier found. Enter slower path.
1471 C = getCharAndSize(CurPtr, Size);
1474 // If we hit a $ and they are not supported in identifiers, we are done.
1475 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1477 // Otherwise, emit a diagnostic and continue.
1478 if (!isLexingRawMode())
1479 Diag(CurPtr, diag::ext_dollar_in_identifier);
1480 CurPtr = ConsumeChar(CurPtr, Size, Result);
1481 C = getCharAndSize(CurPtr, Size);
1484 } else if (C == '\\') {
1485 const char *UCNPtr = CurPtr + Size;
1486 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/0);
1487 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1488 goto FinishIdentifier;
1490 if (!isLexingRawMode()) {
1491 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1492 makeCharRange(*this, CurPtr, UCNPtr),
1496 Result.setFlag(Token::HasUCN);
1497 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1498 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1501 while (CurPtr != UCNPtr)
1502 (void)getAndAdvanceChar(CurPtr, Result);
1504 C = getCharAndSize(CurPtr, Size);
1506 } else if (!isASCII(C)) {
1507 const char *UnicodePtr = CurPtr;
1509 ConversionResult Result =
1510 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1511 (const UTF8 *)BufferEnd,
1514 if (Result != conversionOK ||
1515 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1516 goto FinishIdentifier;
1518 if (!isLexingRawMode()) {
1519 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1520 makeCharRange(*this, CurPtr, UnicodePtr),
1524 CurPtr = UnicodePtr;
1525 C = getCharAndSize(CurPtr, Size);
1527 } else if (!isIdentifierBody(C)) {
1528 goto FinishIdentifier;
1531 // Otherwise, this character is good, consume it.
1532 CurPtr = ConsumeChar(CurPtr, Size, Result);
1534 C = getCharAndSize(CurPtr, Size);
1535 while (isIdentifierBody(C)) {
1536 CurPtr = ConsumeChar(CurPtr, Size, Result);
1537 C = getCharAndSize(CurPtr, Size);
1542 /// isHexaLiteral - Return true if Start points to a hex constant.
1543 /// in microsoft mode (where this is supposed to be several different tokens).
1544 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1546 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1549 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1550 return (C2 == 'x' || C2 == 'X');
1553 /// LexNumericConstant - Lex the remainder of a integer or floating point
1554 /// constant. From[-1] is the first character lexed. Return the end of the
1556 void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1558 char C = getCharAndSize(CurPtr, Size);
1560 while (isPreprocessingNumberBody(C)) { // FIXME: UCNs in ud-suffix.
1561 CurPtr = ConsumeChar(CurPtr, Size, Result);
1563 C = getCharAndSize(CurPtr, Size);
1566 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1567 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1568 // If we are in Microsoft mode, don't continue if the constant is hex.
1569 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1570 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1571 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1574 // If we have a hex FP constant, continue.
1575 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1576 // Outside C99, we accept hexadecimal floating point numbers as a
1577 // not-quite-conforming extension. Only do so if this looks like it's
1578 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1579 bool IsHexFloat = true;
1580 if (!LangOpts.C99) {
1581 if (!isHexaLiteral(BufferPtr, LangOpts))
1583 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1587 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1590 // Update the location of token as well as BufferPtr.
1591 const char *TokStart = BufferPtr;
1592 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1593 Result.setLiteralData(TokStart);
1596 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1597 /// in C++11, or warn on a ud-suffix in C++98.
1598 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr) {
1599 assert(getLangOpts().CPlusPlus);
1601 // Maximally munch an identifier. FIXME: UCNs.
1603 char C = getCharAndSize(CurPtr, Size);
1604 if (isIdentifierHead(C)) {
1605 if (!getLangOpts().CPlusPlus11) {
1606 if (!isLexingRawMode())
1608 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1609 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1610 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1614 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1615 // that does not start with an underscore is ill-formed. As a conforming
1616 // extension, we treat all such suffixes as if they had whitespace before
1619 if (!isLexingRawMode())
1620 Diag(CurPtr, getLangOpts().MicrosoftMode ?
1621 diag::ext_ms_reserved_user_defined_literal :
1622 diag::ext_reserved_user_defined_literal)
1623 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1627 Result.setFlag(Token::HasUDSuffix);
1629 CurPtr = ConsumeChar(CurPtr, Size, Result);
1630 C = getCharAndSize(CurPtr, Size);
1631 } while (isIdentifierBody(C));
1636 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1637 /// either " or L" or u8" or u" or U".
1638 void Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1639 tok::TokenKind Kind) {
1640 const char *NulCharacter = 0; // Does this string contain the \0 character?
1642 if (!isLexingRawMode() &&
1643 (Kind == tok::utf8_string_literal ||
1644 Kind == tok::utf16_string_literal ||
1645 Kind == tok::utf32_string_literal))
1646 Diag(BufferPtr, getLangOpts().CPlusPlus
1647 ? diag::warn_cxx98_compat_unicode_literal
1648 : diag::warn_c99_compat_unicode_literal);
1650 char C = getAndAdvanceChar(CurPtr, Result);
1652 // Skip escaped characters. Escaped newlines will already be processed by
1653 // getAndAdvanceChar.
1655 C = getAndAdvanceChar(CurPtr, Result);
1657 if (C == '\n' || C == '\r' || // Newline.
1658 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1659 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1660 Diag(BufferPtr, diag::ext_unterminated_string);
1661 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1666 if (isCodeCompletionPoint(CurPtr-1)) {
1667 PP->CodeCompleteNaturalLanguage();
1668 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1669 return cutOffLexing();
1672 NulCharacter = CurPtr-1;
1674 C = getAndAdvanceChar(CurPtr, Result);
1677 // If we are in C++11, lex the optional ud-suffix.
1678 if (getLangOpts().CPlusPlus)
1679 CurPtr = LexUDSuffix(Result, CurPtr);
1681 // If a nul character existed in the string, warn about it.
1682 if (NulCharacter && !isLexingRawMode())
1683 Diag(NulCharacter, diag::null_in_string);
1685 // Update the location of the token as well as the BufferPtr instance var.
1686 const char *TokStart = BufferPtr;
1687 FormTokenWithChars(Result, CurPtr, Kind);
1688 Result.setLiteralData(TokStart);
1691 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1692 /// having lexed R", LR", u8R", uR", or UR".
1693 void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1694 tok::TokenKind Kind) {
1695 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1696 // Between the initial and final double quote characters of the raw string,
1697 // any transformations performed in phases 1 and 2 (trigraphs,
1698 // universal-character-names, and line splicing) are reverted.
1700 if (!isLexingRawMode())
1701 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1703 unsigned PrefixLen = 0;
1705 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1708 // If the last character was not a '(', then we didn't lex a valid delimiter.
1709 if (CurPtr[PrefixLen] != '(') {
1710 if (!isLexingRawMode()) {
1711 const char *PrefixEnd = &CurPtr[PrefixLen];
1712 if (PrefixLen == 16) {
1713 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1715 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1716 << StringRef(PrefixEnd, 1);
1720 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1721 // it's possible the '"' was intended to be part of the raw string, but
1722 // there's not much we can do about that.
1728 if (C == 0 && CurPtr-1 == BufferEnd) {
1734 FormTokenWithChars(Result, CurPtr, tok::unknown);
1738 // Save prefix and move CurPtr past it
1739 const char *Prefix = CurPtr;
1740 CurPtr += PrefixLen + 1; // skip over prefix and '('
1746 // Check for prefix match and closing quote.
1747 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1748 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1751 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1752 if (!isLexingRawMode())
1753 Diag(BufferPtr, diag::err_unterminated_raw_string)
1754 << StringRef(Prefix, PrefixLen);
1755 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1760 // If we are in C++11, lex the optional ud-suffix.
1761 if (getLangOpts().CPlusPlus)
1762 CurPtr = LexUDSuffix(Result, CurPtr);
1764 // Update the location of token as well as BufferPtr.
1765 const char *TokStart = BufferPtr;
1766 FormTokenWithChars(Result, CurPtr, Kind);
1767 Result.setLiteralData(TokStart);
1770 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1771 /// after having lexed the '<' character. This is used for #include filenames.
1772 void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1773 const char *NulCharacter = 0; // Does this string contain the \0 character?
1774 const char *AfterLessPos = CurPtr;
1775 char C = getAndAdvanceChar(CurPtr, Result);
1777 // Skip escaped characters.
1779 // Skip the escaped character.
1780 getAndAdvanceChar(CurPtr, Result);
1781 } else if (C == '\n' || C == '\r' || // Newline.
1782 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1783 isCodeCompletionPoint(CurPtr-1)))) {
1784 // If the filename is unterminated, then it must just be a lone <
1785 // character. Return this as such.
1786 FormTokenWithChars(Result, AfterLessPos, tok::less);
1788 } else if (C == 0) {
1789 NulCharacter = CurPtr-1;
1791 C = getAndAdvanceChar(CurPtr, Result);
1794 // If a nul character existed in the string, warn about it.
1795 if (NulCharacter && !isLexingRawMode())
1796 Diag(NulCharacter, diag::null_in_string);
1798 // Update the location of token as well as BufferPtr.
1799 const char *TokStart = BufferPtr;
1800 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1801 Result.setLiteralData(TokStart);
1805 /// LexCharConstant - Lex the remainder of a character constant, after having
1806 /// lexed either ' or L' or u' or U'.
1807 void Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1808 tok::TokenKind Kind) {
1809 const char *NulCharacter = 0; // Does this character contain the \0 character?
1811 if (!isLexingRawMode() &&
1812 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1813 Diag(BufferPtr, getLangOpts().CPlusPlus
1814 ? diag::warn_cxx98_compat_unicode_literal
1815 : diag::warn_c99_compat_unicode_literal);
1817 char C = getAndAdvanceChar(CurPtr, Result);
1819 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1820 Diag(BufferPtr, diag::ext_empty_character);
1821 FormTokenWithChars(Result, CurPtr, tok::unknown);
1826 // Skip escaped characters.
1828 C = getAndAdvanceChar(CurPtr, Result);
1830 if (C == '\n' || C == '\r' || // Newline.
1831 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1832 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1833 Diag(BufferPtr, diag::ext_unterminated_char);
1834 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1839 if (isCodeCompletionPoint(CurPtr-1)) {
1840 PP->CodeCompleteNaturalLanguage();
1841 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1842 return cutOffLexing();
1845 NulCharacter = CurPtr-1;
1847 C = getAndAdvanceChar(CurPtr, Result);
1850 // If we are in C++11, lex the optional ud-suffix.
1851 if (getLangOpts().CPlusPlus)
1852 CurPtr = LexUDSuffix(Result, CurPtr);
1854 // If a nul character existed in the character, warn about it.
1855 if (NulCharacter && !isLexingRawMode())
1856 Diag(NulCharacter, diag::null_in_char);
1858 // Update the location of token as well as BufferPtr.
1859 const char *TokStart = BufferPtr;
1860 FormTokenWithChars(Result, CurPtr, Kind);
1861 Result.setLiteralData(TokStart);
1864 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1865 /// Update BufferPtr to point to the next non-whitespace character and return.
1867 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1869 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) {
1870 // Whitespace - Skip it, then return the token after the whitespace.
1871 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1873 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently.
1875 // Skip horizontal whitespace very aggressively.
1876 while (isHorizontalWhitespace(Char))
1879 // Otherwise if we have something other than whitespace, we're done.
1880 if (!isVerticalWhitespace(Char))
1883 if (ParsingPreprocessorDirective) {
1884 // End of preprocessor directive line, let LexTokenInternal handle this.
1889 // ok, but handle newline.
1894 // If the client wants us to return whitespace, return it now.
1895 if (isKeepWhitespaceMode()) {
1896 FormTokenWithChars(Result, CurPtr, tok::unknown);
1898 IsAtStartOfLine = true;
1899 // FIXME: The next token will not have LeadingSpace set.
1903 // If this isn't immediately after a newline, there is leading space.
1904 char PrevChar = CurPtr[-1];
1905 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
1907 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
1909 Result.setFlag(Token::StartOfLine);
1915 /// We have just read the // characters from input. Skip until we find the
1916 /// newline character thats terminate the comment. Then update BufferPtr and
1919 /// If we're in KeepCommentMode or any CommentHandler has inserted
1920 /// some tokens, this will store the first token and return true.
1921 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr) {
1922 // If Line comments aren't explicitly enabled for this language, emit an
1923 // extension warning.
1924 if (!LangOpts.LineComment && !isLexingRawMode()) {
1925 Diag(BufferPtr, diag::ext_line_comment);
1927 // Mark them enabled so we only emit one warning for this translation
1929 LangOpts.LineComment = true;
1932 // Scan over the body of the comment. The common case, when scanning, is that
1933 // the comment contains normal ascii characters with nothing interesting in
1934 // them. As such, optimize for this case with the inner loop.
1938 // Skip over characters in the fast loop.
1939 while (C != 0 && // Potentially EOF.
1940 C != '\n' && C != '\r') // Newline or DOS-style newline.
1943 const char *NextLine = CurPtr;
1945 // We found a newline, see if it's escaped.
1946 const char *EscapePtr = CurPtr-1;
1947 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace.
1950 if (*EscapePtr == '\\') // Escaped newline.
1952 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
1953 EscapePtr[-2] == '?') // Trigraph-escaped newline.
1954 CurPtr = EscapePtr-2;
1956 break; // This is a newline, we're done.
1959 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
1960 // properly decode the character. Read it in raw mode to avoid emitting
1961 // diagnostics about things like trigraphs. If we see an escaped newline,
1962 // we'll handle it below.
1963 const char *OldPtr = CurPtr;
1964 bool OldRawMode = isLexingRawMode();
1965 LexingRawMode = true;
1966 C = getAndAdvanceChar(CurPtr, Result);
1967 LexingRawMode = OldRawMode;
1969 // If we only read only one character, then no special handling is needed.
1970 // We're done and can skip forward to the newline.
1971 if (C != 0 && CurPtr == OldPtr+1) {
1976 // If we read multiple characters, and one of those characters was a \r or
1977 // \n, then we had an escaped newline within the comment. Emit diagnostic
1978 // unless the next line is also a // comment.
1979 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
1980 for (; OldPtr != CurPtr; ++OldPtr)
1981 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
1982 // Okay, we found a // comment that ends in a newline, if the next
1983 // line is also a // comment, but has spaces, don't emit a diagnostic.
1984 if (isWhitespace(C)) {
1985 const char *ForwardPtr = CurPtr;
1986 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
1988 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
1992 if (!isLexingRawMode())
1993 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
1998 if (CurPtr == BufferEnd+1) {
2003 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2004 PP->CodeCompleteNaturalLanguage();
2009 } while (C != '\n' && C != '\r');
2011 // Found but did not consume the newline. Notify comment handlers about the
2012 // comment unless we're in a #if 0 block.
2013 if (PP && !isLexingRawMode() &&
2014 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2015 getSourceLocation(CurPtr)))) {
2017 return true; // A token has to be returned.
2020 // If we are returning comments as tokens, return this comment as a token.
2021 if (inKeepCommentMode())
2022 return SaveLineComment(Result, CurPtr);
2024 // If we are inside a preprocessor directive and we see the end of line,
2025 // return immediately, so that the lexer can return this as an EOD token.
2026 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2031 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2032 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2033 // contribute to another token), it isn't needed for correctness. Note that
2034 // this is ok even in KeepWhitespaceMode, because we would have returned the
2035 /// comment above in that mode.
2038 // The next returned token is at the start of the line.
2039 Result.setFlag(Token::StartOfLine);
2040 // No leading whitespace seen so far.
2041 Result.clearFlag(Token::LeadingSpace);
2046 /// If in save-comment mode, package up this Line comment in an appropriate
2047 /// way and return it.
2048 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2049 // If we're not in a preprocessor directive, just return the // comment
2051 FormTokenWithChars(Result, CurPtr, tok::comment);
2053 if (!ParsingPreprocessorDirective || LexingRawMode)
2056 // If this Line-style comment is in a macro definition, transmogrify it into
2057 // a C-style block comment.
2058 bool Invalid = false;
2059 std::string Spelling = PP->getSpelling(Result, &Invalid);
2063 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2064 Spelling[1] = '*'; // Change prefix to "/*".
2065 Spelling += "*/"; // add suffix.
2067 Result.setKind(tok::comment);
2068 PP->CreateString(Spelling, Result,
2069 Result.getLocation(), Result.getLocation());
2073 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2074 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2075 /// a diagnostic if so. We know that the newline is inside of a block comment.
2076 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2078 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2080 // Back up off the newline.
2083 // If this is a two-character newline sequence, skip the other character.
2084 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2085 // \n\n or \r\r -> not escaped newline.
2086 if (CurPtr[0] == CurPtr[1])
2088 // \n\r or \r\n -> skip the newline.
2092 // If we have horizontal whitespace, skip over it. We allow whitespace
2093 // between the slash and newline.
2094 bool HasSpace = false;
2095 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2100 // If we have a slash, we know this is an escaped newline.
2101 if (*CurPtr == '\\') {
2102 if (CurPtr[-1] != '*') return false;
2104 // It isn't a slash, is it the ?? / trigraph?
2105 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2109 // This is the trigraph ending the comment. Emit a stern warning!
2112 // If no trigraphs are enabled, warn that we ignored this trigraph and
2113 // ignore this * character.
2114 if (!L->getLangOpts().Trigraphs) {
2115 if (!L->isLexingRawMode())
2116 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2119 if (!L->isLexingRawMode())
2120 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2123 // Warn about having an escaped newline between the */ characters.
2124 if (!L->isLexingRawMode())
2125 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2127 // If there was space between the backslash and newline, warn about it.
2128 if (HasSpace && !L->isLexingRawMode())
2129 L->Diag(CurPtr, diag::backslash_newline_space);
2135 #include <emmintrin.h>
2137 #include <altivec.h>
2141 /// We have just read from input the / and * characters that started a comment.
2142 /// Read until we find the * and / characters that terminate the comment.
2143 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2144 /// comments, because they cannot cause the comment to end. The only thing
2145 /// that can happen is the comment could end with an escaped newline between
2146 /// the terminating * and /.
2148 /// If we're in KeepCommentMode or any CommentHandler has inserted
2149 /// some tokens, this will store the first token and return true.
2150 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) {
2151 // Scan one character past where we should, looking for a '/' character. Once
2152 // we find it, check to see if it was preceded by a *. This common
2153 // optimization helps people who like to put a lot of * characters in their
2156 // The first character we get with newlines and trigraphs skipped to handle
2157 // the degenerate /*/ case below correctly if the * has an escaped newline
2160 unsigned char C = getCharAndSize(CurPtr, CharSize);
2162 if (C == 0 && CurPtr == BufferEnd+1) {
2163 if (!isLexingRawMode())
2164 Diag(BufferPtr, diag::err_unterminated_block_comment);
2167 // KeepWhitespaceMode should return this broken comment as a token. Since
2168 // it isn't a well formed comment, just return it as an 'unknown' token.
2169 if (isKeepWhitespaceMode()) {
2170 FormTokenWithChars(Result, CurPtr, tok::unknown);
2178 // Check to see if the first character after the '/*' is another /. If so,
2179 // then this slash does not end the block comment, it is part of it.
2184 // Skip over all non-interesting characters until we find end of buffer or a
2185 // (probably ending) '/' character.
2186 if (CurPtr + 24 < BufferEnd &&
2187 // If there is a code-completion point avoid the fast scan because it
2188 // doesn't check for '\0'.
2189 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2190 // While not aligned to a 16-byte boundary.
2191 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2194 if (C == '/') goto FoundSlash;
2197 __m128i Slashes = _mm_set1_epi8('/');
2198 while (CurPtr+16 <= BufferEnd) {
2199 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2202 // Adjust the pointer to point directly after the first slash. It's
2203 // not necessary to set C here, it will be overwritten at the end of
2205 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1;
2211 __vector unsigned char Slashes = {
2212 '/', '/', '/', '/', '/', '/', '/', '/',
2213 '/', '/', '/', '/', '/', '/', '/', '/'
2215 while (CurPtr+16 <= BufferEnd &&
2216 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2219 // Scan for '/' quickly. Many block comments are very large.
2220 while (CurPtr[0] != '/' &&
2224 CurPtr+4 < BufferEnd) {
2229 // It has to be one of the bytes scanned, increment to it and read one.
2233 // Loop to scan the remainder.
2234 while (C != '/' && C != '\0')
2239 if (CurPtr[-2] == '*') // We found the final */. We're done!
2242 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2243 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2244 // We found the final */, though it had an escaped newline between the
2245 // * and /. We're done!
2249 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2250 // If this is a /* inside of the comment, emit a warning. Don't do this
2251 // if this is a /*/, which will end the comment. This misses cases with
2252 // embedded escaped newlines, but oh well.
2253 if (!isLexingRawMode())
2254 Diag(CurPtr-1, diag::warn_nested_block_comment);
2256 } else if (C == 0 && CurPtr == BufferEnd+1) {
2257 if (!isLexingRawMode())
2258 Diag(BufferPtr, diag::err_unterminated_block_comment);
2259 // Note: the user probably forgot a */. We could continue immediately
2260 // after the /*, but this would involve lexing a lot of what really is the
2261 // comment, which surely would confuse the parser.
2264 // KeepWhitespaceMode should return this broken comment as a token. Since
2265 // it isn't a well formed comment, just return it as an 'unknown' token.
2266 if (isKeepWhitespaceMode()) {
2267 FormTokenWithChars(Result, CurPtr, tok::unknown);
2273 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2274 PP->CodeCompleteNaturalLanguage();
2282 // Notify comment handlers about the comment unless we're in a #if 0 block.
2283 if (PP && !isLexingRawMode() &&
2284 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2285 getSourceLocation(CurPtr)))) {
2287 return true; // A token has to be returned.
2290 // If we are returning comments as tokens, return this comment as a token.
2291 if (inKeepCommentMode()) {
2292 FormTokenWithChars(Result, CurPtr, tok::comment);
2296 // It is common for the tokens immediately after a /**/ comment to be
2297 // whitespace. Instead of going through the big switch, handle it
2298 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2299 // have already returned above with the comment as a token.
2300 if (isHorizontalWhitespace(*CurPtr)) {
2301 SkipWhitespace(Result, CurPtr+1);
2305 // Otherwise, just return so that the next character will be lexed as a token.
2307 Result.setFlag(Token::LeadingSpace);
2311 //===----------------------------------------------------------------------===//
2312 // Primary Lexing Entry Points
2313 //===----------------------------------------------------------------------===//
2315 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2316 /// uninterpreted string. This switches the lexer out of directive mode.
2317 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2318 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2319 "Must be in a preprocessing directive!");
2322 // CurPtr - Cache BufferPtr in an automatic variable.
2323 const char *CurPtr = BufferPtr;
2325 char Char = getAndAdvanceChar(CurPtr, Tmp);
2329 Result->push_back(Char);
2332 // Found end of file?
2333 if (CurPtr-1 != BufferEnd) {
2334 if (isCodeCompletionPoint(CurPtr-1)) {
2335 PP->CodeCompleteNaturalLanguage();
2340 // Nope, normal character, continue.
2342 Result->push_back(Char);
2348 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2349 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2350 BufferPtr = CurPtr-1;
2352 // Next, lex the character, which should handle the EOD transition.
2354 if (Tmp.is(tok::code_completion)) {
2356 PP->CodeCompleteNaturalLanguage();
2359 assert(Tmp.is(tok::eod) && "Unexpected token!");
2361 // Finally, we're done;
2367 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2368 /// condition, reporting diagnostics and handling other edge cases as required.
2369 /// This returns true if Result contains a token, false if PP.Lex should be
2371 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2372 // If we hit the end of the file while parsing a preprocessor directive,
2373 // end the preprocessor directive first. The next token returned will
2374 // then be the end of file.
2375 if (ParsingPreprocessorDirective) {
2376 // Done parsing the "line".
2377 ParsingPreprocessorDirective = false;
2378 // Update the location of token as well as BufferPtr.
2379 FormTokenWithChars(Result, CurPtr, tok::eod);
2381 // Restore comment saving mode, in case it was disabled for directive.
2382 resetExtendedTokenMode();
2383 return true; // Have a token.
2386 // If we are in raw mode, return this event as an EOF token. Let the caller
2387 // that put us in raw mode handle the event.
2388 if (isLexingRawMode()) {
2389 Result.startToken();
2390 BufferPtr = BufferEnd;
2391 FormTokenWithChars(Result, BufferEnd, tok::eof);
2395 // Issue diagnostics for unterminated #if and missing newline.
2397 // If we are in a #if directive, emit an error.
2398 while (!ConditionalStack.empty()) {
2399 if (PP->getCodeCompletionFileLoc() != FileLoc)
2400 PP->Diag(ConditionalStack.back().IfLoc,
2401 diag::err_pp_unterminated_conditional);
2402 ConditionalStack.pop_back();
2405 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2407 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r'))
2408 Diag(BufferEnd, LangOpts.CPlusPlus11 ? // C++11 [lex.phases] 2.2 p2
2409 diag::warn_cxx98_compat_no_newline_eof : diag::ext_no_newline_eof)
2410 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n");
2414 // Finally, let the preprocessor handle this.
2415 return PP->HandleEndOfFile(Result, isPragmaLexer());
2418 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2419 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2420 /// else and 2 if there are no more tokens in the buffer controlled by the
2422 unsigned Lexer::isNextPPTokenLParen() {
2423 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2425 // Switch to 'skipping' mode. This will ensure that we can lex a token
2426 // without emitting diagnostics, disables macro expansion, and will cause EOF
2427 // to return an EOF token instead of popping the include stack.
2428 LexingRawMode = true;
2430 // Save state that can be changed while lexing so that we can restore it.
2431 const char *TmpBufferPtr = BufferPtr;
2432 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2436 LexTokenInternal(Tok);
2438 // Restore state that may have changed.
2439 BufferPtr = TmpBufferPtr;
2440 ParsingPreprocessorDirective = inPPDirectiveMode;
2442 // Restore the lexer back to non-skipping mode.
2443 LexingRawMode = false;
2445 if (Tok.is(tok::eof))
2447 return Tok.is(tok::l_paren);
2450 /// \brief Find the end of a version control conflict marker.
2451 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2452 ConflictMarkerKind CMK) {
2453 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2454 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2455 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2456 size_t Pos = RestOfBuffer.find(Terminator);
2457 while (Pos != StringRef::npos) {
2458 // Must occur at start of line.
2459 if (RestOfBuffer[Pos-1] != '\r' &&
2460 RestOfBuffer[Pos-1] != '\n') {
2461 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2462 Pos = RestOfBuffer.find(Terminator);
2465 return RestOfBuffer.data()+Pos;
2470 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2471 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2472 /// and recover nicely. This returns true if it is a conflict marker and false
2474 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2475 // Only a conflict marker if it starts at the beginning of a line.
2476 if (CurPtr != BufferStart &&
2477 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2480 // Check to see if we have <<<<<<< or >>>>.
2481 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2482 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
2485 // If we have a situation where we don't care about conflict markers, ignore
2487 if (CurrentConflictMarkerState || isLexingRawMode())
2490 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2492 // Check to see if there is an ending marker somewhere in the buffer at the
2493 // start of a line to terminate this conflict marker.
2494 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2495 // We found a match. We are really in a conflict marker.
2496 // Diagnose this, and ignore to the end of line.
2497 Diag(CurPtr, diag::err_conflict_marker);
2498 CurrentConflictMarkerState = Kind;
2500 // Skip ahead to the end of line. We know this exists because the
2501 // end-of-conflict marker starts with \r or \n.
2502 while (*CurPtr != '\r' && *CurPtr != '\n') {
2503 assert(CurPtr != BufferEnd && "Didn't find end of line");
2510 // No end of conflict marker found.
2515 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2516 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2517 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2518 /// the line. This returns true if it is a conflict marker and false if not.
2519 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2520 // Only a conflict marker if it starts at the beginning of a line.
2521 if (CurPtr != BufferStart &&
2522 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2525 // If we have a situation where we don't care about conflict markers, ignore
2527 if (!CurrentConflictMarkerState || isLexingRawMode())
2530 // Check to see if we have the marker (4 characters in a row).
2531 for (unsigned i = 1; i != 4; ++i)
2532 if (CurPtr[i] != CurPtr[0])
2535 // If we do have it, search for the end of the conflict marker. This could
2536 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2537 // be the end of conflict marker.
2538 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2539 CurrentConflictMarkerState)) {
2542 // Skip ahead to the end of line.
2543 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2548 // No longer in the conflict marker.
2549 CurrentConflictMarkerState = CMK_None;
2556 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2557 if (PP && PP->isCodeCompletionEnabled()) {
2558 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2559 return Loc == PP->getCodeCompletionLoc();
2565 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2568 char Kind = getCharAndSize(StartPtr, CharSize);
2570 unsigned NumHexDigits;
2573 else if (Kind == 'U')
2578 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2579 if (Result && !isLexingRawMode())
2580 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2584 const char *CurPtr = StartPtr + CharSize;
2585 const char *KindLoc = &CurPtr[-1];
2587 uint32_t CodePoint = 0;
2588 for (unsigned i = 0; i < NumHexDigits; ++i) {
2589 char C = getCharAndSize(CurPtr, CharSize);
2591 unsigned Value = llvm::hexDigitValue(C);
2593 if (Result && !isLexingRawMode()) {
2595 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2596 << StringRef(KindLoc, 1);
2598 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2600 // If the user wrote \U1234, suggest a fixit to \u.
2601 if (i == 4 && NumHexDigits == 8) {
2602 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2603 Diag(KindLoc, diag::note_ucn_four_not_eight)
2604 << FixItHint::CreateReplacement(URange, "u");
2619 Result->setFlag(Token::HasUCN);
2620 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2623 while (StartPtr != CurPtr)
2624 (void)getAndAdvanceChar(StartPtr, *Result);
2629 // C99 6.4.3p2: A universal character name shall not specify a character whose
2630 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2631 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2632 // C++11 [lex.charset]p2: If the hexadecimal value for a
2633 // universal-character-name corresponds to a surrogate code point (in the
2634 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2635 // if the hexadecimal value for a universal-character-name outside the
2636 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2637 // string literal corresponds to a control character (in either of the
2638 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2639 // basic source character set, the program is ill-formed.
2640 if (CodePoint < 0xA0) {
2641 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2644 // We don't use isLexingRawMode() here because we need to warn about bad
2645 // UCNs even when skipping preprocessing tokens in a #if block.
2647 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2648 Diag(BufferPtr, diag::err_ucn_control_character);
2650 char C = static_cast<char>(CodePoint);
2651 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2657 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2658 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2659 // We don't use isLexingRawMode() here because we need to diagnose bad
2660 // UCNs even when skipping preprocessing tokens in a #if block.
2662 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2663 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2665 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2673 void Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2674 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2675 isCharInSet(C, UnicodeWhitespaceChars)) {
2676 Diag(BufferPtr, diag::ext_unicode_whitespace)
2677 << makeCharRange(*this, BufferPtr, CurPtr);
2679 Result.setFlag(Token::LeadingSpace);
2680 if (SkipWhitespace(Result, CurPtr))
2681 return; // KeepWhitespaceMode
2683 return LexTokenInternal(Result);
2686 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2687 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2688 !PP->isPreprocessedOutput()) {
2689 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2690 makeCharRange(*this, BufferPtr, CurPtr),
2695 return LexIdentifier(Result, CurPtr);
2698 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2699 !PP->isPreprocessedOutput() &&
2700 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2701 // Non-ASCII characters tend to creep into source code unintentionally.
2702 // Instead of letting the parser complain about the unknown token,
2703 // just drop the character.
2704 // Note that we can /only/ do this when the non-ASCII character is actually
2705 // spelled as Unicode, not written as a UCN. The standard requires that
2706 // we not throw away any possible preprocessor tokens, but there's a
2707 // loophole in the mapping of Unicode characters to basic character set
2708 // characters that allows us to map these particular characters to, say,
2710 Diag(BufferPtr, diag::err_non_ascii)
2711 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2714 return LexTokenInternal(Result);
2717 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2720 FormTokenWithChars(Result, CurPtr, tok::unknown);
2724 /// LexTokenInternal - This implements a simple C family lexer. It is an
2725 /// extremely performance critical piece of code. This assumes that the buffer
2726 /// has a null character at the end of the file. This returns a preprocessing
2727 /// token, not a normal token, as such, it is an internal interface. It assumes
2728 /// that the Flags of result have been cleared before calling this.
2729 void Lexer::LexTokenInternal(Token &Result) {
2731 // New token, can't need cleaning yet.
2732 Result.clearFlag(Token::NeedsCleaning);
2733 Result.setIdentifierInfo(0);
2735 // CurPtr - Cache BufferPtr in an automatic variable.
2736 const char *CurPtr = BufferPtr;
2738 // Small amounts of horizontal whitespace is very common between tokens.
2739 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2741 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2744 // If we are keeping whitespace and other tokens, just return what we just
2745 // skipped. The next lexer invocation will return the token after the
2747 if (isKeepWhitespaceMode()) {
2748 FormTokenWithChars(Result, CurPtr, tok::unknown);
2749 // FIXME: The next token will not have LeadingSpace set.
2754 Result.setFlag(Token::LeadingSpace);
2757 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
2759 // Read a character, advancing over it.
2760 char Char = getAndAdvanceChar(CurPtr, Result);
2761 tok::TokenKind Kind;
2765 // Found end of file?
2766 if (CurPtr-1 == BufferEnd) {
2767 // Read the PP instance variable into an automatic variable, because
2768 // LexEndOfFile will often delete 'this'.
2769 Preprocessor *PPCache = PP;
2770 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2771 return; // Got a token to return.
2772 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2773 return PPCache->Lex(Result);
2776 // Check if we are performing code completion.
2777 if (isCodeCompletionPoint(CurPtr-1)) {
2778 // Return the code-completion token.
2779 Result.startToken();
2780 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2784 if (!isLexingRawMode())
2785 Diag(CurPtr-1, diag::null_in_file);
2786 Result.setFlag(Token::LeadingSpace);
2787 if (SkipWhitespace(Result, CurPtr))
2788 return; // KeepWhitespaceMode
2790 goto LexNextToken; // GCC isn't tail call eliminating.
2792 case 26: // DOS & CP/M EOF: "^Z".
2793 // If we're in Microsoft extensions mode, treat this as end of file.
2794 if (LangOpts.MicrosoftExt) {
2795 // Read the PP instance variable into an automatic variable, because
2796 // LexEndOfFile will often delete 'this'.
2797 Preprocessor *PPCache = PP;
2798 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file.
2799 return; // Got a token to return.
2800 assert(PPCache && "Raw buffer::LexEndOfFile should return a token");
2801 return PPCache->Lex(Result);
2803 // If Microsoft extensions are disabled, this is just random garbage.
2804 Kind = tok::unknown;
2809 // If we are inside a preprocessor directive and we see the end of line,
2810 // we know we are done with the directive, so return an EOD token.
2811 if (ParsingPreprocessorDirective) {
2812 // Done parsing the "line".
2813 ParsingPreprocessorDirective = false;
2815 // Restore comment saving mode, in case it was disabled for directive.
2817 resetExtendedTokenMode();
2819 // Since we consumed a newline, we are back at the start of a line.
2820 IsAtStartOfLine = true;
2826 // No leading whitespace seen so far.
2827 Result.clearFlag(Token::LeadingSpace);
2829 if (SkipWhitespace(Result, CurPtr))
2830 return; // KeepWhitespaceMode
2831 goto LexNextToken; // GCC isn't tail call eliminating.
2836 SkipHorizontalWhitespace:
2837 Result.setFlag(Token::LeadingSpace);
2838 if (SkipWhitespace(Result, CurPtr))
2839 return; // KeepWhitespaceMode
2844 // If the next token is obviously a // or /* */ comment, skip it efficiently
2845 // too (without going through the big switch stmt).
2846 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
2847 LangOpts.LineComment && !LangOpts.TraditionalCPP) {
2848 if (SkipLineComment(Result, CurPtr+2))
2849 return; // There is a token to return.
2850 goto SkipIgnoredUnits;
2851 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
2852 if (SkipBlockComment(Result, CurPtr+2))
2853 return; // There is a token to return.
2854 goto SkipIgnoredUnits;
2855 } else if (isHorizontalWhitespace(*CurPtr)) {
2856 goto SkipHorizontalWhitespace;
2858 goto LexNextToken; // GCC isn't tail call eliminating.
2860 // C99 6.4.4.1: Integer Constants.
2861 // C99 6.4.4.2: Floating Constants.
2862 case '0': case '1': case '2': case '3': case '4':
2863 case '5': case '6': case '7': case '8': case '9':
2864 // Notify MIOpt that we read a non-whitespace/non-comment token.
2866 return LexNumericConstant(Result, CurPtr);
2868 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
2869 // Notify MIOpt that we read a non-whitespace/non-comment token.
2872 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
2873 Char = getCharAndSize(CurPtr, SizeTmp);
2875 // UTF-16 string literal
2877 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2878 tok::utf16_string_literal);
2880 // UTF-16 character constant
2882 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2883 tok::utf16_char_constant);
2885 // UTF-16 raw string literal
2886 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2887 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2888 return LexRawStringLiteral(Result,
2889 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2891 tok::utf16_string_literal);
2894 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
2896 // UTF-8 string literal
2898 return LexStringLiteral(Result,
2899 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2901 tok::utf8_string_literal);
2903 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
2905 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
2906 // UTF-8 raw string literal
2908 return LexRawStringLiteral(Result,
2909 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2912 tok::utf8_string_literal);
2918 // treat u like the start of an identifier.
2919 return LexIdentifier(Result, CurPtr);
2921 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
2922 // Notify MIOpt that we read a non-whitespace/non-comment token.
2925 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
2926 Char = getCharAndSize(CurPtr, SizeTmp);
2928 // UTF-32 string literal
2930 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2931 tok::utf32_string_literal);
2933 // UTF-32 character constant
2935 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2936 tok::utf32_char_constant);
2938 // UTF-32 raw string literal
2939 if (Char == 'R' && LangOpts.CPlusPlus11 &&
2940 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2941 return LexRawStringLiteral(Result,
2942 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2944 tok::utf32_string_literal);
2947 // treat U like the start of an identifier.
2948 return LexIdentifier(Result, CurPtr);
2950 case 'R': // Identifier or C++0x raw string literal
2951 // Notify MIOpt that we read a non-whitespace/non-comment token.
2954 if (LangOpts.CPlusPlus11) {
2955 Char = getCharAndSize(CurPtr, SizeTmp);
2958 return LexRawStringLiteral(Result,
2959 ConsumeChar(CurPtr, SizeTmp, Result),
2960 tok::string_literal);
2963 // treat R like the start of an identifier.
2964 return LexIdentifier(Result, CurPtr);
2966 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
2967 // Notify MIOpt that we read a non-whitespace/non-comment token.
2969 Char = getCharAndSize(CurPtr, SizeTmp);
2971 // Wide string literal.
2973 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2974 tok::wide_string_literal);
2976 // Wide raw string literal.
2977 if (LangOpts.CPlusPlus11 && Char == 'R' &&
2978 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
2979 return LexRawStringLiteral(Result,
2980 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
2982 tok::wide_string_literal);
2984 // Wide character constant.
2986 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
2987 tok::wide_char_constant);
2988 // FALL THROUGH, treating L like the start of an identifier.
2990 // C99 6.4.2: Identifiers.
2991 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
2992 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
2993 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
2994 case 'V': case 'W': case 'X': case 'Y': case 'Z':
2995 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
2996 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
2997 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
2998 case 'v': case 'w': case 'x': case 'y': case 'z':
3000 // Notify MIOpt that we read a non-whitespace/non-comment token.
3002 return LexIdentifier(Result, CurPtr);
3004 case '$': // $ in identifiers.
3005 if (LangOpts.DollarIdents) {
3006 if (!isLexingRawMode())
3007 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3008 // Notify MIOpt that we read a non-whitespace/non-comment token.
3010 return LexIdentifier(Result, CurPtr);
3013 Kind = tok::unknown;
3016 // C99 6.4.4: Character Constants.
3018 // Notify MIOpt that we read a non-whitespace/non-comment token.
3020 return LexCharConstant(Result, CurPtr, tok::char_constant);
3022 // C99 6.4.5: String Literals.
3024 // Notify MIOpt that we read a non-whitespace/non-comment token.
3026 return LexStringLiteral(Result, CurPtr, tok::string_literal);
3028 // C99 6.4.6: Punctuators.
3030 Kind = tok::question;
3033 Kind = tok::l_square;
3036 Kind = tok::r_square;
3039 Kind = tok::l_paren;
3042 Kind = tok::r_paren;
3045 Kind = tok::l_brace;
3048 Kind = tok::r_brace;
3051 Char = getCharAndSize(CurPtr, SizeTmp);
3052 if (Char >= '0' && Char <= '9') {
3053 // Notify MIOpt that we read a non-whitespace/non-comment token.
3056 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3057 } else if (LangOpts.CPlusPlus && Char == '*') {
3058 Kind = tok::periodstar;
3060 } else if (Char == '.' &&
3061 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3062 Kind = tok::ellipsis;
3063 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3070 Char = getCharAndSize(CurPtr, SizeTmp);
3073 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3074 } else if (Char == '=') {
3075 Kind = tok::ampequal;
3076 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3082 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3083 Kind = tok::starequal;
3084 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3090 Char = getCharAndSize(CurPtr, SizeTmp);
3092 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3093 Kind = tok::plusplus;
3094 } else if (Char == '=') {
3095 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3096 Kind = tok::plusequal;
3102 Char = getCharAndSize(CurPtr, SizeTmp);
3103 if (Char == '-') { // --
3104 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3105 Kind = tok::minusminus;
3106 } else if (Char == '>' && LangOpts.CPlusPlus &&
3107 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3108 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3110 Kind = tok::arrowstar;
3111 } else if (Char == '>') { // ->
3112 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3114 } else if (Char == '=') { // -=
3115 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3116 Kind = tok::minusequal;
3125 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3126 Kind = tok::exclaimequal;
3127 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3129 Kind = tok::exclaim;
3134 Char = getCharAndSize(CurPtr, SizeTmp);
3135 if (Char == '/') { // Line comment.
3136 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3137 // want to lex this as a comment. There is one problem with this though,
3138 // that in one particular corner case, this can change the behavior of the
3139 // resultant program. For example, In "foo //**/ bar", C89 would lex
3140 // this as "foo / bar" and langauges with Line comments would lex it as
3141 // "foo". Check to see if the character after the second slash is a '*'.
3142 // If so, we will lex that as a "/" instead of the start of a comment.
3143 // However, we never do this if we are just preprocessing.
3144 bool TreatAsComment = LangOpts.LineComment && !LangOpts.TraditionalCPP;
3145 if (!TreatAsComment)
3146 if (!(PP && PP->isPreprocessedOutput()))
3147 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3149 if (TreatAsComment) {
3150 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
3151 return; // There is a token to return.
3153 // It is common for the tokens immediately after a // comment to be
3154 // whitespace (indentation for the next line). Instead of going through
3155 // the big switch, handle it efficiently now.
3156 goto SkipIgnoredUnits;
3160 if (Char == '*') { // /**/ comment.
3161 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result)))
3162 return; // There is a token to return.
3163 goto LexNextToken; // GCC isn't tail call eliminating.
3167 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3168 Kind = tok::slashequal;
3174 Char = getCharAndSize(CurPtr, SizeTmp);
3176 Kind = tok::percentequal;
3177 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3178 } else if (LangOpts.Digraphs && Char == '>') {
3179 Kind = tok::r_brace; // '%>' -> '}'
3180 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3181 } else if (LangOpts.Digraphs && Char == ':') {
3182 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3183 Char = getCharAndSize(CurPtr, SizeTmp);
3184 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3185 Kind = tok::hashhash; // '%:%:' -> '##'
3186 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3188 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3189 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3190 if (!isLexingRawMode())
3191 Diag(BufferPtr, diag::ext_charize_microsoft);
3193 } else { // '%:' -> '#'
3194 // We parsed a # character. If this occurs at the start of the line,
3195 // it's actually the start of a preprocessing directive. Callback to
3196 // the preprocessor to handle it.
3197 // FIXME: -fpreprocessed mode??
3198 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3199 goto HandleDirective;
3204 Kind = tok::percent;
3208 Char = getCharAndSize(CurPtr, SizeTmp);
3209 if (ParsingFilename) {
3210 return LexAngledStringLiteral(Result, CurPtr);
3211 } else if (Char == '<') {
3212 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3214 Kind = tok::lesslessequal;
3215 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3217 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3218 // If this is actually a '<<<<<<<' version control conflict marker,
3219 // recognize it as such and recover nicely.
3221 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3222 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3225 } else if (LangOpts.CUDA && After == '<') {
3226 Kind = tok::lesslessless;
3227 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3230 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3231 Kind = tok::lessless;
3233 } else if (Char == '=') {
3234 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3235 Kind = tok::lessequal;
3236 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3237 if (LangOpts.CPlusPlus11 &&
3238 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3239 // C++0x [lex.pptoken]p3:
3240 // Otherwise, if the next three characters are <:: and the subsequent
3241 // character is neither : nor >, the < is treated as a preprocessor
3242 // token by itself and not as the first character of the alternative
3245 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3246 if (After != ':' && After != '>') {
3248 if (!isLexingRawMode())
3249 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3254 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3255 Kind = tok::l_square;
3256 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3257 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3258 Kind = tok::l_brace;
3264 Char = getCharAndSize(CurPtr, SizeTmp);
3266 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3267 Kind = tok::greaterequal;
3268 } else if (Char == '>') {
3269 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3271 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3273 Kind = tok::greatergreaterequal;
3274 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3275 // If this is actually a '>>>>' conflict marker, recognize it as such
3276 // and recover nicely.
3278 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3279 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3281 } else if (LangOpts.CUDA && After == '>') {
3282 Kind = tok::greatergreatergreater;
3283 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3286 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3287 Kind = tok::greatergreater;
3291 Kind = tok::greater;
3295 Char = getCharAndSize(CurPtr, SizeTmp);
3297 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3298 Kind = tok::caretequal;
3304 Char = getCharAndSize(CurPtr, SizeTmp);
3306 Kind = tok::pipeequal;
3307 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3308 } else if (Char == '|') {
3309 // If this is '|||||||' and we're in a conflict marker, ignore it.
3310 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3312 Kind = tok::pipepipe;
3313 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3319 Char = getCharAndSize(CurPtr, SizeTmp);
3320 if (LangOpts.Digraphs && Char == '>') {
3321 Kind = tok::r_square; // ':>' -> ']'
3322 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3323 } else if (LangOpts.CPlusPlus && Char == ':') {
3324 Kind = tok::coloncolon;
3325 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3334 Char = getCharAndSize(CurPtr, SizeTmp);
3336 // If this is '====' and we're in a conflict marker, ignore it.
3337 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3340 Kind = tok::equalequal;
3341 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3350 Char = getCharAndSize(CurPtr, SizeTmp);
3352 Kind = tok::hashhash;
3353 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3354 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3356 if (!isLexingRawMode())
3357 Diag(BufferPtr, diag::ext_charize_microsoft);
3358 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3360 // We parsed a # character. If this occurs at the start of the line,
3361 // it's actually the start of a preprocessing directive. Callback to
3362 // the preprocessor to handle it.
3363 // FIXME: -fpreprocessed mode??
3364 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer)
3365 goto HandleDirective;
3372 // Objective C support.
3373 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3376 Kind = tok::unknown;
3379 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3381 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result))
3382 return LexUnicode(Result, CodePoint, CurPtr);
3384 Kind = tok::unknown;
3388 if (isASCII(Char)) {
3389 Kind = tok::unknown;
3395 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3396 // an escaped newline.
3398 ConversionResult Status =
3399 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3400 (const UTF8 *)BufferEnd,
3403 if (Status == conversionOK)
3404 return LexUnicode(Result, CodePoint, CurPtr);
3406 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3407 PP->isPreprocessedOutput()) {
3409 Kind = tok::unknown;
3413 // Non-ASCII characters tend to creep into source code unintentionally.
3414 // Instead of letting the parser complain about the unknown token,
3415 // just diagnose the invalid UTF-8, then drop the character.
3416 Diag(CurPtr, diag::err_invalid_utf8);
3418 BufferPtr = CurPtr+1;
3423 // Notify MIOpt that we read a non-whitespace/non-comment token.
3426 // Update the location of token as well as BufferPtr.
3427 FormTokenWithChars(Result, CurPtr, Kind);
3431 // We parsed a # character and it's the start of a preprocessing directive.
3433 FormTokenWithChars(Result, CurPtr, tok::hash);
3434 PP->HandleDirective(Result);
3436 // As an optimization, if the preprocessor didn't switch lexers, tail
3438 if (PP->isCurrentLexer(this)) {
3439 // Start a new token. If this is a #include or something, the PP may
3440 // want us starting at the beginning of the line again. If so, set
3441 // the StartOfLine flag and clear LeadingSpace.
3442 if (IsAtStartOfLine) {
3443 Result.setFlag(Token::StartOfLine);
3444 Result.clearFlag(Token::LeadingSpace);
3445 IsAtStartOfLine = false;
3447 goto LexNextToken; // GCC isn't tail call eliminating.
3449 return PP->Lex(Result);