1 //===--- Lexer.cpp - C Language Family Lexer ------------------------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the Lexer and Token interfaces.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Lex/Lexer.h"
15 #include "UnicodeCharSets.h"
16 #include "clang/Basic/CharInfo.h"
17 #include "clang/Basic/IdentifierTable.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "llvm/ADT/StringExtras.h"
23 #include "llvm/ADT/StringSwitch.h"
24 #include "llvm/Support/Compiler.h"
25 #include "llvm/Support/ConvertUTF.h"
26 #include "llvm/Support/MathExtras.h"
27 #include "llvm/Support/MemoryBuffer.h"
28 #include "llvm/Support/UnicodeCharRanges.h"
38 using namespace clang;
40 //===----------------------------------------------------------------------===//
41 // Token Class Implementation
42 //===----------------------------------------------------------------------===//
44 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
45 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
46 if (IdentifierInfo *II = getIdentifierInfo())
47 return II->getObjCKeywordID() == objcKey;
51 /// getObjCKeywordID - Return the ObjC keyword kind.
52 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
53 IdentifierInfo *specId = getIdentifierInfo();
54 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
57 //===----------------------------------------------------------------------===//
58 // Lexer Class Implementation
59 //===----------------------------------------------------------------------===//
61 void Lexer::anchor() { }
63 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
65 BufferStart = BufStart;
69 assert(BufEnd[0] == 0 &&
70 "We assume that the input buffer has a null character at the end"
71 " to simplify lexing!");
73 // Check whether we have a BOM in the beginning of the buffer. If yes - act
74 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
75 // skip the UTF-8 BOM if it's present.
76 if (BufferStart == BufferPtr) {
77 // Determine the size of the BOM.
78 StringRef Buf(BufferStart, BufferEnd - BufferStart);
79 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
80 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
84 BufferPtr += BOMLength;
87 Is_PragmaLexer = false;
88 CurrentConflictMarkerState = CMK_None;
90 // Start of the file is a start of line.
91 IsAtStartOfLine = true;
92 IsAtPhysicalStartOfLine = true;
94 HasLeadingSpace = false;
95 HasLeadingEmptyMacro = false;
97 // We are not after parsing a #.
98 ParsingPreprocessorDirective = false;
100 // We are not after parsing #include.
101 ParsingFilename = false;
103 // We are not in raw mode. Raw mode disables diagnostics and interpretation
104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
106 // or otherwise skipping over tokens.
107 LexingRawMode = false;
109 // Default to not keeping comments.
110 ExtendedTokenMode = 0;
113 /// Lexer constructor - Create a new lexer object for the specified buffer
114 /// with the specified preprocessor managing the lexing process. This lexer
115 /// assumes that the associated file buffer and Preprocessor objects will
116 /// outlive it, so it doesn't take ownership of either of them.
117 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
118 : PreprocessorLexer(&PP, FID),
119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
120 LangOpts(PP.getLangOpts()) {
122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
123 InputFile->getBufferEnd());
125 resetExtendedTokenMode();
128 void Lexer::resetExtendedTokenMode() {
129 assert(PP && "Cannot reset token mode without a preprocessor");
130 if (LangOpts.TraditionalCPP)
131 SetKeepWhitespaceMode(true);
133 SetCommentRetentionState(PP->getCommentRetentionState());
136 /// Lexer constructor - Create a new raw lexer object. This object is only
137 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
138 /// range will outlive it, so it doesn't take ownership of it.
139 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
140 const char *BufStart, const char *BufPtr, const char *BufEnd)
141 : FileLoc(fileloc), LangOpts(langOpts) {
143 InitLexer(BufStart, BufPtr, BufEnd);
145 // We *are* in raw mode.
146 LexingRawMode = true;
149 /// Lexer constructor - Create a new raw lexer object. This object is only
150 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
151 /// range will outlive it, so it doesn't take ownership of it.
152 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
153 const SourceManager &SM, const LangOptions &langOpts)
154 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
155 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
157 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
158 /// _Pragma expansion. This has a variety of magic semantics that this method
159 /// sets up. It returns a new'd Lexer that must be delete'd when done.
161 /// On entrance to this routine, TokStartLoc is a macro location which has a
162 /// spelling loc that indicates the bytes to be lexed for the token and an
163 /// expansion location that indicates where all lexed tokens should be
166 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
167 /// normal lexer that remaps tokens as they fly by. This would require making
168 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
169 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
170 /// out of the critical path of the lexer!
172 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
173 SourceLocation ExpansionLocStart,
174 SourceLocation ExpansionLocEnd,
175 unsigned TokLen, Preprocessor &PP) {
176 SourceManager &SM = PP.getSourceManager();
178 // Create the lexer as if we were going to lex the file normally.
179 FileID SpellingFID = SM.getFileID(SpellingLoc);
180 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
181 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
183 // Now that the lexer is created, change the start/end locations so that we
184 // just lex the subsection of the file that we want. This is lexing from a
186 const char *StrData = SM.getCharacterData(SpellingLoc);
188 L->BufferPtr = StrData;
189 L->BufferEnd = StrData+TokLen;
190 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
192 // Set the SourceLocation with the remapping information. This ensures that
193 // GetMappedTokenLoc will remap the tokens as they are lexed.
194 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
196 ExpansionLocEnd, TokLen);
198 // Ensure that the lexer thinks it is inside a directive, so that end \n will
199 // return an EOD token.
200 L->ParsingPreprocessorDirective = true;
202 // This lexer really is for _Pragma.
203 L->Is_PragmaLexer = true;
207 /// Stringify - Convert the specified string into a C string, with surrounding
208 /// ""'s, and with escaped \ and " characters.
209 std::string Lexer::Stringify(StringRef Str, bool Charify) {
210 std::string Result = Str;
211 char Quote = Charify ? '\'' : '"';
212 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
213 if (Result[i] == '\\' || Result[i] == Quote) {
214 Result.insert(Result.begin()+i, '\\');
221 /// Stringify - Convert the specified string into a C string by escaping '\'
222 /// and " characters. This does not add surrounding ""'s to the string.
223 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
224 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
225 if (Str[i] == '\\' || Str[i] == '"') {
226 Str.insert(Str.begin()+i, '\\');
232 //===----------------------------------------------------------------------===//
234 //===----------------------------------------------------------------------===//
236 /// \brief Slow case of getSpelling. Extract the characters comprising the
237 /// spelling of this token from the provided input buffer.
238 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
239 const LangOptions &LangOpts, char *Spelling) {
240 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
243 const char *BufEnd = BufPtr + Tok.getLength();
245 if (tok::isStringLiteral(Tok.getKind())) {
246 // Munch the encoding-prefix and opening double-quote.
247 while (BufPtr < BufEnd) {
249 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
252 if (Spelling[Length - 1] == '"')
256 // Raw string literals need special handling; trigraph expansion and line
257 // splicing do not occur within their d-char-sequence nor within their
260 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
261 // Search backwards from the end of the token to find the matching closing
263 const char *RawEnd = BufEnd;
264 do --RawEnd; while (*RawEnd != '"');
265 size_t RawLength = RawEnd - BufPtr + 1;
267 // Everything between the quotes is included verbatim in the spelling.
268 memcpy(Spelling + Length, BufPtr, RawLength);
272 // The rest of the token is lexed normally.
276 while (BufPtr < BufEnd) {
278 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
282 assert(Length < Tok.getLength() &&
283 "NeedsCleaning flag set on token that didn't need cleaning!");
287 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
288 /// token are the characters used to represent the token in the source file
289 /// after trigraph expansion and escaped-newline folding. In particular, this
290 /// wants to get the true, uncanonicalized, spelling of things like digraphs
292 StringRef Lexer::getSpelling(SourceLocation loc,
293 SmallVectorImpl<char> &buffer,
294 const SourceManager &SM,
295 const LangOptions &options,
297 // Break down the source location.
298 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
300 // Try to the load the file buffer.
301 bool invalidTemp = false;
302 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
304 if (invalid) *invalid = true;
308 const char *tokenBegin = file.data() + locInfo.second;
310 // Lex from the start of the given location.
311 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
312 file.begin(), tokenBegin, file.end());
314 lexer.LexFromRawLexer(token);
316 unsigned length = token.getLength();
318 // Common case: no need for cleaning.
319 if (!token.needsCleaning())
320 return StringRef(tokenBegin, length);
322 // Hard case, we need to relex the characters into the string.
323 buffer.resize(length);
324 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
325 return StringRef(buffer.data(), buffer.size());
328 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
329 /// token are the characters used to represent the token in the source file
330 /// after trigraph expansion and escaped-newline folding. In particular, this
331 /// wants to get the true, uncanonicalized, spelling of things like digraphs
333 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
334 const LangOptions &LangOpts, bool *Invalid) {
335 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
337 bool CharDataInvalid = false;
338 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
341 *Invalid = CharDataInvalid;
343 return std::string();
345 // If this token contains nothing interesting, return it directly.
346 if (!Tok.needsCleaning())
347 return std::string(TokStart, TokStart + Tok.getLength());
350 Result.resize(Tok.getLength());
351 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
355 /// getSpelling - This method is used to get the spelling of a token into a
356 /// preallocated buffer, instead of as an std::string. The caller is required
357 /// to allocate enough space for the token, which is guaranteed to be at least
358 /// Tok.getLength() bytes long. The actual length of the token is returned.
360 /// Note that this method may do two possible things: it may either fill in
361 /// the buffer specified with characters, or it may *change the input pointer*
362 /// to point to a constant buffer with the data already in it (avoiding a
363 /// copy). The caller is not allowed to modify the returned buffer pointer
364 /// if an internal buffer is returned.
365 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
366 const SourceManager &SourceMgr,
367 const LangOptions &LangOpts, bool *Invalid) {
368 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
370 const char *TokStart = nullptr;
371 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
372 if (Tok.is(tok::raw_identifier))
373 TokStart = Tok.getRawIdentifier().data();
374 else if (!Tok.hasUCN()) {
375 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
376 // Just return the string from the identifier table, which is very quick.
377 Buffer = II->getNameStart();
378 return II->getLength();
382 // NOTE: this can be checked even after testing for an IdentifierInfo.
384 TokStart = Tok.getLiteralData();
387 // Compute the start of the token in the input lexer buffer.
388 bool CharDataInvalid = false;
389 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
391 *Invalid = CharDataInvalid;
392 if (CharDataInvalid) {
398 // If this token contains nothing interesting, return it directly.
399 if (!Tok.needsCleaning()) {
401 return Tok.getLength();
404 // Otherwise, hard case, relex the characters into the string.
405 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
408 /// MeasureTokenLength - Relex the token at the specified location and return
409 /// its length in bytes in the input file. If the token needs cleaning (e.g.
410 /// includes a trigraph or an escaped newline) then this count includes bytes
411 /// that are part of that.
412 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
413 const SourceManager &SM,
414 const LangOptions &LangOpts) {
416 if (getRawToken(Loc, TheTok, SM, LangOpts))
418 return TheTok.getLength();
421 /// \brief Relex the token at the specified location.
422 /// \returns true if there was a failure, false on success.
423 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
424 const SourceManager &SM,
425 const LangOptions &LangOpts,
426 bool IgnoreWhiteSpace) {
427 // TODO: this could be special cased for common tokens like identifiers, ')',
428 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
429 // all obviously single-char tokens. This could use
430 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
433 // If this comes from a macro expansion, we really do want the macro name, not
434 // the token this macro expanded to.
435 Loc = SM.getExpansionLoc(Loc);
436 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
437 bool Invalid = false;
438 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
442 const char *StrData = Buffer.data()+LocInfo.second;
444 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
447 // Create a lexer starting at the beginning of this token.
448 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
449 Buffer.begin(), StrData, Buffer.end());
450 TheLexer.SetCommentRetentionState(true);
451 TheLexer.LexFromRawLexer(Result);
455 /// Returns the pointer that points to the beginning of line that contains
456 /// the given offset, or null if the offset if invalid.
457 static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
458 const char *BufStart = Buffer.data();
459 if (Offset >= Buffer.size())
461 const char *StrData = BufStart + Offset;
463 if (StrData[0] == '\n' || StrData[0] == '\r')
466 const char *LexStart = StrData;
467 while (LexStart != BufStart) {
468 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
478 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
479 const SourceManager &SM,
480 const LangOptions &LangOpts) {
481 assert(Loc.isFileID());
482 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
483 if (LocInfo.first.isInvalid())
486 bool Invalid = false;
487 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
491 // Back up from the current location until we hit the beginning of a line
492 // (or the buffer). We'll relex from that point.
493 const char *StrData = Buffer.data() + LocInfo.second;
494 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
495 if (!LexStart || LexStart == StrData)
498 // Create a lexer starting at the beginning of this token.
499 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
500 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
502 TheLexer.SetCommentRetentionState(true);
504 // Lex tokens until we find the token that contains the source location.
507 TheLexer.LexFromRawLexer(TheTok);
509 if (TheLexer.getBufferLocation() > StrData) {
510 // Lexing this token has taken the lexer past the source location we're
511 // looking for. If the current token encompasses our source location,
512 // return the beginning of that token.
513 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
514 return TheTok.getLocation();
516 // We ended up skipping over the source location entirely, which means
517 // that it points into whitespace. We're done here.
520 } while (TheTok.getKind() != tok::eof);
522 // We've passed our source location; just return the original source location.
526 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
527 const SourceManager &SM,
528 const LangOptions &LangOpts) {
530 return getBeginningOfFileToken(Loc, SM, LangOpts);
532 if (!SM.isMacroArgExpansion(Loc))
535 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
536 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
537 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
538 std::pair<FileID, unsigned> BeginFileLocInfo
539 = SM.getDecomposedLoc(BeginFileLoc);
540 assert(FileLocInfo.first == BeginFileLocInfo.first &&
541 FileLocInfo.second >= BeginFileLocInfo.second);
542 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
547 enum PreambleDirectiveKind {
554 } // end anonymous namespace
556 std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
557 const LangOptions &LangOpts,
559 // Create a lexer starting at the beginning of the file. Note that we use a
560 // "fake" file source location at offset 1 so that the lexer will track our
561 // position within the file.
562 const unsigned StartOffset = 1;
563 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
564 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
566 TheLexer.SetCommentRetentionState(true);
568 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
569 SourceLocation StartLoc = TheLexer.getSourceLocation();
571 bool InPreprocessorDirective = false;
574 unsigned IfCount = 0;
575 SourceLocation ActiveCommentLoc;
577 unsigned MaxLineOffset = 0;
579 const char *CurPtr = Buffer.begin();
580 unsigned CurLine = 0;
581 while (CurPtr != Buffer.end()) {
585 if (CurLine == MaxLines)
589 if (CurPtr != Buffer.end())
590 MaxLineOffset = CurPtr - Buffer.begin();
594 TheLexer.LexFromRawLexer(TheTok);
596 if (InPreprocessorDirective) {
597 // If we've hit the end of the file, we're done.
598 if (TheTok.getKind() == tok::eof) {
602 // If we haven't hit the end of the preprocessor directive, skip this
604 if (!TheTok.isAtStartOfLine())
607 // We've passed the end of the preprocessor directive, and will look
608 // at this token again below.
609 InPreprocessorDirective = false;
612 // Keep track of the # of lines in the preamble.
613 if (TheTok.isAtStartOfLine()) {
614 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
616 // If we were asked to limit the number of lines in the preamble,
617 // and we're about to exceed that limit, we're done.
618 if (MaxLineOffset && TokOffset >= MaxLineOffset)
622 // Comments are okay; skip over them.
623 if (TheTok.getKind() == tok::comment) {
624 if (ActiveCommentLoc.isInvalid())
625 ActiveCommentLoc = TheTok.getLocation();
629 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
630 // This is the start of a preprocessor directive.
631 Token HashTok = TheTok;
632 InPreprocessorDirective = true;
633 ActiveCommentLoc = SourceLocation();
635 // Figure out which directive this is. Since we're lexing raw tokens,
636 // we don't have an identifier table available. Instead, just look at
637 // the raw identifier to recognize and categorize preprocessor directives.
638 TheLexer.LexFromRawLexer(TheTok);
639 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
640 StringRef Keyword = TheTok.getRawIdentifier();
641 PreambleDirectiveKind PDK
642 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
643 .Case("include", PDK_Skipped)
644 .Case("__include_macros", PDK_Skipped)
645 .Case("define", PDK_Skipped)
646 .Case("undef", PDK_Skipped)
647 .Case("line", PDK_Skipped)
648 .Case("error", PDK_Skipped)
649 .Case("pragma", PDK_Skipped)
650 .Case("import", PDK_Skipped)
651 .Case("include_next", PDK_Skipped)
652 .Case("warning", PDK_Skipped)
653 .Case("ident", PDK_Skipped)
654 .Case("sccs", PDK_Skipped)
655 .Case("assert", PDK_Skipped)
656 .Case("unassert", PDK_Skipped)
657 .Case("if", PDK_StartIf)
658 .Case("ifdef", PDK_StartIf)
659 .Case("ifndef", PDK_StartIf)
660 .Case("elif", PDK_Skipped)
661 .Case("else", PDK_Skipped)
662 .Case("endif", PDK_EndIf)
663 .Default(PDK_Unknown);
671 IfStartTok = HashTok;
677 // Mismatched #endif. The preamble ends here.
685 // We don't know what this directive is; stop at the '#'.
690 // We only end up here if we didn't recognize the preprocessor
691 // directive or it was one that can't occur in the preamble at this
692 // point. Roll back the current token to the location of the '#'.
693 InPreprocessorDirective = false;
697 // We hit a token that we don't recognize as being in the
698 // "preprocessing only" part of the file, so we're no longer in
705 End = IfStartTok.getLocation();
706 else if (ActiveCommentLoc.isValid())
707 End = ActiveCommentLoc; // don't truncate a decl comment.
709 End = TheTok.getLocation();
711 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
712 IfCount? IfStartTok.isAtStartOfLine()
713 : TheTok.isAtStartOfLine());
716 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
717 /// token, return a new location that specifies a character within the token.
718 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
720 const SourceManager &SM,
721 const LangOptions &LangOpts) {
722 // Figure out how many physical characters away the specified expansion
723 // character is. This needs to take into consideration newlines and
725 bool Invalid = false;
726 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
728 // If they request the first char of the token, we're trivially done.
729 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
732 unsigned PhysOffset = 0;
734 // The usual case is that tokens don't contain anything interesting. Skip
735 // over the uninteresting characters. If a token only consists of simple
736 // chars, this method is extremely fast.
737 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
739 return TokStart.getLocWithOffset(PhysOffset);
745 // If we have a character that may be a trigraph or escaped newline, use a
746 // lexer to parse it correctly.
747 for (; CharNo; --CharNo) {
749 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
754 // Final detail: if we end up on an escaped newline, we want to return the
755 // location of the actual byte of the token. For example foo\<newline>bar
756 // advanced by 3 should return the location of b, not of \\. One compounding
757 // detail of this is that the escape may be made by a trigraph.
758 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
759 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
761 return TokStart.getLocWithOffset(PhysOffset);
764 /// \brief Computes the source location just past the end of the
765 /// token at this source location.
767 /// This routine can be used to produce a source location that
768 /// points just past the end of the token referenced by \p Loc, and
769 /// is generally used when a diagnostic needs to point just after a
770 /// token where it expected something different that it received. If
771 /// the returned source location would not be meaningful (e.g., if
772 /// it points into a macro), this routine returns an invalid
775 /// \param Offset an offset from the end of the token, where the source
776 /// location should refer to. The default offset (0) produces a source
777 /// location pointing just past the end of the token; an offset of 1 produces
778 /// a source location pointing to the last character in the token, etc.
779 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
780 const SourceManager &SM,
781 const LangOptions &LangOpts) {
783 return SourceLocation();
785 if (Loc.isMacroID()) {
786 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
787 return SourceLocation(); // Points inside the macro expansion.
790 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
796 return Loc.getLocWithOffset(Len);
799 /// \brief Returns true if the given MacroID location points at the first
800 /// token of the macro expansion.
801 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
802 const SourceManager &SM,
803 const LangOptions &LangOpts,
804 SourceLocation *MacroBegin) {
805 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
807 SourceLocation expansionLoc;
808 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
811 if (expansionLoc.isFileID()) {
812 // No other macro expansions, this is the first.
814 *MacroBegin = expansionLoc;
818 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
821 /// \brief Returns true if the given MacroID location points at the last
822 /// token of the macro expansion.
823 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
824 const SourceManager &SM,
825 const LangOptions &LangOpts,
826 SourceLocation *MacroEnd) {
827 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
829 SourceLocation spellLoc = SM.getSpellingLoc(loc);
830 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
834 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
835 SourceLocation expansionLoc;
836 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
839 if (expansionLoc.isFileID()) {
840 // No other macro expansions.
842 *MacroEnd = expansionLoc;
846 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
849 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
850 const SourceManager &SM,
851 const LangOptions &LangOpts) {
852 SourceLocation Begin = Range.getBegin();
853 SourceLocation End = Range.getEnd();
854 assert(Begin.isFileID() && End.isFileID());
855 if (Range.isTokenRange()) {
856 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
858 return CharSourceRange();
861 // Break down the source locations.
864 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
866 return CharSourceRange();
869 if (!SM.isInFileID(End, FID, &EndOffs) ||
871 return CharSourceRange();
873 return CharSourceRange::getCharRange(Begin, End);
876 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
877 const SourceManager &SM,
878 const LangOptions &LangOpts) {
879 SourceLocation Begin = Range.getBegin();
880 SourceLocation End = Range.getEnd();
881 if (Begin.isInvalid() || End.isInvalid())
882 return CharSourceRange();
884 if (Begin.isFileID() && End.isFileID())
885 return makeRangeFromFileLocs(Range, SM, LangOpts);
887 if (Begin.isMacroID() && End.isFileID()) {
888 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
889 return CharSourceRange();
890 Range.setBegin(Begin);
891 return makeRangeFromFileLocs(Range, SM, LangOpts);
894 if (Begin.isFileID() && End.isMacroID()) {
895 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
897 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
899 return CharSourceRange();
901 return makeRangeFromFileLocs(Range, SM, LangOpts);
904 assert(Begin.isMacroID() && End.isMacroID());
905 SourceLocation MacroBegin, MacroEnd;
906 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
907 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
909 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
911 Range.setBegin(MacroBegin);
912 Range.setEnd(MacroEnd);
913 return makeRangeFromFileLocs(Range, SM, LangOpts);
916 bool Invalid = false;
917 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
920 return CharSourceRange();
922 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
923 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
926 return CharSourceRange();
928 if (EndEntry.getExpansion().isMacroArgExpansion() &&
929 BeginEntry.getExpansion().getExpansionLocStart() ==
930 EndEntry.getExpansion().getExpansionLocStart()) {
931 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
932 Range.setEnd(SM.getImmediateSpellingLoc(End));
933 return makeFileCharRange(Range, SM, LangOpts);
937 return CharSourceRange();
940 StringRef Lexer::getSourceText(CharSourceRange Range,
941 const SourceManager &SM,
942 const LangOptions &LangOpts,
944 Range = makeFileCharRange(Range, SM, LangOpts);
945 if (Range.isInvalid()) {
946 if (Invalid) *Invalid = true;
950 // Break down the source location.
951 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
952 if (beginInfo.first.isInvalid()) {
953 if (Invalid) *Invalid = true;
958 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
959 beginInfo.second > EndOffs) {
960 if (Invalid) *Invalid = true;
964 // Try to the load the file buffer.
965 bool invalidTemp = false;
966 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
968 if (Invalid) *Invalid = true;
972 if (Invalid) *Invalid = false;
973 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
976 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
977 const SourceManager &SM,
978 const LangOptions &LangOpts) {
979 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
981 // Find the location of the immediate macro expansion.
983 FileID FID = SM.getFileID(Loc);
984 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
985 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
986 Loc = Expansion.getExpansionLocStart();
987 if (!Expansion.isMacroArgExpansion())
990 // For macro arguments we need to check that the argument did not come
991 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
993 // Loc points to the argument id of the macro definition, move to the
995 Loc = SM.getImmediateExpansionRange(Loc).first;
996 SourceLocation SpellLoc = Expansion.getSpellingLoc();
997 if (SpellLoc.isFileID())
998 break; // No inner macro.
1000 // If spelling location resides in the same FileID as macro expansion
1001 // location, it means there is no inner macro.
1002 FileID MacroFID = SM.getFileID(Loc);
1003 if (SM.isInFileID(SpellLoc, MacroFID))
1006 // Argument came from inner macro.
1010 // Find the spelling location of the start of the non-argument expansion
1011 // range. This is where the macro name was spelled in order to begin
1012 // expanding this macro.
1013 Loc = SM.getSpellingLoc(Loc);
1015 // Dig out the buffer where the macro name was spelled and the extents of the
1016 // name so that we can render it into the expansion note.
1017 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1018 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1019 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1020 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1023 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1024 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1025 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1026 // Walk past macro argument expanions.
1027 while (SM.isMacroArgExpansion(Loc))
1028 Loc = SM.getImmediateExpansionRange(Loc).first;
1030 // If the macro's spelling has no FileID, then it's actually a token paste
1031 // or stringization (or similar) and not a macro at all.
1032 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1035 // Find the spelling location of the start of the non-argument expansion
1036 // range. This is where the macro name was spelled in order to begin
1037 // expanding this macro.
1038 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1040 // Dig out the buffer where the macro name was spelled and the extents of the
1041 // name so that we can render it into the expansion note.
1042 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1043 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1044 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1045 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1048 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1049 return isIdentifierBody(c, LangOpts.DollarIdents);
1052 StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1053 const SourceManager &SM) {
1054 if (Loc.isInvalid() || Loc.isMacroID())
1056 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1057 if (LocInfo.first.isInvalid())
1059 bool Invalid = false;
1060 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1063 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1066 StringRef Rest = Buffer.substr(Line - Buffer.data());
1067 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1068 return NumWhitespaceChars == StringRef::npos
1070 : Rest.take_front(NumWhitespaceChars);
1073 //===----------------------------------------------------------------------===//
1074 // Diagnostics forwarding code.
1075 //===----------------------------------------------------------------------===//
1077 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1078 /// lexer buffer was all expanded at a single point, perform the mapping.
1079 /// This is currently only used for _Pragma implementation, so it is the slow
1080 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1081 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1082 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1083 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1084 SourceLocation FileLoc,
1085 unsigned CharNo, unsigned TokLen) {
1086 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1088 // Otherwise, we're lexing "mapped tokens". This is used for things like
1089 // _Pragma handling. Combine the expansion location of FileLoc with the
1090 // spelling location.
1091 SourceManager &SM = PP.getSourceManager();
1093 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1094 // characters come from spelling(FileLoc)+Offset.
1095 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1096 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1098 // Figure out the expansion loc range, which is the range covered by the
1099 // original _Pragma(...) sequence.
1100 std::pair<SourceLocation,SourceLocation> II =
1101 SM.getImmediateExpansionRange(FileLoc);
1103 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1106 /// getSourceLocation - Return a source location identifier for the specified
1107 /// offset in the current file.
1108 SourceLocation Lexer::getSourceLocation(const char *Loc,
1109 unsigned TokLen) const {
1110 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1111 "Location out of range for this buffer!");
1113 // In the normal case, we're just lexing from a simple file buffer, return
1114 // the file id from FileLoc with the offset specified.
1115 unsigned CharNo = Loc-BufferStart;
1116 if (FileLoc.isFileID())
1117 return FileLoc.getLocWithOffset(CharNo);
1119 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1120 // tokens are lexed from where the _Pragma was defined.
1121 assert(PP && "This doesn't work on raw lexers");
1122 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1125 /// Diag - Forwarding function for diagnostics. This translate a source
1126 /// position in the current buffer into a SourceLocation object for rendering.
1127 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1128 return PP->Diag(getSourceLocation(Loc), DiagID);
1131 //===----------------------------------------------------------------------===//
1132 // Trigraph and Escaped Newline Handling Code.
1133 //===----------------------------------------------------------------------===//
1135 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1136 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1137 static char GetTrigraphCharForLetter(char Letter) {
1140 case '=': return '#';
1141 case ')': return ']';
1142 case '(': return '[';
1143 case '!': return '|';
1144 case '\'': return '^';
1145 case '>': return '}';
1146 case '/': return '\\';
1147 case '<': return '{';
1148 case '-': return '~';
1152 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1153 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1154 /// return the result character. Finally, emit a warning about trigraph use
1155 /// whether trigraphs are enabled or not.
1156 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1157 char Res = GetTrigraphCharForLetter(*CP);
1158 if (!Res || !L) return Res;
1160 if (!L->getLangOpts().Trigraphs) {
1161 if (!L->isLexingRawMode())
1162 L->Diag(CP-2, diag::trigraph_ignored);
1166 if (!L->isLexingRawMode())
1167 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1171 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1172 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1173 /// trigraph equivalent on entry to this function.
1174 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1176 while (isWhitespace(Ptr[Size])) {
1179 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1182 // If this is a \r\n or \n\r, skip the other half.
1183 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1184 Ptr[Size-1] != Ptr[Size])
1190 // Not an escaped newline, must be a \t or something else.
1194 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1195 /// them), skip over them and return the first non-escaped-newline found,
1196 /// otherwise return P.
1197 const char *Lexer::SkipEscapedNewLines(const char *P) {
1199 const char *AfterEscape;
1202 } else if (*P == '?') {
1203 // If not a trigraph for escape, bail out.
1204 if (P[1] != '?' || P[2] != '/')
1206 // FIXME: Take LangOpts into account; the language might not
1207 // support trigraphs.
1213 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1214 if (NewLineSize == 0) return P;
1215 P = AfterEscape+NewLineSize;
1219 /// \brief Checks that the given token is the first token that occurs after the
1220 /// given location (this excludes comments and whitespace). Returns the location
1221 /// immediately after the specified token. If the token is not found or the
1222 /// location is inside a macro, the returned source location will be invalid.
1223 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1224 tok::TokenKind TKind,
1225 const SourceManager &SM,
1226 const LangOptions &LangOpts,
1227 bool SkipTrailingWhitespaceAndNewLine) {
1228 if (Loc.isMacroID()) {
1229 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1230 return SourceLocation();
1232 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1234 // Break down the source location.
1235 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1237 // Try to load the file buffer.
1238 bool InvalidTemp = false;
1239 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1241 return SourceLocation();
1243 const char *TokenBegin = File.data() + LocInfo.second;
1245 // Lex from the start of the given location.
1246 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1247 TokenBegin, File.end());
1250 lexer.LexFromRawLexer(Tok);
1251 if (Tok.isNot(TKind))
1252 return SourceLocation();
1253 SourceLocation TokenLoc = Tok.getLocation();
1255 // Calculate how much whitespace needs to be skipped if any.
1256 unsigned NumWhitespaceChars = 0;
1257 if (SkipTrailingWhitespaceAndNewLine) {
1258 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1260 unsigned char C = *TokenEnd;
1261 while (isHorizontalWhitespace(C)) {
1263 NumWhitespaceChars++;
1266 // Skip \r, \n, \r\n, or \n\r
1267 if (C == '\n' || C == '\r') {
1270 NumWhitespaceChars++;
1271 if ((C == '\n' || C == '\r') && C != PrevC)
1272 NumWhitespaceChars++;
1276 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1279 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1280 /// get its size, and return it. This is tricky in several cases:
1281 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1282 /// then either return the trigraph (skipping 3 chars) or the '?',
1283 /// depending on whether trigraphs are enabled or not.
1284 /// 2. If this is an escaped newline (potentially with whitespace between
1285 /// the backslash and newline), implicitly skip the newline and return
1286 /// the char after it.
1288 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1289 /// know that we can accumulate into Size, and that we have already incremented
1290 /// Ptr by Size bytes.
1292 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1293 /// be updated to match.
1295 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1297 // If we have a slash, look for an escaped newline.
1298 if (Ptr[0] == '\\') {
1302 // Common case, backslash-char where the char is not whitespace.
1303 if (!isWhitespace(Ptr[0])) return '\\';
1305 // See if we have optional whitespace characters between the slash and
1307 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1308 // Remember that this token needs to be cleaned.
1309 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1311 // Warn if there was whitespace between the backslash and newline.
1312 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1313 Diag(Ptr, diag::backslash_newline_space);
1315 // Found backslash<whitespace><newline>. Parse the char after it.
1316 Size += EscapedNewLineSize;
1317 Ptr += EscapedNewLineSize;
1319 // Use slow version to accumulate a correct size field.
1320 return getCharAndSizeSlow(Ptr, Size, Tok);
1323 // Otherwise, this is not an escaped newline, just return the slash.
1327 // If this is a trigraph, process it.
1328 if (Ptr[0] == '?' && Ptr[1] == '?') {
1329 // If this is actually a legal trigraph (not something like "??x"), emit
1330 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1331 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1332 // Remember that this token needs to be cleaned.
1333 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1337 if (C == '\\') goto Slash;
1342 // If this is neither, return a single character.
1347 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1348 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1349 /// and that we have already incremented Ptr by Size bytes.
1351 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1352 /// be updated to match.
1353 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1354 const LangOptions &LangOpts) {
1355 // If we have a slash, look for an escaped newline.
1356 if (Ptr[0] == '\\') {
1360 // Common case, backslash-char where the char is not whitespace.
1361 if (!isWhitespace(Ptr[0])) return '\\';
1363 // See if we have optional whitespace characters followed by a newline.
1364 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1365 // Found backslash<whitespace><newline>. Parse the char after it.
1366 Size += EscapedNewLineSize;
1367 Ptr += EscapedNewLineSize;
1369 // Use slow version to accumulate a correct size field.
1370 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1373 // Otherwise, this is not an escaped newline, just return the slash.
1377 // If this is a trigraph, process it.
1378 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1379 // If this is actually a legal trigraph (not something like "??x"), return
1381 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1384 if (C == '\\') goto Slash;
1389 // If this is neither, return a single character.
1394 //===----------------------------------------------------------------------===//
1395 // Helper methods for lexing.
1396 //===----------------------------------------------------------------------===//
1398 /// \brief Routine that indiscriminately skips bytes in the source file.
1399 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1401 if (BufferPtr > BufferEnd)
1402 BufferPtr = BufferEnd;
1403 // FIXME: What exactly does the StartOfLine bit mean? There are two
1404 // possible meanings for the "start" of the line: the first token on the
1405 // unexpanded line, or the first token on the expanded line.
1406 IsAtStartOfLine = StartOfLine;
1407 IsAtPhysicalStartOfLine = StartOfLine;
1410 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1411 if (LangOpts.AsmPreprocessor) {
1413 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1414 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1415 C11AllowedIDCharRanges);
1416 return C11AllowedIDChars.contains(C);
1417 } else if (LangOpts.CPlusPlus) {
1418 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1419 CXX03AllowedIDCharRanges);
1420 return CXX03AllowedIDChars.contains(C);
1422 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1423 C99AllowedIDCharRanges);
1424 return C99AllowedIDChars.contains(C);
1428 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1429 assert(isAllowedIDChar(C, LangOpts));
1430 if (LangOpts.AsmPreprocessor) {
1432 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1433 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1434 C11DisallowedInitialIDCharRanges);
1435 return !C11DisallowedInitialIDChars.contains(C);
1436 } else if (LangOpts.CPlusPlus) {
1439 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1440 C99DisallowedInitialIDCharRanges);
1441 return !C99DisallowedInitialIDChars.contains(C);
1445 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1447 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1448 L.getSourceLocation(End));
1451 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1452 CharSourceRange Range, bool IsFirst) {
1453 // Check C99 compatibility.
1454 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1456 CannotAppearInIdentifier = 0,
1457 CannotStartIdentifier
1460 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1461 C99AllowedIDCharRanges);
1462 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1463 C99DisallowedInitialIDCharRanges);
1464 if (!C99AllowedIDChars.contains(C)) {
1465 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1467 << CannotAppearInIdentifier;
1468 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1469 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1471 << CannotStartIdentifier;
1475 // Check C++98 compatibility.
1476 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1477 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1478 CXX03AllowedIDCharRanges);
1479 if (!CXX03AllowedIDChars.contains(C)) {
1480 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1486 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1488 const char *UCNPtr = CurPtr + Size;
1489 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1490 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1493 if (!isLexingRawMode())
1494 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1495 makeCharRange(*this, CurPtr, UCNPtr),
1498 Result.setFlag(Token::HasUCN);
1499 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1500 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1503 while (CurPtr != UCNPtr)
1504 (void)getAndAdvanceChar(CurPtr, Result);
1508 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1509 const char *UnicodePtr = CurPtr;
1510 llvm::UTF32 CodePoint;
1511 llvm::ConversionResult Result =
1512 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1513 (const llvm::UTF8 *)BufferEnd,
1515 llvm::strictConversion);
1516 if (Result != llvm::conversionOK ||
1517 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1520 if (!isLexingRawMode())
1521 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1522 makeCharRange(*this, CurPtr, UnicodePtr),
1525 CurPtr = UnicodePtr;
1529 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1530 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1532 unsigned char C = *CurPtr++;
1533 while (isIdentifierBody(C))
1536 --CurPtr; // Back up over the skipped character.
1538 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1539 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1541 // TODO: Could merge these checks into an InfoTable flag to make the
1542 // comparison cheaper
1543 if (isASCII(C) && C != '\\' && C != '?' &&
1544 (C != '$' || !LangOpts.DollarIdents)) {
1546 const char *IdStart = BufferPtr;
1547 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1548 Result.setRawIdentifierData(IdStart);
1550 // If we are in raw mode, return this identifier raw. There is no need to
1551 // look up identifier information or attempt to macro expand it.
1555 // Fill in Result.IdentifierInfo and update the token kind,
1556 // looking up the identifier in the identifier table.
1557 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1559 // Finally, now that we know we have an identifier, pass this off to the
1560 // preprocessor, which may macro expand it or something.
1561 if (II->isHandleIdentifierCase())
1562 return PP->HandleIdentifier(Result);
1564 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1565 && II->getPPKeywordID() == tok::pp_not_keyword
1566 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1567 // Return the code-completion token.
1568 Result.setKind(tok::code_completion);
1575 // Otherwise, $,\,? in identifier found. Enter slower path.
1577 C = getCharAndSize(CurPtr, Size);
1580 // If we hit a $ and they are not supported in identifiers, we are done.
1581 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1583 // Otherwise, emit a diagnostic and continue.
1584 if (!isLexingRawMode())
1585 Diag(CurPtr, diag::ext_dollar_in_identifier);
1586 CurPtr = ConsumeChar(CurPtr, Size, Result);
1587 C = getCharAndSize(CurPtr, Size);
1590 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1591 C = getCharAndSize(CurPtr, Size);
1593 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1594 C = getCharAndSize(CurPtr, Size);
1596 } else if (!isIdentifierBody(C)) {
1597 goto FinishIdentifier;
1600 // Otherwise, this character is good, consume it.
1601 CurPtr = ConsumeChar(CurPtr, Size, Result);
1603 C = getCharAndSize(CurPtr, Size);
1604 while (isIdentifierBody(C)) {
1605 CurPtr = ConsumeChar(CurPtr, Size, Result);
1606 C = getCharAndSize(CurPtr, Size);
1611 /// isHexaLiteral - Return true if Start points to a hex constant.
1612 /// in microsoft mode (where this is supposed to be several different tokens).
1613 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1615 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1618 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1619 return (C2 == 'x' || C2 == 'X');
1622 /// LexNumericConstant - Lex the remainder of a integer or floating point
1623 /// constant. From[-1] is the first character lexed. Return the end of the
1625 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1627 char C = getCharAndSize(CurPtr, Size);
1629 while (isPreprocessingNumberBody(C)) {
1630 CurPtr = ConsumeChar(CurPtr, Size, Result);
1632 C = getCharAndSize(CurPtr, Size);
1635 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1636 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1637 // If we are in Microsoft mode, don't continue if the constant is hex.
1638 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1639 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1640 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1643 // If we have a hex FP constant, continue.
1644 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1645 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1646 // not-quite-conforming extension. Only do so if this looks like it's
1647 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1648 bool IsHexFloat = true;
1649 if (!LangOpts.C99) {
1650 if (!isHexaLiteral(BufferPtr, LangOpts))
1652 else if (!getLangOpts().CPlusPlus1z &&
1653 std::find(BufferPtr, CurPtr, '_') != CurPtr)
1657 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1660 // If we have a digit separator, continue.
1661 if (C == '\'' && getLangOpts().CPlusPlus14) {
1663 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1664 if (isIdentifierBody(Next)) {
1665 if (!isLexingRawMode())
1666 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1667 CurPtr = ConsumeChar(CurPtr, Size, Result);
1668 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1669 return LexNumericConstant(Result, CurPtr);
1673 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1674 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1675 return LexNumericConstant(Result, CurPtr);
1676 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1677 return LexNumericConstant(Result, CurPtr);
1679 // Update the location of token as well as BufferPtr.
1680 const char *TokStart = BufferPtr;
1681 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1682 Result.setLiteralData(TokStart);
1686 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1687 /// in C++11, or warn on a ud-suffix in C++98.
1688 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1689 bool IsStringLiteral) {
1690 assert(getLangOpts().CPlusPlus);
1692 // Maximally munch an identifier.
1694 char C = getCharAndSize(CurPtr, Size);
1695 bool Consumed = false;
1697 if (!isIdentifierHead(C)) {
1698 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1700 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1706 if (!getLangOpts().CPlusPlus11) {
1707 if (!isLexingRawMode())
1709 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1710 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1711 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1715 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1716 // that does not start with an underscore is ill-formed. As a conforming
1717 // extension, we treat all such suffixes as if they had whitespace before
1718 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1719 // likely to be a ud-suffix than a macro, however, and accept that.
1721 bool IsUDSuffix = false;
1724 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1725 // In C++1y, we need to look ahead a few characters to see if this is a
1726 // valid suffix for a string literal or a numeric literal (this could be
1727 // the 'operator""if' defining a numeric literal operator).
1728 const unsigned MaxStandardSuffixLength = 3;
1729 char Buffer[MaxStandardSuffixLength] = { C };
1730 unsigned Consumed = Size;
1734 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1736 if (!isIdentifierBody(Next)) {
1737 // End of suffix. Check whether this is on the whitelist.
1738 const StringRef CompleteSuffix(Buffer, Chars);
1739 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1744 if (Chars == MaxStandardSuffixLength)
1745 // Too long: can't be a standard suffix.
1748 Buffer[Chars++] = Next;
1749 Consumed += NextSize;
1754 if (!isLexingRawMode())
1755 Diag(CurPtr, getLangOpts().MSVCCompat
1756 ? diag::ext_ms_reserved_user_defined_literal
1757 : diag::ext_reserved_user_defined_literal)
1758 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1762 CurPtr = ConsumeChar(CurPtr, Size, Result);
1765 Result.setFlag(Token::HasUDSuffix);
1767 C = getCharAndSize(CurPtr, Size);
1768 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1769 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1770 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1777 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1778 /// either " or L" or u8" or u" or U".
1779 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1780 tok::TokenKind Kind) {
1781 // Does this string contain the \0 character?
1782 const char *NulCharacter = nullptr;
1784 if (!isLexingRawMode() &&
1785 (Kind == tok::utf8_string_literal ||
1786 Kind == tok::utf16_string_literal ||
1787 Kind == tok::utf32_string_literal))
1788 Diag(BufferPtr, getLangOpts().CPlusPlus
1789 ? diag::warn_cxx98_compat_unicode_literal
1790 : diag::warn_c99_compat_unicode_literal);
1792 char C = getAndAdvanceChar(CurPtr, Result);
1794 // Skip escaped characters. Escaped newlines will already be processed by
1795 // getAndAdvanceChar.
1797 C = getAndAdvanceChar(CurPtr, Result);
1799 if (C == '\n' || C == '\r' || // Newline.
1800 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1801 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1802 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1803 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1808 if (isCodeCompletionPoint(CurPtr-1)) {
1809 PP->CodeCompleteNaturalLanguage();
1810 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1815 NulCharacter = CurPtr-1;
1817 C = getAndAdvanceChar(CurPtr, Result);
1820 // If we are in C++11, lex the optional ud-suffix.
1821 if (getLangOpts().CPlusPlus)
1822 CurPtr = LexUDSuffix(Result, CurPtr, true);
1824 // If a nul character existed in the string, warn about it.
1825 if (NulCharacter && !isLexingRawMode())
1826 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1828 // Update the location of the token as well as the BufferPtr instance var.
1829 const char *TokStart = BufferPtr;
1830 FormTokenWithChars(Result, CurPtr, Kind);
1831 Result.setLiteralData(TokStart);
1835 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1836 /// having lexed R", LR", u8R", uR", or UR".
1837 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1838 tok::TokenKind Kind) {
1839 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1840 // Between the initial and final double quote characters of the raw string,
1841 // any transformations performed in phases 1 and 2 (trigraphs,
1842 // universal-character-names, and line splicing) are reverted.
1844 if (!isLexingRawMode())
1845 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1847 unsigned PrefixLen = 0;
1849 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1852 // If the last character was not a '(', then we didn't lex a valid delimiter.
1853 if (CurPtr[PrefixLen] != '(') {
1854 if (!isLexingRawMode()) {
1855 const char *PrefixEnd = &CurPtr[PrefixLen];
1856 if (PrefixLen == 16) {
1857 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1859 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1860 << StringRef(PrefixEnd, 1);
1864 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1865 // it's possible the '"' was intended to be part of the raw string, but
1866 // there's not much we can do about that.
1872 if (C == 0 && CurPtr-1 == BufferEnd) {
1878 FormTokenWithChars(Result, CurPtr, tok::unknown);
1882 // Save prefix and move CurPtr past it
1883 const char *Prefix = CurPtr;
1884 CurPtr += PrefixLen + 1; // skip over prefix and '('
1890 // Check for prefix match and closing quote.
1891 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1892 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1895 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1896 if (!isLexingRawMode())
1897 Diag(BufferPtr, diag::err_unterminated_raw_string)
1898 << StringRef(Prefix, PrefixLen);
1899 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1904 // If we are in C++11, lex the optional ud-suffix.
1905 if (getLangOpts().CPlusPlus)
1906 CurPtr = LexUDSuffix(Result, CurPtr, true);
1908 // Update the location of token as well as BufferPtr.
1909 const char *TokStart = BufferPtr;
1910 FormTokenWithChars(Result, CurPtr, Kind);
1911 Result.setLiteralData(TokStart);
1915 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1916 /// after having lexed the '<' character. This is used for #include filenames.
1917 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1918 // Does this string contain the \0 character?
1919 const char *NulCharacter = nullptr;
1920 const char *AfterLessPos = CurPtr;
1921 char C = getAndAdvanceChar(CurPtr, Result);
1923 // Skip escaped characters.
1924 if (C == '\\' && CurPtr < BufferEnd) {
1925 // Skip the escaped character.
1926 getAndAdvanceChar(CurPtr, Result);
1927 } else if (C == '\n' || C == '\r' || // Newline.
1928 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1929 isCodeCompletionPoint(CurPtr-1)))) {
1930 // If the filename is unterminated, then it must just be a lone <
1931 // character. Return this as such.
1932 FormTokenWithChars(Result, AfterLessPos, tok::less);
1934 } else if (C == 0) {
1935 NulCharacter = CurPtr-1;
1937 C = getAndAdvanceChar(CurPtr, Result);
1940 // If a nul character existed in the string, warn about it.
1941 if (NulCharacter && !isLexingRawMode())
1942 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1944 // Update the location of token as well as BufferPtr.
1945 const char *TokStart = BufferPtr;
1946 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1947 Result.setLiteralData(TokStart);
1951 /// LexCharConstant - Lex the remainder of a character constant, after having
1952 /// lexed either ' or L' or u8' or u' or U'.
1953 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1954 tok::TokenKind Kind) {
1955 // Does this character contain the \0 character?
1956 const char *NulCharacter = nullptr;
1958 if (!isLexingRawMode()) {
1959 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1960 Diag(BufferPtr, getLangOpts().CPlusPlus
1961 ? diag::warn_cxx98_compat_unicode_literal
1962 : diag::warn_c99_compat_unicode_literal);
1963 else if (Kind == tok::utf8_char_constant)
1964 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1967 char C = getAndAdvanceChar(CurPtr, Result);
1969 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1970 Diag(BufferPtr, diag::ext_empty_character);
1971 FormTokenWithChars(Result, CurPtr, tok::unknown);
1976 // Skip escaped characters.
1978 C = getAndAdvanceChar(CurPtr, Result);
1980 if (C == '\n' || C == '\r' || // Newline.
1981 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1982 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1983 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
1984 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1989 if (isCodeCompletionPoint(CurPtr-1)) {
1990 PP->CodeCompleteNaturalLanguage();
1991 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1996 NulCharacter = CurPtr-1;
1998 C = getAndAdvanceChar(CurPtr, Result);
2001 // If we are in C++11, lex the optional ud-suffix.
2002 if (getLangOpts().CPlusPlus)
2003 CurPtr = LexUDSuffix(Result, CurPtr, false);
2005 // If a nul character existed in the character, warn about it.
2006 if (NulCharacter && !isLexingRawMode())
2007 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
2009 // Update the location of token as well as BufferPtr.
2010 const char *TokStart = BufferPtr;
2011 FormTokenWithChars(Result, CurPtr, Kind);
2012 Result.setLiteralData(TokStart);
2016 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2017 /// Update BufferPtr to point to the next non-whitespace character and return.
2019 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2021 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2022 bool &TokAtPhysicalStartOfLine) {
2023 // Whitespace - Skip it, then return the token after the whitespace.
2024 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2026 unsigned char Char = *CurPtr;
2028 // Skip consecutive spaces efficiently.
2030 // Skip horizontal whitespace very aggressively.
2031 while (isHorizontalWhitespace(Char))
2034 // Otherwise if we have something other than whitespace, we're done.
2035 if (!isVerticalWhitespace(Char))
2038 if (ParsingPreprocessorDirective) {
2039 // End of preprocessor directive line, let LexTokenInternal handle this.
2044 // OK, but handle newline.
2049 // If the client wants us to return whitespace, return it now.
2050 if (isKeepWhitespaceMode()) {
2051 FormTokenWithChars(Result, CurPtr, tok::unknown);
2053 IsAtStartOfLine = true;
2054 IsAtPhysicalStartOfLine = true;
2056 // FIXME: The next token will not have LeadingSpace set.
2060 // If this isn't immediately after a newline, there is leading space.
2061 char PrevChar = CurPtr[-1];
2062 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2064 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2066 Result.setFlag(Token::StartOfLine);
2067 TokAtPhysicalStartOfLine = true;
2074 /// We have just read the // characters from input. Skip until we find the
2075 /// newline character thats terminate the comment. Then update BufferPtr and
2078 /// If we're in KeepCommentMode or any CommentHandler has inserted
2079 /// some tokens, this will store the first token and return true.
2080 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2081 bool &TokAtPhysicalStartOfLine) {
2082 // If Line comments aren't explicitly enabled for this language, emit an
2083 // extension warning.
2084 if (!LangOpts.LineComment && !isLexingRawMode()) {
2085 Diag(BufferPtr, diag::ext_line_comment);
2087 // Mark them enabled so we only emit one warning for this translation
2089 LangOpts.LineComment = true;
2092 // Scan over the body of the comment. The common case, when scanning, is that
2093 // the comment contains normal ascii characters with nothing interesting in
2094 // them. As such, optimize for this case with the inner loop.
2096 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2097 // character that ends the line comment.
2101 // Skip over characters in the fast loop.
2102 while (C != 0 && // Potentially EOF.
2103 C != '\n' && C != '\r') // Newline or DOS-style newline.
2106 const char *NextLine = CurPtr;
2108 // We found a newline, see if it's escaped.
2109 const char *EscapePtr = CurPtr-1;
2110 bool HasSpace = false;
2111 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2116 if (*EscapePtr == '\\')
2119 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2120 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2121 // Trigraph-escaped newline.
2122 CurPtr = EscapePtr-2;
2124 break; // This is a newline, we're done.
2126 // If there was space between the backslash and newline, warn about it.
2127 if (HasSpace && !isLexingRawMode())
2128 Diag(EscapePtr, diag::backslash_newline_space);
2131 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2132 // properly decode the character. Read it in raw mode to avoid emitting
2133 // diagnostics about things like trigraphs. If we see an escaped newline,
2134 // we'll handle it below.
2135 const char *OldPtr = CurPtr;
2136 bool OldRawMode = isLexingRawMode();
2137 LexingRawMode = true;
2138 C = getAndAdvanceChar(CurPtr, Result);
2139 LexingRawMode = OldRawMode;
2141 // If we only read only one character, then no special handling is needed.
2142 // We're done and can skip forward to the newline.
2143 if (C != 0 && CurPtr == OldPtr+1) {
2148 // If we read multiple characters, and one of those characters was a \r or
2149 // \n, then we had an escaped newline within the comment. Emit diagnostic
2150 // unless the next line is also a // comment.
2151 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2152 for (; OldPtr != CurPtr; ++OldPtr)
2153 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2154 // Okay, we found a // comment that ends in a newline, if the next
2155 // line is also a // comment, but has spaces, don't emit a diagnostic.
2156 if (isWhitespace(C)) {
2157 const char *ForwardPtr = CurPtr;
2158 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2160 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2164 if (!isLexingRawMode())
2165 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2170 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2175 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2176 PP->CodeCompleteNaturalLanguage();
2182 // Found but did not consume the newline. Notify comment handlers about the
2183 // comment unless we're in a #if 0 block.
2184 if (PP && !isLexingRawMode() &&
2185 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2186 getSourceLocation(CurPtr)))) {
2188 return true; // A token has to be returned.
2191 // If we are returning comments as tokens, return this comment as a token.
2192 if (inKeepCommentMode())
2193 return SaveLineComment(Result, CurPtr);
2195 // If we are inside a preprocessor directive and we see the end of line,
2196 // return immediately, so that the lexer can return this as an EOD token.
2197 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2202 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2203 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2204 // contribute to another token), it isn't needed for correctness. Note that
2205 // this is ok even in KeepWhitespaceMode, because we would have returned the
2206 /// comment above in that mode.
2209 // The next returned token is at the start of the line.
2210 Result.setFlag(Token::StartOfLine);
2211 TokAtPhysicalStartOfLine = true;
2212 // No leading whitespace seen so far.
2213 Result.clearFlag(Token::LeadingSpace);
2218 /// If in save-comment mode, package up this Line comment in an appropriate
2219 /// way and return it.
2220 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2221 // If we're not in a preprocessor directive, just return the // comment
2223 FormTokenWithChars(Result, CurPtr, tok::comment);
2225 if (!ParsingPreprocessorDirective || LexingRawMode)
2228 // If this Line-style comment is in a macro definition, transmogrify it into
2229 // a C-style block comment.
2230 bool Invalid = false;
2231 std::string Spelling = PP->getSpelling(Result, &Invalid);
2235 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2236 Spelling[1] = '*'; // Change prefix to "/*".
2237 Spelling += "*/"; // add suffix.
2239 Result.setKind(tok::comment);
2240 PP->CreateString(Spelling, Result,
2241 Result.getLocation(), Result.getLocation());
2245 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2246 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2247 /// a diagnostic if so. We know that the newline is inside of a block comment.
2248 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2250 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2252 // Back up off the newline.
2255 // If this is a two-character newline sequence, skip the other character.
2256 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2257 // \n\n or \r\r -> not escaped newline.
2258 if (CurPtr[0] == CurPtr[1])
2260 // \n\r or \r\n -> skip the newline.
2264 // If we have horizontal whitespace, skip over it. We allow whitespace
2265 // between the slash and newline.
2266 bool HasSpace = false;
2267 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2272 // If we have a slash, we know this is an escaped newline.
2273 if (*CurPtr == '\\') {
2274 if (CurPtr[-1] != '*') return false;
2276 // It isn't a slash, is it the ?? / trigraph?
2277 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2281 // This is the trigraph ending the comment. Emit a stern warning!
2284 // If no trigraphs are enabled, warn that we ignored this trigraph and
2285 // ignore this * character.
2286 if (!L->getLangOpts().Trigraphs) {
2287 if (!L->isLexingRawMode())
2288 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2291 if (!L->isLexingRawMode())
2292 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2295 // Warn about having an escaped newline between the */ characters.
2296 if (!L->isLexingRawMode())
2297 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2299 // If there was space between the backslash and newline, warn about it.
2300 if (HasSpace && !L->isLexingRawMode())
2301 L->Diag(CurPtr, diag::backslash_newline_space);
2307 #include <emmintrin.h>
2309 #include <altivec.h>
2313 /// We have just read from input the / and * characters that started a comment.
2314 /// Read until we find the * and / characters that terminate the comment.
2315 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2316 /// comments, because they cannot cause the comment to end. The only thing
2317 /// that can happen is the comment could end with an escaped newline between
2318 /// the terminating * and /.
2320 /// If we're in KeepCommentMode or any CommentHandler has inserted
2321 /// some tokens, this will store the first token and return true.
2322 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2323 bool &TokAtPhysicalStartOfLine) {
2324 // Scan one character past where we should, looking for a '/' character. Once
2325 // we find it, check to see if it was preceded by a *. This common
2326 // optimization helps people who like to put a lot of * characters in their
2329 // The first character we get with newlines and trigraphs skipped to handle
2330 // the degenerate /*/ case below correctly if the * has an escaped newline
2333 unsigned char C = getCharAndSize(CurPtr, CharSize);
2335 if (C == 0 && CurPtr == BufferEnd+1) {
2336 if (!isLexingRawMode())
2337 Diag(BufferPtr, diag::err_unterminated_block_comment);
2340 // KeepWhitespaceMode should return this broken comment as a token. Since
2341 // it isn't a well formed comment, just return it as an 'unknown' token.
2342 if (isKeepWhitespaceMode()) {
2343 FormTokenWithChars(Result, CurPtr, tok::unknown);
2351 // Check to see if the first character after the '/*' is another /. If so,
2352 // then this slash does not end the block comment, it is part of it.
2357 // Skip over all non-interesting characters until we find end of buffer or a
2358 // (probably ending) '/' character.
2359 if (CurPtr + 24 < BufferEnd &&
2360 // If there is a code-completion point avoid the fast scan because it
2361 // doesn't check for '\0'.
2362 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2363 // While not aligned to a 16-byte boundary.
2364 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2367 if (C == '/') goto FoundSlash;
2370 __m128i Slashes = _mm_set1_epi8('/');
2371 while (CurPtr+16 <= BufferEnd) {
2372 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2375 // Adjust the pointer to point directly after the first slash. It's
2376 // not necessary to set C here, it will be overwritten at the end of
2378 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2384 __vector unsigned char Slashes = {
2385 '/', '/', '/', '/', '/', '/', '/', '/',
2386 '/', '/', '/', '/', '/', '/', '/', '/'
2388 while (CurPtr+16 <= BufferEnd &&
2389 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2392 // Scan for '/' quickly. Many block comments are very large.
2393 while (CurPtr[0] != '/' &&
2397 CurPtr+4 < BufferEnd) {
2402 // It has to be one of the bytes scanned, increment to it and read one.
2406 // Loop to scan the remainder.
2407 while (C != '/' && C != '\0')
2412 if (CurPtr[-2] == '*') // We found the final */. We're done!
2415 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2416 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2417 // We found the final */, though it had an escaped newline between the
2418 // * and /. We're done!
2422 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2423 // If this is a /* inside of the comment, emit a warning. Don't do this
2424 // if this is a /*/, which will end the comment. This misses cases with
2425 // embedded escaped newlines, but oh well.
2426 if (!isLexingRawMode())
2427 Diag(CurPtr-1, diag::warn_nested_block_comment);
2429 } else if (C == 0 && CurPtr == BufferEnd+1) {
2430 if (!isLexingRawMode())
2431 Diag(BufferPtr, diag::err_unterminated_block_comment);
2432 // Note: the user probably forgot a */. We could continue immediately
2433 // after the /*, but this would involve lexing a lot of what really is the
2434 // comment, which surely would confuse the parser.
2437 // KeepWhitespaceMode should return this broken comment as a token. Since
2438 // it isn't a well formed comment, just return it as an 'unknown' token.
2439 if (isKeepWhitespaceMode()) {
2440 FormTokenWithChars(Result, CurPtr, tok::unknown);
2446 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2447 PP->CodeCompleteNaturalLanguage();
2455 // Notify comment handlers about the comment unless we're in a #if 0 block.
2456 if (PP && !isLexingRawMode() &&
2457 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2458 getSourceLocation(CurPtr)))) {
2460 return true; // A token has to be returned.
2463 // If we are returning comments as tokens, return this comment as a token.
2464 if (inKeepCommentMode()) {
2465 FormTokenWithChars(Result, CurPtr, tok::comment);
2469 // It is common for the tokens immediately after a /**/ comment to be
2470 // whitespace. Instead of going through the big switch, handle it
2471 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2472 // have already returned above with the comment as a token.
2473 if (isHorizontalWhitespace(*CurPtr)) {
2474 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2478 // Otherwise, just return so that the next character will be lexed as a token.
2480 Result.setFlag(Token::LeadingSpace);
2484 //===----------------------------------------------------------------------===//
2485 // Primary Lexing Entry Points
2486 //===----------------------------------------------------------------------===//
2488 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2489 /// uninterpreted string. This switches the lexer out of directive mode.
2490 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2491 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2492 "Must be in a preprocessing directive!");
2495 // CurPtr - Cache BufferPtr in an automatic variable.
2496 const char *CurPtr = BufferPtr;
2498 char Char = getAndAdvanceChar(CurPtr, Tmp);
2502 Result->push_back(Char);
2505 // Found end of file?
2506 if (CurPtr-1 != BufferEnd) {
2507 if (isCodeCompletionPoint(CurPtr-1)) {
2508 PP->CodeCompleteNaturalLanguage();
2513 // Nope, normal character, continue.
2515 Result->push_back(Char);
2521 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2522 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2523 BufferPtr = CurPtr-1;
2525 // Next, lex the character, which should handle the EOD transition.
2527 if (Tmp.is(tok::code_completion)) {
2529 PP->CodeCompleteNaturalLanguage();
2532 assert(Tmp.is(tok::eod) && "Unexpected token!");
2534 // Finally, we're done;
2540 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2541 /// condition, reporting diagnostics and handling other edge cases as required.
2542 /// This returns true if Result contains a token, false if PP.Lex should be
2544 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2545 // If we hit the end of the file while parsing a preprocessor directive,
2546 // end the preprocessor directive first. The next token returned will
2547 // then be the end of file.
2548 if (ParsingPreprocessorDirective) {
2549 // Done parsing the "line".
2550 ParsingPreprocessorDirective = false;
2551 // Update the location of token as well as BufferPtr.
2552 FormTokenWithChars(Result, CurPtr, tok::eod);
2554 // Restore comment saving mode, in case it was disabled for directive.
2556 resetExtendedTokenMode();
2557 return true; // Have a token.
2560 // If we are in raw mode, return this event as an EOF token. Let the caller
2561 // that put us in raw mode handle the event.
2562 if (isLexingRawMode()) {
2563 Result.startToken();
2564 BufferPtr = BufferEnd;
2565 FormTokenWithChars(Result, BufferEnd, tok::eof);
2569 // Issue diagnostics for unterminated #if and missing newline.
2571 // If we are in a #if directive, emit an error.
2572 while (!ConditionalStack.empty()) {
2573 if (PP->getCodeCompletionFileLoc() != FileLoc)
2574 PP->Diag(ConditionalStack.back().IfLoc,
2575 diag::err_pp_unterminated_conditional);
2576 ConditionalStack.pop_back();
2579 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2581 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2582 DiagnosticsEngine &Diags = PP->getDiagnostics();
2583 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2586 if (LangOpts.CPlusPlus11) {
2587 // C++11 [lex.phases] 2.2 p2
2588 // Prefer the C++98 pedantic compatibility warning over the generic,
2589 // non-extension, user-requested "missing newline at EOF" warning.
2590 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2591 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2593 DiagID = diag::warn_no_newline_eof;
2596 DiagID = diag::ext_no_newline_eof;
2599 Diag(BufferEnd, DiagID)
2600 << FixItHint::CreateInsertion(EndLoc, "\n");
2605 // Finally, let the preprocessor handle this.
2606 return PP->HandleEndOfFile(Result, isPragmaLexer());
2609 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2610 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2611 /// else and 2 if there are no more tokens in the buffer controlled by the
2613 unsigned Lexer::isNextPPTokenLParen() {
2614 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2616 // Switch to 'skipping' mode. This will ensure that we can lex a token
2617 // without emitting diagnostics, disables macro expansion, and will cause EOF
2618 // to return an EOF token instead of popping the include stack.
2619 LexingRawMode = true;
2621 // Save state that can be changed while lexing so that we can restore it.
2622 const char *TmpBufferPtr = BufferPtr;
2623 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2624 bool atStartOfLine = IsAtStartOfLine;
2625 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2626 bool leadingSpace = HasLeadingSpace;
2631 // Restore state that may have changed.
2632 BufferPtr = TmpBufferPtr;
2633 ParsingPreprocessorDirective = inPPDirectiveMode;
2634 HasLeadingSpace = leadingSpace;
2635 IsAtStartOfLine = atStartOfLine;
2636 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2638 // Restore the lexer back to non-skipping mode.
2639 LexingRawMode = false;
2641 if (Tok.is(tok::eof))
2643 return Tok.is(tok::l_paren);
2646 /// \brief Find the end of a version control conflict marker.
2647 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2648 ConflictMarkerKind CMK) {
2649 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2650 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2651 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2652 size_t Pos = RestOfBuffer.find(Terminator);
2653 while (Pos != StringRef::npos) {
2654 // Must occur at start of line.
2656 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2657 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2658 Pos = RestOfBuffer.find(Terminator);
2661 return RestOfBuffer.data()+Pos;
2666 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2667 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2668 /// and recover nicely. This returns true if it is a conflict marker and false
2670 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2671 // Only a conflict marker if it starts at the beginning of a line.
2672 if (CurPtr != BufferStart &&
2673 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2676 // Check to see if we have <<<<<<< or >>>>.
2677 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2678 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2681 // If we have a situation where we don't care about conflict markers, ignore
2683 if (CurrentConflictMarkerState || isLexingRawMode())
2686 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2688 // Check to see if there is an ending marker somewhere in the buffer at the
2689 // start of a line to terminate this conflict marker.
2690 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2691 // We found a match. We are really in a conflict marker.
2692 // Diagnose this, and ignore to the end of line.
2693 Diag(CurPtr, diag::err_conflict_marker);
2694 CurrentConflictMarkerState = Kind;
2696 // Skip ahead to the end of line. We know this exists because the
2697 // end-of-conflict marker starts with \r or \n.
2698 while (*CurPtr != '\r' && *CurPtr != '\n') {
2699 assert(CurPtr != BufferEnd && "Didn't find end of line");
2706 // No end of conflict marker found.
2710 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2711 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2712 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2713 /// the line. This returns true if it is a conflict marker and false if not.
2714 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2715 // Only a conflict marker if it starts at the beginning of a line.
2716 if (CurPtr != BufferStart &&
2717 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2720 // If we have a situation where we don't care about conflict markers, ignore
2722 if (!CurrentConflictMarkerState || isLexingRawMode())
2725 // Check to see if we have the marker (4 characters in a row).
2726 for (unsigned i = 1; i != 4; ++i)
2727 if (CurPtr[i] != CurPtr[0])
2730 // If we do have it, search for the end of the conflict marker. This could
2731 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2732 // be the end of conflict marker.
2733 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2734 CurrentConflictMarkerState)) {
2737 // Skip ahead to the end of line.
2738 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2743 // No longer in the conflict marker.
2744 CurrentConflictMarkerState = CMK_None;
2751 static const char *findPlaceholderEnd(const char *CurPtr,
2752 const char *BufferEnd) {
2753 if (CurPtr == BufferEnd)
2755 BufferEnd -= 1; // Scan until the second last character.
2756 for (; CurPtr != BufferEnd; ++CurPtr) {
2757 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2763 bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2764 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2765 if (!PP || LexingRawMode)
2767 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2770 const char *Start = CurPtr - 1;
2771 if (!LangOpts.AllowEditorPlaceholders)
2772 Diag(Start, diag::err_placeholder_in_source);
2773 Result.startToken();
2774 FormTokenWithChars(Result, End, tok::raw_identifier);
2775 Result.setRawIdentifierData(Start);
2776 PP->LookUpIdentifierInfo(Result);
2777 Result.setFlag(Token::IsEditorPlaceholder);
2782 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2783 if (PP && PP->isCodeCompletionEnabled()) {
2784 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2785 return Loc == PP->getCodeCompletionLoc();
2791 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2794 char Kind = getCharAndSize(StartPtr, CharSize);
2796 unsigned NumHexDigits;
2799 else if (Kind == 'U')
2804 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2805 if (Result && !isLexingRawMode())
2806 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2810 const char *CurPtr = StartPtr + CharSize;
2811 const char *KindLoc = &CurPtr[-1];
2813 uint32_t CodePoint = 0;
2814 for (unsigned i = 0; i < NumHexDigits; ++i) {
2815 char C = getCharAndSize(CurPtr, CharSize);
2817 unsigned Value = llvm::hexDigitValue(C);
2819 if (Result && !isLexingRawMode()) {
2821 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2822 << StringRef(KindLoc, 1);
2824 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2826 // If the user wrote \U1234, suggest a fixit to \u.
2827 if (i == 4 && NumHexDigits == 8) {
2828 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2829 Diag(KindLoc, diag::note_ucn_four_not_eight)
2830 << FixItHint::CreateReplacement(URange, "u");
2845 Result->setFlag(Token::HasUCN);
2846 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2849 while (StartPtr != CurPtr)
2850 (void)getAndAdvanceChar(StartPtr, *Result);
2855 // Don't apply C family restrictions to UCNs in assembly mode
2856 if (LangOpts.AsmPreprocessor)
2859 // C99 6.4.3p2: A universal character name shall not specify a character whose
2860 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2861 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2862 // C++11 [lex.charset]p2: If the hexadecimal value for a
2863 // universal-character-name corresponds to a surrogate code point (in the
2864 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2865 // if the hexadecimal value for a universal-character-name outside the
2866 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2867 // string literal corresponds to a control character (in either of the
2868 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2869 // basic source character set, the program is ill-formed.
2870 if (CodePoint < 0xA0) {
2871 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2874 // We don't use isLexingRawMode() here because we need to warn about bad
2875 // UCNs even when skipping preprocessing tokens in a #if block.
2877 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2878 Diag(BufferPtr, diag::err_ucn_control_character);
2880 char C = static_cast<char>(CodePoint);
2881 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2887 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2888 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2889 // We don't use isLexingRawMode() here because we need to diagnose bad
2890 // UCNs even when skipping preprocessing tokens in a #if block.
2892 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2893 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2895 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2903 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2904 const char *CurPtr) {
2905 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2906 UnicodeWhitespaceCharRanges);
2907 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2908 UnicodeWhitespaceChars.contains(C)) {
2909 Diag(BufferPtr, diag::ext_unicode_whitespace)
2910 << makeCharRange(*this, BufferPtr, CurPtr);
2912 Result.setFlag(Token::LeadingSpace);
2918 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2919 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2920 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2921 !PP->isPreprocessedOutput()) {
2922 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2923 makeCharRange(*this, BufferPtr, CurPtr),
2928 return LexIdentifier(Result, CurPtr);
2931 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2932 !PP->isPreprocessedOutput() &&
2933 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2934 // Non-ASCII characters tend to creep into source code unintentionally.
2935 // Instead of letting the parser complain about the unknown token,
2936 // just drop the character.
2937 // Note that we can /only/ do this when the non-ASCII character is actually
2938 // spelled as Unicode, not written as a UCN. The standard requires that
2939 // we not throw away any possible preprocessor tokens, but there's a
2940 // loophole in the mapping of Unicode characters to basic character set
2941 // characters that allows us to map these particular characters to, say,
2943 Diag(BufferPtr, diag::err_non_ascii)
2944 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2950 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2953 FormTokenWithChars(Result, CurPtr, tok::unknown);
2957 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2958 IsAtStartOfLine = Result.isAtStartOfLine();
2959 HasLeadingSpace = Result.hasLeadingSpace();
2960 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2961 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2964 bool Lexer::Lex(Token &Result) {
2965 // Start a new token.
2966 Result.startToken();
2968 // Set up misc whitespace flags for LexTokenInternal.
2969 if (IsAtStartOfLine) {
2970 Result.setFlag(Token::StartOfLine);
2971 IsAtStartOfLine = false;
2974 if (HasLeadingSpace) {
2975 Result.setFlag(Token::LeadingSpace);
2976 HasLeadingSpace = false;
2979 if (HasLeadingEmptyMacro) {
2980 Result.setFlag(Token::LeadingEmptyMacro);
2981 HasLeadingEmptyMacro = false;
2984 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2985 IsAtPhysicalStartOfLine = false;
2986 bool isRawLex = isLexingRawMode();
2988 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2989 // (After the LexTokenInternal call, the lexer might be destroyed.)
2990 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2991 return returnedToken;
2994 /// LexTokenInternal - This implements a simple C family lexer. It is an
2995 /// extremely performance critical piece of code. This assumes that the buffer
2996 /// has a null character at the end of the file. This returns a preprocessing
2997 /// token, not a normal token, as such, it is an internal interface. It assumes
2998 /// that the Flags of result have been cleared before calling this.
2999 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
3001 // New token, can't need cleaning yet.
3002 Result.clearFlag(Token::NeedsCleaning);
3003 Result.setIdentifierInfo(nullptr);
3005 // CurPtr - Cache BufferPtr in an automatic variable.
3006 const char *CurPtr = BufferPtr;
3008 // Small amounts of horizontal whitespace is very common between tokens.
3009 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3011 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3014 // If we are keeping whitespace and other tokens, just return what we just
3015 // skipped. The next lexer invocation will return the token after the
3017 if (isKeepWhitespaceMode()) {
3018 FormTokenWithChars(Result, CurPtr, tok::unknown);
3019 // FIXME: The next token will not have LeadingSpace set.
3024 Result.setFlag(Token::LeadingSpace);
3027 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
3029 // Read a character, advancing over it.
3030 char Char = getAndAdvanceChar(CurPtr, Result);
3031 tok::TokenKind Kind;
3035 // Found end of file?
3036 if (CurPtr-1 == BufferEnd)
3037 return LexEndOfFile(Result, CurPtr-1);
3039 // Check if we are performing code completion.
3040 if (isCodeCompletionPoint(CurPtr-1)) {
3041 // Return the code-completion token.
3042 Result.startToken();
3043 FormTokenWithChars(Result, CurPtr, tok::code_completion);
3047 if (!isLexingRawMode())
3048 Diag(CurPtr-1, diag::null_in_file);
3049 Result.setFlag(Token::LeadingSpace);
3050 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3051 return true; // KeepWhitespaceMode
3053 // We know the lexer hasn't changed, so just try again with this lexer.
3054 // (We manually eliminate the tail call to avoid recursion.)
3057 case 26: // DOS & CP/M EOF: "^Z".
3058 // If we're in Microsoft extensions mode, treat this as end of file.
3059 if (LangOpts.MicrosoftExt) {
3060 if (!isLexingRawMode())
3061 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3062 return LexEndOfFile(Result, CurPtr-1);
3065 // If Microsoft extensions are disabled, this is just random garbage.
3066 Kind = tok::unknown;
3071 // If we are inside a preprocessor directive and we see the end of line,
3072 // we know we are done with the directive, so return an EOD token.
3073 if (ParsingPreprocessorDirective) {
3074 // Done parsing the "line".
3075 ParsingPreprocessorDirective = false;
3077 // Restore comment saving mode, in case it was disabled for directive.
3079 resetExtendedTokenMode();
3081 // Since we consumed a newline, we are back at the start of a line.
3082 IsAtStartOfLine = true;
3083 IsAtPhysicalStartOfLine = true;
3089 // No leading whitespace seen so far.
3090 Result.clearFlag(Token::LeadingSpace);
3092 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3093 return true; // KeepWhitespaceMode
3095 // We only saw whitespace, so just try again with this lexer.
3096 // (We manually eliminate the tail call to avoid recursion.)
3102 SkipHorizontalWhitespace:
3103 Result.setFlag(Token::LeadingSpace);
3104 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3105 return true; // KeepWhitespaceMode
3110 // If the next token is obviously a // or /* */ comment, skip it efficiently
3111 // too (without going through the big switch stmt).
3112 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3113 LangOpts.LineComment &&
3114 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3115 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3116 return true; // There is a token to return.
3117 goto SkipIgnoredUnits;
3118 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3119 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3120 return true; // There is a token to return.
3121 goto SkipIgnoredUnits;
3122 } else if (isHorizontalWhitespace(*CurPtr)) {
3123 goto SkipHorizontalWhitespace;
3125 // We only saw whitespace, so just try again with this lexer.
3126 // (We manually eliminate the tail call to avoid recursion.)
3129 // C99 6.4.4.1: Integer Constants.
3130 // C99 6.4.4.2: Floating Constants.
3131 case '0': case '1': case '2': case '3': case '4':
3132 case '5': case '6': case '7': case '8': case '9':
3133 // Notify MIOpt that we read a non-whitespace/non-comment token.
3135 return LexNumericConstant(Result, CurPtr);
3137 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3138 // Notify MIOpt that we read a non-whitespace/non-comment token.
3141 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3142 Char = getCharAndSize(CurPtr, SizeTmp);
3144 // UTF-16 string literal
3146 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3147 tok::utf16_string_literal);
3149 // UTF-16 character constant
3151 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3152 tok::utf16_char_constant);
3154 // UTF-16 raw string literal
3155 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3156 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3157 return LexRawStringLiteral(Result,
3158 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3160 tok::utf16_string_literal);
3163 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3165 // UTF-8 string literal
3167 return LexStringLiteral(Result,
3168 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3170 tok::utf8_string_literal);
3171 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3172 return LexCharConstant(
3173 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3175 tok::utf8_char_constant);
3177 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3179 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3180 // UTF-8 raw string literal
3182 return LexRawStringLiteral(Result,
3183 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3186 tok::utf8_string_literal);
3192 // treat u like the start of an identifier.
3193 return LexIdentifier(Result, CurPtr);
3195 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3196 // Notify MIOpt that we read a non-whitespace/non-comment token.
3199 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3200 Char = getCharAndSize(CurPtr, SizeTmp);
3202 // UTF-32 string literal
3204 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3205 tok::utf32_string_literal);
3207 // UTF-32 character constant
3209 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3210 tok::utf32_char_constant);
3212 // UTF-32 raw string literal
3213 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3214 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3215 return LexRawStringLiteral(Result,
3216 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3218 tok::utf32_string_literal);
3221 // treat U like the start of an identifier.
3222 return LexIdentifier(Result, CurPtr);
3224 case 'R': // Identifier or C++0x raw string literal
3225 // Notify MIOpt that we read a non-whitespace/non-comment token.
3228 if (LangOpts.CPlusPlus11) {
3229 Char = getCharAndSize(CurPtr, SizeTmp);
3232 return LexRawStringLiteral(Result,
3233 ConsumeChar(CurPtr, SizeTmp, Result),
3234 tok::string_literal);
3237 // treat R like the start of an identifier.
3238 return LexIdentifier(Result, CurPtr);
3240 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3241 // Notify MIOpt that we read a non-whitespace/non-comment token.
3243 Char = getCharAndSize(CurPtr, SizeTmp);
3245 // Wide string literal.
3247 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3248 tok::wide_string_literal);
3250 // Wide raw string literal.
3251 if (LangOpts.CPlusPlus11 && Char == 'R' &&
3252 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3253 return LexRawStringLiteral(Result,
3254 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3256 tok::wide_string_literal);
3258 // Wide character constant.
3260 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3261 tok::wide_char_constant);
3262 // FALL THROUGH, treating L like the start of an identifier.
3264 // C99 6.4.2: Identifiers.
3265 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3266 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3267 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3268 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3269 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3270 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3271 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3272 case 'v': case 'w': case 'x': case 'y': case 'z':
3274 // Notify MIOpt that we read a non-whitespace/non-comment token.
3276 return LexIdentifier(Result, CurPtr);
3278 case '$': // $ in identifiers.
3279 if (LangOpts.DollarIdents) {
3280 if (!isLexingRawMode())
3281 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3282 // Notify MIOpt that we read a non-whitespace/non-comment token.
3284 return LexIdentifier(Result, CurPtr);
3287 Kind = tok::unknown;
3290 // C99 6.4.4: Character Constants.
3292 // Notify MIOpt that we read a non-whitespace/non-comment token.
3294 return LexCharConstant(Result, CurPtr, tok::char_constant);
3296 // C99 6.4.5: String Literals.
3298 // Notify MIOpt that we read a non-whitespace/non-comment token.
3300 return LexStringLiteral(Result, CurPtr, tok::string_literal);
3302 // C99 6.4.6: Punctuators.
3304 Kind = tok::question;
3307 Kind = tok::l_square;
3310 Kind = tok::r_square;
3313 Kind = tok::l_paren;
3316 Kind = tok::r_paren;
3319 Kind = tok::l_brace;
3322 Kind = tok::r_brace;
3325 Char = getCharAndSize(CurPtr, SizeTmp);
3326 if (Char >= '0' && Char <= '9') {
3327 // Notify MIOpt that we read a non-whitespace/non-comment token.
3330 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3331 } else if (LangOpts.CPlusPlus && Char == '*') {
3332 Kind = tok::periodstar;
3334 } else if (Char == '.' &&
3335 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3336 Kind = tok::ellipsis;
3337 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3344 Char = getCharAndSize(CurPtr, SizeTmp);
3347 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3348 } else if (Char == '=') {
3349 Kind = tok::ampequal;
3350 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3356 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3357 Kind = tok::starequal;
3358 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3364 Char = getCharAndSize(CurPtr, SizeTmp);
3366 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3367 Kind = tok::plusplus;
3368 } else if (Char == '=') {
3369 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3370 Kind = tok::plusequal;
3376 Char = getCharAndSize(CurPtr, SizeTmp);
3377 if (Char == '-') { // --
3378 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3379 Kind = tok::minusminus;
3380 } else if (Char == '>' && LangOpts.CPlusPlus &&
3381 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3382 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3384 Kind = tok::arrowstar;
3385 } else if (Char == '>') { // ->
3386 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3388 } else if (Char == '=') { // -=
3389 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3390 Kind = tok::minusequal;
3399 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3400 Kind = tok::exclaimequal;
3401 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3403 Kind = tok::exclaim;
3408 Char = getCharAndSize(CurPtr, SizeTmp);
3409 if (Char == '/') { // Line comment.
3410 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3411 // want to lex this as a comment. There is one problem with this though,
3412 // that in one particular corner case, this can change the behavior of the
3413 // resultant program. For example, In "foo //**/ bar", C89 would lex
3414 // this as "foo / bar" and langauges with Line comments would lex it as
3415 // "foo". Check to see if the character after the second slash is a '*'.
3416 // If so, we will lex that as a "/" instead of the start of a comment.
3417 // However, we never do this if we are just preprocessing.
3418 bool TreatAsComment = LangOpts.LineComment &&
3419 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3420 if (!TreatAsComment)
3421 if (!(PP && PP->isPreprocessedOutput()))
3422 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3424 if (TreatAsComment) {
3425 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3426 TokAtPhysicalStartOfLine))
3427 return true; // There is a token to return.
3429 // It is common for the tokens immediately after a // comment to be
3430 // whitespace (indentation for the next line). Instead of going through
3431 // the big switch, handle it efficiently now.
3432 goto SkipIgnoredUnits;
3436 if (Char == '*') { // /**/ comment.
3437 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3438 TokAtPhysicalStartOfLine))
3439 return true; // There is a token to return.
3441 // We only saw whitespace, so just try again with this lexer.
3442 // (We manually eliminate the tail call to avoid recursion.)
3447 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3448 Kind = tok::slashequal;
3454 Char = getCharAndSize(CurPtr, SizeTmp);
3456 Kind = tok::percentequal;
3457 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3458 } else if (LangOpts.Digraphs && Char == '>') {
3459 Kind = tok::r_brace; // '%>' -> '}'
3460 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3461 } else if (LangOpts.Digraphs && Char == ':') {
3462 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3463 Char = getCharAndSize(CurPtr, SizeTmp);
3464 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3465 Kind = tok::hashhash; // '%:%:' -> '##'
3466 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3468 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3469 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3470 if (!isLexingRawMode())
3471 Diag(BufferPtr, diag::ext_charize_microsoft);
3473 } else { // '%:' -> '#'
3474 // We parsed a # character. If this occurs at the start of the line,
3475 // it's actually the start of a preprocessing directive. Callback to
3476 // the preprocessor to handle it.
3477 // TODO: -fpreprocessed mode??
3478 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3479 goto HandleDirective;
3484 Kind = tok::percent;
3488 Char = getCharAndSize(CurPtr, SizeTmp);
3489 if (ParsingFilename) {
3490 return LexAngledStringLiteral(Result, CurPtr);
3491 } else if (Char == '<') {
3492 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3494 Kind = tok::lesslessequal;
3495 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3497 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3498 // If this is actually a '<<<<<<<' version control conflict marker,
3499 // recognize it as such and recover nicely.
3501 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3502 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3505 } else if (LangOpts.CUDA && After == '<') {
3506 Kind = tok::lesslessless;
3507 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3510 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3511 Kind = tok::lessless;
3513 } else if (Char == '=') {
3514 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3515 Kind = tok::lessequal;
3516 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3517 if (LangOpts.CPlusPlus11 &&
3518 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3519 // C++0x [lex.pptoken]p3:
3520 // Otherwise, if the next three characters are <:: and the subsequent
3521 // character is neither : nor >, the < is treated as a preprocessor
3522 // token by itself and not as the first character of the alternative
3525 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3526 if (After != ':' && After != '>') {
3528 if (!isLexingRawMode())
3529 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3534 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3535 Kind = tok::l_square;
3536 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3537 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3538 Kind = tok::l_brace;
3539 } else if (Char == '#' && lexEditorPlaceholder(Result, CurPtr)) {
3546 Char = getCharAndSize(CurPtr, SizeTmp);
3548 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3549 Kind = tok::greaterequal;
3550 } else if (Char == '>') {
3551 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3553 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3555 Kind = tok::greatergreaterequal;
3556 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3557 // If this is actually a '>>>>' conflict marker, recognize it as such
3558 // and recover nicely.
3560 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3561 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3563 } else if (LangOpts.CUDA && After == '>') {
3564 Kind = tok::greatergreatergreater;
3565 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3568 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3569 Kind = tok::greatergreater;
3572 Kind = tok::greater;
3576 Char = getCharAndSize(CurPtr, SizeTmp);
3578 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3579 Kind = tok::caretequal;
3580 } else if (LangOpts.OpenCL && Char == '^') {
3581 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3582 Kind = tok::caretcaret;
3588 Char = getCharAndSize(CurPtr, SizeTmp);
3590 Kind = tok::pipeequal;
3591 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3592 } else if (Char == '|') {
3593 // If this is '|||||||' and we're in a conflict marker, ignore it.
3594 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3596 Kind = tok::pipepipe;
3597 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3603 Char = getCharAndSize(CurPtr, SizeTmp);
3604 if (LangOpts.Digraphs && Char == '>') {
3605 Kind = tok::r_square; // ':>' -> ']'
3606 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3607 } else if (LangOpts.CPlusPlus && Char == ':') {
3608 Kind = tok::coloncolon;
3609 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3618 Char = getCharAndSize(CurPtr, SizeTmp);
3620 // If this is '====' and we're in a conflict marker, ignore it.
3621 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3624 Kind = tok::equalequal;
3625 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3634 Char = getCharAndSize(CurPtr, SizeTmp);
3636 Kind = tok::hashhash;
3637 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3638 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3640 if (!isLexingRawMode())
3641 Diag(BufferPtr, diag::ext_charize_microsoft);
3642 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3644 // We parsed a # character. If this occurs at the start of the line,
3645 // it's actually the start of a preprocessing directive. Callback to
3646 // the preprocessor to handle it.
3647 // TODO: -fpreprocessed mode??
3648 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3649 goto HandleDirective;
3656 // Objective C support.
3657 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3660 Kind = tok::unknown;
3663 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3665 if (!LangOpts.AsmPreprocessor) {
3666 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3667 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3668 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3669 return true; // KeepWhitespaceMode
3671 // We only saw whitespace, so just try again with this lexer.
3672 // (We manually eliminate the tail call to avoid recursion.)
3676 return LexUnicode(Result, CodePoint, CurPtr);
3680 Kind = tok::unknown;
3684 if (isASCII(Char)) {
3685 Kind = tok::unknown;
3689 llvm::UTF32 CodePoint;
3691 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3692 // an escaped newline.
3694 llvm::ConversionResult Status =
3695 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3696 (const llvm::UTF8 *)BufferEnd,
3698 llvm::strictConversion);
3699 if (Status == llvm::conversionOK) {
3700 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3701 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3702 return true; // KeepWhitespaceMode
3704 // We only saw whitespace, so just try again with this lexer.
3705 // (We manually eliminate the tail call to avoid recursion.)
3708 return LexUnicode(Result, CodePoint, CurPtr);
3711 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3712 PP->isPreprocessedOutput()) {
3714 Kind = tok::unknown;
3718 // Non-ASCII characters tend to creep into source code unintentionally.
3719 // Instead of letting the parser complain about the unknown token,
3720 // just diagnose the invalid UTF-8, then drop the character.
3721 Diag(CurPtr, diag::err_invalid_utf8);
3723 BufferPtr = CurPtr+1;
3724 // We're pretending the character didn't exist, so just try again with
3726 // (We manually eliminate the tail call to avoid recursion.)
3731 // Notify MIOpt that we read a non-whitespace/non-comment token.
3734 // Update the location of token as well as BufferPtr.
3735 FormTokenWithChars(Result, CurPtr, Kind);
3739 // We parsed a # character and it's the start of a preprocessing directive.
3741 FormTokenWithChars(Result, CurPtr, tok::hash);
3742 PP->HandleDirective(Result);
3744 if (PP->hadModuleLoaderFatalFailure()) {
3745 // With a fatal failure in the module loader, we abort parsing.
3746 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3750 // We parsed the directive; lex a token with the new state.