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     Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
265     return nullptr;
266 
267   case Module::PrivateModuleFragment:
268     Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
269     Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
270     return nullptr;
271 
272   case Module::ModuleInterfaceUnit:
273     break;
274   }
275 
276   if (!ModuleScopes.back().ModuleInterface) {
277     Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
278     Diag(ModuleScopes.back().BeginLoc,
279          diag::note_not_module_interface_add_export)
280         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
281     return nullptr;
282   }
283 
284   // FIXME: Check this isn't a module interface partition.
285   // FIXME: Check that this translation unit does not import any partitions;
286   // such imports would violate [basic.link]/2's "shall be the only module unit"
287   // restriction.
288 
289   // We've finished the public fragment of the translation unit.
290   ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
291 
292   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
293   Module *PrivateModuleFragment =
294       Map.createPrivateModuleFragmentForInterfaceUnit(
295           ModuleScopes.back().Module, PrivateLoc);
296   assert(PrivateModuleFragment && "module creation should not fail");
297 
298   // Enter the scope of the private module fragment.
299   ModuleScopes.push_back({});
300   ModuleScopes.back().BeginLoc = ModuleLoc;
301   ModuleScopes.back().Module = PrivateModuleFragment;
302   ModuleScopes.back().ModuleInterface = true;
303   VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
304 
305   // All declarations created from now on are scoped to the private module
306   // fragment (and are neither visible nor reachable in importers of the module
307   // interface).
308   auto *TU = Context.getTranslationUnitDecl();
309   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
310   TU->setLocalOwningModule(PrivateModuleFragment);
311 
312   // FIXME: Consider creating an explicit representation of this declaration.
313   return nullptr;
314 }
315 
316 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
317                                    SourceLocation ExportLoc,
318                                    SourceLocation ImportLoc,
319                                    ModuleIdPath Path) {
320   // Flatten the module path for a C++20 or Modules TS module name.
321   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
322   std::string ModuleName;
323   if (getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS) {
324     for (auto &Piece : Path) {
325       if (!ModuleName.empty())
326         ModuleName += ".";
327       ModuleName += Piece.first->getName();
328     }
329     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
330     Path = ModuleIdPath(ModuleNameLoc);
331   }
332 
333   // Diagnose self-import before attempting a load.
334   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
335       getCurrentModule()->Name == ModuleName) {
336     Diag(ImportLoc, diag::err_module_self_import)
337         << ModuleName << getLangOpts().CurrentModule;
338     return true;
339   }
340 
341   Module *Mod =
342       getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
343                                    /*IsInclusionDirective=*/false);
344   if (!Mod)
345     return true;
346 
347   return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
348 }
349 
350 /// Determine whether \p D is lexically within an export-declaration.
351 static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
352   for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
353     if (auto *ED = dyn_cast<ExportDecl>(DC))
354       return ED;
355   return nullptr;
356 }
357 
358 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
359                                    SourceLocation ExportLoc,
360                                    SourceLocation ImportLoc,
361                                    Module *Mod, ModuleIdPath Path) {
362   VisibleModules.setVisible(Mod, ImportLoc);
363 
364   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
365 
366   // FIXME: we should support importing a submodule within a different submodule
367   // of the same top-level module. Until we do, make it an error rather than
368   // silently ignoring the import.
369   // FIXME: Should we warn on a redundant import of the current module?
370   if (!getLangOpts().CPlusPlusModules &&
371       Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
372       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
373     Diag(ImportLoc, getLangOpts().isCompilingModule()
374                         ? diag::err_module_self_import
375                         : diag::err_module_import_in_implementation)
376         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
377   }
378 
379   SmallVector<SourceLocation, 2> IdentifierLocs;
380   Module *ModCheck = Mod;
381   for (unsigned I = 0, N = Path.size(); I != N; ++I) {
382     // If we've run out of module parents, just drop the remaining identifiers.
383     // We need the length to be consistent.
384     if (!ModCheck)
385       break;
386     ModCheck = ModCheck->Parent;
387 
388     IdentifierLocs.push_back(Path[I].second);
389   }
390 
391   // If this was a header import, pad out with dummy locations.
392   // FIXME: Pass in and use the location of the header-name token in this case.
393   if (Path.empty()) {
394     for (; ModCheck; ModCheck = ModCheck->Parent) {
395       IdentifierLocs.push_back(SourceLocation());
396     }
397   }
398 
399   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
400                                           Mod, IdentifierLocs);
401   CurContext->addDecl(Import);
402 
403   // Sequence initialization of the imported module before that of the current
404   // module, if any.
405   if (!ModuleScopes.empty())
406     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
407 
408   if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) {
409     // Re-export the module if the imported module is exported.
410     // Note that we don't need to add re-exported module to Imports field
411     // since `Exports` implies the module is imported already.
412     if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
413       getCurrentModule()->Exports.emplace_back(Mod, false);
414     else
415       getCurrentModule()->Imports.insert(Mod);
416   } else if (ExportLoc.isValid()) {
417     // [module.interface]p1:
418     // An export-declaration shall inhabit a namespace scope and appear in the
419     // purview of a module interface unit.
420     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
421   }
422 
423   return Import;
424 }
425 
426 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
427   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
428   BuildModuleInclude(DirectiveLoc, Mod);
429 }
430 
431 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
432   // Determine whether we're in the #include buffer for a module. The #includes
433   // in that buffer do not qualify as module imports; they're just an
434   // implementation detail of us building the module.
435   //
436   // FIXME: Should we even get ActOnModuleInclude calls for those?
437   bool IsInModuleIncludes =
438       TUKind == TU_Module &&
439       getSourceManager().isWrittenInMainFile(DirectiveLoc);
440 
441   bool ShouldAddImport = !IsInModuleIncludes;
442 
443   // If this module import was due to an inclusion directive, create an
444   // implicit import declaration to capture it in the AST.
445   if (ShouldAddImport) {
446     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
447     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
448                                                      DirectiveLoc, Mod,
449                                                      DirectiveLoc);
450     if (!ModuleScopes.empty())
451       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
452     TU->addDecl(ImportD);
453     Consumer.HandleImplicitImportDecl(ImportD);
454   }
455 
456   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
457   VisibleModules.setVisible(Mod, DirectiveLoc);
458 }
459 
460 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
461   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
462 
463   ModuleScopes.push_back({});
464   ModuleScopes.back().Module = Mod;
465   if (getLangOpts().ModulesLocalVisibility)
466     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
467 
468   VisibleModules.setVisible(Mod, DirectiveLoc);
469 
470   // The enclosing context is now part of this module.
471   // FIXME: Consider creating a child DeclContext to hold the entities
472   // lexically within the module.
473   if (getLangOpts().trackLocalOwningModule()) {
474     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
475       cast<Decl>(DC)->setModuleOwnershipKind(
476           getLangOpts().ModulesLocalVisibility
477               ? Decl::ModuleOwnershipKind::VisibleWhenImported
478               : Decl::ModuleOwnershipKind::Visible);
479       cast<Decl>(DC)->setLocalOwningModule(Mod);
480     }
481   }
482 }
483 
484 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
485   if (getLangOpts().ModulesLocalVisibility) {
486     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
487     // Leaving a module hides namespace names, so our visible namespace cache
488     // is now out of date.
489     VisibleNamespaceCache.clear();
490   }
491 
492   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
493          "left the wrong module scope");
494   ModuleScopes.pop_back();
495 
496   // We got to the end of processing a local module. Create an
497   // ImportDecl as we would for an imported module.
498   FileID File = getSourceManager().getFileID(EomLoc);
499   SourceLocation DirectiveLoc;
500   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
501     // We reached the end of a #included module header. Use the #include loc.
502     assert(File != getSourceManager().getMainFileID() &&
503            "end of submodule in main source file");
504     DirectiveLoc = getSourceManager().getIncludeLoc(File);
505   } else {
506     // We reached an EOM pragma. Use the pragma location.
507     DirectiveLoc = EomLoc;
508   }
509   BuildModuleInclude(DirectiveLoc, Mod);
510 
511   // Any further declarations are in whatever module we returned to.
512   if (getLangOpts().trackLocalOwningModule()) {
513     // The parser guarantees that this is the same context that we entered
514     // the module within.
515     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
516       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
517       if (!getCurrentModule())
518         cast<Decl>(DC)->setModuleOwnershipKind(
519             Decl::ModuleOwnershipKind::Unowned);
520     }
521   }
522 }
523 
524 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
525                                                       Module *Mod) {
526   // Bail if we're not allowed to implicitly import a module here.
527   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
528       VisibleModules.isVisible(Mod))
529     return;
530 
531   // Create the implicit import declaration.
532   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
533   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
534                                                    Loc, Mod, Loc);
535   TU->addDecl(ImportD);
536   Consumer.HandleImplicitImportDecl(ImportD);
537 
538   // Make the module visible.
539   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
540   VisibleModules.setVisible(Mod, Loc);
541 }
542 
543 /// We have parsed the start of an export declaration, including the '{'
544 /// (if present).
545 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
546                                  SourceLocation LBraceLoc) {
547   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
548 
549   // Set this temporarily so we know the export-declaration was braced.
550   D->setRBraceLoc(LBraceLoc);
551 
552   CurContext->addDecl(D);
553   PushDeclContext(S, D);
554 
555   // C++2a [module.interface]p1:
556   //   An export-declaration shall appear only [...] in the purview of a module
557   //   interface unit. An export-declaration shall not appear directly or
558   //   indirectly within [...] a private-module-fragment.
559   if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
560     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
561     D->setInvalidDecl();
562     return D;
563   } else if (!ModuleScopes.back().ModuleInterface) {
564     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
565     Diag(ModuleScopes.back().BeginLoc,
566          diag::note_not_module_interface_add_export)
567         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
568     D->setInvalidDecl();
569     return D;
570   } else if (ModuleScopes.back().Module->Kind ==
571              Module::PrivateModuleFragment) {
572     Diag(ExportLoc, diag::err_export_in_private_module_fragment);
573     Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
574     D->setInvalidDecl();
575     return D;
576   }
577 
578   for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
579     if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
580       //   An export-declaration shall not appear directly or indirectly within
581       //   an unnamed namespace [...]
582       if (ND->isAnonymousNamespace()) {
583         Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
584         Diag(ND->getLocation(), diag::note_anonymous_namespace);
585         // Don't diagnose internal-linkage declarations in this region.
586         D->setInvalidDecl();
587         return D;
588       }
589 
590       //   A declaration is exported if it is [...] a namespace-definition
591       //   that contains an exported declaration.
592       //
593       // Defer exporting the namespace until after we leave it, in order to
594       // avoid marking all subsequent declarations in the namespace as exported.
595       if (!DeferredExportedNamespaces.insert(ND).second)
596         break;
597     }
598   }
599 
600   //   [...] its declaration or declaration-seq shall not contain an
601   //   export-declaration.
602   if (auto *ED = getEnclosingExportDecl(D)) {
603     Diag(ExportLoc, diag::err_export_within_export);
604     if (ED->hasBraces())
605       Diag(ED->getLocation(), diag::note_export);
606     D->setInvalidDecl();
607     return D;
608   }
609 
610   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
611   return D;
612 }
613 
614 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
615                                      SourceLocation BlockStart);
616 
617 namespace {
618 enum class UnnamedDeclKind {
619   Empty,
620   StaticAssert,
621   Asm,
622   UsingDirective,
623   Context
624 };
625 }
626 
627 static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
628   if (isa<EmptyDecl>(D))
629     return UnnamedDeclKind::Empty;
630   if (isa<StaticAssertDecl>(D))
631     return UnnamedDeclKind::StaticAssert;
632   if (isa<FileScopeAsmDecl>(D))
633     return UnnamedDeclKind::Asm;
634   if (isa<UsingDirectiveDecl>(D))
635     return UnnamedDeclKind::UsingDirective;
636   // Everything else either introduces one or more names or is ill-formed.
637   return llvm::None;
638 }
639 
640 unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
641   switch (UDK) {
642   case UnnamedDeclKind::Empty:
643   case UnnamedDeclKind::StaticAssert:
644     // Allow empty-declarations and static_asserts in an export block as an
645     // extension.
646     return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
647 
648   case UnnamedDeclKind::UsingDirective:
649     // Allow exporting using-directives as an extension.
650     return diag::ext_export_using_directive;
651 
652   case UnnamedDeclKind::Context:
653     // Allow exporting DeclContexts that transitively contain no declarations
654     // as an extension.
655     return diag::ext_export_no_names;
656 
657   case UnnamedDeclKind::Asm:
658     return diag::err_export_no_name;
659   }
660   llvm_unreachable("unknown kind");
661 }
662 
663 static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
664                                     SourceLocation BlockStart) {
665   S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
666       << (unsigned)UDK;
667   if (BlockStart.isValid())
668     S.Diag(BlockStart, diag::note_export);
669 }
670 
671 /// Check that it's valid to export \p D.
672 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
673   // C++2a [module.interface]p3:
674   //   An exported declaration shall declare at least one name
675   if (auto UDK = getUnnamedDeclKind(D))
676     diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
677 
678   //   [...] shall not declare a name with internal linkage.
679   if (auto *ND = dyn_cast<NamedDecl>(D)) {
680     // Don't diagnose anonymous union objects; we'll diagnose their members
681     // instead.
682     if (ND->getDeclName() && ND->getFormalLinkage() == InternalLinkage) {
683       S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
684       if (BlockStart.isValid())
685         S.Diag(BlockStart, diag::note_export);
686     }
687   }
688 
689   // C++2a [module.interface]p5:
690   //   all entities to which all of the using-declarators ultimately refer
691   //   shall have been introduced with a name having external linkage
692   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
693     NamedDecl *Target = USD->getUnderlyingDecl();
694     if (Target->getFormalLinkage() == InternalLinkage) {
695       S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
696       S.Diag(Target->getLocation(), diag::note_using_decl_target);
697       if (BlockStart.isValid())
698         S.Diag(BlockStart, diag::note_export);
699     }
700   }
701 
702   // Recurse into namespace-scope DeclContexts. (Only namespace-scope
703   // declarations are exported.)
704   if (auto *DC = dyn_cast<DeclContext>(D))
705     if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
706       return checkExportedDeclContext(S, DC, BlockStart);
707   return false;
708 }
709 
710 /// Check that it's valid to export all the declarations in \p DC.
711 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
712                                      SourceLocation BlockStart) {
713   bool AllUnnamed = true;
714   for (auto *D : DC->decls())
715     AllUnnamed &= checkExportedDecl(S, D, BlockStart);
716   return AllUnnamed;
717 }
718 
719 /// Complete the definition of an export declaration.
720 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
721   auto *ED = cast<ExportDecl>(D);
722   if (RBraceLoc.isValid())
723     ED->setRBraceLoc(RBraceLoc);
724 
725   PopDeclContext();
726 
727   if (!D->isInvalidDecl()) {
728     SourceLocation BlockStart =
729         ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
730     for (auto *Child : ED->decls()) {
731       if (checkExportedDecl(*this, Child, BlockStart)) {
732         // If a top-level child is a linkage-spec declaration, it might contain
733         // no declarations (transitively), in which case it's ill-formed.
734         diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
735                                 BlockStart);
736       }
737     }
738   }
739 
740   return D;
741 }
742 
743 Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc,
744                                        bool IsImplicit) {
745   // We shouldn't create new global module fragment if there is already
746   // one.
747   if (!GlobalModuleFragment) {
748     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
749     GlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
750         BeginLoc, getCurrentModule());
751   }
752 
753   assert(GlobalModuleFragment && "module creation should not fail");
754 
755   // Enter the scope of the global module.
756   ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
757                           /*ModuleInterface=*/false,
758                           /*ImplicitGlobalModuleFragment=*/IsImplicit,
759                           /*VisibleModuleSet*/ {}});
760   VisibleModules.setVisible(GlobalModuleFragment, BeginLoc);
761 
762   return GlobalModuleFragment;
763 }
764 
765 void Sema::PopGlobalModuleFragment() {
766   assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
767          "left the wrong module scope, which is not global module fragment");
768   ModuleScopes.pop_back();
769 }
770