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