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 : FileLoc(SM.getLocForStartOfFile(FID)), LangOpts(langOpts) {
148 InitLexer(FromFile->getBufferStart(), FromFile->getBufferStart(),
149 FromFile->getBufferEnd());
151 // We *are* in raw mode.
152 LexingRawMode = true;
155 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
156 /// _Pragma expansion. This has a variety of magic semantics that this method
157 /// sets up. It returns a new'd Lexer that must be delete'd when done.
159 /// On entrance to this routine, TokStartLoc is a macro location which has a
160 /// spelling loc that indicates the bytes to be lexed for the token and an
161 /// expansion location that indicates where all lexed tokens should be
164 /// TODO: It would really be nice to make _Pragma just be a wrapper around a
165 /// normal lexer that remaps tokens as they fly by. This would require making
166 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
167 /// interface that could handle this stuff. This would pull GetMappedTokenLoc
168 /// out of the critical path of the lexer!
170 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
171 SourceLocation ExpansionLocStart,
172 SourceLocation ExpansionLocEnd,
173 unsigned TokLen, Preprocessor &PP) {
174 SourceManager &SM = PP.getSourceManager();
176 // Create the lexer as if we were going to lex the file normally.
177 FileID SpellingFID = SM.getFileID(SpellingLoc);
178 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID);
179 Lexer *L = new Lexer(SpellingFID, InputFile, PP);
181 // Now that the lexer is created, change the start/end locations so that we
182 // just lex the subsection of the file that we want. This is lexing from a
184 const char *StrData = SM.getCharacterData(SpellingLoc);
186 L->BufferPtr = StrData;
187 L->BufferEnd = StrData+TokLen;
188 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
190 // Set the SourceLocation with the remapping information. This ensures that
191 // GetMappedTokenLoc will remap the tokens as they are lexed.
192 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
194 ExpansionLocEnd, TokLen);
196 // Ensure that the lexer thinks it is inside a directive, so that end \n will
197 // return an EOD token.
198 L->ParsingPreprocessorDirective = true;
200 // This lexer really is for _Pragma.
201 L->Is_PragmaLexer = true;
206 /// Stringify - Convert the specified string into a C string, with surrounding
207 /// ""'s, and with escaped \ and " characters.
208 std::string Lexer::Stringify(const std::string &Str, bool Charify) {
209 std::string Result = Str;
210 char Quote = Charify ? '\'' : '"';
211 for (unsigned i = 0, e = Result.size(); i != e; ++i) {
212 if (Result[i] == '\\' || Result[i] == Quote) {
213 Result.insert(Result.begin()+i, '\\');
220 /// Stringify - Convert the specified string into a C string by escaping '\'
221 /// and " characters. This does not add surrounding ""'s to the string.
222 void Lexer::Stringify(SmallVectorImpl<char> &Str) {
223 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
224 if (Str[i] == '\\' || Str[i] == '"') {
225 Str.insert(Str.begin()+i, '\\');
231 //===----------------------------------------------------------------------===//
233 //===----------------------------------------------------------------------===//
235 /// \brief Slow case of getSpelling. Extract the characters comprising the
236 /// spelling of this token from the provided input buffer.
237 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
238 const LangOptions &LangOpts, char *Spelling) {
239 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
242 const char *BufEnd = BufPtr + Tok.getLength();
244 if (Tok.is(tok::string_literal)) {
245 // Munch the encoding-prefix and opening double-quote.
246 while (BufPtr < BufEnd) {
248 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
251 if (Spelling[Length - 1] == '"')
255 // Raw string literals need special handling; trigraph expansion and line
256 // splicing do not occur within their d-char-sequence nor within their
259 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
260 // Search backwards from the end of the token to find the matching closing
262 const char *RawEnd = BufEnd;
263 do --RawEnd; while (*RawEnd != '"');
264 size_t RawLength = RawEnd - BufPtr + 1;
266 // Everything between the quotes is included verbatim in the spelling.
267 memcpy(Spelling + Length, BufPtr, RawLength);
271 // The rest of the token is lexed normally.
275 while (BufPtr < BufEnd) {
277 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
281 assert(Length < Tok.getLength() &&
282 "NeedsCleaning flag set on token that didn't need cleaning!");
286 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
287 /// token are the characters used to represent the token in the source file
288 /// after trigraph expansion and escaped-newline folding. In particular, this
289 /// wants to get the true, uncanonicalized, spelling of things like digraphs
291 StringRef Lexer::getSpelling(SourceLocation loc,
292 SmallVectorImpl<char> &buffer,
293 const SourceManager &SM,
294 const LangOptions &options,
296 // Break down the source location.
297 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
299 // Try to the load the file buffer.
300 bool invalidTemp = false;
301 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
303 if (invalid) *invalid = true;
307 const char *tokenBegin = file.data() + locInfo.second;
309 // Lex from the start of the given location.
310 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
311 file.begin(), tokenBegin, file.end());
313 lexer.LexFromRawLexer(token);
315 unsigned length = token.getLength();
317 // Common case: no need for cleaning.
318 if (!token.needsCleaning())
319 return StringRef(tokenBegin, length);
321 // Hard case, we need to relex the characters into the string.
322 buffer.resize(length);
323 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
324 return StringRef(buffer.data(), buffer.size());
327 /// getSpelling() - Return the 'spelling' of this token. The spelling of a
328 /// token are the characters used to represent the token in the source file
329 /// after trigraph expansion and escaped-newline folding. In particular, this
330 /// wants to get the true, uncanonicalized, spelling of things like digraphs
332 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
333 const LangOptions &LangOpts, bool *Invalid) {
334 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
336 bool CharDataInvalid = false;
337 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
340 *Invalid = CharDataInvalid;
342 return std::string();
344 // If this token contains nothing interesting, return it directly.
345 if (!Tok.needsCleaning())
346 return std::string(TokStart, TokStart + Tok.getLength());
349 Result.resize(Tok.getLength());
350 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
354 /// getSpelling - This method is used to get the spelling of a token into a
355 /// preallocated buffer, instead of as an std::string. The caller is required
356 /// to allocate enough space for the token, which is guaranteed to be at least
357 /// Tok.getLength() bytes long. The actual length of the token is returned.
359 /// Note that this method may do two possible things: it may either fill in
360 /// the buffer specified with characters, or it may *change the input pointer*
361 /// to point to a constant buffer with the data already in it (avoiding a
362 /// copy). The caller is not allowed to modify the returned buffer pointer
363 /// if an internal buffer is returned.
364 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
365 const SourceManager &SourceMgr,
366 const LangOptions &LangOpts, bool *Invalid) {
367 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
369 const char *TokStart = nullptr;
370 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
371 if (Tok.is(tok::raw_identifier))
372 TokStart = Tok.getRawIdentifier().data();
373 else if (!Tok.hasUCN()) {
374 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
375 // Just return the string from the identifier table, which is very quick.
376 Buffer = II->getNameStart();
377 return II->getLength();
381 // NOTE: this can be checked even after testing for an IdentifierInfo.
383 TokStart = Tok.getLiteralData();
386 // Compute the start of the token in the input lexer buffer.
387 bool CharDataInvalid = false;
388 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
390 *Invalid = CharDataInvalid;
391 if (CharDataInvalid) {
397 // If this token contains nothing interesting, return it directly.
398 if (!Tok.needsCleaning()) {
400 return Tok.getLength();
403 // Otherwise, hard case, relex the characters into the string.
404 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
408 /// MeasureTokenLength - Relex the token at the specified location and return
409 /// its length in bytes in the input file. If the token needs cleaning (e.g.
410 /// includes a trigraph or an escaped newline) then this count includes bytes
411 /// that are part of that.
412 unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
413 const SourceManager &SM,
414 const LangOptions &LangOpts) {
416 if (getRawToken(Loc, TheTok, SM, LangOpts))
418 return TheTok.getLength();
421 /// \brief Relex the token at the specified location.
422 /// \returns true if there was a failure, false on success.
423 bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
424 const SourceManager &SM,
425 const LangOptions &LangOpts,
426 bool IgnoreWhiteSpace) {
427 // TODO: this could be special cased for common tokens like identifiers, ')',
428 // etc to make this faster, if it mattered. Just look at StrData[0] to handle
429 // all obviously single-char tokens. This could use
430 // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
433 // If this comes from a macro expansion, we really do want the macro name, not
434 // the token this macro expanded to.
435 Loc = SM.getExpansionLoc(Loc);
436 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
437 bool Invalid = false;
438 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
442 const char *StrData = Buffer.data()+LocInfo.second;
444 if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
447 // Create a lexer starting at the beginning of this token.
448 Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
449 Buffer.begin(), StrData, Buffer.end());
450 TheLexer.SetCommentRetentionState(true);
451 TheLexer.LexFromRawLexer(Result);
455 static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
456 const SourceManager &SM,
457 const LangOptions &LangOpts) {
458 assert(Loc.isFileID());
459 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
460 if (LocInfo.first.isInvalid())
463 bool Invalid = false;
464 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
468 // Back up from the current location until we hit the beginning of a line
469 // (or the buffer). We'll relex from that point.
470 const char *BufStart = Buffer.data();
471 if (LocInfo.second >= Buffer.size())
474 const char *StrData = BufStart+LocInfo.second;
475 if (StrData[0] == '\n' || StrData[0] == '\r')
478 const char *LexStart = StrData;
479 while (LexStart != BufStart) {
480 if (LexStart[0] == '\n' || LexStart[0] == '\r') {
488 // Create a lexer starting at the beginning of this token.
489 SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
490 Lexer TheLexer(LexerStartLoc, LangOpts, BufStart, LexStart, Buffer.end());
491 TheLexer.SetCommentRetentionState(true);
493 // Lex tokens until we find the token that contains the source location.
496 TheLexer.LexFromRawLexer(TheTok);
498 if (TheLexer.getBufferLocation() > StrData) {
499 // Lexing this token has taken the lexer past the source location we're
500 // looking for. If the current token encompasses our source location,
501 // return the beginning of that token.
502 if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
503 return TheTok.getLocation();
505 // We ended up skipping over the source location entirely, which means
506 // that it points into whitespace. We're done here.
509 } while (TheTok.getKind() != tok::eof);
511 // We've passed our source location; just return the original source location.
515 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
516 const SourceManager &SM,
517 const LangOptions &LangOpts) {
519 return getBeginningOfFileToken(Loc, SM, LangOpts);
521 if (!SM.isMacroArgExpansion(Loc))
524 SourceLocation FileLoc = SM.getSpellingLoc(Loc);
525 SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
526 std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
527 std::pair<FileID, unsigned> BeginFileLocInfo
528 = SM.getDecomposedLoc(BeginFileLoc);
529 assert(FileLocInfo.first == BeginFileLocInfo.first &&
530 FileLocInfo.second >= BeginFileLocInfo.second);
531 return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
535 enum PreambleDirectiveKind {
543 std::pair<unsigned, bool>
544 Lexer::ComputePreamble(const llvm::MemoryBuffer *Buffer,
545 const LangOptions &LangOpts, unsigned MaxLines) {
546 // Create a lexer starting at the beginning of the file. Note that we use a
547 // "fake" file source location at offset 1 so that the lexer will track our
548 // position within the file.
549 const unsigned StartOffset = 1;
550 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
551 Lexer TheLexer(FileLoc, LangOpts, Buffer->getBufferStart(),
552 Buffer->getBufferStart(), Buffer->getBufferEnd());
553 TheLexer.SetCommentRetentionState(true);
555 // StartLoc will differ from FileLoc if there is a BOM that was skipped.
556 SourceLocation StartLoc = TheLexer.getSourceLocation();
558 bool InPreprocessorDirective = false;
561 unsigned IfCount = 0;
562 SourceLocation ActiveCommentLoc;
564 unsigned MaxLineOffset = 0;
566 const char *CurPtr = Buffer->getBufferStart();
567 unsigned CurLine = 0;
568 while (CurPtr != Buffer->getBufferEnd()) {
572 if (CurLine == MaxLines)
576 if (CurPtr != Buffer->getBufferEnd())
577 MaxLineOffset = CurPtr - Buffer->getBufferStart();
581 TheLexer.LexFromRawLexer(TheTok);
583 if (InPreprocessorDirective) {
584 // If we've hit the end of the file, we're done.
585 if (TheTok.getKind() == tok::eof) {
589 // If we haven't hit the end of the preprocessor directive, skip this
591 if (!TheTok.isAtStartOfLine())
594 // We've passed the end of the preprocessor directive, and will look
595 // at this token again below.
596 InPreprocessorDirective = false;
599 // Keep track of the # of lines in the preamble.
600 if (TheTok.isAtStartOfLine()) {
601 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
603 // If we were asked to limit the number of lines in the preamble,
604 // and we're about to exceed that limit, we're done.
605 if (MaxLineOffset && TokOffset >= MaxLineOffset)
609 // Comments are okay; skip over them.
610 if (TheTok.getKind() == tok::comment) {
611 if (ActiveCommentLoc.isInvalid())
612 ActiveCommentLoc = TheTok.getLocation();
616 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
617 // This is the start of a preprocessor directive.
618 Token HashTok = TheTok;
619 InPreprocessorDirective = true;
620 ActiveCommentLoc = SourceLocation();
622 // Figure out which directive this is. Since we're lexing raw tokens,
623 // we don't have an identifier table available. Instead, just look at
624 // the raw identifier to recognize and categorize preprocessor directives.
625 TheLexer.LexFromRawLexer(TheTok);
626 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
627 StringRef Keyword = TheTok.getRawIdentifier();
628 PreambleDirectiveKind PDK
629 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
630 .Case("include", PDK_Skipped)
631 .Case("__include_macros", PDK_Skipped)
632 .Case("define", PDK_Skipped)
633 .Case("undef", PDK_Skipped)
634 .Case("line", PDK_Skipped)
635 .Case("error", PDK_Skipped)
636 .Case("pragma", PDK_Skipped)
637 .Case("import", PDK_Skipped)
638 .Case("include_next", PDK_Skipped)
639 .Case("warning", PDK_Skipped)
640 .Case("ident", PDK_Skipped)
641 .Case("sccs", PDK_Skipped)
642 .Case("assert", PDK_Skipped)
643 .Case("unassert", PDK_Skipped)
644 .Case("if", PDK_StartIf)
645 .Case("ifdef", PDK_StartIf)
646 .Case("ifndef", PDK_StartIf)
647 .Case("elif", PDK_Skipped)
648 .Case("else", PDK_Skipped)
649 .Case("endif", PDK_EndIf)
650 .Default(PDK_Unknown);
658 IfStartTok = HashTok;
664 // Mismatched #endif. The preamble ends here.
672 // We don't know what this directive is; stop at the '#'.
677 // We only end up here if we didn't recognize the preprocessor
678 // directive or it was one that can't occur in the preamble at this
679 // point. Roll back the current token to the location of the '#'.
680 InPreprocessorDirective = false;
684 // We hit a token that we don't recognize as being in the
685 // "preprocessing only" part of the file, so we're no longer in
692 End = IfStartTok.getLocation();
693 else if (ActiveCommentLoc.isValid())
694 End = ActiveCommentLoc; // don't truncate a decl comment.
696 End = TheTok.getLocation();
698 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(),
699 IfCount? IfStartTok.isAtStartOfLine()
700 : TheTok.isAtStartOfLine());
704 /// AdvanceToTokenCharacter - Given a location that specifies the start of a
705 /// token, return a new location that specifies a character within the token.
706 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart,
708 const SourceManager &SM,
709 const LangOptions &LangOpts) {
710 // Figure out how many physical characters away the specified expansion
711 // character is. This needs to take into consideration newlines and
713 bool Invalid = false;
714 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
716 // If they request the first char of the token, we're trivially done.
717 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
720 unsigned PhysOffset = 0;
722 // The usual case is that tokens don't contain anything interesting. Skip
723 // over the uninteresting characters. If a token only consists of simple
724 // chars, this method is extremely fast.
725 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
727 return TokStart.getLocWithOffset(PhysOffset);
728 ++TokPtr, --CharNo, ++PhysOffset;
731 // If we have a character that may be a trigraph or escaped newline, use a
732 // lexer to parse it correctly.
733 for (; CharNo; --CharNo) {
735 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
740 // Final detail: if we end up on an escaped newline, we want to return the
741 // location of the actual byte of the token. For example foo\<newline>bar
742 // advanced by 3 should return the location of b, not of \\. One compounding
743 // detail of this is that the escape may be made by a trigraph.
744 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
745 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
747 return TokStart.getLocWithOffset(PhysOffset);
750 /// \brief Computes the source location just past the end of the
751 /// token at this source location.
753 /// This routine can be used to produce a source location that
754 /// points just past the end of the token referenced by \p Loc, and
755 /// is generally used when a diagnostic needs to point just after a
756 /// token where it expected something different that it received. If
757 /// the returned source location would not be meaningful (e.g., if
758 /// it points into a macro), this routine returns an invalid
761 /// \param Offset an offset from the end of the token, where the source
762 /// location should refer to. The default offset (0) produces a source
763 /// location pointing just past the end of the token; an offset of 1 produces
764 /// a source location pointing to the last character in the token, etc.
765 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
766 const SourceManager &SM,
767 const LangOptions &LangOpts) {
769 return SourceLocation();
771 if (Loc.isMacroID()) {
772 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
773 return SourceLocation(); // Points inside the macro expansion.
776 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
782 return Loc.getLocWithOffset(Len);
785 /// \brief Returns true if the given MacroID location points at the first
786 /// token of the macro expansion.
787 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
788 const SourceManager &SM,
789 const LangOptions &LangOpts,
790 SourceLocation *MacroBegin) {
791 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
793 SourceLocation expansionLoc;
794 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
797 if (expansionLoc.isFileID()) {
798 // No other macro expansions, this is the first.
800 *MacroBegin = expansionLoc;
804 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
807 /// \brief Returns true if the given MacroID location points at the last
808 /// token of the macro expansion.
809 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
810 const SourceManager &SM,
811 const LangOptions &LangOpts,
812 SourceLocation *MacroEnd) {
813 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
815 SourceLocation spellLoc = SM.getSpellingLoc(loc);
816 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
820 SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
821 SourceLocation expansionLoc;
822 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
825 if (expansionLoc.isFileID()) {
826 // No other macro expansions.
828 *MacroEnd = expansionLoc;
832 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
835 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
836 const SourceManager &SM,
837 const LangOptions &LangOpts) {
838 SourceLocation Begin = Range.getBegin();
839 SourceLocation End = Range.getEnd();
840 assert(Begin.isFileID() && End.isFileID());
841 if (Range.isTokenRange()) {
842 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
844 return CharSourceRange();
847 // Break down the source locations.
850 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
852 return CharSourceRange();
855 if (!SM.isInFileID(End, FID, &EndOffs) ||
857 return CharSourceRange();
859 return CharSourceRange::getCharRange(Begin, End);
862 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
863 const SourceManager &SM,
864 const LangOptions &LangOpts) {
865 SourceLocation Begin = Range.getBegin();
866 SourceLocation End = Range.getEnd();
867 if (Begin.isInvalid() || End.isInvalid())
868 return CharSourceRange();
870 if (Begin.isFileID() && End.isFileID())
871 return makeRangeFromFileLocs(Range, SM, LangOpts);
873 if (Begin.isMacroID() && End.isFileID()) {
874 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
875 return CharSourceRange();
876 Range.setBegin(Begin);
877 return makeRangeFromFileLocs(Range, SM, LangOpts);
880 if (Begin.isFileID() && End.isMacroID()) {
881 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts,
883 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts,
885 return CharSourceRange();
887 return makeRangeFromFileLocs(Range, SM, LangOpts);
890 assert(Begin.isMacroID() && End.isMacroID());
891 SourceLocation MacroBegin, MacroEnd;
892 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
893 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
895 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
897 Range.setBegin(MacroBegin);
898 Range.setEnd(MacroEnd);
899 return makeRangeFromFileLocs(Range, SM, LangOpts);
902 bool Invalid = false;
903 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
906 return CharSourceRange();
908 if (BeginEntry.getExpansion().isMacroArgExpansion()) {
909 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
912 return CharSourceRange();
914 if (EndEntry.getExpansion().isMacroArgExpansion() &&
915 BeginEntry.getExpansion().getExpansionLocStart() ==
916 EndEntry.getExpansion().getExpansionLocStart()) {
917 Range.setBegin(SM.getImmediateSpellingLoc(Begin));
918 Range.setEnd(SM.getImmediateSpellingLoc(End));
919 return makeFileCharRange(Range, SM, LangOpts);
923 return CharSourceRange();
926 StringRef Lexer::getSourceText(CharSourceRange Range,
927 const SourceManager &SM,
928 const LangOptions &LangOpts,
930 Range = makeFileCharRange(Range, SM, LangOpts);
931 if (Range.isInvalid()) {
932 if (Invalid) *Invalid = true;
936 // Break down the source location.
937 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
938 if (beginInfo.first.isInvalid()) {
939 if (Invalid) *Invalid = true;
944 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
945 beginInfo.second > EndOffs) {
946 if (Invalid) *Invalid = true;
950 // Try to the load the file buffer.
951 bool invalidTemp = false;
952 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
954 if (Invalid) *Invalid = true;
958 if (Invalid) *Invalid = false;
959 return file.substr(beginInfo.second, EndOffs - beginInfo.second);
962 StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
963 const SourceManager &SM,
964 const LangOptions &LangOpts) {
965 assert(Loc.isMacroID() && "Only reasonble to call this on macros");
967 // Find the location of the immediate macro expansion.
969 FileID FID = SM.getFileID(Loc);
970 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
971 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
972 Loc = Expansion.getExpansionLocStart();
973 if (!Expansion.isMacroArgExpansion())
976 // For macro arguments we need to check that the argument did not come
977 // from an inner macro, e.g: "MAC1( MAC2(foo) )"
979 // Loc points to the argument id of the macro definition, move to the
981 Loc = SM.getImmediateExpansionRange(Loc).first;
982 SourceLocation SpellLoc = Expansion.getSpellingLoc();
983 if (SpellLoc.isFileID())
984 break; // No inner macro.
986 // If spelling location resides in the same FileID as macro expansion
987 // location, it means there is no inner macro.
988 FileID MacroFID = SM.getFileID(Loc);
989 if (SM.isInFileID(SpellLoc, MacroFID))
992 // Argument came from inner macro.
996 // Find the spelling location of the start of the non-argument expansion
997 // range. This is where the macro name was spelled in order to begin
998 // expanding this macro.
999 Loc = SM.getSpellingLoc(Loc);
1001 // Dig out the buffer where the macro name was spelled and the extents of the
1002 // name so that we can render it into the expansion note.
1003 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
1004 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
1005 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
1006 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
1009 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) {
1010 return isIdentifierBody(c, LangOpts.DollarIdents);
1014 //===----------------------------------------------------------------------===//
1015 // Diagnostics forwarding code.
1016 //===----------------------------------------------------------------------===//
1018 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
1019 /// lexer buffer was all expanded at a single point, perform the mapping.
1020 /// This is currently only used for _Pragma implementation, so it is the slow
1021 /// path of the hot getSourceLocation method. Do not allow it to be inlined.
1022 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
1023 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
1024 static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
1025 SourceLocation FileLoc,
1026 unsigned CharNo, unsigned TokLen) {
1027 assert(FileLoc.isMacroID() && "Must be a macro expansion");
1029 // Otherwise, we're lexing "mapped tokens". This is used for things like
1030 // _Pragma handling. Combine the expansion location of FileLoc with the
1031 // spelling location.
1032 SourceManager &SM = PP.getSourceManager();
1034 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
1035 // characters come from spelling(FileLoc)+Offset.
1036 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
1037 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
1039 // Figure out the expansion loc range, which is the range covered by the
1040 // original _Pragma(...) sequence.
1041 std::pair<SourceLocation,SourceLocation> II =
1042 SM.getImmediateExpansionRange(FileLoc);
1044 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen);
1047 /// getSourceLocation - Return a source location identifier for the specified
1048 /// offset in the current file.
1049 SourceLocation Lexer::getSourceLocation(const char *Loc,
1050 unsigned TokLen) const {
1051 assert(Loc >= BufferStart && Loc <= BufferEnd &&
1052 "Location out of range for this buffer!");
1054 // In the normal case, we're just lexing from a simple file buffer, return
1055 // the file id from FileLoc with the offset specified.
1056 unsigned CharNo = Loc-BufferStart;
1057 if (FileLoc.isFileID())
1058 return FileLoc.getLocWithOffset(CharNo);
1060 // Otherwise, this is the _Pragma lexer case, which pretends that all of the
1061 // tokens are lexed from where the _Pragma was defined.
1062 assert(PP && "This doesn't work on raw lexers");
1063 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
1066 /// Diag - Forwarding function for diagnostics. This translate a source
1067 /// position in the current buffer into a SourceLocation object for rendering.
1068 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
1069 return PP->Diag(getSourceLocation(Loc), DiagID);
1072 //===----------------------------------------------------------------------===//
1073 // Trigraph and Escaped Newline Handling Code.
1074 //===----------------------------------------------------------------------===//
1076 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
1077 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
1078 static char GetTrigraphCharForLetter(char Letter) {
1081 case '=': return '#';
1082 case ')': return ']';
1083 case '(': return '[';
1084 case '!': return '|';
1085 case '\'': return '^';
1086 case '>': return '}';
1087 case '/': return '\\';
1088 case '<': return '{';
1089 case '-': return '~';
1093 /// DecodeTrigraphChar - If the specified character is a legal trigraph when
1094 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
1095 /// return the result character. Finally, emit a warning about trigraph use
1096 /// whether trigraphs are enabled or not.
1097 static char DecodeTrigraphChar(const char *CP, Lexer *L) {
1098 char Res = GetTrigraphCharForLetter(*CP);
1099 if (!Res || !L) return Res;
1101 if (!L->getLangOpts().Trigraphs) {
1102 if (!L->isLexingRawMode())
1103 L->Diag(CP-2, diag::trigraph_ignored);
1107 if (!L->isLexingRawMode())
1108 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
1112 /// getEscapedNewLineSize - Return the size of the specified escaped newline,
1113 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
1114 /// trigraph equivalent on entry to this function.
1115 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
1117 while (isWhitespace(Ptr[Size])) {
1120 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
1123 // If this is a \r\n or \n\r, skip the other half.
1124 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
1125 Ptr[Size-1] != Ptr[Size])
1131 // Not an escaped newline, must be a \t or something else.
1135 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
1136 /// them), skip over them and return the first non-escaped-newline found,
1137 /// otherwise return P.
1138 const char *Lexer::SkipEscapedNewLines(const char *P) {
1140 const char *AfterEscape;
1143 } else if (*P == '?') {
1144 // If not a trigraph for escape, bail out.
1145 if (P[1] != '?' || P[2] != '/')
1152 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
1153 if (NewLineSize == 0) return P;
1154 P = AfterEscape+NewLineSize;
1158 /// \brief Checks that the given token is the first token that occurs after the
1159 /// given location (this excludes comments and whitespace). Returns the location
1160 /// immediately after the specified token. If the token is not found or the
1161 /// location is inside a macro, the returned source location will be invalid.
1162 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc,
1163 tok::TokenKind TKind,
1164 const SourceManager &SM,
1165 const LangOptions &LangOpts,
1166 bool SkipTrailingWhitespaceAndNewLine) {
1167 if (Loc.isMacroID()) {
1168 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
1169 return SourceLocation();
1171 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
1173 // Break down the source location.
1174 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
1176 // Try to load the file buffer.
1177 bool InvalidTemp = false;
1178 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
1180 return SourceLocation();
1182 const char *TokenBegin = File.data() + LocInfo.second;
1184 // Lex from the start of the given location.
1185 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
1186 TokenBegin, File.end());
1189 lexer.LexFromRawLexer(Tok);
1190 if (Tok.isNot(TKind))
1191 return SourceLocation();
1192 SourceLocation TokenLoc = Tok.getLocation();
1194 // Calculate how much whitespace needs to be skipped if any.
1195 unsigned NumWhitespaceChars = 0;
1196 if (SkipTrailingWhitespaceAndNewLine) {
1197 const char *TokenEnd = SM.getCharacterData(TokenLoc) +
1199 unsigned char C = *TokenEnd;
1200 while (isHorizontalWhitespace(C)) {
1202 NumWhitespaceChars++;
1205 // Skip \r, \n, \r\n, or \n\r
1206 if (C == '\n' || C == '\r') {
1209 NumWhitespaceChars++;
1210 if ((C == '\n' || C == '\r') && C != PrevC)
1211 NumWhitespaceChars++;
1215 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars);
1218 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
1219 /// get its size, and return it. This is tricky in several cases:
1220 /// 1. If currently at the start of a trigraph, we warn about the trigraph,
1221 /// then either return the trigraph (skipping 3 chars) or the '?',
1222 /// depending on whether trigraphs are enabled or not.
1223 /// 2. If this is an escaped newline (potentially with whitespace between
1224 /// the backslash and newline), implicitly skip the newline and return
1225 /// the char after it.
1227 /// This handles the slow/uncommon case of the getCharAndSize method. Here we
1228 /// know that we can accumulate into Size, and that we have already incremented
1229 /// Ptr by Size bytes.
1231 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
1232 /// be updated to match.
1234 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
1236 // If we have a slash, look for an escaped newline.
1237 if (Ptr[0] == '\\') {
1241 // Common case, backslash-char where the char is not whitespace.
1242 if (!isWhitespace(Ptr[0])) return '\\';
1244 // See if we have optional whitespace characters between the slash and
1246 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1247 // Remember that this token needs to be cleaned.
1248 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1250 // Warn if there was whitespace between the backslash and newline.
1251 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
1252 Diag(Ptr, diag::backslash_newline_space);
1254 // Found backslash<whitespace><newline>. Parse the char after it.
1255 Size += EscapedNewLineSize;
1256 Ptr += EscapedNewLineSize;
1258 // If the char that we finally got was a \n, then we must have had
1259 // something like \<newline><newline>. We don't want to consume the
1261 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1264 // Use slow version to accumulate a correct size field.
1265 return getCharAndSizeSlow(Ptr, Size, Tok);
1268 // Otherwise, this is not an escaped newline, just return the slash.
1272 // If this is a trigraph, process it.
1273 if (Ptr[0] == '?' && Ptr[1] == '?') {
1274 // If this is actually a legal trigraph (not something like "??x"), emit
1275 // a trigraph warning. If so, and if trigraphs are enabled, return it.
1276 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
1277 // Remember that this token needs to be cleaned.
1278 if (Tok) Tok->setFlag(Token::NeedsCleaning);
1282 if (C == '\\') goto Slash;
1287 // If this is neither, return a single character.
1293 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
1294 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
1295 /// and that we have already incremented Ptr by Size bytes.
1297 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
1298 /// be updated to match.
1299 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
1300 const LangOptions &LangOpts) {
1301 // If we have a slash, look for an escaped newline.
1302 if (Ptr[0] == '\\') {
1306 // Common case, backslash-char where the char is not whitespace.
1307 if (!isWhitespace(Ptr[0])) return '\\';
1309 // See if we have optional whitespace characters followed by a newline.
1310 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
1311 // Found backslash<whitespace><newline>. Parse the char after it.
1312 Size += EscapedNewLineSize;
1313 Ptr += EscapedNewLineSize;
1315 // If the char that we finally got was a \n, then we must have had
1316 // something like \<newline><newline>. We don't want to consume the
1318 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0')
1321 // Use slow version to accumulate a correct size field.
1322 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
1325 // Otherwise, this is not an escaped newline, just return the slash.
1329 // If this is a trigraph, process it.
1330 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
1331 // If this is actually a legal trigraph (not something like "??x"), return
1333 if (char C = GetTrigraphCharForLetter(Ptr[2])) {
1336 if (C == '\\') goto Slash;
1341 // If this is neither, return a single character.
1346 //===----------------------------------------------------------------------===//
1347 // Helper methods for lexing.
1348 //===----------------------------------------------------------------------===//
1350 /// \brief Routine that indiscriminately skips bytes in the source file.
1351 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) {
1353 if (BufferPtr > BufferEnd)
1354 BufferPtr = BufferEnd;
1355 // FIXME: What exactly does the StartOfLine bit mean? There are two
1356 // possible meanings for the "start" of the line: the first token on the
1357 // unexpanded line, or the first token on the expanded line.
1358 IsAtStartOfLine = StartOfLine;
1359 IsAtPhysicalStartOfLine = StartOfLine;
1362 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
1363 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1364 static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
1365 C11AllowedIDCharRanges);
1366 return C11AllowedIDChars.contains(C);
1367 } else if (LangOpts.CPlusPlus) {
1368 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1369 CXX03AllowedIDCharRanges);
1370 return CXX03AllowedIDChars.contains(C);
1372 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1373 C99AllowedIDCharRanges);
1374 return C99AllowedIDChars.contains(C);
1378 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
1379 assert(isAllowedIDChar(C, LangOpts));
1380 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
1381 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
1382 C11DisallowedInitialIDCharRanges);
1383 return !C11DisallowedInitialIDChars.contains(C);
1384 } else if (LangOpts.CPlusPlus) {
1387 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1388 C99DisallowedInitialIDCharRanges);
1389 return !C99DisallowedInitialIDChars.contains(C);
1393 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
1395 return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
1396 L.getSourceLocation(End));
1399 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
1400 CharSourceRange Range, bool IsFirst) {
1401 // Check C99 compatibility.
1402 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
1404 CannotAppearInIdentifier = 0,
1405 CannotStartIdentifier
1408 static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
1409 C99AllowedIDCharRanges);
1410 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
1411 C99DisallowedInitialIDCharRanges);
1412 if (!C99AllowedIDChars.contains(C)) {
1413 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1415 << CannotAppearInIdentifier;
1416 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
1417 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
1419 << CannotStartIdentifier;
1423 // Check C++98 compatibility.
1424 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) {
1425 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars(
1426 CXX03AllowedIDCharRanges);
1427 if (!CXX03AllowedIDChars.contains(C)) {
1428 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id)
1434 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
1436 const char *UCNPtr = CurPtr + Size;
1437 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
1438 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts))
1441 if (!isLexingRawMode())
1442 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1443 makeCharRange(*this, CurPtr, UCNPtr),
1446 Result.setFlag(Token::HasUCN);
1447 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
1448 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
1451 while (CurPtr != UCNPtr)
1452 (void)getAndAdvanceChar(CurPtr, Result);
1456 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
1457 const char *UnicodePtr = CurPtr;
1459 ConversionResult Result =
1460 llvm::convertUTF8Sequence((const UTF8 **)&UnicodePtr,
1461 (const UTF8 *)BufferEnd,
1464 if (Result != conversionOK ||
1465 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts))
1468 if (!isLexingRawMode())
1469 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
1470 makeCharRange(*this, CurPtr, UnicodePtr),
1473 CurPtr = UnicodePtr;
1477 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) {
1478 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$]
1480 unsigned char C = *CurPtr++;
1481 while (isIdentifierBody(C))
1484 --CurPtr; // Back up over the skipped character.
1486 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline
1487 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN.
1489 // TODO: Could merge these checks into an InfoTable flag to make the
1490 // comparison cheaper
1491 if (isASCII(C) && C != '\\' && C != '?' &&
1492 (C != '$' || !LangOpts.DollarIdents)) {
1494 const char *IdStart = BufferPtr;
1495 FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
1496 Result.setRawIdentifierData(IdStart);
1498 // If we are in raw mode, return this identifier raw. There is no need to
1499 // look up identifier information or attempt to macro expand it.
1503 // Fill in Result.IdentifierInfo and update the token kind,
1504 // looking up the identifier in the identifier table.
1505 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
1507 // Finally, now that we know we have an identifier, pass this off to the
1508 // preprocessor, which may macro expand it or something.
1509 if (II->isHandleIdentifierCase())
1510 return PP->HandleIdentifier(Result);
1515 // Otherwise, $,\,? in identifier found. Enter slower path.
1517 C = getCharAndSize(CurPtr, Size);
1520 // If we hit a $ and they are not supported in identifiers, we are done.
1521 if (!LangOpts.DollarIdents) goto FinishIdentifier;
1523 // Otherwise, emit a diagnostic and continue.
1524 if (!isLexingRawMode())
1525 Diag(CurPtr, diag::ext_dollar_in_identifier);
1526 CurPtr = ConsumeChar(CurPtr, Size, Result);
1527 C = getCharAndSize(CurPtr, Size);
1530 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
1531 C = getCharAndSize(CurPtr, Size);
1533 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
1534 C = getCharAndSize(CurPtr, Size);
1536 } else if (!isIdentifierBody(C)) {
1537 goto FinishIdentifier;
1540 // Otherwise, this character is good, consume it.
1541 CurPtr = ConsumeChar(CurPtr, Size, Result);
1543 C = getCharAndSize(CurPtr, Size);
1544 while (isIdentifierBody(C)) {
1545 CurPtr = ConsumeChar(CurPtr, Size, Result);
1546 C = getCharAndSize(CurPtr, Size);
1551 /// isHexaLiteral - Return true if Start points to a hex constant.
1552 /// in microsoft mode (where this is supposed to be several different tokens).
1553 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
1555 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
1558 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
1559 return (C2 == 'x' || C2 == 'X');
1562 /// LexNumericConstant - Lex the remainder of a integer or floating point
1563 /// constant. From[-1] is the first character lexed. Return the end of the
1565 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
1567 char C = getCharAndSize(CurPtr, Size);
1569 while (isPreprocessingNumberBody(C)) {
1570 CurPtr = ConsumeChar(CurPtr, Size, Result);
1572 C = getCharAndSize(CurPtr, Size);
1575 // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
1576 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
1577 // If we are in Microsoft mode, don't continue if the constant is hex.
1578 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
1579 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
1580 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1583 // If we have a hex FP constant, continue.
1584 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
1585 // Outside C99, we accept hexadecimal floating point numbers as a
1586 // not-quite-conforming extension. Only do so if this looks like it's
1587 // actually meant to be a hexfloat, and not if it has a ud-suffix.
1588 bool IsHexFloat = true;
1589 if (!LangOpts.C99) {
1590 if (!isHexaLiteral(BufferPtr, LangOpts))
1592 else if (std::find(BufferPtr, CurPtr, '_') != CurPtr)
1596 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
1599 // If we have a digit separator, continue.
1600 if (C == '\'' && getLangOpts().CPlusPlus1y) {
1602 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
1603 if (isIdentifierBody(Next)) {
1604 if (!isLexingRawMode())
1605 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator);
1606 CurPtr = ConsumeChar(CurPtr, Size, Result);
1607 CurPtr = ConsumeChar(CurPtr, NextSize, Result);
1608 return LexNumericConstant(Result, CurPtr);
1612 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
1613 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1614 return LexNumericConstant(Result, CurPtr);
1615 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1616 return LexNumericConstant(Result, CurPtr);
1618 // Update the location of token as well as BufferPtr.
1619 const char *TokStart = BufferPtr;
1620 FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
1621 Result.setLiteralData(TokStart);
1625 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
1626 /// in C++11, or warn on a ud-suffix in C++98.
1627 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
1628 bool IsStringLiteral) {
1629 assert(getLangOpts().CPlusPlus);
1631 // Maximally munch an identifier.
1633 char C = getCharAndSize(CurPtr, Size);
1634 bool Consumed = false;
1636 if (!isIdentifierHead(C)) {
1637 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
1639 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
1645 if (!getLangOpts().CPlusPlus11) {
1646 if (!isLexingRawMode())
1648 C == '_' ? diag::warn_cxx11_compat_user_defined_literal
1649 : diag::warn_cxx11_compat_reserved_user_defined_literal)
1650 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1654 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
1655 // that does not start with an underscore is ill-formed. As a conforming
1656 // extension, we treat all such suffixes as if they had whitespace before
1657 // them. We assume a suffix beginning with a UCN or UTF-8 character is more
1658 // likely to be a ud-suffix than a macro, however, and accept that.
1660 bool IsUDSuffix = false;
1663 else if (IsStringLiteral && getLangOpts().CPlusPlus1y) {
1664 // In C++1y, we need to look ahead a few characters to see if this is a
1665 // valid suffix for a string literal or a numeric literal (this could be
1666 // the 'operator""if' defining a numeric literal operator).
1667 const unsigned MaxStandardSuffixLength = 3;
1668 char Buffer[MaxStandardSuffixLength] = { C };
1669 unsigned Consumed = Size;
1673 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
1675 if (!isIdentifierBody(Next)) {
1676 // End of suffix. Check whether this is on the whitelist.
1677 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') ||
1678 NumericLiteralParser::isValidUDSuffix(
1679 getLangOpts(), StringRef(Buffer, Chars));
1683 if (Chars == MaxStandardSuffixLength)
1684 // Too long: can't be a standard suffix.
1687 Buffer[Chars++] = Next;
1688 Consumed += NextSize;
1693 if (!isLexingRawMode())
1694 Diag(CurPtr, getLangOpts().MSVCCompat
1695 ? diag::ext_ms_reserved_user_defined_literal
1696 : diag::ext_reserved_user_defined_literal)
1697 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
1701 CurPtr = ConsumeChar(CurPtr, Size, Result);
1704 Result.setFlag(Token::HasUDSuffix);
1706 C = getCharAndSize(CurPtr, Size);
1707 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); }
1708 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {}
1709 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {}
1716 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
1717 /// either " or L" or u8" or u" or U".
1718 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
1719 tok::TokenKind Kind) {
1720 // Does this string contain the \0 character?
1721 const char *NulCharacter = nullptr;
1723 if (!isLexingRawMode() &&
1724 (Kind == tok::utf8_string_literal ||
1725 Kind == tok::utf16_string_literal ||
1726 Kind == tok::utf32_string_literal))
1727 Diag(BufferPtr, getLangOpts().CPlusPlus
1728 ? diag::warn_cxx98_compat_unicode_literal
1729 : diag::warn_c99_compat_unicode_literal);
1731 char C = getAndAdvanceChar(CurPtr, Result);
1733 // Skip escaped characters. Escaped newlines will already be processed by
1734 // getAndAdvanceChar.
1736 C = getAndAdvanceChar(CurPtr, Result);
1738 if (C == '\n' || C == '\r' || // Newline.
1739 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1740 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1741 Diag(BufferPtr, diag::ext_unterminated_string);
1742 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1747 if (isCodeCompletionPoint(CurPtr-1)) {
1748 PP->CodeCompleteNaturalLanguage();
1749 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1754 NulCharacter = CurPtr-1;
1756 C = getAndAdvanceChar(CurPtr, Result);
1759 // If we are in C++11, lex the optional ud-suffix.
1760 if (getLangOpts().CPlusPlus)
1761 CurPtr = LexUDSuffix(Result, CurPtr, true);
1763 // If a nul character existed in the string, warn about it.
1764 if (NulCharacter && !isLexingRawMode())
1765 Diag(NulCharacter, diag::null_in_string);
1767 // Update the location of the token as well as the BufferPtr instance var.
1768 const char *TokStart = BufferPtr;
1769 FormTokenWithChars(Result, CurPtr, Kind);
1770 Result.setLiteralData(TokStart);
1774 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
1775 /// having lexed R", LR", u8R", uR", or UR".
1776 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
1777 tok::TokenKind Kind) {
1778 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
1779 // Between the initial and final double quote characters of the raw string,
1780 // any transformations performed in phases 1 and 2 (trigraphs,
1781 // universal-character-names, and line splicing) are reverted.
1783 if (!isLexingRawMode())
1784 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
1786 unsigned PrefixLen = 0;
1788 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
1791 // If the last character was not a '(', then we didn't lex a valid delimiter.
1792 if (CurPtr[PrefixLen] != '(') {
1793 if (!isLexingRawMode()) {
1794 const char *PrefixEnd = &CurPtr[PrefixLen];
1795 if (PrefixLen == 16) {
1796 Diag(PrefixEnd, diag::err_raw_delim_too_long);
1798 Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
1799 << StringRef(PrefixEnd, 1);
1803 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
1804 // it's possible the '"' was intended to be part of the raw string, but
1805 // there's not much we can do about that.
1811 if (C == 0 && CurPtr-1 == BufferEnd) {
1817 FormTokenWithChars(Result, CurPtr, tok::unknown);
1821 // Save prefix and move CurPtr past it
1822 const char *Prefix = CurPtr;
1823 CurPtr += PrefixLen + 1; // skip over prefix and '('
1829 // Check for prefix match and closing quote.
1830 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
1831 CurPtr += PrefixLen + 1; // skip over prefix and '"'
1834 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
1835 if (!isLexingRawMode())
1836 Diag(BufferPtr, diag::err_unterminated_raw_string)
1837 << StringRef(Prefix, PrefixLen);
1838 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1843 // If we are in C++11, lex the optional ud-suffix.
1844 if (getLangOpts().CPlusPlus)
1845 CurPtr = LexUDSuffix(Result, CurPtr, true);
1847 // Update the location of token as well as BufferPtr.
1848 const char *TokStart = BufferPtr;
1849 FormTokenWithChars(Result, CurPtr, Kind);
1850 Result.setLiteralData(TokStart);
1854 /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
1855 /// after having lexed the '<' character. This is used for #include filenames.
1856 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
1857 // Does this string contain the \0 character?
1858 const char *NulCharacter = nullptr;
1859 const char *AfterLessPos = CurPtr;
1860 char C = getAndAdvanceChar(CurPtr, Result);
1862 // Skip escaped characters.
1864 // Skip the escaped character.
1865 getAndAdvanceChar(CurPtr, Result);
1866 } else if (C == '\n' || C == '\r' || // Newline.
1867 (C == 0 && (CurPtr-1 == BufferEnd || // End of file.
1868 isCodeCompletionPoint(CurPtr-1)))) {
1869 // If the filename is unterminated, then it must just be a lone <
1870 // character. Return this as such.
1871 FormTokenWithChars(Result, AfterLessPos, tok::less);
1873 } else if (C == 0) {
1874 NulCharacter = CurPtr-1;
1876 C = getAndAdvanceChar(CurPtr, Result);
1879 // If a nul character existed in the string, warn about it.
1880 if (NulCharacter && !isLexingRawMode())
1881 Diag(NulCharacter, diag::null_in_string);
1883 // Update the location of token as well as BufferPtr.
1884 const char *TokStart = BufferPtr;
1885 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal);
1886 Result.setLiteralData(TokStart);
1891 /// LexCharConstant - Lex the remainder of a character constant, after having
1892 /// lexed either ' or L' or u' or U'.
1893 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
1894 tok::TokenKind Kind) {
1895 // Does this character contain the \0 character?
1896 const char *NulCharacter = nullptr;
1898 if (!isLexingRawMode() &&
1899 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant))
1900 Diag(BufferPtr, getLangOpts().CPlusPlus
1901 ? diag::warn_cxx98_compat_unicode_literal
1902 : diag::warn_c99_compat_unicode_literal);
1904 char C = getAndAdvanceChar(CurPtr, Result);
1906 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1907 Diag(BufferPtr, diag::ext_empty_character);
1908 FormTokenWithChars(Result, CurPtr, tok::unknown);
1913 // Skip escaped characters.
1915 C = getAndAdvanceChar(CurPtr, Result);
1917 if (C == '\n' || C == '\r' || // Newline.
1918 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
1919 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
1920 Diag(BufferPtr, diag::ext_unterminated_char);
1921 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1926 if (isCodeCompletionPoint(CurPtr-1)) {
1927 PP->CodeCompleteNaturalLanguage();
1928 FormTokenWithChars(Result, CurPtr-1, tok::unknown);
1933 NulCharacter = CurPtr-1;
1935 C = getAndAdvanceChar(CurPtr, Result);
1938 // If we are in C++11, lex the optional ud-suffix.
1939 if (getLangOpts().CPlusPlus)
1940 CurPtr = LexUDSuffix(Result, CurPtr, false);
1942 // If a nul character existed in the character, warn about it.
1943 if (NulCharacter && !isLexingRawMode())
1944 Diag(NulCharacter, diag::null_in_char);
1946 // Update the location of token as well as BufferPtr.
1947 const char *TokStart = BufferPtr;
1948 FormTokenWithChars(Result, CurPtr, Kind);
1949 Result.setLiteralData(TokStart);
1953 /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
1954 /// Update BufferPtr to point to the next non-whitespace character and return.
1956 /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
1958 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
1959 bool &TokAtPhysicalStartOfLine) {
1960 // Whitespace - Skip it, then return the token after the whitespace.
1961 bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
1963 unsigned char Char = *CurPtr;
1965 // Skip consecutive spaces efficiently.
1967 // Skip horizontal whitespace very aggressively.
1968 while (isHorizontalWhitespace(Char))
1971 // Otherwise if we have something other than whitespace, we're done.
1972 if (!isVerticalWhitespace(Char))
1975 if (ParsingPreprocessorDirective) {
1976 // End of preprocessor directive line, let LexTokenInternal handle this.
1981 // OK, but handle newline.
1986 // If the client wants us to return whitespace, return it now.
1987 if (isKeepWhitespaceMode()) {
1988 FormTokenWithChars(Result, CurPtr, tok::unknown);
1990 IsAtStartOfLine = true;
1991 IsAtPhysicalStartOfLine = true;
1993 // FIXME: The next token will not have LeadingSpace set.
1997 // If this isn't immediately after a newline, there is leading space.
1998 char PrevChar = CurPtr[-1];
1999 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
2001 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2003 Result.setFlag(Token::StartOfLine);
2004 TokAtPhysicalStartOfLine = true;
2011 /// We have just read the // characters from input. Skip until we find the
2012 /// newline character thats terminate the comment. Then update BufferPtr and
2015 /// If we're in KeepCommentMode or any CommentHandler has inserted
2016 /// some tokens, this will store the first token and return true.
2017 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
2018 bool &TokAtPhysicalStartOfLine) {
2019 // If Line comments aren't explicitly enabled for this language, emit an
2020 // extension warning.
2021 if (!LangOpts.LineComment && !isLexingRawMode()) {
2022 Diag(BufferPtr, diag::ext_line_comment);
2024 // Mark them enabled so we only emit one warning for this translation
2026 LangOpts.LineComment = true;
2029 // Scan over the body of the comment. The common case, when scanning, is that
2030 // the comment contains normal ascii characters with nothing interesting in
2031 // them. As such, optimize for this case with the inner loop.
2035 // Skip over characters in the fast loop.
2036 while (C != 0 && // Potentially EOF.
2037 C != '\n' && C != '\r') // Newline or DOS-style newline.
2040 const char *NextLine = CurPtr;
2042 // We found a newline, see if it's escaped.
2043 const char *EscapePtr = CurPtr-1;
2044 bool HasSpace = false;
2045 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
2050 if (*EscapePtr == '\\') // Escaped newline.
2052 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
2053 EscapePtr[-2] == '?') // Trigraph-escaped newline.
2054 CurPtr = EscapePtr-2;
2056 break; // This is a newline, we're done.
2058 // If there was space between the backslash and newline, warn about it.
2059 if (HasSpace && !isLexingRawMode())
2060 Diag(EscapePtr, diag::backslash_newline_space);
2063 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
2064 // properly decode the character. Read it in raw mode to avoid emitting
2065 // diagnostics about things like trigraphs. If we see an escaped newline,
2066 // we'll handle it below.
2067 const char *OldPtr = CurPtr;
2068 bool OldRawMode = isLexingRawMode();
2069 LexingRawMode = true;
2070 C = getAndAdvanceChar(CurPtr, Result);
2071 LexingRawMode = OldRawMode;
2073 // If we only read only one character, then no special handling is needed.
2074 // We're done and can skip forward to the newline.
2075 if (C != 0 && CurPtr == OldPtr+1) {
2080 // If we read multiple characters, and one of those characters was a \r or
2081 // \n, then we had an escaped newline within the comment. Emit diagnostic
2082 // unless the next line is also a // comment.
2083 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') {
2084 for (; OldPtr != CurPtr; ++OldPtr)
2085 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
2086 // Okay, we found a // comment that ends in a newline, if the next
2087 // line is also a // comment, but has spaces, don't emit a diagnostic.
2088 if (isWhitespace(C)) {
2089 const char *ForwardPtr = CurPtr;
2090 while (isWhitespace(*ForwardPtr)) // Skip whitespace.
2092 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
2096 if (!isLexingRawMode())
2097 Diag(OldPtr-1, diag::ext_multi_line_line_comment);
2102 if (CurPtr == BufferEnd+1) {
2107 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2108 PP->CodeCompleteNaturalLanguage();
2113 } while (C != '\n' && C != '\r');
2115 // Found but did not consume the newline. Notify comment handlers about the
2116 // comment unless we're in a #if 0 block.
2117 if (PP && !isLexingRawMode() &&
2118 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2119 getSourceLocation(CurPtr)))) {
2121 return true; // A token has to be returned.
2124 // If we are returning comments as tokens, return this comment as a token.
2125 if (inKeepCommentMode())
2126 return SaveLineComment(Result, CurPtr);
2128 // If we are inside a preprocessor directive and we see the end of line,
2129 // return immediately, so that the lexer can return this as an EOD token.
2130 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
2135 // Otherwise, eat the \n character. We don't care if this is a \n\r or
2136 // \r\n sequence. This is an efficiency hack (because we know the \n can't
2137 // contribute to another token), it isn't needed for correctness. Note that
2138 // this is ok even in KeepWhitespaceMode, because we would have returned the
2139 /// comment above in that mode.
2142 // The next returned token is at the start of the line.
2143 Result.setFlag(Token::StartOfLine);
2144 TokAtPhysicalStartOfLine = true;
2145 // No leading whitespace seen so far.
2146 Result.clearFlag(Token::LeadingSpace);
2151 /// If in save-comment mode, package up this Line comment in an appropriate
2152 /// way and return it.
2153 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
2154 // If we're not in a preprocessor directive, just return the // comment
2156 FormTokenWithChars(Result, CurPtr, tok::comment);
2158 if (!ParsingPreprocessorDirective || LexingRawMode)
2161 // If this Line-style comment is in a macro definition, transmogrify it into
2162 // a C-style block comment.
2163 bool Invalid = false;
2164 std::string Spelling = PP->getSpelling(Result, &Invalid);
2168 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
2169 Spelling[1] = '*'; // Change prefix to "/*".
2170 Spelling += "*/"; // add suffix.
2172 Result.setKind(tok::comment);
2173 PP->CreateString(Spelling, Result,
2174 Result.getLocation(), Result.getLocation());
2178 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
2179 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
2180 /// a diagnostic if so. We know that the newline is inside of a block comment.
2181 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
2183 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
2185 // Back up off the newline.
2188 // If this is a two-character newline sequence, skip the other character.
2189 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
2190 // \n\n or \r\r -> not escaped newline.
2191 if (CurPtr[0] == CurPtr[1])
2193 // \n\r or \r\n -> skip the newline.
2197 // If we have horizontal whitespace, skip over it. We allow whitespace
2198 // between the slash and newline.
2199 bool HasSpace = false;
2200 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
2205 // If we have a slash, we know this is an escaped newline.
2206 if (*CurPtr == '\\') {
2207 if (CurPtr[-1] != '*') return false;
2209 // It isn't a slash, is it the ?? / trigraph?
2210 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' ||
2214 // This is the trigraph ending the comment. Emit a stern warning!
2217 // If no trigraphs are enabled, warn that we ignored this trigraph and
2218 // ignore this * character.
2219 if (!L->getLangOpts().Trigraphs) {
2220 if (!L->isLexingRawMode())
2221 L->Diag(CurPtr, diag::trigraph_ignored_block_comment);
2224 if (!L->isLexingRawMode())
2225 L->Diag(CurPtr, diag::trigraph_ends_block_comment);
2228 // Warn about having an escaped newline between the */ characters.
2229 if (!L->isLexingRawMode())
2230 L->Diag(CurPtr, diag::escaped_newline_block_comment_end);
2232 // If there was space between the backslash and newline, warn about it.
2233 if (HasSpace && !L->isLexingRawMode())
2234 L->Diag(CurPtr, diag::backslash_newline_space);
2240 #include <emmintrin.h>
2242 #include <altivec.h>
2246 /// We have just read from input the / and * characters that started a comment.
2247 /// Read until we find the * and / characters that terminate the comment.
2248 /// Note that we don't bother decoding trigraphs or escaped newlines in block
2249 /// comments, because they cannot cause the comment to end. The only thing
2250 /// that can happen is the comment could end with an escaped newline between
2251 /// the terminating * and /.
2253 /// If we're in KeepCommentMode or any CommentHandler has inserted
2254 /// some tokens, this will store the first token and return true.
2255 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
2256 bool &TokAtPhysicalStartOfLine) {
2257 // Scan one character past where we should, looking for a '/' character. Once
2258 // we find it, check to see if it was preceded by a *. This common
2259 // optimization helps people who like to put a lot of * characters in their
2262 // The first character we get with newlines and trigraphs skipped to handle
2263 // the degenerate /*/ case below correctly if the * has an escaped newline
2266 unsigned char C = getCharAndSize(CurPtr, CharSize);
2268 if (C == 0 && CurPtr == BufferEnd+1) {
2269 if (!isLexingRawMode())
2270 Diag(BufferPtr, diag::err_unterminated_block_comment);
2273 // KeepWhitespaceMode should return this broken comment as a token. Since
2274 // it isn't a well formed comment, just return it as an 'unknown' token.
2275 if (isKeepWhitespaceMode()) {
2276 FormTokenWithChars(Result, CurPtr, tok::unknown);
2284 // Check to see if the first character after the '/*' is another /. If so,
2285 // then this slash does not end the block comment, it is part of it.
2290 // Skip over all non-interesting characters until we find end of buffer or a
2291 // (probably ending) '/' character.
2292 if (CurPtr + 24 < BufferEnd &&
2293 // If there is a code-completion point avoid the fast scan because it
2294 // doesn't check for '\0'.
2295 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
2296 // While not aligned to a 16-byte boundary.
2297 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
2300 if (C == '/') goto FoundSlash;
2303 __m128i Slashes = _mm_set1_epi8('/');
2304 while (CurPtr+16 <= BufferEnd) {
2305 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
2308 // Adjust the pointer to point directly after the first slash. It's
2309 // not necessary to set C here, it will be overwritten at the end of
2311 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
2317 __vector unsigned char Slashes = {
2318 '/', '/', '/', '/', '/', '/', '/', '/',
2319 '/', '/', '/', '/', '/', '/', '/', '/'
2321 while (CurPtr+16 <= BufferEnd &&
2322 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes))
2325 // Scan for '/' quickly. Many block comments are very large.
2326 while (CurPtr[0] != '/' &&
2330 CurPtr+4 < BufferEnd) {
2335 // It has to be one of the bytes scanned, increment to it and read one.
2339 // Loop to scan the remainder.
2340 while (C != '/' && C != '\0')
2345 if (CurPtr[-2] == '*') // We found the final */. We're done!
2348 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
2349 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
2350 // We found the final */, though it had an escaped newline between the
2351 // * and /. We're done!
2355 if (CurPtr[0] == '*' && CurPtr[1] != '/') {
2356 // If this is a /* inside of the comment, emit a warning. Don't do this
2357 // if this is a /*/, which will end the comment. This misses cases with
2358 // embedded escaped newlines, but oh well.
2359 if (!isLexingRawMode())
2360 Diag(CurPtr-1, diag::warn_nested_block_comment);
2362 } else if (C == 0 && CurPtr == BufferEnd+1) {
2363 if (!isLexingRawMode())
2364 Diag(BufferPtr, diag::err_unterminated_block_comment);
2365 // Note: the user probably forgot a */. We could continue immediately
2366 // after the /*, but this would involve lexing a lot of what really is the
2367 // comment, which surely would confuse the parser.
2370 // KeepWhitespaceMode should return this broken comment as a token. Since
2371 // it isn't a well formed comment, just return it as an 'unknown' token.
2372 if (isKeepWhitespaceMode()) {
2373 FormTokenWithChars(Result, CurPtr, tok::unknown);
2379 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
2380 PP->CodeCompleteNaturalLanguage();
2388 // Notify comment handlers about the comment unless we're in a #if 0 block.
2389 if (PP && !isLexingRawMode() &&
2390 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
2391 getSourceLocation(CurPtr)))) {
2393 return true; // A token has to be returned.
2396 // If we are returning comments as tokens, return this comment as a token.
2397 if (inKeepCommentMode()) {
2398 FormTokenWithChars(Result, CurPtr, tok::comment);
2402 // It is common for the tokens immediately after a /**/ comment to be
2403 // whitespace. Instead of going through the big switch, handle it
2404 // efficiently now. This is safe even in KeepWhitespaceMode because we would
2405 // have already returned above with the comment as a token.
2406 if (isHorizontalWhitespace(*CurPtr)) {
2407 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
2411 // Otherwise, just return so that the next character will be lexed as a token.
2413 Result.setFlag(Token::LeadingSpace);
2417 //===----------------------------------------------------------------------===//
2418 // Primary Lexing Entry Points
2419 //===----------------------------------------------------------------------===//
2421 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
2422 /// uninterpreted string. This switches the lexer out of directive mode.
2423 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
2424 assert(ParsingPreprocessorDirective && ParsingFilename == false &&
2425 "Must be in a preprocessing directive!");
2428 // CurPtr - Cache BufferPtr in an automatic variable.
2429 const char *CurPtr = BufferPtr;
2431 char Char = getAndAdvanceChar(CurPtr, Tmp);
2435 Result->push_back(Char);
2438 // Found end of file?
2439 if (CurPtr-1 != BufferEnd) {
2440 if (isCodeCompletionPoint(CurPtr-1)) {
2441 PP->CodeCompleteNaturalLanguage();
2446 // Nope, normal character, continue.
2448 Result->push_back(Char);
2454 // Okay, we found the end of the line. First, back up past the \0, \r, \n.
2455 assert(CurPtr[-1] == Char && "Trigraphs for newline?");
2456 BufferPtr = CurPtr-1;
2458 // Next, lex the character, which should handle the EOD transition.
2460 if (Tmp.is(tok::code_completion)) {
2462 PP->CodeCompleteNaturalLanguage();
2465 assert(Tmp.is(tok::eod) && "Unexpected token!");
2467 // Finally, we're done;
2473 /// LexEndOfFile - CurPtr points to the end of this file. Handle this
2474 /// condition, reporting diagnostics and handling other edge cases as required.
2475 /// This returns true if Result contains a token, false if PP.Lex should be
2477 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
2478 // If we hit the end of the file while parsing a preprocessor directive,
2479 // end the preprocessor directive first. The next token returned will
2480 // then be the end of file.
2481 if (ParsingPreprocessorDirective) {
2482 // Done parsing the "line".
2483 ParsingPreprocessorDirective = false;
2484 // Update the location of token as well as BufferPtr.
2485 FormTokenWithChars(Result, CurPtr, tok::eod);
2487 // Restore comment saving mode, in case it was disabled for directive.
2489 resetExtendedTokenMode();
2490 return true; // Have a token.
2493 // If we are in raw mode, return this event as an EOF token. Let the caller
2494 // that put us in raw mode handle the event.
2495 if (isLexingRawMode()) {
2496 Result.startToken();
2497 BufferPtr = BufferEnd;
2498 FormTokenWithChars(Result, BufferEnd, tok::eof);
2502 // Issue diagnostics for unterminated #if and missing newline.
2504 // If we are in a #if directive, emit an error.
2505 while (!ConditionalStack.empty()) {
2506 if (PP->getCodeCompletionFileLoc() != FileLoc)
2507 PP->Diag(ConditionalStack.back().IfLoc,
2508 diag::err_pp_unterminated_conditional);
2509 ConditionalStack.pop_back();
2512 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
2514 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
2515 DiagnosticsEngine &Diags = PP->getDiagnostics();
2516 SourceLocation EndLoc = getSourceLocation(BufferEnd);
2519 if (LangOpts.CPlusPlus11) {
2520 // C++11 [lex.phases] 2.2 p2
2521 // Prefer the C++98 pedantic compatibility warning over the generic,
2522 // non-extension, user-requested "missing newline at EOF" warning.
2523 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
2524 DiagID = diag::warn_cxx98_compat_no_newline_eof;
2526 DiagID = diag::warn_no_newline_eof;
2529 DiagID = diag::ext_no_newline_eof;
2532 Diag(BufferEnd, DiagID)
2533 << FixItHint::CreateInsertion(EndLoc, "\n");
2538 // Finally, let the preprocessor handle this.
2539 return PP->HandleEndOfFile(Result, isPragmaLexer());
2542 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
2543 /// the specified lexer will return a tok::l_paren token, 0 if it is something
2544 /// else and 2 if there are no more tokens in the buffer controlled by the
2546 unsigned Lexer::isNextPPTokenLParen() {
2547 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
2549 // Switch to 'skipping' mode. This will ensure that we can lex a token
2550 // without emitting diagnostics, disables macro expansion, and will cause EOF
2551 // to return an EOF token instead of popping the include stack.
2552 LexingRawMode = true;
2554 // Save state that can be changed while lexing so that we can restore it.
2555 const char *TmpBufferPtr = BufferPtr;
2556 bool inPPDirectiveMode = ParsingPreprocessorDirective;
2557 bool atStartOfLine = IsAtStartOfLine;
2558 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2559 bool leadingSpace = HasLeadingSpace;
2564 // Restore state that may have changed.
2565 BufferPtr = TmpBufferPtr;
2566 ParsingPreprocessorDirective = inPPDirectiveMode;
2567 HasLeadingSpace = leadingSpace;
2568 IsAtStartOfLine = atStartOfLine;
2569 IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
2571 // Restore the lexer back to non-skipping mode.
2572 LexingRawMode = false;
2574 if (Tok.is(tok::eof))
2576 return Tok.is(tok::l_paren);
2579 /// \brief Find the end of a version control conflict marker.
2580 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
2581 ConflictMarkerKind CMK) {
2582 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
2583 size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
2584 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen);
2585 size_t Pos = RestOfBuffer.find(Terminator);
2586 while (Pos != StringRef::npos) {
2587 // Must occur at start of line.
2588 if (RestOfBuffer[Pos-1] != '\r' &&
2589 RestOfBuffer[Pos-1] != '\n') {
2590 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
2591 Pos = RestOfBuffer.find(Terminator);
2594 return RestOfBuffer.data()+Pos;
2599 /// IsStartOfConflictMarker - If the specified pointer is the start of a version
2600 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
2601 /// and recover nicely. This returns true if it is a conflict marker and false
2603 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
2604 // Only a conflict marker if it starts at the beginning of a line.
2605 if (CurPtr != BufferStart &&
2606 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2609 // Check to see if we have <<<<<<< or >>>>.
2610 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") &&
2611 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> "))
2614 // If we have a situation where we don't care about conflict markers, ignore
2616 if (CurrentConflictMarkerState || isLexingRawMode())
2619 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
2621 // Check to see if there is an ending marker somewhere in the buffer at the
2622 // start of a line to terminate this conflict marker.
2623 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
2624 // We found a match. We are really in a conflict marker.
2625 // Diagnose this, and ignore to the end of line.
2626 Diag(CurPtr, diag::err_conflict_marker);
2627 CurrentConflictMarkerState = Kind;
2629 // Skip ahead to the end of line. We know this exists because the
2630 // end-of-conflict marker starts with \r or \n.
2631 while (*CurPtr != '\r' && *CurPtr != '\n') {
2632 assert(CurPtr != BufferEnd && "Didn't find end of line");
2639 // No end of conflict marker found.
2644 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
2645 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
2646 /// is the end of a conflict marker. Handle it by ignoring up until the end of
2647 /// the line. This returns true if it is a conflict marker and false if not.
2648 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
2649 // Only a conflict marker if it starts at the beginning of a line.
2650 if (CurPtr != BufferStart &&
2651 CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
2654 // If we have a situation where we don't care about conflict markers, ignore
2656 if (!CurrentConflictMarkerState || isLexingRawMode())
2659 // Check to see if we have the marker (4 characters in a row).
2660 for (unsigned i = 1; i != 4; ++i)
2661 if (CurPtr[i] != CurPtr[0])
2664 // If we do have it, search for the end of the conflict marker. This could
2665 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
2666 // be the end of conflict marker.
2667 if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
2668 CurrentConflictMarkerState)) {
2671 // Skip ahead to the end of line.
2672 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
2677 // No longer in the conflict marker.
2678 CurrentConflictMarkerState = CMK_None;
2685 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
2686 if (PP && PP->isCodeCompletionEnabled()) {
2687 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
2688 return Loc == PP->getCodeCompletionLoc();
2694 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
2697 char Kind = getCharAndSize(StartPtr, CharSize);
2699 unsigned NumHexDigits;
2702 else if (Kind == 'U')
2707 if (!LangOpts.CPlusPlus && !LangOpts.C99) {
2708 if (Result && !isLexingRawMode())
2709 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
2713 const char *CurPtr = StartPtr + CharSize;
2714 const char *KindLoc = &CurPtr[-1];
2716 uint32_t CodePoint = 0;
2717 for (unsigned i = 0; i < NumHexDigits; ++i) {
2718 char C = getCharAndSize(CurPtr, CharSize);
2720 unsigned Value = llvm::hexDigitValue(C);
2722 if (Result && !isLexingRawMode()) {
2724 Diag(BufferPtr, diag::warn_ucn_escape_no_digits)
2725 << StringRef(KindLoc, 1);
2727 Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
2729 // If the user wrote \U1234, suggest a fixit to \u.
2730 if (i == 4 && NumHexDigits == 8) {
2731 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
2732 Diag(KindLoc, diag::note_ucn_four_not_eight)
2733 << FixItHint::CreateReplacement(URange, "u");
2748 Result->setFlag(Token::HasUCN);
2749 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2)
2752 while (StartPtr != CurPtr)
2753 (void)getAndAdvanceChar(StartPtr, *Result);
2758 // Don't apply C family restrictions to UCNs in assembly mode
2759 if (LangOpts.AsmPreprocessor)
2762 // C99 6.4.3p2: A universal character name shall not specify a character whose
2763 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
2764 // 0060 (`), nor one in the range D800 through DFFF inclusive.)
2765 // C++11 [lex.charset]p2: If the hexadecimal value for a
2766 // universal-character-name corresponds to a surrogate code point (in the
2767 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
2768 // if the hexadecimal value for a universal-character-name outside the
2769 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
2770 // string literal corresponds to a control character (in either of the
2771 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
2772 // basic source character set, the program is ill-formed.
2773 if (CodePoint < 0xA0) {
2774 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
2777 // We don't use isLexingRawMode() here because we need to warn about bad
2778 // UCNs even when skipping preprocessing tokens in a #if block.
2780 if (CodePoint < 0x20 || CodePoint >= 0x7F)
2781 Diag(BufferPtr, diag::err_ucn_control_character);
2783 char C = static_cast<char>(CodePoint);
2784 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
2790 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
2791 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
2792 // We don't use isLexingRawMode() here because we need to diagnose bad
2793 // UCNs even when skipping preprocessing tokens in a #if block.
2795 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
2796 Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
2798 Diag(BufferPtr, diag::err_ucn_escape_invalid);
2806 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
2807 const char *CurPtr) {
2808 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
2809 UnicodeWhitespaceCharRanges);
2810 if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
2811 UnicodeWhitespaceChars.contains(C)) {
2812 Diag(BufferPtr, diag::ext_unicode_whitespace)
2813 << makeCharRange(*this, BufferPtr, CurPtr);
2815 Result.setFlag(Token::LeadingSpace);
2821 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) {
2822 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) {
2823 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2824 !PP->isPreprocessedOutput()) {
2825 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
2826 makeCharRange(*this, BufferPtr, CurPtr),
2831 return LexIdentifier(Result, CurPtr);
2834 if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
2835 !PP->isPreprocessedOutput() &&
2836 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) {
2837 // Non-ASCII characters tend to creep into source code unintentionally.
2838 // Instead of letting the parser complain about the unknown token,
2839 // just drop the character.
2840 // Note that we can /only/ do this when the non-ASCII character is actually
2841 // spelled as Unicode, not written as a UCN. The standard requires that
2842 // we not throw away any possible preprocessor tokens, but there's a
2843 // loophole in the mapping of Unicode characters to basic character set
2844 // characters that allows us to map these particular characters to, say,
2846 Diag(BufferPtr, diag::err_non_ascii)
2847 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr));
2853 // Otherwise, we have an explicit UCN or a character that's unlikely to show
2856 FormTokenWithChars(Result, CurPtr, tok::unknown);
2860 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
2861 IsAtStartOfLine = Result.isAtStartOfLine();
2862 HasLeadingSpace = Result.hasLeadingSpace();
2863 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
2864 // Note that this doesn't affect IsAtPhysicalStartOfLine.
2867 bool Lexer::Lex(Token &Result) {
2868 // Start a new token.
2869 Result.startToken();
2871 // Set up misc whitespace flags for LexTokenInternal.
2872 if (IsAtStartOfLine) {
2873 Result.setFlag(Token::StartOfLine);
2874 IsAtStartOfLine = false;
2877 if (HasLeadingSpace) {
2878 Result.setFlag(Token::LeadingSpace);
2879 HasLeadingSpace = false;
2882 if (HasLeadingEmptyMacro) {
2883 Result.setFlag(Token::LeadingEmptyMacro);
2884 HasLeadingEmptyMacro = false;
2887 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
2888 IsAtPhysicalStartOfLine = false;
2889 bool isRawLex = isLexingRawMode();
2891 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
2892 // (After the LexTokenInternal call, the lexer might be destroyed.)
2893 assert((returnedToken || !isRawLex) && "Raw lex must succeed");
2894 return returnedToken;
2897 /// LexTokenInternal - This implements a simple C family lexer. It is an
2898 /// extremely performance critical piece of code. This assumes that the buffer
2899 /// has a null character at the end of the file. This returns a preprocessing
2900 /// token, not a normal token, as such, it is an internal interface. It assumes
2901 /// that the Flags of result have been cleared before calling this.
2902 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
2904 // New token, can't need cleaning yet.
2905 Result.clearFlag(Token::NeedsCleaning);
2906 Result.setIdentifierInfo(nullptr);
2908 // CurPtr - Cache BufferPtr in an automatic variable.
2909 const char *CurPtr = BufferPtr;
2911 // Small amounts of horizontal whitespace is very common between tokens.
2912 if ((*CurPtr == ' ') || (*CurPtr == '\t')) {
2914 while ((*CurPtr == ' ') || (*CurPtr == '\t'))
2917 // If we are keeping whitespace and other tokens, just return what we just
2918 // skipped. The next lexer invocation will return the token after the
2920 if (isKeepWhitespaceMode()) {
2921 FormTokenWithChars(Result, CurPtr, tok::unknown);
2922 // FIXME: The next token will not have LeadingSpace set.
2927 Result.setFlag(Token::LeadingSpace);
2930 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
2932 // Read a character, advancing over it.
2933 char Char = getAndAdvanceChar(CurPtr, Result);
2934 tok::TokenKind Kind;
2938 // Found end of file?
2939 if (CurPtr-1 == BufferEnd)
2940 return LexEndOfFile(Result, CurPtr-1);
2942 // Check if we are performing code completion.
2943 if (isCodeCompletionPoint(CurPtr-1)) {
2944 // Return the code-completion token.
2945 Result.startToken();
2946 FormTokenWithChars(Result, CurPtr, tok::code_completion);
2950 if (!isLexingRawMode())
2951 Diag(CurPtr-1, diag::null_in_file);
2952 Result.setFlag(Token::LeadingSpace);
2953 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2954 return true; // KeepWhitespaceMode
2956 // We know the lexer hasn't changed, so just try again with this lexer.
2957 // (We manually eliminate the tail call to avoid recursion.)
2960 case 26: // DOS & CP/M EOF: "^Z".
2961 // If we're in Microsoft extensions mode, treat this as end of file.
2962 if (LangOpts.MicrosoftExt)
2963 return LexEndOfFile(Result, CurPtr-1);
2965 // If Microsoft extensions are disabled, this is just random garbage.
2966 Kind = tok::unknown;
2971 // If we are inside a preprocessor directive and we see the end of line,
2972 // we know we are done with the directive, so return an EOD token.
2973 if (ParsingPreprocessorDirective) {
2974 // Done parsing the "line".
2975 ParsingPreprocessorDirective = false;
2977 // Restore comment saving mode, in case it was disabled for directive.
2979 resetExtendedTokenMode();
2981 // Since we consumed a newline, we are back at the start of a line.
2982 IsAtStartOfLine = true;
2983 IsAtPhysicalStartOfLine = true;
2989 // No leading whitespace seen so far.
2990 Result.clearFlag(Token::LeadingSpace);
2992 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
2993 return true; // KeepWhitespaceMode
2995 // We only saw whitespace, so just try again with this lexer.
2996 // (We manually eliminate the tail call to avoid recursion.)
3002 SkipHorizontalWhitespace:
3003 Result.setFlag(Token::LeadingSpace);
3004 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3005 return true; // KeepWhitespaceMode
3010 // If the next token is obviously a // or /* */ comment, skip it efficiently
3011 // too (without going through the big switch stmt).
3012 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
3013 LangOpts.LineComment &&
3014 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
3015 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3016 return true; // There is a token to return.
3017 goto SkipIgnoredUnits;
3018 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
3019 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
3020 return true; // There is a token to return.
3021 goto SkipIgnoredUnits;
3022 } else if (isHorizontalWhitespace(*CurPtr)) {
3023 goto SkipHorizontalWhitespace;
3025 // We only saw whitespace, so just try again with this lexer.
3026 // (We manually eliminate the tail call to avoid recursion.)
3029 // C99 6.4.4.1: Integer Constants.
3030 // C99 6.4.4.2: Floating Constants.
3031 case '0': case '1': case '2': case '3': case '4':
3032 case '5': case '6': case '7': case '8': case '9':
3033 // Notify MIOpt that we read a non-whitespace/non-comment token.
3035 return LexNumericConstant(Result, CurPtr);
3037 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
3038 // Notify MIOpt that we read a non-whitespace/non-comment token.
3041 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3042 Char = getCharAndSize(CurPtr, SizeTmp);
3044 // UTF-16 string literal
3046 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3047 tok::utf16_string_literal);
3049 // UTF-16 character constant
3051 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3052 tok::utf16_char_constant);
3054 // UTF-16 raw string literal
3055 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3056 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3057 return LexRawStringLiteral(Result,
3058 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3060 tok::utf16_string_literal);
3063 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
3065 // UTF-8 string literal
3067 return LexStringLiteral(Result,
3068 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3070 tok::utf8_string_literal);
3072 if (Char2 == 'R' && LangOpts.CPlusPlus11) {
3074 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3075 // UTF-8 raw string literal
3077 return LexRawStringLiteral(Result,
3078 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3081 tok::utf8_string_literal);
3087 // treat u like the start of an identifier.
3088 return LexIdentifier(Result, CurPtr);
3090 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
3091 // Notify MIOpt that we read a non-whitespace/non-comment token.
3094 if (LangOpts.CPlusPlus11 || LangOpts.C11) {
3095 Char = getCharAndSize(CurPtr, SizeTmp);
3097 // UTF-32 string literal
3099 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3100 tok::utf32_string_literal);
3102 // UTF-32 character constant
3104 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3105 tok::utf32_char_constant);
3107 // UTF-32 raw string literal
3108 if (Char == 'R' && LangOpts.CPlusPlus11 &&
3109 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3110 return LexRawStringLiteral(Result,
3111 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3113 tok::utf32_string_literal);
3116 // treat U like the start of an identifier.
3117 return LexIdentifier(Result, CurPtr);
3119 case 'R': // Identifier or C++0x raw string literal
3120 // Notify MIOpt that we read a non-whitespace/non-comment token.
3123 if (LangOpts.CPlusPlus11) {
3124 Char = getCharAndSize(CurPtr, SizeTmp);
3127 return LexRawStringLiteral(Result,
3128 ConsumeChar(CurPtr, SizeTmp, Result),
3129 tok::string_literal);
3132 // treat R like the start of an identifier.
3133 return LexIdentifier(Result, CurPtr);
3135 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
3136 // Notify MIOpt that we read a non-whitespace/non-comment token.
3138 Char = getCharAndSize(CurPtr, SizeTmp);
3140 // Wide string literal.
3142 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3143 tok::wide_string_literal);
3145 // Wide raw string literal.
3146 if (LangOpts.CPlusPlus11 && Char == 'R' &&
3147 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
3148 return LexRawStringLiteral(Result,
3149 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3151 tok::wide_string_literal);
3153 // Wide character constant.
3155 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3156 tok::wide_char_constant);
3157 // FALL THROUGH, treating L like the start of an identifier.
3159 // C99 6.4.2: Identifiers.
3160 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
3161 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
3162 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
3163 case 'V': case 'W': case 'X': case 'Y': case 'Z':
3164 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
3165 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
3166 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
3167 case 'v': case 'w': case 'x': case 'y': case 'z':
3169 // Notify MIOpt that we read a non-whitespace/non-comment token.
3171 return LexIdentifier(Result, CurPtr);
3173 case '$': // $ in identifiers.
3174 if (LangOpts.DollarIdents) {
3175 if (!isLexingRawMode())
3176 Diag(CurPtr-1, diag::ext_dollar_in_identifier);
3177 // Notify MIOpt that we read a non-whitespace/non-comment token.
3179 return LexIdentifier(Result, CurPtr);
3182 Kind = tok::unknown;
3185 // C99 6.4.4: Character Constants.
3187 // Notify MIOpt that we read a non-whitespace/non-comment token.
3189 return LexCharConstant(Result, CurPtr, tok::char_constant);
3191 // C99 6.4.5: String Literals.
3193 // Notify MIOpt that we read a non-whitespace/non-comment token.
3195 return LexStringLiteral(Result, CurPtr, tok::string_literal);
3197 // C99 6.4.6: Punctuators.
3199 Kind = tok::question;
3202 Kind = tok::l_square;
3205 Kind = tok::r_square;
3208 Kind = tok::l_paren;
3211 Kind = tok::r_paren;
3214 Kind = tok::l_brace;
3217 Kind = tok::r_brace;
3220 Char = getCharAndSize(CurPtr, SizeTmp);
3221 if (Char >= '0' && Char <= '9') {
3222 // Notify MIOpt that we read a non-whitespace/non-comment token.
3225 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
3226 } else if (LangOpts.CPlusPlus && Char == '*') {
3227 Kind = tok::periodstar;
3229 } else if (Char == '.' &&
3230 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
3231 Kind = tok::ellipsis;
3232 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3239 Char = getCharAndSize(CurPtr, SizeTmp);
3242 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3243 } else if (Char == '=') {
3244 Kind = tok::ampequal;
3245 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3251 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3252 Kind = tok::starequal;
3253 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3259 Char = getCharAndSize(CurPtr, SizeTmp);
3261 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3262 Kind = tok::plusplus;
3263 } else if (Char == '=') {
3264 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3265 Kind = tok::plusequal;
3271 Char = getCharAndSize(CurPtr, SizeTmp);
3272 if (Char == '-') { // --
3273 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3274 Kind = tok::minusminus;
3275 } else if (Char == '>' && LangOpts.CPlusPlus &&
3276 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
3277 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3279 Kind = tok::arrowstar;
3280 } else if (Char == '>') { // ->
3281 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3283 } else if (Char == '=') { // -=
3284 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3285 Kind = tok::minusequal;
3294 if (getCharAndSize(CurPtr, SizeTmp) == '=') {
3295 Kind = tok::exclaimequal;
3296 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3298 Kind = tok::exclaim;
3303 Char = getCharAndSize(CurPtr, SizeTmp);
3304 if (Char == '/') { // Line comment.
3305 // Even if Line comments are disabled (e.g. in C89 mode), we generally
3306 // want to lex this as a comment. There is one problem with this though,
3307 // that in one particular corner case, this can change the behavior of the
3308 // resultant program. For example, In "foo //**/ bar", C89 would lex
3309 // this as "foo / bar" and langauges with Line comments would lex it as
3310 // "foo". Check to see if the character after the second slash is a '*'.
3311 // If so, we will lex that as a "/" instead of the start of a comment.
3312 // However, we never do this if we are just preprocessing.
3313 bool TreatAsComment = LangOpts.LineComment &&
3314 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
3315 if (!TreatAsComment)
3316 if (!(PP && PP->isPreprocessedOutput()))
3317 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
3319 if (TreatAsComment) {
3320 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3321 TokAtPhysicalStartOfLine))
3322 return true; // There is a token to return.
3324 // It is common for the tokens immediately after a // comment to be
3325 // whitespace (indentation for the next line). Instead of going through
3326 // the big switch, handle it efficiently now.
3327 goto SkipIgnoredUnits;
3331 if (Char == '*') { // /**/ comment.
3332 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
3333 TokAtPhysicalStartOfLine))
3334 return true; // There is a token to return.
3336 // We only saw whitespace, so just try again with this lexer.
3337 // (We manually eliminate the tail call to avoid recursion.)
3342 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3343 Kind = tok::slashequal;
3349 Char = getCharAndSize(CurPtr, SizeTmp);
3351 Kind = tok::percentequal;
3352 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3353 } else if (LangOpts.Digraphs && Char == '>') {
3354 Kind = tok::r_brace; // '%>' -> '}'
3355 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3356 } else if (LangOpts.Digraphs && Char == ':') {
3357 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3358 Char = getCharAndSize(CurPtr, SizeTmp);
3359 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
3360 Kind = tok::hashhash; // '%:%:' -> '##'
3361 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3363 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
3364 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3365 if (!isLexingRawMode())
3366 Diag(BufferPtr, diag::ext_charize_microsoft);
3368 } else { // '%:' -> '#'
3369 // We parsed a # character. If this occurs at the start of the line,
3370 // it's actually the start of a preprocessing directive. Callback to
3371 // the preprocessor to handle it.
3372 // TODO: -fpreprocessed mode??
3373 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3374 goto HandleDirective;
3379 Kind = tok::percent;
3383 Char = getCharAndSize(CurPtr, SizeTmp);
3384 if (ParsingFilename) {
3385 return LexAngledStringLiteral(Result, CurPtr);
3386 } else if (Char == '<') {
3387 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3389 Kind = tok::lesslessequal;
3390 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3392 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
3393 // If this is actually a '<<<<<<<' version control conflict marker,
3394 // recognize it as such and recover nicely.
3396 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
3397 // If this is '<<<<' and we're in a Perforce-style conflict marker,
3400 } else if (LangOpts.CUDA && After == '<') {
3401 Kind = tok::lesslessless;
3402 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3405 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3406 Kind = tok::lessless;
3408 } else if (Char == '=') {
3409 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3410 Kind = tok::lessequal;
3411 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
3412 if (LangOpts.CPlusPlus11 &&
3413 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
3414 // C++0x [lex.pptoken]p3:
3415 // Otherwise, if the next three characters are <:: and the subsequent
3416 // character is neither : nor >, the < is treated as a preprocessor
3417 // token by itself and not as the first character of the alternative
3420 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
3421 if (After != ':' && After != '>') {
3423 if (!isLexingRawMode())
3424 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
3429 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3430 Kind = tok::l_square;
3431 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
3432 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3433 Kind = tok::l_brace;
3439 Char = getCharAndSize(CurPtr, SizeTmp);
3441 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3442 Kind = tok::greaterequal;
3443 } else if (Char == '>') {
3444 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
3446 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3448 Kind = tok::greatergreaterequal;
3449 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
3450 // If this is actually a '>>>>' conflict marker, recognize it as such
3451 // and recover nicely.
3453 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
3454 // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
3456 } else if (LangOpts.CUDA && After == '>') {
3457 Kind = tok::greatergreatergreater;
3458 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
3461 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3462 Kind = tok::greatergreater;
3466 Kind = tok::greater;
3470 Char = getCharAndSize(CurPtr, SizeTmp);
3472 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3473 Kind = tok::caretequal;
3479 Char = getCharAndSize(CurPtr, SizeTmp);
3481 Kind = tok::pipeequal;
3482 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3483 } else if (Char == '|') {
3484 // If this is '|||||||' and we're in a conflict marker, ignore it.
3485 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
3487 Kind = tok::pipepipe;
3488 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3494 Char = getCharAndSize(CurPtr, SizeTmp);
3495 if (LangOpts.Digraphs && Char == '>') {
3496 Kind = tok::r_square; // ':>' -> ']'
3497 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3498 } else if (LangOpts.CPlusPlus && Char == ':') {
3499 Kind = tok::coloncolon;
3500 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3509 Char = getCharAndSize(CurPtr, SizeTmp);
3511 // If this is '====' and we're in a conflict marker, ignore it.
3512 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
3515 Kind = tok::equalequal;
3516 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3525 Char = getCharAndSize(CurPtr, SizeTmp);
3527 Kind = tok::hashhash;
3528 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3529 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
3531 if (!isLexingRawMode())
3532 Diag(BufferPtr, diag::ext_charize_microsoft);
3533 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
3535 // We parsed a # character. If this occurs at the start of the line,
3536 // it's actually the start of a preprocessing directive. Callback to
3537 // the preprocessor to handle it.
3538 // TODO: -fpreprocessed mode??
3539 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
3540 goto HandleDirective;
3547 // Objective C support.
3548 if (CurPtr[-1] == '@' && LangOpts.ObjC1)
3551 Kind = tok::unknown;
3554 // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
3556 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
3557 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3558 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3559 return true; // KeepWhitespaceMode
3561 // We only saw whitespace, so just try again with this lexer.
3562 // (We manually eliminate the tail call to avoid recursion.)
3566 return LexUnicode(Result, CodePoint, CurPtr);
3569 Kind = tok::unknown;
3573 if (isASCII(Char)) {
3574 Kind = tok::unknown;
3580 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
3581 // an escaped newline.
3583 ConversionResult Status =
3584 llvm::convertUTF8Sequence((const UTF8 **)&CurPtr,
3585 (const UTF8 *)BufferEnd,
3588 if (Status == conversionOK) {
3589 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
3590 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
3591 return true; // KeepWhitespaceMode
3593 // We only saw whitespace, so just try again with this lexer.
3594 // (We manually eliminate the tail call to avoid recursion.)
3597 return LexUnicode(Result, CodePoint, CurPtr);
3600 if (isLexingRawMode() || ParsingPreprocessorDirective ||
3601 PP->isPreprocessedOutput()) {
3603 Kind = tok::unknown;
3607 // Non-ASCII characters tend to creep into source code unintentionally.
3608 // Instead of letting the parser complain about the unknown token,
3609 // just diagnose the invalid UTF-8, then drop the character.
3610 Diag(CurPtr, diag::err_invalid_utf8);
3612 BufferPtr = CurPtr+1;
3613 // We're pretending the character didn't exist, so just try again with
3615 // (We manually eliminate the tail call to avoid recursion.)
3620 // Notify MIOpt that we read a non-whitespace/non-comment token.
3623 // Update the location of token as well as BufferPtr.
3624 FormTokenWithChars(Result, CurPtr, Kind);
3628 // We parsed a # character and it's the start of a preprocessing directive.
3630 FormTokenWithChars(Result, CurPtr, tok::hash);
3631 PP->HandleDirective(Result);
3633 if (PP->hadModuleLoaderFatalFailure()) {
3634 // With a fatal failure in the module loader, we abort parsing.
3635 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
3639 // We parsed the directive; lex a token with the new state.