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