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