1 //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===// 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 pieces of the Preprocessor interface that manage the 11 // current lexer stack. 12 // 13 //===----------------------------------------------------------------------===// 14 15 #include "clang/Lex/Preprocessor.h" 16 #include "clang/Basic/FileManager.h" 17 #include "clang/Basic/SourceManager.h" 18 #include "clang/Lex/HeaderSearch.h" 19 #include "clang/Lex/LexDiagnostic.h" 20 #include "clang/Lex/MacroInfo.h" 21 #include "clang/Lex/PTHManager.h" 22 #include "llvm/ADT/StringSwitch.h" 23 #include "llvm/Support/FileSystem.h" 24 #include "llvm/Support/MemoryBuffer.h" 25 #include "llvm/Support/Path.h" 26 using namespace clang; 27 28 PPCallbacks::~PPCallbacks() {} 29 30 //===----------------------------------------------------------------------===// 31 // Miscellaneous Methods. 32 //===----------------------------------------------------------------------===// 33 34 /// isInPrimaryFile - Return true if we're in the top-level file, not in a 35 /// \#include. This looks through macro expansions and active _Pragma lexers. 36 bool Preprocessor::isInPrimaryFile() const { 37 if (IsFileLexer()) 38 return IncludeMacroStack.empty(); 39 40 // If there are any stacked lexers, we're in a #include. 41 assert(IsFileLexer(IncludeMacroStack[0]) && 42 "Top level include stack isn't our primary lexer?"); 43 return std::none_of(IncludeMacroStack.begin() + 1, IncludeMacroStack.end(), 44 [this](const IncludeStackInfo &ISI) -> bool { 45 return IsFileLexer(ISI); 46 }); 47 } 48 49 /// getCurrentLexer - Return the current file lexer being lexed from. Note 50 /// that this ignores any potentially active macro expansions and _Pragma 51 /// expansions going on at the time. 52 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const { 53 if (IsFileLexer()) 54 return CurPPLexer; 55 56 // Look for a stacked lexer. 57 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) { 58 if (IsFileLexer(ISI)) 59 return ISI.ThePPLexer; 60 } 61 return nullptr; 62 } 63 64 65 //===----------------------------------------------------------------------===// 66 // Methods for Entering and Callbacks for leaving various contexts 67 //===----------------------------------------------------------------------===// 68 69 /// EnterSourceFile - Add a source file to the top of the include stack and 70 /// start lexing tokens from it instead of the current buffer. 71 bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir, 72 SourceLocation Loc) { 73 assert(!CurTokenLexer && "Cannot #include a file inside a macro!"); 74 ++NumEnteredSourceFiles; 75 76 if (MaxIncludeStackDepth < IncludeMacroStack.size()) 77 MaxIncludeStackDepth = IncludeMacroStack.size(); 78 79 if (PTH) { 80 if (PTHLexer *PL = PTH->CreateLexer(FID)) { 81 EnterSourceFileWithPTH(PL, CurDir); 82 return false; 83 } 84 } 85 86 // Get the MemoryBuffer for this FID, if it fails, we fail. 87 bool Invalid = false; 88 const llvm::MemoryBuffer *InputFile = 89 getSourceManager().getBuffer(FID, Loc, &Invalid); 90 if (Invalid) { 91 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID); 92 Diag(Loc, diag::err_pp_error_opening_file) 93 << std::string(SourceMgr.getBufferName(FileStart)) << ""; 94 return true; 95 } 96 97 if (isCodeCompletionEnabled() && 98 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) { 99 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID); 100 CodeCompletionLoc = 101 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset); 102 } 103 104 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir); 105 return false; 106 } 107 108 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack 109 /// and start lexing tokens from it instead of the current buffer. 110 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer, 111 const DirectoryLookup *CurDir) { 112 113 // Add the current lexer to the include stack. 114 if (CurPPLexer || CurTokenLexer) 115 PushIncludeMacroStack(); 116 117 CurLexer.reset(TheLexer); 118 CurPPLexer = TheLexer; 119 CurDirLookup = CurDir; 120 CurSubmodule = nullptr; 121 if (CurLexerKind != CLK_LexAfterModuleImport) 122 CurLexerKind = CLK_Lexer; 123 124 // Notify the client, if desired, that we are in a new source file. 125 if (Callbacks && !CurLexer->Is_PragmaLexer) { 126 SrcMgr::CharacteristicKind FileType = 127 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc()); 128 129 Callbacks->FileChanged(CurLexer->getFileLoc(), 130 PPCallbacks::EnterFile, FileType); 131 } 132 } 133 134 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack 135 /// and start getting tokens from it using the PTH cache. 136 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL, 137 const DirectoryLookup *CurDir) { 138 139 if (CurPPLexer || CurTokenLexer) 140 PushIncludeMacroStack(); 141 142 CurDirLookup = CurDir; 143 CurPTHLexer.reset(PL); 144 CurPPLexer = CurPTHLexer.get(); 145 CurSubmodule = nullptr; 146 if (CurLexerKind != CLK_LexAfterModuleImport) 147 CurLexerKind = CLK_PTHLexer; 148 149 // Notify the client, if desired, that we are in a new source file. 150 if (Callbacks) { 151 FileID FID = CurPPLexer->getFileID(); 152 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID); 153 SrcMgr::CharacteristicKind FileType = 154 SourceMgr.getFileCharacteristic(EnterLoc); 155 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType); 156 } 157 } 158 159 /// EnterMacro - Add a Macro to the top of the include stack and start lexing 160 /// tokens from it instead of the current buffer. 161 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd, 162 MacroInfo *Macro, MacroArgs *Args) { 163 std::unique_ptr<TokenLexer> TokLexer; 164 if (NumCachedTokenLexers == 0) { 165 TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this); 166 } else { 167 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]); 168 TokLexer->Init(Tok, ILEnd, Macro, Args); 169 } 170 171 PushIncludeMacroStack(); 172 CurDirLookup = nullptr; 173 CurTokenLexer = std::move(TokLexer); 174 if (CurLexerKind != CLK_LexAfterModuleImport) 175 CurLexerKind = CLK_TokenLexer; 176 } 177 178 /// EnterTokenStream - Add a "macro" context to the top of the include stack, 179 /// which will cause the lexer to start returning the specified tokens. 180 /// 181 /// If DisableMacroExpansion is true, tokens lexed from the token stream will 182 /// not be subject to further macro expansion. Otherwise, these tokens will 183 /// be re-macro-expanded when/if expansion is enabled. 184 /// 185 /// If OwnsTokens is false, this method assumes that the specified stream of 186 /// tokens has a permanent owner somewhere, so they do not need to be copied. 187 /// If it is true, it assumes the array of tokens is allocated with new[] and 188 /// must be freed. 189 /// 190 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks, 191 bool DisableMacroExpansion, 192 bool OwnsTokens) { 193 if (CurLexerKind == CLK_CachingLexer) { 194 if (CachedLexPos < CachedTokens.size()) { 195 // We're entering tokens into the middle of our cached token stream. We 196 // can't represent that, so just insert the tokens into the buffer. 197 CachedTokens.insert(CachedTokens.begin() + CachedLexPos, 198 Toks, Toks + NumToks); 199 if (OwnsTokens) 200 delete [] Toks; 201 return; 202 } 203 204 // New tokens are at the end of the cached token sequnece; insert the 205 // token stream underneath the caching lexer. 206 ExitCachingLexMode(); 207 EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens); 208 EnterCachingLexMode(); 209 return; 210 } 211 212 // Create a macro expander to expand from the specified token stream. 213 std::unique_ptr<TokenLexer> TokLexer; 214 if (NumCachedTokenLexers == 0) { 215 TokLexer = llvm::make_unique<TokenLexer>( 216 Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this); 217 } else { 218 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]); 219 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens); 220 } 221 222 // Save our current state. 223 PushIncludeMacroStack(); 224 CurDirLookup = nullptr; 225 CurTokenLexer = std::move(TokLexer); 226 if (CurLexerKind != CLK_LexAfterModuleImport) 227 CurLexerKind = CLK_TokenLexer; 228 } 229 230 /// \brief Compute the relative path that names the given file relative to 231 /// the given directory. 232 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir, 233 const FileEntry *File, 234 SmallString<128> &Result) { 235 Result.clear(); 236 237 StringRef FilePath = File->getDir()->getName(); 238 StringRef Path = FilePath; 239 while (!Path.empty()) { 240 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) { 241 if (CurDir == Dir) { 242 Result = FilePath.substr(Path.size()); 243 llvm::sys::path::append(Result, 244 llvm::sys::path::filename(File->getName())); 245 return; 246 } 247 } 248 249 Path = llvm::sys::path::parent_path(Path); 250 } 251 252 Result = File->getName(); 253 } 254 255 void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) { 256 if (CurTokenLexer) { 257 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result); 258 return; 259 } 260 if (CurLexer) { 261 CurLexer->PropagateLineStartLeadingSpaceInfo(Result); 262 return; 263 } 264 // FIXME: Handle other kinds of lexers? It generally shouldn't matter, 265 // but it might if they're empty? 266 } 267 268 /// \brief Determine the location to use as the end of the buffer for a lexer. 269 /// 270 /// If the file ends with a newline, form the EOF token on the newline itself, 271 /// rather than "on the line following it", which doesn't exist. This makes 272 /// diagnostics relating to the end of file include the last file that the user 273 /// actually typed, which is goodness. 274 const char *Preprocessor::getCurLexerEndPos() { 275 const char *EndPos = CurLexer->BufferEnd; 276 if (EndPos != CurLexer->BufferStart && 277 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) { 278 --EndPos; 279 280 // Handle \n\r and \r\n: 281 if (EndPos != CurLexer->BufferStart && 282 (EndPos[-1] == '\n' || EndPos[-1] == '\r') && 283 EndPos[-1] != EndPos[0]) 284 --EndPos; 285 } 286 287 return EndPos; 288 } 289 290 291 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of 292 /// the current file. This either returns the EOF token or pops a level off 293 /// the include stack and keeps going. 294 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) { 295 assert(!CurTokenLexer && 296 "Ending a file when currently in a macro!"); 297 298 // See if this file had a controlling macro. 299 if (CurPPLexer) { // Not ending a macro, ignore it. 300 if (const IdentifierInfo *ControllingMacro = 301 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) { 302 // Okay, this has a controlling macro, remember in HeaderFileInfo. 303 if (const FileEntry *FE = CurPPLexer->getFileEntry()) { 304 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro); 305 if (MacroInfo *MI = 306 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro))) 307 MI->setUsedForHeaderGuard(true); 308 if (const IdentifierInfo *DefinedMacro = 309 CurPPLexer->MIOpt.GetDefinedMacro()) { 310 if (!isMacroDefined(ControllingMacro) && 311 DefinedMacro != ControllingMacro && 312 HeaderInfo.FirstTimeLexingFile(FE)) { 313 314 // If the edit distance between the two macros is more than 50%, 315 // DefinedMacro may not be header guard, or can be header guard of 316 // another header file. Therefore, it maybe defining something 317 // completely different. This can be observed in the wild when 318 // handling feature macros or header guards in different files. 319 320 const StringRef ControllingMacroName = ControllingMacro->getName(); 321 const StringRef DefinedMacroName = DefinedMacro->getName(); 322 const size_t MaxHalfLength = std::max(ControllingMacroName.size(), 323 DefinedMacroName.size()) / 2; 324 const unsigned ED = ControllingMacroName.edit_distance( 325 DefinedMacroName, true, MaxHalfLength); 326 if (ED <= MaxHalfLength) { 327 // Emit a warning for a bad header guard. 328 Diag(CurPPLexer->MIOpt.GetMacroLocation(), 329 diag::warn_header_guard) 330 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro; 331 Diag(CurPPLexer->MIOpt.GetDefinedLocation(), 332 diag::note_header_guard) 333 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro 334 << ControllingMacro 335 << FixItHint::CreateReplacement( 336 CurPPLexer->MIOpt.GetDefinedLocation(), 337 ControllingMacro->getName()); 338 } 339 } 340 } 341 } 342 } 343 } 344 345 // Complain about reaching a true EOF within arc_cf_code_audited. 346 // We don't want to complain about reaching the end of a macro 347 // instantiation or a _Pragma. 348 if (PragmaARCCFCodeAuditedLoc.isValid() && 349 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) { 350 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited); 351 352 // Recover by leaving immediately. 353 PragmaARCCFCodeAuditedLoc = SourceLocation(); 354 } 355 356 // Complain about reaching a true EOF within assume_nonnull. 357 // We don't want to complain about reaching the end of a macro 358 // instantiation or a _Pragma. 359 if (PragmaAssumeNonNullLoc.isValid() && 360 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) { 361 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull); 362 363 // Recover by leaving immediately. 364 PragmaAssumeNonNullLoc = SourceLocation(); 365 } 366 367 // If this is a #include'd file, pop it off the include stack and continue 368 // lexing the #includer file. 369 if (!IncludeMacroStack.empty()) { 370 371 // If we lexed the code-completion file, act as if we reached EOF. 372 if (isCodeCompletionEnabled() && CurPPLexer && 373 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) == 374 CodeCompletionFileLoc) { 375 if (CurLexer) { 376 Result.startToken(); 377 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); 378 CurLexer.reset(); 379 } else { 380 assert(CurPTHLexer && "Got EOF but no current lexer set!"); 381 CurPTHLexer->getEOF(Result); 382 CurPTHLexer.reset(); 383 } 384 385 CurPPLexer = nullptr; 386 return true; 387 } 388 389 if (!isEndOfMacro && CurPPLexer && 390 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) { 391 // Notify SourceManager to record the number of FileIDs that were created 392 // during lexing of the #include'd file. 393 unsigned NumFIDs = 394 SourceMgr.local_sloc_entry_size() - 395 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/; 396 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs); 397 } 398 399 FileID ExitedFID; 400 if (Callbacks && !isEndOfMacro && CurPPLexer) 401 ExitedFID = CurPPLexer->getFileID(); 402 403 bool LeavingSubmodule = CurSubmodule && CurLexer; 404 if (LeavingSubmodule) { 405 // Notify the parser that we've left the module. 406 const char *EndPos = getCurLexerEndPos(); 407 Result.startToken(); 408 CurLexer->BufferPtr = EndPos; 409 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end); 410 Result.setAnnotationEndLoc(Result.getLocation()); 411 Result.setAnnotationValue(CurSubmodule); 412 413 // We're done with this submodule. 414 LeaveSubmodule(); 415 } 416 417 // We're done with the #included file. 418 RemoveTopOfLexerStack(); 419 420 // Propagate info about start-of-line/leading white-space/etc. 421 PropagateLineStartLeadingSpaceInfo(Result); 422 423 // Notify the client, if desired, that we are in a new source file. 424 if (Callbacks && !isEndOfMacro && CurPPLexer) { 425 SrcMgr::CharacteristicKind FileType = 426 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation()); 427 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), 428 PPCallbacks::ExitFile, FileType, ExitedFID); 429 } 430 431 // Client should lex another token unless we generated an EOM. 432 return LeavingSubmodule; 433 } 434 435 // If this is the end of the main file, form an EOF token. 436 if (CurLexer) { 437 const char *EndPos = getCurLexerEndPos(); 438 Result.startToken(); 439 CurLexer->BufferPtr = EndPos; 440 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof); 441 442 if (isCodeCompletionEnabled()) { 443 // Inserting the code-completion point increases the source buffer by 1, 444 // but the main FileID was created before inserting the point. 445 // Compensate by reducing the EOF location by 1, otherwise the location 446 // will point to the next FileID. 447 // FIXME: This is hacky, the code-completion point should probably be 448 // inserted before the main FileID is created. 449 if (CurLexer->getFileLoc() == CodeCompletionFileLoc) 450 Result.setLocation(Result.getLocation().getLocWithOffset(-1)); 451 } 452 453 if (!isIncrementalProcessingEnabled()) 454 // We're done with lexing. 455 CurLexer.reset(); 456 } else { 457 assert(CurPTHLexer && "Got EOF but no current lexer set!"); 458 CurPTHLexer->getEOF(Result); 459 CurPTHLexer.reset(); 460 } 461 462 if (!isIncrementalProcessingEnabled()) 463 CurPPLexer = nullptr; 464 465 if (TUKind == TU_Complete) { 466 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has 467 // collected all macro locations that we need to warn because they are not 468 // used. 469 for (WarnUnusedMacroLocsTy::iterator 470 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); 471 I!=E; ++I) 472 Diag(*I, diag::pp_macro_not_used); 473 } 474 475 // If we are building a module that has an umbrella header, make sure that 476 // each of the headers within the directory covered by the umbrella header 477 // was actually included by the umbrella header. 478 if (Module *Mod = getCurrentModule()) { 479 if (Mod->getUmbrellaHeader()) { 480 SourceLocation StartLoc 481 = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 482 483 if (!getDiagnostics().isIgnored(diag::warn_uncovered_module_header, 484 StartLoc)) { 485 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); 486 const DirectoryEntry *Dir = Mod->getUmbrellaDir().Entry; 487 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); 488 std::error_code EC; 489 for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End; 490 Entry != End && !EC; Entry.increment(EC)) { 491 using llvm::StringSwitch; 492 493 // Check whether this entry has an extension typically associated with 494 // headers. 495 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName())) 496 .Cases(".h", ".H", ".hh", ".hpp", true) 497 .Default(false)) 498 continue; 499 500 if (const FileEntry *Header = 501 getFileManager().getFile(Entry->getName())) 502 if (!getSourceManager().hasFileInfo(Header)) { 503 if (!ModMap.isHeaderInUnavailableModule(Header)) { 504 // Find the relative path that would access this header. 505 SmallString<128> RelativePath; 506 computeRelativePath(FileMgr, Dir, Header, RelativePath); 507 Diag(StartLoc, diag::warn_uncovered_module_header) 508 << Mod->getFullModuleName() << RelativePath; 509 } 510 } 511 } 512 } 513 } 514 } 515 516 return true; 517 } 518 519 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer 520 /// hits the end of its token stream. 521 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) { 522 assert(CurTokenLexer && !CurPPLexer && 523 "Ending a macro when currently in a #include file!"); 524 525 if (!MacroExpandingLexersStack.empty() && 526 MacroExpandingLexersStack.back().first == CurTokenLexer.get()) 527 removeCachedMacroExpandedTokensOfLastLexer(); 528 529 // Delete or cache the now-dead macro expander. 530 if (NumCachedTokenLexers == TokenLexerCacheSize) 531 CurTokenLexer.reset(); 532 else 533 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer); 534 535 // Handle this like a #include file being popped off the stack. 536 return HandleEndOfFile(Result, true); 537 } 538 539 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 540 /// lexer stack. This should only be used in situations where the current 541 /// state of the top-of-stack lexer is unknown. 542 void Preprocessor::RemoveTopOfLexerStack() { 543 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load"); 544 545 if (CurTokenLexer) { 546 // Delete or cache the now-dead macro expander. 547 if (NumCachedTokenLexers == TokenLexerCacheSize) 548 CurTokenLexer.reset(); 549 else 550 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer); 551 } 552 553 PopIncludeMacroStack(); 554 } 555 556 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 557 /// comment (/##/) in microsoft mode, this method handles updating the current 558 /// state, returning the token on the next source line. 559 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { 560 assert(CurTokenLexer && !CurPPLexer && 561 "Pasted comment can only be formed from macro"); 562 // We handle this by scanning for the closest real lexer, switching it to 563 // raw mode and preprocessor mode. This will cause it to return \n as an 564 // explicit EOD token. 565 PreprocessorLexer *FoundLexer = nullptr; 566 bool LexerWasInPPMode = false; 567 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) { 568 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer. 569 570 // Once we find a real lexer, mark it as raw mode (disabling macro 571 // expansions) and preprocessor mode (return EOD). We know that the lexer 572 // was *not* in raw mode before, because the macro that the comment came 573 // from was expanded. However, it could have already been in preprocessor 574 // mode (#if COMMENT) in which case we have to return it to that mode and 575 // return EOD. 576 FoundLexer = ISI.ThePPLexer; 577 FoundLexer->LexingRawMode = true; 578 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective; 579 FoundLexer->ParsingPreprocessorDirective = true; 580 break; 581 } 582 583 // Okay, we either found and switched over the lexer, or we didn't find a 584 // lexer. In either case, finish off the macro the comment came from, getting 585 // the next token. 586 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok); 587 588 // Discarding comments as long as we don't have EOF or EOD. This 'comments 589 // out' the rest of the line, including any tokens that came from other macros 590 // that were active, as in: 591 // #define submacro a COMMENT b 592 // submacro c 593 // which should lex to 'a' only: 'b' and 'c' should be removed. 594 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) 595 Lex(Tok); 596 597 // If we got an eod token, then we successfully found the end of the line. 598 if (Tok.is(tok::eod)) { 599 assert(FoundLexer && "Can't get end of line without an active lexer"); 600 // Restore the lexer back to normal mode instead of raw mode. 601 FoundLexer->LexingRawMode = false; 602 603 // If the lexer was already in preprocessor mode, just return the EOD token 604 // to finish the preprocessor line. 605 if (LexerWasInPPMode) return; 606 607 // Otherwise, switch out of PP mode and return the next lexed token. 608 FoundLexer->ParsingPreprocessorDirective = false; 609 return Lex(Tok); 610 } 611 612 // If we got an EOF token, then we reached the end of the token stream but 613 // didn't find an explicit \n. This can only happen if there was no lexer 614 // active (an active lexer would return EOD at EOF if there was no \n in 615 // preprocessor directive mode), so just return EOF as our token. 616 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode"); 617 } 618 619 void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc) { 620 if (!getLangOpts().ModulesLocalVisibility) { 621 // Just track that we entered this submodule. 622 BuildingSubmoduleStack.push_back(BuildingSubmoduleInfo( 623 M, ImportLoc, CurSubmoduleState, PendingModuleMacroNames.size())); 624 return; 625 } 626 627 // Resolve as much of the module definition as we can now, before we enter 628 // one of its headers. 629 // FIXME: Can we enable Complain here? 630 // FIXME: Can we do this when local visibility is disabled? 631 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); 632 ModMap.resolveExports(M, /*Complain=*/false); 633 ModMap.resolveUses(M, /*Complain=*/false); 634 ModMap.resolveConflicts(M, /*Complain=*/false); 635 636 // If this is the first time we've entered this module, set up its state. 637 auto R = Submodules.insert(std::make_pair(M, SubmoduleState())); 638 auto &State = R.first->second; 639 bool FirstTime = R.second; 640 if (FirstTime) { 641 // Determine the set of starting macros for this submodule; take these 642 // from the "null" module (the predefines buffer). 643 // 644 // FIXME: If we have local visibility but not modules enabled, the 645 // NullSubmoduleState is polluted by #defines in the top-level source 646 // file. 647 auto &StartingMacros = NullSubmoduleState.Macros; 648 649 // Restore to the starting state. 650 // FIXME: Do this lazily, when each macro name is first referenced. 651 for (auto &Macro : StartingMacros) { 652 // Skip uninteresting macros. 653 if (!Macro.second.getLatest() && 654 Macro.second.getOverriddenMacros().empty()) 655 continue; 656 657 MacroState MS(Macro.second.getLatest()); 658 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros()); 659 State.Macros.insert(std::make_pair(Macro.first, std::move(MS))); 660 } 661 } 662 663 // Track that we entered this module. 664 BuildingSubmoduleStack.push_back(BuildingSubmoduleInfo( 665 M, ImportLoc, CurSubmoduleState, PendingModuleMacroNames.size())); 666 667 // Switch to this submodule as the current submodule. 668 CurSubmoduleState = &State; 669 670 // This module is visible to itself. 671 if (FirstTime) 672 makeModuleVisible(M, ImportLoc); 673 } 674 675 bool Preprocessor::needModuleMacros() const { 676 // If we're not within a submodule, we never need to create ModuleMacros. 677 if (BuildingSubmoduleStack.empty()) 678 return false; 679 // If we are tracking module macro visibility even for textually-included 680 // headers, we need ModuleMacros. 681 if (getLangOpts().ModulesLocalVisibility) 682 return true; 683 // Otherwise, we only need module macros if we're actually compiling a module 684 // interface. 685 return getLangOpts().isCompilingModule(); 686 } 687 688 void Preprocessor::LeaveSubmodule() { 689 auto &Info = BuildingSubmoduleStack.back(); 690 691 Module *LeavingMod = Info.M; 692 SourceLocation ImportLoc = Info.ImportLoc; 693 694 if (!needModuleMacros() || 695 (!getLangOpts().ModulesLocalVisibility && 696 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) { 697 // If we don't need module macros, or this is not a module for which we 698 // are tracking macro visibility, don't build any, and preserve the list 699 // of pending names for the surrounding submodule. 700 BuildingSubmoduleStack.pop_back(); 701 makeModuleVisible(LeavingMod, ImportLoc); 702 return; 703 } 704 705 // Create ModuleMacros for any macros defined in this submodule. 706 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros; 707 for (unsigned I = Info.OuterPendingModuleMacroNames; 708 I != PendingModuleMacroNames.size(); ++I) { 709 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]); 710 if (!VisitedMacros.insert(II).second) 711 continue; 712 713 auto MacroIt = CurSubmoduleState->Macros.find(II); 714 if (MacroIt == CurSubmoduleState->Macros.end()) 715 continue; 716 auto &Macro = MacroIt->second; 717 718 // Find the starting point for the MacroDirective chain in this submodule. 719 MacroDirective *OldMD = nullptr; 720 auto *OldState = Info.OuterSubmoduleState; 721 if (getLangOpts().ModulesLocalVisibility) 722 OldState = &NullSubmoduleState; 723 if (OldState && OldState != CurSubmoduleState) { 724 // FIXME: It'd be better to start at the state from when we most recently 725 // entered this submodule, but it doesn't really matter. 726 auto &OldMacros = OldState->Macros; 727 auto OldMacroIt = OldMacros.find(II); 728 if (OldMacroIt == OldMacros.end()) 729 OldMD = nullptr; 730 else 731 OldMD = OldMacroIt->second.getLatest(); 732 } 733 734 // This module may have exported a new macro. If so, create a ModuleMacro 735 // representing that fact. 736 bool ExplicitlyPublic = false; 737 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) { 738 assert(MD && "broken macro directive chain"); 739 740 // Stop on macros defined in other submodules of this module that we 741 // #included along the way. There's no point doing this if we're 742 // tracking local submodule visibility, since there can be no such 743 // directives in our list. 744 if (!getLangOpts().ModulesLocalVisibility) { 745 Module *Mod = getModuleContainingLocation(MD->getLocation()); 746 if (Mod != LeavingMod && 747 Mod->getTopLevelModule() == LeavingMod->getTopLevelModule()) 748 break; 749 } 750 751 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) { 752 // The latest visibility directive for a name in a submodule affects 753 // all the directives that come before it. 754 if (VisMD->isPublic()) 755 ExplicitlyPublic = true; 756 else if (!ExplicitlyPublic) 757 // Private with no following public directive: not exported. 758 break; 759 } else { 760 MacroInfo *Def = nullptr; 761 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) 762 Def = DefMD->getInfo(); 763 764 // FIXME: Issue a warning if multiple headers for the same submodule 765 // define a macro, rather than silently ignoring all but the first. 766 bool IsNew; 767 // Don't bother creating a module macro if it would represent a #undef 768 // that doesn't override anything. 769 if (Def || !Macro.getOverriddenMacros().empty()) 770 addModuleMacro(LeavingMod, II, Def, 771 Macro.getOverriddenMacros(), IsNew); 772 break; 773 } 774 } 775 } 776 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames); 777 778 // FIXME: Before we leave this submodule, we should parse all the other 779 // headers within it. Otherwise, we're left with an inconsistent state 780 // where we've made the module visible but don't yet have its complete 781 // contents. 782 783 // Put back the outer module's state, if we're tracking it. 784 if (getLangOpts().ModulesLocalVisibility) 785 CurSubmoduleState = Info.OuterSubmoduleState; 786 787 BuildingSubmoduleStack.pop_back(); 788 789 // A nested #include makes the included submodule visible. 790 makeModuleVisible(LeavingMod, ImportLoc); 791 } 792