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