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