xref: /openbsd-src/gnu/llvm/clang/lib/Sema/SemaModule.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- SemaModule.cpp - Semantic Analysis for Modules -------------------===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick //  This file implements semantic analysis for modules (C++ modules syntax,
10e5dd7070Spatrick //  Objective-C modules syntax, and Clang header modules).
11e5dd7070Spatrick //
12e5dd7070Spatrick //===----------------------------------------------------------------------===//
13e5dd7070Spatrick 
14e5dd7070Spatrick #include "clang/AST/ASTConsumer.h"
15e5dd7070Spatrick #include "clang/Lex/HeaderSearch.h"
16e5dd7070Spatrick #include "clang/Lex/Preprocessor.h"
17e5dd7070Spatrick #include "clang/Sema/SemaInternal.h"
18*12c85518Srobert #include <optional>
19e5dd7070Spatrick 
20e5dd7070Spatrick using namespace clang;
21e5dd7070Spatrick using namespace sema;
22e5dd7070Spatrick 
checkModuleImportContext(Sema & S,Module * M,SourceLocation ImportLoc,DeclContext * DC,bool FromInclude=false)23e5dd7070Spatrick static void checkModuleImportContext(Sema &S, Module *M,
24e5dd7070Spatrick                                      SourceLocation ImportLoc, DeclContext *DC,
25e5dd7070Spatrick                                      bool FromInclude = false) {
26e5dd7070Spatrick   SourceLocation ExternCLoc;
27e5dd7070Spatrick 
28e5dd7070Spatrick   if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
29e5dd7070Spatrick     switch (LSD->getLanguage()) {
30e5dd7070Spatrick     case LinkageSpecDecl::lang_c:
31e5dd7070Spatrick       if (ExternCLoc.isInvalid())
32e5dd7070Spatrick         ExternCLoc = LSD->getBeginLoc();
33e5dd7070Spatrick       break;
34e5dd7070Spatrick     case LinkageSpecDecl::lang_cxx:
35e5dd7070Spatrick       break;
36e5dd7070Spatrick     }
37e5dd7070Spatrick     DC = LSD->getParent();
38e5dd7070Spatrick   }
39e5dd7070Spatrick 
40e5dd7070Spatrick   while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
41e5dd7070Spatrick     DC = DC->getParent();
42e5dd7070Spatrick 
43e5dd7070Spatrick   if (!isa<TranslationUnitDecl>(DC)) {
44e5dd7070Spatrick     S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
45e5dd7070Spatrick                           ? diag::ext_module_import_not_at_top_level_noop
46e5dd7070Spatrick                           : diag::err_module_import_not_at_top_level_fatal)
47e5dd7070Spatrick         << M->getFullModuleName() << DC;
48e5dd7070Spatrick     S.Diag(cast<Decl>(DC)->getBeginLoc(),
49e5dd7070Spatrick            diag::note_module_import_not_at_top_level)
50e5dd7070Spatrick         << DC;
51e5dd7070Spatrick   } else if (!M->IsExternC && ExternCLoc.isValid()) {
52e5dd7070Spatrick     S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
53e5dd7070Spatrick       << M->getFullModuleName();
54e5dd7070Spatrick     S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
55e5dd7070Spatrick   }
56e5dd7070Spatrick }
57e5dd7070Spatrick 
58*12c85518Srobert // We represent the primary and partition names as 'Paths' which are sections
59*12c85518Srobert // of the hierarchical access path for a clang module.  However for C++20
60*12c85518Srobert // the periods in a name are just another character, and we will need to
61*12c85518Srobert // flatten them into a string.
stringFromPath(ModuleIdPath Path)62*12c85518Srobert static std::string stringFromPath(ModuleIdPath Path) {
63*12c85518Srobert   std::string Name;
64*12c85518Srobert   if (Path.empty())
65*12c85518Srobert     return Name;
66*12c85518Srobert 
67*12c85518Srobert   for (auto &Piece : Path) {
68*12c85518Srobert     if (!Name.empty())
69*12c85518Srobert       Name += ".";
70*12c85518Srobert     Name += Piece.first->getName();
71*12c85518Srobert   }
72*12c85518Srobert   return Name;
73*12c85518Srobert }
74*12c85518Srobert 
75e5dd7070Spatrick Sema::DeclGroupPtrTy
ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)76e5dd7070Spatrick Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
77e5dd7070Spatrick   if (!ModuleScopes.empty() &&
78e5dd7070Spatrick       ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
79e5dd7070Spatrick     // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
80e5dd7070Spatrick     // already implicitly entering the global module fragment. That's OK.
81e5dd7070Spatrick     assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
82e5dd7070Spatrick            "unexpectedly encountered multiple global module fragment decls");
83e5dd7070Spatrick     ModuleScopes.back().BeginLoc = ModuleLoc;
84e5dd7070Spatrick     return nullptr;
85e5dd7070Spatrick   }
86e5dd7070Spatrick 
87e5dd7070Spatrick   // We start in the global module; all those declarations are implicitly
88e5dd7070Spatrick   // module-private (though they do not have module linkage).
89*12c85518Srobert   Module *GlobalModule =
90*12c85518Srobert       PushGlobalModuleFragment(ModuleLoc, /*IsImplicit=*/false);
91e5dd7070Spatrick 
92e5dd7070Spatrick   // All declarations created from now on are owned by the global module.
93e5dd7070Spatrick   auto *TU = Context.getTranslationUnitDecl();
94*12c85518Srobert   // [module.global.frag]p2
95*12c85518Srobert   // A global-module-fragment specifies the contents of the global module
96*12c85518Srobert   // fragment for a module unit. The global module fragment can be used to
97*12c85518Srobert   // provide declarations that are attached to the global module and usable
98*12c85518Srobert   // within the module unit.
99*12c85518Srobert   //
100*12c85518Srobert   // So the declations in the global module shouldn't be visible by default.
101*12c85518Srobert   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
102e5dd7070Spatrick   TU->setLocalOwningModule(GlobalModule);
103e5dd7070Spatrick 
104e5dd7070Spatrick   // FIXME: Consider creating an explicit representation of this declaration.
105e5dd7070Spatrick   return nullptr;
106e5dd7070Spatrick }
107e5dd7070Spatrick 
HandleStartOfHeaderUnit()108*12c85518Srobert void Sema::HandleStartOfHeaderUnit() {
109*12c85518Srobert   assert(getLangOpts().CPlusPlusModules &&
110*12c85518Srobert          "Header units are only valid for C++20 modules");
111*12c85518Srobert   SourceLocation StartOfTU =
112*12c85518Srobert       SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
113*12c85518Srobert 
114*12c85518Srobert   StringRef HUName = getLangOpts().CurrentModule;
115*12c85518Srobert   if (HUName.empty()) {
116*12c85518Srobert     HUName = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())->getName();
117*12c85518Srobert     const_cast<LangOptions &>(getLangOpts()).CurrentModule = HUName.str();
118*12c85518Srobert   }
119*12c85518Srobert 
120*12c85518Srobert   // TODO: Make the C++20 header lookup independent.
121*12c85518Srobert   // When the input is pre-processed source, we need a file ref to the original
122*12c85518Srobert   // file for the header map.
123*12c85518Srobert   auto F = SourceMgr.getFileManager().getOptionalFileRef(HUName);
124*12c85518Srobert   // For the sake of error recovery (if someone has moved the original header
125*12c85518Srobert   // after creating the pre-processed output) fall back to obtaining the file
126*12c85518Srobert   // ref for the input file, which must be present.
127*12c85518Srobert   if (!F)
128*12c85518Srobert     F = SourceMgr.getFileEntryRefForID(SourceMgr.getMainFileID());
129*12c85518Srobert   assert(F && "failed to find the header unit source?");
130*12c85518Srobert   Module::Header H{HUName.str(), HUName.str(), *F};
131*12c85518Srobert   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
132*12c85518Srobert   Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H);
133*12c85518Srobert   assert(Mod && "module creation should not fail");
134*12c85518Srobert   ModuleScopes.push_back({}); // No GMF
135*12c85518Srobert   ModuleScopes.back().BeginLoc = StartOfTU;
136*12c85518Srobert   ModuleScopes.back().Module = Mod;
137*12c85518Srobert   ModuleScopes.back().ModuleInterface = true;
138*12c85518Srobert   ModuleScopes.back().IsPartition = false;
139*12c85518Srobert   VisibleModules.setVisible(Mod, StartOfTU);
140*12c85518Srobert 
141*12c85518Srobert   // From now on, we have an owning module for all declarations we see.
142*12c85518Srobert   // All of these are implicitly exported.
143*12c85518Srobert   auto *TU = Context.getTranslationUnitDecl();
144*12c85518Srobert   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
145*12c85518Srobert   TU->setLocalOwningModule(Mod);
146*12c85518Srobert }
147*12c85518Srobert 
148*12c85518Srobert /// Tests whether the given identifier is reserved as a module name and
149*12c85518Srobert /// diagnoses if it is. Returns true if a diagnostic is emitted and false
150*12c85518Srobert /// otherwise.
DiagReservedModuleName(Sema & S,const IdentifierInfo * II,SourceLocation Loc)151*12c85518Srobert static bool DiagReservedModuleName(Sema &S, const IdentifierInfo *II,
152*12c85518Srobert                                    SourceLocation Loc) {
153*12c85518Srobert   enum {
154*12c85518Srobert     Valid = -1,
155*12c85518Srobert     Invalid = 0,
156*12c85518Srobert     Reserved = 1,
157*12c85518Srobert   } Reason = Valid;
158*12c85518Srobert 
159*12c85518Srobert   if (II->isStr("module") || II->isStr("import"))
160*12c85518Srobert     Reason = Invalid;
161*12c85518Srobert   else if (II->isReserved(S.getLangOpts()) !=
162*12c85518Srobert            ReservedIdentifierStatus::NotReserved)
163*12c85518Srobert     Reason = Reserved;
164*12c85518Srobert 
165*12c85518Srobert   // If the identifier is reserved (not invalid) but is in a system header,
166*12c85518Srobert   // we do not diagnose (because we expect system headers to use reserved
167*12c85518Srobert   // identifiers).
168*12c85518Srobert   if (Reason == Reserved && S.getSourceManager().isInSystemHeader(Loc))
169*12c85518Srobert     Reason = Valid;
170*12c85518Srobert 
171*12c85518Srobert   if (Reason != Valid) {
172*12c85518Srobert     S.Diag(Loc, diag::err_invalid_module_name) << II << (int)Reason;
173*12c85518Srobert     return true;
174*12c85518Srobert   }
175*12c85518Srobert   return false;
176*12c85518Srobert }
177*12c85518Srobert 
178e5dd7070Spatrick Sema::DeclGroupPtrTy
ActOnModuleDecl(SourceLocation StartLoc,SourceLocation ModuleLoc,ModuleDeclKind MDK,ModuleIdPath Path,ModuleIdPath Partition,ModuleImportState & ImportState)179e5dd7070Spatrick Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
180*12c85518Srobert                       ModuleDeclKind MDK, ModuleIdPath Path,
181*12c85518Srobert                       ModuleIdPath Partition, ModuleImportState &ImportState) {
182e5dd7070Spatrick   assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
183e5dd7070Spatrick          "should only have module decl in Modules TS or C++20");
184e5dd7070Spatrick 
185*12c85518Srobert   bool IsFirstDecl = ImportState == ModuleImportState::FirstDecl;
186*12c85518Srobert   bool SeenGMF = ImportState == ModuleImportState::GlobalFragment;
187*12c85518Srobert   // If any of the steps here fail, we count that as invalidating C++20
188*12c85518Srobert   // module state;
189*12c85518Srobert   ImportState = ModuleImportState::NotACXX20Module;
190*12c85518Srobert 
191*12c85518Srobert   bool IsPartition = !Partition.empty();
192*12c85518Srobert   if (IsPartition)
193*12c85518Srobert     switch (MDK) {
194*12c85518Srobert     case ModuleDeclKind::Implementation:
195*12c85518Srobert       MDK = ModuleDeclKind::PartitionImplementation;
196*12c85518Srobert       break;
197*12c85518Srobert     case ModuleDeclKind::Interface:
198*12c85518Srobert       MDK = ModuleDeclKind::PartitionInterface;
199*12c85518Srobert       break;
200*12c85518Srobert     default:
201*12c85518Srobert       llvm_unreachable("how did we get a partition type set?");
202*12c85518Srobert     }
203*12c85518Srobert 
204*12c85518Srobert   // A (non-partition) module implementation unit requires that we are not
205*12c85518Srobert   // compiling a module of any kind.  A partition implementation emits an
206*12c85518Srobert   // interface (and the AST for the implementation), which will subsequently
207*12c85518Srobert   // be consumed to emit a binary.
208*12c85518Srobert   // A module interface unit requires that we are not compiling a module map.
209e5dd7070Spatrick   switch (getLangOpts().getCompilingModule()) {
210e5dd7070Spatrick   case LangOptions::CMK_None:
211e5dd7070Spatrick     // It's OK to compile a module interface as a normal translation unit.
212e5dd7070Spatrick     break;
213e5dd7070Spatrick 
214e5dd7070Spatrick   case LangOptions::CMK_ModuleInterface:
215e5dd7070Spatrick     if (MDK != ModuleDeclKind::Implementation)
216e5dd7070Spatrick       break;
217e5dd7070Spatrick 
218e5dd7070Spatrick     // We were asked to compile a module interface unit but this is a module
219*12c85518Srobert     // implementation unit.
220e5dd7070Spatrick     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
221e5dd7070Spatrick       << FixItHint::CreateInsertion(ModuleLoc, "export ");
222e5dd7070Spatrick     MDK = ModuleDeclKind::Interface;
223e5dd7070Spatrick     break;
224e5dd7070Spatrick 
225e5dd7070Spatrick   case LangOptions::CMK_ModuleMap:
226e5dd7070Spatrick     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
227e5dd7070Spatrick     return nullptr;
228e5dd7070Spatrick 
229*12c85518Srobert   case LangOptions::CMK_HeaderUnit:
230*12c85518Srobert     Diag(ModuleLoc, diag::err_module_decl_in_header_unit);
231e5dd7070Spatrick     return nullptr;
232e5dd7070Spatrick   }
233e5dd7070Spatrick 
234e5dd7070Spatrick   assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
235e5dd7070Spatrick 
236e5dd7070Spatrick   // FIXME: Most of this work should be done by the preprocessor rather than
237e5dd7070Spatrick   // here, in order to support macro import.
238e5dd7070Spatrick 
239e5dd7070Spatrick   // Only one module-declaration is permitted per source file.
240*12c85518Srobert   if (isCurrentModulePurview()) {
241e5dd7070Spatrick     Diag(ModuleLoc, diag::err_module_redeclaration);
242e5dd7070Spatrick     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
243e5dd7070Spatrick          diag::note_prev_module_declaration);
244e5dd7070Spatrick     return nullptr;
245e5dd7070Spatrick   }
246e5dd7070Spatrick 
247*12c85518Srobert   assert((!getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS ||
248*12c85518Srobert           SeenGMF == (bool)this->GlobalModuleFragment) &&
249*12c85518Srobert          "mismatched global module state");
250e5dd7070Spatrick 
251e5dd7070Spatrick   // In C++20, the module-declaration must be the first declaration if there
252e5dd7070Spatrick   // is no global module fragment.
253*12c85518Srobert   if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !SeenGMF) {
254e5dd7070Spatrick     Diag(ModuleLoc, diag::err_module_decl_not_at_start);
255e5dd7070Spatrick     SourceLocation BeginLoc =
256e5dd7070Spatrick         ModuleScopes.empty()
257e5dd7070Spatrick             ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
258e5dd7070Spatrick             : ModuleScopes.back().BeginLoc;
259e5dd7070Spatrick     if (BeginLoc.isValid()) {
260e5dd7070Spatrick       Diag(BeginLoc, diag::note_global_module_introducer_missing)
261e5dd7070Spatrick           << FixItHint::CreateInsertion(BeginLoc, "module;\n");
262e5dd7070Spatrick     }
263e5dd7070Spatrick   }
264e5dd7070Spatrick 
265*12c85518Srobert   // C++2b [module.unit]p1: ... The identifiers module and import shall not
266*12c85518Srobert   // appear as identifiers in a module-name or module-partition. All
267*12c85518Srobert   // module-names either beginning with an identifier consisting of std
268*12c85518Srobert   // followed by zero or more digits or containing a reserved identifier
269*12c85518Srobert   // ([lex.name]) are reserved and shall not be specified in a
270*12c85518Srobert   // module-declaration; no diagnostic is required.
271*12c85518Srobert 
272*12c85518Srobert   // Test the first part of the path to see if it's std[0-9]+ but allow the
273*12c85518Srobert   // name in a system header.
274*12c85518Srobert   StringRef FirstComponentName = Path[0].first->getName();
275*12c85518Srobert   if (!getSourceManager().isInSystemHeader(Path[0].second) &&
276*12c85518Srobert       (FirstComponentName == "std" ||
277*12c85518Srobert        (FirstComponentName.startswith("std") &&
278*12c85518Srobert         llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit)))) {
279*12c85518Srobert     Diag(Path[0].second, diag::err_invalid_module_name)
280*12c85518Srobert         << Path[0].first << /*reserved*/ 1;
281*12c85518Srobert     return nullptr;
282*12c85518Srobert   }
283*12c85518Srobert 
284*12c85518Srobert   // Then test all of the components in the path to see if any of them are
285*12c85518Srobert   // using another kind of reserved or invalid identifier.
286*12c85518Srobert   for (auto Part : Path) {
287*12c85518Srobert     if (DiagReservedModuleName(*this, Part.first, Part.second))
288*12c85518Srobert       return nullptr;
289*12c85518Srobert   }
290*12c85518Srobert 
291e5dd7070Spatrick   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
292e5dd7070Spatrick   // modules, the dots here are just another character that can appear in a
293e5dd7070Spatrick   // module name.
294*12c85518Srobert   std::string ModuleName = stringFromPath(Path);
295*12c85518Srobert   if (IsPartition) {
296*12c85518Srobert     ModuleName += ":";
297*12c85518Srobert     ModuleName += stringFromPath(Partition);
298e5dd7070Spatrick   }
299e5dd7070Spatrick   // If a module name was explicitly specified on the command line, it must be
300e5dd7070Spatrick   // correct.
301e5dd7070Spatrick   if (!getLangOpts().CurrentModule.empty() &&
302e5dd7070Spatrick       getLangOpts().CurrentModule != ModuleName) {
303e5dd7070Spatrick     Diag(Path.front().second, diag::err_current_module_name_mismatch)
304*12c85518Srobert         << SourceRange(Path.front().second, IsPartition
305*12c85518Srobert                                                 ? Partition.back().second
306*12c85518Srobert                                                 : Path.back().second)
307e5dd7070Spatrick         << getLangOpts().CurrentModule;
308e5dd7070Spatrick     return nullptr;
309e5dd7070Spatrick   }
310e5dd7070Spatrick   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
311e5dd7070Spatrick 
312e5dd7070Spatrick   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
313e5dd7070Spatrick   Module *Mod;
314e5dd7070Spatrick 
315e5dd7070Spatrick   switch (MDK) {
316*12c85518Srobert   case ModuleDeclKind::Interface:
317*12c85518Srobert   case ModuleDeclKind::PartitionInterface: {
318e5dd7070Spatrick     // We can't have parsed or imported a definition of this module or parsed a
319e5dd7070Spatrick     // module map defining it already.
320e5dd7070Spatrick     if (auto *M = Map.findModule(ModuleName)) {
321e5dd7070Spatrick       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
322e5dd7070Spatrick       if (M->DefinitionLoc.isValid())
323e5dd7070Spatrick         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
324*12c85518Srobert       else if (OptionalFileEntryRef FE = M->getASTFile())
325e5dd7070Spatrick         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
326e5dd7070Spatrick             << FE->getName();
327e5dd7070Spatrick       Mod = M;
328e5dd7070Spatrick       break;
329e5dd7070Spatrick     }
330e5dd7070Spatrick 
331e5dd7070Spatrick     // Create a Module for the module that we're defining.
332*12c85518Srobert     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
333*12c85518Srobert     if (MDK == ModuleDeclKind::PartitionInterface)
334*12c85518Srobert       Mod->Kind = Module::ModulePartitionInterface;
335e5dd7070Spatrick     assert(Mod && "module creation should not fail");
336e5dd7070Spatrick     break;
337e5dd7070Spatrick   }
338e5dd7070Spatrick 
339*12c85518Srobert   case ModuleDeclKind::Implementation: {
340*12c85518Srobert     // C++20 A module-declaration that contains neither an export-
341*12c85518Srobert     // keyword nor a module-partition implicitly imports the primary
342*12c85518Srobert     // module interface unit of the module as if by a module-import-
343*12c85518Srobert     // declaration.
344e5dd7070Spatrick     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
345e5dd7070Spatrick         PP.getIdentifierInfo(ModuleName), Path[0].second);
346*12c85518Srobert 
347*12c85518Srobert     // The module loader will assume we're trying to import the module that
348*12c85518Srobert     // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
349*12c85518Srobert     // Change the value for `LangOpts.CurrentModule` temporarily to make the
350*12c85518Srobert     // module loader work properly.
351*12c85518Srobert     const_cast<LangOptions&>(getLangOpts()).CurrentModule = "";
352e5dd7070Spatrick     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
353e5dd7070Spatrick                                        Module::AllVisible,
354e5dd7070Spatrick                                        /*IsInclusionDirective=*/false);
355*12c85518Srobert     const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
356*12c85518Srobert 
357e5dd7070Spatrick     if (!Mod) {
358e5dd7070Spatrick       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
359e5dd7070Spatrick       // Create an empty module interface unit for error recovery.
360*12c85518Srobert       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
361e5dd7070Spatrick     }
362*12c85518Srobert 
363*12c85518Srobert   } break;
364*12c85518Srobert 
365*12c85518Srobert   case ModuleDeclKind::PartitionImplementation:
366*12c85518Srobert     // Create an interface, but note that it is an implementation
367*12c85518Srobert     // unit.
368*12c85518Srobert     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
369*12c85518Srobert     Mod->Kind = Module::ModulePartitionImplementation;
370e5dd7070Spatrick     break;
371e5dd7070Spatrick   }
372e5dd7070Spatrick 
373*12c85518Srobert   if (!this->GlobalModuleFragment) {
374e5dd7070Spatrick     ModuleScopes.push_back({});
375e5dd7070Spatrick     if (getLangOpts().ModulesLocalVisibility)
376e5dd7070Spatrick       ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
377e5dd7070Spatrick   } else {
378e5dd7070Spatrick     // We're done with the global module fragment now.
379e5dd7070Spatrick     ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
380e5dd7070Spatrick   }
381e5dd7070Spatrick 
382e5dd7070Spatrick   // Switch from the global module fragment (if any) to the named module.
383e5dd7070Spatrick   ModuleScopes.back().BeginLoc = StartLoc;
384e5dd7070Spatrick   ModuleScopes.back().Module = Mod;
385e5dd7070Spatrick   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
386*12c85518Srobert   ModuleScopes.back().IsPartition = IsPartition;
387e5dd7070Spatrick   VisibleModules.setVisible(Mod, ModuleLoc);
388e5dd7070Spatrick 
389e5dd7070Spatrick   // From now on, we have an owning module for all declarations we see.
390*12c85518Srobert   // In C++20 modules, those declaration would be reachable when imported
391*12c85518Srobert   // unless explicitily exported.
392*12c85518Srobert   // Otherwise, those declarations are module-private unless explicitly
393e5dd7070Spatrick   // exported.
394e5dd7070Spatrick   auto *TU = Context.getTranslationUnitDecl();
395*12c85518Srobert   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
396e5dd7070Spatrick   TU->setLocalOwningModule(Mod);
397e5dd7070Spatrick 
398*12c85518Srobert   // We are in the module purview, but before any other (non import)
399*12c85518Srobert   // statements, so imports are allowed.
400*12c85518Srobert   ImportState = ModuleImportState::ImportAllowed;
401*12c85518Srobert 
402*12c85518Srobert   // For an implementation, We already made an implicit import (its interface).
403*12c85518Srobert   // Make and return the import decl to be added to the current TU.
404*12c85518Srobert   if (MDK == ModuleDeclKind::Implementation) {
405*12c85518Srobert     // Make the import decl for the interface.
406*12c85518Srobert     ImportDecl *Import =
407*12c85518Srobert         ImportDecl::Create(Context, CurContext, ModuleLoc, Mod, Path[0].second);
408*12c85518Srobert     // and return it to be added.
409*12c85518Srobert     return ConvertDeclToDeclGroup(Import);
410*12c85518Srobert   }
411*12c85518Srobert 
412e5dd7070Spatrick   // FIXME: Create a ModuleDecl.
413e5dd7070Spatrick   return nullptr;
414e5dd7070Spatrick }
415e5dd7070Spatrick 
416e5dd7070Spatrick Sema::DeclGroupPtrTy
ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,SourceLocation PrivateLoc)417e5dd7070Spatrick Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
418e5dd7070Spatrick                                      SourceLocation PrivateLoc) {
419e5dd7070Spatrick   // C++20 [basic.link]/2:
420e5dd7070Spatrick   //   A private-module-fragment shall appear only in a primary module
421e5dd7070Spatrick   //   interface unit.
422e5dd7070Spatrick   switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
423e5dd7070Spatrick                                : ModuleScopes.back().Module->Kind) {
424e5dd7070Spatrick   case Module::ModuleMapModule:
425e5dd7070Spatrick   case Module::GlobalModuleFragment:
426*12c85518Srobert   case Module::ModulePartitionImplementation:
427*12c85518Srobert   case Module::ModulePartitionInterface:
428*12c85518Srobert   case Module::ModuleHeaderUnit:
429e5dd7070Spatrick     Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
430e5dd7070Spatrick     return nullptr;
431e5dd7070Spatrick 
432e5dd7070Spatrick   case Module::PrivateModuleFragment:
433e5dd7070Spatrick     Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
434e5dd7070Spatrick     Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
435e5dd7070Spatrick     return nullptr;
436e5dd7070Spatrick 
437e5dd7070Spatrick   case Module::ModuleInterfaceUnit:
438e5dd7070Spatrick     break;
439e5dd7070Spatrick   }
440e5dd7070Spatrick 
441e5dd7070Spatrick   if (!ModuleScopes.back().ModuleInterface) {
442e5dd7070Spatrick     Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
443e5dd7070Spatrick     Diag(ModuleScopes.back().BeginLoc,
444e5dd7070Spatrick          diag::note_not_module_interface_add_export)
445e5dd7070Spatrick         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
446e5dd7070Spatrick     return nullptr;
447e5dd7070Spatrick   }
448e5dd7070Spatrick 
449e5dd7070Spatrick   // FIXME: Check this isn't a module interface partition.
450e5dd7070Spatrick   // FIXME: Check that this translation unit does not import any partitions;
451e5dd7070Spatrick   // such imports would violate [basic.link]/2's "shall be the only module unit"
452e5dd7070Spatrick   // restriction.
453e5dd7070Spatrick 
454e5dd7070Spatrick   // We've finished the public fragment of the translation unit.
455e5dd7070Spatrick   ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
456e5dd7070Spatrick 
457e5dd7070Spatrick   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
458e5dd7070Spatrick   Module *PrivateModuleFragment =
459e5dd7070Spatrick       Map.createPrivateModuleFragmentForInterfaceUnit(
460e5dd7070Spatrick           ModuleScopes.back().Module, PrivateLoc);
461e5dd7070Spatrick   assert(PrivateModuleFragment && "module creation should not fail");
462e5dd7070Spatrick 
463e5dd7070Spatrick   // Enter the scope of the private module fragment.
464e5dd7070Spatrick   ModuleScopes.push_back({});
465e5dd7070Spatrick   ModuleScopes.back().BeginLoc = ModuleLoc;
466e5dd7070Spatrick   ModuleScopes.back().Module = PrivateModuleFragment;
467e5dd7070Spatrick   ModuleScopes.back().ModuleInterface = true;
468e5dd7070Spatrick   VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
469e5dd7070Spatrick 
470e5dd7070Spatrick   // All declarations created from now on are scoped to the private module
471e5dd7070Spatrick   // fragment (and are neither visible nor reachable in importers of the module
472e5dd7070Spatrick   // interface).
473e5dd7070Spatrick   auto *TU = Context.getTranslationUnitDecl();
474e5dd7070Spatrick   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
475e5dd7070Spatrick   TU->setLocalOwningModule(PrivateModuleFragment);
476e5dd7070Spatrick 
477e5dd7070Spatrick   // FIXME: Consider creating an explicit representation of this declaration.
478e5dd7070Spatrick   return nullptr;
479e5dd7070Spatrick }
480e5dd7070Spatrick 
ActOnModuleImport(SourceLocation StartLoc,SourceLocation ExportLoc,SourceLocation ImportLoc,ModuleIdPath Path,bool IsPartition)481e5dd7070Spatrick DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
482e5dd7070Spatrick                                    SourceLocation ExportLoc,
483*12c85518Srobert                                    SourceLocation ImportLoc, ModuleIdPath Path,
484*12c85518Srobert                                    bool IsPartition) {
485*12c85518Srobert 
486*12c85518Srobert   bool Cxx20Mode = getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS;
487*12c85518Srobert   assert((!IsPartition || Cxx20Mode) && "partition seen in non-C++20 code?");
488*12c85518Srobert 
489*12c85518Srobert   // For a C++20 module name, flatten into a single identifier with the source
490*12c85518Srobert   // location of the first component.
491e5dd7070Spatrick   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
492*12c85518Srobert 
493e5dd7070Spatrick   std::string ModuleName;
494*12c85518Srobert   if (IsPartition) {
495*12c85518Srobert     // We already checked that we are in a module purview in the parser.
496*12c85518Srobert     assert(!ModuleScopes.empty() && "in a module purview, but no module?");
497*12c85518Srobert     Module *NamedMod = ModuleScopes.back().Module;
498*12c85518Srobert     // If we are importing into a partition, find the owning named module,
499*12c85518Srobert     // otherwise, the name of the importing named module.
500*12c85518Srobert     ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
501*12c85518Srobert     ModuleName += ":";
502*12c85518Srobert     ModuleName += stringFromPath(Path);
503*12c85518Srobert     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
504*12c85518Srobert     Path = ModuleIdPath(ModuleNameLoc);
505*12c85518Srobert   } else if (Cxx20Mode) {
506*12c85518Srobert     ModuleName = stringFromPath(Path);
507e5dd7070Spatrick     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
508e5dd7070Spatrick     Path = ModuleIdPath(ModuleNameLoc);
509e5dd7070Spatrick   }
510e5dd7070Spatrick 
511*12c85518Srobert   // Diagnose self-import before attempting a load.
512*12c85518Srobert   // [module.import]/9
513*12c85518Srobert   // A module implementation unit of a module M that is not a module partition
514*12c85518Srobert   // shall not contain a module-import-declaration nominating M.
515*12c85518Srobert   // (for an implementation, the module interface is imported implicitly,
516*12c85518Srobert   //  but that's handled in the module decl code).
517*12c85518Srobert 
518*12c85518Srobert   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
519*12c85518Srobert       getCurrentModule()->Name == ModuleName) {
520*12c85518Srobert     Diag(ImportLoc, diag::err_module_self_import_cxx20)
521*12c85518Srobert         << ModuleName << !ModuleScopes.back().ModuleInterface;
522*12c85518Srobert     return true;
523*12c85518Srobert   }
524*12c85518Srobert 
525*12c85518Srobert   Module *Mod = getModuleLoader().loadModule(
526*12c85518Srobert       ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
527e5dd7070Spatrick   if (!Mod)
528e5dd7070Spatrick     return true;
529e5dd7070Spatrick 
530e5dd7070Spatrick   return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
531e5dd7070Spatrick }
532e5dd7070Spatrick 
533e5dd7070Spatrick /// Determine whether \p D is lexically within an export-declaration.
getEnclosingExportDecl(const Decl * D)534e5dd7070Spatrick static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
535e5dd7070Spatrick   for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
536e5dd7070Spatrick     if (auto *ED = dyn_cast<ExportDecl>(DC))
537e5dd7070Spatrick       return ED;
538e5dd7070Spatrick   return nullptr;
539e5dd7070Spatrick }
540e5dd7070Spatrick 
ActOnModuleImport(SourceLocation StartLoc,SourceLocation ExportLoc,SourceLocation ImportLoc,Module * Mod,ModuleIdPath Path)541e5dd7070Spatrick DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
542e5dd7070Spatrick                                    SourceLocation ExportLoc,
543*12c85518Srobert                                    SourceLocation ImportLoc, Module *Mod,
544*12c85518Srobert                                    ModuleIdPath Path) {
545e5dd7070Spatrick   VisibleModules.setVisible(Mod, ImportLoc);
546e5dd7070Spatrick 
547e5dd7070Spatrick   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
548e5dd7070Spatrick 
549e5dd7070Spatrick   // FIXME: we should support importing a submodule within a different submodule
550e5dd7070Spatrick   // of the same top-level module. Until we do, make it an error rather than
551e5dd7070Spatrick   // silently ignoring the import.
552*12c85518Srobert   // FIXME: Should we warn on a redundant import of the current module?
553*12c85518Srobert   if (Mod->isForBuilding(getLangOpts()) &&
554e5dd7070Spatrick       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
555e5dd7070Spatrick     Diag(ImportLoc, getLangOpts().isCompilingModule()
556e5dd7070Spatrick                         ? diag::err_module_self_import
557e5dd7070Spatrick                         : diag::err_module_import_in_implementation)
558e5dd7070Spatrick         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
559e5dd7070Spatrick   }
560e5dd7070Spatrick 
561e5dd7070Spatrick   SmallVector<SourceLocation, 2> IdentifierLocs;
562*12c85518Srobert 
563*12c85518Srobert   if (Path.empty()) {
564*12c85518Srobert     // If this was a header import, pad out with dummy locations.
565*12c85518Srobert     // FIXME: Pass in and use the location of the header-name token in this
566*12c85518Srobert     // case.
567*12c85518Srobert     for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
568*12c85518Srobert       IdentifierLocs.push_back(SourceLocation());
569*12c85518Srobert   } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
570*12c85518Srobert     // A single identifier for the whole name.
571*12c85518Srobert     IdentifierLocs.push_back(Path[0].second);
572*12c85518Srobert   } else {
573e5dd7070Spatrick     Module *ModCheck = Mod;
574e5dd7070Spatrick     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
575*12c85518Srobert       // If we've run out of module parents, just drop the remaining
576*12c85518Srobert       // identifiers.  We need the length to be consistent.
577e5dd7070Spatrick       if (!ModCheck)
578e5dd7070Spatrick         break;
579e5dd7070Spatrick       ModCheck = ModCheck->Parent;
580e5dd7070Spatrick 
581e5dd7070Spatrick       IdentifierLocs.push_back(Path[I].second);
582e5dd7070Spatrick     }
583e5dd7070Spatrick   }
584e5dd7070Spatrick 
585e5dd7070Spatrick   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
586e5dd7070Spatrick                                           Mod, IdentifierLocs);
587e5dd7070Spatrick   CurContext->addDecl(Import);
588e5dd7070Spatrick 
589e5dd7070Spatrick   // Sequence initialization of the imported module before that of the current
590e5dd7070Spatrick   // module, if any.
591e5dd7070Spatrick   if (!ModuleScopes.empty())
592e5dd7070Spatrick     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
593e5dd7070Spatrick 
594*12c85518Srobert   // A module (partition) implementation unit shall not be exported.
595*12c85518Srobert   if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
596*12c85518Srobert       Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) {
597*12c85518Srobert     Diag(ExportLoc, diag::err_export_partition_impl)
598*12c85518Srobert         << SourceRange(ExportLoc, Path.back().second);
599*12c85518Srobert   } else if (!ModuleScopes.empty() &&
600*12c85518Srobert              (ModuleScopes.back().ModuleInterface ||
601*12c85518Srobert               (getLangOpts().CPlusPlusModules &&
602*12c85518Srobert                ModuleScopes.back().Module->isGlobalModule()))) {
603*12c85518Srobert     // Re-export the module if the imported module is exported.
604*12c85518Srobert     // Note that we don't need to add re-exported module to Imports field
605*12c85518Srobert     // since `Exports` implies the module is imported already.
606e5dd7070Spatrick     if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
607e5dd7070Spatrick       getCurrentModule()->Exports.emplace_back(Mod, false);
608*12c85518Srobert     else
609*12c85518Srobert       getCurrentModule()->Imports.insert(Mod);
610e5dd7070Spatrick   } else if (ExportLoc.isValid()) {
611*12c85518Srobert     // [module.interface]p1:
612*12c85518Srobert     // An export-declaration shall inhabit a namespace scope and appear in the
613*12c85518Srobert     // purview of a module interface unit.
614*12c85518Srobert     Diag(ExportLoc, diag::err_export_not_in_module_interface)
615*12c85518Srobert         << (!ModuleScopes.empty() &&
616*12c85518Srobert             !ModuleScopes.back().ImplicitGlobalModuleFragment);
617e5dd7070Spatrick   }
618e5dd7070Spatrick 
619*12c85518Srobert   // In some cases we need to know if an entity was present in a directly-
620*12c85518Srobert   // imported module (as opposed to a transitive import).  This avoids
621*12c85518Srobert   // searching both Imports and Exports.
622*12c85518Srobert   DirectModuleImports.insert(Mod);
623*12c85518Srobert 
624e5dd7070Spatrick   return Import;
625e5dd7070Spatrick }
626e5dd7070Spatrick 
ActOnModuleInclude(SourceLocation DirectiveLoc,Module * Mod)627e5dd7070Spatrick void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
628e5dd7070Spatrick   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
629e5dd7070Spatrick   BuildModuleInclude(DirectiveLoc, Mod);
630e5dd7070Spatrick }
631e5dd7070Spatrick 
BuildModuleInclude(SourceLocation DirectiveLoc,Module * Mod)632e5dd7070Spatrick void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
633e5dd7070Spatrick   // Determine whether we're in the #include buffer for a module. The #includes
634e5dd7070Spatrick   // in that buffer do not qualify as module imports; they're just an
635e5dd7070Spatrick   // implementation detail of us building the module.
636e5dd7070Spatrick   //
637e5dd7070Spatrick   // FIXME: Should we even get ActOnModuleInclude calls for those?
638e5dd7070Spatrick   bool IsInModuleIncludes =
639e5dd7070Spatrick       TUKind == TU_Module &&
640e5dd7070Spatrick       getSourceManager().isWrittenInMainFile(DirectiveLoc);
641e5dd7070Spatrick 
642e5dd7070Spatrick   bool ShouldAddImport = !IsInModuleIncludes;
643e5dd7070Spatrick 
644e5dd7070Spatrick   // If this module import was due to an inclusion directive, create an
645e5dd7070Spatrick   // implicit import declaration to capture it in the AST.
646e5dd7070Spatrick   if (ShouldAddImport) {
647e5dd7070Spatrick     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
648e5dd7070Spatrick     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
649e5dd7070Spatrick                                                      DirectiveLoc, Mod,
650e5dd7070Spatrick                                                      DirectiveLoc);
651e5dd7070Spatrick     if (!ModuleScopes.empty())
652e5dd7070Spatrick       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
653e5dd7070Spatrick     TU->addDecl(ImportD);
654e5dd7070Spatrick     Consumer.HandleImplicitImportDecl(ImportD);
655e5dd7070Spatrick   }
656e5dd7070Spatrick 
657e5dd7070Spatrick   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
658e5dd7070Spatrick   VisibleModules.setVisible(Mod, DirectiveLoc);
659*12c85518Srobert 
660*12c85518Srobert   if (getLangOpts().isCompilingModule()) {
661*12c85518Srobert     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
662*12c85518Srobert         getLangOpts().CurrentModule, DirectiveLoc, false, false);
663*12c85518Srobert     (void)ThisModule;
664*12c85518Srobert     assert(ThisModule && "was expecting a module if building one");
665*12c85518Srobert   }
666e5dd7070Spatrick }
667e5dd7070Spatrick 
ActOnModuleBegin(SourceLocation DirectiveLoc,Module * Mod)668e5dd7070Spatrick void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
669e5dd7070Spatrick   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
670e5dd7070Spatrick 
671e5dd7070Spatrick   ModuleScopes.push_back({});
672e5dd7070Spatrick   ModuleScopes.back().Module = Mod;
673e5dd7070Spatrick   if (getLangOpts().ModulesLocalVisibility)
674e5dd7070Spatrick     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
675e5dd7070Spatrick 
676e5dd7070Spatrick   VisibleModules.setVisible(Mod, DirectiveLoc);
677e5dd7070Spatrick 
678e5dd7070Spatrick   // The enclosing context is now part of this module.
679e5dd7070Spatrick   // FIXME: Consider creating a child DeclContext to hold the entities
680e5dd7070Spatrick   // lexically within the module.
681e5dd7070Spatrick   if (getLangOpts().trackLocalOwningModule()) {
682e5dd7070Spatrick     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
683e5dd7070Spatrick       cast<Decl>(DC)->setModuleOwnershipKind(
684e5dd7070Spatrick           getLangOpts().ModulesLocalVisibility
685e5dd7070Spatrick               ? Decl::ModuleOwnershipKind::VisibleWhenImported
686e5dd7070Spatrick               : Decl::ModuleOwnershipKind::Visible);
687e5dd7070Spatrick       cast<Decl>(DC)->setLocalOwningModule(Mod);
688e5dd7070Spatrick     }
689e5dd7070Spatrick   }
690e5dd7070Spatrick }
691e5dd7070Spatrick 
ActOnModuleEnd(SourceLocation EomLoc,Module * Mod)692e5dd7070Spatrick void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
693e5dd7070Spatrick   if (getLangOpts().ModulesLocalVisibility) {
694e5dd7070Spatrick     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
695e5dd7070Spatrick     // Leaving a module hides namespace names, so our visible namespace cache
696e5dd7070Spatrick     // is now out of date.
697e5dd7070Spatrick     VisibleNamespaceCache.clear();
698e5dd7070Spatrick   }
699e5dd7070Spatrick 
700e5dd7070Spatrick   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
701e5dd7070Spatrick          "left the wrong module scope");
702e5dd7070Spatrick   ModuleScopes.pop_back();
703e5dd7070Spatrick 
704e5dd7070Spatrick   // We got to the end of processing a local module. Create an
705e5dd7070Spatrick   // ImportDecl as we would for an imported module.
706e5dd7070Spatrick   FileID File = getSourceManager().getFileID(EomLoc);
707e5dd7070Spatrick   SourceLocation DirectiveLoc;
708e5dd7070Spatrick   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
709e5dd7070Spatrick     // We reached the end of a #included module header. Use the #include loc.
710e5dd7070Spatrick     assert(File != getSourceManager().getMainFileID() &&
711e5dd7070Spatrick            "end of submodule in main source file");
712e5dd7070Spatrick     DirectiveLoc = getSourceManager().getIncludeLoc(File);
713e5dd7070Spatrick   } else {
714e5dd7070Spatrick     // We reached an EOM pragma. Use the pragma location.
715e5dd7070Spatrick     DirectiveLoc = EomLoc;
716e5dd7070Spatrick   }
717e5dd7070Spatrick   BuildModuleInclude(DirectiveLoc, Mod);
718e5dd7070Spatrick 
719e5dd7070Spatrick   // Any further declarations are in whatever module we returned to.
720e5dd7070Spatrick   if (getLangOpts().trackLocalOwningModule()) {
721e5dd7070Spatrick     // The parser guarantees that this is the same context that we entered
722e5dd7070Spatrick     // the module within.
723e5dd7070Spatrick     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
724e5dd7070Spatrick       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
725e5dd7070Spatrick       if (!getCurrentModule())
726e5dd7070Spatrick         cast<Decl>(DC)->setModuleOwnershipKind(
727e5dd7070Spatrick             Decl::ModuleOwnershipKind::Unowned);
728e5dd7070Spatrick     }
729e5dd7070Spatrick   }
730e5dd7070Spatrick }
731e5dd7070Spatrick 
createImplicitModuleImportForErrorRecovery(SourceLocation Loc,Module * Mod)732e5dd7070Spatrick void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
733e5dd7070Spatrick                                                       Module *Mod) {
734e5dd7070Spatrick   // Bail if we're not allowed to implicitly import a module here.
735e5dd7070Spatrick   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
736e5dd7070Spatrick       VisibleModules.isVisible(Mod))
737e5dd7070Spatrick     return;
738e5dd7070Spatrick 
739e5dd7070Spatrick   // Create the implicit import declaration.
740e5dd7070Spatrick   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
741e5dd7070Spatrick   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
742e5dd7070Spatrick                                                    Loc, Mod, Loc);
743e5dd7070Spatrick   TU->addDecl(ImportD);
744e5dd7070Spatrick   Consumer.HandleImplicitImportDecl(ImportD);
745e5dd7070Spatrick 
746e5dd7070Spatrick   // Make the module visible.
747e5dd7070Spatrick   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
748e5dd7070Spatrick   VisibleModules.setVisible(Mod, Loc);
749e5dd7070Spatrick }
750e5dd7070Spatrick 
751e5dd7070Spatrick /// We have parsed the start of an export declaration, including the '{'
752e5dd7070Spatrick /// (if present).
ActOnStartExportDecl(Scope * S,SourceLocation ExportLoc,SourceLocation LBraceLoc)753e5dd7070Spatrick Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
754e5dd7070Spatrick                                  SourceLocation LBraceLoc) {
755e5dd7070Spatrick   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
756e5dd7070Spatrick 
757e5dd7070Spatrick   // Set this temporarily so we know the export-declaration was braced.
758e5dd7070Spatrick   D->setRBraceLoc(LBraceLoc);
759e5dd7070Spatrick 
760*12c85518Srobert   CurContext->addDecl(D);
761*12c85518Srobert   PushDeclContext(S, D);
762*12c85518Srobert 
763e5dd7070Spatrick   // C++2a [module.interface]p1:
764e5dd7070Spatrick   //   An export-declaration shall appear only [...] in the purview of a module
765e5dd7070Spatrick   //   interface unit. An export-declaration shall not appear directly or
766e5dd7070Spatrick   //   indirectly within [...] a private-module-fragment.
767*12c85518Srobert   if (!isCurrentModulePurview()) {
768e5dd7070Spatrick     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
769*12c85518Srobert     D->setInvalidDecl();
770*12c85518Srobert     return D;
771e5dd7070Spatrick   } else if (!ModuleScopes.back().ModuleInterface) {
772e5dd7070Spatrick     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
773e5dd7070Spatrick     Diag(ModuleScopes.back().BeginLoc,
774e5dd7070Spatrick          diag::note_not_module_interface_add_export)
775e5dd7070Spatrick         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
776*12c85518Srobert     D->setInvalidDecl();
777*12c85518Srobert     return D;
778e5dd7070Spatrick   } else if (ModuleScopes.back().Module->Kind ==
779e5dd7070Spatrick              Module::PrivateModuleFragment) {
780e5dd7070Spatrick     Diag(ExportLoc, diag::err_export_in_private_module_fragment);
781e5dd7070Spatrick     Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
782*12c85518Srobert     D->setInvalidDecl();
783*12c85518Srobert     return D;
784e5dd7070Spatrick   }
785e5dd7070Spatrick 
786e5dd7070Spatrick   for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
787e5dd7070Spatrick     if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
788e5dd7070Spatrick       //   An export-declaration shall not appear directly or indirectly within
789e5dd7070Spatrick       //   an unnamed namespace [...]
790e5dd7070Spatrick       if (ND->isAnonymousNamespace()) {
791e5dd7070Spatrick         Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
792e5dd7070Spatrick         Diag(ND->getLocation(), diag::note_anonymous_namespace);
793e5dd7070Spatrick         // Don't diagnose internal-linkage declarations in this region.
794e5dd7070Spatrick         D->setInvalidDecl();
795*12c85518Srobert         return D;
796e5dd7070Spatrick       }
797e5dd7070Spatrick 
798e5dd7070Spatrick       //   A declaration is exported if it is [...] a namespace-definition
799e5dd7070Spatrick       //   that contains an exported declaration.
800e5dd7070Spatrick       //
801e5dd7070Spatrick       // Defer exporting the namespace until after we leave it, in order to
802e5dd7070Spatrick       // avoid marking all subsequent declarations in the namespace as exported.
803e5dd7070Spatrick       if (!DeferredExportedNamespaces.insert(ND).second)
804e5dd7070Spatrick         break;
805e5dd7070Spatrick     }
806e5dd7070Spatrick   }
807e5dd7070Spatrick 
808e5dd7070Spatrick   //   [...] its declaration or declaration-seq shall not contain an
809e5dd7070Spatrick   //   export-declaration.
810e5dd7070Spatrick   if (auto *ED = getEnclosingExportDecl(D)) {
811e5dd7070Spatrick     Diag(ExportLoc, diag::err_export_within_export);
812e5dd7070Spatrick     if (ED->hasBraces())
813e5dd7070Spatrick       Diag(ED->getLocation(), diag::note_export);
814*12c85518Srobert     D->setInvalidDecl();
815*12c85518Srobert     return D;
816e5dd7070Spatrick   }
817e5dd7070Spatrick 
818e5dd7070Spatrick   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
819e5dd7070Spatrick   return D;
820e5dd7070Spatrick }
821e5dd7070Spatrick 
822e5dd7070Spatrick static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
823e5dd7070Spatrick                                      SourceLocation BlockStart);
824e5dd7070Spatrick 
825e5dd7070Spatrick namespace {
826e5dd7070Spatrick enum class UnnamedDeclKind {
827e5dd7070Spatrick   Empty,
828e5dd7070Spatrick   StaticAssert,
829e5dd7070Spatrick   Asm,
830e5dd7070Spatrick   UsingDirective,
831*12c85518Srobert   Namespace,
832e5dd7070Spatrick   Context
833e5dd7070Spatrick };
834e5dd7070Spatrick }
835e5dd7070Spatrick 
getUnnamedDeclKind(Decl * D)836*12c85518Srobert static std::optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
837e5dd7070Spatrick   if (isa<EmptyDecl>(D))
838e5dd7070Spatrick     return UnnamedDeclKind::Empty;
839e5dd7070Spatrick   if (isa<StaticAssertDecl>(D))
840e5dd7070Spatrick     return UnnamedDeclKind::StaticAssert;
841e5dd7070Spatrick   if (isa<FileScopeAsmDecl>(D))
842e5dd7070Spatrick     return UnnamedDeclKind::Asm;
843e5dd7070Spatrick   if (isa<UsingDirectiveDecl>(D))
844e5dd7070Spatrick     return UnnamedDeclKind::UsingDirective;
845e5dd7070Spatrick   // Everything else either introduces one or more names or is ill-formed.
846*12c85518Srobert   return std::nullopt;
847e5dd7070Spatrick }
848e5dd7070Spatrick 
getUnnamedDeclDiag(UnnamedDeclKind UDK,bool InBlock)849e5dd7070Spatrick unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
850e5dd7070Spatrick   switch (UDK) {
851e5dd7070Spatrick   case UnnamedDeclKind::Empty:
852e5dd7070Spatrick   case UnnamedDeclKind::StaticAssert:
853e5dd7070Spatrick     // Allow empty-declarations and static_asserts in an export block as an
854e5dd7070Spatrick     // extension.
855e5dd7070Spatrick     return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
856e5dd7070Spatrick 
857e5dd7070Spatrick   case UnnamedDeclKind::UsingDirective:
858e5dd7070Spatrick     // Allow exporting using-directives as an extension.
859e5dd7070Spatrick     return diag::ext_export_using_directive;
860e5dd7070Spatrick 
861*12c85518Srobert   case UnnamedDeclKind::Namespace:
862*12c85518Srobert     // Anonymous namespace with no content.
863*12c85518Srobert     return diag::introduces_no_names;
864*12c85518Srobert 
865e5dd7070Spatrick   case UnnamedDeclKind::Context:
866e5dd7070Spatrick     // Allow exporting DeclContexts that transitively contain no declarations
867e5dd7070Spatrick     // as an extension.
868e5dd7070Spatrick     return diag::ext_export_no_names;
869e5dd7070Spatrick 
870e5dd7070Spatrick   case UnnamedDeclKind::Asm:
871e5dd7070Spatrick     return diag::err_export_no_name;
872e5dd7070Spatrick   }
873e5dd7070Spatrick   llvm_unreachable("unknown kind");
874e5dd7070Spatrick }
875e5dd7070Spatrick 
diagExportedUnnamedDecl(Sema & S,UnnamedDeclKind UDK,Decl * D,SourceLocation BlockStart)876e5dd7070Spatrick static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
877e5dd7070Spatrick                                     SourceLocation BlockStart) {
878e5dd7070Spatrick   S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
879e5dd7070Spatrick       << (unsigned)UDK;
880e5dd7070Spatrick   if (BlockStart.isValid())
881e5dd7070Spatrick     S.Diag(BlockStart, diag::note_export);
882e5dd7070Spatrick }
883e5dd7070Spatrick 
884e5dd7070Spatrick /// Check that it's valid to export \p D.
checkExportedDecl(Sema & S,Decl * D,SourceLocation BlockStart)885e5dd7070Spatrick static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
886e5dd7070Spatrick   // C++2a [module.interface]p3:
887e5dd7070Spatrick   //   An exported declaration shall declare at least one name
888e5dd7070Spatrick   if (auto UDK = getUnnamedDeclKind(D))
889e5dd7070Spatrick     diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
890e5dd7070Spatrick 
891e5dd7070Spatrick   //   [...] shall not declare a name with internal linkage.
892*12c85518Srobert   bool HasName = false;
893e5dd7070Spatrick   if (auto *ND = dyn_cast<NamedDecl>(D)) {
894e5dd7070Spatrick     // Don't diagnose anonymous union objects; we'll diagnose their members
895e5dd7070Spatrick     // instead.
896*12c85518Srobert     HasName = (bool)ND->getDeclName();
897*12c85518Srobert     if (HasName && ND->getFormalLinkage() == InternalLinkage) {
898e5dd7070Spatrick       S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
899e5dd7070Spatrick       if (BlockStart.isValid())
900e5dd7070Spatrick         S.Diag(BlockStart, diag::note_export);
901e5dd7070Spatrick     }
902e5dd7070Spatrick   }
903e5dd7070Spatrick 
904e5dd7070Spatrick   // C++2a [module.interface]p5:
905e5dd7070Spatrick   //   all entities to which all of the using-declarators ultimately refer
906e5dd7070Spatrick   //   shall have been introduced with a name having external linkage
907e5dd7070Spatrick   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
908e5dd7070Spatrick     NamedDecl *Target = USD->getUnderlyingDecl();
909*12c85518Srobert     Linkage Lk = Target->getFormalLinkage();
910*12c85518Srobert     if (Lk == InternalLinkage || Lk == ModuleLinkage) {
911*12c85518Srobert       S.Diag(USD->getLocation(), diag::err_export_using_internal)
912*12c85518Srobert           << (Lk == InternalLinkage ? 0 : 1) << Target;
913e5dd7070Spatrick       S.Diag(Target->getLocation(), diag::note_using_decl_target);
914e5dd7070Spatrick       if (BlockStart.isValid())
915e5dd7070Spatrick         S.Diag(BlockStart, diag::note_export);
916e5dd7070Spatrick     }
917e5dd7070Spatrick   }
918e5dd7070Spatrick 
919e5dd7070Spatrick   // Recurse into namespace-scope DeclContexts. (Only namespace-scope
920*12c85518Srobert   // declarations are exported.).
921*12c85518Srobert   if (auto *DC = dyn_cast<DeclContext>(D)) {
922*12c85518Srobert     if (isa<NamespaceDecl>(D) && DC->decls().empty()) {
923*12c85518Srobert       if (!HasName)
924*12c85518Srobert         // We don't allow an empty anonymous namespace (we don't allow decls
925*12c85518Srobert         // in them either, but that's handled in the recursion).
926*12c85518Srobert         diagExportedUnnamedDecl(S, UnnamedDeclKind::Namespace, D, BlockStart);
927*12c85518Srobert       // We allow an empty named namespace decl.
928*12c85518Srobert     } else if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
929e5dd7070Spatrick       return checkExportedDeclContext(S, DC, BlockStart);
930*12c85518Srobert   }
931e5dd7070Spatrick   return false;
932e5dd7070Spatrick }
933e5dd7070Spatrick 
934e5dd7070Spatrick /// Check that it's valid to export all the declarations in \p DC.
checkExportedDeclContext(Sema & S,DeclContext * DC,SourceLocation BlockStart)935e5dd7070Spatrick static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
936e5dd7070Spatrick                                      SourceLocation BlockStart) {
937e5dd7070Spatrick   bool AllUnnamed = true;
938e5dd7070Spatrick   for (auto *D : DC->decls())
939e5dd7070Spatrick     AllUnnamed &= checkExportedDecl(S, D, BlockStart);
940e5dd7070Spatrick   return AllUnnamed;
941e5dd7070Spatrick }
942e5dd7070Spatrick 
943e5dd7070Spatrick /// Complete the definition of an export declaration.
ActOnFinishExportDecl(Scope * S,Decl * D,SourceLocation RBraceLoc)944e5dd7070Spatrick Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
945e5dd7070Spatrick   auto *ED = cast<ExportDecl>(D);
946e5dd7070Spatrick   if (RBraceLoc.isValid())
947e5dd7070Spatrick     ED->setRBraceLoc(RBraceLoc);
948e5dd7070Spatrick 
949e5dd7070Spatrick   PopDeclContext();
950e5dd7070Spatrick 
951e5dd7070Spatrick   if (!D->isInvalidDecl()) {
952e5dd7070Spatrick     SourceLocation BlockStart =
953e5dd7070Spatrick         ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
954e5dd7070Spatrick     for (auto *Child : ED->decls()) {
955e5dd7070Spatrick       if (checkExportedDecl(*this, Child, BlockStart)) {
956e5dd7070Spatrick         // If a top-level child is a linkage-spec declaration, it might contain
957e5dd7070Spatrick         // no declarations (transitively), in which case it's ill-formed.
958e5dd7070Spatrick         diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
959e5dd7070Spatrick                                 BlockStart);
960e5dd7070Spatrick       }
961*12c85518Srobert       if (auto *FD = dyn_cast<FunctionDecl>(Child)) {
962*12c85518Srobert         // [dcl.inline]/7
963*12c85518Srobert         // If an inline function or variable that is attached to a named module
964*12c85518Srobert         // is declared in a definition domain, it shall be defined in that
965*12c85518Srobert         // domain.
966*12c85518Srobert         // So, if the current declaration does not have a definition, we must
967*12c85518Srobert         // check at the end of the TU (or when the PMF starts) to see that we
968*12c85518Srobert         // have a definition at that point.
969*12c85518Srobert         if (FD->isInlineSpecified() && !FD->isDefined())
970*12c85518Srobert           PendingInlineFuncDecls.insert(FD);
971*12c85518Srobert       }
972e5dd7070Spatrick     }
973e5dd7070Spatrick   }
974e5dd7070Spatrick 
975e5dd7070Spatrick   return D;
976e5dd7070Spatrick }
977*12c85518Srobert 
PushGlobalModuleFragment(SourceLocation BeginLoc,bool IsImplicit)978*12c85518Srobert Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc,
979*12c85518Srobert                                        bool IsImplicit) {
980*12c85518Srobert   // We shouldn't create new global module fragment if there is already
981*12c85518Srobert   // one.
982*12c85518Srobert   if (!GlobalModuleFragment) {
983*12c85518Srobert     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
984*12c85518Srobert     GlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
985*12c85518Srobert         BeginLoc, getCurrentModule());
986*12c85518Srobert   }
987*12c85518Srobert 
988*12c85518Srobert   assert(GlobalModuleFragment && "module creation should not fail");
989*12c85518Srobert 
990*12c85518Srobert   // Enter the scope of the global module.
991*12c85518Srobert   ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
992*12c85518Srobert                           /*ModuleInterface=*/false,
993*12c85518Srobert                           /*IsPartition=*/false,
994*12c85518Srobert                           /*ImplicitGlobalModuleFragment=*/IsImplicit,
995*12c85518Srobert                           /*OuterVisibleModules=*/{}});
996*12c85518Srobert   VisibleModules.setVisible(GlobalModuleFragment, BeginLoc);
997*12c85518Srobert 
998*12c85518Srobert   return GlobalModuleFragment;
999*12c85518Srobert }
1000*12c85518Srobert 
PopGlobalModuleFragment()1001*12c85518Srobert void Sema::PopGlobalModuleFragment() {
1002*12c85518Srobert   assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
1003*12c85518Srobert          "left the wrong module scope, which is not global module fragment");
1004*12c85518Srobert   ModuleScopes.pop_back();
1005*12c85518Srobert }
1006*12c85518Srobert 
isModuleUnitOfCurrentTU(const Module * M) const1007*12c85518Srobert bool Sema::isModuleUnitOfCurrentTU(const Module *M) const {
1008*12c85518Srobert   assert(M);
1009*12c85518Srobert 
1010*12c85518Srobert   Module *CurrentModuleUnit = getCurrentModule();
1011*12c85518Srobert 
1012*12c85518Srobert   // If we are not in a module currently, M must not be the module unit of
1013*12c85518Srobert   // current TU.
1014*12c85518Srobert   if (!CurrentModuleUnit)
1015*12c85518Srobert     return false;
1016*12c85518Srobert 
1017*12c85518Srobert   return M->isSubModuleOf(CurrentModuleUnit->getTopLevelModule());
1018*12c85518Srobert }
1019