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