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