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