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