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