106f32e7eSjoerg //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
206f32e7eSjoerg //
306f32e7eSjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
406f32e7eSjoerg // See https://llvm.org/LICENSE.txt for license information.
506f32e7eSjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
606f32e7eSjoerg //
706f32e7eSjoerg //===----------------------------------------------------------------------===//
806f32e7eSjoerg //
906f32e7eSjoerg // This file implements pieces of the Preprocessor interface that manage the
1006f32e7eSjoerg // current lexer stack.
1106f32e7eSjoerg //
1206f32e7eSjoerg //===----------------------------------------------------------------------===//
1306f32e7eSjoerg 
1406f32e7eSjoerg #include "clang/Basic/FileManager.h"
1506f32e7eSjoerg #include "clang/Basic/SourceManager.h"
1606f32e7eSjoerg #include "clang/Lex/HeaderSearch.h"
1706f32e7eSjoerg #include "clang/Lex/LexDiagnostic.h"
1806f32e7eSjoerg #include "clang/Lex/MacroInfo.h"
19*13fbcb42Sjoerg #include "clang/Lex/Preprocessor.h"
20*13fbcb42Sjoerg #include "clang/Lex/PreprocessorOptions.h"
2106f32e7eSjoerg #include "llvm/ADT/StringSwitch.h"
2206f32e7eSjoerg #include "llvm/Support/FileSystem.h"
23*13fbcb42Sjoerg #include "llvm/Support/MemoryBufferRef.h"
2406f32e7eSjoerg #include "llvm/Support/Path.h"
2506f32e7eSjoerg using namespace clang;
2606f32e7eSjoerg 
2706f32e7eSjoerg //===----------------------------------------------------------------------===//
2806f32e7eSjoerg // Miscellaneous Methods.
2906f32e7eSjoerg //===----------------------------------------------------------------------===//
3006f32e7eSjoerg 
3106f32e7eSjoerg /// isInPrimaryFile - Return true if we're in the top-level file, not in a
3206f32e7eSjoerg /// \#include.  This looks through macro expansions and active _Pragma lexers.
isInPrimaryFile() const3306f32e7eSjoerg bool Preprocessor::isInPrimaryFile() const {
3406f32e7eSjoerg   if (IsFileLexer())
3506f32e7eSjoerg     return IncludeMacroStack.empty();
3606f32e7eSjoerg 
3706f32e7eSjoerg   // If there are any stacked lexers, we're in a #include.
3806f32e7eSjoerg   assert(IsFileLexer(IncludeMacroStack[0]) &&
3906f32e7eSjoerg          "Top level include stack isn't our primary lexer?");
4006f32e7eSjoerg   return std::none_of(
4106f32e7eSjoerg       IncludeMacroStack.begin() + 1, IncludeMacroStack.end(),
4206f32e7eSjoerg       [&](const IncludeStackInfo &ISI) -> bool { return IsFileLexer(ISI); });
4306f32e7eSjoerg }
4406f32e7eSjoerg 
4506f32e7eSjoerg /// getCurrentLexer - Return the current file lexer being lexed from.  Note
4606f32e7eSjoerg /// that this ignores any potentially active macro expansions and _Pragma
4706f32e7eSjoerg /// expansions going on at the time.
getCurrentFileLexer() const4806f32e7eSjoerg PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
4906f32e7eSjoerg   if (IsFileLexer())
5006f32e7eSjoerg     return CurPPLexer;
5106f32e7eSjoerg 
5206f32e7eSjoerg   // Look for a stacked lexer.
5306f32e7eSjoerg   for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
5406f32e7eSjoerg     if (IsFileLexer(ISI))
5506f32e7eSjoerg       return ISI.ThePPLexer;
5606f32e7eSjoerg   }
5706f32e7eSjoerg   return nullptr;
5806f32e7eSjoerg }
5906f32e7eSjoerg 
6006f32e7eSjoerg 
6106f32e7eSjoerg //===----------------------------------------------------------------------===//
6206f32e7eSjoerg // Methods for Entering and Callbacks for leaving various contexts
6306f32e7eSjoerg //===----------------------------------------------------------------------===//
6406f32e7eSjoerg 
6506f32e7eSjoerg /// EnterSourceFile - Add a source file to the top of the include stack and
6606f32e7eSjoerg /// start lexing tokens from it instead of the current buffer.
EnterSourceFile(FileID FID,const DirectoryLookup * CurDir,SourceLocation Loc)6706f32e7eSjoerg bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
6806f32e7eSjoerg                                    SourceLocation Loc) {
6906f32e7eSjoerg   assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
7006f32e7eSjoerg   ++NumEnteredSourceFiles;
7106f32e7eSjoerg 
7206f32e7eSjoerg   if (MaxIncludeStackDepth < IncludeMacroStack.size())
7306f32e7eSjoerg     MaxIncludeStackDepth = IncludeMacroStack.size();
7406f32e7eSjoerg 
7506f32e7eSjoerg   // Get the MemoryBuffer for this FID, if it fails, we fail.
76*13fbcb42Sjoerg   llvm::Optional<llvm::MemoryBufferRef> InputFile =
77*13fbcb42Sjoerg       getSourceManager().getBufferOrNone(FID, Loc);
78*13fbcb42Sjoerg   if (!InputFile) {
7906f32e7eSjoerg     SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
8006f32e7eSjoerg     Diag(Loc, diag::err_pp_error_opening_file)
8106f32e7eSjoerg         << std::string(SourceMgr.getBufferName(FileStart)) << "";
8206f32e7eSjoerg     return true;
8306f32e7eSjoerg   }
8406f32e7eSjoerg 
8506f32e7eSjoerg   if (isCodeCompletionEnabled() &&
8606f32e7eSjoerg       SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
8706f32e7eSjoerg     CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
8806f32e7eSjoerg     CodeCompletionLoc =
8906f32e7eSjoerg         CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
9006f32e7eSjoerg   }
9106f32e7eSjoerg 
92*13fbcb42Sjoerg   EnterSourceFileWithLexer(new Lexer(FID, *InputFile, *this), CurDir);
9306f32e7eSjoerg   return false;
9406f32e7eSjoerg }
9506f32e7eSjoerg 
9606f32e7eSjoerg /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
9706f32e7eSjoerg ///  and start lexing tokens from it instead of the current buffer.
EnterSourceFileWithLexer(Lexer * TheLexer,const DirectoryLookup * CurDir)9806f32e7eSjoerg void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
9906f32e7eSjoerg                                             const DirectoryLookup *CurDir) {
10006f32e7eSjoerg 
10106f32e7eSjoerg   // Add the current lexer to the include stack.
10206f32e7eSjoerg   if (CurPPLexer || CurTokenLexer)
10306f32e7eSjoerg     PushIncludeMacroStack();
10406f32e7eSjoerg 
10506f32e7eSjoerg   CurLexer.reset(TheLexer);
10606f32e7eSjoerg   CurPPLexer = TheLexer;
10706f32e7eSjoerg   CurDirLookup = CurDir;
10806f32e7eSjoerg   CurLexerSubmodule = nullptr;
10906f32e7eSjoerg   if (CurLexerKind != CLK_LexAfterModuleImport)
11006f32e7eSjoerg     CurLexerKind = CLK_Lexer;
11106f32e7eSjoerg 
11206f32e7eSjoerg   // Notify the client, if desired, that we are in a new source file.
11306f32e7eSjoerg   if (Callbacks && !CurLexer->Is_PragmaLexer) {
11406f32e7eSjoerg     SrcMgr::CharacteristicKind FileType =
11506f32e7eSjoerg        SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
11606f32e7eSjoerg 
11706f32e7eSjoerg     Callbacks->FileChanged(CurLexer->getFileLoc(),
11806f32e7eSjoerg                            PPCallbacks::EnterFile, FileType);
11906f32e7eSjoerg   }
12006f32e7eSjoerg }
12106f32e7eSjoerg 
12206f32e7eSjoerg /// EnterMacro - Add a Macro to the top of the include stack and start lexing
12306f32e7eSjoerg /// tokens from it instead of the current buffer.
EnterMacro(Token & Tok,SourceLocation ILEnd,MacroInfo * Macro,MacroArgs * Args)12406f32e7eSjoerg void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
12506f32e7eSjoerg                               MacroInfo *Macro, MacroArgs *Args) {
12606f32e7eSjoerg   std::unique_ptr<TokenLexer> TokLexer;
12706f32e7eSjoerg   if (NumCachedTokenLexers == 0) {
12806f32e7eSjoerg     TokLexer = std::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
12906f32e7eSjoerg   } else {
13006f32e7eSjoerg     TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
13106f32e7eSjoerg     TokLexer->Init(Tok, ILEnd, Macro, Args);
13206f32e7eSjoerg   }
13306f32e7eSjoerg 
13406f32e7eSjoerg   PushIncludeMacroStack();
13506f32e7eSjoerg   CurDirLookup = nullptr;
13606f32e7eSjoerg   CurTokenLexer = std::move(TokLexer);
13706f32e7eSjoerg   if (CurLexerKind != CLK_LexAfterModuleImport)
13806f32e7eSjoerg     CurLexerKind = CLK_TokenLexer;
13906f32e7eSjoerg }
14006f32e7eSjoerg 
14106f32e7eSjoerg /// EnterTokenStream - Add a "macro" context to the top of the include stack,
14206f32e7eSjoerg /// which will cause the lexer to start returning the specified tokens.
14306f32e7eSjoerg ///
14406f32e7eSjoerg /// If DisableMacroExpansion is true, tokens lexed from the token stream will
14506f32e7eSjoerg /// not be subject to further macro expansion.  Otherwise, these tokens will
14606f32e7eSjoerg /// be re-macro-expanded when/if expansion is enabled.
14706f32e7eSjoerg ///
14806f32e7eSjoerg /// If OwnsTokens is false, this method assumes that the specified stream of
14906f32e7eSjoerg /// tokens has a permanent owner somewhere, so they do not need to be copied.
15006f32e7eSjoerg /// If it is true, it assumes the array of tokens is allocated with new[] and
15106f32e7eSjoerg /// must be freed.
15206f32e7eSjoerg ///
EnterTokenStream(const Token * Toks,unsigned NumToks,bool DisableMacroExpansion,bool OwnsTokens,bool IsReinject)15306f32e7eSjoerg void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
15406f32e7eSjoerg                                     bool DisableMacroExpansion, bool OwnsTokens,
15506f32e7eSjoerg                                     bool IsReinject) {
15606f32e7eSjoerg   if (CurLexerKind == CLK_CachingLexer) {
15706f32e7eSjoerg     if (CachedLexPos < CachedTokens.size()) {
15806f32e7eSjoerg       assert(IsReinject && "new tokens in the middle of cached stream");
15906f32e7eSjoerg       // We're entering tokens into the middle of our cached token stream. We
16006f32e7eSjoerg       // can't represent that, so just insert the tokens into the buffer.
16106f32e7eSjoerg       CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
16206f32e7eSjoerg                           Toks, Toks + NumToks);
16306f32e7eSjoerg       if (OwnsTokens)
16406f32e7eSjoerg         delete [] Toks;
16506f32e7eSjoerg       return;
16606f32e7eSjoerg     }
16706f32e7eSjoerg 
16806f32e7eSjoerg     // New tokens are at the end of the cached token sequnece; insert the
16906f32e7eSjoerg     // token stream underneath the caching lexer.
17006f32e7eSjoerg     ExitCachingLexMode();
17106f32e7eSjoerg     EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
17206f32e7eSjoerg                      IsReinject);
17306f32e7eSjoerg     EnterCachingLexMode();
17406f32e7eSjoerg     return;
17506f32e7eSjoerg   }
17606f32e7eSjoerg 
17706f32e7eSjoerg   // Create a macro expander to expand from the specified token stream.
17806f32e7eSjoerg   std::unique_ptr<TokenLexer> TokLexer;
17906f32e7eSjoerg   if (NumCachedTokenLexers == 0) {
18006f32e7eSjoerg     TokLexer = std::make_unique<TokenLexer>(
18106f32e7eSjoerg         Toks, NumToks, DisableMacroExpansion, OwnsTokens, IsReinject, *this);
18206f32e7eSjoerg   } else {
18306f32e7eSjoerg     TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
18406f32e7eSjoerg     TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens,
18506f32e7eSjoerg                    IsReinject);
18606f32e7eSjoerg   }
18706f32e7eSjoerg 
18806f32e7eSjoerg   // Save our current state.
18906f32e7eSjoerg   PushIncludeMacroStack();
19006f32e7eSjoerg   CurDirLookup = nullptr;
19106f32e7eSjoerg   CurTokenLexer = std::move(TokLexer);
19206f32e7eSjoerg   if (CurLexerKind != CLK_LexAfterModuleImport)
19306f32e7eSjoerg     CurLexerKind = CLK_TokenLexer;
19406f32e7eSjoerg }
19506f32e7eSjoerg 
19606f32e7eSjoerg /// Compute the relative path that names the given file relative to
19706f32e7eSjoerg /// the given directory.
computeRelativePath(FileManager & FM,const DirectoryEntry * Dir,const FileEntry * File,SmallString<128> & Result)19806f32e7eSjoerg static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
19906f32e7eSjoerg                                 const FileEntry *File,
20006f32e7eSjoerg                                 SmallString<128> &Result) {
20106f32e7eSjoerg   Result.clear();
20206f32e7eSjoerg 
20306f32e7eSjoerg   StringRef FilePath = File->getDir()->getName();
20406f32e7eSjoerg   StringRef Path = FilePath;
20506f32e7eSjoerg   while (!Path.empty()) {
20606f32e7eSjoerg     if (auto CurDir = FM.getDirectory(Path)) {
20706f32e7eSjoerg       if (*CurDir == Dir) {
20806f32e7eSjoerg         Result = FilePath.substr(Path.size());
20906f32e7eSjoerg         llvm::sys::path::append(Result,
21006f32e7eSjoerg                                 llvm::sys::path::filename(File->getName()));
21106f32e7eSjoerg         return;
21206f32e7eSjoerg       }
21306f32e7eSjoerg     }
21406f32e7eSjoerg 
21506f32e7eSjoerg     Path = llvm::sys::path::parent_path(Path);
21606f32e7eSjoerg   }
21706f32e7eSjoerg 
21806f32e7eSjoerg   Result = File->getName();
21906f32e7eSjoerg }
22006f32e7eSjoerg 
PropagateLineStartLeadingSpaceInfo(Token & Result)22106f32e7eSjoerg void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
22206f32e7eSjoerg   if (CurTokenLexer) {
22306f32e7eSjoerg     CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
22406f32e7eSjoerg     return;
22506f32e7eSjoerg   }
22606f32e7eSjoerg   if (CurLexer) {
22706f32e7eSjoerg     CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
22806f32e7eSjoerg     return;
22906f32e7eSjoerg   }
23006f32e7eSjoerg   // FIXME: Handle other kinds of lexers?  It generally shouldn't matter,
23106f32e7eSjoerg   // but it might if they're empty?
23206f32e7eSjoerg }
23306f32e7eSjoerg 
23406f32e7eSjoerg /// Determine the location to use as the end of the buffer for a lexer.
23506f32e7eSjoerg ///
23606f32e7eSjoerg /// If the file ends with a newline, form the EOF token on the newline itself,
23706f32e7eSjoerg /// rather than "on the line following it", which doesn't exist.  This makes
23806f32e7eSjoerg /// diagnostics relating to the end of file include the last file that the user
23906f32e7eSjoerg /// actually typed, which is goodness.
getCurLexerEndPos()24006f32e7eSjoerg const char *Preprocessor::getCurLexerEndPos() {
24106f32e7eSjoerg   const char *EndPos = CurLexer->BufferEnd;
24206f32e7eSjoerg   if (EndPos != CurLexer->BufferStart &&
24306f32e7eSjoerg       (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
24406f32e7eSjoerg     --EndPos;
24506f32e7eSjoerg 
24606f32e7eSjoerg     // Handle \n\r and \r\n:
24706f32e7eSjoerg     if (EndPos != CurLexer->BufferStart &&
24806f32e7eSjoerg         (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
24906f32e7eSjoerg         EndPos[-1] != EndPos[0])
25006f32e7eSjoerg       --EndPos;
25106f32e7eSjoerg   }
25206f32e7eSjoerg 
25306f32e7eSjoerg   return EndPos;
25406f32e7eSjoerg }
25506f32e7eSjoerg 
collectAllSubModulesWithUmbrellaHeader(const Module & Mod,SmallVectorImpl<const Module * > & SubMods)25606f32e7eSjoerg static void collectAllSubModulesWithUmbrellaHeader(
25706f32e7eSjoerg     const Module &Mod, SmallVectorImpl<const Module *> &SubMods) {
25806f32e7eSjoerg   if (Mod.getUmbrellaHeader())
25906f32e7eSjoerg     SubMods.push_back(&Mod);
26006f32e7eSjoerg   for (auto *M : Mod.submodules())
26106f32e7eSjoerg     collectAllSubModulesWithUmbrellaHeader(*M, SubMods);
26206f32e7eSjoerg }
26306f32e7eSjoerg 
diagnoseMissingHeaderInUmbrellaDir(const Module & Mod)26406f32e7eSjoerg void Preprocessor::diagnoseMissingHeaderInUmbrellaDir(const Module &Mod) {
265*13fbcb42Sjoerg   const Module::Header &UmbrellaHeader = Mod.getUmbrellaHeader();
266*13fbcb42Sjoerg   assert(UmbrellaHeader.Entry && "Module must use umbrella header");
267*13fbcb42Sjoerg   const FileID &File = SourceMgr.translateFile(UmbrellaHeader.Entry);
268*13fbcb42Sjoerg   SourceLocation ExpectedHeadersLoc = SourceMgr.getLocForEndOfFile(File);
269*13fbcb42Sjoerg   if (getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
270*13fbcb42Sjoerg                                  ExpectedHeadersLoc))
27106f32e7eSjoerg     return;
27206f32e7eSjoerg 
27306f32e7eSjoerg   ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
27406f32e7eSjoerg   const DirectoryEntry *Dir = Mod.getUmbrellaDir().Entry;
27506f32e7eSjoerg   llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
27606f32e7eSjoerg   std::error_code EC;
27706f32e7eSjoerg   for (llvm::vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC),
27806f32e7eSjoerg        End;
27906f32e7eSjoerg        Entry != End && !EC; Entry.increment(EC)) {
28006f32e7eSjoerg     using llvm::StringSwitch;
28106f32e7eSjoerg 
28206f32e7eSjoerg     // Check whether this entry has an extension typically associated with
28306f32e7eSjoerg     // headers.
28406f32e7eSjoerg     if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
28506f32e7eSjoerg              .Cases(".h", ".H", ".hh", ".hpp", true)
28606f32e7eSjoerg              .Default(false))
28706f32e7eSjoerg       continue;
28806f32e7eSjoerg 
28906f32e7eSjoerg     if (auto Header = getFileManager().getFile(Entry->path()))
29006f32e7eSjoerg       if (!getSourceManager().hasFileInfo(*Header)) {
29106f32e7eSjoerg         if (!ModMap.isHeaderInUnavailableModule(*Header)) {
29206f32e7eSjoerg           // Find the relative path that would access this header.
29306f32e7eSjoerg           SmallString<128> RelativePath;
29406f32e7eSjoerg           computeRelativePath(FileMgr, Dir, *Header, RelativePath);
295*13fbcb42Sjoerg           Diag(ExpectedHeadersLoc, diag::warn_uncovered_module_header)
29606f32e7eSjoerg               << Mod.getFullModuleName() << RelativePath;
29706f32e7eSjoerg         }
29806f32e7eSjoerg       }
29906f32e7eSjoerg   }
30006f32e7eSjoerg }
30106f32e7eSjoerg 
30206f32e7eSjoerg /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
30306f32e7eSjoerg /// the current file.  This either returns the EOF token or pops a level off
30406f32e7eSjoerg /// the include stack and keeps going.
HandleEndOfFile(Token & Result,bool isEndOfMacro)30506f32e7eSjoerg bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
30606f32e7eSjoerg   assert(!CurTokenLexer &&
30706f32e7eSjoerg          "Ending a file when currently in a macro!");
30806f32e7eSjoerg 
30906f32e7eSjoerg   // If we have an unclosed module region from a pragma at the end of a
31006f32e7eSjoerg   // module, complain and close it now.
31106f32e7eSjoerg   const bool LeavingSubmodule = CurLexer && CurLexerSubmodule;
31206f32e7eSjoerg   if ((LeavingSubmodule || IncludeMacroStack.empty()) &&
31306f32e7eSjoerg       !BuildingSubmoduleStack.empty() &&
31406f32e7eSjoerg       BuildingSubmoduleStack.back().IsPragma) {
31506f32e7eSjoerg     Diag(BuildingSubmoduleStack.back().ImportLoc,
31606f32e7eSjoerg          diag::err_pp_module_begin_without_module_end);
31706f32e7eSjoerg     Module *M = LeaveSubmodule(/*ForPragma*/true);
31806f32e7eSjoerg 
31906f32e7eSjoerg     Result.startToken();
32006f32e7eSjoerg     const char *EndPos = getCurLexerEndPos();
32106f32e7eSjoerg     CurLexer->BufferPtr = EndPos;
32206f32e7eSjoerg     CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
32306f32e7eSjoerg     Result.setAnnotationEndLoc(Result.getLocation());
32406f32e7eSjoerg     Result.setAnnotationValue(M);
32506f32e7eSjoerg     return true;
32606f32e7eSjoerg   }
32706f32e7eSjoerg 
32806f32e7eSjoerg   // See if this file had a controlling macro.
32906f32e7eSjoerg   if (CurPPLexer) {  // Not ending a macro, ignore it.
33006f32e7eSjoerg     if (const IdentifierInfo *ControllingMacro =
33106f32e7eSjoerg           CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
33206f32e7eSjoerg       // Okay, this has a controlling macro, remember in HeaderFileInfo.
33306f32e7eSjoerg       if (const FileEntry *FE = CurPPLexer->getFileEntry()) {
33406f32e7eSjoerg         HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
33506f32e7eSjoerg         if (MacroInfo *MI =
33606f32e7eSjoerg               getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro)))
33706f32e7eSjoerg           MI->setUsedForHeaderGuard(true);
33806f32e7eSjoerg         if (const IdentifierInfo *DefinedMacro =
33906f32e7eSjoerg               CurPPLexer->MIOpt.GetDefinedMacro()) {
34006f32e7eSjoerg           if (!isMacroDefined(ControllingMacro) &&
34106f32e7eSjoerg               DefinedMacro != ControllingMacro &&
34206f32e7eSjoerg               HeaderInfo.FirstTimeLexingFile(FE)) {
34306f32e7eSjoerg 
34406f32e7eSjoerg             // If the edit distance between the two macros is more than 50%,
34506f32e7eSjoerg             // DefinedMacro may not be header guard, or can be header guard of
34606f32e7eSjoerg             // another header file. Therefore, it maybe defining something
34706f32e7eSjoerg             // completely different. This can be observed in the wild when
34806f32e7eSjoerg             // handling feature macros or header guards in different files.
34906f32e7eSjoerg 
35006f32e7eSjoerg             const StringRef ControllingMacroName = ControllingMacro->getName();
35106f32e7eSjoerg             const StringRef DefinedMacroName = DefinedMacro->getName();
35206f32e7eSjoerg             const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
35306f32e7eSjoerg                                                   DefinedMacroName.size()) / 2;
35406f32e7eSjoerg             const unsigned ED = ControllingMacroName.edit_distance(
35506f32e7eSjoerg                 DefinedMacroName, true, MaxHalfLength);
35606f32e7eSjoerg             if (ED <= MaxHalfLength) {
35706f32e7eSjoerg               // Emit a warning for a bad header guard.
35806f32e7eSjoerg               Diag(CurPPLexer->MIOpt.GetMacroLocation(),
35906f32e7eSjoerg                    diag::warn_header_guard)
36006f32e7eSjoerg                   << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
36106f32e7eSjoerg               Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
36206f32e7eSjoerg                    diag::note_header_guard)
36306f32e7eSjoerg                   << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
36406f32e7eSjoerg                   << ControllingMacro
36506f32e7eSjoerg                   << FixItHint::CreateReplacement(
36606f32e7eSjoerg                          CurPPLexer->MIOpt.GetDefinedLocation(),
36706f32e7eSjoerg                          ControllingMacro->getName());
36806f32e7eSjoerg             }
36906f32e7eSjoerg           }
37006f32e7eSjoerg         }
37106f32e7eSjoerg       }
37206f32e7eSjoerg     }
37306f32e7eSjoerg   }
37406f32e7eSjoerg 
37506f32e7eSjoerg   // Complain about reaching a true EOF within arc_cf_code_audited.
37606f32e7eSjoerg   // We don't want to complain about reaching the end of a macro
37706f32e7eSjoerg   // instantiation or a _Pragma.
37806f32e7eSjoerg   if (PragmaARCCFCodeAuditedInfo.second.isValid() && !isEndOfMacro &&
37906f32e7eSjoerg       !(CurLexer && CurLexer->Is_PragmaLexer)) {
38006f32e7eSjoerg     Diag(PragmaARCCFCodeAuditedInfo.second,
38106f32e7eSjoerg          diag::err_pp_eof_in_arc_cf_code_audited);
38206f32e7eSjoerg 
38306f32e7eSjoerg     // Recover by leaving immediately.
38406f32e7eSjoerg     PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
38506f32e7eSjoerg   }
38606f32e7eSjoerg 
38706f32e7eSjoerg   // Complain about reaching a true EOF within assume_nonnull.
38806f32e7eSjoerg   // We don't want to complain about reaching the end of a macro
38906f32e7eSjoerg   // instantiation or a _Pragma.
39006f32e7eSjoerg   if (PragmaAssumeNonNullLoc.isValid() &&
39106f32e7eSjoerg       !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
39206f32e7eSjoerg     Diag(PragmaAssumeNonNullLoc, diag::err_pp_eof_in_assume_nonnull);
39306f32e7eSjoerg 
39406f32e7eSjoerg     // Recover by leaving immediately.
39506f32e7eSjoerg     PragmaAssumeNonNullLoc = SourceLocation();
39606f32e7eSjoerg   }
39706f32e7eSjoerg 
39806f32e7eSjoerg   bool LeavingPCHThroughHeader = false;
39906f32e7eSjoerg 
40006f32e7eSjoerg   // If this is a #include'd file, pop it off the include stack and continue
40106f32e7eSjoerg   // lexing the #includer file.
40206f32e7eSjoerg   if (!IncludeMacroStack.empty()) {
40306f32e7eSjoerg 
40406f32e7eSjoerg     // If we lexed the code-completion file, act as if we reached EOF.
40506f32e7eSjoerg     if (isCodeCompletionEnabled() && CurPPLexer &&
40606f32e7eSjoerg         SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
40706f32e7eSjoerg             CodeCompletionFileLoc) {
40806f32e7eSjoerg       assert(CurLexer && "Got EOF but no current lexer set!");
40906f32e7eSjoerg       Result.startToken();
41006f32e7eSjoerg       CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
41106f32e7eSjoerg       CurLexer.reset();
41206f32e7eSjoerg 
41306f32e7eSjoerg       CurPPLexer = nullptr;
41406f32e7eSjoerg       recomputeCurLexerKind();
41506f32e7eSjoerg       return true;
41606f32e7eSjoerg     }
41706f32e7eSjoerg 
41806f32e7eSjoerg     if (!isEndOfMacro && CurPPLexer &&
419*13fbcb42Sjoerg         (SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid() ||
420*13fbcb42Sjoerg          // Predefines file doesn't have a valid include location.
421*13fbcb42Sjoerg          (PredefinesFileID.isValid() &&
422*13fbcb42Sjoerg           CurPPLexer->getFileID() == PredefinesFileID))) {
42306f32e7eSjoerg       // Notify SourceManager to record the number of FileIDs that were created
42406f32e7eSjoerg       // during lexing of the #include'd file.
42506f32e7eSjoerg       unsigned NumFIDs =
42606f32e7eSjoerg           SourceMgr.local_sloc_entry_size() -
42706f32e7eSjoerg           CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
42806f32e7eSjoerg       SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
42906f32e7eSjoerg     }
43006f32e7eSjoerg 
43106f32e7eSjoerg     bool ExitedFromPredefinesFile = false;
43206f32e7eSjoerg     FileID ExitedFID;
43306f32e7eSjoerg     if (!isEndOfMacro && CurPPLexer) {
43406f32e7eSjoerg       ExitedFID = CurPPLexer->getFileID();
43506f32e7eSjoerg 
43606f32e7eSjoerg       assert(PredefinesFileID.isValid() &&
43706f32e7eSjoerg              "HandleEndOfFile is called before PredefinesFileId is set");
43806f32e7eSjoerg       ExitedFromPredefinesFile = (PredefinesFileID == ExitedFID);
43906f32e7eSjoerg     }
44006f32e7eSjoerg 
44106f32e7eSjoerg     if (LeavingSubmodule) {
44206f32e7eSjoerg       // We're done with this submodule.
44306f32e7eSjoerg       Module *M = LeaveSubmodule(/*ForPragma*/false);
44406f32e7eSjoerg 
44506f32e7eSjoerg       // Notify the parser that we've left the module.
44606f32e7eSjoerg       const char *EndPos = getCurLexerEndPos();
44706f32e7eSjoerg       Result.startToken();
44806f32e7eSjoerg       CurLexer->BufferPtr = EndPos;
44906f32e7eSjoerg       CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
45006f32e7eSjoerg       Result.setAnnotationEndLoc(Result.getLocation());
45106f32e7eSjoerg       Result.setAnnotationValue(M);
45206f32e7eSjoerg     }
45306f32e7eSjoerg 
45406f32e7eSjoerg     bool FoundPCHThroughHeader = false;
45506f32e7eSjoerg     if (CurPPLexer && creatingPCHWithThroughHeader() &&
45606f32e7eSjoerg         isPCHThroughHeader(
45706f32e7eSjoerg             SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
45806f32e7eSjoerg       FoundPCHThroughHeader = true;
45906f32e7eSjoerg 
46006f32e7eSjoerg     // We're done with the #included file.
46106f32e7eSjoerg     RemoveTopOfLexerStack();
46206f32e7eSjoerg 
46306f32e7eSjoerg     // Propagate info about start-of-line/leading white-space/etc.
46406f32e7eSjoerg     PropagateLineStartLeadingSpaceInfo(Result);
46506f32e7eSjoerg 
46606f32e7eSjoerg     // Notify the client, if desired, that we are in a new source file.
46706f32e7eSjoerg     if (Callbacks && !isEndOfMacro && CurPPLexer) {
46806f32e7eSjoerg       SrcMgr::CharacteristicKind FileType =
46906f32e7eSjoerg         SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
47006f32e7eSjoerg       Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
47106f32e7eSjoerg                              PPCallbacks::ExitFile, FileType, ExitedFID);
47206f32e7eSjoerg     }
47306f32e7eSjoerg 
47406f32e7eSjoerg     // Restore conditional stack from the preamble right after exiting from the
47506f32e7eSjoerg     // predefines file.
47606f32e7eSjoerg     if (ExitedFromPredefinesFile)
47706f32e7eSjoerg       replayPreambleConditionalStack();
47806f32e7eSjoerg 
47906f32e7eSjoerg     if (!isEndOfMacro && CurPPLexer && FoundPCHThroughHeader &&
48006f32e7eSjoerg         (isInPrimaryFile() ||
48106f32e7eSjoerg          CurPPLexer->getFileID() == getPredefinesFileID())) {
48206f32e7eSjoerg       // Leaving the through header. Continue directly to end of main file
48306f32e7eSjoerg       // processing.
48406f32e7eSjoerg       LeavingPCHThroughHeader = true;
48506f32e7eSjoerg     } else {
48606f32e7eSjoerg       // Client should lex another token unless we generated an EOM.
48706f32e7eSjoerg       return LeavingSubmodule;
48806f32e7eSjoerg     }
48906f32e7eSjoerg   }
49006f32e7eSjoerg 
49106f32e7eSjoerg   // If this is the end of the main file, form an EOF token.
49206f32e7eSjoerg   assert(CurLexer && "Got EOF but no current lexer set!");
49306f32e7eSjoerg   const char *EndPos = getCurLexerEndPos();
49406f32e7eSjoerg   Result.startToken();
49506f32e7eSjoerg   CurLexer->BufferPtr = EndPos;
49606f32e7eSjoerg   CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
49706f32e7eSjoerg 
49806f32e7eSjoerg   if (isCodeCompletionEnabled()) {
49906f32e7eSjoerg     // Inserting the code-completion point increases the source buffer by 1,
50006f32e7eSjoerg     // but the main FileID was created before inserting the point.
50106f32e7eSjoerg     // Compensate by reducing the EOF location by 1, otherwise the location
50206f32e7eSjoerg     // will point to the next FileID.
50306f32e7eSjoerg     // FIXME: This is hacky, the code-completion point should probably be
50406f32e7eSjoerg     // inserted before the main FileID is created.
50506f32e7eSjoerg     if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
50606f32e7eSjoerg       Result.setLocation(Result.getLocation().getLocWithOffset(-1));
50706f32e7eSjoerg   }
50806f32e7eSjoerg 
50906f32e7eSjoerg   if (creatingPCHWithThroughHeader() && !LeavingPCHThroughHeader) {
51006f32e7eSjoerg     // Reached the end of the compilation without finding the through header.
51106f32e7eSjoerg     Diag(CurLexer->getFileLoc(), diag::err_pp_through_header_not_seen)
51206f32e7eSjoerg         << PPOpts->PCHThroughHeader << 0;
51306f32e7eSjoerg   }
51406f32e7eSjoerg 
51506f32e7eSjoerg   if (!isIncrementalProcessingEnabled())
51606f32e7eSjoerg     // We're done with lexing.
51706f32e7eSjoerg     CurLexer.reset();
51806f32e7eSjoerg 
51906f32e7eSjoerg   if (!isIncrementalProcessingEnabled())
52006f32e7eSjoerg     CurPPLexer = nullptr;
52106f32e7eSjoerg 
52206f32e7eSjoerg   if (TUKind == TU_Complete) {
52306f32e7eSjoerg     // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
52406f32e7eSjoerg     // collected all macro locations that we need to warn because they are not
52506f32e7eSjoerg     // used.
52606f32e7eSjoerg     for (WarnUnusedMacroLocsTy::iterator
52706f32e7eSjoerg            I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
52806f32e7eSjoerg            I!=E; ++I)
52906f32e7eSjoerg       Diag(*I, diag::pp_macro_not_used);
53006f32e7eSjoerg   }
53106f32e7eSjoerg 
53206f32e7eSjoerg   // If we are building a module that has an umbrella header, make sure that
53306f32e7eSjoerg   // each of the headers within the directory, including all submodules, is
53406f32e7eSjoerg   // covered by the umbrella header was actually included by the umbrella
53506f32e7eSjoerg   // header.
53606f32e7eSjoerg   if (Module *Mod = getCurrentModule()) {
53706f32e7eSjoerg     llvm::SmallVector<const Module *, 4> AllMods;
53806f32e7eSjoerg     collectAllSubModulesWithUmbrellaHeader(*Mod, AllMods);
53906f32e7eSjoerg     for (auto *M : AllMods)
54006f32e7eSjoerg       diagnoseMissingHeaderInUmbrellaDir(*M);
54106f32e7eSjoerg   }
54206f32e7eSjoerg 
54306f32e7eSjoerg   return true;
54406f32e7eSjoerg }
54506f32e7eSjoerg 
54606f32e7eSjoerg /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
54706f32e7eSjoerg /// hits the end of its token stream.
HandleEndOfTokenLexer(Token & Result)54806f32e7eSjoerg bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
54906f32e7eSjoerg   assert(CurTokenLexer && !CurPPLexer &&
55006f32e7eSjoerg          "Ending a macro when currently in a #include file!");
55106f32e7eSjoerg 
55206f32e7eSjoerg   if (!MacroExpandingLexersStack.empty() &&
55306f32e7eSjoerg       MacroExpandingLexersStack.back().first == CurTokenLexer.get())
55406f32e7eSjoerg     removeCachedMacroExpandedTokensOfLastLexer();
55506f32e7eSjoerg 
55606f32e7eSjoerg   // Delete or cache the now-dead macro expander.
55706f32e7eSjoerg   if (NumCachedTokenLexers == TokenLexerCacheSize)
55806f32e7eSjoerg     CurTokenLexer.reset();
55906f32e7eSjoerg   else
56006f32e7eSjoerg     TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
56106f32e7eSjoerg 
56206f32e7eSjoerg   // Handle this like a #include file being popped off the stack.
56306f32e7eSjoerg   return HandleEndOfFile(Result, true);
56406f32e7eSjoerg }
56506f32e7eSjoerg 
56606f32e7eSjoerg /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
56706f32e7eSjoerg /// lexer stack.  This should only be used in situations where the current
56806f32e7eSjoerg /// state of the top-of-stack lexer is unknown.
RemoveTopOfLexerStack()56906f32e7eSjoerg void Preprocessor::RemoveTopOfLexerStack() {
57006f32e7eSjoerg   assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
57106f32e7eSjoerg 
57206f32e7eSjoerg   if (CurTokenLexer) {
57306f32e7eSjoerg     // Delete or cache the now-dead macro expander.
57406f32e7eSjoerg     if (NumCachedTokenLexers == TokenLexerCacheSize)
57506f32e7eSjoerg       CurTokenLexer.reset();
57606f32e7eSjoerg     else
57706f32e7eSjoerg       TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
57806f32e7eSjoerg   }
57906f32e7eSjoerg 
58006f32e7eSjoerg   PopIncludeMacroStack();
58106f32e7eSjoerg }
58206f32e7eSjoerg 
58306f32e7eSjoerg /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
58406f32e7eSjoerg /// comment (/##/) in microsoft mode, this method handles updating the current
58506f32e7eSjoerg /// state, returning the token on the next source line.
HandleMicrosoftCommentPaste(Token & Tok)58606f32e7eSjoerg void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
58706f32e7eSjoerg   assert(CurTokenLexer && !CurPPLexer &&
58806f32e7eSjoerg          "Pasted comment can only be formed from macro");
58906f32e7eSjoerg   // We handle this by scanning for the closest real lexer, switching it to
59006f32e7eSjoerg   // raw mode and preprocessor mode.  This will cause it to return \n as an
59106f32e7eSjoerg   // explicit EOD token.
59206f32e7eSjoerg   PreprocessorLexer *FoundLexer = nullptr;
59306f32e7eSjoerg   bool LexerWasInPPMode = false;
59406f32e7eSjoerg   for (const IncludeStackInfo &ISI : llvm::reverse(IncludeMacroStack)) {
59506f32e7eSjoerg     if (ISI.ThePPLexer == nullptr) continue;  // Scan for a real lexer.
59606f32e7eSjoerg 
59706f32e7eSjoerg     // Once we find a real lexer, mark it as raw mode (disabling macro
59806f32e7eSjoerg     // expansions) and preprocessor mode (return EOD).  We know that the lexer
59906f32e7eSjoerg     // was *not* in raw mode before, because the macro that the comment came
60006f32e7eSjoerg     // from was expanded.  However, it could have already been in preprocessor
60106f32e7eSjoerg     // mode (#if COMMENT) in which case we have to return it to that mode and
60206f32e7eSjoerg     // return EOD.
60306f32e7eSjoerg     FoundLexer = ISI.ThePPLexer;
60406f32e7eSjoerg     FoundLexer->LexingRawMode = true;
60506f32e7eSjoerg     LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
60606f32e7eSjoerg     FoundLexer->ParsingPreprocessorDirective = true;
60706f32e7eSjoerg     break;
60806f32e7eSjoerg   }
60906f32e7eSjoerg 
61006f32e7eSjoerg   // Okay, we either found and switched over the lexer, or we didn't find a
61106f32e7eSjoerg   // lexer.  In either case, finish off the macro the comment came from, getting
61206f32e7eSjoerg   // the next token.
61306f32e7eSjoerg   if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
61406f32e7eSjoerg 
61506f32e7eSjoerg   // Discarding comments as long as we don't have EOF or EOD.  This 'comments
61606f32e7eSjoerg   // out' the rest of the line, including any tokens that came from other macros
61706f32e7eSjoerg   // that were active, as in:
61806f32e7eSjoerg   //  #define submacro a COMMENT b
61906f32e7eSjoerg   //    submacro c
62006f32e7eSjoerg   // which should lex to 'a' only: 'b' and 'c' should be removed.
62106f32e7eSjoerg   while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
62206f32e7eSjoerg     Lex(Tok);
62306f32e7eSjoerg 
62406f32e7eSjoerg   // If we got an eod token, then we successfully found the end of the line.
62506f32e7eSjoerg   if (Tok.is(tok::eod)) {
62606f32e7eSjoerg     assert(FoundLexer && "Can't get end of line without an active lexer");
62706f32e7eSjoerg     // Restore the lexer back to normal mode instead of raw mode.
62806f32e7eSjoerg     FoundLexer->LexingRawMode = false;
62906f32e7eSjoerg 
63006f32e7eSjoerg     // If the lexer was already in preprocessor mode, just return the EOD token
63106f32e7eSjoerg     // to finish the preprocessor line.
63206f32e7eSjoerg     if (LexerWasInPPMode) return;
63306f32e7eSjoerg 
63406f32e7eSjoerg     // Otherwise, switch out of PP mode and return the next lexed token.
63506f32e7eSjoerg     FoundLexer->ParsingPreprocessorDirective = false;
63606f32e7eSjoerg     return Lex(Tok);
63706f32e7eSjoerg   }
63806f32e7eSjoerg 
63906f32e7eSjoerg   // If we got an EOF token, then we reached the end of the token stream but
64006f32e7eSjoerg   // didn't find an explicit \n.  This can only happen if there was no lexer
64106f32e7eSjoerg   // active (an active lexer would return EOD at EOF if there was no \n in
64206f32e7eSjoerg   // preprocessor directive mode), so just return EOF as our token.
64306f32e7eSjoerg   assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
64406f32e7eSjoerg }
64506f32e7eSjoerg 
EnterSubmodule(Module * M,SourceLocation ImportLoc,bool ForPragma)64606f32e7eSjoerg void Preprocessor::EnterSubmodule(Module *M, SourceLocation ImportLoc,
64706f32e7eSjoerg                                   bool ForPragma) {
64806f32e7eSjoerg   if (!getLangOpts().ModulesLocalVisibility) {
64906f32e7eSjoerg     // Just track that we entered this submodule.
65006f32e7eSjoerg     BuildingSubmoduleStack.push_back(
65106f32e7eSjoerg         BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
65206f32e7eSjoerg                               PendingModuleMacroNames.size()));
65306f32e7eSjoerg     if (Callbacks)
65406f32e7eSjoerg       Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
65506f32e7eSjoerg     return;
65606f32e7eSjoerg   }
65706f32e7eSjoerg 
65806f32e7eSjoerg   // Resolve as much of the module definition as we can now, before we enter
65906f32e7eSjoerg   // one of its headers.
66006f32e7eSjoerg   // FIXME: Can we enable Complain here?
66106f32e7eSjoerg   // FIXME: Can we do this when local visibility is disabled?
66206f32e7eSjoerg   ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
66306f32e7eSjoerg   ModMap.resolveExports(M, /*Complain=*/false);
66406f32e7eSjoerg   ModMap.resolveUses(M, /*Complain=*/false);
66506f32e7eSjoerg   ModMap.resolveConflicts(M, /*Complain=*/false);
66606f32e7eSjoerg 
66706f32e7eSjoerg   // If this is the first time we've entered this module, set up its state.
66806f32e7eSjoerg   auto R = Submodules.insert(std::make_pair(M, SubmoduleState()));
66906f32e7eSjoerg   auto &State = R.first->second;
67006f32e7eSjoerg   bool FirstTime = R.second;
67106f32e7eSjoerg   if (FirstTime) {
67206f32e7eSjoerg     // Determine the set of starting macros for this submodule; take these
67306f32e7eSjoerg     // from the "null" module (the predefines buffer).
67406f32e7eSjoerg     //
67506f32e7eSjoerg     // FIXME: If we have local visibility but not modules enabled, the
67606f32e7eSjoerg     // NullSubmoduleState is polluted by #defines in the top-level source
67706f32e7eSjoerg     // file.
67806f32e7eSjoerg     auto &StartingMacros = NullSubmoduleState.Macros;
67906f32e7eSjoerg 
68006f32e7eSjoerg     // Restore to the starting state.
68106f32e7eSjoerg     // FIXME: Do this lazily, when each macro name is first referenced.
68206f32e7eSjoerg     for (auto &Macro : StartingMacros) {
68306f32e7eSjoerg       // Skip uninteresting macros.
68406f32e7eSjoerg       if (!Macro.second.getLatest() &&
68506f32e7eSjoerg           Macro.second.getOverriddenMacros().empty())
68606f32e7eSjoerg         continue;
68706f32e7eSjoerg 
68806f32e7eSjoerg       MacroState MS(Macro.second.getLatest());
68906f32e7eSjoerg       MS.setOverriddenMacros(*this, Macro.second.getOverriddenMacros());
69006f32e7eSjoerg       State.Macros.insert(std::make_pair(Macro.first, std::move(MS)));
69106f32e7eSjoerg     }
69206f32e7eSjoerg   }
69306f32e7eSjoerg 
69406f32e7eSjoerg   // Track that we entered this module.
69506f32e7eSjoerg   BuildingSubmoduleStack.push_back(
69606f32e7eSjoerg       BuildingSubmoduleInfo(M, ImportLoc, ForPragma, CurSubmoduleState,
69706f32e7eSjoerg                             PendingModuleMacroNames.size()));
69806f32e7eSjoerg 
69906f32e7eSjoerg   if (Callbacks)
70006f32e7eSjoerg     Callbacks->EnteredSubmodule(M, ImportLoc, ForPragma);
70106f32e7eSjoerg 
70206f32e7eSjoerg   // Switch to this submodule as the current submodule.
70306f32e7eSjoerg   CurSubmoduleState = &State;
70406f32e7eSjoerg 
70506f32e7eSjoerg   // This module is visible to itself.
70606f32e7eSjoerg   if (FirstTime)
70706f32e7eSjoerg     makeModuleVisible(M, ImportLoc);
70806f32e7eSjoerg }
70906f32e7eSjoerg 
needModuleMacros() const71006f32e7eSjoerg bool Preprocessor::needModuleMacros() const {
71106f32e7eSjoerg   // If we're not within a submodule, we never need to create ModuleMacros.
71206f32e7eSjoerg   if (BuildingSubmoduleStack.empty())
71306f32e7eSjoerg     return false;
71406f32e7eSjoerg   // If we are tracking module macro visibility even for textually-included
71506f32e7eSjoerg   // headers, we need ModuleMacros.
71606f32e7eSjoerg   if (getLangOpts().ModulesLocalVisibility)
71706f32e7eSjoerg     return true;
71806f32e7eSjoerg   // Otherwise, we only need module macros if we're actually compiling a module
71906f32e7eSjoerg   // interface.
72006f32e7eSjoerg   return getLangOpts().isCompilingModule();
72106f32e7eSjoerg }
72206f32e7eSjoerg 
LeaveSubmodule(bool ForPragma)72306f32e7eSjoerg Module *Preprocessor::LeaveSubmodule(bool ForPragma) {
72406f32e7eSjoerg   if (BuildingSubmoduleStack.empty() ||
72506f32e7eSjoerg       BuildingSubmoduleStack.back().IsPragma != ForPragma) {
72606f32e7eSjoerg     assert(ForPragma && "non-pragma module enter/leave mismatch");
72706f32e7eSjoerg     return nullptr;
72806f32e7eSjoerg   }
72906f32e7eSjoerg 
73006f32e7eSjoerg   auto &Info = BuildingSubmoduleStack.back();
73106f32e7eSjoerg 
73206f32e7eSjoerg   Module *LeavingMod = Info.M;
73306f32e7eSjoerg   SourceLocation ImportLoc = Info.ImportLoc;
73406f32e7eSjoerg 
73506f32e7eSjoerg   if (!needModuleMacros() ||
73606f32e7eSjoerg       (!getLangOpts().ModulesLocalVisibility &&
73706f32e7eSjoerg        LeavingMod->getTopLevelModuleName() != getLangOpts().CurrentModule)) {
73806f32e7eSjoerg     // If we don't need module macros, or this is not a module for which we
73906f32e7eSjoerg     // are tracking macro visibility, don't build any, and preserve the list
74006f32e7eSjoerg     // of pending names for the surrounding submodule.
74106f32e7eSjoerg     BuildingSubmoduleStack.pop_back();
74206f32e7eSjoerg 
74306f32e7eSjoerg     if (Callbacks)
74406f32e7eSjoerg       Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
74506f32e7eSjoerg 
74606f32e7eSjoerg     makeModuleVisible(LeavingMod, ImportLoc);
74706f32e7eSjoerg     return LeavingMod;
74806f32e7eSjoerg   }
74906f32e7eSjoerg 
75006f32e7eSjoerg   // Create ModuleMacros for any macros defined in this submodule.
75106f32e7eSjoerg   llvm::SmallPtrSet<const IdentifierInfo*, 8> VisitedMacros;
75206f32e7eSjoerg   for (unsigned I = Info.OuterPendingModuleMacroNames;
75306f32e7eSjoerg        I != PendingModuleMacroNames.size(); ++I) {
75406f32e7eSjoerg     auto *II = const_cast<IdentifierInfo*>(PendingModuleMacroNames[I]);
75506f32e7eSjoerg     if (!VisitedMacros.insert(II).second)
75606f32e7eSjoerg       continue;
75706f32e7eSjoerg 
75806f32e7eSjoerg     auto MacroIt = CurSubmoduleState->Macros.find(II);
75906f32e7eSjoerg     if (MacroIt == CurSubmoduleState->Macros.end())
76006f32e7eSjoerg       continue;
76106f32e7eSjoerg     auto &Macro = MacroIt->second;
76206f32e7eSjoerg 
76306f32e7eSjoerg     // Find the starting point for the MacroDirective chain in this submodule.
76406f32e7eSjoerg     MacroDirective *OldMD = nullptr;
76506f32e7eSjoerg     auto *OldState = Info.OuterSubmoduleState;
76606f32e7eSjoerg     if (getLangOpts().ModulesLocalVisibility)
76706f32e7eSjoerg       OldState = &NullSubmoduleState;
76806f32e7eSjoerg     if (OldState && OldState != CurSubmoduleState) {
76906f32e7eSjoerg       // FIXME: It'd be better to start at the state from when we most recently
77006f32e7eSjoerg       // entered this submodule, but it doesn't really matter.
77106f32e7eSjoerg       auto &OldMacros = OldState->Macros;
77206f32e7eSjoerg       auto OldMacroIt = OldMacros.find(II);
77306f32e7eSjoerg       if (OldMacroIt == OldMacros.end())
77406f32e7eSjoerg         OldMD = nullptr;
77506f32e7eSjoerg       else
77606f32e7eSjoerg         OldMD = OldMacroIt->second.getLatest();
77706f32e7eSjoerg     }
77806f32e7eSjoerg 
77906f32e7eSjoerg     // This module may have exported a new macro. If so, create a ModuleMacro
78006f32e7eSjoerg     // representing that fact.
78106f32e7eSjoerg     bool ExplicitlyPublic = false;
78206f32e7eSjoerg     for (auto *MD = Macro.getLatest(); MD != OldMD; MD = MD->getPrevious()) {
78306f32e7eSjoerg       assert(MD && "broken macro directive chain");
78406f32e7eSjoerg 
78506f32e7eSjoerg       if (auto *VisMD = dyn_cast<VisibilityMacroDirective>(MD)) {
78606f32e7eSjoerg         // The latest visibility directive for a name in a submodule affects
78706f32e7eSjoerg         // all the directives that come before it.
78806f32e7eSjoerg         if (VisMD->isPublic())
78906f32e7eSjoerg           ExplicitlyPublic = true;
79006f32e7eSjoerg         else if (!ExplicitlyPublic)
79106f32e7eSjoerg           // Private with no following public directive: not exported.
79206f32e7eSjoerg           break;
79306f32e7eSjoerg       } else {
79406f32e7eSjoerg         MacroInfo *Def = nullptr;
79506f32e7eSjoerg         if (DefMacroDirective *DefMD = dyn_cast<DefMacroDirective>(MD))
79606f32e7eSjoerg           Def = DefMD->getInfo();
79706f32e7eSjoerg 
79806f32e7eSjoerg         // FIXME: Issue a warning if multiple headers for the same submodule
79906f32e7eSjoerg         // define a macro, rather than silently ignoring all but the first.
80006f32e7eSjoerg         bool IsNew;
80106f32e7eSjoerg         // Don't bother creating a module macro if it would represent a #undef
80206f32e7eSjoerg         // that doesn't override anything.
80306f32e7eSjoerg         if (Def || !Macro.getOverriddenMacros().empty())
80406f32e7eSjoerg           addModuleMacro(LeavingMod, II, Def,
80506f32e7eSjoerg                          Macro.getOverriddenMacros(), IsNew);
80606f32e7eSjoerg 
80706f32e7eSjoerg         if (!getLangOpts().ModulesLocalVisibility) {
80806f32e7eSjoerg           // This macro is exposed to the rest of this compilation as a
80906f32e7eSjoerg           // ModuleMacro; we don't need to track its MacroDirective any more.
81006f32e7eSjoerg           Macro.setLatest(nullptr);
81106f32e7eSjoerg           Macro.setOverriddenMacros(*this, {});
81206f32e7eSjoerg         }
81306f32e7eSjoerg         break;
81406f32e7eSjoerg       }
81506f32e7eSjoerg     }
81606f32e7eSjoerg   }
81706f32e7eSjoerg   PendingModuleMacroNames.resize(Info.OuterPendingModuleMacroNames);
81806f32e7eSjoerg 
81906f32e7eSjoerg   // FIXME: Before we leave this submodule, we should parse all the other
82006f32e7eSjoerg   // headers within it. Otherwise, we're left with an inconsistent state
82106f32e7eSjoerg   // where we've made the module visible but don't yet have its complete
82206f32e7eSjoerg   // contents.
82306f32e7eSjoerg 
82406f32e7eSjoerg   // Put back the outer module's state, if we're tracking it.
82506f32e7eSjoerg   if (getLangOpts().ModulesLocalVisibility)
82606f32e7eSjoerg     CurSubmoduleState = Info.OuterSubmoduleState;
82706f32e7eSjoerg 
82806f32e7eSjoerg   BuildingSubmoduleStack.pop_back();
82906f32e7eSjoerg 
83006f32e7eSjoerg   if (Callbacks)
83106f32e7eSjoerg     Callbacks->LeftSubmodule(LeavingMod, ImportLoc, ForPragma);
83206f32e7eSjoerg 
83306f32e7eSjoerg   // A nested #include makes the included submodule visible.
83406f32e7eSjoerg   makeModuleVisible(LeavingMod, ImportLoc);
83506f32e7eSjoerg   return LeavingMod;
83606f32e7eSjoerg }
837