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