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