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