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