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->UsedForHeaderGuard = true; 308 } 309 if (const IdentifierInfo *DefinedMacro = 310 CurPPLexer->MIOpt.GetDefinedMacro()) { 311 if (!isMacroDefined(ControllingMacro) && 312 DefinedMacro != ControllingMacro && 313 HeaderInfo.FirstTimeLexingFile(FE)) { 314 315 // If the edit distance between the two macros is more than 50%, 316 // DefinedMacro may not be header guard, or can be header guard of 317 // another header file. Therefore, it maybe defining something 318 // completely different. This can be observed in the wild when 319 // handling feature macros or header guards in different files. 320 321 const StringRef ControllingMacroName = ControllingMacro->getName(); 322 const StringRef DefinedMacroName = DefinedMacro->getName(); 323 const size_t MaxHalfLength = std::max(ControllingMacroName.size(), 324 DefinedMacroName.size()) / 2; 325 const unsigned ED = ControllingMacroName.edit_distance( 326 DefinedMacroName, true, MaxHalfLength); 327 if (ED <= MaxHalfLength) { 328 // Emit a warning for a bad header guard. 329 Diag(CurPPLexer->MIOpt.GetMacroLocation(), 330 diag::warn_header_guard) 331 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro; 332 Diag(CurPPLexer->MIOpt.GetDefinedLocation(), 333 diag::note_header_guard) 334 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro 335 << ControllingMacro 336 << FixItHint::CreateReplacement( 337 CurPPLexer->MIOpt.GetDefinedLocation(), 338 ControllingMacro->getName()); 339 } 340 } 341 } 342 } 343 } 344 } 345 346 // Complain about reaching a true EOF within arc_cf_code_audited. 347 // We don't want to complain about reaching the end of a macro 348 // instantiation or a _Pragma. 349 if (PragmaARCCFCodeAuditedLoc.isValid() && 350 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) { 351 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited); 352 353 // Recover by leaving immediately. 354 PragmaARCCFCodeAuditedLoc = SourceLocation(); 355 } 356 357 // Complain about reaching a true EOF within assume_nonnull. 358 // We don't want to complain about reaching the end of a macro 359 // instantiation or a _Pragma. 360 if (PragmaAssumeNonNullLoc.isValid() && 361 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) { 362 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull); 363 364 // Recover by leaving immediately. 365 PragmaAssumeNonNullLoc = SourceLocation(); 366 } 367 368 // If this is a #include'd file, pop it off the include stack and continue 369 // lexing the #includer file. 370 if (!IncludeMacroStack.empty()) { 371 372 // If we lexed the code-completion file, act as if we reached EOF. 373 if (isCodeCompletionEnabled() && CurPPLexer && 374 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) == 375 CodeCompletionFileLoc) { 376 if (CurLexer) { 377 Result.startToken(); 378 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof); 379 CurLexer.reset(); 380 } else { 381 assert(CurPTHLexer && "Got EOF but no current lexer set!"); 382 CurPTHLexer->getEOF(Result); 383 CurPTHLexer.reset(); 384 } 385 386 CurPPLexer = nullptr; 387 return true; 388 } 389 390 if (!isEndOfMacro && CurPPLexer && 391 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) { 392 // Notify SourceManager to record the number of FileIDs that were created 393 // during lexing of the #include'd file. 394 unsigned NumFIDs = 395 SourceMgr.local_sloc_entry_size() - 396 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/; 397 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs); 398 } 399 400 FileID ExitedFID; 401 if (Callbacks && !isEndOfMacro && CurPPLexer) 402 ExitedFID = CurPPLexer->getFileID(); 403 404 bool LeavingSubmodule = CurSubmodule && CurLexer; 405 if (LeavingSubmodule) { 406 // Notify the parser that we've left the module. 407 const char *EndPos = getCurLexerEndPos(); 408 Result.startToken(); 409 CurLexer->BufferPtr = EndPos; 410 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end); 411 Result.setAnnotationEndLoc(Result.getLocation()); 412 Result.setAnnotationValue(CurSubmodule); 413 414 // We're done with this submodule. 415 LeaveSubmodule(); 416 } 417 418 // We're done with the #included file. 419 RemoveTopOfLexerStack(); 420 421 // Propagate info about start-of-line/leading white-space/etc. 422 PropagateLineStartLeadingSpaceInfo(Result); 423 424 // Notify the client, if desired, that we are in a new source file. 425 if (Callbacks && !isEndOfMacro && CurPPLexer) { 426 SrcMgr::CharacteristicKind FileType = 427 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation()); 428 Callbacks->FileChanged(CurPPLexer->getSourceLocation(), 429 PPCallbacks::ExitFile, FileType, ExitedFID); 430 } 431 432 // Client should lex another token unless we generated an EOM. 433 return LeavingSubmodule; 434 } 435 436 // If this is the end of the main file, form an EOF token. 437 if (CurLexer) { 438 const char *EndPos = getCurLexerEndPos(); 439 Result.startToken(); 440 CurLexer->BufferPtr = EndPos; 441 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof); 442 443 if (isCodeCompletionEnabled()) { 444 // Inserting the code-completion point increases the source buffer by 1, 445 // but the main FileID was created before inserting the point. 446 // Compensate by reducing the EOF location by 1, otherwise the location 447 // will point to the next FileID. 448 // FIXME: This is hacky, the code-completion point should probably be 449 // inserted before the main FileID is created. 450 if (CurLexer->getFileLoc() == CodeCompletionFileLoc) 451 Result.setLocation(Result.getLocation().getLocWithOffset(-1)); 452 } 453 454 if (!isIncrementalProcessingEnabled()) 455 // We're done with lexing. 456 CurLexer.reset(); 457 } else { 458 assert(CurPTHLexer && "Got EOF but no current lexer set!"); 459 CurPTHLexer->getEOF(Result); 460 CurPTHLexer.reset(); 461 } 462 463 if (!isIncrementalProcessingEnabled()) 464 CurPPLexer = nullptr; 465 466 if (TUKind == TU_Complete) { 467 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has 468 // collected all macro locations that we need to warn because they are not 469 // used. 470 for (WarnUnusedMacroLocsTy::iterator 471 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); 472 I!=E; ++I) 473 Diag(*I, diag::pp_macro_not_used); 474 } 475 476 // If we are building a module that has an umbrella header, make sure that 477 // each of the headers within the directory covered by the umbrella header 478 // was actually included by the umbrella header. 479 if (Module *Mod = getCurrentModule()) { 480 if (Mod->getUmbrellaHeader()) { 481 SourceLocation StartLoc 482 = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 483 484 if (!getDiagnostics().isIgnored(diag::warn_uncovered_module_header, 485 StartLoc)) { 486 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); 487 const DirectoryEntry *Dir = Mod->getUmbrellaDir().Entry; 488 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem(); 489 std::error_code EC; 490 for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End; 491 Entry != End && !EC; Entry.increment(EC)) { 492 using llvm::StringSwitch; 493 494 // Check whether this entry has an extension typically associated with 495 // headers. 496 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName())) 497 .Cases(".h", ".H", ".hh", ".hpp", true) 498 .Default(false)) 499 continue; 500 501 if (const FileEntry *Header = 502 getFileManager().getFile(Entry->getName())) 503 if (!getSourceManager().hasFileInfo(Header)) { 504 if (!ModMap.isHeaderInUnavailableModule(Header)) { 505 // Find the relative path that would access this header. 506 SmallString<128> RelativePath; 507 computeRelativePath(FileMgr, Dir, Header, RelativePath); 508 Diag(StartLoc, diag::warn_uncovered_module_header) 509 << Mod->getFullModuleName() << RelativePath; 510 } 511 } 512 } 513 } 514 } 515 } 516 517 return true; 518 } 519 520 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer 521 /// hits the end of its token stream. 522 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) { 523 assert(CurTokenLexer && !CurPPLexer && 524 "Ending a macro when currently in a #include file!"); 525 526 if (!MacroExpandingLexersStack.empty() && 527 MacroExpandingLexersStack.back().first == CurTokenLexer.get()) 528 removeCachedMacroExpandedTokensOfLastLexer(); 529 530 // Delete or cache the now-dead macro expander. 531 if (NumCachedTokenLexers == TokenLexerCacheSize) 532 CurTokenLexer.reset(); 533 else 534 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer); 535 536 // Handle this like a #include file being popped off the stack. 537 return HandleEndOfFile(Result, true); 538 } 539 540 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the 541 /// lexer stack. This should only be used in situations where the current 542 /// state of the top-of-stack lexer is unknown. 543 void Preprocessor::RemoveTopOfLexerStack() { 544 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load"); 545 546 if (CurTokenLexer) { 547 // Delete or cache the now-dead macro expander. 548 if (NumCachedTokenLexers == TokenLexerCacheSize) 549 CurTokenLexer.reset(); 550 else 551 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer); 552 } 553 554 PopIncludeMacroStack(); 555 } 556 557 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a 558 /// comment (/##/) in microsoft mode, this method handles updating the current 559 /// state, returning the token on the next source line. 560 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) { 561 assert(CurTokenLexer && !CurPPLexer && 562 "Pasted comment can only be formed from macro"); 563 // We handle this by scanning for the closest real lexer, switching it to 564 // raw mode and preprocessor mode. This will cause it to return \n as an 565 // explicit EOD token. 566 PreprocessorLexer *FoundLexer = nullptr; 567 bool LexerWasInPPMode = false; 568 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) { 569 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer. 570 571 // Once we find a real lexer, mark it as raw mode (disabling macro 572 // expansions) and preprocessor mode (return EOD). We know that the lexer 573 // was *not* in raw mode before, because the macro that the comment came 574 // from was expanded. However, it could have already been in preprocessor 575 // mode (#if COMMENT) in which case we have to return it to that mode and 576 // return EOD. 577 FoundLexer = ISI.ThePPLexer; 578 FoundLexer->LexingRawMode = true; 579 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective; 580 FoundLexer->ParsingPreprocessorDirective = true; 581 break; 582 } 583 584 // Okay, we either found and switched over the lexer, or we didn't find a 585 // lexer. In either case, finish off the macro the comment came from, getting 586 // the next token. 587 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok); 588 589 // Discarding comments as long as we don't have EOF or EOD. This 'comments 590 // out' the rest of the line, including any tokens that came from other macros 591 // that were active, as in: 592 // #define submacro a COMMENT b 593 // submacro c 594 // which should lex to 'a' only: 'b' and 'c' should be removed. 595 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof)) 596 Lex(Tok); 597 598 // If we got an eod token, then we successfully found the end of the line. 599 if (Tok.is(tok::eod)) { 600 assert(FoundLexer && "Can't get end of line without an active lexer"); 601 // Restore the lexer back to normal mode instead of raw mode. 602 FoundLexer->LexingRawMode = false; 603 604 // If the lexer was already in preprocessor mode, just return the EOD token 605 // to finish the preprocessor line. 606 if (LexerWasInPPMode) return; 607 608 // Otherwise, switch out of PP mode and return the next lexed token. 609 FoundLexer->ParsingPreprocessorDirective = false; 610 return Lex(Tok); 611 } 612 613 // If we got an EOF token, then we reached the end of the token stream but 614 // didn't find an explicit \n. This can only happen if there was no lexer 615 // active (an active lexer would return EOD at EOF if there was no \n in 616 // preprocessor directive mode), so just return EOF as our token. 617 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode"); 618 } 619 620 void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc) { 621 if (!getLangOpts().ModulesLocalVisibility) { 622 // Just track that we entered this submodule. 623 BuildingSubmoduleStack.push_back(BuildingSubmoduleInfo( 624 M, ImportLoc, CurSubmoduleState, PendingModuleMacroNames.size())); 625 return; 626 } 627 628 // Resolve as much of the module definition as we can now, before we enter 629 // one of its headers. 630 // FIXME: Can we enable Complain here? 631 // FIXME: Can we do this when local visibility is disabled? 632 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap(); 633 ModMap.resolveExports(M, /*Complain=*/false); 634 ModMap.resolveUses(M, /*Complain=*/false); 635 ModMap.resolveConflicts(M, /*Complain=*/false); 636 637 // If this is the first time we've entered this module, set up its state. 638 auto R = Submodules.insert(std::make_pair(M, SubmoduleState())); 639 auto &State = R.first->second; 640 bool FirstTime = R.second; 641 if (FirstTime) { 642 // Determine the set of starting macros for this submodule; take these 643 // from the "null" module (the predefines buffer). 644 // 645 // FIXME: If we have local visibility but not modules enabled, the 646 // NullSubmoduleState is polluted by #defines in the top-level source 647 // file. 648 auto &StartingMacros = NullSubmoduleState.Macros; 649 650 // Restore to the starting state. 651 // FIXME: Do this lazily, when each macro name is first referenced. 652 for (auto &Macro : StartingMacros) { 653 // Skip uninteresting macros. 654 if (!Macro.second.getLatest() && 655 Macro.second.getOverriddenMacros().empty()) 656 continue; 657 658 MacroState MS(Macro.second.getLatest()); 659 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros()); 660 State.Macros.insert(std::make_pair(Macro.first, std::move(MS))); 661 } 662 } 663 664 // Track that we entered this module. 665 BuildingSubmoduleStack.push_back(BuildingSubmoduleInfo( 666 M, ImportLoc, CurSubmoduleState, PendingModuleMacroNames.size())); 667 668 // Switch to this submodule as the current submodule. 669 CurSubmoduleState = &State; 670 671 // This module is visible to itself. 672 if (FirstTime) 673 makeModuleVisible(M, ImportLoc); 674 } 675 676 bool Preprocessor::needModuleMacros() const { 677 // If we're not within a submodule, we never need to create ModuleMacros. 678 if (BuildingSubmoduleStack.empty()) 679 return false; 680 // If we are tracking module macro visibility even for textually-included 681 // headers, we need ModuleMacros. 682 if (getLangOpts().ModulesLocalVisibility) 683 return true; 684 // Otherwise, we only need module macros if we're actually compiling a module 685 // interface. 686 return getLangOpts().isCompilingModule(); 687 } 688 689 void Preprocessor::LeaveSubmodule() { 690 auto &Info = BuildingSubmoduleStack.back(); 691 692 Module *LeavingMod = Info.M; 693 SourceLocation ImportLoc = Info.ImportLoc; 694 695 if (!needModuleMacros() || 696 (!getLangOpts().ModulesLocalVisibility && 697 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) { 698 // If we don't need module macros, or this is not a module for which we 699 // are tracking macro visibility, don't build any, and preserve the list 700 // of pending names for the surrounding submodule. 701 BuildingSubmoduleStack.pop_back(); 702 makeModuleVisible(LeavingMod, ImportLoc); 703 return; 704 } 705 706 // Create ModuleMacros for any macros defined in this submodule. 707 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros; 708 for (unsigned I = Info.OuterPendingModuleMacroNames; 709 I != PendingModuleMacroNames.size(); ++I) { 710 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]); 711 if (!VisitedMacros.insert(II).second) 712 continue; 713 714 auto MacroIt = CurSubmoduleState->Macros.find(II); 715 if (MacroIt == CurSubmoduleState->Macros.end()) 716 continue; 717 auto &Macro = MacroIt->second; 718 719 // Find the starting point for the MacroDirective chain in this submodule. 720 MacroDirective *OldMD = nullptr; 721 auto *OldState = Info.OuterSubmoduleState; 722 if (getLangOpts().ModulesLocalVisibility) 723 OldState = &NullSubmoduleState; 724 if (OldState && OldState != CurSubmoduleState) { 725 // FIXME: It'd be better to start at the state from when we most recently 726 // entered this submodule, but it doesn't really matter. 727 auto &OldMacros = OldState->Macros; 728 auto OldMacroIt = OldMacros.find(II); 729 if (OldMacroIt == OldMacros.end()) 730 OldMD = nullptr; 731 else 732 OldMD = OldMacroIt->second.getLatest(); 733 } 734 735 // This module may have exported a new macro. If so, create a ModuleMacro 736 // representing that fact. 737 bool ExplicitlyPublic = false; 738 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) { 739 assert(MD && "broken macro directive chain"); 740 741 // Stop on macros defined in other submodules of this module that we 742 // #included along the way. There's no point doing this if we're 743 // tracking local submodule visibility, since there can be no such 744 // directives in our list. 745 if (!getLangOpts().ModulesLocalVisibility) { 746 Module *Mod = getModuleContainingLocation(MD->getLocation()); 747 if (Mod != LeavingMod && 748 Mod->getTopLevelModule() == LeavingMod->getTopLevelModule()) 749 break; 750 } 751 752 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) { 753 // The latest visibility directive for a name in a submodule affects 754 // all the directives that come before it. 755 if (VisMD->isPublic()) 756 ExplicitlyPublic = true; 757 else if (!ExplicitlyPublic) 758 // Private with no following public directive: not exported. 759 break; 760 } else { 761 MacroInfo *Def = nullptr; 762 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD)) 763 Def = DefMD->getInfo(); 764 765 // FIXME: Issue a warning if multiple headers for the same submodule 766 // define a macro, rather than silently ignoring all but the first. 767 bool IsNew; 768 // Don't bother creating a module macro if it would represent a #undef 769 // that doesn't override anything. 770 if (Def || !Macro.getOverriddenMacros().empty()) 771 addModuleMacro(LeavingMod, II, Def, 772 Macro.getOverriddenMacros(), IsNew); 773 break; 774 } 775 } 776 } 777 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames); 778 779 // FIXME: Before we leave this submodule, we should parse all the other 780 // headers within it. Otherwise, we're left with an inconsistent state 781 // where we've made the module visible but don't yet have its complete 782 // contents. 783 784 // Put back the outer module's state, if we're tracking it. 785 if (getLangOpts().ModulesLocalVisibility) 786 CurSubmoduleState = Info.OuterSubmoduleState; 787 788 BuildingSubmoduleStack.pop_back(); 789 790 // A nested #include makes the included submodule visible. 791 makeModuleVisible(LeavingMod, ImportLoc); 792 } 793