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