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 "clang/Lex/PreprocessorOptions.h"
23 #include "llvm/ADT/StringExtras.h"
24 #include "llvm/ADT/StringSwitch.h"
25 #include "llvm/Support/Compiler.h"
26 #include "llvm/Support/ConvertUTF.h"
27 #include "llvm/Support/MathExtras.h"
28 #include "llvm/Support/MemoryBuffer.h"
29 #include "llvm/Support/UnicodeCharRanges.h"
39 using namespace clang;
41 //===----------------------------------------------------------------------===//
42 // Token Class Implementation
43 //===----------------------------------------------------------------------===//
45 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
46 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
49 if (IdentifierInfo *II = getIdentifierInfo())
50 return II->getObjCKeywordID() == objcKey;
54 /// getObjCKeywordID - Return the ObjC keyword kind.
55 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
57 return tok::objc_not_keyword;
58 IdentifierInfo *specId = getIdentifierInfo();
59 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
62 //===----------------------------------------------------------------------===//
63 // Lexer Class Implementation
64 //===----------------------------------------------------------------------===//
66 void Lexer::anchor() { }
68 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
70 BufferStart = BufStart;
74 assert(BufEnd[0] == 0 &&
75 "We assume that the input buffer has a null character at the end"
76 " to simplify lexing!");
78 // Check whether we have a BOM in the beginning of the buffer. If yes - act
79 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
80 // skip the UTF-8 BOM if it's present.
81 if (BufferStart == BufferPtr) {
82 // Determine the size of the BOM.
83 StringRef Buf(BufferStart, BufferEnd - BufferStart);
84 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
85 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
89 BufferPtr += BOMLength;
92 Is_PragmaLexer = false;
93 CurrentConflictMarkerState = CMK_None;
95 // Start of the file is a start of line.
96 IsAtStartOfLine = true;
97 IsAtPhysicalStartOfLine = true;
99 HasLeadingSpace = false;
100 HasLeadingEmptyMacro = false;
102 // We are not after parsing a #.
103 ParsingPreprocessorDirective = false;
105 // We are not after parsing #include.
106 ParsingFilename = false;
108 // We are not in raw mode. Raw mode disables diagnostics and interpretation
109 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
110 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
111 // or otherwise skipping over tokens.
112 LexingRawMode = false;
114 // Default to not keeping comments.
115 ExtendedTokenMode = 0;
118 /// Lexer constructor - Create a new lexer object for the specified buffer
119 /// with the specified preprocessor managing the lexing process. This lexer
120 /// assumes that the associated file buffer and Preprocessor objects will
121 /// outlive it, so it doesn't take ownership of either of them.
122 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
123 : PreprocessorLexer(&PP, FID),
124 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
125 LangOpts(PP.getLangOpts()) {
127 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
128 InputFile->getBufferEnd());
130 resetExtendedTokenMode();
133 void Lexer::resetExtendedTokenMode() {
134 assert(PP && "Cannot reset token mode without a preprocessor");
135 if (LangOpts.TraditionalCPP)
136 SetKeepWhitespaceMode(true);
138 SetCommentRetentionState(PP->getCommentRetentionState());
141 /// Lexer constructor - Create a new raw lexer object. This object is only
142 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
143 /// range will outlive it, so it doesn't take ownership of it.
144 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
145 const char *BufStart, const char *BufPtr, const char *BufEnd)
146 : FileLoc(fileloc), LangOpts(langOpts) {
148 InitLexer(BufStart, BufPtr, BufEnd);
150 // We *are* in raw mode.
151 LexingRawMode = true;
154 /// Lexer constructor - Create a new raw lexer object. This object is only
155 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
156 /// range will outlive it, so it doesn't take ownership of it.
157 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile,
158 const SourceManager &SM, const LangOptions &langOpts)
159 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
160 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
162 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
163 /// _Pragma expansion. This has a variety of magic semantics that this method
164 /// sets up. It returns a new'd Lexer that must be delete'd when done.
166 /// On entrance to this routine, TokStartLoc is a macro location which has a
167 /// spelling loc that indicates the bytes to be lexed for the token and an
168 /// expansion location that indicates where all lexed tokens should be
171 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
172 /// normal lexer that remaps tokens as they fly by. This would require making
173 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
174 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
175 /// out of the critical path of the lexer!
177 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
178 SourceLocation ExpansionLocStart,
179 SourceLocation ExpansionLocEnd,
180 unsigned TokLen, Preprocessor &PP) {
181 SourceManager &SM = PP.getSourceManager();
183 // Create the lexer as if we were going to lex the file normally.
184 FileID SpellingFID = SM.getFileID(SpellingLoc);
185 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
186 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
188 // Now that the lexer is created, change the start/end locations so that we
189 // just lex the subsection of the file that we want. This is lexing from a
191 const char *StrData = SM.getCharacterData(SpellingLoc);
193 L->BufferPtr = StrData;
194 L->BufferEnd = StrData+TokLen;
195 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
197 // Set the SourceLocation with the remapping information. This ensures that
198 // GetMappedTokenLoc will remap the tokens as they are lexed.
199 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
201 ExpansionLocEnd, TokLen);
203 // Ensure that the lexer thinks it is inside a directive, so that end \n will
204 // return an EOD token.
205 L->ParsingPreprocessorDirective = true;
207 // This lexer really is for _Pragma.
208 L->Is_PragmaLexer = true;
212 /// Stringify - Convert the specified string into a C string, with surrounding
213 /// ""'s, and with escaped \ and " characters.
214 std::string Lexer::Stringify(StringRef Str, bool Charify) {
215 std::string Result = Str;
216 char Quote = Charify ? '\'' : '"';
217 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
218 if (Result[i] == '\\' || Result[i] == Quote) {
219 Result.insert(Result.begin()+i, '\\');
226 /// Stringify - Convert the specified string into a C string by escaping '\'
227 /// and " characters. This does not add surrounding ""'s to the string.
228 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
229 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
230 if (Str[i] == '\\' || Str[i] == '"') {
231 Str.insert(Str.begin()+i, '\\');
237 //===----------------------------------------------------------------------===//
239 //===----------------------------------------------------------------------===//
241 /// \brief Slow case of getSpelling. Extract the characters comprising the
242 /// spelling of this token from the provided input buffer.
243 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
244 const LangOptions &LangOpts, char *Spelling) {
245 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
248 const char *BufEnd = BufPtr + Tok.getLength();
250 if (tok::isStringLiteral(Tok.getKind())) {
251 // Munch the encoding-prefix and opening double-quote.
252 while (BufPtr < BufEnd) {
254 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
257 if (Spelling[Length - 1] == '"')
261 // Raw string literals need special handling; trigraph expansion and line
262 // splicing do not occur within their d-char-sequence nor within their
265 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
266 // Search backwards from the end of the token to find the matching closing
268 const char *RawEnd = BufEnd;
269 do --RawEnd; while (*RawEnd != '"');
270 size_t RawLength = RawEnd - BufPtr + 1;
272 // Everything between the quotes is included verbatim in the spelling.
273 memcpy(Spelling + Length, BufPtr, RawLength);
277 // The rest of the token is lexed normally.
281 while (BufPtr < BufEnd) {
283 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
287 assert(Length < Tok.getLength() &&
288 "NeedsCleaning flag set on token that didn't need cleaning!");
292 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
293 /// token are the characters used to represent the token in the source file
294 /// after trigraph expansion and escaped-newline folding. In particular, this
295 /// wants to get the true, uncanonicalized, spelling of things like digraphs
297 StringRef Lexer::getSpelling(SourceLocation loc,
298 SmallVectorImpl<char> &buffer,
299 const SourceManager &SM,
300 const LangOptions &options,
302 // Break down the source location.
303 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
305 // Try to the load the file buffer.
306 bool invalidTemp = false;
307 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
309 if (invalid) *invalid = true;
313 const char *tokenBegin = file.data() + locInfo.second;
315 // Lex from the start of the given location.
316 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
317 file.begin(), tokenBegin, file.end());
319 lexer.LexFromRawLexer(token);
321 unsigned length = token.getLength();
323 // Common case: no need for cleaning.
324 if (!token.needsCleaning())
325 return StringRef(tokenBegin, length);
327 // Hard case, we need to relex the characters into the string.
328 buffer.resize(length);
329 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
330 return StringRef(buffer.data(), buffer.size());
333 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
334 /// token are the characters used to represent the token in the source file
335 /// after trigraph expansion and escaped-newline folding. In particular, this
336 /// wants to get the true, uncanonicalized, spelling of things like digraphs
338 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
339 const LangOptions &LangOpts, bool *Invalid) {
340 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
342 bool CharDataInvalid = false;
343 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
346 *Invalid = CharDataInvalid;
348 return std::string();
350 // If this token contains nothing interesting, return it directly.
351 if (!Tok.needsCleaning())
352 return std::string(TokStart, TokStart + Tok.getLength());
355 Result.resize(Tok.getLength());
356 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
360 /// getSpelling - This method is used to get the spelling of a token into a
361 /// preallocated buffer, instead of as an std::string. The caller is required
362 /// to allocate enough space for the token, which is guaranteed to be at least
363 /// Tok.getLength() bytes long. The actual length of the token is returned.
365 /// Note that this method may do two possible things: it may either fill in
366 /// the buffer specified with characters, or it may *change the input pointer*
367 /// to point to a constant buffer with the data already in it (avoiding a
368 /// copy). The caller is not allowed to modify the returned buffer pointer
369 /// if an internal buffer is returned.
370 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
371 const SourceManager &SourceMgr,
372 const LangOptions &LangOpts, bool *Invalid) {
373 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
375 const char *TokStart = nullptr;
376 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
377 if (Tok.is(tok::raw_identifier))
378 TokStart = Tok.getRawIdentifier().data();
379 else if (!Tok.hasUCN()) {
380 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
381 // Just return the string from the identifier table, which is very quick.
382 Buffer = II->getNameStart();
383 return II->getLength();
387 // NOTE: this can be checked even after testing for an IdentifierInfo.
389 TokStart = Tok.getLiteralData();
392 // Compute the start of the token in the input lexer buffer.
393 bool CharDataInvalid = false;
394 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
396 *Invalid = CharDataInvalid;
397 if (CharDataInvalid) {
403 // If this token contains nothing interesting, return it directly.
404 if (!Tok.needsCleaning()) {
406 return Tok.getLength();
409 // Otherwise, hard case, relex the characters into the string.
410 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
413 /// MeasureTokenLength - Relex the token at the specified location and return
414 /// its length in bytes in the input file. If the token needs cleaning (e.g.
415 /// includes a trigraph or an escaped newline) then this count includes bytes
416 /// that are part of that.
417 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
418 const SourceManager &SM,
419 const LangOptions &LangOpts) {
421 if (getRawToken(Loc, TheTok, SM, LangOpts))
423 return TheTok.getLength();
426 /// \brief Relex the token at the specified location.
427 /// \returns true if there was a failure, false on success.
428 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
429 const SourceManager &SM,
430 const LangOptions &LangOpts,
431 bool IgnoreWhiteSpace) {
432 // TODO: this could be special cased for common tokens like identifiers, ')',
433 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
434 // all obviously single-char tokens. This could use
435 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
438 // If this comes from a macro expansion, we really do want the macro name, not
439 // the token this macro expanded to.
440 Loc = SM.getExpansionLoc(Loc);
441 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
442 bool Invalid = false;
443 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
447 const char *StrData = Buffer.data()+LocInfo.second;
449 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
452 // Create a lexer starting at the beginning of this token.
453 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
454 Buffer.begin(), StrData, Buffer.end());
455 TheLexer.SetCommentRetentionState(true);
456 TheLexer.LexFromRawLexer(Result);
460 /// Returns the pointer that points to the beginning of line that contains
461 /// the given offset, or null if the offset if invalid.
462 static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
463 const char *BufStart = Buffer.data();
464 if (Offset >= Buffer.size())
466 const char *StrData = BufStart + Offset;
468 if (StrData[0] == '\n' || StrData[0] == '\r')
471 const char *LexStart = StrData;
472 while (LexStart != BufStart) {
473 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
483 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
484 const SourceManager &SM,
485 const LangOptions &LangOpts) {
486 assert(Loc.isFileID());
487 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
488 if (LocInfo.first.isInvalid())
491 bool Invalid = false;
492 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
496 // Back up from the current location until we hit the beginning of a line
497 // (or the buffer). We'll relex from that point.
498 const char *StrData = Buffer.data() + LocInfo.second;
499 const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
500 if (!LexStart || LexStart == StrData)
503 // Create a lexer starting at the beginning of this token.
504 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
505 Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
507 TheLexer.SetCommentRetentionState(true);
509 // Lex tokens until we find the token that contains the source location.
512 TheLexer.LexFromRawLexer(TheTok);
514 if (TheLexer.getBufferLocation() > StrData) {
515 // Lexing this token has taken the lexer past the source location we're
516 // looking for. If the current token encompasses our source location,
517 // return the beginning of that token.
518 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
519 return TheTok.getLocation();
521 // We ended up skipping over the source location entirely, which means
522 // that it points into whitespace. We're done here.
525 } while (TheTok.getKind() != tok::eof);
527 // We've passed our source location; just return the original source location.
531 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
532 const SourceManager &SM,
533 const LangOptions &LangOpts) {
535 return getBeginningOfFileToken(Loc, SM, LangOpts);
537 if (!SM.isMacroArgExpansion(Loc))
540 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
541 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
542 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
543 std::pair<FileID, unsigned> BeginFileLocInfo
544 = SM.getDecomposedLoc(BeginFileLoc);
545 assert(FileLocInfo.first == BeginFileLocInfo.first &&
546 FileLocInfo.second >= BeginFileLocInfo.second);
547 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
552 enum PreambleDirectiveKind {
557 } // end anonymous namespace
559 std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
560 const LangOptions &LangOpts,
562 // Create a lexer starting at the beginning of the file. Note that we use a
563 // "fake" file source location at offset 1 so that the lexer will track our
564 // position within the file.
565 const unsigned StartOffset = 1;
566 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
567 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
569 TheLexer.SetCommentRetentionState(true);
571 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
572 SourceLocation StartLoc = TheLexer.getSourceLocation();
574 bool InPreprocessorDirective = false;
576 SourceLocation ActiveCommentLoc;
578 unsigned MaxLineOffset = 0;
580 const char *CurPtr = Buffer.begin();
581 unsigned CurLine = 0;
582 while (CurPtr != Buffer.end()) {
586 if (CurLine == MaxLines)
590 if (CurPtr != Buffer.end())
591 MaxLineOffset = CurPtr - Buffer.begin();
595 TheLexer.LexFromRawLexer(TheTok);
597 if (InPreprocessorDirective) {
598 // If we've hit the end of the file, we're done.
599 if (TheTok.getKind() == tok::eof) {
603 // If we haven't hit the end of the preprocessor directive, skip this
605 if (!TheTok.isAtStartOfLine())
608 // We've passed the end of the preprocessor directive, and will look
609 // at this token again below.
610 InPreprocessorDirective = false;
613 // Keep track of the # of lines in the preamble.
614 if (TheTok.isAtStartOfLine()) {
615 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
617 // If we were asked to limit the number of lines in the preamble,
618 // and we're about to exceed that limit, we're done.
619 if (MaxLineOffset && TokOffset >= MaxLineOffset)
623 // Comments are okay; skip over them.
624 if (TheTok.getKind() == tok::comment) {
625 if (ActiveCommentLoc.isInvalid())
626 ActiveCommentLoc = TheTok.getLocation();
630 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
631 // This is the start of a preprocessor directive.
632 Token HashTok = TheTok;
633 InPreprocessorDirective = true;
634 ActiveCommentLoc = SourceLocation();
636 // Figure out which directive this is. Since we're lexing raw tokens,
637 // we don't have an identifier table available. Instead, just look at
638 // the raw identifier to recognize and categorize preprocessor directives.
639 TheLexer.LexFromRawLexer(TheTok);
640 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
641 StringRef Keyword = TheTok.getRawIdentifier();
642 PreambleDirectiveKind PDK
643 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
644 .Case("include", PDK_Skipped)
645 .Case("__include_macros", PDK_Skipped)
646 .Case("define", PDK_Skipped)
647 .Case("undef", PDK_Skipped)
648 .Case("line", PDK_Skipped)
649 .Case("error", PDK_Skipped)
650 .Case("pragma", PDK_Skipped)
651 .Case("import", PDK_Skipped)
652 .Case("include_next", PDK_Skipped)
653 .Case("warning", PDK_Skipped)
654 .Case("ident", PDK_Skipped)
655 .Case("sccs", PDK_Skipped)
656 .Case("assert", PDK_Skipped)
657 .Case("unassert", PDK_Skipped)
658 .Case("if", PDK_Skipped)
659 .Case("ifdef", PDK_Skipped)
660 .Case("ifndef", PDK_Skipped)
661 .Case("elif", PDK_Skipped)
662 .Case("else", PDK_Skipped)
663 .Case("endif", PDK_Skipped)
664 .Default(PDK_Unknown);
671 // We don't know what this directive is; stop at the '#'.
676 // We only end up here if we didn't recognize the preprocessor
677 // directive or it was one that can't occur in the preamble at this
678 // point. Roll back the current token to the location of the '#'.
679 InPreprocessorDirective = false;
683 // We hit a token that we don't recognize as being in the
684 // "preprocessing only" part of the file, so we're no longer in
690 if (ActiveCommentLoc.isValid())
691 End = ActiveCommentLoc; // don't truncate a decl comment.
693 End = TheTok.getLocation();
695 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
696 TheTok.isAtStartOfLine());
699 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
700 /// token, return a new location that specifies a character within the token.
701 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
703 const SourceManager &SM,
704 const LangOptions &LangOpts) {
705 // Figure out how many physical characters away the specified expansion
706 // character is. This needs to take into consideration newlines and
708 bool Invalid = false;
709 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
711 // If they request the first char of the token, we're trivially done.
712 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
715 unsigned PhysOffset = 0;
717 // The usual case is that tokens don't contain anything interesting. Skip
718 // over the uninteresting characters. If a token only consists of simple
719 // chars, this method is extremely fast.
720 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
722 return TokStart.getLocWithOffset(PhysOffset);
728 // If we have a character that may be a trigraph or escaped newline, use a
729 // lexer to parse it correctly.
730 for (; CharNo; --CharNo) {
732 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
737 // Final detail: if we end up on an escaped newline, we want to return the
738 // location of the actual byte of the token. For example foo\<newline>bar
739 // advanced by 3 should return the location of b, not of \\. One compounding
740 // detail of this is that the escape may be made by a trigraph.
741 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
742 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
744 return TokStart.getLocWithOffset(PhysOffset);
747 /// \brief Computes the source location just past the end of the
748 /// token at this source location.
750 /// This routine can be used to produce a source location that
751 /// points just past the end of the token referenced by \p Loc, and
752 /// is generally used when a diagnostic needs to point just after a
753 /// token where it expected something different that it received. If
754 /// the returned source location would not be meaningful (e.g., if
755 /// it points into a macro), this routine returns an invalid
758 /// \param Offset an offset from the end of the token, where the source
759 /// location should refer to. The default offset (0) produces a source
760 /// location pointing just past the end of the token; an offset of 1 produces
761 /// a source location pointing to the last character in the token, etc.
762 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
763 const SourceManager &SM,
764 const LangOptions &LangOpts) {
766 return SourceLocation();
768 if (Loc.isMacroID()) {
769 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
770 return SourceLocation(); // Points inside the macro expansion.
773 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
779 return Loc.getLocWithOffset(Len);
782 /// \brief Returns true if the given MacroID location points at the first
783 /// token of the macro expansion.
784 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
785 const SourceManager &SM,
786 const LangOptions &LangOpts,
787 SourceLocation *MacroBegin) {
788 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
790 SourceLocation expansionLoc;
791 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
794 if (expansionLoc.isFileID()) {
795 // No other macro expansions, this is the first.
797 *MacroBegin = expansionLoc;
801 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
804 /// \brief Returns true if the given MacroID location points at the last
805 /// token of the macro expansion.
806 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
807 const SourceManager &SM,
808 const LangOptions &LangOpts,
809 SourceLocation *MacroEnd) {
810 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
812 SourceLocation spellLoc = SM.getSpellingLoc(loc);
813 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
817 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
818 SourceLocation expansionLoc;
819 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
822 if (expansionLoc.isFileID()) {
823 // No other macro expansions.
825 *MacroEnd = expansionLoc;
829 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
832 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
833 const SourceManager &SM,
834 const LangOptions &LangOpts) {
835 SourceLocation Begin = Range.getBegin();
836 SourceLocation End = Range.getEnd();
837 assert(Begin.isFileID() && End.isFileID());
838 if (Range.isTokenRange()) {
839 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
841 return CharSourceRange();
844 // Break down the source locations.
847 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
849 return CharSourceRange();
852 if (!SM.isInFileID(End, FID, &EndOffs) ||
854 return CharSourceRange();
856 return CharSourceRange::getCharRange(Begin, End);
859 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
860 const SourceManager &SM,
861 const LangOptions &LangOpts) {
862 SourceLocation Begin = Range.getBegin();
863 SourceLocation End = Range.getEnd();
864 if (Begin.isInvalid() || End.isInvalid())
865 return CharSourceRange();
867 if (Begin.isFileID() && End.isFileID())
868 return makeRangeFromFileLocs(Range, SM, LangOpts);
870 if (Begin.isMacroID() && End.isFileID()) {
871 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
872 return CharSourceRange();
873 Range.setBegin(Begin);
874 return makeRangeFromFileLocs(Range, SM, LangOpts);
877 if (Begin.isFileID() && End.isMacroID()) {
878 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
880 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
882 return CharSourceRange();
884 return makeRangeFromFileLocs(Range, SM, LangOpts);
887 assert(Begin.isMacroID() && End.isMacroID());
888 SourceLocation MacroBegin, MacroEnd;
889 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
890 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
892 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
894 Range.setBegin(MacroBegin);
895 Range.setEnd(MacroEnd);
896 return makeRangeFromFileLocs(Range, SM, LangOpts);
899 bool Invalid = false;
900 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
903 return CharSourceRange();
905 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
906 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
909 return CharSourceRange();
911 if (EndEntry.getExpansion().isMacroArgExpansion() &&
912 BeginEntry.getExpansion().getExpansionLocStart() ==
913 EndEntry.getExpansion().getExpansionLocStart()) {
914 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
915 Range.setEnd(SM.getImmediateSpellingLoc(End));
916 return makeFileCharRange(Range, SM, LangOpts);
920 return CharSourceRange();
923 StringRef Lexer::getSourceText(CharSourceRange Range,
924 const SourceManager &SM,
925 const LangOptions &LangOpts,
927 Range = makeFileCharRange(Range, SM, LangOpts);
928 if (Range.isInvalid()) {
929 if (Invalid) *Invalid = true;
933 // Break down the source location.
934 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
935 if (beginInfo.first.isInvalid()) {
936 if (Invalid) *Invalid = true;
941 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
942 beginInfo.second > EndOffs) {
943 if (Invalid) *Invalid = true;
947 // Try to the load the file buffer.
948 bool invalidTemp = false;
949 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
951 if (Invalid) *Invalid = true;
955 if (Invalid) *Invalid = false;
956 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
959 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
960 const SourceManager &SM,
961 const LangOptions &LangOpts) {
962 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
964 // Find the location of the immediate macro expansion.
966 FileID FID = SM.getFileID(Loc);
967 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
968 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
969 Loc = Expansion.getExpansionLocStart();
970 if (!Expansion.isMacroArgExpansion())
973 // For macro arguments we need to check that the argument did not come
974 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
976 // Loc points to the argument id of the macro definition, move to the
978 Loc = SM.getImmediateExpansionRange(Loc).first;
979 SourceLocation SpellLoc = Expansion.getSpellingLoc();
980 if (SpellLoc.isFileID())
981 break; // No inner macro.
983 // If spelling location resides in the same FileID as macro expansion
984 // location, it means there is no inner macro.
985 FileID MacroFID = SM.getFileID(Loc);
986 if (SM.isInFileID(SpellLoc, MacroFID))
989 // Argument came from inner macro.
993 // Find the spelling location of the start of the non-argument expansion
994 // range. This is where the macro name was spelled in order to begin
995 // expanding this macro.
996 Loc = SM.getSpellingLoc(Loc);
998 // Dig out the buffer where the macro name was spelled and the extents of the
999 // name so that we can render it into the expansion note.
1000 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1001 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1002 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1003 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1006 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1007 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1008 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1009 // Walk past macro argument expanions.
1010 while (SM.isMacroArgExpansion(Loc))
1011 Loc = SM.getImmediateExpansionRange(Loc).first;
1013 // If the macro's spelling has no FileID, then it's actually a token paste
1014 // or stringization (or similar) and not a macro at all.
1015 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1018 // Find the spelling location of the start of the non-argument expansion
1019 // range. This is where the macro name was spelled in order to begin
1020 // expanding this macro.
1021 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1023 // Dig out the buffer where the macro name was spelled and the extents of the
1024 // name so that we can render it into the expansion note.
1025 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1026 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1027 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1028 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1031 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1032 return isIdentifierBody(c, LangOpts.DollarIdents);
1035 StringRef Lexer::getIndentationForLine(SourceLocation Loc,
1036 const SourceManager &SM) {
1037 if (Loc.isInvalid() || Loc.isMacroID())
1039 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1040 if (LocInfo.first.isInvalid())
1042 bool Invalid = false;
1043 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
1046 const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
1049 StringRef Rest = Buffer.substr(Line - Buffer.data());
1050 size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
1051 return NumWhitespaceChars == StringRef::npos
1053 : Rest.take_front(NumWhitespaceChars);
1056 //===----------------------------------------------------------------------===//
1057 // Diagnostics forwarding code.
1058 //===----------------------------------------------------------------------===//
1060 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1061 /// lexer buffer was all expanded at a single point, perform the mapping.
1062 /// This is currently only used for _Pragma implementation, so it is the slow
1063 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1064 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1065 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1066 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1067 SourceLocation FileLoc,
1068 unsigned CharNo, unsigned TokLen) {
1069 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1071 // Otherwise, we're lexing "mapped tokens". This is used for things like
1072 // _Pragma handling. Combine the expansion location of FileLoc with the
1073 // spelling location.
1074 SourceManager &SM = PP.getSourceManager();
1076 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1077 // characters come from spelling(FileLoc)+Offset.
1078 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1079 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1081 // Figure out the expansion loc range, which is the range covered by the
1082 // original _Pragma(...) sequence.
1083 std::pair<SourceLocation,SourceLocation> II =
1084 SM.getImmediateExpansionRange(FileLoc);
1086 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1089 /// getSourceLocation - Return a source location identifier for the specified
1090 /// offset in the current file.
1091 SourceLocation Lexer::getSourceLocation(const char *Loc,
1092 unsigned TokLen) const {
1093 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1094 "Location out of range for this buffer!");
1096 // In the normal case, we're just lexing from a simple file buffer, return
1097 // the file id from FileLoc with the offset specified.
1098 unsigned CharNo = Loc-BufferStart;
1099 if (FileLoc.isFileID())
1100 return FileLoc.getLocWithOffset(CharNo);
1102 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1103 // tokens are lexed from where the _Pragma was defined.
1104 assert(PP && "This doesn't work on raw lexers");
1105 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1108 /// Diag - Forwarding function for diagnostics. This translate a source
1109 /// position in the current buffer into a SourceLocation object for rendering.
1110 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1111 return PP->Diag(getSourceLocation(Loc), DiagID);
1114 //===----------------------------------------------------------------------===//
1115 // Trigraph and Escaped Newline Handling Code.
1116 //===----------------------------------------------------------------------===//
1118 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1119 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1120 static char GetTrigraphCharForLetter(char Letter) {
1123 case '=': return '#';
1124 case ')': return ']';
1125 case '(': return '[';
1126 case '!': return '|';
1127 case '\'': return '^';
1128 case '>': return '}';
1129 case '/': return '\\';
1130 case '<': return '{';
1131 case '-': return '~';
1135 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1136 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1137 /// return the result character. Finally, emit a warning about trigraph use
1138 /// whether trigraphs are enabled or not.
1139 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1140 char Res = GetTrigraphCharForLetter(*CP);
1141 if (!Res || !L) return Res;
1143 if (!L->getLangOpts().Trigraphs) {
1144 if (!L->isLexingRawMode())
1145 L->Diag(CP-2, diag::trigraph_ignored);
1149 if (!L->isLexingRawMode())
1150 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1154 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1155 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1156 /// trigraph equivalent on entry to this function.
1157 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1159 while (isWhitespace(Ptr[Size])) {
1162 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1165 // If this is a \r\n or \n\r, skip the other half.
1166 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1167 Ptr[Size-1] != Ptr[Size])
1173 // Not an escaped newline, must be a \t or something else.
1177 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1178 /// them), skip over them and return the first non-escaped-newline found,
1179 /// otherwise return P.
1180 const char *Lexer::SkipEscapedNewLines(const char *P) {
1182 const char *AfterEscape;
1185 } else if (*P == '?') {
1186 // If not a trigraph for escape, bail out.
1187 if (P[1] != '?' || P[2] != '/')
1189 // FIXME: Take LangOpts into account; the language might not
1190 // support trigraphs.
1196 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1197 if (NewLineSize == 0) return P;
1198 P = AfterEscape+NewLineSize;
1202 /// \brief Checks that the given token is the first token that occurs after the
1203 /// given location (this excludes comments and whitespace). Returns the location
1204 /// immediately after the specified token. If the token is not found or the
1205 /// location is inside a macro, the returned source location will be invalid.
1206 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1207 tok::TokenKind TKind,
1208 const SourceManager &SM,
1209 const LangOptions &LangOpts,
1210 bool SkipTrailingWhitespaceAndNewLine) {
1211 if (Loc.isMacroID()) {
1212 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1213 return SourceLocation();
1215 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1217 // Break down the source location.
1218 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1220 // Try to load the file buffer.
1221 bool InvalidTemp = false;
1222 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1224 return SourceLocation();
1226 const char *TokenBegin = File.data() + LocInfo.second;
1228 // Lex from the start of the given location.
1229 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1230 TokenBegin, File.end());
1233 lexer.LexFromRawLexer(Tok);
1234 if (Tok.isNot(TKind))
1235 return SourceLocation();
1236 SourceLocation TokenLoc = Tok.getLocation();
1238 // Calculate how much whitespace needs to be skipped if any.
1239 unsigned NumWhitespaceChars = 0;
1240 if (SkipTrailingWhitespaceAndNewLine) {
1241 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1243 unsigned char C = *TokenEnd;
1244 while (isHorizontalWhitespace(C)) {
1246 NumWhitespaceChars++;
1249 // Skip \r, \n, \r\n, or \n\r
1250 if (C == '\n' || C == '\r') {
1253 NumWhitespaceChars++;
1254 if ((C == '\n' || C == '\r') && C != PrevC)
1255 NumWhitespaceChars++;
1259 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1262 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1263 /// get its size, and return it. This is tricky in several cases:
1264 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1265 /// then either return the trigraph (skipping 3 chars) or the '?',
1266 /// depending on whether trigraphs are enabled or not.
1267 /// 2. If this is an escaped newline (potentially with whitespace between
1268 /// the backslash and newline), implicitly skip the newline and return
1269 /// the char after it.
1271 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1272 /// know that we can accumulate into Size, and that we have already incremented
1273 /// Ptr by Size bytes.
1275 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1276 /// be updated to match.
1278 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1280 // If we have a slash, look for an escaped newline.
1281 if (Ptr[0] == '\\') {
1285 // Common case, backslash-char where the char is not whitespace.
1286 if (!isWhitespace(Ptr[0])) return '\\';
1288 // See if we have optional whitespace characters between the slash and
1290 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1291 // Remember that this token needs to be cleaned.
1292 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1294 // Warn if there was whitespace between the backslash and newline.
1295 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1296 Diag(Ptr, diag::backslash_newline_space);
1298 // Found backslash<whitespace><newline>. Parse the char after it.
1299 Size += EscapedNewLineSize;
1300 Ptr += EscapedNewLineSize;
1302 // Use slow version to accumulate a correct size field.
1303 return getCharAndSizeSlow(Ptr, Size, Tok);
1306 // Otherwise, this is not an escaped newline, just return the slash.
1310 // If this is a trigraph, process it.
1311 if (Ptr[0] == '?' && Ptr[1] == '?') {
1312 // If this is actually a legal trigraph (not something like "??x"), emit
1313 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1314 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1315 // Remember that this token needs to be cleaned.
1316 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1320 if (C == '\\') goto Slash;
1325 // If this is neither, return a single character.
1330 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1331 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1332 /// and that we have already incremented Ptr by Size bytes.
1334 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1335 /// be updated to match.
1336 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1337 const LangOptions &LangOpts) {
1338 // If we have a slash, look for an escaped newline.
1339 if (Ptr[0] == '\\') {
1343 // Common case, backslash-char where the char is not whitespace.
1344 if (!isWhitespace(Ptr[0])) return '\\';
1346 // See if we have optional whitespace characters followed by a newline.
1347 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1348 // Found backslash<whitespace><newline>. Parse the char after it.
1349 Size += EscapedNewLineSize;
1350 Ptr += EscapedNewLineSize;
1352 // Use slow version to accumulate a correct size field.
1353 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1356 // Otherwise, this is not an escaped newline, just return the slash.
1360 // If this is a trigraph, process it.
1361 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1362 // If this is actually a legal trigraph (not something like "??x"), return
1364 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1367 if (C == '\\') goto Slash;
1372 // If this is neither, return a single character.
1377 //===----------------------------------------------------------------------===//
1378 // Helper methods for lexing.
1379 //===----------------------------------------------------------------------===//
1381 /// \brief Routine that indiscriminately skips bytes in the source file.
1382 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1384 if (BufferPtr > BufferEnd)
1385 BufferPtr = BufferEnd;
1386 // FIXME: What exactly does the StartOfLine bit mean? There are two
1387 // possible meanings for the "start" of the line: the first token on the
1388 // unexpanded line, or the first token on the expanded line.
1389 IsAtStartOfLine = StartOfLine;
1390 IsAtPhysicalStartOfLine = StartOfLine;
1393 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1394 if (LangOpts.AsmPreprocessor) {
1396 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1397 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1398 C11AllowedIDCharRanges);
1399 return C11AllowedIDChars.contains(C);
1400 } else if (LangOpts.CPlusPlus) {
1401 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1402 CXX03AllowedIDCharRanges);
1403 return CXX03AllowedIDChars.contains(C);
1405 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1406 C99AllowedIDCharRanges);
1407 return C99AllowedIDChars.contains(C);
1411 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1412 assert(isAllowedIDChar(C, LangOpts));
1413 if (LangOpts.AsmPreprocessor) {
1415 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1416 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1417 C11DisallowedInitialIDCharRanges);
1418 return !C11DisallowedInitialIDChars.contains(C);
1419 } else if (LangOpts.CPlusPlus) {
1422 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1423 C99DisallowedInitialIDCharRanges);
1424 return !C99DisallowedInitialIDChars.contains(C);
1428 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1430 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1431 L.getSourceLocation(End));
1434 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1435 CharSourceRange Range, bool IsFirst) {
1436 // Check C99 compatibility.
1437 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1439 CannotAppearInIdentifier = 0,
1440 CannotStartIdentifier
1443 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1444 C99AllowedIDCharRanges);
1445 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1446 C99DisallowedInitialIDCharRanges);
1447 if (!C99AllowedIDChars.contains(C)) {
1448 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1450 << CannotAppearInIdentifier;
1451 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1452 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1454 << CannotStartIdentifier;
1458 // Check C++98 compatibility.
1459 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1460 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1461 CXX03AllowedIDCharRanges);
1462 if (!CXX03AllowedIDChars.contains(C)) {
1463 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1469 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1471 const char *UCNPtr = CurPtr + Size;
1472 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1473 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1476 if (!isLexingRawMode())
1477 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1478 makeCharRange(*this, CurPtr, UCNPtr),
1481 Result.setFlag(Token::HasUCN);
1482 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1483 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1486 while (CurPtr != UCNPtr)
1487 (void)getAndAdvanceChar(CurPtr, Result);
1491 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1492 const char *UnicodePtr = CurPtr;
1493 llvm::UTF32 CodePoint;
1494 llvm::ConversionResult Result =
1495 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
1496 (const llvm::UTF8 *)BufferEnd,
1498 llvm::strictConversion);
1499 if (Result != llvm::conversionOK ||
1500 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1503 if (!isLexingRawMode())
1504 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1505 makeCharRange(*this, CurPtr, UnicodePtr),
1508 CurPtr = UnicodePtr;
1512 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1513 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1515 unsigned char C = *CurPtr++;
1516 while (isIdentifierBody(C))
1519 --CurPtr; // Back up over the skipped character.
1521 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1522 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1524 // TODO: Could merge these checks into an InfoTable flag to make the
1525 // comparison cheaper
1526 if (isASCII(C) && C != '\\' && C != '?' &&
1527 (C != '$' || !LangOpts.DollarIdents)) {
1529 const char *IdStart = BufferPtr;
1530 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1531 Result.setRawIdentifierData(IdStart);
1533 // If we are in raw mode, return this identifier raw. There is no need to
1534 // look up identifier information or attempt to macro expand it.
1538 // Fill in Result.IdentifierInfo and update the token kind,
1539 // looking up the identifier in the identifier table.
1540 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1542 // Finally, now that we know we have an identifier, pass this off to the
1543 // preprocessor, which may macro expand it or something.
1544 if (II->isHandleIdentifierCase())
1545 return PP->HandleIdentifier(Result);
1547 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr)
1548 && II->getPPKeywordID() == tok::pp_not_keyword
1549 && II->getObjCKeywordID() == tok::objc_not_keyword) {
1550 // Return the code-completion token.
1551 Result.setKind(tok::code_completion);
1558 // Otherwise, $,\,? in identifier found. Enter slower path.
1560 C = getCharAndSize(CurPtr, Size);
1563 // If we hit a $ and they are not supported in identifiers, we are done.
1564 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1566 // Otherwise, emit a diagnostic and continue.
1567 if (!isLexingRawMode())
1568 Diag(CurPtr, diag::ext_dollar_in_identifier);
1569 CurPtr = ConsumeChar(CurPtr, Size, Result);
1570 C = getCharAndSize(CurPtr, Size);
1573 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1574 C = getCharAndSize(CurPtr, Size);
1576 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1577 C = getCharAndSize(CurPtr, Size);
1579 } else if (!isIdentifierBody(C)) {
1580 goto FinishIdentifier;
1583 // Otherwise, this character is good, consume it.
1584 CurPtr = ConsumeChar(CurPtr, Size, Result);
1586 C = getCharAndSize(CurPtr, Size);
1587 while (isIdentifierBody(C)) {
1588 CurPtr = ConsumeChar(CurPtr, Size, Result);
1589 C = getCharAndSize(CurPtr, Size);
1594 /// isHexaLiteral - Return true if Start points to a hex constant.
1595 /// in microsoft mode (where this is supposed to be several different tokens).
1596 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1598 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1601 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1602 return (C2 == 'x' || C2 == 'X');
1605 /// LexNumericConstant - Lex the remainder of a integer or floating point
1606 /// constant. From[-1] is the first character lexed. Return the end of the
1608 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1610 char C = getCharAndSize(CurPtr, Size);
1612 while (isPreprocessingNumberBody(C)) {
1613 CurPtr = ConsumeChar(CurPtr, Size, Result);
1615 C = getCharAndSize(CurPtr, Size);
1618 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1619 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1620 // If we are in Microsoft mode, don't continue if the constant is hex.
1621 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1622 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1623 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1626 // If we have a hex FP constant, continue.
1627 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1628 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1629 // not-quite-conforming extension. Only do so if this looks like it's
1630 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1631 bool IsHexFloat = true;
1632 if (!LangOpts.C99) {
1633 if (!isHexaLiteral(BufferPtr, LangOpts))
1635 else if (!getLangOpts().CPlusPlus1z &&
1636 std::find(BufferPtr, CurPtr, '_') != CurPtr)
1640 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1643 // If we have a digit separator, continue.
1644 if (C == '\'' && getLangOpts().CPlusPlus14) {
1646 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1647 if (isIdentifierBody(Next)) {
1648 if (!isLexingRawMode())
1649 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1650 CurPtr = ConsumeChar(CurPtr, Size, Result);
1651 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1652 return LexNumericConstant(Result, CurPtr);
1656 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1657 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1658 return LexNumericConstant(Result, CurPtr);
1659 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1660 return LexNumericConstant(Result, CurPtr);
1662 // Update the location of token as well as BufferPtr.
1663 const char *TokStart = BufferPtr;
1664 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1665 Result.setLiteralData(TokStart);
1669 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1670 /// in C++11, or warn on a ud-suffix in C++98.
1671 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1672 bool IsStringLiteral) {
1673 assert(getLangOpts().CPlusPlus);
1675 // Maximally munch an identifier.
1677 char C = getCharAndSize(CurPtr, Size);
1678 bool Consumed = false;
1680 if (!isIdentifierHead(C)) {
1681 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1683 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1689 if (!getLangOpts().CPlusPlus11) {
1690 if (!isLexingRawMode())
1692 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1693 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1694 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1698 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1699 // that does not start with an underscore is ill-formed. As a conforming
1700 // extension, we treat all such suffixes as if they had whitespace before
1701 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1702 // likely to be a ud-suffix than a macro, however, and accept that.
1704 bool IsUDSuffix = false;
1707 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1708 // In C++1y, we need to look ahead a few characters to see if this is a
1709 // valid suffix for a string literal or a numeric literal (this could be
1710 // the 'operator""if' defining a numeric literal operator).
1711 const unsigned MaxStandardSuffixLength = 3;
1712 char Buffer[MaxStandardSuffixLength] = { C };
1713 unsigned Consumed = Size;
1717 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1719 if (!isIdentifierBody(Next)) {
1720 // End of suffix. Check whether this is on the whitelist.
1721 const StringRef CompleteSuffix(Buffer, Chars);
1722 IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
1727 if (Chars == MaxStandardSuffixLength)
1728 // Too long: can't be a standard suffix.
1731 Buffer[Chars++] = Next;
1732 Consumed += NextSize;
1737 if (!isLexingRawMode())
1738 Diag(CurPtr, getLangOpts().MSVCCompat
1739 ? diag::ext_ms_reserved_user_defined_literal
1740 : diag::ext_reserved_user_defined_literal)
1741 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1745 CurPtr = ConsumeChar(CurPtr, Size, Result);
1748 Result.setFlag(Token::HasUDSuffix);
1750 C = getCharAndSize(CurPtr, Size);
1751 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1752 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1753 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1760 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1761 /// either " or L" or u8" or u" or U".
1762 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1763 tok::TokenKind Kind) {
1764 // Does this string contain the \0 character?
1765 const char *NulCharacter = nullptr;
1767 if (!isLexingRawMode() &&
1768 (Kind == tok::utf8_string_literal ||
1769 Kind == tok::utf16_string_literal ||
1770 Kind == tok::utf32_string_literal))
1771 Diag(BufferPtr, getLangOpts().CPlusPlus
1772 ? diag::warn_cxx98_compat_unicode_literal
1773 : diag::warn_c99_compat_unicode_literal);
1775 char C = getAndAdvanceChar(CurPtr, Result);
1777 // Skip escaped characters. Escaped newlines will already be processed by
1778 // getAndAdvanceChar.
1780 C = getAndAdvanceChar(CurPtr, Result);
1782 if (C == '\n' || C == '\r' || // Newline.
1783 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1784 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1785 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1786 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1791 if (isCodeCompletionPoint(CurPtr-1)) {
1792 PP->CodeCompleteNaturalLanguage();
1793 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1798 NulCharacter = CurPtr-1;
1800 C = getAndAdvanceChar(CurPtr, Result);
1803 // If we are in C++11, lex the optional ud-suffix.
1804 if (getLangOpts().CPlusPlus)
1805 CurPtr = LexUDSuffix(Result, CurPtr, true);
1807 // If a nul character existed in the string, warn about it.
1808 if (NulCharacter && !isLexingRawMode())
1809 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1811 // Update the location of the token as well as the BufferPtr instance var.
1812 const char *TokStart = BufferPtr;
1813 FormTokenWithChars(Result, CurPtr, Kind);
1814 Result.setLiteralData(TokStart);
1818 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1819 /// having lexed R", LR", u8R", uR", or UR".
1820 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1821 tok::TokenKind Kind) {
1822 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1823 // Between the initial and final double quote characters of the raw string,
1824 // any transformations performed in phases 1 and 2 (trigraphs,
1825 // universal-character-names, and line splicing) are reverted.
1827 if (!isLexingRawMode())
1828 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1830 unsigned PrefixLen = 0;
1832 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1835 // If the last character was not a '(', then we didn't lex a valid delimiter.
1836 if (CurPtr[PrefixLen] != '(') {
1837 if (!isLexingRawMode()) {
1838 const char *PrefixEnd = &CurPtr[PrefixLen];
1839 if (PrefixLen == 16) {
1840 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1842 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1843 << StringRef(PrefixEnd, 1);
1847 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1848 // it's possible the '"' was intended to be part of the raw string, but
1849 // there's not much we can do about that.
1855 if (C == 0 && CurPtr-1 == BufferEnd) {
1861 FormTokenWithChars(Result, CurPtr, tok::unknown);
1865 // Save prefix and move CurPtr past it
1866 const char *Prefix = CurPtr;
1867 CurPtr += PrefixLen + 1; // skip over prefix and '('
1873 // Check for prefix match and closing quote.
1874 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1875 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1878 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1879 if (!isLexingRawMode())
1880 Diag(BufferPtr, diag::err_unterminated_raw_string)
1881 << StringRef(Prefix, PrefixLen);
1882 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1887 // If we are in C++11, lex the optional ud-suffix.
1888 if (getLangOpts().CPlusPlus)
1889 CurPtr = LexUDSuffix(Result, CurPtr, true);
1891 // Update the location of token as well as BufferPtr.
1892 const char *TokStart = BufferPtr;
1893 FormTokenWithChars(Result, CurPtr, Kind);
1894 Result.setLiteralData(TokStart);
1898 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1899 /// after having lexed the '<' character. This is used for #include filenames.
1900 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1901 // Does this string contain the \0 character?
1902 const char *NulCharacter = nullptr;
1903 const char *AfterLessPos = CurPtr;
1904 char C = getAndAdvanceChar(CurPtr, Result);
1906 // Skip escaped characters.
1907 if (C == '\\' && CurPtr < BufferEnd) {
1908 // Skip the escaped character.
1909 getAndAdvanceChar(CurPtr, Result);
1910 } else if (C == '\n' || C == '\r' || // Newline.
1911 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1912 isCodeCompletionPoint(CurPtr-1)))) {
1913 // If the filename is unterminated, then it must just be a lone <
1914 // character. Return this as such.
1915 FormTokenWithChars(Result, AfterLessPos, tok::less);
1917 } else if (C == 0) {
1918 NulCharacter = CurPtr-1;
1920 C = getAndAdvanceChar(CurPtr, Result);
1923 // If a nul character existed in the string, warn about it.
1924 if (NulCharacter && !isLexingRawMode())
1925 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1927 // Update the location of token as well as BufferPtr.
1928 const char *TokStart = BufferPtr;
1929 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1930 Result.setLiteralData(TokStart);
1934 /// LexCharConstant - Lex the remainder of a character constant, after having
1935 /// lexed either ' or L' or u8' or u' or U'.
1936 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1937 tok::TokenKind Kind) {
1938 // Does this character contain the \0 character?
1939 const char *NulCharacter = nullptr;
1941 if (!isLexingRawMode()) {
1942 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1943 Diag(BufferPtr, getLangOpts().CPlusPlus
1944 ? diag::warn_cxx98_compat_unicode_literal
1945 : diag::warn_c99_compat_unicode_literal);
1946 else if (Kind == tok::utf8_char_constant)
1947 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1950 char C = getAndAdvanceChar(CurPtr, Result);
1952 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1953 Diag(BufferPtr, diag::ext_empty_character);
1954 FormTokenWithChars(Result, CurPtr, tok::unknown);
1959 // Skip escaped characters.
1961 C = getAndAdvanceChar(CurPtr, Result);
1963 if (C == '\n' || C == '\r' || // Newline.
1964 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1965 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1966 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
1967 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1972 if (isCodeCompletionPoint(CurPtr-1)) {
1973 PP->CodeCompleteNaturalLanguage();
1974 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1979 NulCharacter = CurPtr-1;
1981 C = getAndAdvanceChar(CurPtr, Result);
1984 // If we are in C++11, lex the optional ud-suffix.
1985 if (getLangOpts().CPlusPlus)
1986 CurPtr = LexUDSuffix(Result, CurPtr, false);
1988 // If a nul character existed in the character, warn about it.
1989 if (NulCharacter && !isLexingRawMode())
1990 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
1992 // Update the location of token as well as BufferPtr.
1993 const char *TokStart = BufferPtr;
1994 FormTokenWithChars(Result, CurPtr, Kind);
1995 Result.setLiteralData(TokStart);
1999 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
2000 /// Update BufferPtr to point to the next non-whitespace character and return.
2002 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
2004 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
2005 bool &TokAtPhysicalStartOfLine) {
2006 // Whitespace - Skip it, then return the token after the whitespace.
2007 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
2009 unsigned char Char = *CurPtr;
2011 // Skip consecutive spaces efficiently.
2013 // Skip horizontal whitespace very aggressively.
2014 while (isHorizontalWhitespace(Char))
2017 // Otherwise if we have something other than whitespace, we're done.
2018 if (!isVerticalWhitespace(Char))
2021 if (ParsingPreprocessorDirective) {
2022 // End of preprocessor directive line, let LexTokenInternal handle this.
2027 // OK, but handle newline.
2032 // If the client wants us to return whitespace, return it now.
2033 if (isKeepWhitespaceMode()) {
2034 FormTokenWithChars(Result, CurPtr, tok::unknown);
2036 IsAtStartOfLine = true;
2037 IsAtPhysicalStartOfLine = true;
2039 // FIXME: The next token will not have LeadingSpace set.
2043 // If this isn't immediately after a newline, there is leading space.
2044 char PrevChar = CurPtr[-1];
2045 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2047 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2049 Result.setFlag(Token::StartOfLine);
2050 TokAtPhysicalStartOfLine = true;
2057 /// We have just read the // characters from input. Skip until we find the
2058 /// newline character thats terminate the comment. Then update BufferPtr and
2061 /// If we're in KeepCommentMode or any CommentHandler has inserted
2062 /// some tokens, this will store the first token and return true.
2063 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2064 bool &TokAtPhysicalStartOfLine) {
2065 // If Line comments aren't explicitly enabled for this language, emit an
2066 // extension warning.
2067 if (!LangOpts.LineComment && !isLexingRawMode()) {
2068 Diag(BufferPtr, diag::ext_line_comment);
2070 // Mark them enabled so we only emit one warning for this translation
2072 LangOpts.LineComment = true;
2075 // Scan over the body of the comment. The common case, when scanning, is that
2076 // the comment contains normal ascii characters with nothing interesting in
2077 // them. As such, optimize for this case with the inner loop.
2079 // This loop terminates with CurPtr pointing at the newline (or end of buffer)
2080 // character that ends the line comment.
2084 // Skip over characters in the fast loop.
2085 while (C != 0 && // Potentially EOF.
2086 C != '\n' && C != '\r') // Newline or DOS-style newline.
2089 const char *NextLine = CurPtr;
2091 // We found a newline, see if it's escaped.
2092 const char *EscapePtr = CurPtr-1;
2093 bool HasSpace = false;
2094 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2099 if (*EscapePtr == '\\')
2102 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2103 EscapePtr[-2] == '?' && LangOpts.Trigraphs)
2104 // Trigraph-escaped newline.
2105 CurPtr = EscapePtr-2;
2107 break; // This is a newline, we're done.
2109 // If there was space between the backslash and newline, warn about it.
2110 if (HasSpace && !isLexingRawMode())
2111 Diag(EscapePtr, diag::backslash_newline_space);
2114 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2115 // properly decode the character. Read it in raw mode to avoid emitting
2116 // diagnostics about things like trigraphs. If we see an escaped newline,
2117 // we'll handle it below.
2118 const char *OldPtr = CurPtr;
2119 bool OldRawMode = isLexingRawMode();
2120 LexingRawMode = true;
2121 C = getAndAdvanceChar(CurPtr, Result);
2122 LexingRawMode = OldRawMode;
2124 // If we only read only one character, then no special handling is needed.
2125 // We're done and can skip forward to the newline.
2126 if (C != 0 && CurPtr == OldPtr+1) {
2131 // If we read multiple characters, and one of those characters was a \r or
2132 // \n, then we had an escaped newline within the comment. Emit diagnostic
2133 // unless the next line is also a // comment.
2134 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2135 for (; OldPtr != CurPtr; ++OldPtr)
2136 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2137 // Okay, we found a // comment that ends in a newline, if the next
2138 // line is also a // comment, but has spaces, don't emit a diagnostic.
2139 if (isWhitespace(C)) {
2140 const char *ForwardPtr = CurPtr;
2141 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2143 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2147 if (!isLexingRawMode())
2148 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2153 if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
2158 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2159 PP->CodeCompleteNaturalLanguage();
2165 // Found but did not consume the newline. Notify comment handlers about the
2166 // comment unless we're in a #if 0 block.
2167 if (PP && !isLexingRawMode() &&
2168 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2169 getSourceLocation(CurPtr)))) {
2171 return true; // A token has to be returned.
2174 // If we are returning comments as tokens, return this comment as a token.
2175 if (inKeepCommentMode())
2176 return SaveLineComment(Result, CurPtr);
2178 // If we are inside a preprocessor directive and we see the end of line,
2179 // return immediately, so that the lexer can return this as an EOD token.
2180 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2185 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2186 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2187 // contribute to another token), it isn't needed for correctness. Note that
2188 // this is ok even in KeepWhitespaceMode, because we would have returned the
2189 /// comment above in that mode.
2192 // The next returned token is at the start of the line.
2193 Result.setFlag(Token::StartOfLine);
2194 TokAtPhysicalStartOfLine = true;
2195 // No leading whitespace seen so far.
2196 Result.clearFlag(Token::LeadingSpace);
2201 /// If in save-comment mode, package up this Line comment in an appropriate
2202 /// way and return it.
2203 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2204 // If we're not in a preprocessor directive, just return the // comment
2206 FormTokenWithChars(Result, CurPtr, tok::comment);
2208 if (!ParsingPreprocessorDirective || LexingRawMode)
2211 // If this Line-style comment is in a macro definition, transmogrify it into
2212 // a C-style block comment.
2213 bool Invalid = false;
2214 std::string Spelling = PP->getSpelling(Result, &Invalid);
2218 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2219 Spelling[1] = '*'; // Change prefix to "/*".
2220 Spelling += "*/"; // add suffix.
2222 Result.setKind(tok::comment);
2223 PP->CreateString(Spelling, Result,
2224 Result.getLocation(), Result.getLocation());
2228 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2229 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2230 /// a diagnostic if so. We know that the newline is inside of a block comment.
2231 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2233 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2235 // Back up off the newline.
2238 // If this is a two-character newline sequence, skip the other character.
2239 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2240 // \n\n or \r\r -> not escaped newline.
2241 if (CurPtr[0] == CurPtr[1])
2243 // \n\r or \r\n -> skip the newline.
2247 // If we have horizontal whitespace, skip over it. We allow whitespace
2248 // between the slash and newline.
2249 bool HasSpace = false;
2250 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2255 // If we have a slash, we know this is an escaped newline.
2256 if (*CurPtr == '\\') {
2257 if (CurPtr[-1] != '*') return false;
2259 // It isn't a slash, is it the ?? / trigraph?
2260 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2264 // This is the trigraph ending the comment. Emit a stern warning!
2267 // If no trigraphs are enabled, warn that we ignored this trigraph and
2268 // ignore this * character.
2269 if (!L->getLangOpts().Trigraphs) {
2270 if (!L->isLexingRawMode())
2271 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2274 if (!L->isLexingRawMode())
2275 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2278 // Warn about having an escaped newline between the */ characters.
2279 if (!L->isLexingRawMode())
2280 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2282 // If there was space between the backslash and newline, warn about it.
2283 if (HasSpace && !L->isLexingRawMode())
2284 L->Diag(CurPtr, diag::backslash_newline_space);
2290 #include <emmintrin.h>
2292 #include <altivec.h>
2296 /// We have just read from input the / and * characters that started a comment.
2297 /// Read until we find the * and / characters that terminate the comment.
2298 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2299 /// comments, because they cannot cause the comment to end. The only thing
2300 /// that can happen is the comment could end with an escaped newline between
2301 /// the terminating * and /.
2303 /// If we're in KeepCommentMode or any CommentHandler has inserted
2304 /// some tokens, this will store the first token and return true.
2305 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2306 bool &TokAtPhysicalStartOfLine) {
2307 // Scan one character past where we should, looking for a '/' character. Once
2308 // we find it, check to see if it was preceded by a *. This common
2309 // optimization helps people who like to put a lot of * characters in their
2312 // The first character we get with newlines and trigraphs skipped to handle
2313 // the degenerate /*/ case below correctly if the * has an escaped newline
2316 unsigned char C = getCharAndSize(CurPtr, CharSize);
2318 if (C == 0 && CurPtr == BufferEnd+1) {
2319 if (!isLexingRawMode())
2320 Diag(BufferPtr, diag::err_unterminated_block_comment);
2323 // KeepWhitespaceMode should return this broken comment as a token. Since
2324 // it isn't a well formed comment, just return it as an 'unknown' token.
2325 if (isKeepWhitespaceMode()) {
2326 FormTokenWithChars(Result, CurPtr, tok::unknown);
2334 // Check to see if the first character after the '/*' is another /. If so,
2335 // then this slash does not end the block comment, it is part of it.
2340 // Skip over all non-interesting characters until we find end of buffer or a
2341 // (probably ending) '/' character.
2342 if (CurPtr + 24 < BufferEnd &&
2343 // If there is a code-completion point avoid the fast scan because it
2344 // doesn't check for '\0'.
2345 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2346 // While not aligned to a 16-byte boundary.
2347 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2350 if (C == '/') goto FoundSlash;
2353 __m128i Slashes = _mm_set1_epi8('/');
2354 while (CurPtr+16 <= BufferEnd) {
2355 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2358 // Adjust the pointer to point directly after the first slash. It's
2359 // not necessary to set C here, it will be overwritten at the end of
2361 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2367 __vector unsigned char Slashes = {
2368 '/', '/', '/', '/', '/', '/', '/', '/',
2369 '/', '/', '/', '/', '/', '/', '/', '/'
2371 while (CurPtr+16 <= BufferEnd &&
2372 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2375 // Scan for '/' quickly. Many block comments are very large.
2376 while (CurPtr[0] != '/' &&
2380 CurPtr+4 < BufferEnd) {
2385 // It has to be one of the bytes scanned, increment to it and read one.
2389 // Loop to scan the remainder.
2390 while (C != '/' && C != '\0')
2395 if (CurPtr[-2] == '*') // We found the final */. We're done!
2398 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2399 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2400 // We found the final */, though it had an escaped newline between the
2401 // * and /. We're done!
2405 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2406 // If this is a /* inside of the comment, emit a warning. Don't do this
2407 // if this is a /*/, which will end the comment. This misses cases with
2408 // embedded escaped newlines, but oh well.
2409 if (!isLexingRawMode())
2410 Diag(CurPtr-1, diag::warn_nested_block_comment);
2412 } else if (C == 0 && CurPtr == BufferEnd+1) {
2413 if (!isLexingRawMode())
2414 Diag(BufferPtr, diag::err_unterminated_block_comment);
2415 // Note: the user probably forgot a */. We could continue immediately
2416 // after the /*, but this would involve lexing a lot of what really is the
2417 // comment, which surely would confuse the parser.
2420 // KeepWhitespaceMode should return this broken comment as a token. Since
2421 // it isn't a well formed comment, just return it as an 'unknown' token.
2422 if (isKeepWhitespaceMode()) {
2423 FormTokenWithChars(Result, CurPtr, tok::unknown);
2429 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2430 PP->CodeCompleteNaturalLanguage();
2438 // Notify comment handlers about the comment unless we're in a #if 0 block.
2439 if (PP && !isLexingRawMode() &&
2440 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2441 getSourceLocation(CurPtr)))) {
2443 return true; // A token has to be returned.
2446 // If we are returning comments as tokens, return this comment as a token.
2447 if (inKeepCommentMode()) {
2448 FormTokenWithChars(Result, CurPtr, tok::comment);
2452 // It is common for the tokens immediately after a /**/ comment to be
2453 // whitespace. Instead of going through the big switch, handle it
2454 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2455 // have already returned above with the comment as a token.
2456 if (isHorizontalWhitespace(*CurPtr)) {
2457 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2461 // Otherwise, just return so that the next character will be lexed as a token.
2463 Result.setFlag(Token::LeadingSpace);
2467 //===----------------------------------------------------------------------===//
2468 // Primary Lexing Entry Points
2469 //===----------------------------------------------------------------------===//
2471 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2472 /// uninterpreted string. This switches the lexer out of directive mode.
2473 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2474 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2475 "Must be in a preprocessing directive!");
2478 // CurPtr - Cache BufferPtr in an automatic variable.
2479 const char *CurPtr = BufferPtr;
2481 char Char = getAndAdvanceChar(CurPtr, Tmp);
2485 Result->push_back(Char);
2488 // Found end of file?
2489 if (CurPtr-1 != BufferEnd) {
2490 if (isCodeCompletionPoint(CurPtr-1)) {
2491 PP->CodeCompleteNaturalLanguage();
2496 // Nope, normal character, continue.
2498 Result->push_back(Char);
2505 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2506 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2507 BufferPtr = CurPtr-1;
2509 // Next, lex the character, which should handle the EOD transition.
2511 if (Tmp.is(tok::code_completion)) {
2513 PP->CodeCompleteNaturalLanguage();
2516 assert(Tmp.is(tok::eod) && "Unexpected token!");
2518 // Finally, we're done;
2524 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2525 /// condition, reporting diagnostics and handling other edge cases as required.
2526 /// This returns true if Result contains a token, false if PP.Lex should be
2528 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2529 // If we hit the end of the file while parsing a preprocessor directive,
2530 // end the preprocessor directive first. The next token returned will
2531 // then be the end of file.
2532 if (ParsingPreprocessorDirective) {
2533 // Done parsing the "line".
2534 ParsingPreprocessorDirective = false;
2535 // Update the location of token as well as BufferPtr.
2536 FormTokenWithChars(Result, CurPtr, tok::eod);
2538 // Restore comment saving mode, in case it was disabled for directive.
2540 resetExtendedTokenMode();
2541 return true; // Have a token.
2544 // If we are in raw mode, return this event as an EOF token. Let the caller
2545 // that put us in raw mode handle the event.
2546 if (isLexingRawMode()) {
2547 Result.startToken();
2548 BufferPtr = BufferEnd;
2549 FormTokenWithChars(Result, BufferEnd, tok::eof);
2553 if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
2554 PP->setRecordedPreambleConditionalStack(ConditionalStack);
2555 ConditionalStack.clear();
2558 // Issue diagnostics for unterminated #if and missing newline.
2560 // If we are in a #if directive, emit an error.
2561 while (!ConditionalStack.empty()) {
2562 if (PP->getCodeCompletionFileLoc() != FileLoc)
2563 PP->Diag(ConditionalStack.back().IfLoc,
2564 diag::err_pp_unterminated_conditional);
2565 ConditionalStack.pop_back();
2568 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2570 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2571 DiagnosticsEngine &Diags = PP->getDiagnostics();
2572 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2575 if (LangOpts.CPlusPlus11) {
2576 // C++11 [lex.phases] 2.2 p2
2577 // Prefer the C++98 pedantic compatibility warning over the generic,
2578 // non-extension, user-requested "missing newline at EOF" warning.
2579 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2580 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2582 DiagID = diag::warn_no_newline_eof;
2585 DiagID = diag::ext_no_newline_eof;
2588 Diag(BufferEnd, DiagID)
2589 << FixItHint::CreateInsertion(EndLoc, "\n");
2594 // Finally, let the preprocessor handle this.
2595 return PP->HandleEndOfFile(Result, isPragmaLexer());
2598 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2599 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2600 /// else and 2 if there are no more tokens in the buffer controlled by the
2602 unsigned Lexer::isNextPPTokenLParen() {
2603 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2605 // Switch to 'skipping' mode. This will ensure that we can lex a token
2606 // without emitting diagnostics, disables macro expansion, and will cause EOF
2607 // to return an EOF token instead of popping the include stack.
2608 LexingRawMode = true;
2610 // Save state that can be changed while lexing so that we can restore it.
2611 const char *TmpBufferPtr = BufferPtr;
2612 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2613 bool atStartOfLine = IsAtStartOfLine;
2614 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2615 bool leadingSpace = HasLeadingSpace;
2620 // Restore state that may have changed.
2621 BufferPtr = TmpBufferPtr;
2622 ParsingPreprocessorDirective = inPPDirectiveMode;
2623 HasLeadingSpace = leadingSpace;
2624 IsAtStartOfLine = atStartOfLine;
2625 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2627 // Restore the lexer back to non-skipping mode.
2628 LexingRawMode = false;
2630 if (Tok.is(tok::eof))
2632 return Tok.is(tok::l_paren);
2635 /// \brief Find the end of a version control conflict marker.
2636 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2637 ConflictMarkerKind CMK) {
2638 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2639 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2640 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2641 size_t Pos = RestOfBuffer.find(Terminator);
2642 while (Pos != StringRef::npos) {
2643 // Must occur at start of line.
2645 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2646 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2647 Pos = RestOfBuffer.find(Terminator);
2650 return RestOfBuffer.data()+Pos;
2655 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2656 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2657 /// and recover nicely. This returns true if it is a conflict marker and false
2659 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2660 // Only a conflict marker if it starts at the beginning of a line.
2661 if (CurPtr != BufferStart &&
2662 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2665 // Check to see if we have <<<<<<< or >>>>.
2666 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2667 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2670 // If we have a situation where we don't care about conflict markers, ignore
2672 if (CurrentConflictMarkerState || isLexingRawMode())
2675 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2677 // Check to see if there is an ending marker somewhere in the buffer at the
2678 // start of a line to terminate this conflict marker.
2679 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2680 // We found a match. We are really in a conflict marker.
2681 // Diagnose this, and ignore to the end of line.
2682 Diag(CurPtr, diag::err_conflict_marker);
2683 CurrentConflictMarkerState = Kind;
2685 // Skip ahead to the end of line. We know this exists because the
2686 // end-of-conflict marker starts with \r or \n.
2687 while (*CurPtr != '\r' && *CurPtr != '\n') {
2688 assert(CurPtr != BufferEnd && "Didn't find end of line");
2695 // No end of conflict marker found.
2699 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2700 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2701 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2702 /// the line. This returns true if it is a conflict marker and false if not.
2703 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2704 // Only a conflict marker if it starts at the beginning of a line.
2705 if (CurPtr != BufferStart &&
2706 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2709 // If we have a situation where we don't care about conflict markers, ignore
2711 if (!CurrentConflictMarkerState || isLexingRawMode())
2714 // Check to see if we have the marker (4 characters in a row).
2715 for (unsigned i = 1; i != 4; ++i)
2716 if (CurPtr[i] != CurPtr[0])
2719 // If we do have it, search for the end of the conflict marker. This could
2720 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2721 // be the end of conflict marker.
2722 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2723 CurrentConflictMarkerState)) {
2726 // Skip ahead to the end of line.
2727 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2732 // No longer in the conflict marker.
2733 CurrentConflictMarkerState = CMK_None;
2740 static const char *findPlaceholderEnd(const char *CurPtr,
2741 const char *BufferEnd) {
2742 if (CurPtr == BufferEnd)
2744 BufferEnd -= 1; // Scan until the second last character.
2745 for (; CurPtr != BufferEnd; ++CurPtr) {
2746 if (CurPtr[0] == '#' && CurPtr[1] == '>')
2752 bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
2753 assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
2754 if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
2756 const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
2759 const char *Start = CurPtr - 1;
2760 if (!LangOpts.AllowEditorPlaceholders)
2761 Diag(Start, diag::err_placeholder_in_source);
2762 Result.startToken();
2763 FormTokenWithChars(Result, End, tok::raw_identifier);
2764 Result.setRawIdentifierData(Start);
2765 PP->LookUpIdentifierInfo(Result);
2766 Result.setFlag(Token::IsEditorPlaceholder);
2771 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2772 if (PP && PP->isCodeCompletionEnabled()) {
2773 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2774 return Loc == PP->getCodeCompletionLoc();
2780 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2783 char Kind = getCharAndSize(StartPtr, CharSize);
2785 unsigned NumHexDigits;
2788 else if (Kind == 'U')
2793 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2794 if (Result && !isLexingRawMode())
2795 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2799 const char *CurPtr = StartPtr + CharSize;
2800 const char *KindLoc = &CurPtr[-1];
2802 uint32_t CodePoint = 0;
2803 for (unsigned i = 0; i < NumHexDigits; ++i) {
2804 char C = getCharAndSize(CurPtr, CharSize);
2806 unsigned Value = llvm::hexDigitValue(C);
2808 if (Result && !isLexingRawMode()) {
2810 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2811 << StringRef(KindLoc, 1);
2813 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2815 // If the user wrote \U1234, suggest a fixit to \u.
2816 if (i == 4 && NumHexDigits == 8) {
2817 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2818 Diag(KindLoc, diag::note_ucn_four_not_eight)
2819 << FixItHint::CreateReplacement(URange, "u");
2834 Result->setFlag(Token::HasUCN);
2835 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2838 while (StartPtr != CurPtr)
2839 (void)getAndAdvanceChar(StartPtr, *Result);
2844 // Don't apply C family restrictions to UCNs in assembly mode
2845 if (LangOpts.AsmPreprocessor)
2848 // C99 6.4.3p2: A universal character name shall not specify a character whose
2849 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2850 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2851 // C++11 [lex.charset]p2: If the hexadecimal value for a
2852 // universal-character-name corresponds to a surrogate code point (in the
2853 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2854 // if the hexadecimal value for a universal-character-name outside the
2855 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2856 // string literal corresponds to a control character (in either of the
2857 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2858 // basic source character set, the program is ill-formed.
2859 if (CodePoint < 0xA0) {
2860 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2863 // We don't use isLexingRawMode() here because we need to warn about bad
2864 // UCNs even when skipping preprocessing tokens in a #if block.
2866 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2867 Diag(BufferPtr, diag::err_ucn_control_character);
2869 char C = static_cast<char>(CodePoint);
2870 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2876 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2877 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2878 // We don't use isLexingRawMode() here because we need to diagnose bad
2879 // UCNs even when skipping preprocessing tokens in a #if block.
2881 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2882 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2884 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2892 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2893 const char *CurPtr) {
2894 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2895 UnicodeWhitespaceCharRanges);
2896 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2897 UnicodeWhitespaceChars.contains(C)) {
2898 Diag(BufferPtr, diag::ext_unicode_whitespace)
2899 << makeCharRange(*this, BufferPtr, CurPtr);
2901 Result.setFlag(Token::LeadingSpace);
2907 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2908 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2909 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2910 !PP->isPreprocessedOutput()) {
2911 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2912 makeCharRange(*this, BufferPtr, CurPtr),
2917 return LexIdentifier(Result, CurPtr);
2920 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2921 !PP->isPreprocessedOutput() &&
2922 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2923 // Non-ASCII characters tend to creep into source code unintentionally.
2924 // Instead of letting the parser complain about the unknown token,
2925 // just drop the character.
2926 // Note that we can /only/ do this when the non-ASCII character is actually
2927 // spelled as Unicode, not written as a UCN. The standard requires that
2928 // we not throw away any possible preprocessor tokens, but there's a
2929 // loophole in the mapping of Unicode characters to basic character set
2930 // characters that allows us to map these particular characters to, say,
2932 Diag(BufferPtr, diag::err_non_ascii)
2933 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2939 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2942 FormTokenWithChars(Result, CurPtr, tok::unknown);
2946 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2947 IsAtStartOfLine = Result.isAtStartOfLine();
2948 HasLeadingSpace = Result.hasLeadingSpace();
2949 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2950 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2953 bool Lexer::Lex(Token &Result) {
2954 // Start a new token.
2955 Result.startToken();
2957 // Set up misc whitespace flags for LexTokenInternal.
2958 if (IsAtStartOfLine) {
2959 Result.setFlag(Token::StartOfLine);
2960 IsAtStartOfLine = false;
2963 if (HasLeadingSpace) {
2964 Result.setFlag(Token::LeadingSpace);
2965 HasLeadingSpace = false;
2968 if (HasLeadingEmptyMacro) {
2969 Result.setFlag(Token::LeadingEmptyMacro);
2970 HasLeadingEmptyMacro = false;
2973 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2974 IsAtPhysicalStartOfLine = false;
2975 bool isRawLex = isLexingRawMode();
2977 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2978 // (After the LexTokenInternal call, the lexer might be destroyed.)
2979 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2980 return returnedToken;
2983 /// LexTokenInternal - This implements a simple C family lexer. It is an
2984 /// extremely performance critical piece of code. This assumes that the buffer
2985 /// has a null character at the end of the file. This returns a preprocessing
2986 /// token, not a normal token, as such, it is an internal interface. It assumes
2987 /// that the Flags of result have been cleared before calling this.
2988 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
2990 // New token, can't need cleaning yet.
2991 Result.clearFlag(Token::NeedsCleaning);
2992 Result.setIdentifierInfo(nullptr);
2994 // CurPtr - Cache BufferPtr in an automatic variable.
2995 const char *CurPtr = BufferPtr;
2997 // Small amounts of horizontal whitespace is very common between tokens.
2998 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
3000 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
3003 // If we are keeping whitespace and other tokens, just return what we just
3004 // skipped. The next lexer invocation will return the token after the
3006 if (isKeepWhitespaceMode()) {
3007 FormTokenWithChars(Result, CurPtr, tok::unknown);
3008 // FIXME: The next token will not have LeadingSpace set.
3013 Result.setFlag(Token::LeadingSpace);
3016 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
3018 // Read a character, advancing over it.
3019 char Char = getAndAdvanceChar(CurPtr, Result);
3020 tok::TokenKind Kind;
3024 // Found end of file?
3025 if (CurPtr-1 == BufferEnd)
3026 return LexEndOfFile(Result, CurPtr-1);
3028 // Check if we are performing code completion.
3029 if (isCodeCompletionPoint(CurPtr-1)) {
3030 // Return the code-completion token.
3031 Result.startToken();
3032 FormTokenWithChars(Result, CurPtr, tok::code_completion);
3036 if (!isLexingRawMode())
3037 Diag(CurPtr-1, diag::null_in_file);
3038 Result.setFlag(Token::LeadingSpace);
3039 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3040 return true; // KeepWhitespaceMode
3042 // We know the lexer hasn't changed, so just try again with this lexer.
3043 // (We manually eliminate the tail call to avoid recursion.)
3046 case 26: // DOS & CP/M EOF: "^Z".
3047 // If we're in Microsoft extensions mode, treat this as end of file.
3048 if (LangOpts.MicrosoftExt) {
3049 if (!isLexingRawMode())
3050 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
3051 return LexEndOfFile(Result, CurPtr-1);
3054 // If Microsoft extensions are disabled, this is just random garbage.
3055 Kind = tok::unknown;
3060 // If we are inside a preprocessor directive and we see the end of line,
3061 // we know we are done with the directive, so return an EOD token.
3062 if (ParsingPreprocessorDirective) {
3063 // Done parsing the "line".
3064 ParsingPreprocessorDirective = false;
3066 // Restore comment saving mode, in case it was disabled for directive.
3068 resetExtendedTokenMode();
3070 // Since we consumed a newline, we are back at the start of a line.
3071 IsAtStartOfLine = true;
3072 IsAtPhysicalStartOfLine = true;
3078 // No leading whitespace seen so far.
3079 Result.clearFlag(Token::LeadingSpace);
3081 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3082 return true; // KeepWhitespaceMode
3084 // We only saw whitespace, so just try again with this lexer.
3085 // (We manually eliminate the tail call to avoid recursion.)
3091 SkipHorizontalWhitespace:
3092 Result.setFlag(Token::LeadingSpace);
3093 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3094 return true; // KeepWhitespaceMode
3099 // If the next token is obviously a // or /* */ comment, skip it efficiently
3100 // too (without going through the big switch stmt).
3101 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3102 LangOpts.LineComment &&
3103 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3104 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3105 return true; // There is a token to return.
3106 goto SkipIgnoredUnits;
3107 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3108 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3109 return true; // There is a token to return.
3110 goto SkipIgnoredUnits;
3111 } else if (isHorizontalWhitespace(*CurPtr)) {
3112 goto SkipHorizontalWhitespace;
3114 // We only saw whitespace, so just try again with this lexer.
3115 // (We manually eliminate the tail call to avoid recursion.)
3118 // C99 6.4.4.1: Integer Constants.
3119 // C99 6.4.4.2: Floating Constants.
3120 case '0': case '1': case '2': case '3': case '4':
3121 case '5': case '6': case '7': case '8': case '9':
3122 // Notify MIOpt that we read a non-whitespace/non-comment token.
3124 return LexNumericConstant(Result, CurPtr);
3126 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3127 // Notify MIOpt that we read a non-whitespace/non-comment token.
3130 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3131 Char = getCharAndSize(CurPtr, SizeTmp);
3133 // UTF-16 string literal
3135 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3136 tok::utf16_string_literal);
3138 // UTF-16 character constant
3140 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3141 tok::utf16_char_constant);
3143 // UTF-16 raw string literal
3144 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3145 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3146 return LexRawStringLiteral(Result,
3147 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3149 tok::utf16_string_literal);
3152 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3154 // UTF-8 string literal
3156 return LexStringLiteral(Result,
3157 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3159 tok::utf8_string_literal);
3160 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3161 return LexCharConstant(
3162 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3164 tok::utf8_char_constant);
3166 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3168 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3169 // UTF-8 raw string literal
3171 return LexRawStringLiteral(Result,
3172 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3175 tok::utf8_string_literal);
3181 // treat u like the start of an identifier.
3182 return LexIdentifier(Result, CurPtr);
3184 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3185 // Notify MIOpt that we read a non-whitespace/non-comment token.
3188 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3189 Char = getCharAndSize(CurPtr, SizeTmp);
3191 // UTF-32 string literal
3193 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3194 tok::utf32_string_literal);
3196 // UTF-32 character constant
3198 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3199 tok::utf32_char_constant);
3201 // UTF-32 raw string literal
3202 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3203 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3204 return LexRawStringLiteral(Result,
3205 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3207 tok::utf32_string_literal);
3210 // treat U like the start of an identifier.
3211 return LexIdentifier(Result, CurPtr);
3213 case 'R': // Identifier or C++0x raw string literal
3214 // Notify MIOpt that we read a non-whitespace/non-comment token.
3217 if (LangOpts.CPlusPlus11) {
3218 Char = getCharAndSize(CurPtr, SizeTmp);
3221 return LexRawStringLiteral(Result,
3222 ConsumeChar(CurPtr, SizeTmp, Result),
3223 tok::string_literal);
3226 // treat R like the start of an identifier.
3227 return LexIdentifier(Result, CurPtr);
3229 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3230 // Notify MIOpt that we read a non-whitespace/non-comment token.
3232 Char = getCharAndSize(CurPtr, SizeTmp);
3234 // Wide string literal.
3236 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3237 tok::wide_string_literal);
3239 // Wide raw string literal.
3240 if (LangOpts.CPlusPlus11 && Char == 'R' &&
3241 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3242 return LexRawStringLiteral(Result,
3243 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3245 tok::wide_string_literal);
3247 // Wide character constant.
3249 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3250 tok::wide_char_constant);
3251 // FALL THROUGH, treating L like the start of an identifier.
3254 // C99 6.4.2: Identifiers.
3255 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3256 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3257 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3258 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3259 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3260 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3261 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3262 case 'v': case 'w': case 'x': case 'y': case 'z':
3264 // Notify MIOpt that we read a non-whitespace/non-comment token.
3266 return LexIdentifier(Result, CurPtr);
3268 case '$': // $ in identifiers.
3269 if (LangOpts.DollarIdents) {
3270 if (!isLexingRawMode())
3271 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3272 // Notify MIOpt that we read a non-whitespace/non-comment token.
3274 return LexIdentifier(Result, CurPtr);
3277 Kind = tok::unknown;
3280 // C99 6.4.4: Character Constants.
3282 // Notify MIOpt that we read a non-whitespace/non-comment token.
3284 return LexCharConstant(Result, CurPtr, tok::char_constant);
3286 // C99 6.4.5: String Literals.
3288 // Notify MIOpt that we read a non-whitespace/non-comment token.
3290 return LexStringLiteral(Result, CurPtr, tok::string_literal);
3292 // C99 6.4.6: Punctuators.
3294 Kind = tok::question;
3297 Kind = tok::l_square;
3300 Kind = tok::r_square;
3303 Kind = tok::l_paren;
3306 Kind = tok::r_paren;
3309 Kind = tok::l_brace;
3312 Kind = tok::r_brace;
3315 Char = getCharAndSize(CurPtr, SizeTmp);
3316 if (Char >= '0' && Char <= '9') {
3317 // Notify MIOpt that we read a non-whitespace/non-comment token.
3320 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3321 } else if (LangOpts.CPlusPlus && Char == '*') {
3322 Kind = tok::periodstar;
3324 } else if (Char == '.' &&
3325 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3326 Kind = tok::ellipsis;
3327 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3334 Char = getCharAndSize(CurPtr, SizeTmp);
3337 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3338 } else if (Char == '=') {
3339 Kind = tok::ampequal;
3340 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3346 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3347 Kind = tok::starequal;
3348 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3354 Char = getCharAndSize(CurPtr, SizeTmp);
3356 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3357 Kind = tok::plusplus;
3358 } else if (Char == '=') {
3359 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3360 Kind = tok::plusequal;
3366 Char = getCharAndSize(CurPtr, SizeTmp);
3367 if (Char == '-') { // --
3368 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3369 Kind = tok::minusminus;
3370 } else if (Char == '>' && LangOpts.CPlusPlus &&
3371 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3372 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3374 Kind = tok::arrowstar;
3375 } else if (Char == '>') { // ->
3376 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3378 } else if (Char == '=') { // -=
3379 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3380 Kind = tok::minusequal;
3389 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3390 Kind = tok::exclaimequal;
3391 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3393 Kind = tok::exclaim;
3398 Char = getCharAndSize(CurPtr, SizeTmp);
3399 if (Char == '/') { // Line comment.
3400 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3401 // want to lex this as a comment. There is one problem with this though,
3402 // that in one particular corner case, this can change the behavior of the
3403 // resultant program. For example, In "foo //**/ bar", C89 would lex
3404 // this as "foo / bar" and langauges with Line comments would lex it as
3405 // "foo". Check to see if the character after the second slash is a '*'.
3406 // If so, we will lex that as a "/" instead of the start of a comment.
3407 // However, we never do this if we are just preprocessing.
3408 bool TreatAsComment = LangOpts.LineComment &&
3409 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3410 if (!TreatAsComment)
3411 if (!(PP && PP->isPreprocessedOutput()))
3412 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3414 if (TreatAsComment) {
3415 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3416 TokAtPhysicalStartOfLine))
3417 return true; // There is a token to return.
3419 // It is common for the tokens immediately after a // comment to be
3420 // whitespace (indentation for the next line). Instead of going through
3421 // the big switch, handle it efficiently now.
3422 goto SkipIgnoredUnits;
3426 if (Char == '*') { // /**/ comment.
3427 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3428 TokAtPhysicalStartOfLine))
3429 return true; // There is a token to return.
3431 // We only saw whitespace, so just try again with this lexer.
3432 // (We manually eliminate the tail call to avoid recursion.)
3437 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3438 Kind = tok::slashequal;
3444 Char = getCharAndSize(CurPtr, SizeTmp);
3446 Kind = tok::percentequal;
3447 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3448 } else if (LangOpts.Digraphs && Char == '>') {
3449 Kind = tok::r_brace; // '%>' -> '}'
3450 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3451 } else if (LangOpts.Digraphs && Char == ':') {
3452 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3453 Char = getCharAndSize(CurPtr, SizeTmp);
3454 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3455 Kind = tok::hashhash; // '%:%:' -> '##'
3456 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3458 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3459 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3460 if (!isLexingRawMode())
3461 Diag(BufferPtr, diag::ext_charize_microsoft);
3463 } else { // '%:' -> '#'
3464 // We parsed a # character. If this occurs at the start of the line,
3465 // it's actually the start of a preprocessing directive. Callback to
3466 // the preprocessor to handle it.
3467 // TODO: -fpreprocessed mode??
3468 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3469 goto HandleDirective;
3474 Kind = tok::percent;
3478 Char = getCharAndSize(CurPtr, SizeTmp);
3479 if (ParsingFilename) {
3480 return LexAngledStringLiteral(Result, CurPtr);
3481 } else if (Char == '<') {
3482 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3484 Kind = tok::lesslessequal;
3485 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3487 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3488 // If this is actually a '<<<<<<<' version control conflict marker,
3489 // recognize it as such and recover nicely.
3491 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3492 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3495 } else if (LangOpts.CUDA && After == '<') {
3496 Kind = tok::lesslessless;
3497 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3500 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3501 Kind = tok::lessless;
3503 } else if (Char == '=') {
3504 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3505 Kind = tok::lessequal;
3506 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3507 if (LangOpts.CPlusPlus11 &&
3508 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3509 // C++0x [lex.pptoken]p3:
3510 // Otherwise, if the next three characters are <:: and the subsequent
3511 // character is neither : nor >, the < is treated as a preprocessor
3512 // token by itself and not as the first character of the alternative
3515 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3516 if (After != ':' && After != '>') {
3518 if (!isLexingRawMode())
3519 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3524 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3525 Kind = tok::l_square;
3526 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3527 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3528 Kind = tok::l_brace;
3529 } else if (Char == '#' && lexEditorPlaceholder(Result, CurPtr)) {
3536 Char = getCharAndSize(CurPtr, SizeTmp);
3538 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3539 Kind = tok::greaterequal;
3540 } else if (Char == '>') {
3541 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3543 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3545 Kind = tok::greatergreaterequal;
3546 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3547 // If this is actually a '>>>>' conflict marker, recognize it as such
3548 // and recover nicely.
3550 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3551 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3553 } else if (LangOpts.CUDA && After == '>') {
3554 Kind = tok::greatergreatergreater;
3555 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3558 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3559 Kind = tok::greatergreater;
3562 Kind = tok::greater;
3566 Char = getCharAndSize(CurPtr, SizeTmp);
3568 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3569 Kind = tok::caretequal;
3570 } else if (LangOpts.OpenCL && Char == '^') {
3571 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3572 Kind = tok::caretcaret;
3578 Char = getCharAndSize(CurPtr, SizeTmp);
3580 Kind = tok::pipeequal;
3581 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3582 } else if (Char == '|') {
3583 // If this is '|||||||' and we're in a conflict marker, ignore it.
3584 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3586 Kind = tok::pipepipe;
3587 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3593 Char = getCharAndSize(CurPtr, SizeTmp);
3594 if (LangOpts.Digraphs && Char == '>') {
3595 Kind = tok::r_square; // ':>' -> ']'
3596 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3597 } else if (LangOpts.CPlusPlus && Char == ':') {
3598 Kind = tok::coloncolon;
3599 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3608 Char = getCharAndSize(CurPtr, SizeTmp);
3610 // If this is '====' and we're in a conflict marker, ignore it.
3611 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3614 Kind = tok::equalequal;
3615 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3624 Char = getCharAndSize(CurPtr, SizeTmp);
3626 Kind = tok::hashhash;
3627 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3628 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3630 if (!isLexingRawMode())
3631 Diag(BufferPtr, diag::ext_charize_microsoft);
3632 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3634 // We parsed a # character. If this occurs at the start of the line,
3635 // it's actually the start of a preprocessing directive. Callback to
3636 // the preprocessor to handle it.
3637 // TODO: -fpreprocessed mode??
3638 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3639 goto HandleDirective;
3646 // Objective C support.
3647 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3650 Kind = tok::unknown;
3653 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3655 if (!LangOpts.AsmPreprocessor) {
3656 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3657 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3658 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3659 return true; // KeepWhitespaceMode
3661 // We only saw whitespace, so just try again with this lexer.
3662 // (We manually eliminate the tail call to avoid recursion.)
3666 return LexUnicode(Result, CodePoint, CurPtr);
3670 Kind = tok::unknown;
3674 if (isASCII(Char)) {
3675 Kind = tok::unknown;
3679 llvm::UTF32 CodePoint;
3681 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3682 // an escaped newline.
3684 llvm::ConversionResult Status =
3685 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
3686 (const llvm::UTF8 *)BufferEnd,
3688 llvm::strictConversion);
3689 if (Status == llvm::conversionOK) {
3690 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3691 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3692 return true; // KeepWhitespaceMode
3694 // We only saw whitespace, so just try again with this lexer.
3695 // (We manually eliminate the tail call to avoid recursion.)
3698 return LexUnicode(Result, CodePoint, CurPtr);
3701 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3702 PP->isPreprocessedOutput()) {
3704 Kind = tok::unknown;
3708 // Non-ASCII characters tend to creep into source code unintentionally.
3709 // Instead of letting the parser complain about the unknown token,
3710 // just diagnose the invalid UTF-8, then drop the character.
3711 Diag(CurPtr, diag::err_invalid_utf8);
3713 BufferPtr = CurPtr+1;
3714 // We're pretending the character didn't exist, so just try again with
3716 // (We manually eliminate the tail call to avoid recursion.)
3721 // Notify MIOpt that we read a non-whitespace/non-comment token.
3724 // Update the location of token as well as BufferPtr.
3725 FormTokenWithChars(Result, CurPtr, Kind);
3729 // We parsed a # character and it's the start of a preprocessing directive.
3731 FormTokenWithChars(Result, CurPtr, tok::hash);
3732 PP->HandleDirective(Result);
3734 if (PP->hadModuleLoaderFatalFailure()) {
3735 // With a fatal failure in the module loader, we abort parsing.
3736 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3740 // We parsed the directive; lex a token with the new state.