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