xref: /llvm-project/clang/lib/Sema/SemaModule.cpp (revision 1a76d2563940e6b4bfcb9e77b8a4d1d3f0cc7d30)
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                                    ModuleIdPath Partition) {
369 
370   bool IsPartition = !Partition.empty();
371   bool Cxx20Mode = getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS;
372   assert((!IsPartition || Cxx20Mode) && "partition seen in non-C++20 code?");
373   assert((!IsPartition || Path.empty()) &&
374          "trying to import a partition with its named module specified?");
375 
376   // For a C++20 module name, flatten into a single identifier with the source
377   // location of the first component.
378   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
379 
380   std::string ModuleName;
381   if (IsPartition) {
382     // We already checked that we are in a module purview in the parser.
383     assert(!ModuleScopes.empty() && "in a module purview, but no module?");
384     Module *NamedMod = ModuleScopes.back().Module;
385     if (ModuleScopes.back().IsPartition) {
386       // We're importing a partition into a partition, find the name of the
387       // owning named module.
388       size_t P = NamedMod->Name.find_first_of(":");
389       ModuleName = NamedMod->Name.substr(0, P + 1);
390     } else {
391       // We're importing a partition into the named module itself (either the
392       // interface or an implementation TU).
393       ModuleName = NamedMod->Name;
394       ModuleName += ":";
395     }
396     ModuleName += stringFromPath(Partition);
397     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Partition[0].second};
398     Partition = ModuleIdPath(ModuleNameLoc);
399   } else if (Cxx20Mode) {
400     ModuleName = stringFromPath(Path);
401     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
402     Path = ModuleIdPath(ModuleNameLoc);
403   }
404 
405   // Diagnose self-import before attempting a load.
406   // [module.import]/9
407   // A module implementation unit of a module M that is not a module partition
408   // shall not contain a module-import-declaration nominating M.
409   // (for an implementation, the module interface is imported implicitly,
410   //  but that's handled in the module decl code).
411 
412   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
413       getCurrentModule()->Name == ModuleName) {
414     Diag(ImportLoc, diag::err_module_self_import_cxx20)
415         << ModuleName << !ModuleScopes.back().ModuleInterface;
416     return true;
417   }
418 
419   Module *Mod = getModuleLoader().loadModule(
420       ImportLoc, IsPartition ? Partition : Path, Module::AllVisible,
421       /*IsInclusionDirective=*/false);
422   if (!Mod)
423     return true;
424 
425   return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod,
426                            IsPartition ? Partition : Path);
427 }
428 
429 /// Determine whether \p D is lexically within an export-declaration.
430 static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
431   for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
432     if (auto *ED = dyn_cast<ExportDecl>(DC))
433       return ED;
434   return nullptr;
435 }
436 
437 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
438                                    SourceLocation ExportLoc,
439                                    SourceLocation ImportLoc, Module *Mod,
440                                    ModuleIdPath Path) {
441   VisibleModules.setVisible(Mod, ImportLoc);
442 
443   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
444 
445   // FIXME: we should support importing a submodule within a different submodule
446   // of the same top-level module. Until we do, make it an error rather than
447   // silently ignoring the import.
448   // FIXME: Should we warn on a redundant import of the current module?
449   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
450       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
451     Diag(ImportLoc, getLangOpts().isCompilingModule()
452                         ? diag::err_module_self_import
453                         : diag::err_module_import_in_implementation)
454         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
455   }
456 
457   SmallVector<SourceLocation, 2> IdentifierLocs;
458 
459   if (Path.empty()) {
460     // If this was a header import, pad out with dummy locations.
461     // FIXME: Pass in and use the location of the header-name token in this
462     // case.
463     for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
464       IdentifierLocs.push_back(SourceLocation());
465   } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
466     // A single identifier for the whole name.
467     IdentifierLocs.push_back(Path[0].second);
468   } else {
469     Module *ModCheck = Mod;
470     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
471       // If we've run out of module parents, just drop the remaining
472       // identifiers.  We need the length to be consistent.
473       if (!ModCheck)
474         break;
475       ModCheck = ModCheck->Parent;
476 
477       IdentifierLocs.push_back(Path[I].second);
478     }
479   }
480 
481   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
482                                           Mod, IdentifierLocs);
483   CurContext->addDecl(Import);
484 
485   // Sequence initialization of the imported module before that of the current
486   // module, if any.
487   if (!ModuleScopes.empty())
488     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
489 
490   // A module (partition) implementation unit shall not be exported.
491   if (getLangOpts().CPlusPlusModules && Mod && ExportLoc.isValid() &&
492       Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) {
493     Diag(ExportLoc, diag::err_export_partition_impl)
494         << SourceRange(ExportLoc, Path.back().second);
495   } else if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) {
496     // Re-export the module if the imported module is exported.
497     // Note that we don't need to add re-exported module to Imports field
498     // since `Exports` implies the module is imported already.
499     if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
500       getCurrentModule()->Exports.emplace_back(Mod, false);
501     else
502       getCurrentModule()->Imports.insert(Mod);
503   } else if (ExportLoc.isValid()) {
504     // [module.interface]p1:
505     // An export-declaration shall inhabit a namespace scope and appear in the
506     // purview of a module interface unit.
507     Diag(ExportLoc, diag::err_export_not_in_module_interface)
508         << (!ModuleScopes.empty() &&
509             !ModuleScopes.back().ImplicitGlobalModuleFragment);
510   } else if (getLangOpts().isCompilingModule()) {
511     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
512         getLangOpts().CurrentModule, ExportLoc, false, false);
513     (void)ThisModule;
514     assert(ThisModule && "was expecting a module if building one");
515   }
516 
517   return Import;
518 }
519 
520 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
521   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
522   BuildModuleInclude(DirectiveLoc, Mod);
523 }
524 
525 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
526   // Determine whether we're in the #include buffer for a module. The #includes
527   // in that buffer do not qualify as module imports; they're just an
528   // implementation detail of us building the module.
529   //
530   // FIXME: Should we even get ActOnModuleInclude calls for those?
531   bool IsInModuleIncludes =
532       TUKind == TU_Module &&
533       getSourceManager().isWrittenInMainFile(DirectiveLoc);
534 
535   bool ShouldAddImport = !IsInModuleIncludes;
536 
537   // If this module import was due to an inclusion directive, create an
538   // implicit import declaration to capture it in the AST.
539   if (ShouldAddImport) {
540     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
541     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
542                                                      DirectiveLoc, Mod,
543                                                      DirectiveLoc);
544     if (!ModuleScopes.empty())
545       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
546     TU->addDecl(ImportD);
547     Consumer.HandleImplicitImportDecl(ImportD);
548   }
549 
550   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
551   VisibleModules.setVisible(Mod, DirectiveLoc);
552 
553   if (getLangOpts().isCompilingModule()) {
554     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
555         getLangOpts().CurrentModule, DirectiveLoc, false, false);
556     (void)ThisModule;
557     assert(ThisModule && "was expecting a module if building one");
558   }
559 }
560 
561 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
562   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
563 
564   ModuleScopes.push_back({});
565   ModuleScopes.back().Module = Mod;
566   if (getLangOpts().ModulesLocalVisibility)
567     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
568 
569   VisibleModules.setVisible(Mod, DirectiveLoc);
570 
571   // The enclosing context is now part of this module.
572   // FIXME: Consider creating a child DeclContext to hold the entities
573   // lexically within the module.
574   if (getLangOpts().trackLocalOwningModule()) {
575     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
576       cast<Decl>(DC)->setModuleOwnershipKind(
577           getLangOpts().ModulesLocalVisibility
578               ? Decl::ModuleOwnershipKind::VisibleWhenImported
579               : Decl::ModuleOwnershipKind::Visible);
580       cast<Decl>(DC)->setLocalOwningModule(Mod);
581     }
582   }
583 }
584 
585 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
586   if (getLangOpts().ModulesLocalVisibility) {
587     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
588     // Leaving a module hides namespace names, so our visible namespace cache
589     // is now out of date.
590     VisibleNamespaceCache.clear();
591   }
592 
593   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
594          "left the wrong module scope");
595   ModuleScopes.pop_back();
596 
597   // We got to the end of processing a local module. Create an
598   // ImportDecl as we would for an imported module.
599   FileID File = getSourceManager().getFileID(EomLoc);
600   SourceLocation DirectiveLoc;
601   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
602     // We reached the end of a #included module header. Use the #include loc.
603     assert(File != getSourceManager().getMainFileID() &&
604            "end of submodule in main source file");
605     DirectiveLoc = getSourceManager().getIncludeLoc(File);
606   } else {
607     // We reached an EOM pragma. Use the pragma location.
608     DirectiveLoc = EomLoc;
609   }
610   BuildModuleInclude(DirectiveLoc, Mod);
611 
612   // Any further declarations are in whatever module we returned to.
613   if (getLangOpts().trackLocalOwningModule()) {
614     // The parser guarantees that this is the same context that we entered
615     // the module within.
616     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
617       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
618       if (!getCurrentModule())
619         cast<Decl>(DC)->setModuleOwnershipKind(
620             Decl::ModuleOwnershipKind::Unowned);
621     }
622   }
623 }
624 
625 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
626                                                       Module *Mod) {
627   // Bail if we're not allowed to implicitly import a module here.
628   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
629       VisibleModules.isVisible(Mod))
630     return;
631 
632   // Create the implicit import declaration.
633   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
634   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
635                                                    Loc, Mod, Loc);
636   TU->addDecl(ImportD);
637   Consumer.HandleImplicitImportDecl(ImportD);
638 
639   // Make the module visible.
640   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
641   VisibleModules.setVisible(Mod, Loc);
642 }
643 
644 /// We have parsed the start of an export declaration, including the '{'
645 /// (if present).
646 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
647                                  SourceLocation LBraceLoc) {
648   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
649 
650   // Set this temporarily so we know the export-declaration was braced.
651   D->setRBraceLoc(LBraceLoc);
652 
653   CurContext->addDecl(D);
654   PushDeclContext(S, D);
655 
656   // C++2a [module.interface]p1:
657   //   An export-declaration shall appear only [...] in the purview of a module
658   //   interface unit. An export-declaration shall not appear directly or
659   //   indirectly within [...] a private-module-fragment.
660   if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
661     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
662     D->setInvalidDecl();
663     return D;
664   } else if (!ModuleScopes.back().ModuleInterface) {
665     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
666     Diag(ModuleScopes.back().BeginLoc,
667          diag::note_not_module_interface_add_export)
668         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
669     D->setInvalidDecl();
670     return D;
671   } else if (ModuleScopes.back().Module->Kind ==
672              Module::PrivateModuleFragment) {
673     Diag(ExportLoc, diag::err_export_in_private_module_fragment);
674     Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
675     D->setInvalidDecl();
676     return D;
677   }
678 
679   for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
680     if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
681       //   An export-declaration shall not appear directly or indirectly within
682       //   an unnamed namespace [...]
683       if (ND->isAnonymousNamespace()) {
684         Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
685         Diag(ND->getLocation(), diag::note_anonymous_namespace);
686         // Don't diagnose internal-linkage declarations in this region.
687         D->setInvalidDecl();
688         return D;
689       }
690 
691       //   A declaration is exported if it is [...] a namespace-definition
692       //   that contains an exported declaration.
693       //
694       // Defer exporting the namespace until after we leave it, in order to
695       // avoid marking all subsequent declarations in the namespace as exported.
696       if (!DeferredExportedNamespaces.insert(ND).second)
697         break;
698     }
699   }
700 
701   //   [...] its declaration or declaration-seq shall not contain an
702   //   export-declaration.
703   if (auto *ED = getEnclosingExportDecl(D)) {
704     Diag(ExportLoc, diag::err_export_within_export);
705     if (ED->hasBraces())
706       Diag(ED->getLocation(), diag::note_export);
707     D->setInvalidDecl();
708     return D;
709   }
710 
711   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
712   return D;
713 }
714 
715 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
716                                      SourceLocation BlockStart);
717 
718 namespace {
719 enum class UnnamedDeclKind {
720   Empty,
721   StaticAssert,
722   Asm,
723   UsingDirective,
724   Context
725 };
726 }
727 
728 static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
729   if (isa<EmptyDecl>(D))
730     return UnnamedDeclKind::Empty;
731   if (isa<StaticAssertDecl>(D))
732     return UnnamedDeclKind::StaticAssert;
733   if (isa<FileScopeAsmDecl>(D))
734     return UnnamedDeclKind::Asm;
735   if (isa<UsingDirectiveDecl>(D))
736     return UnnamedDeclKind::UsingDirective;
737   // Everything else either introduces one or more names or is ill-formed.
738   return llvm::None;
739 }
740 
741 unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
742   switch (UDK) {
743   case UnnamedDeclKind::Empty:
744   case UnnamedDeclKind::StaticAssert:
745     // Allow empty-declarations and static_asserts in an export block as an
746     // extension.
747     return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
748 
749   case UnnamedDeclKind::UsingDirective:
750     // Allow exporting using-directives as an extension.
751     return diag::ext_export_using_directive;
752 
753   case UnnamedDeclKind::Context:
754     // Allow exporting DeclContexts that transitively contain no declarations
755     // as an extension.
756     return diag::ext_export_no_names;
757 
758   case UnnamedDeclKind::Asm:
759     return diag::err_export_no_name;
760   }
761   llvm_unreachable("unknown kind");
762 }
763 
764 static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
765                                     SourceLocation BlockStart) {
766   S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
767       << (unsigned)UDK;
768   if (BlockStart.isValid())
769     S.Diag(BlockStart, diag::note_export);
770 }
771 
772 /// Check that it's valid to export \p D.
773 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
774   // C++2a [module.interface]p3:
775   //   An exported declaration shall declare at least one name
776   if (auto UDK = getUnnamedDeclKind(D))
777     diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
778 
779   //   [...] shall not declare a name with internal linkage.
780   if (auto *ND = dyn_cast<NamedDecl>(D)) {
781     // Don't diagnose anonymous union objects; we'll diagnose their members
782     // instead.
783     if (ND->getDeclName() && ND->getFormalLinkage() == InternalLinkage) {
784       S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
785       if (BlockStart.isValid())
786         S.Diag(BlockStart, diag::note_export);
787     }
788   }
789 
790   // C++2a [module.interface]p5:
791   //   all entities to which all of the using-declarators ultimately refer
792   //   shall have been introduced with a name having external linkage
793   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
794     NamedDecl *Target = USD->getUnderlyingDecl();
795     if (Target->getFormalLinkage() == InternalLinkage) {
796       S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
797       S.Diag(Target->getLocation(), diag::note_using_decl_target);
798       if (BlockStart.isValid())
799         S.Diag(BlockStart, diag::note_export);
800     }
801   }
802 
803   // Recurse into namespace-scope DeclContexts. (Only namespace-scope
804   // declarations are exported.)
805   if (auto *DC = dyn_cast<DeclContext>(D))
806     if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
807       return checkExportedDeclContext(S, DC, BlockStart);
808   return false;
809 }
810 
811 /// Check that it's valid to export all the declarations in \p DC.
812 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
813                                      SourceLocation BlockStart) {
814   bool AllUnnamed = true;
815   for (auto *D : DC->decls())
816     AllUnnamed &= checkExportedDecl(S, D, BlockStart);
817   return AllUnnamed;
818 }
819 
820 /// Complete the definition of an export declaration.
821 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
822   auto *ED = cast<ExportDecl>(D);
823   if (RBraceLoc.isValid())
824     ED->setRBraceLoc(RBraceLoc);
825 
826   PopDeclContext();
827 
828   if (!D->isInvalidDecl()) {
829     SourceLocation BlockStart =
830         ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
831     for (auto *Child : ED->decls()) {
832       if (checkExportedDecl(*this, Child, BlockStart)) {
833         // If a top-level child is a linkage-spec declaration, it might contain
834         // no declarations (transitively), in which case it's ill-formed.
835         diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
836                                 BlockStart);
837       }
838     }
839   }
840 
841   return D;
842 }
843 
844 Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc,
845                                        bool IsImplicit) {
846   // We shouldn't create new global module fragment if there is already
847   // one.
848   if (!GlobalModuleFragment) {
849     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
850     GlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
851         BeginLoc, getCurrentModule());
852   }
853 
854   assert(GlobalModuleFragment && "module creation should not fail");
855 
856   // Enter the scope of the global module.
857   ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
858                           /*ModuleInterface=*/false,
859                           /*IsPartition=*/false,
860                           /*ImplicitGlobalModuleFragment=*/IsImplicit,
861                           /*OuterVisibleModules=*/{}});
862   VisibleModules.setVisible(GlobalModuleFragment, BeginLoc);
863 
864   return GlobalModuleFragment;
865 }
866 
867 void Sema::PopGlobalModuleFragment() {
868   assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
869          "left the wrong module scope, which is not global module fragment");
870   ModuleScopes.pop_back();
871 }
872