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