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