1 //===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===// 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 Preprocessor interface. 11 // 12 //===----------------------------------------------------------------------===// 13 // 14 // Options to support: 15 // -H - Print the name of each header file used. 16 // -d[DNI] - Dump various things. 17 // -fworking-directory - #line's with preprocessor's working dir. 18 // -fpreprocessed 19 // -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD 20 // -W* 21 // -w 22 // 23 // Messages to emit: 24 // "Multiple include guards may be useful for:\n" 25 // 26 //===----------------------------------------------------------------------===// 27 28 #include "clang/Lex/Preprocessor.h" 29 #include "clang/Lex/MacroArgs.h" 30 #include "clang/Basic/FileManager.h" 31 #include "clang/Basic/SourceManager.h" 32 #include "clang/Basic/TargetInfo.h" 33 #include "clang/Lex/CodeCompletionHandler.h" 34 #include "clang/Lex/ExternalPreprocessorSource.h" 35 #include "clang/Lex/HeaderSearch.h" 36 #include "clang/Lex/LexDiagnostic.h" 37 #include "clang/Lex/LiteralSupport.h" 38 #include "clang/Lex/MacroInfo.h" 39 #include "clang/Lex/ModuleLoader.h" 40 #include "clang/Lex/Pragma.h" 41 #include "clang/Lex/PreprocessingRecord.h" 42 #include "clang/Lex/PreprocessorOptions.h" 43 #include "clang/Lex/ScratchBuffer.h" 44 #include "llvm/ADT/APFloat.h" 45 #include "llvm/ADT/SmallString.h" 46 #include "llvm/ADT/STLExtras.h" 47 #include "llvm/ADT/StringExtras.h" 48 #include "llvm/Support/Capacity.h" 49 #include "llvm/Support/ConvertUTF.h" 50 #include "llvm/Support/MemoryBuffer.h" 51 #include "llvm/Support/raw_ostream.h" 52 using namespace clang; 53 54 //===----------------------------------------------------------------------===// 55 ExternalPreprocessorSource::~ExternalPreprocessorSource() { } 56 57 Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts, 58 DiagnosticsEngine &diags, LangOptions &opts, 59 const TargetInfo *target, SourceManager &SM, 60 HeaderSearch &Headers, ModuleLoader &TheModuleLoader, 61 IdentifierInfoLookup *IILookup, bool OwnsHeaders, 62 bool DelayInitialization, bool IncrProcessing) 63 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(target), 64 FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers), 65 TheModuleLoader(TheModuleLoader), ExternalSource(0), 66 Identifiers(opts, IILookup), IncrementalProcessing(IncrProcessing), 67 CodeComplete(0), CodeCompletionFile(0), CodeCompletionOffset(0), 68 CodeCompletionReached(0), SkipMainFilePreamble(0, true), CurPPLexer(0), 69 CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0), 70 MacroArgCache(0), Record(0), MIChainHead(0), MICache(0), 71 DeserialMIChainHead(0) { 72 OwnsHeaderSearch = OwnsHeaders; 73 74 ScratchBuf = new ScratchBuffer(SourceMgr); 75 CounterValue = 0; // __COUNTER__ starts at 0. 76 77 // Clear stats. 78 NumDirectives = NumDefined = NumUndefined = NumPragma = 0; 79 NumIf = NumElse = NumEndif = 0; 80 NumEnteredSourceFiles = 0; 81 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0; 82 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0; 83 MaxIncludeStackDepth = 0; 84 NumSkipped = 0; 85 86 // Default to discarding comments. 87 KeepComments = false; 88 KeepMacroComments = false; 89 SuppressIncludeNotFoundError = false; 90 91 // Macro expansion is enabled. 92 DisableMacroExpansion = false; 93 MacroExpansionInDirectivesOverride = false; 94 InMacroArgs = false; 95 InMacroArgPreExpansion = false; 96 NumCachedTokenLexers = 0; 97 PragmasEnabled = true; 98 ParsingIfOrElifDirective = false; 99 PreprocessedOutput = false; 100 101 CachedLexPos = 0; 102 103 // We haven't read anything from the external source. 104 ReadMacrosFromExternalSource = false; 105 106 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro. 107 // This gets unpoisoned where it is allowed. 108 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned(); 109 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use); 110 111 // Initialize the pragma handlers. 112 PragmaHandlers = new PragmaNamespace(StringRef()); 113 RegisterBuiltinPragmas(); 114 115 // Initialize builtin macros like __LINE__ and friends. 116 RegisterBuiltinMacros(); 117 118 if(LangOpts.Borland) { 119 Ident__exception_info = getIdentifierInfo("_exception_info"); 120 Ident___exception_info = getIdentifierInfo("__exception_info"); 121 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation"); 122 Ident__exception_code = getIdentifierInfo("_exception_code"); 123 Ident___exception_code = getIdentifierInfo("__exception_code"); 124 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode"); 125 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination"); 126 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination"); 127 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination"); 128 } else { 129 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0; 130 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0; 131 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0; 132 } 133 134 if (!DelayInitialization) { 135 assert(Target && "Must provide target information for PP initialization"); 136 Initialize(*Target); 137 } 138 } 139 140 Preprocessor::~Preprocessor() { 141 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!"); 142 143 while (!IncludeMacroStack.empty()) { 144 delete IncludeMacroStack.back().TheLexer; 145 delete IncludeMacroStack.back().TheTokenLexer; 146 IncludeMacroStack.pop_back(); 147 } 148 149 // Free any macro definitions. 150 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next) 151 I->MI.Destroy(); 152 153 // Free any cached macro expanders. 154 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i) 155 delete TokenLexerCache[i]; 156 157 for (DeserializedMacroInfoChain *I = DeserialMIChainHead ; I ; I = I->Next) 158 I->MI.Destroy(); 159 160 // Free any cached MacroArgs. 161 for (MacroArgs *ArgList = MacroArgCache; ArgList; ) 162 ArgList = ArgList->deallocate(); 163 164 // Release pragma information. 165 delete PragmaHandlers; 166 167 // Delete the scratch buffer info. 168 delete ScratchBuf; 169 170 // Delete the header search info, if we own it. 171 if (OwnsHeaderSearch) 172 delete &HeaderInfo; 173 174 delete Callbacks; 175 } 176 177 void Preprocessor::Initialize(const TargetInfo &Target) { 178 assert((!this->Target || this->Target == &Target) && 179 "Invalid override of target information"); 180 this->Target = &Target; 181 182 // Initialize information about built-ins. 183 BuiltinInfo.InitializeTarget(Target); 184 HeaderInfo.setTarget(Target); 185 } 186 187 void Preprocessor::setPTHManager(PTHManager* pm) { 188 PTH.reset(pm); 189 FileMgr.addStatCache(PTH->createStatCache()); 190 } 191 192 void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const { 193 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '" 194 << getSpelling(Tok) << "'"; 195 196 if (!DumpFlags) return; 197 198 llvm::errs() << "\t"; 199 if (Tok.isAtStartOfLine()) 200 llvm::errs() << " [StartOfLine]"; 201 if (Tok.hasLeadingSpace()) 202 llvm::errs() << " [LeadingSpace]"; 203 if (Tok.isExpandDisabled()) 204 llvm::errs() << " [ExpandDisabled]"; 205 if (Tok.needsCleaning()) { 206 const char *Start = SourceMgr.getCharacterData(Tok.getLocation()); 207 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength()) 208 << "']"; 209 } 210 211 llvm::errs() << "\tLoc=<"; 212 DumpLocation(Tok.getLocation()); 213 llvm::errs() << ">"; 214 } 215 216 void Preprocessor::DumpLocation(SourceLocation Loc) const { 217 Loc.dump(SourceMgr); 218 } 219 220 void Preprocessor::DumpMacro(const MacroInfo &MI) const { 221 llvm::errs() << "MACRO: "; 222 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) { 223 DumpToken(MI.getReplacementToken(i)); 224 llvm::errs() << " "; 225 } 226 llvm::errs() << "\n"; 227 } 228 229 void Preprocessor::PrintStats() { 230 llvm::errs() << "\n*** Preprocessor Stats:\n"; 231 llvm::errs() << NumDirectives << " directives found:\n"; 232 llvm::errs() << " " << NumDefined << " #define.\n"; 233 llvm::errs() << " " << NumUndefined << " #undef.\n"; 234 llvm::errs() << " #include/#include_next/#import:\n"; 235 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n"; 236 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n"; 237 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n"; 238 llvm::errs() << " " << NumElse << " #else/#elif.\n"; 239 llvm::errs() << " " << NumEndif << " #endif.\n"; 240 llvm::errs() << " " << NumPragma << " #pragma.\n"; 241 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n"; 242 243 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/" 244 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, " 245 << NumFastMacroExpanded << " on the fast path.\n"; 246 llvm::errs() << (NumFastTokenPaste+NumTokenPaste) 247 << " token paste (##) operations performed, " 248 << NumFastTokenPaste << " on the fast path.\n"; 249 250 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total"; 251 252 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory(); 253 llvm::errs() << "\n Macro Expanded Tokens: " 254 << llvm::capacity_in_bytes(MacroExpandedTokens); 255 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity(); 256 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros); 257 llvm::errs() << "\n #pragma push_macro Info: " 258 << llvm::capacity_in_bytes(PragmaPushMacroInfo); 259 llvm::errs() << "\n Poison Reasons: " 260 << llvm::capacity_in_bytes(PoisonReasons); 261 llvm::errs() << "\n Comment Handlers: " 262 << llvm::capacity_in_bytes(CommentHandlers) << "\n"; 263 } 264 265 Preprocessor::macro_iterator 266 Preprocessor::macro_begin(bool IncludeExternalMacros) const { 267 if (IncludeExternalMacros && ExternalSource && 268 !ReadMacrosFromExternalSource) { 269 ReadMacrosFromExternalSource = true; 270 ExternalSource->ReadDefinedMacros(); 271 } 272 273 return Macros.begin(); 274 } 275 276 size_t Preprocessor::getTotalMemory() const { 277 return BP.getTotalMemory() 278 + llvm::capacity_in_bytes(MacroExpandedTokens) 279 + Predefines.capacity() /* Predefines buffer. */ 280 + llvm::capacity_in_bytes(Macros) 281 + llvm::capacity_in_bytes(PragmaPushMacroInfo) 282 + llvm::capacity_in_bytes(PoisonReasons) 283 + llvm::capacity_in_bytes(CommentHandlers); 284 } 285 286 Preprocessor::macro_iterator 287 Preprocessor::macro_end(bool IncludeExternalMacros) const { 288 if (IncludeExternalMacros && ExternalSource && 289 !ReadMacrosFromExternalSource) { 290 ReadMacrosFromExternalSource = true; 291 ExternalSource->ReadDefinedMacros(); 292 } 293 294 return Macros.end(); 295 } 296 297 /// \brief Compares macro tokens with a specified token value sequence. 298 static bool MacroDefinitionEquals(const MacroInfo *MI, 299 ArrayRef<TokenValue> Tokens) { 300 return Tokens.size() == MI->getNumTokens() && 301 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin()); 302 } 303 304 StringRef Preprocessor::getLastMacroWithSpelling( 305 SourceLocation Loc, 306 ArrayRef<TokenValue> Tokens) const { 307 SourceLocation BestLocation; 308 StringRef BestSpelling; 309 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end(); 310 I != E; ++I) { 311 if (!I->second->getMacroInfo()->isObjectLike()) 312 continue; 313 const MacroDirective::DefInfo 314 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr); 315 if (!Def) 316 continue; 317 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens)) 318 continue; 319 SourceLocation Location = Def.getLocation(); 320 // Choose the macro defined latest. 321 if (BestLocation.isInvalid() || 322 (Location.isValid() && 323 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) { 324 BestLocation = Location; 325 BestSpelling = I->first->getName(); 326 } 327 } 328 return BestSpelling; 329 } 330 331 void Preprocessor::recomputeCurLexerKind() { 332 if (CurLexer) 333 CurLexerKind = CLK_Lexer; 334 else if (CurPTHLexer) 335 CurLexerKind = CLK_PTHLexer; 336 else if (CurTokenLexer) 337 CurLexerKind = CLK_TokenLexer; 338 else 339 CurLexerKind = CLK_CachingLexer; 340 } 341 342 bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File, 343 unsigned CompleteLine, 344 unsigned CompleteColumn) { 345 assert(File); 346 assert(CompleteLine && CompleteColumn && "Starts from 1:1"); 347 assert(!CodeCompletionFile && "Already set"); 348 349 using llvm::MemoryBuffer; 350 351 // Load the actual file's contents. 352 bool Invalid = false; 353 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid); 354 if (Invalid) 355 return true; 356 357 // Find the byte position of the truncation point. 358 const char *Position = Buffer->getBufferStart(); 359 for (unsigned Line = 1; Line < CompleteLine; ++Line) { 360 for (; *Position; ++Position) { 361 if (*Position != '\r' && *Position != '\n') 362 continue; 363 364 // Eat \r\n or \n\r as a single line. 365 if ((Position[1] == '\r' || Position[1] == '\n') && 366 Position[0] != Position[1]) 367 ++Position; 368 ++Position; 369 break; 370 } 371 } 372 373 Position += CompleteColumn - 1; 374 375 // Insert '\0' at the code-completion point. 376 if (Position < Buffer->getBufferEnd()) { 377 CodeCompletionFile = File; 378 CodeCompletionOffset = Position - Buffer->getBufferStart(); 379 380 MemoryBuffer *NewBuffer = 381 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1, 382 Buffer->getBufferIdentifier()); 383 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart()); 384 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf); 385 *NewPos = '\0'; 386 std::copy(Position, Buffer->getBufferEnd(), NewPos+1); 387 SourceMgr.overrideFileContents(File, NewBuffer); 388 } 389 390 return false; 391 } 392 393 void Preprocessor::CodeCompleteNaturalLanguage() { 394 if (CodeComplete) 395 CodeComplete->CodeCompleteNaturalLanguage(); 396 setCodeCompletionReached(); 397 } 398 399 /// getSpelling - This method is used to get the spelling of a token into a 400 /// SmallVector. Note that the returned StringRef may not point to the 401 /// supplied buffer if a copy can be avoided. 402 StringRef Preprocessor::getSpelling(const Token &Tok, 403 SmallVectorImpl<char> &Buffer, 404 bool *Invalid) const { 405 // NOTE: this has to be checked *before* testing for an IdentifierInfo. 406 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) { 407 // Try the fast path. 408 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) 409 return II->getName(); 410 } 411 412 // Resize the buffer if we need to copy into it. 413 if (Tok.needsCleaning()) 414 Buffer.resize(Tok.getLength()); 415 416 const char *Ptr = Buffer.data(); 417 unsigned Len = getSpelling(Tok, Ptr, Invalid); 418 return StringRef(Ptr, Len); 419 } 420 421 /// CreateString - Plop the specified string into a scratch buffer and return a 422 /// location for it. If specified, the source location provides a source 423 /// location for the token. 424 void Preprocessor::CreateString(StringRef Str, Token &Tok, 425 SourceLocation ExpansionLocStart, 426 SourceLocation ExpansionLocEnd) { 427 Tok.setLength(Str.size()); 428 429 const char *DestPtr; 430 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr); 431 432 if (ExpansionLocStart.isValid()) 433 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart, 434 ExpansionLocEnd, Str.size()); 435 Tok.setLocation(Loc); 436 437 // If this is a raw identifier or a literal token, set the pointer data. 438 if (Tok.is(tok::raw_identifier)) 439 Tok.setRawIdentifierData(DestPtr); 440 else if (Tok.isLiteral()) 441 Tok.setLiteralData(DestPtr); 442 } 443 444 Module *Preprocessor::getCurrentModule() { 445 if (getLangOpts().CurrentModule.empty()) 446 return 0; 447 448 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule); 449 } 450 451 //===----------------------------------------------------------------------===// 452 // Preprocessor Initialization Methods 453 //===----------------------------------------------------------------------===// 454 455 456 /// EnterMainSourceFile - Enter the specified FileID as the main source file, 457 /// which implicitly adds the builtin defines etc. 458 void Preprocessor::EnterMainSourceFile() { 459 // We do not allow the preprocessor to reenter the main file. Doing so will 460 // cause FileID's to accumulate information from both runs (e.g. #line 461 // information) and predefined macros aren't guaranteed to be set properly. 462 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!"); 463 FileID MainFileID = SourceMgr.getMainFileID(); 464 465 // If MainFileID is loaded it means we loaded an AST file, no need to enter 466 // a main file. 467 if (!SourceMgr.isLoadedFileID(MainFileID)) { 468 // Enter the main file source buffer. 469 EnterSourceFile(MainFileID, 0, SourceLocation()); 470 471 // If we've been asked to skip bytes in the main file (e.g., as part of a 472 // precompiled preamble), do so now. 473 if (SkipMainFilePreamble.first > 0) 474 CurLexer->SkipBytes(SkipMainFilePreamble.first, 475 SkipMainFilePreamble.second); 476 477 // Tell the header info that the main file was entered. If the file is later 478 // #imported, it won't be re-entered. 479 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID)) 480 HeaderInfo.IncrementIncludeCount(FE); 481 } 482 483 // Preprocess Predefines to populate the initial preprocessor state. 484 llvm::MemoryBuffer *SB = 485 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>"); 486 assert(SB && "Cannot create predefined source buffer"); 487 FileID FID = SourceMgr.createFileIDForMemBuffer(SB); 488 assert(!FID.isInvalid() && "Could not create FileID for predefines?"); 489 setPredefinesFileID(FID); 490 491 // Start parsing the predefines. 492 EnterSourceFile(FID, 0, SourceLocation()); 493 } 494 495 void Preprocessor::EndSourceFile() { 496 // Notify the client that we reached the end of the source file. 497 if (Callbacks) 498 Callbacks->EndOfMainFile(); 499 } 500 501 //===----------------------------------------------------------------------===// 502 // Lexer Event Handling. 503 //===----------------------------------------------------------------------===// 504 505 static void appendCodePoint(unsigned Codepoint, 506 llvm::SmallVectorImpl<char> &Str) { 507 char ResultBuf[4]; 508 char *ResultPtr = ResultBuf; 509 bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr); 510 (void)Res; 511 assert(Res && "Unexpected conversion failure"); 512 Str.append(ResultBuf, ResultPtr); 513 } 514 515 static void expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) { 516 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) { 517 if (*I != '\\') { 518 Buf.push_back(*I); 519 continue; 520 } 521 522 ++I; 523 assert(*I == 'u' || *I == 'U'); 524 525 unsigned NumHexDigits; 526 if (*I == 'u') 527 NumHexDigits = 4; 528 else 529 NumHexDigits = 8; 530 531 assert(I + NumHexDigits <= E); 532 533 uint32_t CodePoint = 0; 534 for (++I; NumHexDigits != 0; ++I, --NumHexDigits) { 535 unsigned Value = llvm::hexDigitValue(*I); 536 assert(Value != -1U); 537 538 CodePoint <<= 4; 539 CodePoint += Value; 540 } 541 542 appendCodePoint(CodePoint, Buf); 543 --I; 544 } 545 } 546 547 /// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the 548 /// identifier information for the token and install it into the token, 549 /// updating the token kind accordingly. 550 IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const { 551 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!"); 552 553 // Look up this token, see if it is a macro, or if it is a language keyword. 554 IdentifierInfo *II; 555 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) { 556 // No cleaning needed, just use the characters from the lexed buffer. 557 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(), 558 Identifier.getLength())); 559 } else { 560 // Cleaning needed, alloca a buffer, clean into it, then use the buffer. 561 SmallString<64> IdentifierBuffer; 562 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer); 563 564 if (Identifier.hasUCN()) { 565 SmallString<64> UCNIdentifierBuffer; 566 expandUCNs(UCNIdentifierBuffer, CleanedStr); 567 II = getIdentifierInfo(UCNIdentifierBuffer); 568 } else { 569 II = getIdentifierInfo(CleanedStr); 570 } 571 } 572 573 // Update the token info (identifier info and appropriate token kind). 574 Identifier.setIdentifierInfo(II); 575 Identifier.setKind(II->getTokenID()); 576 577 return II; 578 } 579 580 void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) { 581 PoisonReasons[II] = DiagID; 582 } 583 584 void Preprocessor::PoisonSEHIdentifiers(bool Poison) { 585 assert(Ident__exception_code && Ident__exception_info); 586 assert(Ident___exception_code && Ident___exception_info); 587 Ident__exception_code->setIsPoisoned(Poison); 588 Ident___exception_code->setIsPoisoned(Poison); 589 Ident_GetExceptionCode->setIsPoisoned(Poison); 590 Ident__exception_info->setIsPoisoned(Poison); 591 Ident___exception_info->setIsPoisoned(Poison); 592 Ident_GetExceptionInfo->setIsPoisoned(Poison); 593 Ident__abnormal_termination->setIsPoisoned(Poison); 594 Ident___abnormal_termination->setIsPoisoned(Poison); 595 Ident_AbnormalTermination->setIsPoisoned(Poison); 596 } 597 598 void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) { 599 assert(Identifier.getIdentifierInfo() && 600 "Can't handle identifiers without identifier info!"); 601 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it = 602 PoisonReasons.find(Identifier.getIdentifierInfo()); 603 if(it == PoisonReasons.end()) 604 Diag(Identifier, diag::err_pp_used_poisoned_id); 605 else 606 Diag(Identifier,it->second) << Identifier.getIdentifierInfo(); 607 } 608 609 /// HandleIdentifier - This callback is invoked when the lexer reads an 610 /// identifier. This callback looks up the identifier in the map and/or 611 /// potentially macro expands it or turns it into a named token (like 'for'). 612 /// 613 /// Note that callers of this method are guarded by checking the 614 /// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the 615 /// IdentifierInfo methods that compute these properties will need to change to 616 /// match. 617 void Preprocessor::HandleIdentifier(Token &Identifier) { 618 assert(Identifier.getIdentifierInfo() && 619 "Can't handle identifiers without identifier info!"); 620 621 IdentifierInfo &II = *Identifier.getIdentifierInfo(); 622 623 // If the information about this identifier is out of date, update it from 624 // the external source. 625 // We have to treat __VA_ARGS__ in a special way, since it gets 626 // serialized with isPoisoned = true, but our preprocessor may have 627 // unpoisoned it if we're defining a C99 macro. 628 if (II.isOutOfDate()) { 629 bool CurrentIsPoisoned = false; 630 if (&II == Ident__VA_ARGS__) 631 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned(); 632 633 ExternalSource->updateOutOfDateIdentifier(II); 634 Identifier.setKind(II.getTokenID()); 635 636 if (&II == Ident__VA_ARGS__) 637 II.setIsPoisoned(CurrentIsPoisoned); 638 } 639 640 // If this identifier was poisoned, and if it was not produced from a macro 641 // expansion, emit an error. 642 if (II.isPoisoned() && CurPPLexer) { 643 HandlePoisonedIdentifier(Identifier); 644 } 645 646 // If this is a macro to be expanded, do it. 647 if (MacroDirective *MD = getMacroDirective(&II)) { 648 MacroInfo *MI = MD->getMacroInfo(); 649 if (!DisableMacroExpansion) { 650 if (!Identifier.isExpandDisabled() && MI->isEnabled()) { 651 if (!HandleMacroExpandedIdentifier(Identifier, MD)) 652 return; 653 } else { 654 // C99 6.10.3.4p2 says that a disabled macro may never again be 655 // expanded, even if it's in a context where it could be expanded in the 656 // future. 657 Identifier.setFlag(Token::DisableExpand); 658 if (MI->isObjectLike() || isNextPPTokenLParen()) 659 Diag(Identifier, diag::pp_disabled_macro_expansion); 660 } 661 } 662 } 663 664 // If this identifier is a keyword in C++11, produce a warning. Don't warn if 665 // we're not considering macro expansion, since this identifier might be the 666 // name of a macro. 667 // FIXME: This warning is disabled in cases where it shouldn't be, like 668 // "#define constexpr constexpr", "int constexpr;" 669 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) { 670 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName(); 671 // Don't diagnose this keyword again in this translation unit. 672 II.setIsCXX11CompatKeyword(false); 673 } 674 675 // C++ 2.11p2: If this is an alternative representation of a C++ operator, 676 // then we act as if it is the actual operator and not the textual 677 // representation of it. 678 if (II.isCPlusPlusOperatorKeyword()) 679 Identifier.setIdentifierInfo(0); 680 681 // If this is an extension token, diagnose its use. 682 // We avoid diagnosing tokens that originate from macro definitions. 683 // FIXME: This warning is disabled in cases where it shouldn't be, 684 // like "#define TY typeof", "TY(1) x". 685 if (II.isExtensionToken() && !DisableMacroExpansion) 686 Diag(Identifier, diag::ext_token_used); 687 688 // If this is the 'import' contextual keyword, note 689 // that the next token indicates a module name. 690 // 691 // Note that we do not treat 'import' as a contextual 692 // keyword when we're in a caching lexer, because caching lexers only get 693 // used in contexts where import declarations are disallowed. 694 if (II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion && 695 getLangOpts().Modules && CurLexerKind != CLK_CachingLexer) { 696 ModuleImportLoc = Identifier.getLocation(); 697 ModuleImportPath.clear(); 698 ModuleImportExpectsIdentifier = true; 699 CurLexerKind = CLK_LexAfterModuleImport; 700 } 701 } 702 703 /// \brief Lex a token following the 'import' contextual keyword. 704 /// 705 void Preprocessor::LexAfterModuleImport(Token &Result) { 706 // Figure out what kind of lexer we actually have. 707 recomputeCurLexerKind(); 708 709 // Lex the next token. 710 Lex(Result); 711 712 // The token sequence 713 // 714 // import identifier (. identifier)* 715 // 716 // indicates a module import directive. We already saw the 'import' 717 // contextual keyword, so now we're looking for the identifiers. 718 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) { 719 // We expected to see an identifier here, and we did; continue handling 720 // identifiers. 721 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(), 722 Result.getLocation())); 723 ModuleImportExpectsIdentifier = false; 724 CurLexerKind = CLK_LexAfterModuleImport; 725 return; 726 } 727 728 // If we're expecting a '.' or a ';', and we got a '.', then wait until we 729 // see the next identifier. 730 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) { 731 ModuleImportExpectsIdentifier = true; 732 CurLexerKind = CLK_LexAfterModuleImport; 733 return; 734 } 735 736 // If we have a non-empty module path, load the named module. 737 if (!ModuleImportPath.empty() && getLangOpts().Modules) { 738 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc, 739 ModuleImportPath, 740 Module::MacrosVisible, 741 /*IsIncludeDirective=*/false); 742 if (Callbacks) 743 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported); 744 } 745 } 746 747 bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String, 748 const char *DiagnosticTag, 749 bool AllowMacroExpansion) { 750 // We need at least one string literal. 751 if (Result.isNot(tok::string_literal)) { 752 Diag(Result, diag::err_expected_string_literal) 753 << /*Source='in...'*/0 << DiagnosticTag; 754 return false; 755 } 756 757 // Lex string literal tokens, optionally with macro expansion. 758 SmallVector<Token, 4> StrToks; 759 do { 760 StrToks.push_back(Result); 761 762 if (Result.hasUDSuffix()) 763 Diag(Result, diag::err_invalid_string_udl); 764 765 if (AllowMacroExpansion) 766 Lex(Result); 767 else 768 LexUnexpandedToken(Result); 769 } while (Result.is(tok::string_literal)); 770 771 // Concatenate and parse the strings. 772 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this); 773 assert(Literal.isAscii() && "Didn't allow wide strings in"); 774 775 if (Literal.hadError) 776 return false; 777 778 if (Literal.Pascal) { 779 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal) 780 << /*Source='in...'*/0 << DiagnosticTag; 781 return false; 782 } 783 784 String = Literal.GetString(); 785 return true; 786 } 787 788 void Preprocessor::addCommentHandler(CommentHandler *Handler) { 789 assert(Handler && "NULL comment handler"); 790 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) == 791 CommentHandlers.end() && "Comment handler already registered"); 792 CommentHandlers.push_back(Handler); 793 } 794 795 void Preprocessor::removeCommentHandler(CommentHandler *Handler) { 796 std::vector<CommentHandler *>::iterator Pos 797 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler); 798 assert(Pos != CommentHandlers.end() && "Comment handler not registered"); 799 CommentHandlers.erase(Pos); 800 } 801 802 bool Preprocessor::HandleComment(Token &result, SourceRange Comment) { 803 bool AnyPendingTokens = false; 804 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(), 805 HEnd = CommentHandlers.end(); 806 H != HEnd; ++H) { 807 if ((*H)->HandleComment(*this, Comment)) 808 AnyPendingTokens = true; 809 } 810 if (!AnyPendingTokens || getCommentRetentionState()) 811 return false; 812 Lex(result); 813 return true; 814 } 815 816 ModuleLoader::~ModuleLoader() { } 817 818 CommentHandler::~CommentHandler() { } 819 820 CodeCompletionHandler::~CodeCompletionHandler() { } 821 822 void Preprocessor::createPreprocessingRecord() { 823 if (Record) 824 return; 825 826 Record = new PreprocessingRecord(getSourceManager()); 827 addPPCallbacks(Record); 828 } 829