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