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