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