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