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/SourceManager.h"
18 #include "clang/Lex/CodeCompletionHandler.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/LiteralSupport.h"
21 #include "clang/Lex/Preprocessor.h"
22 #include "llvm/ADT/STLExtras.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/MemoryBuffer.h"
29 using namespace clang;
31 //===----------------------------------------------------------------------===//
32 // Token Class Implementation
33 //===----------------------------------------------------------------------===//
35 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
36 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
37 if (IdentifierInfo *II = getIdentifierInfo())
38 return II->getObjCKeywordID() == objcKey;
42 /// getObjCKeywordID - Return the ObjC keyword kind.
43 tok::ObjCKeywordKind Token::getObjCKeywordID() const {
44 IdentifierInfo *specId = getIdentifierInfo();
45 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
49 //===----------------------------------------------------------------------===//
50 // Lexer Class Implementation
51 //===----------------------------------------------------------------------===//
53 void Lexer::anchor() { }
55 void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
57 BufferStart = BufStart;
61 assert(BufEnd[0] == 0 &&
62 "We assume that the input buffer has a null character at the end"
63 " to simplify lexing!");
65 // Check whether we have a BOM in the beginning of the buffer. If yes - act
66 // accordingly. Right now we support only UTF-8 with and without BOM, so, just
67 // skip the UTF-8 BOM if it's present.
68 if (BufferStart == BufferPtr) {
69 // Determine the size of the BOM.
70 StringRef Buf(BufferStart, BufferEnd - BufferStart);
71 size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
72 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
76 BufferPtr += BOMLength;
79 Is_PragmaLexer = false;
80 CurrentConflictMarkerState = CMK_None;
82 // Start of the file is a start of line.
83 IsAtStartOfLine = true;
84 IsAtPhysicalStartOfLine = true;
86 HasLeadingSpace = false;
87 HasLeadingEmptyMacro = false;
89 // We are not after parsing a #.
90 ParsingPreprocessorDirective = false;
92 // We are not after parsing #include.
93 ParsingFilename = false;
95 // We are not in raw mode. Raw mode disables diagnostics and interpretation
96 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
97 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
98 // or otherwise skipping over tokens.
99 LexingRawMode = false;
101 // Default to not keeping comments.
102 ExtendedTokenMode = 0;
105 /// Lexer constructor - Create a new lexer object for the specified buffer
106 /// with the specified preprocessor managing the lexing process. This lexer
107 /// assumes that the associated file buffer and Preprocessor objects will
108 /// outlive it, so it doesn't take ownership of either of them.
109 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP)
110 : PreprocessorLexer(&PP, FID),
111 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
112 LangOpts(PP.getLangOpts()) {
114 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(),
115 InputFile->getBufferEnd());
117 resetExtendedTokenMode();
120 void Lexer::resetExtendedTokenMode() {
121 assert(PP && "Cannot reset token mode without a preprocessor");
122 if (LangOpts.TraditionalCPP)
123 SetKeepWhitespaceMode(true);
125 SetCommentRetentionState(PP->getCommentRetentionState());
128 /// Lexer constructor - Create a new raw lexer object. This object is only
129 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
130 /// range will outlive it, so it doesn't take ownership of it.
131 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
132 const char *BufStart, const char *BufPtr, const char *BufEnd)
133 : FileLoc(fileloc), LangOpts(langOpts) {
135 InitLexer(BufStart, BufPtr, BufEnd);
137 // We *are* in raw mode.
138 LexingRawMode = true;
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(FileID FID, const llvm::MemoryBuffer *FromFile,
145 const SourceManager &SM, const LangOptions &langOpts)
146 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(),
147 FromFile->getBufferStart(), FromFile->getBufferEnd()) {}
149 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
150 /// _Pragma expansion. This has a variety of magic semantics that this method
151 /// sets up. It returns a new'd Lexer that must be delete'd when done.
153 /// On entrance to this routine, TokStartLoc is a macro location which has a
154 /// spelling loc that indicates the bytes to be lexed for the token and an
155 /// expansion location that indicates where all lexed tokens should be
158 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
159 /// normal lexer that remaps tokens as they fly by. This would require making
160 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
161 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
162 /// out of the critical path of the lexer!
164 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
165 SourceLocation ExpansionLocStart,
166 SourceLocation ExpansionLocEnd,
167 unsigned TokLen, Preprocessor &PP) {
168 SourceManager &SM = PP.getSourceManager();
170 // Create the lexer as if we were going to lex the file normally.
171 FileID SpellingFID = SM.getFileID(SpellingLoc);
172 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
173 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
175 // Now that the lexer is created, change the start/end locations so that we
176 // just lex the subsection of the file that we want. This is lexing from a
178 const char *StrData = SM.getCharacterData(SpellingLoc);
180 L->BufferPtr = StrData;
181 L->BufferEnd = StrData+TokLen;
182 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
184 // Set the SourceLocation with the remapping information. This ensures that
185 // GetMappedTokenLoc will remap the tokens as they are lexed.
186 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
188 ExpansionLocEnd, TokLen);
190 // Ensure that the lexer thinks it is inside a directive, so that end \n will
191 // return an EOD token.
192 L->ParsingPreprocessorDirective = true;
194 // This lexer really is for _Pragma.
195 L->Is_PragmaLexer = true;
200 /// Stringify - Convert the specified string into a C string, with surrounding
201 /// ""'s, and with escaped \ and " characters.
202 std::string Lexer::Stringify(StringRef Str, bool Charify) {
203 std::string Result = Str;
204 char Quote = Charify ? '\'' : '"';
205 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
206 if (Result[i] == '\\' || Result[i] == Quote) {
207 Result.insert(Result.begin()+i, '\\');
214 /// Stringify - Convert the specified string into a C string by escaping '\'
215 /// and " characters. This does not add surrounding ""'s to the string.
216 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
217 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
218 if (Str[i] == '\\' || Str[i] == '"') {
219 Str.insert(Str.begin()+i, '\\');
225 //===----------------------------------------------------------------------===//
227 //===----------------------------------------------------------------------===//
229 /// \brief Slow case of getSpelling. Extract the characters comprising the
230 /// spelling of this token from the provided input buffer.
231 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
232 const LangOptions &LangOpts, char *Spelling) {
233 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
236 const char *BufEnd = BufPtr + Tok.getLength();
238 if (tok::isStringLiteral(Tok.getKind())) {
239 // Munch the encoding-prefix and opening double-quote.
240 while (BufPtr < BufEnd) {
242 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
245 if (Spelling[Length - 1] == '"')
249 // Raw string literals need special handling; trigraph expansion and line
250 // splicing do not occur within their d-char-sequence nor within their
253 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
254 // Search backwards from the end of the token to find the matching closing
256 const char *RawEnd = BufEnd;
257 do --RawEnd; while (*RawEnd != '"');
258 size_t RawLength = RawEnd - BufPtr + 1;
260 // Everything between the quotes is included verbatim in the spelling.
261 memcpy(Spelling + Length, BufPtr, RawLength);
265 // The rest of the token is lexed normally.
269 while (BufPtr < BufEnd) {
271 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
275 assert(Length < Tok.getLength() &&
276 "NeedsCleaning flag set on token that didn't need cleaning!");
280 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
281 /// token are the characters used to represent the token in the source file
282 /// after trigraph expansion and escaped-newline folding. In particular, this
283 /// wants to get the true, uncanonicalized, spelling of things like digraphs
285 StringRef Lexer::getSpelling(SourceLocation loc,
286 SmallVectorImpl<char> &buffer,
287 const SourceManager &SM,
288 const LangOptions &options,
290 // Break down the source location.
291 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
293 // Try to the load the file buffer.
294 bool invalidTemp = false;
295 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
297 if (invalid) *invalid = true;
301 const char *tokenBegin = file.data() + locInfo.second;
303 // Lex from the start of the given location.
304 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
305 file.begin(), tokenBegin, file.end());
307 lexer.LexFromRawLexer(token);
309 unsigned length = token.getLength();
311 // Common case: no need for cleaning.
312 if (!token.needsCleaning())
313 return StringRef(tokenBegin, length);
315 // Hard case, we need to relex the characters into the string.
316 buffer.resize(length);
317 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
318 return StringRef(buffer.data(), buffer.size());
321 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
322 /// token are the characters used to represent the token in the source file
323 /// after trigraph expansion and escaped-newline folding. In particular, this
324 /// wants to get the true, uncanonicalized, spelling of things like digraphs
326 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
327 const LangOptions &LangOpts, bool *Invalid) {
328 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
330 bool CharDataInvalid = false;
331 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
334 *Invalid = CharDataInvalid;
336 return std::string();
338 // If this token contains nothing interesting, return it directly.
339 if (!Tok.needsCleaning())
340 return std::string(TokStart, TokStart + Tok.getLength());
343 Result.resize(Tok.getLength());
344 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
348 /// getSpelling - This method is used to get the spelling of a token into a
349 /// preallocated buffer, instead of as an std::string. The caller is required
350 /// to allocate enough space for the token, which is guaranteed to be at least
351 /// Tok.getLength() bytes long. The actual length of the token is returned.
353 /// Note that this method may do two possible things: it may either fill in
354 /// the buffer specified with characters, or it may *change the input pointer*
355 /// to point to a constant buffer with the data already in it (avoiding a
356 /// copy). The caller is not allowed to modify the returned buffer pointer
357 /// if an internal buffer is returned.
358 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
359 const SourceManager &SourceMgr,
360 const LangOptions &LangOpts, bool *Invalid) {
361 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
363 const char *TokStart = nullptr;
364 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
365 if (Tok.is(tok::raw_identifier))
366 TokStart = Tok.getRawIdentifier().data();
367 else if (!Tok.hasUCN()) {
368 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
369 // Just return the string from the identifier table, which is very quick.
370 Buffer = II->getNameStart();
371 return II->getLength();
375 // NOTE: this can be checked even after testing for an IdentifierInfo.
377 TokStart = Tok.getLiteralData();
380 // Compute the start of the token in the input lexer buffer.
381 bool CharDataInvalid = false;
382 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
384 *Invalid = CharDataInvalid;
385 if (CharDataInvalid) {
391 // If this token contains nothing interesting, return it directly.
392 if (!Tok.needsCleaning()) {
394 return Tok.getLength();
397 // Otherwise, hard case, relex the characters into the string.
398 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
402 /// MeasureTokenLength - Relex the token at the specified location and return
403 /// its length in bytes in the input file. If the token needs cleaning (e.g.
404 /// includes a trigraph or an escaped newline) then this count includes bytes
405 /// that are part of that.
406 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
407 const SourceManager &SM,
408 const LangOptions &LangOpts) {
410 if (getRawToken(Loc, TheTok, SM, LangOpts))
412 return TheTok.getLength();
415 /// \brief Relex the token at the specified location.
416 /// \returns true if there was a failure, false on success.
417 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
418 const SourceManager &SM,
419 const LangOptions &LangOpts,
420 bool IgnoreWhiteSpace) {
421 // TODO: this could be special cased for common tokens like identifiers, ')',
422 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
423 // all obviously single-char tokens. This could use
424 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
427 // If this comes from a macro expansion, we really do want the macro name, not
428 // the token this macro expanded to.
429 Loc = SM.getExpansionLoc(Loc);
430 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
431 bool Invalid = false;
432 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
436 const char *StrData = Buffer.data()+LocInfo.second;
438 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
441 // Create a lexer starting at the beginning of this token.
442 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
443 Buffer.begin(), StrData, Buffer.end());
444 TheLexer.SetCommentRetentionState(true);
445 TheLexer.LexFromRawLexer(Result);
449 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
450 const SourceManager &SM,
451 const LangOptions &LangOpts) {
452 assert(Loc.isFileID());
453 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
454 if (LocInfo.first.isInvalid())
457 bool Invalid = false;
458 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
462 // Back up from the current location until we hit the beginning of a line
463 // (or the buffer). We'll relex from that point.
464 const char *BufStart = Buffer.data();
465 if (LocInfo.second >= Buffer.size())
468 const char *StrData = BufStart+LocInfo.second;
469 if (StrData[0] == '\n' || StrData[0] == '\r')
472 const char *LexStart = StrData;
473 while (LexStart != BufStart) {
474 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
482 // Create a lexer starting at the beginning of this token.
483 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
484 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
485 TheLexer.SetCommentRetentionState(true);
487 // Lex tokens until we find the token that contains the source location.
490 TheLexer.LexFromRawLexer(TheTok);
492 if (TheLexer.getBufferLocation() > StrData) {
493 // Lexing this token has taken the lexer past the source location we're
494 // looking for. If the current token encompasses our source location,
495 // return the beginning of that token.
496 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
497 return TheTok.getLocation();
499 // We ended up skipping over the source location entirely, which means
500 // that it points into whitespace. We're done here.
503 } while (TheTok.getKind() != tok::eof);
505 // We've passed our source location; just return the original source location.
509 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
510 const SourceManager &SM,
511 const LangOptions &LangOpts) {
513 return getBeginningOfFileToken(Loc, SM, LangOpts);
515 if (!SM.isMacroArgExpansion(Loc))
518 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
519 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
520 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
521 std::pair<FileID, unsigned> BeginFileLocInfo
522 = SM.getDecomposedLoc(BeginFileLoc);
523 assert(FileLocInfo.first == BeginFileLocInfo.first &&
524 FileLocInfo.second >= BeginFileLocInfo.second);
525 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
529 enum PreambleDirectiveKind {
537 std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer,
538 const LangOptions &LangOpts,
540 // Create a lexer starting at the beginning of the file. Note that we use a
541 // "fake" file source location at offset 1 so that the lexer will track our
542 // position within the file.
543 const unsigned StartOffset = 1;
544 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
545 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
547 TheLexer.SetCommentRetentionState(true);
549 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
550 SourceLocation StartLoc = TheLexer.getSourceLocation();
552 bool InPreprocessorDirective = false;
555 unsigned IfCount = 0;
556 SourceLocation ActiveCommentLoc;
558 unsigned MaxLineOffset = 0;
560 const char *CurPtr = Buffer.begin();
561 unsigned CurLine = 0;
562 while (CurPtr != Buffer.end()) {
566 if (CurLine == MaxLines)
570 if (CurPtr != Buffer.end())
571 MaxLineOffset = CurPtr - Buffer.begin();
575 TheLexer.LexFromRawLexer(TheTok);
577 if (InPreprocessorDirective) {
578 // If we've hit the end of the file, we're done.
579 if (TheTok.getKind() == tok::eof) {
583 // If we haven't hit the end of the preprocessor directive, skip this
585 if (!TheTok.isAtStartOfLine())
588 // We've passed the end of the preprocessor directive, and will look
589 // at this token again below.
590 InPreprocessorDirective = false;
593 // Keep track of the # of lines in the preamble.
594 if (TheTok.isAtStartOfLine()) {
595 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
597 // If we were asked to limit the number of lines in the preamble,
598 // and we're about to exceed that limit, we're done.
599 if (MaxLineOffset && TokOffset >= MaxLineOffset)
603 // Comments are okay; skip over them.
604 if (TheTok.getKind() == tok::comment) {
605 if (ActiveCommentLoc.isInvalid())
606 ActiveCommentLoc = TheTok.getLocation();
610 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
611 // This is the start of a preprocessor directive.
612 Token HashTok = TheTok;
613 InPreprocessorDirective = true;
614 ActiveCommentLoc = SourceLocation();
616 // Figure out which directive this is. Since we're lexing raw tokens,
617 // we don't have an identifier table available. Instead, just look at
618 // the raw identifier to recognize and categorize preprocessor directives.
619 TheLexer.LexFromRawLexer(TheTok);
620 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
621 StringRef Keyword = TheTok.getRawIdentifier();
622 PreambleDirectiveKind PDK
623 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
624 .Case("include", PDK_Skipped)
625 .Case("__include_macros", PDK_Skipped)
626 .Case("define", PDK_Skipped)
627 .Case("undef", PDK_Skipped)
628 .Case("line", PDK_Skipped)
629 .Case("error", PDK_Skipped)
630 .Case("pragma", PDK_Skipped)
631 .Case("import", PDK_Skipped)
632 .Case("include_next", PDK_Skipped)
633 .Case("warning", PDK_Skipped)
634 .Case("ident", PDK_Skipped)
635 .Case("sccs", PDK_Skipped)
636 .Case("assert", PDK_Skipped)
637 .Case("unassert", PDK_Skipped)
638 .Case("if", PDK_StartIf)
639 .Case("ifdef", PDK_StartIf)
640 .Case("ifndef", PDK_StartIf)
641 .Case("elif", PDK_Skipped)
642 .Case("else", PDK_Skipped)
643 .Case("endif", PDK_EndIf)
644 .Default(PDK_Unknown);
652 IfStartTok = HashTok;
658 // Mismatched #endif. The preamble ends here.
666 // We don't know what this directive is; stop at the '#'.
671 // We only end up here if we didn't recognize the preprocessor
672 // directive or it was one that can't occur in the preamble at this
673 // point. Roll back the current token to the location of the '#'.
674 InPreprocessorDirective = false;
678 // We hit a token that we don't recognize as being in the
679 // "preprocessing only" part of the file, so we're no longer in
686 End = IfStartTok.getLocation();
687 else if (ActiveCommentLoc.isValid())
688 End = ActiveCommentLoc; // don't truncate a decl comment.
690 End = TheTok.getLocation();
692 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
693 IfCount? IfStartTok.isAtStartOfLine()
694 : TheTok.isAtStartOfLine());
698 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
699 /// token, return a new location that specifies a character within the token.
700 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
702 const SourceManager &SM,
703 const LangOptions &LangOpts) {
704 // Figure out how many physical characters away the specified expansion
705 // character is. This needs to take into consideration newlines and
707 bool Invalid = false;
708 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
710 // If they request the first char of the token, we're trivially done.
711 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
714 unsigned PhysOffset = 0;
716 // The usual case is that tokens don't contain anything interesting. Skip
717 // over the uninteresting characters. If a token only consists of simple
718 // chars, this method is extremely fast.
719 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
721 return TokStart.getLocWithOffset(PhysOffset);
727 // If we have a character that may be a trigraph or escaped newline, use a
728 // lexer to parse it correctly.
729 for (; CharNo; --CharNo) {
731 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
736 // Final detail: if we end up on an escaped newline, we want to return the
737 // location of the actual byte of the token. For example foo\<newline>bar
738 // advanced by 3 should return the location of b, not of \\. One compounding
739 // detail of this is that the escape may be made by a trigraph.
740 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
741 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
743 return TokStart.getLocWithOffset(PhysOffset);
746 /// \brief Computes the source location just past the end of the
747 /// token at this source location.
749 /// This routine can be used to produce a source location that
750 /// points just past the end of the token referenced by \p Loc, and
751 /// is generally used when a diagnostic needs to point just after a
752 /// token where it expected something different that it received. If
753 /// the returned source location would not be meaningful (e.g., if
754 /// it points into a macro), this routine returns an invalid
757 /// \param Offset an offset from the end of the token, where the source
758 /// location should refer to. The default offset (0) produces a source
759 /// location pointing just past the end of the token; an offset of 1 produces
760 /// a source location pointing to the last character in the token, etc.
761 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
762 const SourceManager &SM,
763 const LangOptions &LangOpts) {
765 return SourceLocation();
767 if (Loc.isMacroID()) {
768 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
769 return SourceLocation(); // Points inside the macro expansion.
772 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
778 return Loc.getLocWithOffset(Len);
781 /// \brief Returns true if the given MacroID location points at the first
782 /// token of the macro expansion.
783 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
784 const SourceManager &SM,
785 const LangOptions &LangOpts,
786 SourceLocation *MacroBegin) {
787 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
789 SourceLocation expansionLoc;
790 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
793 if (expansionLoc.isFileID()) {
794 // No other macro expansions, this is the first.
796 *MacroBegin = expansionLoc;
800 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
803 /// \brief Returns true if the given MacroID location points at the last
804 /// token of the macro expansion.
805 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
806 const SourceManager &SM,
807 const LangOptions &LangOpts,
808 SourceLocation *MacroEnd) {
809 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
811 SourceLocation spellLoc = SM.getSpellingLoc(loc);
812 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
816 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
817 SourceLocation expansionLoc;
818 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
821 if (expansionLoc.isFileID()) {
822 // No other macro expansions.
824 *MacroEnd = expansionLoc;
828 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
831 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
832 const SourceManager &SM,
833 const LangOptions &LangOpts) {
834 SourceLocation Begin = Range.getBegin();
835 SourceLocation End = Range.getEnd();
836 assert(Begin.isFileID() && End.isFileID());
837 if (Range.isTokenRange()) {
838 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
840 return CharSourceRange();
843 // Break down the source locations.
846 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
848 return CharSourceRange();
851 if (!SM.isInFileID(End, FID, &EndOffs) ||
853 return CharSourceRange();
855 return CharSourceRange::getCharRange(Begin, End);
858 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
859 const SourceManager &SM,
860 const LangOptions &LangOpts) {
861 SourceLocation Begin = Range.getBegin();
862 SourceLocation End = Range.getEnd();
863 if (Begin.isInvalid() || End.isInvalid())
864 return CharSourceRange();
866 if (Begin.isFileID() && End.isFileID())
867 return makeRangeFromFileLocs(Range, SM, LangOpts);
869 if (Begin.isMacroID() && End.isFileID()) {
870 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
871 return CharSourceRange();
872 Range.setBegin(Begin);
873 return makeRangeFromFileLocs(Range, SM, LangOpts);
876 if (Begin.isFileID() && End.isMacroID()) {
877 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
879 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
881 return CharSourceRange();
883 return makeRangeFromFileLocs(Range, SM, LangOpts);
886 assert(Begin.isMacroID() && End.isMacroID());
887 SourceLocation MacroBegin, MacroEnd;
888 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
889 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
891 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
893 Range.setBegin(MacroBegin);
894 Range.setEnd(MacroEnd);
895 return makeRangeFromFileLocs(Range, SM, LangOpts);
898 bool Invalid = false;
899 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
902 return CharSourceRange();
904 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
905 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
908 return CharSourceRange();
910 if (EndEntry.getExpansion().isMacroArgExpansion() &&
911 BeginEntry.getExpansion().getExpansionLocStart() ==
912 EndEntry.getExpansion().getExpansionLocStart()) {
913 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
914 Range.setEnd(SM.getImmediateSpellingLoc(End));
915 return makeFileCharRange(Range, SM, LangOpts);
919 return CharSourceRange();
922 StringRef Lexer::getSourceText(CharSourceRange Range,
923 const SourceManager &SM,
924 const LangOptions &LangOpts,
926 Range = makeFileCharRange(Range, SM, LangOpts);
927 if (Range.isInvalid()) {
928 if (Invalid) *Invalid = true;
932 // Break down the source location.
933 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
934 if (beginInfo.first.isInvalid()) {
935 if (Invalid) *Invalid = true;
940 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
941 beginInfo.second > EndOffs) {
942 if (Invalid) *Invalid = true;
946 // Try to the load the file buffer.
947 bool invalidTemp = false;
948 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
950 if (Invalid) *Invalid = true;
954 if (Invalid) *Invalid = false;
955 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
958 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
959 const SourceManager &SM,
960 const LangOptions &LangOpts) {
961 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
963 // Find the location of the immediate macro expansion.
965 FileID FID = SM.getFileID(Loc);
966 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
967 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
968 Loc = Expansion.getExpansionLocStart();
969 if (!Expansion.isMacroArgExpansion())
972 // For macro arguments we need to check that the argument did not come
973 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
975 // Loc points to the argument id of the macro definition, move to the
977 Loc = SM.getImmediateExpansionRange(Loc).first;
978 SourceLocation SpellLoc = Expansion.getSpellingLoc();
979 if (SpellLoc.isFileID())
980 break; // No inner macro.
982 // If spelling location resides in the same FileID as macro expansion
983 // location, it means there is no inner macro.
984 FileID MacroFID = SM.getFileID(Loc);
985 if (SM.isInFileID(SpellLoc, MacroFID))
988 // Argument came from inner macro.
992 // Find the spelling location of the start of the non-argument expansion
993 // range. This is where the macro name was spelled in order to begin
994 // expanding this macro.
995 Loc = SM.getSpellingLoc(Loc);
997 // Dig out the buffer where the macro name was spelled and the extents of the
998 // name so that we can render it into the expansion note.
999 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1000 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1001 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1002 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1005 StringRef Lexer::getImmediateMacroNameForDiagnostics(
1006 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
1007 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
1008 // Walk past macro argument expanions.
1009 while (SM.isMacroArgExpansion(Loc))
1010 Loc = SM.getImmediateExpansionRange(Loc).first;
1012 // If the macro's spelling has no FileID, then it's actually a token paste
1013 // or stringization (or similar) and not a macro at all.
1014 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
1017 // Find the spelling location of the start of the non-argument expansion
1018 // range. This is where the macro name was spelled in order to begin
1019 // expanding this macro.
1020 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first);
1022 // Dig out the buffer where the macro name was spelled and the extents of the
1023 // name so that we can render it into the expansion note.
1024 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1025 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1026 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1027 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1030 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1031 return isIdentifierBody(c, LangOpts.DollarIdents);
1035 //===----------------------------------------------------------------------===//
1036 // Diagnostics forwarding code.
1037 //===----------------------------------------------------------------------===//
1039 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1040 /// lexer buffer was all expanded at a single point, perform the mapping.
1041 /// This is currently only used for _Pragma implementation, so it is the slow
1042 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1043 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1044 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1045 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1046 SourceLocation FileLoc,
1047 unsigned CharNo, unsigned TokLen) {
1048 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1050 // Otherwise, we're lexing "mapped tokens". This is used for things like
1051 // _Pragma handling. Combine the expansion location of FileLoc with the
1052 // spelling location.
1053 SourceManager &SM = PP.getSourceManager();
1055 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1056 // characters come from spelling(FileLoc)+Offset.
1057 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1058 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1060 // Figure out the expansion loc range, which is the range covered by the
1061 // original _Pragma(...) sequence.
1062 std::pair<SourceLocation,SourceLocation> II =
1063 SM.getImmediateExpansionRange(FileLoc);
1065 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1068 /// getSourceLocation - Return a source location identifier for the specified
1069 /// offset in the current file.
1070 SourceLocation Lexer::getSourceLocation(const char *Loc,
1071 unsigned TokLen) const {
1072 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1073 "Location out of range for this buffer!");
1075 // In the normal case, we're just lexing from a simple file buffer, return
1076 // the file id from FileLoc with the offset specified.
1077 unsigned CharNo = Loc-BufferStart;
1078 if (FileLoc.isFileID())
1079 return FileLoc.getLocWithOffset(CharNo);
1081 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1082 // tokens are lexed from where the _Pragma was defined.
1083 assert(PP && "This doesn't work on raw lexers");
1084 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1087 /// Diag - Forwarding function for diagnostics. This translate a source
1088 /// position in the current buffer into a SourceLocation object for rendering.
1089 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1090 return PP->Diag(getSourceLocation(Loc), DiagID);
1093 //===----------------------------------------------------------------------===//
1094 // Trigraph and Escaped Newline Handling Code.
1095 //===----------------------------------------------------------------------===//
1097 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1098 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1099 static char GetTrigraphCharForLetter(char Letter) {
1102 case '=': return '#';
1103 case ')': return ']';
1104 case '(': return '[';
1105 case '!': return '|';
1106 case '\'': return '^';
1107 case '>': return '}';
1108 case '/': return '\\';
1109 case '<': return '{';
1110 case '-': return '~';
1114 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1115 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1116 /// return the result character. Finally, emit a warning about trigraph use
1117 /// whether trigraphs are enabled or not.
1118 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1119 char Res = GetTrigraphCharForLetter(*CP);
1120 if (!Res || !L) return Res;
1122 if (!L->getLangOpts().Trigraphs) {
1123 if (!L->isLexingRawMode())
1124 L->Diag(CP-2, diag::trigraph_ignored);
1128 if (!L->isLexingRawMode())
1129 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1133 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1134 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1135 /// trigraph equivalent on entry to this function.
1136 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1138 while (isWhitespace(Ptr[Size])) {
1141 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1144 // If this is a \r\n or \n\r, skip the other half.
1145 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1146 Ptr[Size-1] != Ptr[Size])
1152 // Not an escaped newline, must be a \t or something else.
1156 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1157 /// them), skip over them and return the first non-escaped-newline found,
1158 /// otherwise return P.
1159 const char *Lexer::SkipEscapedNewLines(const char *P) {
1161 const char *AfterEscape;
1164 } else if (*P == '?') {
1165 // If not a trigraph for escape, bail out.
1166 if (P[1] != '?' || P[2] != '/')
1173 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1174 if (NewLineSize == 0) return P;
1175 P = AfterEscape+NewLineSize;
1179 /// \brief Checks that the given token is the first token that occurs after the
1180 /// given location (this excludes comments and whitespace). Returns the location
1181 /// immediately after the specified token. If the token is not found or the
1182 /// location is inside a macro, the returned source location will be invalid.
1183 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1184 tok::TokenKind TKind,
1185 const SourceManager &SM,
1186 const LangOptions &LangOpts,
1187 bool SkipTrailingWhitespaceAndNewLine) {
1188 if (Loc.isMacroID()) {
1189 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1190 return SourceLocation();
1192 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1194 // Break down the source location.
1195 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1197 // Try to load the file buffer.
1198 bool InvalidTemp = false;
1199 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1201 return SourceLocation();
1203 const char *TokenBegin = File.data() + LocInfo.second;
1205 // Lex from the start of the given location.
1206 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1207 TokenBegin, File.end());
1210 lexer.LexFromRawLexer(Tok);
1211 if (Tok.isNot(TKind))
1212 return SourceLocation();
1213 SourceLocation TokenLoc = Tok.getLocation();
1215 // Calculate how much whitespace needs to be skipped if any.
1216 unsigned NumWhitespaceChars = 0;
1217 if (SkipTrailingWhitespaceAndNewLine) {
1218 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1220 unsigned char C = *TokenEnd;
1221 while (isHorizontalWhitespace(C)) {
1223 NumWhitespaceChars++;
1226 // Skip \r, \n, \r\n, or \n\r
1227 if (C == '\n' || C == '\r') {
1230 NumWhitespaceChars++;
1231 if ((C == '\n' || C == '\r') && C != PrevC)
1232 NumWhitespaceChars++;
1236 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1239 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1240 /// get its size, and return it. This is tricky in several cases:
1241 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1242 /// then either return the trigraph (skipping 3 chars) or the '?',
1243 /// depending on whether trigraphs are enabled or not.
1244 /// 2. If this is an escaped newline (potentially with whitespace between
1245 /// the backslash and newline), implicitly skip the newline and return
1246 /// the char after it.
1248 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1249 /// know that we can accumulate into Size, and that we have already incremented
1250 /// Ptr by Size bytes.
1252 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1253 /// be updated to match.
1255 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1257 // If we have a slash, look for an escaped newline.
1258 if (Ptr[0] == '\\') {
1262 // Common case, backslash-char where the char is not whitespace.
1263 if (!isWhitespace(Ptr[0])) return '\\';
1265 // See if we have optional whitespace characters between the slash and
1267 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1268 // Remember that this token needs to be cleaned.
1269 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1271 // Warn if there was whitespace between the backslash and newline.
1272 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1273 Diag(Ptr, diag::backslash_newline_space);
1275 // Found backslash<whitespace><newline>. Parse the char after it.
1276 Size += EscapedNewLineSize;
1277 Ptr += EscapedNewLineSize;
1279 // If the char that we finally got was a \n, then we must have had
1280 // something like \<newline><newline>. We don't want to consume the
1282 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1285 // Use slow version to accumulate a correct size field.
1286 return getCharAndSizeSlow(Ptr, Size, Tok);
1289 // Otherwise, this is not an escaped newline, just return the slash.
1293 // If this is a trigraph, process it.
1294 if (Ptr[0] == '?' && Ptr[1] == '?') {
1295 // If this is actually a legal trigraph (not something like "??x"), emit
1296 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1297 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1298 // Remember that this token needs to be cleaned.
1299 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1303 if (C == '\\') goto Slash;
1308 // If this is neither, return a single character.
1314 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1315 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1316 /// and that we have already incremented Ptr by Size bytes.
1318 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1319 /// be updated to match.
1320 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1321 const LangOptions &LangOpts) {
1322 // If we have a slash, look for an escaped newline.
1323 if (Ptr[0] == '\\') {
1327 // Common case, backslash-char where the char is not whitespace.
1328 if (!isWhitespace(Ptr[0])) return '\\';
1330 // See if we have optional whitespace characters followed by a newline.
1331 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1332 // Found backslash<whitespace><newline>. Parse the char after it.
1333 Size += EscapedNewLineSize;
1334 Ptr += EscapedNewLineSize;
1336 // If the char that we finally got was a \n, then we must have had
1337 // something like \<newline><newline>. We don't want to consume the
1339 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1342 // Use slow version to accumulate a correct size field.
1343 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1346 // Otherwise, this is not an escaped newline, just return the slash.
1350 // If this is a trigraph, process it.
1351 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1352 // If this is actually a legal trigraph (not something like "??x"), return
1354 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1357 if (C == '\\') goto Slash;
1362 // If this is neither, return a single character.
1367 //===----------------------------------------------------------------------===//
1368 // Helper methods for lexing.
1369 //===----------------------------------------------------------------------===//
1371 /// \brief Routine that indiscriminately skips bytes in the source file.
1372 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1374 if (BufferPtr > BufferEnd)
1375 BufferPtr = BufferEnd;
1376 // FIXME: What exactly does the StartOfLine bit mean? There are two
1377 // possible meanings for the "start" of the line: the first token on the
1378 // unexpanded line, or the first token on the expanded line.
1379 IsAtStartOfLine = StartOfLine;
1380 IsAtPhysicalStartOfLine = StartOfLine;
1383 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1384 if (LangOpts.AsmPreprocessor) {
1386 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1387 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1388 C11AllowedIDCharRanges);
1389 return C11AllowedIDChars.contains(C);
1390 } else if (LangOpts.CPlusPlus) {
1391 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1392 CXX03AllowedIDCharRanges);
1393 return CXX03AllowedIDChars.contains(C);
1395 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1396 C99AllowedIDCharRanges);
1397 return C99AllowedIDChars.contains(C);
1401 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1402 assert(isAllowedIDChar(C, LangOpts));
1403 if (LangOpts.AsmPreprocessor) {
1405 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1406 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1407 C11DisallowedInitialIDCharRanges);
1408 return !C11DisallowedInitialIDChars.contains(C);
1409 } else if (LangOpts.CPlusPlus) {
1412 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1413 C99DisallowedInitialIDCharRanges);
1414 return !C99DisallowedInitialIDChars.contains(C);
1418 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1420 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1421 L.getSourceLocation(End));
1424 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1425 CharSourceRange Range, bool IsFirst) {
1426 // Check C99 compatibility.
1427 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1429 CannotAppearInIdentifier = 0,
1430 CannotStartIdentifier
1433 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1434 C99AllowedIDCharRanges);
1435 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1436 C99DisallowedInitialIDCharRanges);
1437 if (!C99AllowedIDChars.contains(C)) {
1438 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1440 << CannotAppearInIdentifier;
1441 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1442 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1444 << CannotStartIdentifier;
1448 // Check C++98 compatibility.
1449 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1450 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1451 CXX03AllowedIDCharRanges);
1452 if (!CXX03AllowedIDChars.contains(C)) {
1453 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1459 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1461 const char *UCNPtr = CurPtr + Size;
1462 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1463 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1466 if (!isLexingRawMode())
1467 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1468 makeCharRange(*this, CurPtr, UCNPtr),
1471 Result.setFlag(Token::HasUCN);
1472 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1473 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1476 while (CurPtr != UCNPtr)
1477 (void)getAndAdvanceChar(CurPtr, Result);
1481 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1482 const char *UnicodePtr = CurPtr;
1484 ConversionResult Result =
1485 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1486 (const UTF8 *)BufferEnd,
1489 if (Result != conversionOK ||
1490 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1493 if (!isLexingRawMode())
1494 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1495 makeCharRange(*this, CurPtr, UnicodePtr),
1498 CurPtr = UnicodePtr;
1502 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1503 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1505 unsigned char C = *CurPtr++;
1506 while (isIdentifierBody(C))
1509 --CurPtr; // Back up over the skipped character.
1511 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1512 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1514 // TODO: Could merge these checks into an InfoTable flag to make the
1515 // comparison cheaper
1516 if (isASCII(C) && C != '\\' && C != '?' &&
1517 (C != '$' || !LangOpts.DollarIdents)) {
1519 const char *IdStart = BufferPtr;
1520 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1521 Result.setRawIdentifierData(IdStart);
1523 // If we are in raw mode, return this identifier raw. There is no need to
1524 // look up identifier information or attempt to macro expand it.
1528 // Fill in Result.IdentifierInfo and update the token kind,
1529 // looking up the identifier in the identifier table.
1530 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1532 // Finally, now that we know we have an identifier, pass this off to the
1533 // preprocessor, which may macro expand it or something.
1534 if (II->isHandleIdentifierCase())
1535 return PP->HandleIdentifier(Result);
1540 // Otherwise, $,\,? in identifier found. Enter slower path.
1542 C = getCharAndSize(CurPtr, Size);
1545 // If we hit a $ and they are not supported in identifiers, we are done.
1546 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1548 // Otherwise, emit a diagnostic and continue.
1549 if (!isLexingRawMode())
1550 Diag(CurPtr, diag::ext_dollar_in_identifier);
1551 CurPtr = ConsumeChar(CurPtr, Size, Result);
1552 C = getCharAndSize(CurPtr, Size);
1555 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1556 C = getCharAndSize(CurPtr, Size);
1558 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1559 C = getCharAndSize(CurPtr, Size);
1561 } else if (!isIdentifierBody(C)) {
1562 goto FinishIdentifier;
1565 // Otherwise, this character is good, consume it.
1566 CurPtr = ConsumeChar(CurPtr, Size, Result);
1568 C = getCharAndSize(CurPtr, Size);
1569 while (isIdentifierBody(C)) {
1570 CurPtr = ConsumeChar(CurPtr, Size, Result);
1571 C = getCharAndSize(CurPtr, Size);
1576 /// isHexaLiteral - Return true if Start points to a hex constant.
1577 /// in microsoft mode (where this is supposed to be several different tokens).
1578 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1580 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1583 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1584 return (C2 == 'x' || C2 == 'X');
1587 /// LexNumericConstant - Lex the remainder of a integer or floating point
1588 /// constant. From[-1] is the first character lexed. Return the end of the
1590 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1592 char C = getCharAndSize(CurPtr, Size);
1594 while (isPreprocessingNumberBody(C)) {
1595 CurPtr = ConsumeChar(CurPtr, Size, Result);
1597 C = getCharAndSize(CurPtr, Size);
1600 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1601 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1602 // If we are in Microsoft mode, don't continue if the constant is hex.
1603 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1604 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1605 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1608 // If we have a hex FP constant, continue.
1609 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1610 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
1611 // not-quite-conforming extension. Only do so if this looks like it's
1612 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1613 bool IsHexFloat = true;
1614 if (!LangOpts.C99) {
1615 if (!isHexaLiteral(BufferPtr, LangOpts))
1617 else if (!getLangOpts().CPlusPlus1z &&
1618 std::find(BufferPtr, CurPtr, '_') != CurPtr)
1622 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1625 // If we have a digit separator, continue.
1626 if (C == '\'' && getLangOpts().CPlusPlus14) {
1628 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1629 if (isIdentifierBody(Next)) {
1630 if (!isLexingRawMode())
1631 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1632 CurPtr = ConsumeChar(CurPtr, Size, Result);
1633 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1634 return LexNumericConstant(Result, CurPtr);
1638 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1639 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1640 return LexNumericConstant(Result, CurPtr);
1641 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1642 return LexNumericConstant(Result, CurPtr);
1644 // Update the location of token as well as BufferPtr.
1645 const char *TokStart = BufferPtr;
1646 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1647 Result.setLiteralData(TokStart);
1651 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1652 /// in C++11, or warn on a ud-suffix in C++98.
1653 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1654 bool IsStringLiteral) {
1655 assert(getLangOpts().CPlusPlus);
1657 // Maximally munch an identifier.
1659 char C = getCharAndSize(CurPtr, Size);
1660 bool Consumed = false;
1662 if (!isIdentifierHead(C)) {
1663 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1665 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1671 if (!getLangOpts().CPlusPlus11) {
1672 if (!isLexingRawMode())
1674 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1675 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1676 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1680 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1681 // that does not start with an underscore is ill-formed. As a conforming
1682 // extension, we treat all such suffixes as if they had whitespace before
1683 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1684 // likely to be a ud-suffix than a macro, however, and accept that.
1686 bool IsUDSuffix = false;
1689 else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
1690 // In C++1y, we need to look ahead a few characters to see if this is a
1691 // valid suffix for a string literal or a numeric literal (this could be
1692 // the 'operator""if' defining a numeric literal operator).
1693 const unsigned MaxStandardSuffixLength = 3;
1694 char Buffer[MaxStandardSuffixLength] = { C };
1695 unsigned Consumed = Size;
1699 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1701 if (!isIdentifierBody(Next)) {
1702 // End of suffix. Check whether this is on the whitelist.
1703 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1704 NumericLiteralParser::isValidUDSuffix(
1705 getLangOpts(), StringRef(Buffer, Chars));
1709 if (Chars == MaxStandardSuffixLength)
1710 // Too long: can't be a standard suffix.
1713 Buffer[Chars++] = Next;
1714 Consumed += NextSize;
1719 if (!isLexingRawMode())
1720 Diag(CurPtr, getLangOpts().MSVCCompat
1721 ? diag::ext_ms_reserved_user_defined_literal
1722 : diag::ext_reserved_user_defined_literal)
1723 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1727 CurPtr = ConsumeChar(CurPtr, Size, Result);
1730 Result.setFlag(Token::HasUDSuffix);
1732 C = getCharAndSize(CurPtr, Size);
1733 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1734 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1735 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1742 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1743 /// either " or L" or u8" or u" or U".
1744 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1745 tok::TokenKind Kind) {
1746 // Does this string contain the \0 character?
1747 const char *NulCharacter = nullptr;
1749 if (!isLexingRawMode() &&
1750 (Kind == tok::utf8_string_literal ||
1751 Kind == tok::utf16_string_literal ||
1752 Kind == tok::utf32_string_literal))
1753 Diag(BufferPtr, getLangOpts().CPlusPlus
1754 ? diag::warn_cxx98_compat_unicode_literal
1755 : diag::warn_c99_compat_unicode_literal);
1757 char C = getAndAdvanceChar(CurPtr, Result);
1759 // Skip escaped characters. Escaped newlines will already be processed by
1760 // getAndAdvanceChar.
1762 C = getAndAdvanceChar(CurPtr, Result);
1764 if (C == '\n' || C == '\r' || // Newline.
1765 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1766 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1767 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
1768 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1773 if (isCodeCompletionPoint(CurPtr-1)) {
1774 PP->CodeCompleteNaturalLanguage();
1775 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1780 NulCharacter = CurPtr-1;
1782 C = getAndAdvanceChar(CurPtr, Result);
1785 // If we are in C++11, lex the optional ud-suffix.
1786 if (getLangOpts().CPlusPlus)
1787 CurPtr = LexUDSuffix(Result, CurPtr, true);
1789 // If a nul character existed in the string, warn about it.
1790 if (NulCharacter && !isLexingRawMode())
1791 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1793 // Update the location of the token as well as the BufferPtr instance var.
1794 const char *TokStart = BufferPtr;
1795 FormTokenWithChars(Result, CurPtr, Kind);
1796 Result.setLiteralData(TokStart);
1800 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1801 /// having lexed R", LR", u8R", uR", or UR".
1802 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1803 tok::TokenKind Kind) {
1804 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1805 // Between the initial and final double quote characters of the raw string,
1806 // any transformations performed in phases 1 and 2 (trigraphs,
1807 // universal-character-names, and line splicing) are reverted.
1809 if (!isLexingRawMode())
1810 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1812 unsigned PrefixLen = 0;
1814 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1817 // If the last character was not a '(', then we didn't lex a valid delimiter.
1818 if (CurPtr[PrefixLen] != '(') {
1819 if (!isLexingRawMode()) {
1820 const char *PrefixEnd = &CurPtr[PrefixLen];
1821 if (PrefixLen == 16) {
1822 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1824 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1825 << StringRef(PrefixEnd, 1);
1829 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1830 // it's possible the '"' was intended to be part of the raw string, but
1831 // there's not much we can do about that.
1837 if (C == 0 && CurPtr-1 == BufferEnd) {
1843 FormTokenWithChars(Result, CurPtr, tok::unknown);
1847 // Save prefix and move CurPtr past it
1848 const char *Prefix = CurPtr;
1849 CurPtr += PrefixLen + 1; // skip over prefix and '('
1855 // Check for prefix match and closing quote.
1856 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1857 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1860 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1861 if (!isLexingRawMode())
1862 Diag(BufferPtr, diag::err_unterminated_raw_string)
1863 << StringRef(Prefix, PrefixLen);
1864 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1869 // If we are in C++11, lex the optional ud-suffix.
1870 if (getLangOpts().CPlusPlus)
1871 CurPtr = LexUDSuffix(Result, CurPtr, true);
1873 // Update the location of token as well as BufferPtr.
1874 const char *TokStart = BufferPtr;
1875 FormTokenWithChars(Result, CurPtr, Kind);
1876 Result.setLiteralData(TokStart);
1880 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1881 /// after having lexed the '<' character. This is used for #include filenames.
1882 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1883 // Does this string contain the \0 character?
1884 const char *NulCharacter = nullptr;
1885 const char *AfterLessPos = CurPtr;
1886 char C = getAndAdvanceChar(CurPtr, Result);
1888 // Skip escaped characters.
1889 if (C == '\\' && CurPtr < BufferEnd) {
1890 // Skip the escaped character.
1891 getAndAdvanceChar(CurPtr, Result);
1892 } else if (C == '\n' || C == '\r' || // Newline.
1893 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1894 isCodeCompletionPoint(CurPtr-1)))) {
1895 // If the filename is unterminated, then it must just be a lone <
1896 // character. Return this as such.
1897 FormTokenWithChars(Result, AfterLessPos, tok::less);
1899 } else if (C == 0) {
1900 NulCharacter = CurPtr-1;
1902 C = getAndAdvanceChar(CurPtr, Result);
1905 // If a nul character existed in the string, warn about it.
1906 if (NulCharacter && !isLexingRawMode())
1907 Diag(NulCharacter, diag::null_in_char_or_string) << 1;
1909 // Update the location of token as well as BufferPtr.
1910 const char *TokStart = BufferPtr;
1911 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1912 Result.setLiteralData(TokStart);
1917 /// LexCharConstant - Lex the remainder of a character constant, after having
1918 /// lexed either ' or L' or u8' or u' or U'.
1919 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1920 tok::TokenKind Kind) {
1921 // Does this character contain the \0 character?
1922 const char *NulCharacter = nullptr;
1924 if (!isLexingRawMode()) {
1925 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
1926 Diag(BufferPtr, getLangOpts().CPlusPlus
1927 ? diag::warn_cxx98_compat_unicode_literal
1928 : diag::warn_c99_compat_unicode_literal);
1929 else if (Kind == tok::utf8_char_constant)
1930 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
1933 char C = getAndAdvanceChar(CurPtr, Result);
1935 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1936 Diag(BufferPtr, diag::ext_empty_character);
1937 FormTokenWithChars(Result, CurPtr, tok::unknown);
1942 // Skip escaped characters.
1944 C = getAndAdvanceChar(CurPtr, Result);
1946 if (C == '\n' || C == '\r' || // Newline.
1947 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1948 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1949 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
1950 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1955 if (isCodeCompletionPoint(CurPtr-1)) {
1956 PP->CodeCompleteNaturalLanguage();
1957 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1962 NulCharacter = CurPtr-1;
1964 C = getAndAdvanceChar(CurPtr, Result);
1967 // If we are in C++11, lex the optional ud-suffix.
1968 if (getLangOpts().CPlusPlus)
1969 CurPtr = LexUDSuffix(Result, CurPtr, false);
1971 // If a nul character existed in the character, warn about it.
1972 if (NulCharacter && !isLexingRawMode())
1973 Diag(NulCharacter, diag::null_in_char_or_string) << 0;
1975 // Update the location of token as well as BufferPtr.
1976 const char *TokStart = BufferPtr;
1977 FormTokenWithChars(Result, CurPtr, Kind);
1978 Result.setLiteralData(TokStart);
1982 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1983 /// Update BufferPtr to point to the next non-whitespace character and return.
1985 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1987 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1988 bool &TokAtPhysicalStartOfLine) {
1989 // Whitespace - Skip it, then return the token after the whitespace.
1990 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1992 unsigned char Char = *CurPtr;
1994 // Skip consecutive spaces efficiently.
1996 // Skip horizontal whitespace very aggressively.
1997 while (isHorizontalWhitespace(Char))
2000 // Otherwise if we have something other than whitespace, we're done.
2001 if (!isVerticalWhitespace(Char))
2004 if (ParsingPreprocessorDirective) {
2005 // End of preprocessor directive line, let LexTokenInternal handle this.
2010 // OK, but handle newline.
2015 // If the client wants us to return whitespace, return it now.
2016 if (isKeepWhitespaceMode()) {
2017 FormTokenWithChars(Result, CurPtr, tok::unknown);
2019 IsAtStartOfLine = true;
2020 IsAtPhysicalStartOfLine = true;
2022 // FIXME: The next token will not have LeadingSpace set.
2026 // If this isn't immediately after a newline, there is leading space.
2027 char PrevChar = CurPtr[-1];
2028 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2030 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2032 Result.setFlag(Token::StartOfLine);
2033 TokAtPhysicalStartOfLine = true;
2040 /// We have just read the // characters from input. Skip until we find the
2041 /// newline character thats terminate the comment. Then update BufferPtr and
2044 /// If we're in KeepCommentMode or any CommentHandler has inserted
2045 /// some tokens, this will store the first token and return true.
2046 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2047 bool &TokAtPhysicalStartOfLine) {
2048 // If Line comments aren't explicitly enabled for this language, emit an
2049 // extension warning.
2050 if (!LangOpts.LineComment && !isLexingRawMode()) {
2051 Diag(BufferPtr, diag::ext_line_comment);
2053 // Mark them enabled so we only emit one warning for this translation
2055 LangOpts.LineComment = true;
2058 // Scan over the body of the comment. The common case, when scanning, is that
2059 // the comment contains normal ascii characters with nothing interesting in
2060 // them. As such, optimize for this case with the inner loop.
2064 // Skip over characters in the fast loop.
2065 while (C != 0 && // Potentially EOF.
2066 C != '\n' && C != '\r') // Newline or DOS-style newline.
2069 const char *NextLine = CurPtr;
2071 // We found a newline, see if it's escaped.
2072 const char *EscapePtr = CurPtr-1;
2073 bool HasSpace = false;
2074 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2079 if (*EscapePtr == '\\') // Escaped newline.
2081 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2082 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2083 CurPtr = EscapePtr-2;
2085 break; // This is a newline, we're done.
2087 // If there was space between the backslash and newline, warn about it.
2088 if (HasSpace && !isLexingRawMode())
2089 Diag(EscapePtr, diag::backslash_newline_space);
2092 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2093 // properly decode the character. Read it in raw mode to avoid emitting
2094 // diagnostics about things like trigraphs. If we see an escaped newline,
2095 // we'll handle it below.
2096 const char *OldPtr = CurPtr;
2097 bool OldRawMode = isLexingRawMode();
2098 LexingRawMode = true;
2099 C = getAndAdvanceChar(CurPtr, Result);
2100 LexingRawMode = OldRawMode;
2102 // If we only read only one character, then no special handling is needed.
2103 // We're done and can skip forward to the newline.
2104 if (C != 0 && CurPtr == OldPtr+1) {
2109 // If we read multiple characters, and one of those characters was a \r or
2110 // \n, then we had an escaped newline within the comment. Emit diagnostic
2111 // unless the next line is also a // comment.
2112 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2113 for (; OldPtr != CurPtr; ++OldPtr)
2114 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2115 // Okay, we found a // comment that ends in a newline, if the next
2116 // line is also a // comment, but has spaces, don't emit a diagnostic.
2117 if (isWhitespace(C)) {
2118 const char *ForwardPtr = CurPtr;
2119 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2121 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2125 if (!isLexingRawMode())
2126 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2131 if (CurPtr == BufferEnd+1) {
2136 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2137 PP->CodeCompleteNaturalLanguage();
2142 } while (C != '\n' && C != '\r');
2144 // Found but did not consume the newline. Notify comment handlers about the
2145 // comment unless we're in a #if 0 block.
2146 if (PP && !isLexingRawMode() &&
2147 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2148 getSourceLocation(CurPtr)))) {
2150 return true; // A token has to be returned.
2153 // If we are returning comments as tokens, return this comment as a token.
2154 if (inKeepCommentMode())
2155 return SaveLineComment(Result, CurPtr);
2157 // If we are inside a preprocessor directive and we see the end of line,
2158 // return immediately, so that the lexer can return this as an EOD token.
2159 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2164 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2165 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2166 // contribute to another token), it isn't needed for correctness. Note that
2167 // this is ok even in KeepWhitespaceMode, because we would have returned the
2168 /// comment above in that mode.
2171 // The next returned token is at the start of the line.
2172 Result.setFlag(Token::StartOfLine);
2173 TokAtPhysicalStartOfLine = true;
2174 // No leading whitespace seen so far.
2175 Result.clearFlag(Token::LeadingSpace);
2180 /// If in save-comment mode, package up this Line comment in an appropriate
2181 /// way and return it.
2182 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2183 // If we're not in a preprocessor directive, just return the // comment
2185 FormTokenWithChars(Result, CurPtr, tok::comment);
2187 if (!ParsingPreprocessorDirective || LexingRawMode)
2190 // If this Line-style comment is in a macro definition, transmogrify it into
2191 // a C-style block comment.
2192 bool Invalid = false;
2193 std::string Spelling = PP->getSpelling(Result, &Invalid);
2197 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2198 Spelling[1] = '*'; // Change prefix to "/*".
2199 Spelling += "*/"; // add suffix.
2201 Result.setKind(tok::comment);
2202 PP->CreateString(Spelling, Result,
2203 Result.getLocation(), Result.getLocation());
2207 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2208 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2209 /// a diagnostic if so. We know that the newline is inside of a block comment.
2210 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2212 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2214 // Back up off the newline.
2217 // If this is a two-character newline sequence, skip the other character.
2218 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2219 // \n\n or \r\r -> not escaped newline.
2220 if (CurPtr[0] == CurPtr[1])
2222 // \n\r or \r\n -> skip the newline.
2226 // If we have horizontal whitespace, skip over it. We allow whitespace
2227 // between the slash and newline.
2228 bool HasSpace = false;
2229 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2234 // If we have a slash, we know this is an escaped newline.
2235 if (*CurPtr == '\\') {
2236 if (CurPtr[-1] != '*') return false;
2238 // It isn't a slash, is it the ?? / trigraph?
2239 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2243 // This is the trigraph ending the comment. Emit a stern warning!
2246 // If no trigraphs are enabled, warn that we ignored this trigraph and
2247 // ignore this * character.
2248 if (!L->getLangOpts().Trigraphs) {
2249 if (!L->isLexingRawMode())
2250 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2253 if (!L->isLexingRawMode())
2254 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2257 // Warn about having an escaped newline between the */ characters.
2258 if (!L->isLexingRawMode())
2259 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2261 // If there was space between the backslash and newline, warn about it.
2262 if (HasSpace && !L->isLexingRawMode())
2263 L->Diag(CurPtr, diag::backslash_newline_space);
2269 #include <emmintrin.h>
2271 #include <altivec.h>
2275 /// We have just read from input the / and * characters that started a comment.
2276 /// Read until we find the * and / characters that terminate the comment.
2277 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2278 /// comments, because they cannot cause the comment to end. The only thing
2279 /// that can happen is the comment could end with an escaped newline between
2280 /// the terminating * and /.
2282 /// If we're in KeepCommentMode or any CommentHandler has inserted
2283 /// some tokens, this will store the first token and return true.
2284 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2285 bool &TokAtPhysicalStartOfLine) {
2286 // Scan one character past where we should, looking for a '/' character. Once
2287 // we find it, check to see if it was preceded by a *. This common
2288 // optimization helps people who like to put a lot of * characters in their
2291 // The first character we get with newlines and trigraphs skipped to handle
2292 // the degenerate /*/ case below correctly if the * has an escaped newline
2295 unsigned char C = getCharAndSize(CurPtr, CharSize);
2297 if (C == 0 && CurPtr == BufferEnd+1) {
2298 if (!isLexingRawMode())
2299 Diag(BufferPtr, diag::err_unterminated_block_comment);
2302 // KeepWhitespaceMode should return this broken comment as a token. Since
2303 // it isn't a well formed comment, just return it as an 'unknown' token.
2304 if (isKeepWhitespaceMode()) {
2305 FormTokenWithChars(Result, CurPtr, tok::unknown);
2313 // Check to see if the first character after the '/*' is another /. If so,
2314 // then this slash does not end the block comment, it is part of it.
2319 // Skip over all non-interesting characters until we find end of buffer or a
2320 // (probably ending) '/' character.
2321 if (CurPtr + 24 < BufferEnd &&
2322 // If there is a code-completion point avoid the fast scan because it
2323 // doesn't check for '\0'.
2324 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2325 // While not aligned to a 16-byte boundary.
2326 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2329 if (C == '/') goto FoundSlash;
2332 __m128i Slashes = _mm_set1_epi8('/');
2333 while (CurPtr+16 <= BufferEnd) {
2334 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2337 // Adjust the pointer to point directly after the first slash. It's
2338 // not necessary to set C here, it will be overwritten at the end of
2340 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2346 __vector unsigned char Slashes = {
2347 '/', '/', '/', '/', '/', '/', '/', '/',
2348 '/', '/', '/', '/', '/', '/', '/', '/'
2350 while (CurPtr+16 <= BufferEnd &&
2351 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes))
2354 // Scan for '/' quickly. Many block comments are very large.
2355 while (CurPtr[0] != '/' &&
2359 CurPtr+4 < BufferEnd) {
2364 // It has to be one of the bytes scanned, increment to it and read one.
2368 // Loop to scan the remainder.
2369 while (C != '/' && C != '\0')
2374 if (CurPtr[-2] == '*') // We found the final */. We're done!
2377 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2378 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2379 // We found the final */, though it had an escaped newline between the
2380 // * and /. We're done!
2384 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2385 // If this is a /* inside of the comment, emit a warning. Don't do this
2386 // if this is a /*/, which will end the comment. This misses cases with
2387 // embedded escaped newlines, but oh well.
2388 if (!isLexingRawMode())
2389 Diag(CurPtr-1, diag::warn_nested_block_comment);
2391 } else if (C == 0 && CurPtr == BufferEnd+1) {
2392 if (!isLexingRawMode())
2393 Diag(BufferPtr, diag::err_unterminated_block_comment);
2394 // Note: the user probably forgot a */. We could continue immediately
2395 // after the /*, but this would involve lexing a lot of what really is the
2396 // comment, which surely would confuse the parser.
2399 // KeepWhitespaceMode should return this broken comment as a token. Since
2400 // it isn't a well formed comment, just return it as an 'unknown' token.
2401 if (isKeepWhitespaceMode()) {
2402 FormTokenWithChars(Result, CurPtr, tok::unknown);
2408 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2409 PP->CodeCompleteNaturalLanguage();
2417 // Notify comment handlers about the comment unless we're in a #if 0 block.
2418 if (PP && !isLexingRawMode() &&
2419 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2420 getSourceLocation(CurPtr)))) {
2422 return true; // A token has to be returned.
2425 // If we are returning comments as tokens, return this comment as a token.
2426 if (inKeepCommentMode()) {
2427 FormTokenWithChars(Result, CurPtr, tok::comment);
2431 // It is common for the tokens immediately after a /**/ comment to be
2432 // whitespace. Instead of going through the big switch, handle it
2433 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2434 // have already returned above with the comment as a token.
2435 if (isHorizontalWhitespace(*CurPtr)) {
2436 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2440 // Otherwise, just return so that the next character will be lexed as a token.
2442 Result.setFlag(Token::LeadingSpace);
2446 //===----------------------------------------------------------------------===//
2447 // Primary Lexing Entry Points
2448 //===----------------------------------------------------------------------===//
2450 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2451 /// uninterpreted string. This switches the lexer out of directive mode.
2452 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2453 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2454 "Must be in a preprocessing directive!");
2457 // CurPtr - Cache BufferPtr in an automatic variable.
2458 const char *CurPtr = BufferPtr;
2460 char Char = getAndAdvanceChar(CurPtr, Tmp);
2464 Result->push_back(Char);
2467 // Found end of file?
2468 if (CurPtr-1 != BufferEnd) {
2469 if (isCodeCompletionPoint(CurPtr-1)) {
2470 PP->CodeCompleteNaturalLanguage();
2475 // Nope, normal character, continue.
2477 Result->push_back(Char);
2483 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2484 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2485 BufferPtr = CurPtr-1;
2487 // Next, lex the character, which should handle the EOD transition.
2489 if (Tmp.is(tok::code_completion)) {
2491 PP->CodeCompleteNaturalLanguage();
2494 assert(Tmp.is(tok::eod) && "Unexpected token!");
2496 // Finally, we're done;
2502 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2503 /// condition, reporting diagnostics and handling other edge cases as required.
2504 /// This returns true if Result contains a token, false if PP.Lex should be
2506 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2507 // If we hit the end of the file while parsing a preprocessor directive,
2508 // end the preprocessor directive first. The next token returned will
2509 // then be the end of file.
2510 if (ParsingPreprocessorDirective) {
2511 // Done parsing the "line".
2512 ParsingPreprocessorDirective = false;
2513 // Update the location of token as well as BufferPtr.
2514 FormTokenWithChars(Result, CurPtr, tok::eod);
2516 // Restore comment saving mode, in case it was disabled for directive.
2518 resetExtendedTokenMode();
2519 return true; // Have a token.
2522 // If we are in raw mode, return this event as an EOF token. Let the caller
2523 // that put us in raw mode handle the event.
2524 if (isLexingRawMode()) {
2525 Result.startToken();
2526 BufferPtr = BufferEnd;
2527 FormTokenWithChars(Result, BufferEnd, tok::eof);
2531 // Issue diagnostics for unterminated #if and missing newline.
2533 // If we are in a #if directive, emit an error.
2534 while (!ConditionalStack.empty()) {
2535 if (PP->getCodeCompletionFileLoc() != FileLoc)
2536 PP->Diag(ConditionalStack.back().IfLoc,
2537 diag::err_pp_unterminated_conditional);
2538 ConditionalStack.pop_back();
2541 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2543 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2544 DiagnosticsEngine &Diags = PP->getDiagnostics();
2545 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2548 if (LangOpts.CPlusPlus11) {
2549 // C++11 [lex.phases] 2.2 p2
2550 // Prefer the C++98 pedantic compatibility warning over the generic,
2551 // non-extension, user-requested "missing newline at EOF" warning.
2552 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2553 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2555 DiagID = diag::warn_no_newline_eof;
2558 DiagID = diag::ext_no_newline_eof;
2561 Diag(BufferEnd, DiagID)
2562 << FixItHint::CreateInsertion(EndLoc, "\n");
2567 // Finally, let the preprocessor handle this.
2568 return PP->HandleEndOfFile(Result, isPragmaLexer());
2571 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2572 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2573 /// else and 2 if there are no more tokens in the buffer controlled by the
2575 unsigned Lexer::isNextPPTokenLParen() {
2576 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2578 // Switch to 'skipping' mode. This will ensure that we can lex a token
2579 // without emitting diagnostics, disables macro expansion, and will cause EOF
2580 // to return an EOF token instead of popping the include stack.
2581 LexingRawMode = true;
2583 // Save state that can be changed while lexing so that we can restore it.
2584 const char *TmpBufferPtr = BufferPtr;
2585 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2586 bool atStartOfLine = IsAtStartOfLine;
2587 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2588 bool leadingSpace = HasLeadingSpace;
2593 // Restore state that may have changed.
2594 BufferPtr = TmpBufferPtr;
2595 ParsingPreprocessorDirective = inPPDirectiveMode;
2596 HasLeadingSpace = leadingSpace;
2597 IsAtStartOfLine = atStartOfLine;
2598 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2600 // Restore the lexer back to non-skipping mode.
2601 LexingRawMode = false;
2603 if (Tok.is(tok::eof))
2605 return Tok.is(tok::l_paren);
2608 /// \brief Find the end of a version control conflict marker.
2609 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2610 ConflictMarkerKind CMK) {
2611 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2612 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2613 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
2614 size_t Pos = RestOfBuffer.find(Terminator);
2615 while (Pos != StringRef::npos) {
2616 // Must occur at start of line.
2618 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
2619 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2620 Pos = RestOfBuffer.find(Terminator);
2623 return RestOfBuffer.data()+Pos;
2628 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2629 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2630 /// and recover nicely. This returns true if it is a conflict marker and false
2632 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2633 // Only a conflict marker if it starts at the beginning of a line.
2634 if (CurPtr != BufferStart &&
2635 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2638 // Check to see if we have <<<<<<< or >>>>.
2639 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
2640 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
2643 // If we have a situation where we don't care about conflict markers, ignore
2645 if (CurrentConflictMarkerState || isLexingRawMode())
2648 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2650 // Check to see if there is an ending marker somewhere in the buffer at the
2651 // start of a line to terminate this conflict marker.
2652 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2653 // We found a match. We are really in a conflict marker.
2654 // Diagnose this, and ignore to the end of line.
2655 Diag(CurPtr, diag::err_conflict_marker);
2656 CurrentConflictMarkerState = Kind;
2658 // Skip ahead to the end of line. We know this exists because the
2659 // end-of-conflict marker starts with \r or \n.
2660 while (*CurPtr != '\r' && *CurPtr != '\n') {
2661 assert(CurPtr != BufferEnd && "Didn't find end of line");
2668 // No end of conflict marker found.
2673 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2674 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2675 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2676 /// the line. This returns true if it is a conflict marker and false if not.
2677 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2678 // Only a conflict marker if it starts at the beginning of a line.
2679 if (CurPtr != BufferStart &&
2680 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2683 // If we have a situation where we don't care about conflict markers, ignore
2685 if (!CurrentConflictMarkerState || isLexingRawMode())
2688 // Check to see if we have the marker (4 characters in a row).
2689 for (unsigned i = 1; i != 4; ++i)
2690 if (CurPtr[i] != CurPtr[0])
2693 // If we do have it, search for the end of the conflict marker. This could
2694 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2695 // be the end of conflict marker.
2696 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2697 CurrentConflictMarkerState)) {
2700 // Skip ahead to the end of line.
2701 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2706 // No longer in the conflict marker.
2707 CurrentConflictMarkerState = CMK_None;
2714 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2715 if (PP && PP->isCodeCompletionEnabled()) {
2716 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2717 return Loc == PP->getCodeCompletionLoc();
2723 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2726 char Kind = getCharAndSize(StartPtr, CharSize);
2728 unsigned NumHexDigits;
2731 else if (Kind == 'U')
2736 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2737 if (Result && !isLexingRawMode())
2738 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2742 const char *CurPtr = StartPtr + CharSize;
2743 const char *KindLoc = &CurPtr[-1];
2745 uint32_t CodePoint = 0;
2746 for (unsigned i = 0; i < NumHexDigits; ++i) {
2747 char C = getCharAndSize(CurPtr, CharSize);
2749 unsigned Value = llvm::hexDigitValue(C);
2751 if (Result && !isLexingRawMode()) {
2753 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2754 << StringRef(KindLoc, 1);
2756 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2758 // If the user wrote \U1234, suggest a fixit to \u.
2759 if (i == 4 && NumHexDigits == 8) {
2760 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2761 Diag(KindLoc, diag::note_ucn_four_not_eight)
2762 << FixItHint::CreateReplacement(URange, "u");
2777 Result->setFlag(Token::HasUCN);
2778 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2781 while (StartPtr != CurPtr)
2782 (void)getAndAdvanceChar(StartPtr, *Result);
2787 // Don't apply C family restrictions to UCNs in assembly mode
2788 if (LangOpts.AsmPreprocessor)
2791 // C99 6.4.3p2: A universal character name shall not specify a character whose
2792 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2793 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2794 // C++11 [lex.charset]p2: If the hexadecimal value for a
2795 // universal-character-name corresponds to a surrogate code point (in the
2796 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2797 // if the hexadecimal value for a universal-character-name outside the
2798 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2799 // string literal corresponds to a control character (in either of the
2800 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2801 // basic source character set, the program is ill-formed.
2802 if (CodePoint < 0xA0) {
2803 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2806 // We don't use isLexingRawMode() here because we need to warn about bad
2807 // UCNs even when skipping preprocessing tokens in a #if block.
2809 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2810 Diag(BufferPtr, diag::err_ucn_control_character);
2812 char C = static_cast<char>(CodePoint);
2813 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2819 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2820 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2821 // We don't use isLexingRawMode() here because we need to diagnose bad
2822 // UCNs even when skipping preprocessing tokens in a #if block.
2824 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2825 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2827 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2835 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2836 const char *CurPtr) {
2837 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2838 UnicodeWhitespaceCharRanges);
2839 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2840 UnicodeWhitespaceChars.contains(C)) {
2841 Diag(BufferPtr, diag::ext_unicode_whitespace)
2842 << makeCharRange(*this, BufferPtr, CurPtr);
2844 Result.setFlag(Token::LeadingSpace);
2850 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2851 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2852 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2853 !PP->isPreprocessedOutput()) {
2854 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2855 makeCharRange(*this, BufferPtr, CurPtr),
2860 return LexIdentifier(Result, CurPtr);
2863 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2864 !PP->isPreprocessedOutput() &&
2865 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2866 // Non-ASCII characters tend to creep into source code unintentionally.
2867 // Instead of letting the parser complain about the unknown token,
2868 // just drop the character.
2869 // Note that we can /only/ do this when the non-ASCII character is actually
2870 // spelled as Unicode, not written as a UCN. The standard requires that
2871 // we not throw away any possible preprocessor tokens, but there's a
2872 // loophole in the mapping of Unicode characters to basic character set
2873 // characters that allows us to map these particular characters to, say,
2875 Diag(BufferPtr, diag::err_non_ascii)
2876 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2882 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2885 FormTokenWithChars(Result, CurPtr, tok::unknown);
2889 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2890 IsAtStartOfLine = Result.isAtStartOfLine();
2891 HasLeadingSpace = Result.hasLeadingSpace();
2892 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2893 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2896 bool Lexer::Lex(Token &Result) {
2897 // Start a new token.
2898 Result.startToken();
2900 // Set up misc whitespace flags for LexTokenInternal.
2901 if (IsAtStartOfLine) {
2902 Result.setFlag(Token::StartOfLine);
2903 IsAtStartOfLine = false;
2906 if (HasLeadingSpace) {
2907 Result.setFlag(Token::LeadingSpace);
2908 HasLeadingSpace = false;
2911 if (HasLeadingEmptyMacro) {
2912 Result.setFlag(Token::LeadingEmptyMacro);
2913 HasLeadingEmptyMacro = false;
2916 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2917 IsAtPhysicalStartOfLine = false;
2918 bool isRawLex = isLexingRawMode();
2920 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2921 // (After the LexTokenInternal call, the lexer might be destroyed.)
2922 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2923 return returnedToken;
2926 /// LexTokenInternal - This implements a simple C family lexer. It is an
2927 /// extremely performance critical piece of code. This assumes that the buffer
2928 /// has a null character at the end of the file. This returns a preprocessing
2929 /// token, not a normal token, as such, it is an internal interface. It assumes
2930 /// that the Flags of result have been cleared before calling this.
2931 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
2933 // New token, can't need cleaning yet.
2934 Result.clearFlag(Token::NeedsCleaning);
2935 Result.setIdentifierInfo(nullptr);
2937 // CurPtr - Cache BufferPtr in an automatic variable.
2938 const char *CurPtr = BufferPtr;
2940 // Small amounts of horizontal whitespace is very common between tokens.
2941 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2943 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2946 // If we are keeping whitespace and other tokens, just return what we just
2947 // skipped. The next lexer invocation will return the token after the
2949 if (isKeepWhitespaceMode()) {
2950 FormTokenWithChars(Result, CurPtr, tok::unknown);
2951 // FIXME: The next token will not have LeadingSpace set.
2956 Result.setFlag(Token::LeadingSpace);
2959 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
2961 // Read a character, advancing over it.
2962 char Char = getAndAdvanceChar(CurPtr, Result);
2963 tok::TokenKind Kind;
2967 // Found end of file?
2968 if (CurPtr-1 == BufferEnd)
2969 return LexEndOfFile(Result, CurPtr-1);
2971 // Check if we are performing code completion.
2972 if (isCodeCompletionPoint(CurPtr-1)) {
2973 // Return the code-completion token.
2974 Result.startToken();
2975 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2979 if (!isLexingRawMode())
2980 Diag(CurPtr-1, diag::null_in_file);
2981 Result.setFlag(Token::LeadingSpace);
2982 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2983 return true; // KeepWhitespaceMode
2985 // We know the lexer hasn't changed, so just try again with this lexer.
2986 // (We manually eliminate the tail call to avoid recursion.)
2989 case 26: // DOS & CP/M EOF: "^Z".
2990 // If we're in Microsoft extensions mode, treat this as end of file.
2991 if (LangOpts.MicrosoftExt) {
2992 if (!isLexingRawMode())
2993 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
2994 return LexEndOfFile(Result, CurPtr-1);
2997 // If Microsoft extensions are disabled, this is just random garbage.
2998 Kind = tok::unknown;
3003 // If we are inside a preprocessor directive and we see the end of line,
3004 // we know we are done with the directive, so return an EOD token.
3005 if (ParsingPreprocessorDirective) {
3006 // Done parsing the "line".
3007 ParsingPreprocessorDirective = false;
3009 // Restore comment saving mode, in case it was disabled for directive.
3011 resetExtendedTokenMode();
3013 // Since we consumed a newline, we are back at the start of a line.
3014 IsAtStartOfLine = true;
3015 IsAtPhysicalStartOfLine = true;
3021 // No leading whitespace seen so far.
3022 Result.clearFlag(Token::LeadingSpace);
3024 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3025 return true; // KeepWhitespaceMode
3027 // We only saw whitespace, so just try again with this lexer.
3028 // (We manually eliminate the tail call to avoid recursion.)
3034 SkipHorizontalWhitespace:
3035 Result.setFlag(Token::LeadingSpace);
3036 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3037 return true; // KeepWhitespaceMode
3042 // If the next token is obviously a // or /* */ comment, skip it efficiently
3043 // too (without going through the big switch stmt).
3044 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3045 LangOpts.LineComment &&
3046 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3047 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3048 return true; // There is a token to return.
3049 goto SkipIgnoredUnits;
3050 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3051 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3052 return true; // There is a token to return.
3053 goto SkipIgnoredUnits;
3054 } else if (isHorizontalWhitespace(*CurPtr)) {
3055 goto SkipHorizontalWhitespace;
3057 // We only saw whitespace, so just try again with this lexer.
3058 // (We manually eliminate the tail call to avoid recursion.)
3061 // C99 6.4.4.1: Integer Constants.
3062 // C99 6.4.4.2: Floating Constants.
3063 case '0': case '1': case '2': case '3': case '4':
3064 case '5': case '6': case '7': case '8': case '9':
3065 // Notify MIOpt that we read a non-whitespace/non-comment token.
3067 return LexNumericConstant(Result, CurPtr);
3069 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3070 // Notify MIOpt that we read a non-whitespace/non-comment token.
3073 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3074 Char = getCharAndSize(CurPtr, SizeTmp);
3076 // UTF-16 string literal
3078 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3079 tok::utf16_string_literal);
3081 // UTF-16 character constant
3083 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3084 tok::utf16_char_constant);
3086 // UTF-16 raw string literal
3087 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3088 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3089 return LexRawStringLiteral(Result,
3090 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3092 tok::utf16_string_literal);
3095 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3097 // UTF-8 string literal
3099 return LexStringLiteral(Result,
3100 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3102 tok::utf8_string_literal);
3103 if (Char2 == '\'' && LangOpts.CPlusPlus1z)
3104 return LexCharConstant(
3105 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3107 tok::utf8_char_constant);
3109 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3111 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3112 // UTF-8 raw string literal
3114 return LexRawStringLiteral(Result,
3115 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3118 tok::utf8_string_literal);
3124 // treat u like the start of an identifier.
3125 return LexIdentifier(Result, CurPtr);
3127 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3128 // Notify MIOpt that we read a non-whitespace/non-comment token.
3131 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3132 Char = getCharAndSize(CurPtr, SizeTmp);
3134 // UTF-32 string literal
3136 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3137 tok::utf32_string_literal);
3139 // UTF-32 character constant
3141 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3142 tok::utf32_char_constant);
3144 // UTF-32 raw string literal
3145 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3146 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3147 return LexRawStringLiteral(Result,
3148 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3150 tok::utf32_string_literal);
3153 // treat U like the start of an identifier.
3154 return LexIdentifier(Result, CurPtr);
3156 case 'R': // Identifier or C++0x raw string literal
3157 // Notify MIOpt that we read a non-whitespace/non-comment token.
3160 if (LangOpts.CPlusPlus11) {
3161 Char = getCharAndSize(CurPtr, SizeTmp);
3164 return LexRawStringLiteral(Result,
3165 ConsumeChar(CurPtr, SizeTmp, Result),
3166 tok::string_literal);
3169 // treat R like the start of an identifier.
3170 return LexIdentifier(Result, CurPtr);
3172 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3173 // Notify MIOpt that we read a non-whitespace/non-comment token.
3175 Char = getCharAndSize(CurPtr, SizeTmp);
3177 // Wide string literal.
3179 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3180 tok::wide_string_literal);
3182 // Wide raw string literal.
3183 if (LangOpts.CPlusPlus11 && Char == 'R' &&
3184 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3185 return LexRawStringLiteral(Result,
3186 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3188 tok::wide_string_literal);
3190 // Wide character constant.
3192 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3193 tok::wide_char_constant);
3194 // FALL THROUGH, treating L like the start of an identifier.
3196 // C99 6.4.2: Identifiers.
3197 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3198 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3199 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3200 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3201 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3202 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3203 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3204 case 'v': case 'w': case 'x': case 'y': case 'z':
3206 // Notify MIOpt that we read a non-whitespace/non-comment token.
3208 return LexIdentifier(Result, CurPtr);
3210 case '$': // $ in identifiers.
3211 if (LangOpts.DollarIdents) {
3212 if (!isLexingRawMode())
3213 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3214 // Notify MIOpt that we read a non-whitespace/non-comment token.
3216 return LexIdentifier(Result, CurPtr);
3219 Kind = tok::unknown;
3222 // C99 6.4.4: Character Constants.
3224 // Notify MIOpt that we read a non-whitespace/non-comment token.
3226 return LexCharConstant(Result, CurPtr, tok::char_constant);
3228 // C99 6.4.5: String Literals.
3230 // Notify MIOpt that we read a non-whitespace/non-comment token.
3232 return LexStringLiteral(Result, CurPtr, tok::string_literal);
3234 // C99 6.4.6: Punctuators.
3236 Kind = tok::question;
3239 Kind = tok::l_square;
3242 Kind = tok::r_square;
3245 Kind = tok::l_paren;
3248 Kind = tok::r_paren;
3251 Kind = tok::l_brace;
3254 Kind = tok::r_brace;
3257 Char = getCharAndSize(CurPtr, SizeTmp);
3258 if (Char >= '0' && Char <= '9') {
3259 // Notify MIOpt that we read a non-whitespace/non-comment token.
3262 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3263 } else if (LangOpts.CPlusPlus && Char == '*') {
3264 Kind = tok::periodstar;
3266 } else if (Char == '.' &&
3267 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3268 Kind = tok::ellipsis;
3269 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3276 Char = getCharAndSize(CurPtr, SizeTmp);
3279 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3280 } else if (Char == '=') {
3281 Kind = tok::ampequal;
3282 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3288 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3289 Kind = tok::starequal;
3290 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3296 Char = getCharAndSize(CurPtr, SizeTmp);
3298 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3299 Kind = tok::plusplus;
3300 } else if (Char == '=') {
3301 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3302 Kind = tok::plusequal;
3308 Char = getCharAndSize(CurPtr, SizeTmp);
3309 if (Char == '-') { // --
3310 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3311 Kind = tok::minusminus;
3312 } else if (Char == '>' && LangOpts.CPlusPlus &&
3313 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3314 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3316 Kind = tok::arrowstar;
3317 } else if (Char == '>') { // ->
3318 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3320 } else if (Char == '=') { // -=
3321 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3322 Kind = tok::minusequal;
3331 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3332 Kind = tok::exclaimequal;
3333 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3335 Kind = tok::exclaim;
3340 Char = getCharAndSize(CurPtr, SizeTmp);
3341 if (Char == '/') { // Line comment.
3342 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3343 // want to lex this as a comment. There is one problem with this though,
3344 // that in one particular corner case, this can change the behavior of the
3345 // resultant program. For example, In "foo //**/ bar", C89 would lex
3346 // this as "foo / bar" and langauges with Line comments would lex it as
3347 // "foo". Check to see if the character after the second slash is a '*'.
3348 // If so, we will lex that as a "/" instead of the start of a comment.
3349 // However, we never do this if we are just preprocessing.
3350 bool TreatAsComment = LangOpts.LineComment &&
3351 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3352 if (!TreatAsComment)
3353 if (!(PP && PP->isPreprocessedOutput()))
3354 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3356 if (TreatAsComment) {
3357 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3358 TokAtPhysicalStartOfLine))
3359 return true; // There is a token to return.
3361 // It is common for the tokens immediately after a // comment to be
3362 // whitespace (indentation for the next line). Instead of going through
3363 // the big switch, handle it efficiently now.
3364 goto SkipIgnoredUnits;
3368 if (Char == '*') { // /**/ comment.
3369 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3370 TokAtPhysicalStartOfLine))
3371 return true; // There is a token to return.
3373 // We only saw whitespace, so just try again with this lexer.
3374 // (We manually eliminate the tail call to avoid recursion.)
3379 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3380 Kind = tok::slashequal;
3386 Char = getCharAndSize(CurPtr, SizeTmp);
3388 Kind = tok::percentequal;
3389 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3390 } else if (LangOpts.Digraphs && Char == '>') {
3391 Kind = tok::r_brace; // '%>' -> '}'
3392 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3393 } else if (LangOpts.Digraphs && Char == ':') {
3394 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3395 Char = getCharAndSize(CurPtr, SizeTmp);
3396 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3397 Kind = tok::hashhash; // '%:%:' -> '##'
3398 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3400 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3401 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3402 if (!isLexingRawMode())
3403 Diag(BufferPtr, diag::ext_charize_microsoft);
3405 } else { // '%:' -> '#'
3406 // We parsed a # character. If this occurs at the start of the line,
3407 // it's actually the start of a preprocessing directive. Callback to
3408 // the preprocessor to handle it.
3409 // TODO: -fpreprocessed mode??
3410 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3411 goto HandleDirective;
3416 Kind = tok::percent;
3420 Char = getCharAndSize(CurPtr, SizeTmp);
3421 if (ParsingFilename) {
3422 return LexAngledStringLiteral(Result, CurPtr);
3423 } else if (Char == '<') {
3424 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3426 Kind = tok::lesslessequal;
3427 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3429 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3430 // If this is actually a '<<<<<<<' version control conflict marker,
3431 // recognize it as such and recover nicely.
3433 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3434 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3437 } else if (LangOpts.CUDA && After == '<') {
3438 Kind = tok::lesslessless;
3439 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3442 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3443 Kind = tok::lessless;
3445 } else if (Char == '=') {
3446 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3447 Kind = tok::lessequal;
3448 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3449 if (LangOpts.CPlusPlus11 &&
3450 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3451 // C++0x [lex.pptoken]p3:
3452 // Otherwise, if the next three characters are <:: and the subsequent
3453 // character is neither : nor >, the < is treated as a preprocessor
3454 // token by itself and not as the first character of the alternative
3457 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3458 if (After != ':' && After != '>') {
3460 if (!isLexingRawMode())
3461 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3466 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3467 Kind = tok::l_square;
3468 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3469 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3470 Kind = tok::l_brace;
3476 Char = getCharAndSize(CurPtr, SizeTmp);
3478 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3479 Kind = tok::greaterequal;
3480 } else if (Char == '>') {
3481 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3483 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3485 Kind = tok::greatergreaterequal;
3486 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3487 // If this is actually a '>>>>' conflict marker, recognize it as such
3488 // and recover nicely.
3490 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3491 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3493 } else if (LangOpts.CUDA && After == '>') {
3494 Kind = tok::greatergreatergreater;
3495 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3498 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3499 Kind = tok::greatergreater;
3503 Kind = tok::greater;
3507 Char = getCharAndSize(CurPtr, SizeTmp);
3509 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3510 Kind = tok::caretequal;
3511 } else if (LangOpts.OpenCL && Char == '^') {
3512 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3513 Kind = tok::caretcaret;
3519 Char = getCharAndSize(CurPtr, SizeTmp);
3521 Kind = tok::pipeequal;
3522 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3523 } else if (Char == '|') {
3524 // If this is '|||||||' and we're in a conflict marker, ignore it.
3525 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3527 Kind = tok::pipepipe;
3528 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3534 Char = getCharAndSize(CurPtr, SizeTmp);
3535 if (LangOpts.Digraphs && Char == '>') {
3536 Kind = tok::r_square; // ':>' -> ']'
3537 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3538 } else if (LangOpts.CPlusPlus && Char == ':') {
3539 Kind = tok::coloncolon;
3540 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3549 Char = getCharAndSize(CurPtr, SizeTmp);
3551 // If this is '====' and we're in a conflict marker, ignore it.
3552 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3555 Kind = tok::equalequal;
3556 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3565 Char = getCharAndSize(CurPtr, SizeTmp);
3567 Kind = tok::hashhash;
3568 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3569 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3571 if (!isLexingRawMode())
3572 Diag(BufferPtr, diag::ext_charize_microsoft);
3573 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3575 // We parsed a # character. If this occurs at the start of the line,
3576 // it's actually the start of a preprocessing directive. Callback to
3577 // the preprocessor to handle it.
3578 // TODO: -fpreprocessed mode??
3579 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3580 goto HandleDirective;
3587 // Objective C support.
3588 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3591 Kind = tok::unknown;
3594 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3596 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3597 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3598 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3599 return true; // KeepWhitespaceMode
3601 // We only saw whitespace, so just try again with this lexer.
3602 // (We manually eliminate the tail call to avoid recursion.)
3606 return LexUnicode(Result, CodePoint, CurPtr);
3609 Kind = tok::unknown;
3613 if (isASCII(Char)) {
3614 Kind = tok::unknown;
3620 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3621 // an escaped newline.
3623 ConversionResult Status =
3624 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3625 (const UTF8 *)BufferEnd,
3628 if (Status == conversionOK) {
3629 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3630 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3631 return true; // KeepWhitespaceMode
3633 // We only saw whitespace, so just try again with this lexer.
3634 // (We manually eliminate the tail call to avoid recursion.)
3637 return LexUnicode(Result, CodePoint, CurPtr);
3640 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3641 PP->isPreprocessedOutput()) {
3643 Kind = tok::unknown;
3647 // Non-ASCII characters tend to creep into source code unintentionally.
3648 // Instead of letting the parser complain about the unknown token,
3649 // just diagnose the invalid UTF-8, then drop the character.
3650 Diag(CurPtr, diag::err_invalid_utf8);
3652 BufferPtr = CurPtr+1;
3653 // We're pretending the character didn't exist, so just try again with
3655 // (We manually eliminate the tail call to avoid recursion.)
3660 // Notify MIOpt that we read a non-whitespace/non-comment token.
3663 // Update the location of token as well as BufferPtr.
3664 FormTokenWithChars(Result, CurPtr, Kind);
3668 // We parsed a # character and it's the start of a preprocessing directive.
3670 FormTokenWithChars(Result, CurPtr, tok::hash);
3671 PP->HandleDirective(Result);
3673 if (PP->hadModuleLoaderFatalFailure()) {
3674 // With a fatal failure in the module loader, we abort parsing.
3675 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3679 // We parsed the directive; lex a token with the new state.