1 //===--- Lexer.cpp - C Language Family Lexer ------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This file implements the Lexer and Token interfaces. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/Lex/Lexer.h" 15 #include "UnicodeCharSets.h" 16 #include "clang/Basic/CharInfo.h" 17 #include "clang/Basic/IdentifierTable.h" 18 #include "clang/Basic/SourceManager.h" 19 #include "clang/Lex/LexDiagnostic.h" 20 #include "clang/Lex/LiteralSupport.h" 21 #include "clang/Lex/Preprocessor.h" 22 #include "llvm/ADT/StringExtras.h" 23 #include "llvm/ADT/StringSwitch.h" 24 #include "llvm/Support/Compiler.h" 25 #include "llvm/Support/ConvertUTF.h" 26 #include "llvm/Support/MathExtras.h" 27 #include "llvm/Support/MemoryBuffer.h" 28 #include "llvm/Support/UnicodeCharRanges.h" 29 #include <algorithm> 30 #include <cassert> 31 #include <cstddef> 32 #include <cstdint> 33 #include <cstring> 34 #include <string> 35 #include <tuple> 36 #include <utility> 37 38 using namespace clang; 39 40 //===----------------------------------------------------------------------===// 41 // Token Class Implementation 42 //===----------------------------------------------------------------------===// 43 44 /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier. 45 bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const { 46 if (IdentifierInfo *II = getIdentifierInfo()) 47 return II->getObjCKeywordID() == objcKey; 48 return false; 49 } 50 51 /// getObjCKeywordID - Return the ObjC keyword kind. 52 tok::ObjCKeywordKind Token::getObjCKeywordID() const { 53 IdentifierInfo *specId = getIdentifierInfo(); 54 return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword; 55 } 56 57 //===----------------------------------------------------------------------===// 58 // Lexer Class Implementation 59 //===----------------------------------------------------------------------===// 60 61 void Lexer::anchor() { } 62 63 void Lexer::InitLexer(const char *BufStart, const char *BufPtr, 64 const char *BufEnd) { 65 BufferStart = BufStart; 66 BufferPtr = BufPtr; 67 BufferEnd = BufEnd; 68 69 assert(BufEnd[0] == 0 && 70 "We assume that the input buffer has a null character at the end" 71 " to simplify lexing!"); 72 73 // Check whether we have a BOM in the beginning of the buffer. If yes - act 74 // accordingly. Right now we support only UTF-8 with and without BOM, so, just 75 // skip the UTF-8 BOM if it's present. 76 if (BufferStart == BufferPtr) { 77 // Determine the size of the BOM. 78 StringRef Buf(BufferStart, BufferEnd - BufferStart); 79 size_t BOMLength = llvm::StringSwitch<size_t>(Buf) 80 .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM 81 .Default(0); 82 83 // Skip the BOM. 84 BufferPtr += BOMLength; 85 } 86 87 Is_PragmaLexer = false; 88 CurrentConflictMarkerState = CMK_None; 89 90 // Start of the file is a start of line. 91 IsAtStartOfLine = true; 92 IsAtPhysicalStartOfLine = true; 93 94 HasLeadingSpace = false; 95 HasLeadingEmptyMacro = false; 96 97 // We are not after parsing a #. 98 ParsingPreprocessorDirective = false; 99 100 // We are not after parsing #include. 101 ParsingFilename = false; 102 103 // We are not in raw mode. Raw mode disables diagnostics and interpretation 104 // of tokens (e.g. identifiers, thus disabling macro expansion). It is used 105 // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block 106 // or otherwise skipping over tokens. 107 LexingRawMode = false; 108 109 // Default to not keeping comments. 110 ExtendedTokenMode = 0; 111 } 112 113 /// Lexer constructor - Create a new lexer object for the specified buffer 114 /// with the specified preprocessor managing the lexing process. This lexer 115 /// assumes that the associated file buffer and Preprocessor objects will 116 /// outlive it, so it doesn't take ownership of either of them. 117 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *InputFile, Preprocessor &PP) 118 : PreprocessorLexer(&PP, FID), 119 FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)), 120 LangOpts(PP.getLangOpts()) { 121 122 InitLexer(InputFile->getBufferStart(), InputFile->getBufferStart(), 123 InputFile->getBufferEnd()); 124 125 resetExtendedTokenMode(); 126 } 127 128 void Lexer::resetExtendedTokenMode() { 129 assert(PP && "Cannot reset token mode without a preprocessor"); 130 if (LangOpts.TraditionalCPP) 131 SetKeepWhitespaceMode(true); 132 else 133 SetCommentRetentionState(PP->getCommentRetentionState()); 134 } 135 136 /// Lexer constructor - Create a new raw lexer object. This object is only 137 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text 138 /// range will outlive it, so it doesn't take ownership of it. 139 Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts, 140 const char *BufStart, const char *BufPtr, const char *BufEnd) 141 : FileLoc(fileloc), LangOpts(langOpts) { 142 143 InitLexer(BufStart, BufPtr, BufEnd); 144 145 // We *are* in raw mode. 146 LexingRawMode = true; 147 } 148 149 /// Lexer constructor - Create a new raw lexer object. This object is only 150 /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text 151 /// range will outlive it, so it doesn't take ownership of it. 152 Lexer::Lexer(FileID FID, const llvm::MemoryBuffer *FromFile, 153 const SourceManager &SM, const LangOptions &langOpts) 154 : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile->getBufferStart(), 155 FromFile->getBufferStart(), FromFile->getBufferEnd()) {} 156 157 /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for 158 /// _Pragma expansion. This has a variety of magic semantics that this method 159 /// sets up. It returns a new'd Lexer that must be delete'd when done. 160 /// 161 /// On entrance to this routine, TokStartLoc is a macro location which has a 162 /// spelling loc that indicates the bytes to be lexed for the token and an 163 /// expansion location that indicates where all lexed tokens should be 164 /// "expanded from". 165 /// 166 /// TODO: It would really be nice to make _Pragma just be a wrapper around a 167 /// normal lexer that remaps tokens as they fly by. This would require making 168 /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer 169 /// interface that could handle this stuff. This would pull GetMappedTokenLoc 170 /// out of the critical path of the lexer! 171 /// 172 Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc, 173 SourceLocation ExpansionLocStart, 174 SourceLocation ExpansionLocEnd, 175 unsigned TokLen, Preprocessor &PP) { 176 SourceManager &SM = PP.getSourceManager(); 177 178 // Create the lexer as if we were going to lex the file normally. 179 FileID SpellingFID = SM.getFileID(SpellingLoc); 180 const llvm::MemoryBuffer *InputFile = SM.getBuffer(SpellingFID); 181 Lexer *L = new Lexer(SpellingFID, InputFile, PP); 182 183 // Now that the lexer is created, change the start/end locations so that we 184 // just lex the subsection of the file that we want. This is lexing from a 185 // scratch buffer. 186 const char *StrData = SM.getCharacterData(SpellingLoc); 187 188 L->BufferPtr = StrData; 189 L->BufferEnd = StrData+TokLen; 190 assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!"); 191 192 // Set the SourceLocation with the remapping information. This ensures that 193 // GetMappedTokenLoc will remap the tokens as they are lexed. 194 L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID), 195 ExpansionLocStart, 196 ExpansionLocEnd, TokLen); 197 198 // Ensure that the lexer thinks it is inside a directive, so that end \n will 199 // return an EOD token. 200 L->ParsingPreprocessorDirective = true; 201 202 // This lexer really is for _Pragma. 203 L->Is_PragmaLexer = true; 204 return L; 205 } 206 207 /// Stringify - Convert the specified string into a C string, with surrounding 208 /// ""'s, and with escaped \ and " characters. 209 std::string Lexer::Stringify(StringRef Str, bool Charify) { 210 std::string Result = Str; 211 char Quote = Charify ? '\'' : '"'; 212 for (unsigned i = 0, e = Result.size(); i != e; ++i) { 213 if (Result[i] == '\\' || Result[i] == Quote) { 214 Result.insert(Result.begin()+i, '\\'); 215 ++i; ++e; 216 } 217 } 218 return Result; 219 } 220 221 /// Stringify - Convert the specified string into a C string by escaping '\' 222 /// and " characters. This does not add surrounding ""'s to the string. 223 void Lexer::Stringify(SmallVectorImpl<char> &Str) { 224 for (unsigned i = 0, e = Str.size(); i != e; ++i) { 225 if (Str[i] == '\\' || Str[i] == '"') { 226 Str.insert(Str.begin()+i, '\\'); 227 ++i; ++e; 228 } 229 } 230 } 231 232 //===----------------------------------------------------------------------===// 233 // Token Spelling 234 //===----------------------------------------------------------------------===// 235 236 /// \brief Slow case of getSpelling. Extract the characters comprising the 237 /// spelling of this token from the provided input buffer. 238 static size_t getSpellingSlow(const Token &Tok, const char *BufPtr, 239 const LangOptions &LangOpts, char *Spelling) { 240 assert(Tok.needsCleaning() && "getSpellingSlow called on simple token"); 241 242 size_t Length = 0; 243 const char *BufEnd = BufPtr + Tok.getLength(); 244 245 if (tok::isStringLiteral(Tok.getKind())) { 246 // Munch the encoding-prefix and opening double-quote. 247 while (BufPtr < BufEnd) { 248 unsigned Size; 249 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts); 250 BufPtr += Size; 251 252 if (Spelling[Length - 1] == '"') 253 break; 254 } 255 256 // Raw string literals need special handling; trigraph expansion and line 257 // splicing do not occur within their d-char-sequence nor within their 258 // r-char-sequence. 259 if (Length >= 2 && 260 Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') { 261 // Search backwards from the end of the token to find the matching closing 262 // quote. 263 const char *RawEnd = BufEnd; 264 do --RawEnd; while (*RawEnd != '"'); 265 size_t RawLength = RawEnd - BufPtr + 1; 266 267 // Everything between the quotes is included verbatim in the spelling. 268 memcpy(Spelling + Length, BufPtr, RawLength); 269 Length += RawLength; 270 BufPtr += RawLength; 271 272 // The rest of the token is lexed normally. 273 } 274 } 275 276 while (BufPtr < BufEnd) { 277 unsigned Size; 278 Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts); 279 BufPtr += Size; 280 } 281 282 assert(Length < Tok.getLength() && 283 "NeedsCleaning flag set on token that didn't need cleaning!"); 284 return Length; 285 } 286 287 /// getSpelling() - Return the 'spelling' of this token. The spelling of a 288 /// token are the characters used to represent the token in the source file 289 /// after trigraph expansion and escaped-newline folding. In particular, this 290 /// wants to get the true, uncanonicalized, spelling of things like digraphs 291 /// UCNs, etc. 292 StringRef Lexer::getSpelling(SourceLocation loc, 293 SmallVectorImpl<char> &buffer, 294 const SourceManager &SM, 295 const LangOptions &options, 296 bool *invalid) { 297 // Break down the source location. 298 std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc); 299 300 // Try to the load the file buffer. 301 bool invalidTemp = false; 302 StringRef file = SM.getBufferData(locInfo.first, &invalidTemp); 303 if (invalidTemp) { 304 if (invalid) *invalid = true; 305 return StringRef(); 306 } 307 308 const char *tokenBegin = file.data() + locInfo.second; 309 310 // Lex from the start of the given location. 311 Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options, 312 file.begin(), tokenBegin, file.end()); 313 Token token; 314 lexer.LexFromRawLexer(token); 315 316 unsigned length = token.getLength(); 317 318 // Common case: no need for cleaning. 319 if (!token.needsCleaning()) 320 return StringRef(tokenBegin, length); 321 322 // Hard case, we need to relex the characters into the string. 323 buffer.resize(length); 324 buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data())); 325 return StringRef(buffer.data(), buffer.size()); 326 } 327 328 /// getSpelling() - Return the 'spelling' of this token. The spelling of a 329 /// token are the characters used to represent the token in the source file 330 /// after trigraph expansion and escaped-newline folding. In particular, this 331 /// wants to get the true, uncanonicalized, spelling of things like digraphs 332 /// UCNs, etc. 333 std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr, 334 const LangOptions &LangOpts, bool *Invalid) { 335 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); 336 337 bool CharDataInvalid = false; 338 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(), 339 &CharDataInvalid); 340 if (Invalid) 341 *Invalid = CharDataInvalid; 342 if (CharDataInvalid) 343 return std::string(); 344 345 // If this token contains nothing interesting, return it directly. 346 if (!Tok.needsCleaning()) 347 return std::string(TokStart, TokStart + Tok.getLength()); 348 349 std::string Result; 350 Result.resize(Tok.getLength()); 351 Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin())); 352 return Result; 353 } 354 355 /// getSpelling - This method is used to get the spelling of a token into a 356 /// preallocated buffer, instead of as an std::string. The caller is required 357 /// to allocate enough space for the token, which is guaranteed to be at least 358 /// Tok.getLength() bytes long. The actual length of the token is returned. 359 /// 360 /// Note that this method may do two possible things: it may either fill in 361 /// the buffer specified with characters, or it may *change the input pointer* 362 /// to point to a constant buffer with the data already in it (avoiding a 363 /// copy). The caller is not allowed to modify the returned buffer pointer 364 /// if an internal buffer is returned. 365 unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer, 366 const SourceManager &SourceMgr, 367 const LangOptions &LangOpts, bool *Invalid) { 368 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!"); 369 370 const char *TokStart = nullptr; 371 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 372 if (Tok.is(tok::raw_identifier)) 373 TokStart = Tok.getRawIdentifier().data(); 374 else if (!Tok.hasUCN()) { 375 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) { 376 // Just return the string from the identifier table, which is very quick. 377 Buffer = II->getNameStart(); 378 return II->getLength(); 379 } 380 } 381 382 // NOTE: this can be checked even after testing for an IdentifierInfo. 383 if (Tok.isLiteral()) 384 TokStart = Tok.getLiteralData(); 385 386 if (!TokStart) { 387 // Compute the start of the token in the input lexer buffer. 388 bool CharDataInvalid = false; 389 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid); 390 if (Invalid) 391 *Invalid = CharDataInvalid; 392 if (CharDataInvalid) { 393 Buffer = ""; 394 return 0; 395 } 396 } 397 398 // If this token contains nothing interesting, return it directly. 399 if (!Tok.needsCleaning()) { 400 Buffer = TokStart; 401 return Tok.getLength(); 402 } 403 404 // Otherwise, hard case, relex the characters into the string. 405 return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer)); 406 } 407 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) { 415 Token TheTok; 416 if (getRawToken(Loc, TheTok, SM, LangOpts)) 417 return 0; 418 return TheTok.getLength(); 419 } 420 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 431 // something. 432 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); 439 if (Invalid) 440 return true; 441 442 const char *StrData = Buffer.data()+LocInfo.second; 443 444 if (!IgnoreWhiteSpace && isWhitespace(StrData[0])) 445 return true; 446 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); 452 return false; 453 } 454 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()) 461 return Loc; 462 463 bool Invalid = false; 464 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid); 465 if (Invalid) 466 return Loc; 467 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()) 472 return Loc; 473 474 const char *StrData = BufStart+LocInfo.second; 475 if (StrData[0] == '\n' || StrData[0] == '\r') 476 return Loc; 477 478 const char *LexStart = StrData; 479 while (LexStart != BufStart) { 480 if (LexStart[0] == '\n' || LexStart[0] == '\r') { 481 ++LexStart; 482 break; 483 } 484 485 --LexStart; 486 } 487 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); 492 493 // Lex tokens until we find the token that contains the source location. 494 Token TheTok; 495 do { 496 TheLexer.LexFromRawLexer(TheTok); 497 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(); 504 505 // We ended up skipping over the source location entirely, which means 506 // that it points into whitespace. We're done here. 507 break; 508 } 509 } while (TheTok.getKind() != tok::eof); 510 511 // We've passed our source location; just return the original source location. 512 return Loc; 513 } 514 515 SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc, 516 const SourceManager &SM, 517 const LangOptions &LangOpts) { 518 if (Loc.isFileID()) 519 return getBeginningOfFileToken(Loc, SM, LangOpts); 520 521 if (!SM.isMacroArgExpansion(Loc)) 522 return Loc; 523 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); 532 } 533 534 namespace { 535 536 enum PreambleDirectiveKind { 537 PDK_Skipped, 538 PDK_StartIf, 539 PDK_EndIf, 540 PDK_Unknown 541 }; 542 543 } // end anonymous namespace 544 545 std::pair<unsigned, bool> Lexer::ComputePreamble(StringRef Buffer, 546 const LangOptions &LangOpts, 547 unsigned MaxLines) { 548 // Create a lexer starting at the beginning of the file. Note that we use a 549 // "fake" file source location at offset 1 so that the lexer will track our 550 // position within the file. 551 const unsigned StartOffset = 1; 552 SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset); 553 Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(), 554 Buffer.end()); 555 TheLexer.SetCommentRetentionState(true); 556 557 // StartLoc will differ from FileLoc if there is a BOM that was skipped. 558 SourceLocation StartLoc = TheLexer.getSourceLocation(); 559 560 bool InPreprocessorDirective = false; 561 Token TheTok; 562 Token IfStartTok; 563 unsigned IfCount = 0; 564 SourceLocation ActiveCommentLoc; 565 566 unsigned MaxLineOffset = 0; 567 if (MaxLines) { 568 const char *CurPtr = Buffer.begin(); 569 unsigned CurLine = 0; 570 while (CurPtr != Buffer.end()) { 571 char ch = *CurPtr++; 572 if (ch == '\n') { 573 ++CurLine; 574 if (CurLine == MaxLines) 575 break; 576 } 577 } 578 if (CurPtr != Buffer.end()) 579 MaxLineOffset = CurPtr - Buffer.begin(); 580 } 581 582 do { 583 TheLexer.LexFromRawLexer(TheTok); 584 585 if (InPreprocessorDirective) { 586 // If we've hit the end of the file, we're done. 587 if (TheTok.getKind() == tok::eof) { 588 break; 589 } 590 591 // If we haven't hit the end of the preprocessor directive, skip this 592 // token. 593 if (!TheTok.isAtStartOfLine()) 594 continue; 595 596 // We've passed the end of the preprocessor directive, and will look 597 // at this token again below. 598 InPreprocessorDirective = false; 599 } 600 601 // Keep track of the # of lines in the preamble. 602 if (TheTok.isAtStartOfLine()) { 603 unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset; 604 605 // If we were asked to limit the number of lines in the preamble, 606 // and we're about to exceed that limit, we're done. 607 if (MaxLineOffset && TokOffset >= MaxLineOffset) 608 break; 609 } 610 611 // Comments are okay; skip over them. 612 if (TheTok.getKind() == tok::comment) { 613 if (ActiveCommentLoc.isInvalid()) 614 ActiveCommentLoc = TheTok.getLocation(); 615 continue; 616 } 617 618 if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) { 619 // This is the start of a preprocessor directive. 620 Token HashTok = TheTok; 621 InPreprocessorDirective = true; 622 ActiveCommentLoc = SourceLocation(); 623 624 // Figure out which directive this is. Since we're lexing raw tokens, 625 // we don't have an identifier table available. Instead, just look at 626 // the raw identifier to recognize and categorize preprocessor directives. 627 TheLexer.LexFromRawLexer(TheTok); 628 if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) { 629 StringRef Keyword = TheTok.getRawIdentifier(); 630 PreambleDirectiveKind PDK 631 = llvm::StringSwitch<PreambleDirectiveKind>(Keyword) 632 .Case("include", PDK_Skipped) 633 .Case("__include_macros", PDK_Skipped) 634 .Case("define", PDK_Skipped) 635 .Case("undef", PDK_Skipped) 636 .Case("line", PDK_Skipped) 637 .Case("error", PDK_Skipped) 638 .Case("pragma", PDK_Skipped) 639 .Case("import", PDK_Skipped) 640 .Case("include_next", PDK_Skipped) 641 .Case("warning", PDK_Skipped) 642 .Case("ident", PDK_Skipped) 643 .Case("sccs", PDK_Skipped) 644 .Case("assert", PDK_Skipped) 645 .Case("unassert", PDK_Skipped) 646 .Case("if", PDK_StartIf) 647 .Case("ifdef", PDK_StartIf) 648 .Case("ifndef", PDK_StartIf) 649 .Case("elif", PDK_Skipped) 650 .Case("else", PDK_Skipped) 651 .Case("endif", PDK_EndIf) 652 .Default(PDK_Unknown); 653 654 switch (PDK) { 655 case PDK_Skipped: 656 continue; 657 658 case PDK_StartIf: 659 if (IfCount == 0) 660 IfStartTok = HashTok; 661 662 ++IfCount; 663 continue; 664 665 case PDK_EndIf: 666 // Mismatched #endif. The preamble ends here. 667 if (IfCount == 0) 668 break; 669 670 --IfCount; 671 continue; 672 673 case PDK_Unknown: 674 // We don't know what this directive is; stop at the '#'. 675 break; 676 } 677 } 678 679 // We only end up here if we didn't recognize the preprocessor 680 // directive or it was one that can't occur in the preamble at this 681 // point. Roll back the current token to the location of the '#'. 682 InPreprocessorDirective = false; 683 TheTok = HashTok; 684 } 685 686 // We hit a token that we don't recognize as being in the 687 // "preprocessing only" part of the file, so we're no longer in 688 // the preamble. 689 break; 690 } while (true); 691 692 SourceLocation End; 693 if (IfCount) 694 End = IfStartTok.getLocation(); 695 else if (ActiveCommentLoc.isValid()) 696 End = ActiveCommentLoc; // don't truncate a decl comment. 697 else 698 End = TheTok.getLocation(); 699 700 return std::make_pair(End.getRawEncoding() - StartLoc.getRawEncoding(), 701 IfCount? IfStartTok.isAtStartOfLine() 702 : TheTok.isAtStartOfLine()); 703 } 704 705 /// AdvanceToTokenCharacter - Given a location that specifies the start of a 706 /// token, return a new location that specifies a character within the token. 707 SourceLocation Lexer::AdvanceToTokenCharacter(SourceLocation TokStart, 708 unsigned CharNo, 709 const SourceManager &SM, 710 const LangOptions &LangOpts) { 711 // Figure out how many physical characters away the specified expansion 712 // character is. This needs to take into consideration newlines and 713 // trigraphs. 714 bool Invalid = false; 715 const char *TokPtr = SM.getCharacterData(TokStart, &Invalid); 716 717 // If they request the first char of the token, we're trivially done. 718 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr))) 719 return TokStart; 720 721 unsigned PhysOffset = 0; 722 723 // The usual case is that tokens don't contain anything interesting. Skip 724 // over the uninteresting characters. If a token only consists of simple 725 // chars, this method is extremely fast. 726 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) { 727 if (CharNo == 0) 728 return TokStart.getLocWithOffset(PhysOffset); 729 ++TokPtr; 730 --CharNo; 731 ++PhysOffset; 732 } 733 734 // If we have a character that may be a trigraph or escaped newline, use a 735 // lexer to parse it correctly. 736 for (; CharNo; --CharNo) { 737 unsigned Size; 738 Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts); 739 TokPtr += Size; 740 PhysOffset += Size; 741 } 742 743 // Final detail: if we end up on an escaped newline, we want to return the 744 // location of the actual byte of the token. For example foo\<newline>bar 745 // advanced by 3 should return the location of b, not of \\. One compounding 746 // detail of this is that the escape may be made by a trigraph. 747 if (!Lexer::isObviouslySimpleCharacter(*TokPtr)) 748 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr; 749 750 return TokStart.getLocWithOffset(PhysOffset); 751 } 752 753 /// \brief Computes the source location just past the end of the 754 /// token at this source location. 755 /// 756 /// This routine can be used to produce a source location that 757 /// points just past the end of the token referenced by \p Loc, and 758 /// is generally used when a diagnostic needs to point just after a 759 /// token where it expected something different that it received. If 760 /// the returned source location would not be meaningful (e.g., if 761 /// it points into a macro), this routine returns an invalid 762 /// source location. 763 /// 764 /// \param Offset an offset from the end of the token, where the source 765 /// location should refer to. The default offset (0) produces a source 766 /// location pointing just past the end of the token; an offset of 1 produces 767 /// a source location pointing to the last character in the token, etc. 768 SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset, 769 const SourceManager &SM, 770 const LangOptions &LangOpts) { 771 if (Loc.isInvalid()) 772 return SourceLocation(); 773 774 if (Loc.isMacroID()) { 775 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc)) 776 return SourceLocation(); // Points inside the macro expansion. 777 } 778 779 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts); 780 if (Len > Offset) 781 Len = Len - Offset; 782 else 783 return Loc; 784 785 return Loc.getLocWithOffset(Len); 786 } 787 788 /// \brief Returns true if the given MacroID location points at the first 789 /// token of the macro expansion. 790 bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc, 791 const SourceManager &SM, 792 const LangOptions &LangOpts, 793 SourceLocation *MacroBegin) { 794 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc"); 795 796 SourceLocation expansionLoc; 797 if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc)) 798 return false; 799 800 if (expansionLoc.isFileID()) { 801 // No other macro expansions, this is the first. 802 if (MacroBegin) 803 *MacroBegin = expansionLoc; 804 return true; 805 } 806 807 return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin); 808 } 809 810 /// \brief Returns true if the given MacroID location points at the last 811 /// token of the macro expansion. 812 bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc, 813 const SourceManager &SM, 814 const LangOptions &LangOpts, 815 SourceLocation *MacroEnd) { 816 assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc"); 817 818 SourceLocation spellLoc = SM.getSpellingLoc(loc); 819 unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts); 820 if (tokLen == 0) 821 return false; 822 823 SourceLocation afterLoc = loc.getLocWithOffset(tokLen); 824 SourceLocation expansionLoc; 825 if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc)) 826 return false; 827 828 if (expansionLoc.isFileID()) { 829 // No other macro expansions. 830 if (MacroEnd) 831 *MacroEnd = expansionLoc; 832 return true; 833 } 834 835 return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd); 836 } 837 838 static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range, 839 const SourceManager &SM, 840 const LangOptions &LangOpts) { 841 SourceLocation Begin = Range.getBegin(); 842 SourceLocation End = Range.getEnd(); 843 assert(Begin.isFileID() && End.isFileID()); 844 if (Range.isTokenRange()) { 845 End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts); 846 if (End.isInvalid()) 847 return CharSourceRange(); 848 } 849 850 // Break down the source locations. 851 FileID FID; 852 unsigned BeginOffs; 853 std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin); 854 if (FID.isInvalid()) 855 return CharSourceRange(); 856 857 unsigned EndOffs; 858 if (!SM.isInFileID(End, FID, &EndOffs) || 859 BeginOffs > EndOffs) 860 return CharSourceRange(); 861 862 return CharSourceRange::getCharRange(Begin, End); 863 } 864 865 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range, 866 const SourceManager &SM, 867 const LangOptions &LangOpts) { 868 SourceLocation Begin = Range.getBegin(); 869 SourceLocation End = Range.getEnd(); 870 if (Begin.isInvalid() || End.isInvalid()) 871 return CharSourceRange(); 872 873 if (Begin.isFileID() && End.isFileID()) 874 return makeRangeFromFileLocs(Range, SM, LangOpts); 875 876 if (Begin.isMacroID() && End.isFileID()) { 877 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin)) 878 return CharSourceRange(); 879 Range.setBegin(Begin); 880 return makeRangeFromFileLocs(Range, SM, LangOpts); 881 } 882 883 if (Begin.isFileID() && End.isMacroID()) { 884 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts, 885 &End)) || 886 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts, 887 &End))) 888 return CharSourceRange(); 889 Range.setEnd(End); 890 return makeRangeFromFileLocs(Range, SM, LangOpts); 891 } 892 893 assert(Begin.isMacroID() && End.isMacroID()); 894 SourceLocation MacroBegin, MacroEnd; 895 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) && 896 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts, 897 &MacroEnd)) || 898 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts, 899 &MacroEnd)))) { 900 Range.setBegin(MacroBegin); 901 Range.setEnd(MacroEnd); 902 return makeRangeFromFileLocs(Range, SM, LangOpts); 903 } 904 905 bool Invalid = false; 906 const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin), 907 &Invalid); 908 if (Invalid) 909 return CharSourceRange(); 910 911 if (BeginEntry.getExpansion().isMacroArgExpansion()) { 912 const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End), 913 &Invalid); 914 if (Invalid) 915 return CharSourceRange(); 916 917 if (EndEntry.getExpansion().isMacroArgExpansion() && 918 BeginEntry.getExpansion().getExpansionLocStart() == 919 EndEntry.getExpansion().getExpansionLocStart()) { 920 Range.setBegin(SM.getImmediateSpellingLoc(Begin)); 921 Range.setEnd(SM.getImmediateSpellingLoc(End)); 922 return makeFileCharRange(Range, SM, LangOpts); 923 } 924 } 925 926 return CharSourceRange(); 927 } 928 929 StringRef Lexer::getSourceText(CharSourceRange Range, 930 const SourceManager &SM, 931 const LangOptions &LangOpts, 932 bool *Invalid) { 933 Range = makeFileCharRange(Range, SM, LangOpts); 934 if (Range.isInvalid()) { 935 if (Invalid) *Invalid = true; 936 return StringRef(); 937 } 938 939 // Break down the source location. 940 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin()); 941 if (beginInfo.first.isInvalid()) { 942 if (Invalid) *Invalid = true; 943 return StringRef(); 944 } 945 946 unsigned EndOffs; 947 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) || 948 beginInfo.second > EndOffs) { 949 if (Invalid) *Invalid = true; 950 return StringRef(); 951 } 952 953 // Try to the load the file buffer. 954 bool invalidTemp = false; 955 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp); 956 if (invalidTemp) { 957 if (Invalid) *Invalid = true; 958 return StringRef(); 959 } 960 961 if (Invalid) *Invalid = false; 962 return file.substr(beginInfo.second, EndOffs - beginInfo.second); 963 } 964 965 StringRef Lexer::getImmediateMacroName(SourceLocation Loc, 966 const SourceManager &SM, 967 const LangOptions &LangOpts) { 968 assert(Loc.isMacroID() && "Only reasonble to call this on macros"); 969 970 // Find the location of the immediate macro expansion. 971 while (true) { 972 FileID FID = SM.getFileID(Loc); 973 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID); 974 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); 975 Loc = Expansion.getExpansionLocStart(); 976 if (!Expansion.isMacroArgExpansion()) 977 break; 978 979 // For macro arguments we need to check that the argument did not come 980 // from an inner macro, e.g: "MAC1( MAC2(foo) )" 981 982 // Loc points to the argument id of the macro definition, move to the 983 // macro expansion. 984 Loc = SM.getImmediateExpansionRange(Loc).first; 985 SourceLocation SpellLoc = Expansion.getSpellingLoc(); 986 if (SpellLoc.isFileID()) 987 break; // No inner macro. 988 989 // If spelling location resides in the same FileID as macro expansion 990 // location, it means there is no inner macro. 991 FileID MacroFID = SM.getFileID(Loc); 992 if (SM.isInFileID(SpellLoc, MacroFID)) 993 break; 994 995 // Argument came from inner macro. 996 Loc = SpellLoc; 997 } 998 999 // Find the spelling location of the start of the non-argument expansion 1000 // range. This is where the macro name was spelled in order to begin 1001 // expanding this macro. 1002 Loc = SM.getSpellingLoc(Loc); 1003 1004 // Dig out the buffer where the macro name was spelled and the extents of the 1005 // name so that we can render it into the expansion note. 1006 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc); 1007 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts); 1008 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first); 1009 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength); 1010 } 1011 1012 StringRef Lexer::getImmediateMacroNameForDiagnostics( 1013 SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) { 1014 assert(Loc.isMacroID() && "Only reasonble to call this on macros"); 1015 // Walk past macro argument expanions. 1016 while (SM.isMacroArgExpansion(Loc)) 1017 Loc = SM.getImmediateExpansionRange(Loc).first; 1018 1019 // If the macro's spelling has no FileID, then it's actually a token paste 1020 // or stringization (or similar) and not a macro at all. 1021 if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc)))) 1022 return StringRef(); 1023 1024 // Find the spelling location of the start of the non-argument expansion 1025 // range. This is where the macro name was spelled in order to begin 1026 // expanding this macro. 1027 Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).first); 1028 1029 // Dig out the buffer where the macro name was spelled and the extents of the 1030 // name so that we can render it into the expansion note. 1031 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc); 1032 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts); 1033 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first); 1034 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength); 1035 } 1036 1037 bool Lexer::isIdentifierBodyChar(char c, const LangOptions &LangOpts) { 1038 return isIdentifierBody(c, LangOpts.DollarIdents); 1039 } 1040 1041 //===----------------------------------------------------------------------===// 1042 // Diagnostics forwarding code. 1043 //===----------------------------------------------------------------------===// 1044 1045 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the 1046 /// lexer buffer was all expanded at a single point, perform the mapping. 1047 /// This is currently only used for _Pragma implementation, so it is the slow 1048 /// path of the hot getSourceLocation method. Do not allow it to be inlined. 1049 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc( 1050 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen); 1051 static SourceLocation GetMappedTokenLoc(Preprocessor &PP, 1052 SourceLocation FileLoc, 1053 unsigned CharNo, unsigned TokLen) { 1054 assert(FileLoc.isMacroID() && "Must be a macro expansion"); 1055 1056 // Otherwise, we're lexing "mapped tokens". This is used for things like 1057 // _Pragma handling. Combine the expansion location of FileLoc with the 1058 // spelling location. 1059 SourceManager &SM = PP.getSourceManager(); 1060 1061 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose 1062 // characters come from spelling(FileLoc)+Offset. 1063 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc); 1064 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo); 1065 1066 // Figure out the expansion loc range, which is the range covered by the 1067 // original _Pragma(...) sequence. 1068 std::pair<SourceLocation,SourceLocation> II = 1069 SM.getImmediateExpansionRange(FileLoc); 1070 1071 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen); 1072 } 1073 1074 /// getSourceLocation - Return a source location identifier for the specified 1075 /// offset in the current file. 1076 SourceLocation Lexer::getSourceLocation(const char *Loc, 1077 unsigned TokLen) const { 1078 assert(Loc >= BufferStart && Loc <= BufferEnd && 1079 "Location out of range for this buffer!"); 1080 1081 // In the normal case, we're just lexing from a simple file buffer, return 1082 // the file id from FileLoc with the offset specified. 1083 unsigned CharNo = Loc-BufferStart; 1084 if (FileLoc.isFileID()) 1085 return FileLoc.getLocWithOffset(CharNo); 1086 1087 // Otherwise, this is the _Pragma lexer case, which pretends that all of the 1088 // tokens are lexed from where the _Pragma was defined. 1089 assert(PP && "This doesn't work on raw lexers"); 1090 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen); 1091 } 1092 1093 /// Diag - Forwarding function for diagnostics. This translate a source 1094 /// position in the current buffer into a SourceLocation object for rendering. 1095 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const { 1096 return PP->Diag(getSourceLocation(Loc), DiagID); 1097 } 1098 1099 //===----------------------------------------------------------------------===// 1100 // Trigraph and Escaped Newline Handling Code. 1101 //===----------------------------------------------------------------------===// 1102 1103 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair, 1104 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing. 1105 static char GetTrigraphCharForLetter(char Letter) { 1106 switch (Letter) { 1107 default: return 0; 1108 case '=': return '#'; 1109 case ')': return ']'; 1110 case '(': return '['; 1111 case '!': return '|'; 1112 case '\'': return '^'; 1113 case '>': return '}'; 1114 case '/': return '\\'; 1115 case '<': return '{'; 1116 case '-': return '~'; 1117 } 1118 } 1119 1120 /// DecodeTrigraphChar - If the specified character is a legal trigraph when 1121 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled, 1122 /// return the result character. Finally, emit a warning about trigraph use 1123 /// whether trigraphs are enabled or not. 1124 static char DecodeTrigraphChar(const char *CP, Lexer *L) { 1125 char Res = GetTrigraphCharForLetter(*CP); 1126 if (!Res || !L) return Res; 1127 1128 if (!L->getLangOpts().Trigraphs) { 1129 if (!L->isLexingRawMode()) 1130 L->Diag(CP-2, diag::trigraph_ignored); 1131 return 0; 1132 } 1133 1134 if (!L->isLexingRawMode()) 1135 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1); 1136 return Res; 1137 } 1138 1139 /// getEscapedNewLineSize - Return the size of the specified escaped newline, 1140 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a 1141 /// trigraph equivalent on entry to this function. 1142 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) { 1143 unsigned Size = 0; 1144 while (isWhitespace(Ptr[Size])) { 1145 ++Size; 1146 1147 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r') 1148 continue; 1149 1150 // If this is a \r\n or \n\r, skip the other half. 1151 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') && 1152 Ptr[Size-1] != Ptr[Size]) 1153 ++Size; 1154 1155 return Size; 1156 } 1157 1158 // Not an escaped newline, must be a \t or something else. 1159 return 0; 1160 } 1161 1162 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of 1163 /// them), skip over them and return the first non-escaped-newline found, 1164 /// otherwise return P. 1165 const char *Lexer::SkipEscapedNewLines(const char *P) { 1166 while (true) { 1167 const char *AfterEscape; 1168 if (*P == '\\') { 1169 AfterEscape = P+1; 1170 } else if (*P == '?') { 1171 // If not a trigraph for escape, bail out. 1172 if (P[1] != '?' || P[2] != '/') 1173 return P; 1174 AfterEscape = P+3; 1175 } else { 1176 return P; 1177 } 1178 1179 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape); 1180 if (NewLineSize == 0) return P; 1181 P = AfterEscape+NewLineSize; 1182 } 1183 } 1184 1185 /// \brief Checks that the given token is the first token that occurs after the 1186 /// given location (this excludes comments and whitespace). Returns the location 1187 /// immediately after the specified token. If the token is not found or the 1188 /// location is inside a macro, the returned source location will be invalid. 1189 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc, 1190 tok::TokenKind TKind, 1191 const SourceManager &SM, 1192 const LangOptions &LangOpts, 1193 bool SkipTrailingWhitespaceAndNewLine) { 1194 if (Loc.isMacroID()) { 1195 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc)) 1196 return SourceLocation(); 1197 } 1198 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts); 1199 1200 // Break down the source location. 1201 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 1202 1203 // Try to load the file buffer. 1204 bool InvalidTemp = false; 1205 StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp); 1206 if (InvalidTemp) 1207 return SourceLocation(); 1208 1209 const char *TokenBegin = File.data() + LocInfo.second; 1210 1211 // Lex from the start of the given location. 1212 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(), 1213 TokenBegin, File.end()); 1214 // Find the token. 1215 Token Tok; 1216 lexer.LexFromRawLexer(Tok); 1217 if (Tok.isNot(TKind)) 1218 return SourceLocation(); 1219 SourceLocation TokenLoc = Tok.getLocation(); 1220 1221 // Calculate how much whitespace needs to be skipped if any. 1222 unsigned NumWhitespaceChars = 0; 1223 if (SkipTrailingWhitespaceAndNewLine) { 1224 const char *TokenEnd = SM.getCharacterData(TokenLoc) + 1225 Tok.getLength(); 1226 unsigned char C = *TokenEnd; 1227 while (isHorizontalWhitespace(C)) { 1228 C = *(++TokenEnd); 1229 NumWhitespaceChars++; 1230 } 1231 1232 // Skip \r, \n, \r\n, or \n\r 1233 if (C == '\n' || C == '\r') { 1234 char PrevC = C; 1235 C = *(++TokenEnd); 1236 NumWhitespaceChars++; 1237 if ((C == '\n' || C == '\r') && C != PrevC) 1238 NumWhitespaceChars++; 1239 } 1240 } 1241 1242 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars); 1243 } 1244 1245 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer, 1246 /// get its size, and return it. This is tricky in several cases: 1247 /// 1. If currently at the start of a trigraph, we warn about the trigraph, 1248 /// then either return the trigraph (skipping 3 chars) or the '?', 1249 /// depending on whether trigraphs are enabled or not. 1250 /// 2. If this is an escaped newline (potentially with whitespace between 1251 /// the backslash and newline), implicitly skip the newline and return 1252 /// the char after it. 1253 /// 1254 /// This handles the slow/uncommon case of the getCharAndSize method. Here we 1255 /// know that we can accumulate into Size, and that we have already incremented 1256 /// Ptr by Size bytes. 1257 /// 1258 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should 1259 /// be updated to match. 1260 /// 1261 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size, 1262 Token *Tok) { 1263 // If we have a slash, look for an escaped newline. 1264 if (Ptr[0] == '\\') { 1265 ++Size; 1266 ++Ptr; 1267 Slash: 1268 // Common case, backslash-char where the char is not whitespace. 1269 if (!isWhitespace(Ptr[0])) return '\\'; 1270 1271 // See if we have optional whitespace characters between the slash and 1272 // newline. 1273 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { 1274 // Remember that this token needs to be cleaned. 1275 if (Tok) Tok->setFlag(Token::NeedsCleaning); 1276 1277 // Warn if there was whitespace between the backslash and newline. 1278 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode()) 1279 Diag(Ptr, diag::backslash_newline_space); 1280 1281 // Found backslash<whitespace><newline>. Parse the char after it. 1282 Size += EscapedNewLineSize; 1283 Ptr += EscapedNewLineSize; 1284 1285 // If the char that we finally got was a \n, then we must have had 1286 // something like \<newline><newline>. We don't want to consume the 1287 // second newline. 1288 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0') 1289 return ' '; 1290 1291 // Use slow version to accumulate a correct size field. 1292 return getCharAndSizeSlow(Ptr, Size, Tok); 1293 } 1294 1295 // Otherwise, this is not an escaped newline, just return the slash. 1296 return '\\'; 1297 } 1298 1299 // If this is a trigraph, process it. 1300 if (Ptr[0] == '?' && Ptr[1] == '?') { 1301 // If this is actually a legal trigraph (not something like "??x"), emit 1302 // a trigraph warning. If so, and if trigraphs are enabled, return it. 1303 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) { 1304 // Remember that this token needs to be cleaned. 1305 if (Tok) Tok->setFlag(Token::NeedsCleaning); 1306 1307 Ptr += 3; 1308 Size += 3; 1309 if (C == '\\') goto Slash; 1310 return C; 1311 } 1312 } 1313 1314 // If this is neither, return a single character. 1315 ++Size; 1316 return *Ptr; 1317 } 1318 1319 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the 1320 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size, 1321 /// and that we have already incremented Ptr by Size bytes. 1322 /// 1323 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should 1324 /// be updated to match. 1325 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 1326 const LangOptions &LangOpts) { 1327 // If we have a slash, look for an escaped newline. 1328 if (Ptr[0] == '\\') { 1329 ++Size; 1330 ++Ptr; 1331 Slash: 1332 // Common case, backslash-char where the char is not whitespace. 1333 if (!isWhitespace(Ptr[0])) return '\\'; 1334 1335 // See if we have optional whitespace characters followed by a newline. 1336 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { 1337 // Found backslash<whitespace><newline>. Parse the char after it. 1338 Size += EscapedNewLineSize; 1339 Ptr += EscapedNewLineSize; 1340 1341 // If the char that we finally got was a \n, then we must have had 1342 // something like \<newline><newline>. We don't want to consume the 1343 // second newline. 1344 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0') 1345 return ' '; 1346 1347 // Use slow version to accumulate a correct size field. 1348 return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts); 1349 } 1350 1351 // Otherwise, this is not an escaped newline, just return the slash. 1352 return '\\'; 1353 } 1354 1355 // If this is a trigraph, process it. 1356 if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') { 1357 // If this is actually a legal trigraph (not something like "??x"), return 1358 // it. 1359 if (char C = GetTrigraphCharForLetter(Ptr[2])) { 1360 Ptr += 3; 1361 Size += 3; 1362 if (C == '\\') goto Slash; 1363 return C; 1364 } 1365 } 1366 1367 // If this is neither, return a single character. 1368 ++Size; 1369 return *Ptr; 1370 } 1371 1372 //===----------------------------------------------------------------------===// 1373 // Helper methods for lexing. 1374 //===----------------------------------------------------------------------===// 1375 1376 /// \brief Routine that indiscriminately skips bytes in the source file. 1377 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) { 1378 BufferPtr += Bytes; 1379 if (BufferPtr > BufferEnd) 1380 BufferPtr = BufferEnd; 1381 // FIXME: What exactly does the StartOfLine bit mean? There are two 1382 // possible meanings for the "start" of the line: the first token on the 1383 // unexpanded line, or the first token on the expanded line. 1384 IsAtStartOfLine = StartOfLine; 1385 IsAtPhysicalStartOfLine = StartOfLine; 1386 } 1387 1388 static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) { 1389 if (LangOpts.AsmPreprocessor) { 1390 return false; 1391 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) { 1392 static const llvm::sys::UnicodeCharSet C11AllowedIDChars( 1393 C11AllowedIDCharRanges); 1394 return C11AllowedIDChars.contains(C); 1395 } else if (LangOpts.CPlusPlus) { 1396 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars( 1397 CXX03AllowedIDCharRanges); 1398 return CXX03AllowedIDChars.contains(C); 1399 } else { 1400 static const llvm::sys::UnicodeCharSet C99AllowedIDChars( 1401 C99AllowedIDCharRanges); 1402 return C99AllowedIDChars.contains(C); 1403 } 1404 } 1405 1406 static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) { 1407 assert(isAllowedIDChar(C, LangOpts)); 1408 if (LangOpts.AsmPreprocessor) { 1409 return false; 1410 } else if (LangOpts.CPlusPlus11 || LangOpts.C11) { 1411 static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars( 1412 C11DisallowedInitialIDCharRanges); 1413 return !C11DisallowedInitialIDChars.contains(C); 1414 } else if (LangOpts.CPlusPlus) { 1415 return true; 1416 } else { 1417 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars( 1418 C99DisallowedInitialIDCharRanges); 1419 return !C99DisallowedInitialIDChars.contains(C); 1420 } 1421 } 1422 1423 static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin, 1424 const char *End) { 1425 return CharSourceRange::getCharRange(L.getSourceLocation(Begin), 1426 L.getSourceLocation(End)); 1427 } 1428 1429 static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C, 1430 CharSourceRange Range, bool IsFirst) { 1431 // Check C99 compatibility. 1432 if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) { 1433 enum { 1434 CannotAppearInIdentifier = 0, 1435 CannotStartIdentifier 1436 }; 1437 1438 static const llvm::sys::UnicodeCharSet C99AllowedIDChars( 1439 C99AllowedIDCharRanges); 1440 static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars( 1441 C99DisallowedInitialIDCharRanges); 1442 if (!C99AllowedIDChars.contains(C)) { 1443 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id) 1444 << Range 1445 << CannotAppearInIdentifier; 1446 } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) { 1447 Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id) 1448 << Range 1449 << CannotStartIdentifier; 1450 } 1451 } 1452 1453 // Check C++98 compatibility. 1454 if (!Diags.isIgnored(diag::warn_cxx98_compat_unicode_id, Range.getBegin())) { 1455 static const llvm::sys::UnicodeCharSet CXX03AllowedIDChars( 1456 CXX03AllowedIDCharRanges); 1457 if (!CXX03AllowedIDChars.contains(C)) { 1458 Diags.Report(Range.getBegin(), diag::warn_cxx98_compat_unicode_id) 1459 << Range; 1460 } 1461 } 1462 } 1463 1464 bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size, 1465 Token &Result) { 1466 const char *UCNPtr = CurPtr + Size; 1467 uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr); 1468 if (CodePoint == 0 || !isAllowedIDChar(CodePoint, LangOpts)) 1469 return false; 1470 1471 if (!isLexingRawMode()) 1472 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint, 1473 makeCharRange(*this, CurPtr, UCNPtr), 1474 /*IsFirst=*/false); 1475 1476 Result.setFlag(Token::HasUCN); 1477 if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') || 1478 (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U')) 1479 CurPtr = UCNPtr; 1480 else 1481 while (CurPtr != UCNPtr) 1482 (void)getAndAdvanceChar(CurPtr, Result); 1483 return true; 1484 } 1485 1486 bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) { 1487 const char *UnicodePtr = CurPtr; 1488 llvm::UTF32 CodePoint; 1489 llvm::ConversionResult Result = 1490 llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr, 1491 (const llvm::UTF8 *)BufferEnd, 1492 &CodePoint, 1493 llvm::strictConversion); 1494 if (Result != llvm::conversionOK || 1495 !isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts)) 1496 return false; 1497 1498 if (!isLexingRawMode()) 1499 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint, 1500 makeCharRange(*this, CurPtr, UnicodePtr), 1501 /*IsFirst=*/false); 1502 1503 CurPtr = UnicodePtr; 1504 return true; 1505 } 1506 1507 bool Lexer::LexIdentifier(Token &Result, const char *CurPtr) { 1508 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$] 1509 unsigned Size; 1510 unsigned char C = *CurPtr++; 1511 while (isIdentifierBody(C)) 1512 C = *CurPtr++; 1513 1514 --CurPtr; // Back up over the skipped character. 1515 1516 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline 1517 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN. 1518 // 1519 // TODO: Could merge these checks into an InfoTable flag to make the 1520 // comparison cheaper 1521 if (isASCII(C) && C != '\\' && C != '?' && 1522 (C != '$' || !LangOpts.DollarIdents)) { 1523 FinishIdentifier: 1524 const char *IdStart = BufferPtr; 1525 FormTokenWithChars(Result, CurPtr, tok::raw_identifier); 1526 Result.setRawIdentifierData(IdStart); 1527 1528 // If we are in raw mode, return this identifier raw. There is no need to 1529 // look up identifier information or attempt to macro expand it. 1530 if (LexingRawMode) 1531 return true; 1532 1533 // Fill in Result.IdentifierInfo and update the token kind, 1534 // looking up the identifier in the identifier table. 1535 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result); 1536 1537 // Finally, now that we know we have an identifier, pass this off to the 1538 // preprocessor, which may macro expand it or something. 1539 if (II->isHandleIdentifierCase()) 1540 return PP->HandleIdentifier(Result); 1541 1542 if (II->getTokenID() == tok::identifier && isCodeCompletionPoint(CurPtr) 1543 && II->getPPKeywordID() == tok::pp_not_keyword 1544 && II->getObjCKeywordID() == tok::objc_not_keyword) { 1545 // Return the code-completion token. 1546 Result.setKind(tok::code_completion); 1547 cutOffLexing(); 1548 return true; 1549 } 1550 return true; 1551 } 1552 1553 // Otherwise, $,\,? in identifier found. Enter slower path. 1554 1555 C = getCharAndSize(CurPtr, Size); 1556 while (true) { 1557 if (C == '$') { 1558 // If we hit a $ and they are not supported in identifiers, we are done. 1559 if (!LangOpts.DollarIdents) goto FinishIdentifier; 1560 1561 // Otherwise, emit a diagnostic and continue. 1562 if (!isLexingRawMode()) 1563 Diag(CurPtr, diag::ext_dollar_in_identifier); 1564 CurPtr = ConsumeChar(CurPtr, Size, Result); 1565 C = getCharAndSize(CurPtr, Size); 1566 continue; 1567 1568 } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) { 1569 C = getCharAndSize(CurPtr, Size); 1570 continue; 1571 } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) { 1572 C = getCharAndSize(CurPtr, Size); 1573 continue; 1574 } else if (!isIdentifierBody(C)) { 1575 goto FinishIdentifier; 1576 } 1577 1578 // Otherwise, this character is good, consume it. 1579 CurPtr = ConsumeChar(CurPtr, Size, Result); 1580 1581 C = getCharAndSize(CurPtr, Size); 1582 while (isIdentifierBody(C)) { 1583 CurPtr = ConsumeChar(CurPtr, Size, Result); 1584 C = getCharAndSize(CurPtr, Size); 1585 } 1586 } 1587 } 1588 1589 /// isHexaLiteral - Return true if Start points to a hex constant. 1590 /// in microsoft mode (where this is supposed to be several different tokens). 1591 bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) { 1592 unsigned Size; 1593 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts); 1594 if (C1 != '0') 1595 return false; 1596 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts); 1597 return (C2 == 'x' || C2 == 'X'); 1598 } 1599 1600 /// LexNumericConstant - Lex the remainder of a integer or floating point 1601 /// constant. From[-1] is the first character lexed. Return the end of the 1602 /// constant. 1603 bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) { 1604 unsigned Size; 1605 char C = getCharAndSize(CurPtr, Size); 1606 char PrevCh = 0; 1607 while (isPreprocessingNumberBody(C)) { 1608 CurPtr = ConsumeChar(CurPtr, Size, Result); 1609 PrevCh = C; 1610 C = getCharAndSize(CurPtr, Size); 1611 } 1612 1613 // If we fell out, check for a sign, due to 1e+12. If we have one, continue. 1614 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) { 1615 // If we are in Microsoft mode, don't continue if the constant is hex. 1616 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1 1617 if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts)) 1618 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); 1619 } 1620 1621 // If we have a hex FP constant, continue. 1622 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) { 1623 // Outside C99 and C++17, we accept hexadecimal floating point numbers as a 1624 // not-quite-conforming extension. Only do so if this looks like it's 1625 // actually meant to be a hexfloat, and not if it has a ud-suffix. 1626 bool IsHexFloat = true; 1627 if (!LangOpts.C99) { 1628 if (!isHexaLiteral(BufferPtr, LangOpts)) 1629 IsHexFloat = false; 1630 else if (!getLangOpts().CPlusPlus1z && 1631 std::find(BufferPtr, CurPtr, '_') != CurPtr) 1632 IsHexFloat = false; 1633 } 1634 if (IsHexFloat) 1635 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); 1636 } 1637 1638 // If we have a digit separator, continue. 1639 if (C == '\'' && getLangOpts().CPlusPlus14) { 1640 unsigned NextSize; 1641 char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts()); 1642 if (isIdentifierBody(Next)) { 1643 if (!isLexingRawMode()) 1644 Diag(CurPtr, diag::warn_cxx11_compat_digit_separator); 1645 CurPtr = ConsumeChar(CurPtr, Size, Result); 1646 CurPtr = ConsumeChar(CurPtr, NextSize, Result); 1647 return LexNumericConstant(Result, CurPtr); 1648 } 1649 } 1650 1651 // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue. 1652 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) 1653 return LexNumericConstant(Result, CurPtr); 1654 if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) 1655 return LexNumericConstant(Result, CurPtr); 1656 1657 // Update the location of token as well as BufferPtr. 1658 const char *TokStart = BufferPtr; 1659 FormTokenWithChars(Result, CurPtr, tok::numeric_constant); 1660 Result.setLiteralData(TokStart); 1661 return true; 1662 } 1663 1664 /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes 1665 /// in C++11, or warn on a ud-suffix in C++98. 1666 const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr, 1667 bool IsStringLiteral) { 1668 assert(getLangOpts().CPlusPlus); 1669 1670 // Maximally munch an identifier. 1671 unsigned Size; 1672 char C = getCharAndSize(CurPtr, Size); 1673 bool Consumed = false; 1674 1675 if (!isIdentifierHead(C)) { 1676 if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) 1677 Consumed = true; 1678 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) 1679 Consumed = true; 1680 else 1681 return CurPtr; 1682 } 1683 1684 if (!getLangOpts().CPlusPlus11) { 1685 if (!isLexingRawMode()) 1686 Diag(CurPtr, 1687 C == '_' ? diag::warn_cxx11_compat_user_defined_literal 1688 : diag::warn_cxx11_compat_reserved_user_defined_literal) 1689 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " "); 1690 return CurPtr; 1691 } 1692 1693 // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix 1694 // that does not start with an underscore is ill-formed. As a conforming 1695 // extension, we treat all such suffixes as if they had whitespace before 1696 // them. We assume a suffix beginning with a UCN or UTF-8 character is more 1697 // likely to be a ud-suffix than a macro, however, and accept that. 1698 if (!Consumed) { 1699 bool IsUDSuffix = false; 1700 if (C == '_') 1701 IsUDSuffix = true; 1702 else if (IsStringLiteral && getLangOpts().CPlusPlus14) { 1703 // In C++1y, we need to look ahead a few characters to see if this is a 1704 // valid suffix for a string literal or a numeric literal (this could be 1705 // the 'operator""if' defining a numeric literal operator). 1706 const unsigned MaxStandardSuffixLength = 3; 1707 char Buffer[MaxStandardSuffixLength] = { C }; 1708 unsigned Consumed = Size; 1709 unsigned Chars = 1; 1710 while (true) { 1711 unsigned NextSize; 1712 char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize, 1713 getLangOpts()); 1714 if (!isIdentifierBody(Next)) { 1715 // End of suffix. Check whether this is on the whitelist. 1716 IsUDSuffix = (Chars == 1 && Buffer[0] == 's') || 1717 NumericLiteralParser::isValidUDSuffix( 1718 getLangOpts(), StringRef(Buffer, Chars)); 1719 break; 1720 } 1721 1722 if (Chars == MaxStandardSuffixLength) 1723 // Too long: can't be a standard suffix. 1724 break; 1725 1726 Buffer[Chars++] = Next; 1727 Consumed += NextSize; 1728 } 1729 } 1730 1731 if (!IsUDSuffix) { 1732 if (!isLexingRawMode()) 1733 Diag(CurPtr, getLangOpts().MSVCCompat 1734 ? diag::ext_ms_reserved_user_defined_literal 1735 : diag::ext_reserved_user_defined_literal) 1736 << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " "); 1737 return CurPtr; 1738 } 1739 1740 CurPtr = ConsumeChar(CurPtr, Size, Result); 1741 } 1742 1743 Result.setFlag(Token::HasUDSuffix); 1744 while (true) { 1745 C = getCharAndSize(CurPtr, Size); 1746 if (isIdentifierBody(C)) { CurPtr = ConsumeChar(CurPtr, Size, Result); } 1747 else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {} 1748 else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {} 1749 else break; 1750 } 1751 1752 return CurPtr; 1753 } 1754 1755 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed 1756 /// either " or L" or u8" or u" or U". 1757 bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr, 1758 tok::TokenKind Kind) { 1759 // Does this string contain the \0 character? 1760 const char *NulCharacter = nullptr; 1761 1762 if (!isLexingRawMode() && 1763 (Kind == tok::utf8_string_literal || 1764 Kind == tok::utf16_string_literal || 1765 Kind == tok::utf32_string_literal)) 1766 Diag(BufferPtr, getLangOpts().CPlusPlus 1767 ? diag::warn_cxx98_compat_unicode_literal 1768 : diag::warn_c99_compat_unicode_literal); 1769 1770 char C = getAndAdvanceChar(CurPtr, Result); 1771 while (C != '"') { 1772 // Skip escaped characters. Escaped newlines will already be processed by 1773 // getAndAdvanceChar. 1774 if (C == '\\') 1775 C = getAndAdvanceChar(CurPtr, Result); 1776 1777 if (C == '\n' || C == '\r' || // Newline. 1778 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. 1779 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor) 1780 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1; 1781 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1782 return true; 1783 } 1784 1785 if (C == 0) { 1786 if (isCodeCompletionPoint(CurPtr-1)) { 1787 PP->CodeCompleteNaturalLanguage(); 1788 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1789 cutOffLexing(); 1790 return true; 1791 } 1792 1793 NulCharacter = CurPtr-1; 1794 } 1795 C = getAndAdvanceChar(CurPtr, Result); 1796 } 1797 1798 // If we are in C++11, lex the optional ud-suffix. 1799 if (getLangOpts().CPlusPlus) 1800 CurPtr = LexUDSuffix(Result, CurPtr, true); 1801 1802 // If a nul character existed in the string, warn about it. 1803 if (NulCharacter && !isLexingRawMode()) 1804 Diag(NulCharacter, diag::null_in_char_or_string) << 1; 1805 1806 // Update the location of the token as well as the BufferPtr instance var. 1807 const char *TokStart = BufferPtr; 1808 FormTokenWithChars(Result, CurPtr, Kind); 1809 Result.setLiteralData(TokStart); 1810 return true; 1811 } 1812 1813 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after 1814 /// having lexed R", LR", u8R", uR", or UR". 1815 bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr, 1816 tok::TokenKind Kind) { 1817 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3: 1818 // Between the initial and final double quote characters of the raw string, 1819 // any transformations performed in phases 1 and 2 (trigraphs, 1820 // universal-character-names, and line splicing) are reverted. 1821 1822 if (!isLexingRawMode()) 1823 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal); 1824 1825 unsigned PrefixLen = 0; 1826 1827 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen])) 1828 ++PrefixLen; 1829 1830 // If the last character was not a '(', then we didn't lex a valid delimiter. 1831 if (CurPtr[PrefixLen] != '(') { 1832 if (!isLexingRawMode()) { 1833 const char *PrefixEnd = &CurPtr[PrefixLen]; 1834 if (PrefixLen == 16) { 1835 Diag(PrefixEnd, diag::err_raw_delim_too_long); 1836 } else { 1837 Diag(PrefixEnd, diag::err_invalid_char_raw_delim) 1838 << StringRef(PrefixEnd, 1); 1839 } 1840 } 1841 1842 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately, 1843 // it's possible the '"' was intended to be part of the raw string, but 1844 // there's not much we can do about that. 1845 while (true) { 1846 char C = *CurPtr++; 1847 1848 if (C == '"') 1849 break; 1850 if (C == 0 && CurPtr-1 == BufferEnd) { 1851 --CurPtr; 1852 break; 1853 } 1854 } 1855 1856 FormTokenWithChars(Result, CurPtr, tok::unknown); 1857 return true; 1858 } 1859 1860 // Save prefix and move CurPtr past it 1861 const char *Prefix = CurPtr; 1862 CurPtr += PrefixLen + 1; // skip over prefix and '(' 1863 1864 while (true) { 1865 char C = *CurPtr++; 1866 1867 if (C == ')') { 1868 // Check for prefix match and closing quote. 1869 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') { 1870 CurPtr += PrefixLen + 1; // skip over prefix and '"' 1871 break; 1872 } 1873 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file. 1874 if (!isLexingRawMode()) 1875 Diag(BufferPtr, diag::err_unterminated_raw_string) 1876 << StringRef(Prefix, PrefixLen); 1877 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1878 return true; 1879 } 1880 } 1881 1882 // If we are in C++11, lex the optional ud-suffix. 1883 if (getLangOpts().CPlusPlus) 1884 CurPtr = LexUDSuffix(Result, CurPtr, true); 1885 1886 // Update the location of token as well as BufferPtr. 1887 const char *TokStart = BufferPtr; 1888 FormTokenWithChars(Result, CurPtr, Kind); 1889 Result.setLiteralData(TokStart); 1890 return true; 1891 } 1892 1893 /// LexAngledStringLiteral - Lex the remainder of an angled string literal, 1894 /// after having lexed the '<' character. This is used for #include filenames. 1895 bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) { 1896 // Does this string contain the \0 character? 1897 const char *NulCharacter = nullptr; 1898 const char *AfterLessPos = CurPtr; 1899 char C = getAndAdvanceChar(CurPtr, Result); 1900 while (C != '>') { 1901 // Skip escaped characters. 1902 if (C == '\\' && CurPtr < BufferEnd) { 1903 // Skip the escaped character. 1904 getAndAdvanceChar(CurPtr, Result); 1905 } else if (C == '\n' || C == '\r' || // Newline. 1906 (C == 0 && (CurPtr-1 == BufferEnd || // End of file. 1907 isCodeCompletionPoint(CurPtr-1)))) { 1908 // If the filename is unterminated, then it must just be a lone < 1909 // character. Return this as such. 1910 FormTokenWithChars(Result, AfterLessPos, tok::less); 1911 return true; 1912 } else if (C == 0) { 1913 NulCharacter = CurPtr-1; 1914 } 1915 C = getAndAdvanceChar(CurPtr, Result); 1916 } 1917 1918 // If a nul character existed in the string, warn about it. 1919 if (NulCharacter && !isLexingRawMode()) 1920 Diag(NulCharacter, diag::null_in_char_or_string) << 1; 1921 1922 // Update the location of token as well as BufferPtr. 1923 const char *TokStart = BufferPtr; 1924 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal); 1925 Result.setLiteralData(TokStart); 1926 return true; 1927 } 1928 1929 /// LexCharConstant - Lex the remainder of a character constant, after having 1930 /// lexed either ' or L' or u8' or u' or U'. 1931 bool Lexer::LexCharConstant(Token &Result, const char *CurPtr, 1932 tok::TokenKind Kind) { 1933 // Does this character contain the \0 character? 1934 const char *NulCharacter = nullptr; 1935 1936 if (!isLexingRawMode()) { 1937 if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant) 1938 Diag(BufferPtr, getLangOpts().CPlusPlus 1939 ? diag::warn_cxx98_compat_unicode_literal 1940 : diag::warn_c99_compat_unicode_literal); 1941 else if (Kind == tok::utf8_char_constant) 1942 Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal); 1943 } 1944 1945 char C = getAndAdvanceChar(CurPtr, Result); 1946 if (C == '\'') { 1947 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor) 1948 Diag(BufferPtr, diag::ext_empty_character); 1949 FormTokenWithChars(Result, CurPtr, tok::unknown); 1950 return true; 1951 } 1952 1953 while (C != '\'') { 1954 // Skip escaped characters. 1955 if (C == '\\') 1956 C = getAndAdvanceChar(CurPtr, Result); 1957 1958 if (C == '\n' || C == '\r' || // Newline. 1959 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. 1960 if (!isLexingRawMode() && !LangOpts.AsmPreprocessor) 1961 Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0; 1962 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1963 return true; 1964 } 1965 1966 if (C == 0) { 1967 if (isCodeCompletionPoint(CurPtr-1)) { 1968 PP->CodeCompleteNaturalLanguage(); 1969 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1970 cutOffLexing(); 1971 return true; 1972 } 1973 1974 NulCharacter = CurPtr-1; 1975 } 1976 C = getAndAdvanceChar(CurPtr, Result); 1977 } 1978 1979 // If we are in C++11, lex the optional ud-suffix. 1980 if (getLangOpts().CPlusPlus) 1981 CurPtr = LexUDSuffix(Result, CurPtr, false); 1982 1983 // If a nul character existed in the character, warn about it. 1984 if (NulCharacter && !isLexingRawMode()) 1985 Diag(NulCharacter, diag::null_in_char_or_string) << 0; 1986 1987 // Update the location of token as well as BufferPtr. 1988 const char *TokStart = BufferPtr; 1989 FormTokenWithChars(Result, CurPtr, Kind); 1990 Result.setLiteralData(TokStart); 1991 return true; 1992 } 1993 1994 /// SkipWhitespace - Efficiently skip over a series of whitespace characters. 1995 /// Update BufferPtr to point to the next non-whitespace character and return. 1996 /// 1997 /// This method forms a token and returns true if KeepWhitespaceMode is enabled. 1998 /// 1999 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr, 2000 bool &TokAtPhysicalStartOfLine) { 2001 // Whitespace - Skip it, then return the token after the whitespace. 2002 bool SawNewline = isVerticalWhitespace(CurPtr[-1]); 2003 2004 unsigned char Char = *CurPtr; 2005 2006 // Skip consecutive spaces efficiently. 2007 while (true) { 2008 // Skip horizontal whitespace very aggressively. 2009 while (isHorizontalWhitespace(Char)) 2010 Char = *++CurPtr; 2011 2012 // Otherwise if we have something other than whitespace, we're done. 2013 if (!isVerticalWhitespace(Char)) 2014 break; 2015 2016 if (ParsingPreprocessorDirective) { 2017 // End of preprocessor directive line, let LexTokenInternal handle this. 2018 BufferPtr = CurPtr; 2019 return false; 2020 } 2021 2022 // OK, but handle newline. 2023 SawNewline = true; 2024 Char = *++CurPtr; 2025 } 2026 2027 // If the client wants us to return whitespace, return it now. 2028 if (isKeepWhitespaceMode()) { 2029 FormTokenWithChars(Result, CurPtr, tok::unknown); 2030 if (SawNewline) { 2031 IsAtStartOfLine = true; 2032 IsAtPhysicalStartOfLine = true; 2033 } 2034 // FIXME: The next token will not have LeadingSpace set. 2035 return true; 2036 } 2037 2038 // If this isn't immediately after a newline, there is leading space. 2039 char PrevChar = CurPtr[-1]; 2040 bool HasLeadingSpace = !isVerticalWhitespace(PrevChar); 2041 2042 Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace); 2043 if (SawNewline) { 2044 Result.setFlag(Token::StartOfLine); 2045 TokAtPhysicalStartOfLine = true; 2046 } 2047 2048 BufferPtr = CurPtr; 2049 return false; 2050 } 2051 2052 /// We have just read the // characters from input. Skip until we find the 2053 /// newline character thats terminate the comment. Then update BufferPtr and 2054 /// return. 2055 /// 2056 /// If we're in KeepCommentMode or any CommentHandler has inserted 2057 /// some tokens, this will store the first token and return true. 2058 bool Lexer::SkipLineComment(Token &Result, const char *CurPtr, 2059 bool &TokAtPhysicalStartOfLine) { 2060 // If Line comments aren't explicitly enabled for this language, emit an 2061 // extension warning. 2062 if (!LangOpts.LineComment && !isLexingRawMode()) { 2063 Diag(BufferPtr, diag::ext_line_comment); 2064 2065 // Mark them enabled so we only emit one warning for this translation 2066 // unit. 2067 LangOpts.LineComment = true; 2068 } 2069 2070 // Scan over the body of the comment. The common case, when scanning, is that 2071 // the comment contains normal ascii characters with nothing interesting in 2072 // them. As such, optimize for this case with the inner loop. 2073 char C; 2074 do { 2075 C = *CurPtr; 2076 // Skip over characters in the fast loop. 2077 while (C != 0 && // Potentially EOF. 2078 C != '\n' && C != '\r') // Newline or DOS-style newline. 2079 C = *++CurPtr; 2080 2081 const char *NextLine = CurPtr; 2082 if (C != 0) { 2083 // We found a newline, see if it's escaped. 2084 const char *EscapePtr = CurPtr-1; 2085 bool HasSpace = false; 2086 while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace. 2087 --EscapePtr; 2088 HasSpace = true; 2089 } 2090 2091 if (*EscapePtr == '\\') // Escaped newline. 2092 CurPtr = EscapePtr; 2093 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' && 2094 EscapePtr[-2] == '?') // Trigraph-escaped newline. 2095 CurPtr = EscapePtr-2; 2096 else 2097 break; // This is a newline, we're done. 2098 2099 // If there was space between the backslash and newline, warn about it. 2100 if (HasSpace && !isLexingRawMode()) 2101 Diag(EscapePtr, diag::backslash_newline_space); 2102 } 2103 2104 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to 2105 // properly decode the character. Read it in raw mode to avoid emitting 2106 // diagnostics about things like trigraphs. If we see an escaped newline, 2107 // we'll handle it below. 2108 const char *OldPtr = CurPtr; 2109 bool OldRawMode = isLexingRawMode(); 2110 LexingRawMode = true; 2111 C = getAndAdvanceChar(CurPtr, Result); 2112 LexingRawMode = OldRawMode; 2113 2114 // If we only read only one character, then no special handling is needed. 2115 // We're done and can skip forward to the newline. 2116 if (C != 0 && CurPtr == OldPtr+1) { 2117 CurPtr = NextLine; 2118 break; 2119 } 2120 2121 // If we read multiple characters, and one of those characters was a \r or 2122 // \n, then we had an escaped newline within the comment. Emit diagnostic 2123 // unless the next line is also a // comment. 2124 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') { 2125 for (; OldPtr != CurPtr; ++OldPtr) 2126 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') { 2127 // Okay, we found a // comment that ends in a newline, if the next 2128 // line is also a // comment, but has spaces, don't emit a diagnostic. 2129 if (isWhitespace(C)) { 2130 const char *ForwardPtr = CurPtr; 2131 while (isWhitespace(*ForwardPtr)) // Skip whitespace. 2132 ++ForwardPtr; 2133 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/') 2134 break; 2135 } 2136 2137 if (!isLexingRawMode()) 2138 Diag(OldPtr-1, diag::ext_multi_line_line_comment); 2139 break; 2140 } 2141 } 2142 2143 if (CurPtr == BufferEnd+1) { 2144 --CurPtr; 2145 break; 2146 } 2147 2148 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) { 2149 PP->CodeCompleteNaturalLanguage(); 2150 cutOffLexing(); 2151 return false; 2152 } 2153 2154 } while (C != '\n' && C != '\r'); 2155 2156 // Found but did not consume the newline. Notify comment handlers about the 2157 // comment unless we're in a #if 0 block. 2158 if (PP && !isLexingRawMode() && 2159 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr), 2160 getSourceLocation(CurPtr)))) { 2161 BufferPtr = CurPtr; 2162 return true; // A token has to be returned. 2163 } 2164 2165 // If we are returning comments as tokens, return this comment as a token. 2166 if (inKeepCommentMode()) 2167 return SaveLineComment(Result, CurPtr); 2168 2169 // If we are inside a preprocessor directive and we see the end of line, 2170 // return immediately, so that the lexer can return this as an EOD token. 2171 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) { 2172 BufferPtr = CurPtr; 2173 return false; 2174 } 2175 2176 // Otherwise, eat the \n character. We don't care if this is a \n\r or 2177 // \r\n sequence. This is an efficiency hack (because we know the \n can't 2178 // contribute to another token), it isn't needed for correctness. Note that 2179 // this is ok even in KeepWhitespaceMode, because we would have returned the 2180 /// comment above in that mode. 2181 ++CurPtr; 2182 2183 // The next returned token is at the start of the line. 2184 Result.setFlag(Token::StartOfLine); 2185 TokAtPhysicalStartOfLine = true; 2186 // No leading whitespace seen so far. 2187 Result.clearFlag(Token::LeadingSpace); 2188 BufferPtr = CurPtr; 2189 return false; 2190 } 2191 2192 /// If in save-comment mode, package up this Line comment in an appropriate 2193 /// way and return it. 2194 bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) { 2195 // If we're not in a preprocessor directive, just return the // comment 2196 // directly. 2197 FormTokenWithChars(Result, CurPtr, tok::comment); 2198 2199 if (!ParsingPreprocessorDirective || LexingRawMode) 2200 return true; 2201 2202 // If this Line-style comment is in a macro definition, transmogrify it into 2203 // a C-style block comment. 2204 bool Invalid = false; 2205 std::string Spelling = PP->getSpelling(Result, &Invalid); 2206 if (Invalid) 2207 return true; 2208 2209 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?"); 2210 Spelling[1] = '*'; // Change prefix to "/*". 2211 Spelling += "*/"; // add suffix. 2212 2213 Result.setKind(tok::comment); 2214 PP->CreateString(Spelling, Result, 2215 Result.getLocation(), Result.getLocation()); 2216 return true; 2217 } 2218 2219 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline 2220 /// character (either \\n or \\r) is part of an escaped newline sequence. Issue 2221 /// a diagnostic if so. We know that the newline is inside of a block comment. 2222 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, 2223 Lexer *L) { 2224 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r'); 2225 2226 // Back up off the newline. 2227 --CurPtr; 2228 2229 // If this is a two-character newline sequence, skip the other character. 2230 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') { 2231 // \n\n or \r\r -> not escaped newline. 2232 if (CurPtr[0] == CurPtr[1]) 2233 return false; 2234 // \n\r or \r\n -> skip the newline. 2235 --CurPtr; 2236 } 2237 2238 // If we have horizontal whitespace, skip over it. We allow whitespace 2239 // between the slash and newline. 2240 bool HasSpace = false; 2241 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) { 2242 --CurPtr; 2243 HasSpace = true; 2244 } 2245 2246 // If we have a slash, we know this is an escaped newline. 2247 if (*CurPtr == '\\') { 2248 if (CurPtr[-1] != '*') return false; 2249 } else { 2250 // It isn't a slash, is it the ?? / trigraph? 2251 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' || 2252 CurPtr[-3] != '*') 2253 return false; 2254 2255 // This is the trigraph ending the comment. Emit a stern warning! 2256 CurPtr -= 2; 2257 2258 // If no trigraphs are enabled, warn that we ignored this trigraph and 2259 // ignore this * character. 2260 if (!L->getLangOpts().Trigraphs) { 2261 if (!L->isLexingRawMode()) 2262 L->Diag(CurPtr, diag::trigraph_ignored_block_comment); 2263 return false; 2264 } 2265 if (!L->isLexingRawMode()) 2266 L->Diag(CurPtr, diag::trigraph_ends_block_comment); 2267 } 2268 2269 // Warn about having an escaped newline between the */ characters. 2270 if (!L->isLexingRawMode()) 2271 L->Diag(CurPtr, diag::escaped_newline_block_comment_end); 2272 2273 // If there was space between the backslash and newline, warn about it. 2274 if (HasSpace && !L->isLexingRawMode()) 2275 L->Diag(CurPtr, diag::backslash_newline_space); 2276 2277 return true; 2278 } 2279 2280 #ifdef __SSE2__ 2281 #include <emmintrin.h> 2282 #elif __ALTIVEC__ 2283 #include <altivec.h> 2284 #undef bool 2285 #endif 2286 2287 /// We have just read from input the / and * characters that started a comment. 2288 /// Read until we find the * and / characters that terminate the comment. 2289 /// Note that we don't bother decoding trigraphs or escaped newlines in block 2290 /// comments, because they cannot cause the comment to end. The only thing 2291 /// that can happen is the comment could end with an escaped newline between 2292 /// the terminating * and /. 2293 /// 2294 /// If we're in KeepCommentMode or any CommentHandler has inserted 2295 /// some tokens, this will store the first token and return true. 2296 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr, 2297 bool &TokAtPhysicalStartOfLine) { 2298 // Scan one character past where we should, looking for a '/' character. Once 2299 // we find it, check to see if it was preceded by a *. This common 2300 // optimization helps people who like to put a lot of * characters in their 2301 // comments. 2302 2303 // The first character we get with newlines and trigraphs skipped to handle 2304 // the degenerate /*/ case below correctly if the * has an escaped newline 2305 // after it. 2306 unsigned CharSize; 2307 unsigned char C = getCharAndSize(CurPtr, CharSize); 2308 CurPtr += CharSize; 2309 if (C == 0 && CurPtr == BufferEnd+1) { 2310 if (!isLexingRawMode()) 2311 Diag(BufferPtr, diag::err_unterminated_block_comment); 2312 --CurPtr; 2313 2314 // KeepWhitespaceMode should return this broken comment as a token. Since 2315 // it isn't a well formed comment, just return it as an 'unknown' token. 2316 if (isKeepWhitespaceMode()) { 2317 FormTokenWithChars(Result, CurPtr, tok::unknown); 2318 return true; 2319 } 2320 2321 BufferPtr = CurPtr; 2322 return false; 2323 } 2324 2325 // Check to see if the first character after the '/*' is another /. If so, 2326 // then this slash does not end the block comment, it is part of it. 2327 if (C == '/') 2328 C = *CurPtr++; 2329 2330 while (true) { 2331 // Skip over all non-interesting characters until we find end of buffer or a 2332 // (probably ending) '/' character. 2333 if (CurPtr + 24 < BufferEnd && 2334 // If there is a code-completion point avoid the fast scan because it 2335 // doesn't check for '\0'. 2336 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) { 2337 // While not aligned to a 16-byte boundary. 2338 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0) 2339 C = *CurPtr++; 2340 2341 if (C == '/') goto FoundSlash; 2342 2343 #ifdef __SSE2__ 2344 __m128i Slashes = _mm_set1_epi8('/'); 2345 while (CurPtr+16 <= BufferEnd) { 2346 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr, 2347 Slashes)); 2348 if (cmp != 0) { 2349 // Adjust the pointer to point directly after the first slash. It's 2350 // not necessary to set C here, it will be overwritten at the end of 2351 // the outer loop. 2352 CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1; 2353 goto FoundSlash; 2354 } 2355 CurPtr += 16; 2356 } 2357 #elif __ALTIVEC__ 2358 __vector unsigned char Slashes = { 2359 '/', '/', '/', '/', '/', '/', '/', '/', 2360 '/', '/', '/', '/', '/', '/', '/', '/' 2361 }; 2362 while (CurPtr+16 <= BufferEnd && 2363 !vec_any_eq(*(const vector unsigned char*)CurPtr, Slashes)) 2364 CurPtr += 16; 2365 #else 2366 // Scan for '/' quickly. Many block comments are very large. 2367 while (CurPtr[0] != '/' && 2368 CurPtr[1] != '/' && 2369 CurPtr[2] != '/' && 2370 CurPtr[3] != '/' && 2371 CurPtr+4 < BufferEnd) { 2372 CurPtr += 4; 2373 } 2374 #endif 2375 2376 // It has to be one of the bytes scanned, increment to it and read one. 2377 C = *CurPtr++; 2378 } 2379 2380 // Loop to scan the remainder. 2381 while (C != '/' && C != '\0') 2382 C = *CurPtr++; 2383 2384 if (C == '/') { 2385 FoundSlash: 2386 if (CurPtr[-2] == '*') // We found the final */. We're done! 2387 break; 2388 2389 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) { 2390 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) { 2391 // We found the final */, though it had an escaped newline between the 2392 // * and /. We're done! 2393 break; 2394 } 2395 } 2396 if (CurPtr[0] == '*' && CurPtr[1] != '/') { 2397 // If this is a /* inside of the comment, emit a warning. Don't do this 2398 // if this is a /*/, which will end the comment. This misses cases with 2399 // embedded escaped newlines, but oh well. 2400 if (!isLexingRawMode()) 2401 Diag(CurPtr-1, diag::warn_nested_block_comment); 2402 } 2403 } else if (C == 0 && CurPtr == BufferEnd+1) { 2404 if (!isLexingRawMode()) 2405 Diag(BufferPtr, diag::err_unterminated_block_comment); 2406 // Note: the user probably forgot a */. We could continue immediately 2407 // after the /*, but this would involve lexing a lot of what really is the 2408 // comment, which surely would confuse the parser. 2409 --CurPtr; 2410 2411 // KeepWhitespaceMode should return this broken comment as a token. Since 2412 // it isn't a well formed comment, just return it as an 'unknown' token. 2413 if (isKeepWhitespaceMode()) { 2414 FormTokenWithChars(Result, CurPtr, tok::unknown); 2415 return true; 2416 } 2417 2418 BufferPtr = CurPtr; 2419 return false; 2420 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) { 2421 PP->CodeCompleteNaturalLanguage(); 2422 cutOffLexing(); 2423 return false; 2424 } 2425 2426 C = *CurPtr++; 2427 } 2428 2429 // Notify comment handlers about the comment unless we're in a #if 0 block. 2430 if (PP && !isLexingRawMode() && 2431 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr), 2432 getSourceLocation(CurPtr)))) { 2433 BufferPtr = CurPtr; 2434 return true; // A token has to be returned. 2435 } 2436 2437 // If we are returning comments as tokens, return this comment as a token. 2438 if (inKeepCommentMode()) { 2439 FormTokenWithChars(Result, CurPtr, tok::comment); 2440 return true; 2441 } 2442 2443 // It is common for the tokens immediately after a /**/ comment to be 2444 // whitespace. Instead of going through the big switch, handle it 2445 // efficiently now. This is safe even in KeepWhitespaceMode because we would 2446 // have already returned above with the comment as a token. 2447 if (isHorizontalWhitespace(*CurPtr)) { 2448 SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine); 2449 return false; 2450 } 2451 2452 // Otherwise, just return so that the next character will be lexed as a token. 2453 BufferPtr = CurPtr; 2454 Result.setFlag(Token::LeadingSpace); 2455 return false; 2456 } 2457 2458 //===----------------------------------------------------------------------===// 2459 // Primary Lexing Entry Points 2460 //===----------------------------------------------------------------------===// 2461 2462 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 2463 /// uninterpreted string. This switches the lexer out of directive mode. 2464 void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) { 2465 assert(ParsingPreprocessorDirective && ParsingFilename == false && 2466 "Must be in a preprocessing directive!"); 2467 Token Tmp; 2468 2469 // CurPtr - Cache BufferPtr in an automatic variable. 2470 const char *CurPtr = BufferPtr; 2471 while (true) { 2472 char Char = getAndAdvanceChar(CurPtr, Tmp); 2473 switch (Char) { 2474 default: 2475 if (Result) 2476 Result->push_back(Char); 2477 break; 2478 case 0: // Null. 2479 // Found end of file? 2480 if (CurPtr-1 != BufferEnd) { 2481 if (isCodeCompletionPoint(CurPtr-1)) { 2482 PP->CodeCompleteNaturalLanguage(); 2483 cutOffLexing(); 2484 return; 2485 } 2486 2487 // Nope, normal character, continue. 2488 if (Result) 2489 Result->push_back(Char); 2490 break; 2491 } 2492 // FALL THROUGH. 2493 case '\r': 2494 case '\n': 2495 // Okay, we found the end of the line. First, back up past the \0, \r, \n. 2496 assert(CurPtr[-1] == Char && "Trigraphs for newline?"); 2497 BufferPtr = CurPtr-1; 2498 2499 // Next, lex the character, which should handle the EOD transition. 2500 Lex(Tmp); 2501 if (Tmp.is(tok::code_completion)) { 2502 if (PP) 2503 PP->CodeCompleteNaturalLanguage(); 2504 Lex(Tmp); 2505 } 2506 assert(Tmp.is(tok::eod) && "Unexpected token!"); 2507 2508 // Finally, we're done; 2509 return; 2510 } 2511 } 2512 } 2513 2514 /// LexEndOfFile - CurPtr points to the end of this file. Handle this 2515 /// condition, reporting diagnostics and handling other edge cases as required. 2516 /// This returns true if Result contains a token, false if PP.Lex should be 2517 /// called again. 2518 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { 2519 // If we hit the end of the file while parsing a preprocessor directive, 2520 // end the preprocessor directive first. The next token returned will 2521 // then be the end of file. 2522 if (ParsingPreprocessorDirective) { 2523 // Done parsing the "line". 2524 ParsingPreprocessorDirective = false; 2525 // Update the location of token as well as BufferPtr. 2526 FormTokenWithChars(Result, CurPtr, tok::eod); 2527 2528 // Restore comment saving mode, in case it was disabled for directive. 2529 if (PP) 2530 resetExtendedTokenMode(); 2531 return true; // Have a token. 2532 } 2533 2534 // If we are in raw mode, return this event as an EOF token. Let the caller 2535 // that put us in raw mode handle the event. 2536 if (isLexingRawMode()) { 2537 Result.startToken(); 2538 BufferPtr = BufferEnd; 2539 FormTokenWithChars(Result, BufferEnd, tok::eof); 2540 return true; 2541 } 2542 2543 // Issue diagnostics for unterminated #if and missing newline. 2544 2545 // If we are in a #if directive, emit an error. 2546 while (!ConditionalStack.empty()) { 2547 if (PP->getCodeCompletionFileLoc() != FileLoc) 2548 PP->Diag(ConditionalStack.back().IfLoc, 2549 diag::err_pp_unterminated_conditional); 2550 ConditionalStack.pop_back(); 2551 } 2552 2553 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue 2554 // a pedwarn. 2555 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) { 2556 DiagnosticsEngine &Diags = PP->getDiagnostics(); 2557 SourceLocation EndLoc = getSourceLocation(BufferEnd); 2558 unsigned DiagID; 2559 2560 if (LangOpts.CPlusPlus11) { 2561 // C++11 [lex.phases] 2.2 p2 2562 // Prefer the C++98 pedantic compatibility warning over the generic, 2563 // non-extension, user-requested "missing newline at EOF" warning. 2564 if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) { 2565 DiagID = diag::warn_cxx98_compat_no_newline_eof; 2566 } else { 2567 DiagID = diag::warn_no_newline_eof; 2568 } 2569 } else { 2570 DiagID = diag::ext_no_newline_eof; 2571 } 2572 2573 Diag(BufferEnd, DiagID) 2574 << FixItHint::CreateInsertion(EndLoc, "\n"); 2575 } 2576 2577 BufferPtr = CurPtr; 2578 2579 // Finally, let the preprocessor handle this. 2580 return PP->HandleEndOfFile(Result, isPragmaLexer()); 2581 } 2582 2583 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from 2584 /// the specified lexer will return a tok::l_paren token, 0 if it is something 2585 /// else and 2 if there are no more tokens in the buffer controlled by the 2586 /// lexer. 2587 unsigned Lexer::isNextPPTokenLParen() { 2588 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?"); 2589 2590 // Switch to 'skipping' mode. This will ensure that we can lex a token 2591 // without emitting diagnostics, disables macro expansion, and will cause EOF 2592 // to return an EOF token instead of popping the include stack. 2593 LexingRawMode = true; 2594 2595 // Save state that can be changed while lexing so that we can restore it. 2596 const char *TmpBufferPtr = BufferPtr; 2597 bool inPPDirectiveMode = ParsingPreprocessorDirective; 2598 bool atStartOfLine = IsAtStartOfLine; 2599 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine; 2600 bool leadingSpace = HasLeadingSpace; 2601 2602 Token Tok; 2603 Lex(Tok); 2604 2605 // Restore state that may have changed. 2606 BufferPtr = TmpBufferPtr; 2607 ParsingPreprocessorDirective = inPPDirectiveMode; 2608 HasLeadingSpace = leadingSpace; 2609 IsAtStartOfLine = atStartOfLine; 2610 IsAtPhysicalStartOfLine = atPhysicalStartOfLine; 2611 2612 // Restore the lexer back to non-skipping mode. 2613 LexingRawMode = false; 2614 2615 if (Tok.is(tok::eof)) 2616 return 2; 2617 return Tok.is(tok::l_paren); 2618 } 2619 2620 /// \brief Find the end of a version control conflict marker. 2621 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd, 2622 ConflictMarkerKind CMK) { 2623 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>"; 2624 size_t TermLen = CMK == CMK_Perforce ? 5 : 7; 2625 auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen); 2626 size_t Pos = RestOfBuffer.find(Terminator); 2627 while (Pos != StringRef::npos) { 2628 // Must occur at start of line. 2629 if (Pos == 0 || 2630 (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) { 2631 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen); 2632 Pos = RestOfBuffer.find(Terminator); 2633 continue; 2634 } 2635 return RestOfBuffer.data()+Pos; 2636 } 2637 return nullptr; 2638 } 2639 2640 /// IsStartOfConflictMarker - If the specified pointer is the start of a version 2641 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error 2642 /// and recover nicely. This returns true if it is a conflict marker and false 2643 /// if not. 2644 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) { 2645 // Only a conflict marker if it starts at the beginning of a line. 2646 if (CurPtr != BufferStart && 2647 CurPtr[-1] != '\n' && CurPtr[-1] != '\r') 2648 return false; 2649 2650 // Check to see if we have <<<<<<< or >>>>. 2651 if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") && 2652 !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> ")) 2653 return false; 2654 2655 // If we have a situation where we don't care about conflict markers, ignore 2656 // it. 2657 if (CurrentConflictMarkerState || isLexingRawMode()) 2658 return false; 2659 2660 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce; 2661 2662 // Check to see if there is an ending marker somewhere in the buffer at the 2663 // start of a line to terminate this conflict marker. 2664 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) { 2665 // We found a match. We are really in a conflict marker. 2666 // Diagnose this, and ignore to the end of line. 2667 Diag(CurPtr, diag::err_conflict_marker); 2668 CurrentConflictMarkerState = Kind; 2669 2670 // Skip ahead to the end of line. We know this exists because the 2671 // end-of-conflict marker starts with \r or \n. 2672 while (*CurPtr != '\r' && *CurPtr != '\n') { 2673 assert(CurPtr != BufferEnd && "Didn't find end of line"); 2674 ++CurPtr; 2675 } 2676 BufferPtr = CurPtr; 2677 return true; 2678 } 2679 2680 // No end of conflict marker found. 2681 return false; 2682 } 2683 2684 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if 2685 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it 2686 /// is the end of a conflict marker. Handle it by ignoring up until the end of 2687 /// the line. This returns true if it is a conflict marker and false if not. 2688 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) { 2689 // Only a conflict marker if it starts at the beginning of a line. 2690 if (CurPtr != BufferStart && 2691 CurPtr[-1] != '\n' && CurPtr[-1] != '\r') 2692 return false; 2693 2694 // If we have a situation where we don't care about conflict markers, ignore 2695 // it. 2696 if (!CurrentConflictMarkerState || isLexingRawMode()) 2697 return false; 2698 2699 // Check to see if we have the marker (4 characters in a row). 2700 for (unsigned i = 1; i != 4; ++i) 2701 if (CurPtr[i] != CurPtr[0]) 2702 return false; 2703 2704 // If we do have it, search for the end of the conflict marker. This could 2705 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might 2706 // be the end of conflict marker. 2707 if (const char *End = FindConflictEnd(CurPtr, BufferEnd, 2708 CurrentConflictMarkerState)) { 2709 CurPtr = End; 2710 2711 // Skip ahead to the end of line. 2712 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n') 2713 ++CurPtr; 2714 2715 BufferPtr = CurPtr; 2716 2717 // No longer in the conflict marker. 2718 CurrentConflictMarkerState = CMK_None; 2719 return true; 2720 } 2721 2722 return false; 2723 } 2724 2725 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const { 2726 if (PP && PP->isCodeCompletionEnabled()) { 2727 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart); 2728 return Loc == PP->getCodeCompletionLoc(); 2729 } 2730 2731 return false; 2732 } 2733 2734 uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc, 2735 Token *Result) { 2736 unsigned CharSize; 2737 char Kind = getCharAndSize(StartPtr, CharSize); 2738 2739 unsigned NumHexDigits; 2740 if (Kind == 'u') 2741 NumHexDigits = 4; 2742 else if (Kind == 'U') 2743 NumHexDigits = 8; 2744 else 2745 return 0; 2746 2747 if (!LangOpts.CPlusPlus && !LangOpts.C99) { 2748 if (Result && !isLexingRawMode()) 2749 Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89); 2750 return 0; 2751 } 2752 2753 const char *CurPtr = StartPtr + CharSize; 2754 const char *KindLoc = &CurPtr[-1]; 2755 2756 uint32_t CodePoint = 0; 2757 for (unsigned i = 0; i < NumHexDigits; ++i) { 2758 char C = getCharAndSize(CurPtr, CharSize); 2759 2760 unsigned Value = llvm::hexDigitValue(C); 2761 if (Value == -1U) { 2762 if (Result && !isLexingRawMode()) { 2763 if (i == 0) { 2764 Diag(BufferPtr, diag::warn_ucn_escape_no_digits) 2765 << StringRef(KindLoc, 1); 2766 } else { 2767 Diag(BufferPtr, diag::warn_ucn_escape_incomplete); 2768 2769 // If the user wrote \U1234, suggest a fixit to \u. 2770 if (i == 4 && NumHexDigits == 8) { 2771 CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1); 2772 Diag(KindLoc, diag::note_ucn_four_not_eight) 2773 << FixItHint::CreateReplacement(URange, "u"); 2774 } 2775 } 2776 } 2777 2778 return 0; 2779 } 2780 2781 CodePoint <<= 4; 2782 CodePoint += Value; 2783 2784 CurPtr += CharSize; 2785 } 2786 2787 if (Result) { 2788 Result->setFlag(Token::HasUCN); 2789 if (CurPtr - StartPtr == (ptrdiff_t)NumHexDigits + 2) 2790 StartPtr = CurPtr; 2791 else 2792 while (StartPtr != CurPtr) 2793 (void)getAndAdvanceChar(StartPtr, *Result); 2794 } else { 2795 StartPtr = CurPtr; 2796 } 2797 2798 // Don't apply C family restrictions to UCNs in assembly mode 2799 if (LangOpts.AsmPreprocessor) 2800 return CodePoint; 2801 2802 // C99 6.4.3p2: A universal character name shall not specify a character whose 2803 // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or 2804 // 0060 (`), nor one in the range D800 through DFFF inclusive.) 2805 // C++11 [lex.charset]p2: If the hexadecimal value for a 2806 // universal-character-name corresponds to a surrogate code point (in the 2807 // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally, 2808 // if the hexadecimal value for a universal-character-name outside the 2809 // c-char-sequence, s-char-sequence, or r-char-sequence of a character or 2810 // string literal corresponds to a control character (in either of the 2811 // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the 2812 // basic source character set, the program is ill-formed. 2813 if (CodePoint < 0xA0) { 2814 if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60) 2815 return CodePoint; 2816 2817 // We don't use isLexingRawMode() here because we need to warn about bad 2818 // UCNs even when skipping preprocessing tokens in a #if block. 2819 if (Result && PP) { 2820 if (CodePoint < 0x20 || CodePoint >= 0x7F) 2821 Diag(BufferPtr, diag::err_ucn_control_character); 2822 else { 2823 char C = static_cast<char>(CodePoint); 2824 Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1); 2825 } 2826 } 2827 2828 return 0; 2829 2830 } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) { 2831 // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't. 2832 // We don't use isLexingRawMode() here because we need to diagnose bad 2833 // UCNs even when skipping preprocessing tokens in a #if block. 2834 if (Result && PP) { 2835 if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11) 2836 Diag(BufferPtr, diag::warn_ucn_escape_surrogate); 2837 else 2838 Diag(BufferPtr, diag::err_ucn_escape_invalid); 2839 } 2840 return 0; 2841 } 2842 2843 return CodePoint; 2844 } 2845 2846 bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C, 2847 const char *CurPtr) { 2848 static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars( 2849 UnicodeWhitespaceCharRanges); 2850 if (!isLexingRawMode() && !PP->isPreprocessedOutput() && 2851 UnicodeWhitespaceChars.contains(C)) { 2852 Diag(BufferPtr, diag::ext_unicode_whitespace) 2853 << makeCharRange(*this, BufferPtr, CurPtr); 2854 2855 Result.setFlag(Token::LeadingSpace); 2856 return true; 2857 } 2858 return false; 2859 } 2860 2861 bool Lexer::LexUnicode(Token &Result, uint32_t C, const char *CurPtr) { 2862 if (isAllowedIDChar(C, LangOpts) && isAllowedInitiallyIDChar(C, LangOpts)) { 2863 if (!isLexingRawMode() && !ParsingPreprocessorDirective && 2864 !PP->isPreprocessedOutput()) { 2865 maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C, 2866 makeCharRange(*this, BufferPtr, CurPtr), 2867 /*IsFirst=*/true); 2868 } 2869 2870 MIOpt.ReadToken(); 2871 return LexIdentifier(Result, CurPtr); 2872 } 2873 2874 if (!isLexingRawMode() && !ParsingPreprocessorDirective && 2875 !PP->isPreprocessedOutput() && 2876 !isASCII(*BufferPtr) && !isAllowedIDChar(C, LangOpts)) { 2877 // Non-ASCII characters tend to creep into source code unintentionally. 2878 // Instead of letting the parser complain about the unknown token, 2879 // just drop the character. 2880 // Note that we can /only/ do this when the non-ASCII character is actually 2881 // spelled as Unicode, not written as a UCN. The standard requires that 2882 // we not throw away any possible preprocessor tokens, but there's a 2883 // loophole in the mapping of Unicode characters to basic character set 2884 // characters that allows us to map these particular characters to, say, 2885 // whitespace. 2886 Diag(BufferPtr, diag::err_non_ascii) 2887 << FixItHint::CreateRemoval(makeCharRange(*this, BufferPtr, CurPtr)); 2888 2889 BufferPtr = CurPtr; 2890 return false; 2891 } 2892 2893 // Otherwise, we have an explicit UCN or a character that's unlikely to show 2894 // up by accident. 2895 MIOpt.ReadToken(); 2896 FormTokenWithChars(Result, CurPtr, tok::unknown); 2897 return true; 2898 } 2899 2900 void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) { 2901 IsAtStartOfLine = Result.isAtStartOfLine(); 2902 HasLeadingSpace = Result.hasLeadingSpace(); 2903 HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro(); 2904 // Note that this doesn't affect IsAtPhysicalStartOfLine. 2905 } 2906 2907 bool Lexer::Lex(Token &Result) { 2908 // Start a new token. 2909 Result.startToken(); 2910 2911 // Set up misc whitespace flags for LexTokenInternal. 2912 if (IsAtStartOfLine) { 2913 Result.setFlag(Token::StartOfLine); 2914 IsAtStartOfLine = false; 2915 } 2916 2917 if (HasLeadingSpace) { 2918 Result.setFlag(Token::LeadingSpace); 2919 HasLeadingSpace = false; 2920 } 2921 2922 if (HasLeadingEmptyMacro) { 2923 Result.setFlag(Token::LeadingEmptyMacro); 2924 HasLeadingEmptyMacro = false; 2925 } 2926 2927 bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine; 2928 IsAtPhysicalStartOfLine = false; 2929 bool isRawLex = isLexingRawMode(); 2930 (void) isRawLex; 2931 bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine); 2932 // (After the LexTokenInternal call, the lexer might be destroyed.) 2933 assert((returnedToken || !isRawLex) && "Raw lex must succeed"); 2934 return returnedToken; 2935 } 2936 2937 /// LexTokenInternal - This implements a simple C family lexer. It is an 2938 /// extremely performance critical piece of code. This assumes that the buffer 2939 /// has a null character at the end of the file. This returns a preprocessing 2940 /// token, not a normal token, as such, it is an internal interface. It assumes 2941 /// that the Flags of result have been cleared before calling this. 2942 bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) { 2943 LexNextToken: 2944 // New token, can't need cleaning yet. 2945 Result.clearFlag(Token::NeedsCleaning); 2946 Result.setIdentifierInfo(nullptr); 2947 2948 // CurPtr - Cache BufferPtr in an automatic variable. 2949 const char *CurPtr = BufferPtr; 2950 2951 // Small amounts of horizontal whitespace is very common between tokens. 2952 if ((*CurPtr == ' ') || (*CurPtr == '\t')) { 2953 ++CurPtr; 2954 while ((*CurPtr == ' ') || (*CurPtr == '\t')) 2955 ++CurPtr; 2956 2957 // If we are keeping whitespace and other tokens, just return what we just 2958 // skipped. The next lexer invocation will return the token after the 2959 // whitespace. 2960 if (isKeepWhitespaceMode()) { 2961 FormTokenWithChars(Result, CurPtr, tok::unknown); 2962 // FIXME: The next token will not have LeadingSpace set. 2963 return true; 2964 } 2965 2966 BufferPtr = CurPtr; 2967 Result.setFlag(Token::LeadingSpace); 2968 } 2969 2970 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below. 2971 2972 // Read a character, advancing over it. 2973 char Char = getAndAdvanceChar(CurPtr, Result); 2974 tok::TokenKind Kind; 2975 2976 switch (Char) { 2977 case 0: // Null. 2978 // Found end of file? 2979 if (CurPtr-1 == BufferEnd) 2980 return LexEndOfFile(Result, CurPtr-1); 2981 2982 // Check if we are performing code completion. 2983 if (isCodeCompletionPoint(CurPtr-1)) { 2984 // Return the code-completion token. 2985 Result.startToken(); 2986 FormTokenWithChars(Result, CurPtr, tok::code_completion); 2987 return true; 2988 } 2989 2990 if (!isLexingRawMode()) 2991 Diag(CurPtr-1, diag::null_in_file); 2992 Result.setFlag(Token::LeadingSpace); 2993 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) 2994 return true; // KeepWhitespaceMode 2995 2996 // We know the lexer hasn't changed, so just try again with this lexer. 2997 // (We manually eliminate the tail call to avoid recursion.) 2998 goto LexNextToken; 2999 3000 case 26: // DOS & CP/M EOF: "^Z". 3001 // If we're in Microsoft extensions mode, treat this as end of file. 3002 if (LangOpts.MicrosoftExt) { 3003 if (!isLexingRawMode()) 3004 Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft); 3005 return LexEndOfFile(Result, CurPtr-1); 3006 } 3007 3008 // If Microsoft extensions are disabled, this is just random garbage. 3009 Kind = tok::unknown; 3010 break; 3011 3012 case '\n': 3013 case '\r': 3014 // If we are inside a preprocessor directive and we see the end of line, 3015 // we know we are done with the directive, so return an EOD token. 3016 if (ParsingPreprocessorDirective) { 3017 // Done parsing the "line". 3018 ParsingPreprocessorDirective = false; 3019 3020 // Restore comment saving mode, in case it was disabled for directive. 3021 if (PP) 3022 resetExtendedTokenMode(); 3023 3024 // Since we consumed a newline, we are back at the start of a line. 3025 IsAtStartOfLine = true; 3026 IsAtPhysicalStartOfLine = true; 3027 3028 Kind = tok::eod; 3029 break; 3030 } 3031 3032 // No leading whitespace seen so far. 3033 Result.clearFlag(Token::LeadingSpace); 3034 3035 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) 3036 return true; // KeepWhitespaceMode 3037 3038 // We only saw whitespace, so just try again with this lexer. 3039 // (We manually eliminate the tail call to avoid recursion.) 3040 goto LexNextToken; 3041 case ' ': 3042 case '\t': 3043 case '\f': 3044 case '\v': 3045 SkipHorizontalWhitespace: 3046 Result.setFlag(Token::LeadingSpace); 3047 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) 3048 return true; // KeepWhitespaceMode 3049 3050 SkipIgnoredUnits: 3051 CurPtr = BufferPtr; 3052 3053 // If the next token is obviously a // or /* */ comment, skip it efficiently 3054 // too (without going through the big switch stmt). 3055 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() && 3056 LangOpts.LineComment && 3057 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) { 3058 if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine)) 3059 return true; // There is a token to return. 3060 goto SkipIgnoredUnits; 3061 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) { 3062 if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine)) 3063 return true; // There is a token to return. 3064 goto SkipIgnoredUnits; 3065 } else if (isHorizontalWhitespace(*CurPtr)) { 3066 goto SkipHorizontalWhitespace; 3067 } 3068 // We only saw whitespace, so just try again with this lexer. 3069 // (We manually eliminate the tail call to avoid recursion.) 3070 goto LexNextToken; 3071 3072 // C99 6.4.4.1: Integer Constants. 3073 // C99 6.4.4.2: Floating Constants. 3074 case '0': case '1': case '2': case '3': case '4': 3075 case '5': case '6': case '7': case '8': case '9': 3076 // Notify MIOpt that we read a non-whitespace/non-comment token. 3077 MIOpt.ReadToken(); 3078 return LexNumericConstant(Result, CurPtr); 3079 3080 case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal 3081 // Notify MIOpt that we read a non-whitespace/non-comment token. 3082 MIOpt.ReadToken(); 3083 3084 if (LangOpts.CPlusPlus11 || LangOpts.C11) { 3085 Char = getCharAndSize(CurPtr, SizeTmp); 3086 3087 // UTF-16 string literal 3088 if (Char == '"') 3089 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), 3090 tok::utf16_string_literal); 3091 3092 // UTF-16 character constant 3093 if (Char == '\'') 3094 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), 3095 tok::utf16_char_constant); 3096 3097 // UTF-16 raw string literal 3098 if (Char == 'R' && LangOpts.CPlusPlus11 && 3099 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') 3100 return LexRawStringLiteral(Result, 3101 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3102 SizeTmp2, Result), 3103 tok::utf16_string_literal); 3104 3105 if (Char == '8') { 3106 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2); 3107 3108 // UTF-8 string literal 3109 if (Char2 == '"') 3110 return LexStringLiteral(Result, 3111 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3112 SizeTmp2, Result), 3113 tok::utf8_string_literal); 3114 if (Char2 == '\'' && LangOpts.CPlusPlus1z) 3115 return LexCharConstant( 3116 Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3117 SizeTmp2, Result), 3118 tok::utf8_char_constant); 3119 3120 if (Char2 == 'R' && LangOpts.CPlusPlus11) { 3121 unsigned SizeTmp3; 3122 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3); 3123 // UTF-8 raw string literal 3124 if (Char3 == '"') { 3125 return LexRawStringLiteral(Result, 3126 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3127 SizeTmp2, Result), 3128 SizeTmp3, Result), 3129 tok::utf8_string_literal); 3130 } 3131 } 3132 } 3133 } 3134 3135 // treat u like the start of an identifier. 3136 return LexIdentifier(Result, CurPtr); 3137 3138 case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal 3139 // Notify MIOpt that we read a non-whitespace/non-comment token. 3140 MIOpt.ReadToken(); 3141 3142 if (LangOpts.CPlusPlus11 || LangOpts.C11) { 3143 Char = getCharAndSize(CurPtr, SizeTmp); 3144 3145 // UTF-32 string literal 3146 if (Char == '"') 3147 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), 3148 tok::utf32_string_literal); 3149 3150 // UTF-32 character constant 3151 if (Char == '\'') 3152 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), 3153 tok::utf32_char_constant); 3154 3155 // UTF-32 raw string literal 3156 if (Char == 'R' && LangOpts.CPlusPlus11 && 3157 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') 3158 return LexRawStringLiteral(Result, 3159 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3160 SizeTmp2, Result), 3161 tok::utf32_string_literal); 3162 } 3163 3164 // treat U like the start of an identifier. 3165 return LexIdentifier(Result, CurPtr); 3166 3167 case 'R': // Identifier or C++0x raw string literal 3168 // Notify MIOpt that we read a non-whitespace/non-comment token. 3169 MIOpt.ReadToken(); 3170 3171 if (LangOpts.CPlusPlus11) { 3172 Char = getCharAndSize(CurPtr, SizeTmp); 3173 3174 if (Char == '"') 3175 return LexRawStringLiteral(Result, 3176 ConsumeChar(CurPtr, SizeTmp, Result), 3177 tok::string_literal); 3178 } 3179 3180 // treat R like the start of an identifier. 3181 return LexIdentifier(Result, CurPtr); 3182 3183 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz"). 3184 // Notify MIOpt that we read a non-whitespace/non-comment token. 3185 MIOpt.ReadToken(); 3186 Char = getCharAndSize(CurPtr, SizeTmp); 3187 3188 // Wide string literal. 3189 if (Char == '"') 3190 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), 3191 tok::wide_string_literal); 3192 3193 // Wide raw string literal. 3194 if (LangOpts.CPlusPlus11 && Char == 'R' && 3195 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') 3196 return LexRawStringLiteral(Result, 3197 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3198 SizeTmp2, Result), 3199 tok::wide_string_literal); 3200 3201 // Wide character constant. 3202 if (Char == '\'') 3203 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), 3204 tok::wide_char_constant); 3205 // FALL THROUGH, treating L like the start of an identifier. 3206 3207 // C99 6.4.2: Identifiers. 3208 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': 3209 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N': 3210 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/ 3211 case 'V': case 'W': case 'X': case 'Y': case 'Z': 3212 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': 3213 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': 3214 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/ 3215 case 'v': case 'w': case 'x': case 'y': case 'z': 3216 case '_': 3217 // Notify MIOpt that we read a non-whitespace/non-comment token. 3218 MIOpt.ReadToken(); 3219 return LexIdentifier(Result, CurPtr); 3220 3221 case '$': // $ in identifiers. 3222 if (LangOpts.DollarIdents) { 3223 if (!isLexingRawMode()) 3224 Diag(CurPtr-1, diag::ext_dollar_in_identifier); 3225 // Notify MIOpt that we read a non-whitespace/non-comment token. 3226 MIOpt.ReadToken(); 3227 return LexIdentifier(Result, CurPtr); 3228 } 3229 3230 Kind = tok::unknown; 3231 break; 3232 3233 // C99 6.4.4: Character Constants. 3234 case '\'': 3235 // Notify MIOpt that we read a non-whitespace/non-comment token. 3236 MIOpt.ReadToken(); 3237 return LexCharConstant(Result, CurPtr, tok::char_constant); 3238 3239 // C99 6.4.5: String Literals. 3240 case '"': 3241 // Notify MIOpt that we read a non-whitespace/non-comment token. 3242 MIOpt.ReadToken(); 3243 return LexStringLiteral(Result, CurPtr, tok::string_literal); 3244 3245 // C99 6.4.6: Punctuators. 3246 case '?': 3247 Kind = tok::question; 3248 break; 3249 case '[': 3250 Kind = tok::l_square; 3251 break; 3252 case ']': 3253 Kind = tok::r_square; 3254 break; 3255 case '(': 3256 Kind = tok::l_paren; 3257 break; 3258 case ')': 3259 Kind = tok::r_paren; 3260 break; 3261 case '{': 3262 Kind = tok::l_brace; 3263 break; 3264 case '}': 3265 Kind = tok::r_brace; 3266 break; 3267 case '.': 3268 Char = getCharAndSize(CurPtr, SizeTmp); 3269 if (Char >= '0' && Char <= '9') { 3270 // Notify MIOpt that we read a non-whitespace/non-comment token. 3271 MIOpt.ReadToken(); 3272 3273 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result)); 3274 } else if (LangOpts.CPlusPlus && Char == '*') { 3275 Kind = tok::periodstar; 3276 CurPtr += SizeTmp; 3277 } else if (Char == '.' && 3278 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') { 3279 Kind = tok::ellipsis; 3280 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3281 SizeTmp2, Result); 3282 } else { 3283 Kind = tok::period; 3284 } 3285 break; 3286 case '&': 3287 Char = getCharAndSize(CurPtr, SizeTmp); 3288 if (Char == '&') { 3289 Kind = tok::ampamp; 3290 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3291 } else if (Char == '=') { 3292 Kind = tok::ampequal; 3293 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3294 } else { 3295 Kind = tok::amp; 3296 } 3297 break; 3298 case '*': 3299 if (getCharAndSize(CurPtr, SizeTmp) == '=') { 3300 Kind = tok::starequal; 3301 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3302 } else { 3303 Kind = tok::star; 3304 } 3305 break; 3306 case '+': 3307 Char = getCharAndSize(CurPtr, SizeTmp); 3308 if (Char == '+') { 3309 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3310 Kind = tok::plusplus; 3311 } else if (Char == '=') { 3312 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3313 Kind = tok::plusequal; 3314 } else { 3315 Kind = tok::plus; 3316 } 3317 break; 3318 case '-': 3319 Char = getCharAndSize(CurPtr, SizeTmp); 3320 if (Char == '-') { // -- 3321 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3322 Kind = tok::minusminus; 3323 } else if (Char == '>' && LangOpts.CPlusPlus && 3324 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->* 3325 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3326 SizeTmp2, Result); 3327 Kind = tok::arrowstar; 3328 } else if (Char == '>') { // -> 3329 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3330 Kind = tok::arrow; 3331 } else if (Char == '=') { // -= 3332 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3333 Kind = tok::minusequal; 3334 } else { 3335 Kind = tok::minus; 3336 } 3337 break; 3338 case '~': 3339 Kind = tok::tilde; 3340 break; 3341 case '!': 3342 if (getCharAndSize(CurPtr, SizeTmp) == '=') { 3343 Kind = tok::exclaimequal; 3344 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3345 } else { 3346 Kind = tok::exclaim; 3347 } 3348 break; 3349 case '/': 3350 // 6.4.9: Comments 3351 Char = getCharAndSize(CurPtr, SizeTmp); 3352 if (Char == '/') { // Line comment. 3353 // Even if Line comments are disabled (e.g. in C89 mode), we generally 3354 // want to lex this as a comment. There is one problem with this though, 3355 // that in one particular corner case, this can change the behavior of the 3356 // resultant program. For example, In "foo //**/ bar", C89 would lex 3357 // this as "foo / bar" and langauges with Line comments would lex it as 3358 // "foo". Check to see if the character after the second slash is a '*'. 3359 // If so, we will lex that as a "/" instead of the start of a comment. 3360 // However, we never do this if we are just preprocessing. 3361 bool TreatAsComment = LangOpts.LineComment && 3362 (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP); 3363 if (!TreatAsComment) 3364 if (!(PP && PP->isPreprocessedOutput())) 3365 TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*'; 3366 3367 if (TreatAsComment) { 3368 if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result), 3369 TokAtPhysicalStartOfLine)) 3370 return true; // There is a token to return. 3371 3372 // It is common for the tokens immediately after a // comment to be 3373 // whitespace (indentation for the next line). Instead of going through 3374 // the big switch, handle it efficiently now. 3375 goto SkipIgnoredUnits; 3376 } 3377 } 3378 3379 if (Char == '*') { // /**/ comment. 3380 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result), 3381 TokAtPhysicalStartOfLine)) 3382 return true; // There is a token to return. 3383 3384 // We only saw whitespace, so just try again with this lexer. 3385 // (We manually eliminate the tail call to avoid recursion.) 3386 goto LexNextToken; 3387 } 3388 3389 if (Char == '=') { 3390 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3391 Kind = tok::slashequal; 3392 } else { 3393 Kind = tok::slash; 3394 } 3395 break; 3396 case '%': 3397 Char = getCharAndSize(CurPtr, SizeTmp); 3398 if (Char == '=') { 3399 Kind = tok::percentequal; 3400 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3401 } else if (LangOpts.Digraphs && Char == '>') { 3402 Kind = tok::r_brace; // '%>' -> '}' 3403 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3404 } else if (LangOpts.Digraphs && Char == ':') { 3405 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3406 Char = getCharAndSize(CurPtr, SizeTmp); 3407 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') { 3408 Kind = tok::hashhash; // '%:%:' -> '##' 3409 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3410 SizeTmp2, Result); 3411 } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize 3412 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3413 if (!isLexingRawMode()) 3414 Diag(BufferPtr, diag::ext_charize_microsoft); 3415 Kind = tok::hashat; 3416 } else { // '%:' -> '#' 3417 // We parsed a # character. If this occurs at the start of the line, 3418 // it's actually the start of a preprocessing directive. Callback to 3419 // the preprocessor to handle it. 3420 // TODO: -fpreprocessed mode?? 3421 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer) 3422 goto HandleDirective; 3423 3424 Kind = tok::hash; 3425 } 3426 } else { 3427 Kind = tok::percent; 3428 } 3429 break; 3430 case '<': 3431 Char = getCharAndSize(CurPtr, SizeTmp); 3432 if (ParsingFilename) { 3433 return LexAngledStringLiteral(Result, CurPtr); 3434 } else if (Char == '<') { 3435 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2); 3436 if (After == '=') { 3437 Kind = tok::lesslessequal; 3438 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3439 SizeTmp2, Result); 3440 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) { 3441 // If this is actually a '<<<<<<<' version control conflict marker, 3442 // recognize it as such and recover nicely. 3443 goto LexNextToken; 3444 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) { 3445 // If this is '<<<<' and we're in a Perforce-style conflict marker, 3446 // ignore it. 3447 goto LexNextToken; 3448 } else if (LangOpts.CUDA && After == '<') { 3449 Kind = tok::lesslessless; 3450 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3451 SizeTmp2, Result); 3452 } else { 3453 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3454 Kind = tok::lessless; 3455 } 3456 } else if (Char == '=') { 3457 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3458 Kind = tok::lessequal; 3459 } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '[' 3460 if (LangOpts.CPlusPlus11 && 3461 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') { 3462 // C++0x [lex.pptoken]p3: 3463 // Otherwise, if the next three characters are <:: and the subsequent 3464 // character is neither : nor >, the < is treated as a preprocessor 3465 // token by itself and not as the first character of the alternative 3466 // token <:. 3467 unsigned SizeTmp3; 3468 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3); 3469 if (After != ':' && After != '>') { 3470 Kind = tok::less; 3471 if (!isLexingRawMode()) 3472 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon); 3473 break; 3474 } 3475 } 3476 3477 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3478 Kind = tok::l_square; 3479 } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{' 3480 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3481 Kind = tok::l_brace; 3482 } else { 3483 Kind = tok::less; 3484 } 3485 break; 3486 case '>': 3487 Char = getCharAndSize(CurPtr, SizeTmp); 3488 if (Char == '=') { 3489 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3490 Kind = tok::greaterequal; 3491 } else if (Char == '>') { 3492 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2); 3493 if (After == '=') { 3494 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3495 SizeTmp2, Result); 3496 Kind = tok::greatergreaterequal; 3497 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) { 3498 // If this is actually a '>>>>' conflict marker, recognize it as such 3499 // and recover nicely. 3500 goto LexNextToken; 3501 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) { 3502 // If this is '>>>>>>>' and we're in a conflict marker, ignore it. 3503 goto LexNextToken; 3504 } else if (LangOpts.CUDA && After == '>') { 3505 Kind = tok::greatergreatergreater; 3506 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3507 SizeTmp2, Result); 3508 } else { 3509 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3510 Kind = tok::greatergreater; 3511 } 3512 } else { 3513 Kind = tok::greater; 3514 } 3515 break; 3516 case '^': 3517 Char = getCharAndSize(CurPtr, SizeTmp); 3518 if (Char == '=') { 3519 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3520 Kind = tok::caretequal; 3521 } else if (LangOpts.OpenCL && Char == '^') { 3522 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3523 Kind = tok::caretcaret; 3524 } else { 3525 Kind = tok::caret; 3526 } 3527 break; 3528 case '|': 3529 Char = getCharAndSize(CurPtr, SizeTmp); 3530 if (Char == '=') { 3531 Kind = tok::pipeequal; 3532 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3533 } else if (Char == '|') { 3534 // If this is '|||||||' and we're in a conflict marker, ignore it. 3535 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1)) 3536 goto LexNextToken; 3537 Kind = tok::pipepipe; 3538 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3539 } else { 3540 Kind = tok::pipe; 3541 } 3542 break; 3543 case ':': 3544 Char = getCharAndSize(CurPtr, SizeTmp); 3545 if (LangOpts.Digraphs && Char == '>') { 3546 Kind = tok::r_square; // ':>' -> ']' 3547 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3548 } else if (LangOpts.CPlusPlus && Char == ':') { 3549 Kind = tok::coloncolon; 3550 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3551 } else { 3552 Kind = tok::colon; 3553 } 3554 break; 3555 case ';': 3556 Kind = tok::semi; 3557 break; 3558 case '=': 3559 Char = getCharAndSize(CurPtr, SizeTmp); 3560 if (Char == '=') { 3561 // If this is '====' and we're in a conflict marker, ignore it. 3562 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1)) 3563 goto LexNextToken; 3564 3565 Kind = tok::equalequal; 3566 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3567 } else { 3568 Kind = tok::equal; 3569 } 3570 break; 3571 case ',': 3572 Kind = tok::comma; 3573 break; 3574 case '#': 3575 Char = getCharAndSize(CurPtr, SizeTmp); 3576 if (Char == '#') { 3577 Kind = tok::hashhash; 3578 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3579 } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize 3580 Kind = tok::hashat; 3581 if (!isLexingRawMode()) 3582 Diag(BufferPtr, diag::ext_charize_microsoft); 3583 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3584 } else { 3585 // We parsed a # character. If this occurs at the start of the line, 3586 // it's actually the start of a preprocessing directive. Callback to 3587 // the preprocessor to handle it. 3588 // TODO: -fpreprocessed mode?? 3589 if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer) 3590 goto HandleDirective; 3591 3592 Kind = tok::hash; 3593 } 3594 break; 3595 3596 case '@': 3597 // Objective C support. 3598 if (CurPtr[-1] == '@' && LangOpts.ObjC1) 3599 Kind = tok::at; 3600 else 3601 Kind = tok::unknown; 3602 break; 3603 3604 // UCNs (C99 6.4.3, C++11 [lex.charset]p2) 3605 case '\\': 3606 if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) { 3607 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) { 3608 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) 3609 return true; // KeepWhitespaceMode 3610 3611 // We only saw whitespace, so just try again with this lexer. 3612 // (We manually eliminate the tail call to avoid recursion.) 3613 goto LexNextToken; 3614 } 3615 3616 return LexUnicode(Result, CodePoint, CurPtr); 3617 } 3618 3619 Kind = tok::unknown; 3620 break; 3621 3622 default: { 3623 if (isASCII(Char)) { 3624 Kind = tok::unknown; 3625 break; 3626 } 3627 3628 llvm::UTF32 CodePoint; 3629 3630 // We can't just reset CurPtr to BufferPtr because BufferPtr may point to 3631 // an escaped newline. 3632 --CurPtr; 3633 llvm::ConversionResult Status = 3634 llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr, 3635 (const llvm::UTF8 *)BufferEnd, 3636 &CodePoint, 3637 llvm::strictConversion); 3638 if (Status == llvm::conversionOK) { 3639 if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) { 3640 if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine)) 3641 return true; // KeepWhitespaceMode 3642 3643 // We only saw whitespace, so just try again with this lexer. 3644 // (We manually eliminate the tail call to avoid recursion.) 3645 goto LexNextToken; 3646 } 3647 return LexUnicode(Result, CodePoint, CurPtr); 3648 } 3649 3650 if (isLexingRawMode() || ParsingPreprocessorDirective || 3651 PP->isPreprocessedOutput()) { 3652 ++CurPtr; 3653 Kind = tok::unknown; 3654 break; 3655 } 3656 3657 // Non-ASCII characters tend to creep into source code unintentionally. 3658 // Instead of letting the parser complain about the unknown token, 3659 // just diagnose the invalid UTF-8, then drop the character. 3660 Diag(CurPtr, diag::err_invalid_utf8); 3661 3662 BufferPtr = CurPtr+1; 3663 // We're pretending the character didn't exist, so just try again with 3664 // this lexer. 3665 // (We manually eliminate the tail call to avoid recursion.) 3666 goto LexNextToken; 3667 } 3668 } 3669 3670 // Notify MIOpt that we read a non-whitespace/non-comment token. 3671 MIOpt.ReadToken(); 3672 3673 // Update the location of token as well as BufferPtr. 3674 FormTokenWithChars(Result, CurPtr, Kind); 3675 return true; 3676 3677 HandleDirective: 3678 // We parsed a # character and it's the start of a preprocessing directive. 3679 3680 FormTokenWithChars(Result, CurPtr, tok::hash); 3681 PP->HandleDirective(Result); 3682 3683 if (PP->hadModuleLoaderFatalFailure()) { 3684 // With a fatal failure in the module loader, we abort parsing. 3685 assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof"); 3686 return true; 3687 } 3688 3689 // We parsed the directive; lex a token with the new state. 3690 return false; 3691 } 3692