1 //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements pieces of the Preprocessor interface that manage the
11 // current lexer stack.
13 //===----------------------------------------------------------------------===//
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;
28 PPCallbacks::~PPCallbacks() {}
30 //===----------------------------------------------------------------------===//
31 // Miscellaneous Methods.
32 //===----------------------------------------------------------------------===//
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 {
38 return IncludeMacroStack.empty();
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);
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 {
56 // Look for a stacked lexer.
57 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
59 return ISI.ThePPLexer;
65 //===----------------------------------------------------------------------===//
66 // Methods for Entering and Callbacks for leaving various contexts
67 //===----------------------------------------------------------------------===//
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,
73 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
74 ++NumEnteredSourceFiles;
76 if (MaxIncludeStackDepth < IncludeMacroStack.size())
77 MaxIncludeStackDepth = IncludeMacroStack.size();
80 if (PTHLexer *PL = PTH->CreateLexer(FID)) {
81 EnterSourceFileWithPTH(PL, CurDir);
86 // Get the MemoryBuffer for this FID, if it fails, we fail.
88 const llvm::MemoryBuffer *InputFile =
89 getSourceManager().getBuffer(FID, Loc, &Invalid);
91 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
92 Diag(Loc, diag::err_pp_error_opening_file)
93 << std::string(SourceMgr.getBufferName(FileStart)) << "";
97 if (isCodeCompletionEnabled() &&
98 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
99 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
101 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
104 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
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) {
113 // Add the current lexer to the include stack.
114 if (CurPPLexer || CurTokenLexer)
115 PushIncludeMacroStack();
117 CurLexer.reset(TheLexer);
118 CurPPLexer = TheLexer;
119 CurDirLookup = CurDir;
120 CurSubmodule = nullptr;
121 if (CurLexerKind != CLK_LexAfterModuleImport)
122 CurLexerKind = CLK_Lexer;
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());
129 Callbacks->FileChanged(CurLexer->getFileLoc(),
130 PPCallbacks::EnterFile, FileType);
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) {
139 if (CurPPLexer || CurTokenLexer)
140 PushIncludeMacroStack();
142 CurDirLookup = CurDir;
143 CurPTHLexer.reset(PL);
144 CurPPLexer = CurPTHLexer.get();
145 CurSubmodule = nullptr;
146 if (CurLexerKind != CLK_LexAfterModuleImport)
147 CurLexerKind = CLK_PTHLexer;
149 // Notify the client, if desired, that we are in a new source file.
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);
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);
167 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
168 TokLexer->Init(Tok, ILEnd, Macro, Args);
171 PushIncludeMacroStack();
172 CurDirLookup = nullptr;
173 CurTokenLexer = std::move(TokLexer);
174 if (CurLexerKind != CLK_LexAfterModuleImport)
175 CurLexerKind = CLK_TokenLexer;
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.
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.
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
190 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
191 bool DisableMacroExpansion,
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);
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();
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);
218 TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
219 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
222 // Save our current state.
223 PushIncludeMacroStack();
224 CurDirLookup = nullptr;
225 CurTokenLexer = std::move(TokLexer);
226 if (CurLexerKind != CLK_LexAfterModuleImport)
227 CurLexerKind = CLK_TokenLexer;
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) {
237 StringRef FilePath = File->getDir()->getName();
238 StringRef Path = FilePath;
239 while (!Path.empty()) {
240 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
242 Result = FilePath.substr(Path.size());
243 llvm::sys::path::append(Result,
244 llvm::sys::path::filename(File->getName()));
249 Path = llvm::sys::path::parent_path(Path);
252 Result = File->getName();
255 void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
257 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
261 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
264 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
265 // but it might if they're empty?
268 /// \brief Determine the location to use as the end of the buffer for a lexer.
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')) {
280 // Handle \n\r and \r\n:
281 if (EndPos != CurLexer->BufferStart &&
282 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
283 EndPos[-1] != EndPos[0])
290 static void collectAllSubModulesWithUmbrellaHeader(
291 const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
292 if (Mod.getUmbrellaHeader())
293 SubMods.push_back(&Mod);
294 for (auto *M : Mod.submodules())
295 collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
298 void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
299 assert(Mod.getUmbrellaHeader() && "Module must use umbrella header");
300 SourceLocation StartLoc =
301 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
302 if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header, StartLoc))
305 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
306 const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
307 vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
309 for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End;
310 Entry != End && !EC; Entry.increment(EC)) {
311 using llvm::StringSwitch;
313 // Check whether this entry has an extension typically associated with
315 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName()))
316 .Cases(".h", ".H", ".hh", ".hpp", true)
320 if (const FileEntry *Header = getFileManager().getFile(Entry->getName()))
321 if (!getSourceManager().hasFileInfo(Header)) {
322 if (!ModMap.isHeaderInUnavailableModule(Header)) {
323 // Find the relative path that would access this header.
324 SmallString<128> RelativePath;
325 computeRelativePath(FileMgr, Dir, Header, RelativePath);
326 Diag(StartLoc, diag::warn_uncovered_module_header)
327 << Mod.getFullModuleName() << RelativePath;
333 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
334 /// the current file. This either returns the EOF token or pops a level off
335 /// the include stack and keeps going.
336 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
337 assert(!CurTokenLexer &&
338 "Ending a file when currently in a macro!");
340 // See if this file had a controlling macro.
341 if (CurPPLexer) { // Not ending a macro, ignore it.
342 if (const IdentifierInfo *ControllingMacro =
343 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
344 // Okay, this has a controlling macro, remember in HeaderFileInfo.
345 if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
346 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
348 getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
349 MI->setUsedForHeaderGuard(true);
350 if (const IdentifierInfo *DefinedMacro =
351 CurPPLexer->MIOpt.GetDefinedMacro()) {
352 if (!isMacroDefined(ControllingMacro) &&
353 DefinedMacro != ControllingMacro &&
354 HeaderInfo.FirstTimeLexingFile(FE)) {
356 // If the edit distance between the two macros is more than 50%,
357 // DefinedMacro may not be header guard, or can be header guard of
358 // another header file. Therefore, it maybe defining something
359 // completely different. This can be observed in the wild when
360 // handling feature macros or header guards in different files.
362 const StringRef ControllingMacroName = ControllingMacro->getName();
363 const StringRef DefinedMacroName = DefinedMacro->getName();
364 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
365 DefinedMacroName.size()) / 2;
366 const unsigned ED = ControllingMacroName.edit_distance(
367 DefinedMacroName, true, MaxHalfLength);
368 if (ED <= MaxHalfLength) {
369 // Emit a warning for a bad header guard.
370 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
371 diag::warn_header_guard)
372 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
373 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
374 diag::note_header_guard)
375 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
377 << FixItHint::CreateReplacement(
378 CurPPLexer->MIOpt.GetDefinedLocation(),
379 ControllingMacro->getName());
387 // Complain about reaching a true EOF within arc_cf_code_audited.
388 // We don't want to complain about reaching the end of a macro
389 // instantiation or a _Pragma.
390 if (PragmaARCCFCodeAuditedLoc.isValid() &&
391 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
392 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
394 // Recover by leaving immediately.
395 PragmaARCCFCodeAuditedLoc = SourceLocation();
398 // Complain about reaching a true EOF within assume_nonnull.
399 // We don't want to complain about reaching the end of a macro
400 // instantiation or a _Pragma.
401 if (PragmaAssumeNonNullLoc.isValid() &&
402 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
403 Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
405 // Recover by leaving immediately.
406 PragmaAssumeNonNullLoc = SourceLocation();
409 // If this is a #include'd file, pop it off the include stack and continue
410 // lexing the #includer file.
411 if (!IncludeMacroStack.empty()) {
413 // If we lexed the code-completion file, act as if we reached EOF.
414 if (isCodeCompletionEnabled() && CurPPLexer &&
415 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
416 CodeCompletionFileLoc) {
419 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
422 assert(CurPTHLexer && "Got EOF but no current lexer set!");
423 CurPTHLexer->getEOF(Result);
427 CurPPLexer = nullptr;
431 if (!isEndOfMacro && CurPPLexer &&
432 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
433 // Notify SourceManager to record the number of FileIDs that were created
434 // during lexing of the #include'd file.
436 SourceMgr.local_sloc_entry_size() -
437 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
438 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
442 if (Callbacks && !isEndOfMacro && CurPPLexer)
443 ExitedFID = CurPPLexer->getFileID();
445 bool LeavingSubmodule = CurSubmodule && CurLexer;
446 if (LeavingSubmodule) {
447 // Notify the parser that we've left the module.
448 const char *EndPos = getCurLexerEndPos();
450 CurLexer->BufferPtr = EndPos;
451 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
452 Result.setAnnotationEndLoc(Result.getLocation());
453 Result.setAnnotationValue(CurSubmodule);
455 // We're done with this submodule.
459 // We're done with the #included file.
460 RemoveTopOfLexerStack();
462 // Propagate info about start-of-line/leading white-space/etc.
463 PropagateLineStartLeadingSpaceInfo(Result);
465 // Notify the client, if desired, that we are in a new source file.
466 if (Callbacks && !isEndOfMacro && CurPPLexer) {
467 SrcMgr::CharacteristicKind FileType =
468 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
469 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
470 PPCallbacks::ExitFile, FileType, ExitedFID);
473 // Client should lex another token unless we generated an EOM.
474 return LeavingSubmodule;
477 // If this is the end of the main file, form an EOF token.
479 const char *EndPos = getCurLexerEndPos();
481 CurLexer->BufferPtr = EndPos;
482 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
484 if (isCodeCompletionEnabled()) {
485 // Inserting the code-completion point increases the source buffer by 1,
486 // but the main FileID was created before inserting the point.
487 // Compensate by reducing the EOF location by 1, otherwise the location
488 // will point to the next FileID.
489 // FIXME: This is hacky, the code-completion point should probably be
490 // inserted before the main FileID is created.
491 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
492 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
495 if (!isIncrementalProcessingEnabled())
496 // We're done with lexing.
499 assert(CurPTHLexer && "Got EOF but no current lexer set!");
500 CurPTHLexer->getEOF(Result);
504 if (!isIncrementalProcessingEnabled())
505 CurPPLexer = nullptr;
507 if (TUKind == TU_Complete) {
508 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
509 // collected all macro locations that we need to warn because they are not
511 for (WarnUnusedMacroLocsTy::iterator
512 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
514 Diag(*I, diag::pp_macro_not_used);
517 // If we are building a module that has an umbrella header, make sure that
518 // each of the headers within the directory, including all submodules, is
519 // covered by the umbrella header was actually included by the umbrella
521 if (Module *Mod = getCurrentModule()) {
522 llvm::SmallVector<const Module *, 4> AllMods;
523 collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
524 for (auto *M : AllMods)
525 diagnoseMissingHeaderInUmbrellaDir(*M);
531 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
532 /// hits the end of its token stream.
533 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
534 assert(CurTokenLexer && !CurPPLexer &&
535 "Ending a macro when currently in a #include file!");
537 if (!MacroExpandingLexersStack.empty() &&
538 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
539 removeCachedMacroExpandedTokensOfLastLexer();
541 // Delete or cache the now-dead macro expander.
542 if (NumCachedTokenLexers == TokenLexerCacheSize)
543 CurTokenLexer.reset();
545 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
547 // Handle this like a #include file being popped off the stack.
548 return HandleEndOfFile(Result, true);
551 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
552 /// lexer stack. This should only be used in situations where the current
553 /// state of the top-of-stack lexer is unknown.
554 void Preprocessor::RemoveTopOfLexerStack() {
555 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
558 // Delete or cache the now-dead macro expander.
559 if (NumCachedTokenLexers == TokenLexerCacheSize)
560 CurTokenLexer.reset();
562 TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
565 PopIncludeMacroStack();
568 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
569 /// comment (/##/) in microsoft mode, this method handles updating the current
570 /// state, returning the token on the next source line.
571 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
572 assert(CurTokenLexer && !CurPPLexer &&
573 "Pasted comment can only be formed from macro");
574 // We handle this by scanning for the closest real lexer, switching it to
575 // raw mode and preprocessor mode. This will cause it to return \n as an
576 // explicit EOD token.
577 PreprocessorLexer *FoundLexer = nullptr;
578 bool LexerWasInPPMode = false;
579 for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
580 if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
582 // Once we find a real lexer, mark it as raw mode (disabling macro
583 // expansions) and preprocessor mode (return EOD). We know that the lexer
584 // was *not* in raw mode before, because the macro that the comment came
585 // from was expanded. However, it could have already been in preprocessor
586 // mode (#if COMMENT) in which case we have to return it to that mode and
588 FoundLexer = ISI.ThePPLexer;
589 FoundLexer->LexingRawMode = true;
590 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
591 FoundLexer->ParsingPreprocessorDirective = true;
595 // Okay, we either found and switched over the lexer, or we didn't find a
596 // lexer. In either case, finish off the macro the comment came from, getting
598 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
600 // Discarding comments as long as we don't have EOF or EOD. This 'comments
601 // out' the rest of the line, including any tokens that came from other macros
602 // that were active, as in:
603 // #define submacro a COMMENT b
605 // which should lex to 'a' only: 'b' and 'c' should be removed.
606 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
609 // If we got an eod token, then we successfully found the end of the line.
610 if (Tok.is(tok::eod)) {
611 assert(FoundLexer && "Can't get end of line without an active lexer");
612 // Restore the lexer back to normal mode instead of raw mode.
613 FoundLexer->LexingRawMode = false;
615 // If the lexer was already in preprocessor mode, just return the EOD token
616 // to finish the preprocessor line.
617 if (LexerWasInPPMode) return;
619 // Otherwise, switch out of PP mode and return the next lexed token.
620 FoundLexer->ParsingPreprocessorDirective = false;
624 // If we got an EOF token, then we reached the end of the token stream but
625 // didn't find an explicit \n. This can only happen if there was no lexer
626 // active (an active lexer would return EOD at EOF if there was no \n in
627 // preprocessor directive mode), so just return EOF as our token.
628 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
631 void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc) {
632 if (!getLangOpts().ModulesLocalVisibility) {
633 // Just track that we entered this submodule.
634 BuildingSubmoduleStack.push_back(BuildingSubmoduleInfo(
635 M, ImportLoc, CurSubmoduleState, PendingModuleMacroNames.size()));
639 // Resolve as much of the module definition as we can now, before we enter
640 // one of its headers.
641 // FIXME: Can we enable Complain here?
642 // FIXME: Can we do this when local visibility is disabled?
643 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
644 ModMap.resolveExports(M, /*Complain=*/false);
645 ModMap.resolveUses(M, /*Complain=*/false);
646 ModMap.resolveConflicts(M, /*Complain=*/false);
648 // If this is the first time we've entered this module, set up its state.
649 auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
650 auto &State = R.first->second;
651 bool FirstTime = R.second;
653 // Determine the set of starting macros for this submodule; take these
654 // from the "null" module (the predefines buffer).
656 // FIXME: If we have local visibility but not modules enabled, the
657 // NullSubmoduleState is polluted by #defines in the top-level source
659 auto &StartingMacros = NullSubmoduleState.Macros;
661 // Restore to the starting state.
662 // FIXME: Do this lazily, when each macro name is first referenced.
663 for (auto &Macro : StartingMacros) {
664 // Skip uninteresting macros.
665 if (!Macro.second.getLatest() &&
666 Macro.second.getOverriddenMacros().empty())
669 MacroState MS(Macro.second.getLatest());
670 MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
671 State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
675 // Track that we entered this module.
676 BuildingSubmoduleStack.push_back(BuildingSubmoduleInfo(
677 M, ImportLoc, CurSubmoduleState, PendingModuleMacroNames.size()));
679 // Switch to this submodule as the current submodule.
680 CurSubmoduleState = &State;
682 // This module is visible to itself.
684 makeModuleVisible(M, ImportLoc);
687 bool Preprocessor::needModuleMacros() const {
688 // If we're not within a submodule, we never need to create ModuleMacros.
689 if (BuildingSubmoduleStack.empty())
691 // If we are tracking module macro visibility even for textually-included
692 // headers, we need ModuleMacros.
693 if (getLangOpts().ModulesLocalVisibility)
695 // Otherwise, we only need module macros if we're actually compiling a module
697 return getLangOpts().isCompilingModule();
700 void Preprocessor::LeaveSubmodule() {
701 auto &Info = BuildingSubmoduleStack.back();
703 Module *LeavingMod = Info.M;
704 SourceLocation ImportLoc = Info.ImportLoc;
706 if (!needModuleMacros() ||
707 (!getLangOpts().ModulesLocalVisibility &&
708 LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
709 // If we don't need module macros, or this is not a module for which we
710 // are tracking macro visibility, don't build any, and preserve the list
711 // of pending names for the surrounding submodule.
712 BuildingSubmoduleStack.pop_back();
713 makeModuleVisible(LeavingMod, ImportLoc);
717 // Create ModuleMacros for any macros defined in this submodule.
718 llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
719 for (unsigned I = Info.OuterPendingModuleMacroNames;
720 I != PendingModuleMacroNames.size(); ++I) {
721 auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
722 if (!VisitedMacros.insert(II).second)
725 auto MacroIt = CurSubmoduleState->Macros.find(II);
726 if (MacroIt == CurSubmoduleState->Macros.end())
728 auto &Macro = MacroIt->second;
730 // Find the starting point for the MacroDirective chain in this submodule.
731 MacroDirective *OldMD = nullptr;
732 auto *OldState = Info.OuterSubmoduleState;
733 if (getLangOpts().ModulesLocalVisibility)
734 OldState = &NullSubmoduleState;
735 if (OldState && OldState != CurSubmoduleState) {
736 // FIXME: It'd be better to start at the state from when we most recently
737 // entered this submodule, but it doesn't really matter.
738 auto &OldMacros = OldState->Macros;
739 auto OldMacroIt = OldMacros.find(II);
740 if (OldMacroIt == OldMacros.end())
743 OldMD = OldMacroIt->second.getLatest();
746 // This module may have exported a new macro. If so, create a ModuleMacro
747 // representing that fact.
748 bool ExplicitlyPublic = false;
749 for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
750 assert(MD && "broken macro directive chain");
752 // Stop on macros defined in other submodules of this module that we
753 // #included along the way. There's no point doing this if we're
754 // tracking local submodule visibility, since there can be no such
755 // directives in our list.
756 if (!getLangOpts().ModulesLocalVisibility) {
757 Module *Mod = getModuleContainingLocation(MD->getLocation());
758 if (Mod != LeavingMod &&
759 Mod->getTopLevelModule() == LeavingMod->getTopLevelModule())
763 if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
764 // The latest visibility directive for a name in a submodule affects
765 // all the directives that come before it.
766 if (VisMD->isPublic())
767 ExplicitlyPublic = true;
768 else if (!ExplicitlyPublic)
769 // Private with no following public directive: not exported.
772 MacroInfo *Def = nullptr;
773 if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
774 Def = DefMD->getInfo();
776 // FIXME: Issue a warning if multiple headers for the same submodule
777 // define a macro, rather than silently ignoring all but the first.
779 // Don't bother creating a module macro if it would represent a #undef
780 // that doesn't override anything.
781 if (Def || !Macro.getOverriddenMacros().empty())
782 addModuleMacro(LeavingMod, II, Def,
783 Macro.getOverriddenMacros(), IsNew);
788 PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
790 // FIXME: Before we leave this submodule, we should parse all the other
791 // headers within it. Otherwise, we're left with an inconsistent state
792 // where we've made the module visible but don't yet have its complete
795 // Put back the outer module's state, if we're tracking it.
796 if (getLangOpts().ModulesLocalVisibility)
797 CurSubmoduleState = Info.OuterSubmoduleState;
799 BuildingSubmoduleStack.pop_back();
801 // A nested #include makes the included submodule visible.
802 makeModuleVisible(LeavingMod, ImportLoc);