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