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