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 Features(PP.getLangOptions()) { 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 'LexRawToken'. 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 &features, 133 const char *BufStart, const char *BufPtr, const char *BufEnd) 134 : FileLoc(fileloc), Features(features) { 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 'LexRawToken'. 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 &features) 147 : FileLoc(SM.getLocForStartOfFile(FID)), Features(features) { 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 &Features, 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, Features)); 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 &Features, 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, Features); 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 &Features, 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, Features, 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 &Features) { 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, Features); 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 &Features) { 720 if (Loc.isInvalid()) 721 return SourceLocation(); 722 723 if (Loc.isMacroID()) { 724 if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, Features, &Loc)) 725 return SourceLocation(); // Points inside the macro expansion. 726 } 727 728 unsigned Len = Lexer::MeasureTokenLength(Loc, SM, Features); 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 /// \brief Accepts a range and returns a character range with file locations. 824 /// 825 /// Returns a null range if a part of the range resides inside a macro 826 /// expansion or the range does not reside on the same FileID. 827 CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range, 828 const SourceManager &SM, 829 const LangOptions &LangOpts) { 830 SourceLocation Begin = Range.getBegin(); 831 SourceLocation End = Range.getEnd(); 832 if (Begin.isInvalid() || End.isInvalid()) 833 return CharSourceRange(); 834 835 if (Begin.isFileID() && End.isFileID()) 836 return makeRangeFromFileLocs(Range, SM, LangOpts); 837 838 if (Begin.isMacroID() && End.isFileID()) { 839 if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin)) 840 return CharSourceRange(); 841 Range.setBegin(Begin); 842 return makeRangeFromFileLocs(Range, SM, LangOpts); 843 } 844 845 if (Begin.isFileID() && End.isMacroID()) { 846 if ((Range.isTokenRange() && !isAtEndOfMacroExpansion(End, SM, LangOpts, 847 &End)) || 848 (Range.isCharRange() && !isAtStartOfMacroExpansion(End, SM, LangOpts, 849 &End))) 850 return CharSourceRange(); 851 Range.setEnd(End); 852 return makeRangeFromFileLocs(Range, SM, LangOpts); 853 } 854 855 assert(Begin.isMacroID() && End.isMacroID()); 856 SourceLocation MacroBegin, MacroEnd; 857 if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) && 858 ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts, 859 &MacroEnd)) || 860 (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts, 861 &MacroEnd)))) { 862 Range.setBegin(MacroBegin); 863 Range.setEnd(MacroEnd); 864 return makeRangeFromFileLocs(Range, SM, LangOpts); 865 } 866 867 FileID FID; 868 unsigned BeginOffs; 869 llvm::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin); 870 if (FID.isInvalid()) 871 return CharSourceRange(); 872 873 unsigned EndOffs; 874 if (!SM.isInFileID(End, FID, &EndOffs) || 875 BeginOffs > EndOffs) 876 return CharSourceRange(); 877 878 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID); 879 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); 880 if (Expansion.isMacroArgExpansion() && 881 Expansion.getSpellingLoc().isFileID()) { 882 SourceLocation SpellLoc = Expansion.getSpellingLoc(); 883 Range.setBegin(SpellLoc.getLocWithOffset(BeginOffs)); 884 Range.setEnd(SpellLoc.getLocWithOffset(EndOffs)); 885 return makeRangeFromFileLocs(Range, SM, LangOpts); 886 } 887 888 return CharSourceRange(); 889 } 890 891 StringRef Lexer::getSourceText(CharSourceRange Range, 892 const SourceManager &SM, 893 const LangOptions &LangOpts, 894 bool *Invalid) { 895 Range = makeFileCharRange(Range, SM, LangOpts); 896 if (Range.isInvalid()) { 897 if (Invalid) *Invalid = true; 898 return StringRef(); 899 } 900 901 // Break down the source location. 902 std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin()); 903 if (beginInfo.first.isInvalid()) { 904 if (Invalid) *Invalid = true; 905 return StringRef(); 906 } 907 908 unsigned EndOffs; 909 if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) || 910 beginInfo.second > EndOffs) { 911 if (Invalid) *Invalid = true; 912 return StringRef(); 913 } 914 915 // Try to the load the file buffer. 916 bool invalidTemp = false; 917 StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp); 918 if (invalidTemp) { 919 if (Invalid) *Invalid = true; 920 return StringRef(); 921 } 922 923 if (Invalid) *Invalid = false; 924 return file.substr(beginInfo.second, EndOffs - beginInfo.second); 925 } 926 927 StringRef Lexer::getImmediateMacroName(SourceLocation Loc, 928 const SourceManager &SM, 929 const LangOptions &LangOpts) { 930 assert(Loc.isMacroID() && "Only reasonble to call this on macros"); 931 932 // Find the location of the immediate macro expansion. 933 while (1) { 934 FileID FID = SM.getFileID(Loc); 935 const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID); 936 const SrcMgr::ExpansionInfo &Expansion = E->getExpansion(); 937 Loc = Expansion.getExpansionLocStart(); 938 if (!Expansion.isMacroArgExpansion()) 939 break; 940 941 // For macro arguments we need to check that the argument did not come 942 // from an inner macro, e.g: "MAC1( MAC2(foo) )" 943 944 // Loc points to the argument id of the macro definition, move to the 945 // macro expansion. 946 Loc = SM.getImmediateExpansionRange(Loc).first; 947 SourceLocation SpellLoc = Expansion.getSpellingLoc(); 948 if (SpellLoc.isFileID()) 949 break; // No inner macro. 950 951 // If spelling location resides in the same FileID as macro expansion 952 // location, it means there is no inner macro. 953 FileID MacroFID = SM.getFileID(Loc); 954 if (SM.isInFileID(SpellLoc, MacroFID)) 955 break; 956 957 // Argument came from inner macro. 958 Loc = SpellLoc; 959 } 960 961 // Find the spelling location of the start of the non-argument expansion 962 // range. This is where the macro name was spelled in order to begin 963 // expanding this macro. 964 Loc = SM.getSpellingLoc(Loc); 965 966 // Dig out the buffer where the macro name was spelled and the extents of the 967 // name so that we can render it into the expansion note. 968 std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc); 969 unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts); 970 StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first); 971 return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength); 972 } 973 974 //===----------------------------------------------------------------------===// 975 // Character information. 976 //===----------------------------------------------------------------------===// 977 978 enum { 979 CHAR_HORZ_WS = 0x01, // ' ', '\t', '\f', '\v'. Note, no '\0' 980 CHAR_VERT_WS = 0x02, // '\r', '\n' 981 CHAR_LETTER = 0x04, // a-z,A-Z 982 CHAR_NUMBER = 0x08, // 0-9 983 CHAR_UNDER = 0x10, // _ 984 CHAR_PERIOD = 0x20, // . 985 CHAR_RAWDEL = 0x40 // {}[]#<>%:;?*+-/^&|~!=,"' 986 }; 987 988 // Statically initialize CharInfo table based on ASCII character set 989 // Reference: FreeBSD 7.2 /usr/share/misc/ascii 990 static const unsigned char CharInfo[256] = 991 { 992 // 0 NUL 1 SOH 2 STX 3 ETX 993 // 4 EOT 5 ENQ 6 ACK 7 BEL 994 0 , 0 , 0 , 0 , 995 0 , 0 , 0 , 0 , 996 // 8 BS 9 HT 10 NL 11 VT 997 //12 NP 13 CR 14 SO 15 SI 998 0 , CHAR_HORZ_WS, CHAR_VERT_WS, CHAR_HORZ_WS, 999 CHAR_HORZ_WS, CHAR_VERT_WS, 0 , 0 , 1000 //16 DLE 17 DC1 18 DC2 19 DC3 1001 //20 DC4 21 NAK 22 SYN 23 ETB 1002 0 , 0 , 0 , 0 , 1003 0 , 0 , 0 , 0 , 1004 //24 CAN 25 EM 26 SUB 27 ESC 1005 //28 FS 29 GS 30 RS 31 US 1006 0 , 0 , 0 , 0 , 1007 0 , 0 , 0 , 0 , 1008 //32 SP 33 ! 34 " 35 # 1009 //36 $ 37 % 38 & 39 ' 1010 CHAR_HORZ_WS, CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 1011 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 1012 //40 ( 41 ) 42 * 43 + 1013 //44 , 45 - 46 . 47 / 1014 0 , 0 , CHAR_RAWDEL , CHAR_RAWDEL , 1015 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_PERIOD , CHAR_RAWDEL , 1016 //48 0 49 1 50 2 51 3 1017 //52 4 53 5 54 6 55 7 1018 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , 1019 CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , CHAR_NUMBER , 1020 //56 8 57 9 58 : 59 ; 1021 //60 < 61 = 62 > 63 ? 1022 CHAR_NUMBER , CHAR_NUMBER , CHAR_RAWDEL , CHAR_RAWDEL , 1023 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 1024 //64 @ 65 A 66 B 67 C 1025 //68 D 69 E 70 F 71 G 1026 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1027 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1028 //72 H 73 I 74 J 75 K 1029 //76 L 77 M 78 N 79 O 1030 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1031 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1032 //80 P 81 Q 82 R 83 S 1033 //84 T 85 U 86 V 87 W 1034 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1035 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1036 //88 X 89 Y 90 Z 91 [ 1037 //92 \ 93 ] 94 ^ 95 _ 1038 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL , 1039 0 , CHAR_RAWDEL , CHAR_RAWDEL , CHAR_UNDER , 1040 //96 ` 97 a 98 b 99 c 1041 //100 d 101 e 102 f 103 g 1042 0 , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1043 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1044 //104 h 105 i 106 j 107 k 1045 //108 l 109 m 110 n 111 o 1046 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1047 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1048 //112 p 113 q 114 r 115 s 1049 //116 t 117 u 118 v 119 w 1050 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1051 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , 1052 //120 x 121 y 122 z 123 { 1053 //124 | 125 } 126 ~ 127 DEL 1054 CHAR_LETTER , CHAR_LETTER , CHAR_LETTER , CHAR_RAWDEL , 1055 CHAR_RAWDEL , CHAR_RAWDEL , CHAR_RAWDEL , 0 1056 }; 1057 1058 static void InitCharacterInfo() { 1059 static bool isInited = false; 1060 if (isInited) return; 1061 // check the statically-initialized CharInfo table 1062 assert(CHAR_HORZ_WS == CharInfo[(int)' ']); 1063 assert(CHAR_HORZ_WS == CharInfo[(int)'\t']); 1064 assert(CHAR_HORZ_WS == CharInfo[(int)'\f']); 1065 assert(CHAR_HORZ_WS == CharInfo[(int)'\v']); 1066 assert(CHAR_VERT_WS == CharInfo[(int)'\n']); 1067 assert(CHAR_VERT_WS == CharInfo[(int)'\r']); 1068 assert(CHAR_UNDER == CharInfo[(int)'_']); 1069 assert(CHAR_PERIOD == CharInfo[(int)'.']); 1070 for (unsigned i = 'a'; i <= 'z'; ++i) { 1071 assert(CHAR_LETTER == CharInfo[i]); 1072 assert(CHAR_LETTER == CharInfo[i+'A'-'a']); 1073 } 1074 for (unsigned i = '0'; i <= '9'; ++i) 1075 assert(CHAR_NUMBER == CharInfo[i]); 1076 1077 isInited = true; 1078 } 1079 1080 1081 /// isIdentifierBody - Return true if this is the body character of an 1082 /// identifier, which is [a-zA-Z0-9_]. 1083 static inline bool isIdentifierBody(unsigned char c) { 1084 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER)) ? true : false; 1085 } 1086 1087 /// isHorizontalWhitespace - Return true if this character is horizontal 1088 /// whitespace: ' ', '\t', '\f', '\v'. Note that this returns false for '\0'. 1089 static inline bool isHorizontalWhitespace(unsigned char c) { 1090 return (CharInfo[c] & CHAR_HORZ_WS) ? true : false; 1091 } 1092 1093 /// isVerticalWhitespace - Return true if this character is vertical 1094 /// whitespace: '\n', '\r'. Note that this returns false for '\0'. 1095 static inline bool isVerticalWhitespace(unsigned char c) { 1096 return (CharInfo[c] & CHAR_VERT_WS) ? true : false; 1097 } 1098 1099 /// isWhitespace - Return true if this character is horizontal or vertical 1100 /// whitespace: ' ', '\t', '\f', '\v', '\n', '\r'. Note that this returns false 1101 /// for '\0'. 1102 static inline bool isWhitespace(unsigned char c) { 1103 return (CharInfo[c] & (CHAR_HORZ_WS|CHAR_VERT_WS)) ? true : false; 1104 } 1105 1106 /// isNumberBody - Return true if this is the body character of an 1107 /// preprocessing number, which is [a-zA-Z0-9_.]. 1108 static inline bool isNumberBody(unsigned char c) { 1109 return (CharInfo[c] & (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD)) ? 1110 true : false; 1111 } 1112 1113 /// isRawStringDelimBody - Return true if this is the body character of a 1114 /// raw string delimiter. 1115 static inline bool isRawStringDelimBody(unsigned char c) { 1116 return (CharInfo[c] & 1117 (CHAR_LETTER|CHAR_NUMBER|CHAR_UNDER|CHAR_PERIOD|CHAR_RAWDEL)) ? 1118 true : false; 1119 } 1120 1121 1122 //===----------------------------------------------------------------------===// 1123 // Diagnostics forwarding code. 1124 //===----------------------------------------------------------------------===// 1125 1126 /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the 1127 /// lexer buffer was all expanded at a single point, perform the mapping. 1128 /// This is currently only used for _Pragma implementation, so it is the slow 1129 /// path of the hot getSourceLocation method. Do not allow it to be inlined. 1130 static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc( 1131 Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen); 1132 static SourceLocation GetMappedTokenLoc(Preprocessor &PP, 1133 SourceLocation FileLoc, 1134 unsigned CharNo, unsigned TokLen) { 1135 assert(FileLoc.isMacroID() && "Must be a macro expansion"); 1136 1137 // Otherwise, we're lexing "mapped tokens". This is used for things like 1138 // _Pragma handling. Combine the expansion location of FileLoc with the 1139 // spelling location. 1140 SourceManager &SM = PP.getSourceManager(); 1141 1142 // Create a new SLoc which is expanded from Expansion(FileLoc) but whose 1143 // characters come from spelling(FileLoc)+Offset. 1144 SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc); 1145 SpellingLoc = SpellingLoc.getLocWithOffset(CharNo); 1146 1147 // Figure out the expansion loc range, which is the range covered by the 1148 // original _Pragma(...) sequence. 1149 std::pair<SourceLocation,SourceLocation> II = 1150 SM.getImmediateExpansionRange(FileLoc); 1151 1152 return SM.createExpansionLoc(SpellingLoc, II.first, II.second, TokLen); 1153 } 1154 1155 /// getSourceLocation - Return a source location identifier for the specified 1156 /// offset in the current file. 1157 SourceLocation Lexer::getSourceLocation(const char *Loc, 1158 unsigned TokLen) const { 1159 assert(Loc >= BufferStart && Loc <= BufferEnd && 1160 "Location out of range for this buffer!"); 1161 1162 // In the normal case, we're just lexing from a simple file buffer, return 1163 // the file id from FileLoc with the offset specified. 1164 unsigned CharNo = Loc-BufferStart; 1165 if (FileLoc.isFileID()) 1166 return FileLoc.getLocWithOffset(CharNo); 1167 1168 // Otherwise, this is the _Pragma lexer case, which pretends that all of the 1169 // tokens are lexed from where the _Pragma was defined. 1170 assert(PP && "This doesn't work on raw lexers"); 1171 return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen); 1172 } 1173 1174 /// Diag - Forwarding function for diagnostics. This translate a source 1175 /// position in the current buffer into a SourceLocation object for rendering. 1176 DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const { 1177 return PP->Diag(getSourceLocation(Loc), DiagID); 1178 } 1179 1180 //===----------------------------------------------------------------------===// 1181 // Trigraph and Escaped Newline Handling Code. 1182 //===----------------------------------------------------------------------===// 1183 1184 /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair, 1185 /// return the decoded trigraph letter it corresponds to, or '\0' if nothing. 1186 static char GetTrigraphCharForLetter(char Letter) { 1187 switch (Letter) { 1188 default: return 0; 1189 case '=': return '#'; 1190 case ')': return ']'; 1191 case '(': return '['; 1192 case '!': return '|'; 1193 case '\'': return '^'; 1194 case '>': return '}'; 1195 case '/': return '\\'; 1196 case '<': return '{'; 1197 case '-': return '~'; 1198 } 1199 } 1200 1201 /// DecodeTrigraphChar - If the specified character is a legal trigraph when 1202 /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled, 1203 /// return the result character. Finally, emit a warning about trigraph use 1204 /// whether trigraphs are enabled or not. 1205 static char DecodeTrigraphChar(const char *CP, Lexer *L) { 1206 char Res = GetTrigraphCharForLetter(*CP); 1207 if (!Res || !L) return Res; 1208 1209 if (!L->getFeatures().Trigraphs) { 1210 if (!L->isLexingRawMode()) 1211 L->Diag(CP-2, diag::trigraph_ignored); 1212 return 0; 1213 } 1214 1215 if (!L->isLexingRawMode()) 1216 L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1); 1217 return Res; 1218 } 1219 1220 /// getEscapedNewLineSize - Return the size of the specified escaped newline, 1221 /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a 1222 /// trigraph equivalent on entry to this function. 1223 unsigned Lexer::getEscapedNewLineSize(const char *Ptr) { 1224 unsigned Size = 0; 1225 while (isWhitespace(Ptr[Size])) { 1226 ++Size; 1227 1228 if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r') 1229 continue; 1230 1231 // If this is a \r\n or \n\r, skip the other half. 1232 if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') && 1233 Ptr[Size-1] != Ptr[Size]) 1234 ++Size; 1235 1236 return Size; 1237 } 1238 1239 // Not an escaped newline, must be a \t or something else. 1240 return 0; 1241 } 1242 1243 /// SkipEscapedNewLines - If P points to an escaped newline (or a series of 1244 /// them), skip over them and return the first non-escaped-newline found, 1245 /// otherwise return P. 1246 const char *Lexer::SkipEscapedNewLines(const char *P) { 1247 while (1) { 1248 const char *AfterEscape; 1249 if (*P == '\\') { 1250 AfterEscape = P+1; 1251 } else if (*P == '?') { 1252 // If not a trigraph for escape, bail out. 1253 if (P[1] != '?' || P[2] != '/') 1254 return P; 1255 AfterEscape = P+3; 1256 } else { 1257 return P; 1258 } 1259 1260 unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape); 1261 if (NewLineSize == 0) return P; 1262 P = AfterEscape+NewLineSize; 1263 } 1264 } 1265 1266 /// \brief Checks that the given token is the first token that occurs after the 1267 /// given location (this excludes comments and whitespace). Returns the location 1268 /// immediately after the specified token. If the token is not found or the 1269 /// location is inside a macro, the returned source location will be invalid. 1270 SourceLocation Lexer::findLocationAfterToken(SourceLocation Loc, 1271 tok::TokenKind TKind, 1272 const SourceManager &SM, 1273 const LangOptions &LangOpts, 1274 bool SkipTrailingWhitespaceAndNewLine) { 1275 if (Loc.isMacroID()) { 1276 if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc)) 1277 return SourceLocation(); 1278 } 1279 Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts); 1280 1281 // Break down the source location. 1282 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc); 1283 1284 // Try to load the file buffer. 1285 bool InvalidTemp = false; 1286 llvm::StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp); 1287 if (InvalidTemp) 1288 return SourceLocation(); 1289 1290 const char *TokenBegin = File.data() + LocInfo.second; 1291 1292 // Lex from the start of the given location. 1293 Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(), 1294 TokenBegin, File.end()); 1295 // Find the token. 1296 Token Tok; 1297 lexer.LexFromRawLexer(Tok); 1298 if (Tok.isNot(TKind)) 1299 return SourceLocation(); 1300 SourceLocation TokenLoc = Tok.getLocation(); 1301 1302 // Calculate how much whitespace needs to be skipped if any. 1303 unsigned NumWhitespaceChars = 0; 1304 if (SkipTrailingWhitespaceAndNewLine) { 1305 const char *TokenEnd = SM.getCharacterData(TokenLoc) + 1306 Tok.getLength(); 1307 unsigned char C = *TokenEnd; 1308 while (isHorizontalWhitespace(C)) { 1309 C = *(++TokenEnd); 1310 NumWhitespaceChars++; 1311 } 1312 if (isVerticalWhitespace(C)) 1313 NumWhitespaceChars++; 1314 } 1315 1316 return TokenLoc.getLocWithOffset(Tok.getLength() + NumWhitespaceChars); 1317 } 1318 1319 /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer, 1320 /// get its size, and return it. This is tricky in several cases: 1321 /// 1. If currently at the start of a trigraph, we warn about the trigraph, 1322 /// then either return the trigraph (skipping 3 chars) or the '?', 1323 /// depending on whether trigraphs are enabled or not. 1324 /// 2. If this is an escaped newline (potentially with whitespace between 1325 /// the backslash and newline), implicitly skip the newline and return 1326 /// the char after it. 1327 /// 3. If this is a UCN, return it. FIXME: C++ UCN's? 1328 /// 1329 /// This handles the slow/uncommon case of the getCharAndSize method. Here we 1330 /// know that we can accumulate into Size, and that we have already incremented 1331 /// Ptr by Size bytes. 1332 /// 1333 /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should 1334 /// be updated to match. 1335 /// 1336 char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size, 1337 Token *Tok) { 1338 // If we have a slash, look for an escaped newline. 1339 if (Ptr[0] == '\\') { 1340 ++Size; 1341 ++Ptr; 1342 Slash: 1343 // Common case, backslash-char where the char is not whitespace. 1344 if (!isWhitespace(Ptr[0])) return '\\'; 1345 1346 // See if we have optional whitespace characters between the slash and 1347 // newline. 1348 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { 1349 // Remember that this token needs to be cleaned. 1350 if (Tok) Tok->setFlag(Token::NeedsCleaning); 1351 1352 // Warn if there was whitespace between the backslash and newline. 1353 if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode()) 1354 Diag(Ptr, diag::backslash_newline_space); 1355 1356 // Found backslash<whitespace><newline>. Parse the char after it. 1357 Size += EscapedNewLineSize; 1358 Ptr += EscapedNewLineSize; 1359 1360 // If the char that we finally got was a \n, then we must have had 1361 // something like \<newline><newline>. We don't want to consume the 1362 // second newline. 1363 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0') 1364 return ' '; 1365 1366 // Use slow version to accumulate a correct size field. 1367 return getCharAndSizeSlow(Ptr, Size, Tok); 1368 } 1369 1370 // Otherwise, this is not an escaped newline, just return the slash. 1371 return '\\'; 1372 } 1373 1374 // If this is a trigraph, process it. 1375 if (Ptr[0] == '?' && Ptr[1] == '?') { 1376 // If this is actually a legal trigraph (not something like "??x"), emit 1377 // a trigraph warning. If so, and if trigraphs are enabled, return it. 1378 if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : 0)) { 1379 // Remember that this token needs to be cleaned. 1380 if (Tok) Tok->setFlag(Token::NeedsCleaning); 1381 1382 Ptr += 3; 1383 Size += 3; 1384 if (C == '\\') goto Slash; 1385 return C; 1386 } 1387 } 1388 1389 // If this is neither, return a single character. 1390 ++Size; 1391 return *Ptr; 1392 } 1393 1394 1395 /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the 1396 /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size, 1397 /// and that we have already incremented Ptr by Size bytes. 1398 /// 1399 /// NOTE: When this method is updated, getCharAndSizeSlow (above) should 1400 /// be updated to match. 1401 char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size, 1402 const LangOptions &Features) { 1403 // If we have a slash, look for an escaped newline. 1404 if (Ptr[0] == '\\') { 1405 ++Size; 1406 ++Ptr; 1407 Slash: 1408 // Common case, backslash-char where the char is not whitespace. 1409 if (!isWhitespace(Ptr[0])) return '\\'; 1410 1411 // See if we have optional whitespace characters followed by a newline. 1412 if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) { 1413 // Found backslash<whitespace><newline>. Parse the char after it. 1414 Size += EscapedNewLineSize; 1415 Ptr += EscapedNewLineSize; 1416 1417 // If the char that we finally got was a \n, then we must have had 1418 // something like \<newline><newline>. We don't want to consume the 1419 // second newline. 1420 if (*Ptr == '\n' || *Ptr == '\r' || *Ptr == '\0') 1421 return ' '; 1422 1423 // Use slow version to accumulate a correct size field. 1424 return getCharAndSizeSlowNoWarn(Ptr, Size, Features); 1425 } 1426 1427 // Otherwise, this is not an escaped newline, just return the slash. 1428 return '\\'; 1429 } 1430 1431 // If this is a trigraph, process it. 1432 if (Features.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') { 1433 // If this is actually a legal trigraph (not something like "??x"), return 1434 // it. 1435 if (char C = GetTrigraphCharForLetter(Ptr[2])) { 1436 Ptr += 3; 1437 Size += 3; 1438 if (C == '\\') goto Slash; 1439 return C; 1440 } 1441 } 1442 1443 // If this is neither, return a single character. 1444 ++Size; 1445 return *Ptr; 1446 } 1447 1448 //===----------------------------------------------------------------------===// 1449 // Helper methods for lexing. 1450 //===----------------------------------------------------------------------===// 1451 1452 /// \brief Routine that indiscriminately skips bytes in the source file. 1453 void Lexer::SkipBytes(unsigned Bytes, bool StartOfLine) { 1454 BufferPtr += Bytes; 1455 if (BufferPtr > BufferEnd) 1456 BufferPtr = BufferEnd; 1457 IsAtStartOfLine = StartOfLine; 1458 } 1459 1460 void Lexer::LexIdentifier(Token &Result, const char *CurPtr) { 1461 // Match [_A-Za-z0-9]*, we have already matched [_A-Za-z$] 1462 unsigned Size; 1463 unsigned char C = *CurPtr++; 1464 while (isIdentifierBody(C)) 1465 C = *CurPtr++; 1466 1467 --CurPtr; // Back up over the skipped character. 1468 1469 // Fast path, no $,\,? in identifier found. '\' might be an escaped newline 1470 // or UCN, and ? might be a trigraph for '\', an escaped newline or UCN. 1471 // FIXME: UCNs. 1472 // 1473 // TODO: Could merge these checks into a CharInfo flag to make the comparison 1474 // cheaper 1475 if (C != '\\' && C != '?' && (C != '$' || !Features.DollarIdents)) { 1476 FinishIdentifier: 1477 const char *IdStart = BufferPtr; 1478 FormTokenWithChars(Result, CurPtr, tok::raw_identifier); 1479 Result.setRawIdentifierData(IdStart); 1480 1481 // If we are in raw mode, return this identifier raw. There is no need to 1482 // look up identifier information or attempt to macro expand it. 1483 if (LexingRawMode) 1484 return; 1485 1486 // Fill in Result.IdentifierInfo and update the token kind, 1487 // looking up the identifier in the identifier table. 1488 IdentifierInfo *II = PP->LookUpIdentifierInfo(Result); 1489 1490 // Finally, now that we know we have an identifier, pass this off to the 1491 // preprocessor, which may macro expand it or something. 1492 if (II->isHandleIdentifierCase()) 1493 PP->HandleIdentifier(Result); 1494 1495 return; 1496 } 1497 1498 // Otherwise, $,\,? in identifier found. Enter slower path. 1499 1500 C = getCharAndSize(CurPtr, Size); 1501 while (1) { 1502 if (C == '$') { 1503 // If we hit a $ and they are not supported in identifiers, we are done. 1504 if (!Features.DollarIdents) goto FinishIdentifier; 1505 1506 // Otherwise, emit a diagnostic and continue. 1507 if (!isLexingRawMode()) 1508 Diag(CurPtr, diag::ext_dollar_in_identifier); 1509 CurPtr = ConsumeChar(CurPtr, Size, Result); 1510 C = getCharAndSize(CurPtr, Size); 1511 continue; 1512 } else if (!isIdentifierBody(C)) { // FIXME: UCNs. 1513 // Found end of identifier. 1514 goto FinishIdentifier; 1515 } 1516 1517 // Otherwise, this character is good, consume it. 1518 CurPtr = ConsumeChar(CurPtr, Size, Result); 1519 1520 C = getCharAndSize(CurPtr, Size); 1521 while (isIdentifierBody(C)) { // FIXME: UCNs. 1522 CurPtr = ConsumeChar(CurPtr, Size, Result); 1523 C = getCharAndSize(CurPtr, Size); 1524 } 1525 } 1526 } 1527 1528 /// isHexaLiteral - Return true if Start points to a hex constant. 1529 /// in microsoft mode (where this is supposed to be several different tokens). 1530 static bool isHexaLiteral(const char *Start, const LangOptions &Features) { 1531 unsigned Size; 1532 char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, Features); 1533 if (C1 != '0') 1534 return false; 1535 char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, Features); 1536 return (C2 == 'x' || C2 == 'X'); 1537 } 1538 1539 /// LexNumericConstant - Lex the remainder of a integer or floating point 1540 /// constant. From[-1] is the first character lexed. Return the end of the 1541 /// constant. 1542 void Lexer::LexNumericConstant(Token &Result, const char *CurPtr) { 1543 unsigned Size; 1544 char C = getCharAndSize(CurPtr, Size); 1545 char PrevCh = 0; 1546 while (isNumberBody(C)) { // FIXME: UCNs? 1547 CurPtr = ConsumeChar(CurPtr, Size, Result); 1548 PrevCh = C; 1549 C = getCharAndSize(CurPtr, Size); 1550 } 1551 1552 // If we fell out, check for a sign, due to 1e+12. If we have one, continue. 1553 if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) { 1554 // If we are in Microsoft mode, don't continue if the constant is hex. 1555 // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1 1556 if (!Features.MicrosoftExt || !isHexaLiteral(BufferPtr, Features)) 1557 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); 1558 } 1559 1560 // If we have a hex FP constant, continue. 1561 if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) 1562 return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result)); 1563 1564 // Update the location of token as well as BufferPtr. 1565 const char *TokStart = BufferPtr; 1566 FormTokenWithChars(Result, CurPtr, tok::numeric_constant); 1567 Result.setLiteralData(TokStart); 1568 } 1569 1570 /// LexStringLiteral - Lex the remainder of a string literal, after having lexed 1571 /// either " or L" or u8" or u" or U". 1572 void Lexer::LexStringLiteral(Token &Result, const char *CurPtr, 1573 tok::TokenKind Kind) { 1574 const char *NulCharacter = 0; // Does this string contain the \0 character? 1575 1576 if (!isLexingRawMode() && 1577 (Kind == tok::utf8_string_literal || 1578 Kind == tok::utf16_string_literal || 1579 Kind == tok::utf32_string_literal)) 1580 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal); 1581 1582 char C = getAndAdvanceChar(CurPtr, Result); 1583 while (C != '"') { 1584 // Skip escaped characters. Escaped newlines will already be processed by 1585 // getAndAdvanceChar. 1586 if (C == '\\') 1587 C = getAndAdvanceChar(CurPtr, Result); 1588 1589 if (C == '\n' || C == '\r' || // Newline. 1590 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. 1591 if (!isLexingRawMode() && !Features.AsmPreprocessor) 1592 Diag(BufferPtr, diag::warn_unterminated_string); 1593 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1594 return; 1595 } 1596 1597 if (C == 0) { 1598 if (isCodeCompletionPoint(CurPtr-1)) { 1599 PP->CodeCompleteNaturalLanguage(); 1600 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1601 return cutOffLexing(); 1602 } 1603 1604 NulCharacter = CurPtr-1; 1605 } 1606 C = getAndAdvanceChar(CurPtr, Result); 1607 } 1608 1609 // If a nul character existed in the string, warn about it. 1610 if (NulCharacter && !isLexingRawMode()) 1611 Diag(NulCharacter, diag::null_in_string); 1612 1613 // Update the location of the token as well as the BufferPtr instance var. 1614 const char *TokStart = BufferPtr; 1615 FormTokenWithChars(Result, CurPtr, Kind); 1616 Result.setLiteralData(TokStart); 1617 } 1618 1619 /// LexRawStringLiteral - Lex the remainder of a raw string literal, after 1620 /// having lexed R", LR", u8R", uR", or UR". 1621 void Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr, 1622 tok::TokenKind Kind) { 1623 // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3: 1624 // Between the initial and final double quote characters of the raw string, 1625 // any transformations performed in phases 1 and 2 (trigraphs, 1626 // universal-character-names, and line splicing) are reverted. 1627 1628 if (!isLexingRawMode()) 1629 Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal); 1630 1631 unsigned PrefixLen = 0; 1632 1633 while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen])) 1634 ++PrefixLen; 1635 1636 // If the last character was not a '(', then we didn't lex a valid delimiter. 1637 if (CurPtr[PrefixLen] != '(') { 1638 if (!isLexingRawMode()) { 1639 const char *PrefixEnd = &CurPtr[PrefixLen]; 1640 if (PrefixLen == 16) { 1641 Diag(PrefixEnd, diag::err_raw_delim_too_long); 1642 } else { 1643 Diag(PrefixEnd, diag::err_invalid_char_raw_delim) 1644 << StringRef(PrefixEnd, 1); 1645 } 1646 } 1647 1648 // Search for the next '"' in hopes of salvaging the lexer. Unfortunately, 1649 // it's possible the '"' was intended to be part of the raw string, but 1650 // there's not much we can do about that. 1651 while (1) { 1652 char C = *CurPtr++; 1653 1654 if (C == '"') 1655 break; 1656 if (C == 0 && CurPtr-1 == BufferEnd) { 1657 --CurPtr; 1658 break; 1659 } 1660 } 1661 1662 FormTokenWithChars(Result, CurPtr, tok::unknown); 1663 return; 1664 } 1665 1666 // Save prefix and move CurPtr past it 1667 const char *Prefix = CurPtr; 1668 CurPtr += PrefixLen + 1; // skip over prefix and '(' 1669 1670 while (1) { 1671 char C = *CurPtr++; 1672 1673 if (C == ')') { 1674 // Check for prefix match and closing quote. 1675 if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') { 1676 CurPtr += PrefixLen + 1; // skip over prefix and '"' 1677 break; 1678 } 1679 } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file. 1680 if (!isLexingRawMode()) 1681 Diag(BufferPtr, diag::err_unterminated_raw_string) 1682 << StringRef(Prefix, PrefixLen); 1683 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1684 return; 1685 } 1686 } 1687 1688 // Update the location of token as well as BufferPtr. 1689 const char *TokStart = BufferPtr; 1690 FormTokenWithChars(Result, CurPtr, Kind); 1691 Result.setLiteralData(TokStart); 1692 } 1693 1694 /// LexAngledStringLiteral - Lex the remainder of an angled string literal, 1695 /// after having lexed the '<' character. This is used for #include filenames. 1696 void Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) { 1697 const char *NulCharacter = 0; // Does this string contain the \0 character? 1698 const char *AfterLessPos = CurPtr; 1699 char C = getAndAdvanceChar(CurPtr, Result); 1700 while (C != '>') { 1701 // Skip escaped characters. 1702 if (C == '\\') { 1703 // Skip the escaped character. 1704 C = getAndAdvanceChar(CurPtr, Result); 1705 } else if (C == '\n' || C == '\r' || // Newline. 1706 (C == 0 && (CurPtr-1 == BufferEnd || // End of file. 1707 isCodeCompletionPoint(CurPtr-1)))) { 1708 // If the filename is unterminated, then it must just be a lone < 1709 // character. Return this as such. 1710 FormTokenWithChars(Result, AfterLessPos, tok::less); 1711 return; 1712 } else if (C == 0) { 1713 NulCharacter = CurPtr-1; 1714 } 1715 C = getAndAdvanceChar(CurPtr, Result); 1716 } 1717 1718 // If a nul character existed in the string, warn about it. 1719 if (NulCharacter && !isLexingRawMode()) 1720 Diag(NulCharacter, diag::null_in_string); 1721 1722 // Update the location of token as well as BufferPtr. 1723 const char *TokStart = BufferPtr; 1724 FormTokenWithChars(Result, CurPtr, tok::angle_string_literal); 1725 Result.setLiteralData(TokStart); 1726 } 1727 1728 1729 /// LexCharConstant - Lex the remainder of a character constant, after having 1730 /// lexed either ' or L' or u' or U'. 1731 void Lexer::LexCharConstant(Token &Result, const char *CurPtr, 1732 tok::TokenKind Kind) { 1733 const char *NulCharacter = 0; // Does this character contain the \0 character? 1734 1735 if (!isLexingRawMode() && 1736 (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)) 1737 Diag(BufferPtr, diag::warn_cxx98_compat_unicode_literal); 1738 1739 char C = getAndAdvanceChar(CurPtr, Result); 1740 if (C == '\'') { 1741 if (!isLexingRawMode() && !Features.AsmPreprocessor) 1742 Diag(BufferPtr, diag::err_empty_character); 1743 FormTokenWithChars(Result, CurPtr, tok::unknown); 1744 return; 1745 } 1746 1747 while (C != '\'') { 1748 // Skip escaped characters. 1749 if (C == '\\') { 1750 // Skip the escaped character. 1751 // FIXME: UCN's 1752 C = getAndAdvanceChar(CurPtr, Result); 1753 } else if (C == '\n' || C == '\r' || // Newline. 1754 (C == 0 && CurPtr-1 == BufferEnd)) { // End of file. 1755 if (!isLexingRawMode() && !Features.AsmPreprocessor) 1756 Diag(BufferPtr, diag::warn_unterminated_char); 1757 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1758 return; 1759 } else if (C == 0) { 1760 if (isCodeCompletionPoint(CurPtr-1)) { 1761 PP->CodeCompleteNaturalLanguage(); 1762 FormTokenWithChars(Result, CurPtr-1, tok::unknown); 1763 return cutOffLexing(); 1764 } 1765 1766 NulCharacter = CurPtr-1; 1767 } 1768 C = getAndAdvanceChar(CurPtr, Result); 1769 } 1770 1771 // If a nul character existed in the character, warn about it. 1772 if (NulCharacter && !isLexingRawMode()) 1773 Diag(NulCharacter, diag::null_in_char); 1774 1775 // Update the location of token as well as BufferPtr. 1776 const char *TokStart = BufferPtr; 1777 FormTokenWithChars(Result, CurPtr, Kind); 1778 Result.setLiteralData(TokStart); 1779 } 1780 1781 /// SkipWhitespace - Efficiently skip over a series of whitespace characters. 1782 /// Update BufferPtr to point to the next non-whitespace character and return. 1783 /// 1784 /// This method forms a token and returns true if KeepWhitespaceMode is enabled. 1785 /// 1786 bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr) { 1787 // Whitespace - Skip it, then return the token after the whitespace. 1788 unsigned char Char = *CurPtr; // Skip consequtive spaces efficiently. 1789 while (1) { 1790 // Skip horizontal whitespace very aggressively. 1791 while (isHorizontalWhitespace(Char)) 1792 Char = *++CurPtr; 1793 1794 // Otherwise if we have something other than whitespace, we're done. 1795 if (Char != '\n' && Char != '\r') 1796 break; 1797 1798 if (ParsingPreprocessorDirective) { 1799 // End of preprocessor directive line, let LexTokenInternal handle this. 1800 BufferPtr = CurPtr; 1801 return false; 1802 } 1803 1804 // ok, but handle newline. 1805 // The returned token is at the start of the line. 1806 Result.setFlag(Token::StartOfLine); 1807 // No leading whitespace seen so far. 1808 Result.clearFlag(Token::LeadingSpace); 1809 Char = *++CurPtr; 1810 } 1811 1812 // If this isn't immediately after a newline, there is leading space. 1813 char PrevChar = CurPtr[-1]; 1814 if (PrevChar != '\n' && PrevChar != '\r') 1815 Result.setFlag(Token::LeadingSpace); 1816 1817 // If the client wants us to return whitespace, return it now. 1818 if (isKeepWhitespaceMode()) { 1819 FormTokenWithChars(Result, CurPtr, tok::unknown); 1820 return true; 1821 } 1822 1823 BufferPtr = CurPtr; 1824 return false; 1825 } 1826 1827 // SkipBCPLComment - We have just read the // characters from input. Skip until 1828 // we find the newline character thats terminate the comment. Then update 1829 /// BufferPtr and return. 1830 /// 1831 /// If we're in KeepCommentMode or any CommentHandler has inserted 1832 /// some tokens, this will store the first token and return true. 1833 bool Lexer::SkipBCPLComment(Token &Result, const char *CurPtr) { 1834 // If BCPL comments aren't explicitly enabled for this language, emit an 1835 // extension warning. 1836 if (!Features.BCPLComment && !isLexingRawMode()) { 1837 Diag(BufferPtr, diag::ext_bcpl_comment); 1838 1839 // Mark them enabled so we only emit one warning for this translation 1840 // unit. 1841 Features.BCPLComment = true; 1842 } 1843 1844 // Scan over the body of the comment. The common case, when scanning, is that 1845 // the comment contains normal ascii characters with nothing interesting in 1846 // them. As such, optimize for this case with the inner loop. 1847 char C; 1848 do { 1849 C = *CurPtr; 1850 // Skip over characters in the fast loop. 1851 while (C != 0 && // Potentially EOF. 1852 C != '\n' && C != '\r') // Newline or DOS-style newline. 1853 C = *++CurPtr; 1854 1855 const char *NextLine = CurPtr; 1856 if (C != 0) { 1857 // We found a newline, see if it's escaped. 1858 const char *EscapePtr = CurPtr-1; 1859 while (isHorizontalWhitespace(*EscapePtr)) // Skip whitespace. 1860 --EscapePtr; 1861 1862 if (*EscapePtr == '\\') // Escaped newline. 1863 CurPtr = EscapePtr; 1864 else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' && 1865 EscapePtr[-2] == '?') // Trigraph-escaped newline. 1866 CurPtr = EscapePtr-2; 1867 else 1868 break; // This is a newline, we're done. 1869 1870 C = *CurPtr; 1871 } 1872 1873 // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to 1874 // properly decode the character. Read it in raw mode to avoid emitting 1875 // diagnostics about things like trigraphs. If we see an escaped newline, 1876 // we'll handle it below. 1877 const char *OldPtr = CurPtr; 1878 bool OldRawMode = isLexingRawMode(); 1879 LexingRawMode = true; 1880 C = getAndAdvanceChar(CurPtr, Result); 1881 LexingRawMode = OldRawMode; 1882 1883 // If we only read only one character, then no special handling is needed. 1884 // We're done and can skip forward to the newline. 1885 if (C != 0 && CurPtr == OldPtr+1) { 1886 CurPtr = NextLine; 1887 break; 1888 } 1889 1890 // If we read multiple characters, and one of those characters was a \r or 1891 // \n, then we had an escaped newline within the comment. Emit diagnostic 1892 // unless the next line is also a // comment. 1893 if (CurPtr != OldPtr+1 && C != '/' && CurPtr[0] != '/') { 1894 for (; OldPtr != CurPtr; ++OldPtr) 1895 if (OldPtr[0] == '\n' || OldPtr[0] == '\r') { 1896 // Okay, we found a // comment that ends in a newline, if the next 1897 // line is also a // comment, but has spaces, don't emit a diagnostic. 1898 if (isWhitespace(C)) { 1899 const char *ForwardPtr = CurPtr; 1900 while (isWhitespace(*ForwardPtr)) // Skip whitespace. 1901 ++ForwardPtr; 1902 if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/') 1903 break; 1904 } 1905 1906 if (!isLexingRawMode()) 1907 Diag(OldPtr-1, diag::ext_multi_line_bcpl_comment); 1908 break; 1909 } 1910 } 1911 1912 if (CurPtr == BufferEnd+1) { 1913 --CurPtr; 1914 break; 1915 } 1916 1917 if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) { 1918 PP->CodeCompleteNaturalLanguage(); 1919 cutOffLexing(); 1920 return false; 1921 } 1922 1923 } while (C != '\n' && C != '\r'); 1924 1925 // Found but did not consume the newline. Notify comment handlers about the 1926 // comment unless we're in a #if 0 block. 1927 if (PP && !isLexingRawMode() && 1928 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr), 1929 getSourceLocation(CurPtr)))) { 1930 BufferPtr = CurPtr; 1931 return true; // A token has to be returned. 1932 } 1933 1934 // If we are returning comments as tokens, return this comment as a token. 1935 if (inKeepCommentMode()) 1936 return SaveBCPLComment(Result, CurPtr); 1937 1938 // If we are inside a preprocessor directive and we see the end of line, 1939 // return immediately, so that the lexer can return this as an EOD token. 1940 if (ParsingPreprocessorDirective || CurPtr == BufferEnd) { 1941 BufferPtr = CurPtr; 1942 return false; 1943 } 1944 1945 // Otherwise, eat the \n character. We don't care if this is a \n\r or 1946 // \r\n sequence. This is an efficiency hack (because we know the \n can't 1947 // contribute to another token), it isn't needed for correctness. Note that 1948 // this is ok even in KeepWhitespaceMode, because we would have returned the 1949 /// comment above in that mode. 1950 ++CurPtr; 1951 1952 // The next returned token is at the start of the line. 1953 Result.setFlag(Token::StartOfLine); 1954 // No leading whitespace seen so far. 1955 Result.clearFlag(Token::LeadingSpace); 1956 BufferPtr = CurPtr; 1957 return false; 1958 } 1959 1960 /// SaveBCPLComment - If in save-comment mode, package up this BCPL comment in 1961 /// an appropriate way and return it. 1962 bool Lexer::SaveBCPLComment(Token &Result, const char *CurPtr) { 1963 // If we're not in a preprocessor directive, just return the // comment 1964 // directly. 1965 FormTokenWithChars(Result, CurPtr, tok::comment); 1966 1967 if (!ParsingPreprocessorDirective) 1968 return true; 1969 1970 // If this BCPL-style comment is in a macro definition, transmogrify it into 1971 // a C-style block comment. 1972 bool Invalid = false; 1973 std::string Spelling = PP->getSpelling(Result, &Invalid); 1974 if (Invalid) 1975 return true; 1976 1977 assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not bcpl comment?"); 1978 Spelling[1] = '*'; // Change prefix to "/*". 1979 Spelling += "*/"; // add suffix. 1980 1981 Result.setKind(tok::comment); 1982 PP->CreateString(&Spelling[0], Spelling.size(), Result, 1983 Result.getLocation(), Result.getLocation()); 1984 return true; 1985 } 1986 1987 /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline 1988 /// character (either \n or \r) is part of an escaped newline sequence. Issue a 1989 /// diagnostic if so. We know that the newline is inside of a block comment. 1990 static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr, 1991 Lexer *L) { 1992 assert(CurPtr[0] == '\n' || CurPtr[0] == '\r'); 1993 1994 // Back up off the newline. 1995 --CurPtr; 1996 1997 // If this is a two-character newline sequence, skip the other character. 1998 if (CurPtr[0] == '\n' || CurPtr[0] == '\r') { 1999 // \n\n or \r\r -> not escaped newline. 2000 if (CurPtr[0] == CurPtr[1]) 2001 return false; 2002 // \n\r or \r\n -> skip the newline. 2003 --CurPtr; 2004 } 2005 2006 // If we have horizontal whitespace, skip over it. We allow whitespace 2007 // between the slash and newline. 2008 bool HasSpace = false; 2009 while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) { 2010 --CurPtr; 2011 HasSpace = true; 2012 } 2013 2014 // If we have a slash, we know this is an escaped newline. 2015 if (*CurPtr == '\\') { 2016 if (CurPtr[-1] != '*') return false; 2017 } else { 2018 // It isn't a slash, is it the ?? / trigraph? 2019 if (CurPtr[0] != '/' || CurPtr[-1] != '?' || CurPtr[-2] != '?' || 2020 CurPtr[-3] != '*') 2021 return false; 2022 2023 // This is the trigraph ending the comment. Emit a stern warning! 2024 CurPtr -= 2; 2025 2026 // If no trigraphs are enabled, warn that we ignored this trigraph and 2027 // ignore this * character. 2028 if (!L->getFeatures().Trigraphs) { 2029 if (!L->isLexingRawMode()) 2030 L->Diag(CurPtr, diag::trigraph_ignored_block_comment); 2031 return false; 2032 } 2033 if (!L->isLexingRawMode()) 2034 L->Diag(CurPtr, diag::trigraph_ends_block_comment); 2035 } 2036 2037 // Warn about having an escaped newline between the */ characters. 2038 if (!L->isLexingRawMode()) 2039 L->Diag(CurPtr, diag::escaped_newline_block_comment_end); 2040 2041 // If there was space between the backslash and newline, warn about it. 2042 if (HasSpace && !L->isLexingRawMode()) 2043 L->Diag(CurPtr, diag::backslash_newline_space); 2044 2045 return true; 2046 } 2047 2048 #ifdef __SSE2__ 2049 #include <emmintrin.h> 2050 #elif __ALTIVEC__ 2051 #include <altivec.h> 2052 #undef bool 2053 #endif 2054 2055 /// SkipBlockComment - We have just read the /* characters from input. Read 2056 /// until we find the */ characters that terminate the comment. Note that we 2057 /// don't bother decoding trigraphs or escaped newlines in block comments, 2058 /// because they cannot cause the comment to end. The only thing that can 2059 /// happen is the comment could end with an escaped newline between the */ end 2060 /// of comment. 2061 /// 2062 /// If we're in KeepCommentMode or any CommentHandler has inserted 2063 /// some tokens, this will store the first token and return true. 2064 bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr) { 2065 // Scan one character past where we should, looking for a '/' character. Once 2066 // we find it, check to see if it was preceded by a *. This common 2067 // optimization helps people who like to put a lot of * characters in their 2068 // comments. 2069 2070 // The first character we get with newlines and trigraphs skipped to handle 2071 // the degenerate /*/ case below correctly if the * has an escaped newline 2072 // after it. 2073 unsigned CharSize; 2074 unsigned char C = getCharAndSize(CurPtr, CharSize); 2075 CurPtr += CharSize; 2076 if (C == 0 && CurPtr == BufferEnd+1) { 2077 if (!isLexingRawMode()) 2078 Diag(BufferPtr, diag::err_unterminated_block_comment); 2079 --CurPtr; 2080 2081 // KeepWhitespaceMode should return this broken comment as a token. Since 2082 // it isn't a well formed comment, just return it as an 'unknown' token. 2083 if (isKeepWhitespaceMode()) { 2084 FormTokenWithChars(Result, CurPtr, tok::unknown); 2085 return true; 2086 } 2087 2088 BufferPtr = CurPtr; 2089 return false; 2090 } 2091 2092 // Check to see if the first character after the '/*' is another /. If so, 2093 // then this slash does not end the block comment, it is part of it. 2094 if (C == '/') 2095 C = *CurPtr++; 2096 2097 while (1) { 2098 // Skip over all non-interesting characters until we find end of buffer or a 2099 // (probably ending) '/' character. 2100 if (CurPtr + 24 < BufferEnd && 2101 // If there is a code-completion point avoid the fast scan because it 2102 // doesn't check for '\0'. 2103 !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) { 2104 // While not aligned to a 16-byte boundary. 2105 while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0) 2106 C = *CurPtr++; 2107 2108 if (C == '/') goto FoundSlash; 2109 2110 #ifdef __SSE2__ 2111 __m128i Slashes = _mm_set1_epi8('/'); 2112 while (CurPtr+16 <= BufferEnd) { 2113 int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(__m128i*)CurPtr, Slashes)); 2114 if (cmp != 0) { 2115 // Adjust the pointer to point directly after the first slash. It's 2116 // not necessary to set C here, it will be overwritten at the end of 2117 // the outer loop. 2118 CurPtr += llvm::CountTrailingZeros_32(cmp) + 1; 2119 goto FoundSlash; 2120 } 2121 CurPtr += 16; 2122 } 2123 #elif __ALTIVEC__ 2124 __vector unsigned char Slashes = { 2125 '/', '/', '/', '/', '/', '/', '/', '/', 2126 '/', '/', '/', '/', '/', '/', '/', '/' 2127 }; 2128 while (CurPtr+16 <= BufferEnd && 2129 !vec_any_eq(*(vector unsigned char*)CurPtr, Slashes)) 2130 CurPtr += 16; 2131 #else 2132 // Scan for '/' quickly. Many block comments are very large. 2133 while (CurPtr[0] != '/' && 2134 CurPtr[1] != '/' && 2135 CurPtr[2] != '/' && 2136 CurPtr[3] != '/' && 2137 CurPtr+4 < BufferEnd) { 2138 CurPtr += 4; 2139 } 2140 #endif 2141 2142 // It has to be one of the bytes scanned, increment to it and read one. 2143 C = *CurPtr++; 2144 } 2145 2146 // Loop to scan the remainder. 2147 while (C != '/' && C != '\0') 2148 C = *CurPtr++; 2149 2150 if (C == '/') { 2151 FoundSlash: 2152 if (CurPtr[-2] == '*') // We found the final */. We're done! 2153 break; 2154 2155 if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) { 2156 if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) { 2157 // We found the final */, though it had an escaped newline between the 2158 // * and /. We're done! 2159 break; 2160 } 2161 } 2162 if (CurPtr[0] == '*' && CurPtr[1] != '/') { 2163 // If this is a /* inside of the comment, emit a warning. Don't do this 2164 // if this is a /*/, which will end the comment. This misses cases with 2165 // embedded escaped newlines, but oh well. 2166 if (!isLexingRawMode()) 2167 Diag(CurPtr-1, diag::warn_nested_block_comment); 2168 } 2169 } else if (C == 0 && CurPtr == BufferEnd+1) { 2170 if (!isLexingRawMode()) 2171 Diag(BufferPtr, diag::err_unterminated_block_comment); 2172 // Note: the user probably forgot a */. We could continue immediately 2173 // after the /*, but this would involve lexing a lot of what really is the 2174 // comment, which surely would confuse the parser. 2175 --CurPtr; 2176 2177 // KeepWhitespaceMode should return this broken comment as a token. Since 2178 // it isn't a well formed comment, just return it as an 'unknown' token. 2179 if (isKeepWhitespaceMode()) { 2180 FormTokenWithChars(Result, CurPtr, tok::unknown); 2181 return true; 2182 } 2183 2184 BufferPtr = CurPtr; 2185 return false; 2186 } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) { 2187 PP->CodeCompleteNaturalLanguage(); 2188 cutOffLexing(); 2189 return false; 2190 } 2191 2192 C = *CurPtr++; 2193 } 2194 2195 // Notify comment handlers about the comment unless we're in a #if 0 block. 2196 if (PP && !isLexingRawMode() && 2197 PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr), 2198 getSourceLocation(CurPtr)))) { 2199 BufferPtr = CurPtr; 2200 return true; // A token has to be returned. 2201 } 2202 2203 // If we are returning comments as tokens, return this comment as a token. 2204 if (inKeepCommentMode()) { 2205 FormTokenWithChars(Result, CurPtr, tok::comment); 2206 return true; 2207 } 2208 2209 // It is common for the tokens immediately after a /**/ comment to be 2210 // whitespace. Instead of going through the big switch, handle it 2211 // efficiently now. This is safe even in KeepWhitespaceMode because we would 2212 // have already returned above with the comment as a token. 2213 if (isHorizontalWhitespace(*CurPtr)) { 2214 Result.setFlag(Token::LeadingSpace); 2215 SkipWhitespace(Result, CurPtr+1); 2216 return false; 2217 } 2218 2219 // Otherwise, just return so that the next character will be lexed as a token. 2220 BufferPtr = CurPtr; 2221 Result.setFlag(Token::LeadingSpace); 2222 return false; 2223 } 2224 2225 //===----------------------------------------------------------------------===// 2226 // Primary Lexing Entry Points 2227 //===----------------------------------------------------------------------===// 2228 2229 /// ReadToEndOfLine - Read the rest of the current preprocessor line as an 2230 /// uninterpreted string. This switches the lexer out of directive mode. 2231 std::string Lexer::ReadToEndOfLine() { 2232 assert(ParsingPreprocessorDirective && ParsingFilename == false && 2233 "Must be in a preprocessing directive!"); 2234 std::string Result; 2235 Token Tmp; 2236 2237 // CurPtr - Cache BufferPtr in an automatic variable. 2238 const char *CurPtr = BufferPtr; 2239 while (1) { 2240 char Char = getAndAdvanceChar(CurPtr, Tmp); 2241 switch (Char) { 2242 default: 2243 Result += Char; 2244 break; 2245 case 0: // Null. 2246 // Found end of file? 2247 if (CurPtr-1 != BufferEnd) { 2248 if (isCodeCompletionPoint(CurPtr-1)) { 2249 PP->CodeCompleteNaturalLanguage(); 2250 cutOffLexing(); 2251 return Result; 2252 } 2253 2254 // Nope, normal character, continue. 2255 Result += Char; 2256 break; 2257 } 2258 // FALL THROUGH. 2259 case '\r': 2260 case '\n': 2261 // Okay, we found the end of the line. First, back up past the \0, \r, \n. 2262 assert(CurPtr[-1] == Char && "Trigraphs for newline?"); 2263 BufferPtr = CurPtr-1; 2264 2265 // Next, lex the character, which should handle the EOD transition. 2266 Lex(Tmp); 2267 if (Tmp.is(tok::code_completion)) { 2268 if (PP) 2269 PP->CodeCompleteNaturalLanguage(); 2270 Lex(Tmp); 2271 } 2272 assert(Tmp.is(tok::eod) && "Unexpected token!"); 2273 2274 // Finally, we're done, return the string we found. 2275 return Result; 2276 } 2277 } 2278 } 2279 2280 /// LexEndOfFile - CurPtr points to the end of this file. Handle this 2281 /// condition, reporting diagnostics and handling other edge cases as required. 2282 /// This returns true if Result contains a token, false if PP.Lex should be 2283 /// called again. 2284 bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) { 2285 // If we hit the end of the file while parsing a preprocessor directive, 2286 // end the preprocessor directive first. The next token returned will 2287 // then be the end of file. 2288 if (ParsingPreprocessorDirective) { 2289 // Done parsing the "line". 2290 ParsingPreprocessorDirective = false; 2291 // Update the location of token as well as BufferPtr. 2292 FormTokenWithChars(Result, CurPtr, tok::eod); 2293 2294 // Restore comment saving mode, in case it was disabled for directive. 2295 SetCommentRetentionState(PP->getCommentRetentionState()); 2296 return true; // Have a token. 2297 } 2298 2299 // If we are in raw mode, return this event as an EOF token. Let the caller 2300 // that put us in raw mode handle the event. 2301 if (isLexingRawMode()) { 2302 Result.startToken(); 2303 BufferPtr = BufferEnd; 2304 FormTokenWithChars(Result, BufferEnd, tok::eof); 2305 return true; 2306 } 2307 2308 // Issue diagnostics for unterminated #if and missing newline. 2309 2310 // If we are in a #if directive, emit an error. 2311 while (!ConditionalStack.empty()) { 2312 if (PP->getCodeCompletionFileLoc() != FileLoc) 2313 PP->Diag(ConditionalStack.back().IfLoc, 2314 diag::err_pp_unterminated_conditional); 2315 ConditionalStack.pop_back(); 2316 } 2317 2318 // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue 2319 // a pedwarn. 2320 if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) 2321 Diag(BufferEnd, diag::ext_no_newline_eof) 2322 << FixItHint::CreateInsertion(getSourceLocation(BufferEnd), "\n"); 2323 2324 BufferPtr = CurPtr; 2325 2326 // Finally, let the preprocessor handle this. 2327 return PP->HandleEndOfFile(Result); 2328 } 2329 2330 /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from 2331 /// the specified lexer will return a tok::l_paren token, 0 if it is something 2332 /// else and 2 if there are no more tokens in the buffer controlled by the 2333 /// lexer. 2334 unsigned Lexer::isNextPPTokenLParen() { 2335 assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?"); 2336 2337 // Switch to 'skipping' mode. This will ensure that we can lex a token 2338 // without emitting diagnostics, disables macro expansion, and will cause EOF 2339 // to return an EOF token instead of popping the include stack. 2340 LexingRawMode = true; 2341 2342 // Save state that can be changed while lexing so that we can restore it. 2343 const char *TmpBufferPtr = BufferPtr; 2344 bool inPPDirectiveMode = ParsingPreprocessorDirective; 2345 2346 Token Tok; 2347 Tok.startToken(); 2348 LexTokenInternal(Tok); 2349 2350 // Restore state that may have changed. 2351 BufferPtr = TmpBufferPtr; 2352 ParsingPreprocessorDirective = inPPDirectiveMode; 2353 2354 // Restore the lexer back to non-skipping mode. 2355 LexingRawMode = false; 2356 2357 if (Tok.is(tok::eof)) 2358 return 2; 2359 return Tok.is(tok::l_paren); 2360 } 2361 2362 /// FindConflictEnd - Find the end of a version control conflict marker. 2363 static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd, 2364 ConflictMarkerKind CMK) { 2365 const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>"; 2366 size_t TermLen = CMK == CMK_Perforce ? 5 : 7; 2367 StringRef RestOfBuffer(CurPtr+TermLen, BufferEnd-CurPtr-TermLen); 2368 size_t Pos = RestOfBuffer.find(Terminator); 2369 while (Pos != StringRef::npos) { 2370 // Must occur at start of line. 2371 if (RestOfBuffer[Pos-1] != '\r' && 2372 RestOfBuffer[Pos-1] != '\n') { 2373 RestOfBuffer = RestOfBuffer.substr(Pos+TermLen); 2374 Pos = RestOfBuffer.find(Terminator); 2375 continue; 2376 } 2377 return RestOfBuffer.data()+Pos; 2378 } 2379 return 0; 2380 } 2381 2382 /// IsStartOfConflictMarker - If the specified pointer is the start of a version 2383 /// control conflict marker like '<<<<<<<', recognize it as such, emit an error 2384 /// and recover nicely. This returns true if it is a conflict marker and false 2385 /// if not. 2386 bool Lexer::IsStartOfConflictMarker(const char *CurPtr) { 2387 // Only a conflict marker if it starts at the beginning of a line. 2388 if (CurPtr != BufferStart && 2389 CurPtr[-1] != '\n' && CurPtr[-1] != '\r') 2390 return false; 2391 2392 // Check to see if we have <<<<<<< or >>>>. 2393 if ((BufferEnd-CurPtr < 8 || StringRef(CurPtr, 7) != "<<<<<<<") && 2394 (BufferEnd-CurPtr < 6 || StringRef(CurPtr, 5) != ">>>> ")) 2395 return false; 2396 2397 // If we have a situation where we don't care about conflict markers, ignore 2398 // it. 2399 if (CurrentConflictMarkerState || isLexingRawMode()) 2400 return false; 2401 2402 ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce; 2403 2404 // Check to see if there is an ending marker somewhere in the buffer at the 2405 // start of a line to terminate this conflict marker. 2406 if (FindConflictEnd(CurPtr, BufferEnd, Kind)) { 2407 // We found a match. We are really in a conflict marker. 2408 // Diagnose this, and ignore to the end of line. 2409 Diag(CurPtr, diag::err_conflict_marker); 2410 CurrentConflictMarkerState = Kind; 2411 2412 // Skip ahead to the end of line. We know this exists because the 2413 // end-of-conflict marker starts with \r or \n. 2414 while (*CurPtr != '\r' && *CurPtr != '\n') { 2415 assert(CurPtr != BufferEnd && "Didn't find end of line"); 2416 ++CurPtr; 2417 } 2418 BufferPtr = CurPtr; 2419 return true; 2420 } 2421 2422 // No end of conflict marker found. 2423 return false; 2424 } 2425 2426 2427 /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if 2428 /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it 2429 /// is the end of a conflict marker. Handle it by ignoring up until the end of 2430 /// the line. This returns true if it is a conflict marker and false if not. 2431 bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) { 2432 // Only a conflict marker if it starts at the beginning of a line. 2433 if (CurPtr != BufferStart && 2434 CurPtr[-1] != '\n' && CurPtr[-1] != '\r') 2435 return false; 2436 2437 // If we have a situation where we don't care about conflict markers, ignore 2438 // it. 2439 if (!CurrentConflictMarkerState || isLexingRawMode()) 2440 return false; 2441 2442 // Check to see if we have the marker (4 characters in a row). 2443 for (unsigned i = 1; i != 4; ++i) 2444 if (CurPtr[i] != CurPtr[0]) 2445 return false; 2446 2447 // If we do have it, search for the end of the conflict marker. This could 2448 // fail if it got skipped with a '#if 0' or something. Note that CurPtr might 2449 // be the end of conflict marker. 2450 if (const char *End = FindConflictEnd(CurPtr, BufferEnd, 2451 CurrentConflictMarkerState)) { 2452 CurPtr = End; 2453 2454 // Skip ahead to the end of line. 2455 while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n') 2456 ++CurPtr; 2457 2458 BufferPtr = CurPtr; 2459 2460 // No longer in the conflict marker. 2461 CurrentConflictMarkerState = CMK_None; 2462 return true; 2463 } 2464 2465 return false; 2466 } 2467 2468 bool Lexer::isCodeCompletionPoint(const char *CurPtr) const { 2469 if (PP && PP->isCodeCompletionEnabled()) { 2470 SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart); 2471 return Loc == PP->getCodeCompletionLoc(); 2472 } 2473 2474 return false; 2475 } 2476 2477 2478 /// LexTokenInternal - This implements a simple C family lexer. It is an 2479 /// extremely performance critical piece of code. This assumes that the buffer 2480 /// has a null character at the end of the file. This returns a preprocessing 2481 /// token, not a normal token, as such, it is an internal interface. It assumes 2482 /// that the Flags of result have been cleared before calling this. 2483 void Lexer::LexTokenInternal(Token &Result) { 2484 LexNextToken: 2485 // New token, can't need cleaning yet. 2486 Result.clearFlag(Token::NeedsCleaning); 2487 Result.setIdentifierInfo(0); 2488 2489 // CurPtr - Cache BufferPtr in an automatic variable. 2490 const char *CurPtr = BufferPtr; 2491 2492 // Small amounts of horizontal whitespace is very common between tokens. 2493 if ((*CurPtr == ' ') || (*CurPtr == '\t')) { 2494 ++CurPtr; 2495 while ((*CurPtr == ' ') || (*CurPtr == '\t')) 2496 ++CurPtr; 2497 2498 // If we are keeping whitespace and other tokens, just return what we just 2499 // skipped. The next lexer invocation will return the token after the 2500 // whitespace. 2501 if (isKeepWhitespaceMode()) { 2502 FormTokenWithChars(Result, CurPtr, tok::unknown); 2503 return; 2504 } 2505 2506 BufferPtr = CurPtr; 2507 Result.setFlag(Token::LeadingSpace); 2508 } 2509 2510 unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below. 2511 2512 // Read a character, advancing over it. 2513 char Char = getAndAdvanceChar(CurPtr, Result); 2514 tok::TokenKind Kind; 2515 2516 switch (Char) { 2517 case 0: // Null. 2518 // Found end of file? 2519 if (CurPtr-1 == BufferEnd) { 2520 // Read the PP instance variable into an automatic variable, because 2521 // LexEndOfFile will often delete 'this'. 2522 Preprocessor *PPCache = PP; 2523 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file. 2524 return; // Got a token to return. 2525 assert(PPCache && "Raw buffer::LexEndOfFile should return a token"); 2526 return PPCache->Lex(Result); 2527 } 2528 2529 // Check if we are performing code completion. 2530 if (isCodeCompletionPoint(CurPtr-1)) { 2531 // Return the code-completion token. 2532 Result.startToken(); 2533 FormTokenWithChars(Result, CurPtr, tok::code_completion); 2534 return; 2535 } 2536 2537 if (!isLexingRawMode()) 2538 Diag(CurPtr-1, diag::null_in_file); 2539 Result.setFlag(Token::LeadingSpace); 2540 if (SkipWhitespace(Result, CurPtr)) 2541 return; // KeepWhitespaceMode 2542 2543 goto LexNextToken; // GCC isn't tail call eliminating. 2544 2545 case 26: // DOS & CP/M EOF: "^Z". 2546 // If we're in Microsoft extensions mode, treat this as end of file. 2547 if (Features.MicrosoftExt) { 2548 // Read the PP instance variable into an automatic variable, because 2549 // LexEndOfFile will often delete 'this'. 2550 Preprocessor *PPCache = PP; 2551 if (LexEndOfFile(Result, CurPtr-1)) // Retreat back into the file. 2552 return; // Got a token to return. 2553 assert(PPCache && "Raw buffer::LexEndOfFile should return a token"); 2554 return PPCache->Lex(Result); 2555 } 2556 // If Microsoft extensions are disabled, this is just random garbage. 2557 Kind = tok::unknown; 2558 break; 2559 2560 case '\n': 2561 case '\r': 2562 // If we are inside a preprocessor directive and we see the end of line, 2563 // we know we are done with the directive, so return an EOD token. 2564 if (ParsingPreprocessorDirective) { 2565 // Done parsing the "line". 2566 ParsingPreprocessorDirective = false; 2567 2568 // Restore comment saving mode, in case it was disabled for directive. 2569 SetCommentRetentionState(PP->getCommentRetentionState()); 2570 2571 // Since we consumed a newline, we are back at the start of a line. 2572 IsAtStartOfLine = true; 2573 2574 Kind = tok::eod; 2575 break; 2576 } 2577 // The returned token is at the start of the line. 2578 Result.setFlag(Token::StartOfLine); 2579 // No leading whitespace seen so far. 2580 Result.clearFlag(Token::LeadingSpace); 2581 2582 if (SkipWhitespace(Result, CurPtr)) 2583 return; // KeepWhitespaceMode 2584 goto LexNextToken; // GCC isn't tail call eliminating. 2585 case ' ': 2586 case '\t': 2587 case '\f': 2588 case '\v': 2589 SkipHorizontalWhitespace: 2590 Result.setFlag(Token::LeadingSpace); 2591 if (SkipWhitespace(Result, CurPtr)) 2592 return; // KeepWhitespaceMode 2593 2594 SkipIgnoredUnits: 2595 CurPtr = BufferPtr; 2596 2597 // If the next token is obviously a // or /* */ comment, skip it efficiently 2598 // too (without going through the big switch stmt). 2599 if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() && 2600 Features.BCPLComment && !Features.TraditionalCPP) { 2601 if (SkipBCPLComment(Result, CurPtr+2)) 2602 return; // There is a token to return. 2603 goto SkipIgnoredUnits; 2604 } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) { 2605 if (SkipBlockComment(Result, CurPtr+2)) 2606 return; // There is a token to return. 2607 goto SkipIgnoredUnits; 2608 } else if (isHorizontalWhitespace(*CurPtr)) { 2609 goto SkipHorizontalWhitespace; 2610 } 2611 goto LexNextToken; // GCC isn't tail call eliminating. 2612 2613 // C99 6.4.4.1: Integer Constants. 2614 // C99 6.4.4.2: Floating Constants. 2615 case '0': case '1': case '2': case '3': case '4': 2616 case '5': case '6': case '7': case '8': case '9': 2617 // Notify MIOpt that we read a non-whitespace/non-comment token. 2618 MIOpt.ReadToken(); 2619 return LexNumericConstant(Result, CurPtr); 2620 2621 case 'u': // Identifier (uber) or C++0x UTF-8 or UTF-16 string literal 2622 // Notify MIOpt that we read a non-whitespace/non-comment token. 2623 MIOpt.ReadToken(); 2624 2625 if (Features.CPlusPlus0x) { 2626 Char = getCharAndSize(CurPtr, SizeTmp); 2627 2628 // UTF-16 string literal 2629 if (Char == '"') 2630 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), 2631 tok::utf16_string_literal); 2632 2633 // UTF-16 character constant 2634 if (Char == '\'') 2635 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), 2636 tok::utf16_char_constant); 2637 2638 // UTF-16 raw string literal 2639 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') 2640 return LexRawStringLiteral(Result, 2641 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2642 SizeTmp2, Result), 2643 tok::utf16_string_literal); 2644 2645 if (Char == '8') { 2646 char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2); 2647 2648 // UTF-8 string literal 2649 if (Char2 == '"') 2650 return LexStringLiteral(Result, 2651 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2652 SizeTmp2, Result), 2653 tok::utf8_string_literal); 2654 2655 if (Char2 == 'R') { 2656 unsigned SizeTmp3; 2657 char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3); 2658 // UTF-8 raw string literal 2659 if (Char3 == '"') { 2660 return LexRawStringLiteral(Result, 2661 ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2662 SizeTmp2, Result), 2663 SizeTmp3, Result), 2664 tok::utf8_string_literal); 2665 } 2666 } 2667 } 2668 } 2669 2670 // treat u like the start of an identifier. 2671 return LexIdentifier(Result, CurPtr); 2672 2673 case 'U': // Identifier (Uber) or C++0x UTF-32 string literal 2674 // Notify MIOpt that we read a non-whitespace/non-comment token. 2675 MIOpt.ReadToken(); 2676 2677 if (Features.CPlusPlus0x) { 2678 Char = getCharAndSize(CurPtr, SizeTmp); 2679 2680 // UTF-32 string literal 2681 if (Char == '"') 2682 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), 2683 tok::utf32_string_literal); 2684 2685 // UTF-32 character constant 2686 if (Char == '\'') 2687 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), 2688 tok::utf32_char_constant); 2689 2690 // UTF-32 raw string literal 2691 if (Char == 'R' && getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') 2692 return LexRawStringLiteral(Result, 2693 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2694 SizeTmp2, Result), 2695 tok::utf32_string_literal); 2696 } 2697 2698 // treat U like the start of an identifier. 2699 return LexIdentifier(Result, CurPtr); 2700 2701 case 'R': // Identifier or C++0x raw string literal 2702 // Notify MIOpt that we read a non-whitespace/non-comment token. 2703 MIOpt.ReadToken(); 2704 2705 if (Features.CPlusPlus0x) { 2706 Char = getCharAndSize(CurPtr, SizeTmp); 2707 2708 if (Char == '"') 2709 return LexRawStringLiteral(Result, 2710 ConsumeChar(CurPtr, SizeTmp, Result), 2711 tok::string_literal); 2712 } 2713 2714 // treat R like the start of an identifier. 2715 return LexIdentifier(Result, CurPtr); 2716 2717 case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz"). 2718 // Notify MIOpt that we read a non-whitespace/non-comment token. 2719 MIOpt.ReadToken(); 2720 Char = getCharAndSize(CurPtr, SizeTmp); 2721 2722 // Wide string literal. 2723 if (Char == '"') 2724 return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result), 2725 tok::wide_string_literal); 2726 2727 // Wide raw string literal. 2728 if (Features.CPlusPlus0x && Char == 'R' && 2729 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"') 2730 return LexRawStringLiteral(Result, 2731 ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2732 SizeTmp2, Result), 2733 tok::wide_string_literal); 2734 2735 // Wide character constant. 2736 if (Char == '\'') 2737 return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result), 2738 tok::wide_char_constant); 2739 // FALL THROUGH, treating L like the start of an identifier. 2740 2741 // C99 6.4.2: Identifiers. 2742 case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': 2743 case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N': 2744 case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/ 2745 case 'V': case 'W': case 'X': case 'Y': case 'Z': 2746 case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': 2747 case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': 2748 case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/ 2749 case 'v': case 'w': case 'x': case 'y': case 'z': 2750 case '_': 2751 // Notify MIOpt that we read a non-whitespace/non-comment token. 2752 MIOpt.ReadToken(); 2753 return LexIdentifier(Result, CurPtr); 2754 2755 case '$': // $ in identifiers. 2756 if (Features.DollarIdents) { 2757 if (!isLexingRawMode()) 2758 Diag(CurPtr-1, diag::ext_dollar_in_identifier); 2759 // Notify MIOpt that we read a non-whitespace/non-comment token. 2760 MIOpt.ReadToken(); 2761 return LexIdentifier(Result, CurPtr); 2762 } 2763 2764 Kind = tok::unknown; 2765 break; 2766 2767 // C99 6.4.4: Character Constants. 2768 case '\'': 2769 // Notify MIOpt that we read a non-whitespace/non-comment token. 2770 MIOpt.ReadToken(); 2771 return LexCharConstant(Result, CurPtr, tok::char_constant); 2772 2773 // C99 6.4.5: String Literals. 2774 case '"': 2775 // Notify MIOpt that we read a non-whitespace/non-comment token. 2776 MIOpt.ReadToken(); 2777 return LexStringLiteral(Result, CurPtr, tok::string_literal); 2778 2779 // C99 6.4.6: Punctuators. 2780 case '?': 2781 Kind = tok::question; 2782 break; 2783 case '[': 2784 Kind = tok::l_square; 2785 break; 2786 case ']': 2787 Kind = tok::r_square; 2788 break; 2789 case '(': 2790 Kind = tok::l_paren; 2791 break; 2792 case ')': 2793 Kind = tok::r_paren; 2794 break; 2795 case '{': 2796 Kind = tok::l_brace; 2797 break; 2798 case '}': 2799 Kind = tok::r_brace; 2800 break; 2801 case '.': 2802 Char = getCharAndSize(CurPtr, SizeTmp); 2803 if (Char >= '0' && Char <= '9') { 2804 // Notify MIOpt that we read a non-whitespace/non-comment token. 2805 MIOpt.ReadToken(); 2806 2807 return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result)); 2808 } else if (Features.CPlusPlus && Char == '*') { 2809 Kind = tok::periodstar; 2810 CurPtr += SizeTmp; 2811 } else if (Char == '.' && 2812 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') { 2813 Kind = tok::ellipsis; 2814 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2815 SizeTmp2, Result); 2816 } else { 2817 Kind = tok::period; 2818 } 2819 break; 2820 case '&': 2821 Char = getCharAndSize(CurPtr, SizeTmp); 2822 if (Char == '&') { 2823 Kind = tok::ampamp; 2824 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2825 } else if (Char == '=') { 2826 Kind = tok::ampequal; 2827 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2828 } else { 2829 Kind = tok::amp; 2830 } 2831 break; 2832 case '*': 2833 if (getCharAndSize(CurPtr, SizeTmp) == '=') { 2834 Kind = tok::starequal; 2835 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2836 } else { 2837 Kind = tok::star; 2838 } 2839 break; 2840 case '+': 2841 Char = getCharAndSize(CurPtr, SizeTmp); 2842 if (Char == '+') { 2843 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2844 Kind = tok::plusplus; 2845 } else if (Char == '=') { 2846 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2847 Kind = tok::plusequal; 2848 } else { 2849 Kind = tok::plus; 2850 } 2851 break; 2852 case '-': 2853 Char = getCharAndSize(CurPtr, SizeTmp); 2854 if (Char == '-') { // -- 2855 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2856 Kind = tok::minusminus; 2857 } else if (Char == '>' && Features.CPlusPlus && 2858 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->* 2859 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2860 SizeTmp2, Result); 2861 Kind = tok::arrowstar; 2862 } else if (Char == '>') { // -> 2863 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2864 Kind = tok::arrow; 2865 } else if (Char == '=') { // -= 2866 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2867 Kind = tok::minusequal; 2868 } else { 2869 Kind = tok::minus; 2870 } 2871 break; 2872 case '~': 2873 Kind = tok::tilde; 2874 break; 2875 case '!': 2876 if (getCharAndSize(CurPtr, SizeTmp) == '=') { 2877 Kind = tok::exclaimequal; 2878 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2879 } else { 2880 Kind = tok::exclaim; 2881 } 2882 break; 2883 case '/': 2884 // 6.4.9: Comments 2885 Char = getCharAndSize(CurPtr, SizeTmp); 2886 if (Char == '/') { // BCPL comment. 2887 // Even if BCPL comments are disabled (e.g. in C89 mode), we generally 2888 // want to lex this as a comment. There is one problem with this though, 2889 // that in one particular corner case, this can change the behavior of the 2890 // resultant program. For example, In "foo //**/ bar", C89 would lex 2891 // this as "foo / bar" and langauges with BCPL comments would lex it as 2892 // "foo". Check to see if the character after the second slash is a '*'. 2893 // If so, we will lex that as a "/" instead of the start of a comment. 2894 // However, we never do this in -traditional-cpp mode. 2895 if ((Features.BCPLComment || 2896 getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*') && 2897 !Features.TraditionalCPP) { 2898 if (SkipBCPLComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) 2899 return; // There is a token to return. 2900 2901 // It is common for the tokens immediately after a // comment to be 2902 // whitespace (indentation for the next line). Instead of going through 2903 // the big switch, handle it efficiently now. 2904 goto SkipIgnoredUnits; 2905 } 2906 } 2907 2908 if (Char == '*') { // /**/ comment. 2909 if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result))) 2910 return; // There is a token to return. 2911 goto LexNextToken; // GCC isn't tail call eliminating. 2912 } 2913 2914 if (Char == '=') { 2915 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2916 Kind = tok::slashequal; 2917 } else { 2918 Kind = tok::slash; 2919 } 2920 break; 2921 case '%': 2922 Char = getCharAndSize(CurPtr, SizeTmp); 2923 if (Char == '=') { 2924 Kind = tok::percentequal; 2925 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2926 } else if (Features.Digraphs && Char == '>') { 2927 Kind = tok::r_brace; // '%>' -> '}' 2928 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2929 } else if (Features.Digraphs && Char == ':') { 2930 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2931 Char = getCharAndSize(CurPtr, SizeTmp); 2932 if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') { 2933 Kind = tok::hashhash; // '%:%:' -> '##' 2934 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2935 SizeTmp2, Result); 2936 } else if (Char == '@' && Features.MicrosoftExt) {// %:@ -> #@ -> Charize 2937 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2938 if (!isLexingRawMode()) 2939 Diag(BufferPtr, diag::ext_charize_microsoft); 2940 Kind = tok::hashat; 2941 } else { // '%:' -> '#' 2942 // We parsed a # character. If this occurs at the start of the line, 2943 // it's actually the start of a preprocessing directive. Callback to 2944 // the preprocessor to handle it. 2945 // FIXME: -fpreprocessed mode?? 2946 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) { 2947 FormTokenWithChars(Result, CurPtr, tok::hash); 2948 PP->HandleDirective(Result); 2949 2950 // As an optimization, if the preprocessor didn't switch lexers, tail 2951 // recurse. 2952 if (PP->isCurrentLexer(this)) { 2953 // Start a new token. If this is a #include or something, the PP may 2954 // want us starting at the beginning of the line again. If so, set 2955 // the StartOfLine flag and clear LeadingSpace. 2956 if (IsAtStartOfLine) { 2957 Result.setFlag(Token::StartOfLine); 2958 Result.clearFlag(Token::LeadingSpace); 2959 IsAtStartOfLine = false; 2960 } 2961 goto LexNextToken; // GCC isn't tail call eliminating. 2962 } 2963 2964 return PP->Lex(Result); 2965 } 2966 2967 Kind = tok::hash; 2968 } 2969 } else { 2970 Kind = tok::percent; 2971 } 2972 break; 2973 case '<': 2974 Char = getCharAndSize(CurPtr, SizeTmp); 2975 if (ParsingFilename) { 2976 return LexAngledStringLiteral(Result, CurPtr); 2977 } else if (Char == '<') { 2978 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2); 2979 if (After == '=') { 2980 Kind = tok::lesslessequal; 2981 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2982 SizeTmp2, Result); 2983 } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) { 2984 // If this is actually a '<<<<<<<' version control conflict marker, 2985 // recognize it as such and recover nicely. 2986 goto LexNextToken; 2987 } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) { 2988 // If this is '<<<<' and we're in a Perforce-style conflict marker, 2989 // ignore it. 2990 goto LexNextToken; 2991 } else if (Features.CUDA && After == '<') { 2992 Kind = tok::lesslessless; 2993 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 2994 SizeTmp2, Result); 2995 } else { 2996 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 2997 Kind = tok::lessless; 2998 } 2999 } else if (Char == '=') { 3000 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3001 Kind = tok::lessequal; 3002 } else if (Features.Digraphs && Char == ':') { // '<:' -> '[' 3003 if (Features.CPlusPlus0x && 3004 getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') { 3005 // C++0x [lex.pptoken]p3: 3006 // Otherwise, if the next three characters are <:: and the subsequent 3007 // character is neither : nor >, the < is treated as a preprocessor 3008 // token by itself and not as the first character of the alternative 3009 // token <:. 3010 unsigned SizeTmp3; 3011 char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3); 3012 if (After != ':' && After != '>') { 3013 Kind = tok::less; 3014 if (!isLexingRawMode()) 3015 Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon); 3016 break; 3017 } 3018 } 3019 3020 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3021 Kind = tok::l_square; 3022 } else if (Features.Digraphs && Char == '%') { // '<%' -> '{' 3023 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3024 Kind = tok::l_brace; 3025 } else { 3026 Kind = tok::less; 3027 } 3028 break; 3029 case '>': 3030 Char = getCharAndSize(CurPtr, SizeTmp); 3031 if (Char == '=') { 3032 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3033 Kind = tok::greaterequal; 3034 } else if (Char == '>') { 3035 char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2); 3036 if (After == '=') { 3037 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3038 SizeTmp2, Result); 3039 Kind = tok::greatergreaterequal; 3040 } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) { 3041 // If this is actually a '>>>>' conflict marker, recognize it as such 3042 // and recover nicely. 3043 goto LexNextToken; 3044 } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) { 3045 // If this is '>>>>>>>' and we're in a conflict marker, ignore it. 3046 goto LexNextToken; 3047 } else if (Features.CUDA && After == '>') { 3048 Kind = tok::greatergreatergreater; 3049 CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result), 3050 SizeTmp2, Result); 3051 } else { 3052 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3053 Kind = tok::greatergreater; 3054 } 3055 3056 } else { 3057 Kind = tok::greater; 3058 } 3059 break; 3060 case '^': 3061 Char = getCharAndSize(CurPtr, SizeTmp); 3062 if (Char == '=') { 3063 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3064 Kind = tok::caretequal; 3065 } else { 3066 Kind = tok::caret; 3067 } 3068 break; 3069 case '|': 3070 Char = getCharAndSize(CurPtr, SizeTmp); 3071 if (Char == '=') { 3072 Kind = tok::pipeequal; 3073 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3074 } else if (Char == '|') { 3075 // If this is '|||||||' and we're in a conflict marker, ignore it. 3076 if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1)) 3077 goto LexNextToken; 3078 Kind = tok::pipepipe; 3079 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3080 } else { 3081 Kind = tok::pipe; 3082 } 3083 break; 3084 case ':': 3085 Char = getCharAndSize(CurPtr, SizeTmp); 3086 if (Features.Digraphs && Char == '>') { 3087 Kind = tok::r_square; // ':>' -> ']' 3088 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3089 } else if (Features.CPlusPlus && Char == ':') { 3090 Kind = tok::coloncolon; 3091 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3092 } else { 3093 Kind = tok::colon; 3094 } 3095 break; 3096 case ';': 3097 Kind = tok::semi; 3098 break; 3099 case '=': 3100 Char = getCharAndSize(CurPtr, SizeTmp); 3101 if (Char == '=') { 3102 // If this is '====' and we're in a conflict marker, ignore it. 3103 if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1)) 3104 goto LexNextToken; 3105 3106 Kind = tok::equalequal; 3107 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3108 } else { 3109 Kind = tok::equal; 3110 } 3111 break; 3112 case ',': 3113 Kind = tok::comma; 3114 break; 3115 case '#': 3116 Char = getCharAndSize(CurPtr, SizeTmp); 3117 if (Char == '#') { 3118 Kind = tok::hashhash; 3119 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3120 } else if (Char == '@' && Features.MicrosoftExt) { // #@ -> Charize 3121 Kind = tok::hashat; 3122 if (!isLexingRawMode()) 3123 Diag(BufferPtr, diag::ext_charize_microsoft); 3124 CurPtr = ConsumeChar(CurPtr, SizeTmp, Result); 3125 } else { 3126 // We parsed a # character. If this occurs at the start of the line, 3127 // it's actually the start of a preprocessing directive. Callback to 3128 // the preprocessor to handle it. 3129 // FIXME: -fpreprocessed mode?? 3130 if (Result.isAtStartOfLine() && !LexingRawMode && !Is_PragmaLexer) { 3131 FormTokenWithChars(Result, CurPtr, tok::hash); 3132 PP->HandleDirective(Result); 3133 3134 // As an optimization, if the preprocessor didn't switch lexers, tail 3135 // recurse. 3136 if (PP->isCurrentLexer(this)) { 3137 // Start a new token. If this is a #include or something, the PP may 3138 // want us starting at the beginning of the line again. If so, set 3139 // the StartOfLine flag and clear LeadingSpace. 3140 if (IsAtStartOfLine) { 3141 Result.setFlag(Token::StartOfLine); 3142 Result.clearFlag(Token::LeadingSpace); 3143 IsAtStartOfLine = false; 3144 } 3145 goto LexNextToken; // GCC isn't tail call eliminating. 3146 } 3147 return PP->Lex(Result); 3148 } 3149 3150 Kind = tok::hash; 3151 } 3152 break; 3153 3154 case '@': 3155 // Objective C support. 3156 if (CurPtr[-1] == '@' && Features.ObjC1) 3157 Kind = tok::at; 3158 else 3159 Kind = tok::unknown; 3160 break; 3161 3162 case '\\': 3163 // FIXME: UCN's. 3164 // FALL THROUGH. 3165 default: 3166 Kind = tok::unknown; 3167 break; 3168 } 3169 3170 // Notify MIOpt that we read a non-whitespace/non-comment token. 3171 MIOpt.ReadToken(); 3172 3173 // Update the location of token as well as BufferPtr. 3174 FormTokenWithChars(Result, CurPtr, Kind); 3175 } 3176