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