xref: /llvm-project/clang/lib/Sema/SemaModule.cpp (revision 4d0cfa6d09e2a84cceb669949d72df58c031a8c5)
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   // If we are really importing a module (not just checking layering) due to an
640   // #include in the main file, synthesize an ImportDecl.
641   if (getLangOpts().Modules && !IsInModuleIncludes) {
642     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
643     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
644                                                      DirectiveLoc, Mod,
645                                                      DirectiveLoc);
646     if (!ModuleScopes.empty())
647       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
648     TU->addDecl(ImportD);
649     Consumer.HandleImplicitImportDecl(ImportD);
650   }
651 
652   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
653   VisibleModules.setVisible(Mod, DirectiveLoc);
654 
655   if (getLangOpts().isCompilingModule()) {
656     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
657         getLangOpts().CurrentModule, DirectiveLoc, false, false);
658     (void)ThisModule;
659     assert(ThisModule && "was expecting a module if building one");
660   }
661 }
662 
663 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
664   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
665 
666   ModuleScopes.push_back({});
667   ModuleScopes.back().Module = Mod;
668   if (getLangOpts().ModulesLocalVisibility)
669     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
670 
671   VisibleModules.setVisible(Mod, DirectiveLoc);
672 
673   // The enclosing context is now part of this module.
674   // FIXME: Consider creating a child DeclContext to hold the entities
675   // lexically within the module.
676   if (getLangOpts().trackLocalOwningModule()) {
677     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
678       cast<Decl>(DC)->setModuleOwnershipKind(
679           getLangOpts().ModulesLocalVisibility
680               ? Decl::ModuleOwnershipKind::VisibleWhenImported
681               : Decl::ModuleOwnershipKind::Visible);
682       cast<Decl>(DC)->setLocalOwningModule(Mod);
683     }
684   }
685 }
686 
687 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
688   if (getLangOpts().ModulesLocalVisibility) {
689     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
690     // Leaving a module hides namespace names, so our visible namespace cache
691     // is now out of date.
692     VisibleNamespaceCache.clear();
693   }
694 
695   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
696          "left the wrong module scope");
697   ModuleScopes.pop_back();
698 
699   // We got to the end of processing a local module. Create an
700   // ImportDecl as we would for an imported module.
701   FileID File = getSourceManager().getFileID(EomLoc);
702   SourceLocation DirectiveLoc;
703   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
704     // We reached the end of a #included module header. Use the #include loc.
705     assert(File != getSourceManager().getMainFileID() &&
706            "end of submodule in main source file");
707     DirectiveLoc = getSourceManager().getIncludeLoc(File);
708   } else {
709     // We reached an EOM pragma. Use the pragma location.
710     DirectiveLoc = EomLoc;
711   }
712   BuildModuleInclude(DirectiveLoc, Mod);
713 
714   // Any further declarations are in whatever module we returned to.
715   if (getLangOpts().trackLocalOwningModule()) {
716     // The parser guarantees that this is the same context that we entered
717     // the module within.
718     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
719       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
720       if (!getCurrentModule())
721         cast<Decl>(DC)->setModuleOwnershipKind(
722             Decl::ModuleOwnershipKind::Unowned);
723     }
724   }
725 }
726 
727 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
728                                                       Module *Mod) {
729   // Bail if we're not allowed to implicitly import a module here.
730   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
731       VisibleModules.isVisible(Mod))
732     return;
733 
734   // Create the implicit import declaration.
735   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
736   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
737                                                    Loc, Mod, Loc);
738   TU->addDecl(ImportD);
739   Consumer.HandleImplicitImportDecl(ImportD);
740 
741   // Make the module visible.
742   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
743   VisibleModules.setVisible(Mod, Loc);
744 }
745 
746 /// We have parsed the start of an export declaration, including the '{'
747 /// (if present).
748 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
749                                  SourceLocation LBraceLoc) {
750   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
751 
752   // Set this temporarily so we know the export-declaration was braced.
753   D->setRBraceLoc(LBraceLoc);
754 
755   CurContext->addDecl(D);
756   PushDeclContext(S, D);
757 
758   // C++2a [module.interface]p1:
759   //   An export-declaration shall appear only [...] in the purview of a module
760   //   interface unit. An export-declaration shall not appear directly or
761   //   indirectly within [...] a private-module-fragment.
762   if (!isCurrentModulePurview()) {
763     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
764     D->setInvalidDecl();
765     return D;
766   } else if (!ModuleScopes.back().ModuleInterface) {
767     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
768     Diag(ModuleScopes.back().BeginLoc,
769          diag::note_not_module_interface_add_export)
770         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
771     D->setInvalidDecl();
772     return D;
773   } else if (ModuleScopes.back().Module->Kind ==
774              Module::PrivateModuleFragment) {
775     Diag(ExportLoc, diag::err_export_in_private_module_fragment);
776     Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
777     D->setInvalidDecl();
778     return D;
779   }
780 
781   for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
782     if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
783       //   An export-declaration shall not appear directly or indirectly within
784       //   an unnamed namespace [...]
785       if (ND->isAnonymousNamespace()) {
786         Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
787         Diag(ND->getLocation(), diag::note_anonymous_namespace);
788         // Don't diagnose internal-linkage declarations in this region.
789         D->setInvalidDecl();
790         return D;
791       }
792 
793       //   A declaration is exported if it is [...] a namespace-definition
794       //   that contains an exported declaration.
795       //
796       // Defer exporting the namespace until after we leave it, in order to
797       // avoid marking all subsequent declarations in the namespace as exported.
798       if (!DeferredExportedNamespaces.insert(ND).second)
799         break;
800     }
801   }
802 
803   //   [...] its declaration or declaration-seq shall not contain an
804   //   export-declaration.
805   if (auto *ED = getEnclosingExportDecl(D)) {
806     Diag(ExportLoc, diag::err_export_within_export);
807     if (ED->hasBraces())
808       Diag(ED->getLocation(), diag::note_export);
809     D->setInvalidDecl();
810     return D;
811   }
812 
813   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
814   return D;
815 }
816 
817 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
818                                      SourceLocation BlockStart);
819 
820 namespace {
821 enum class UnnamedDeclKind {
822   Empty,
823   StaticAssert,
824   Asm,
825   UsingDirective,
826   Namespace,
827   Context
828 };
829 }
830 
831 static std::optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
832   if (isa<EmptyDecl>(D))
833     return UnnamedDeclKind::Empty;
834   if (isa<StaticAssertDecl>(D))
835     return UnnamedDeclKind::StaticAssert;
836   if (isa<FileScopeAsmDecl>(D))
837     return UnnamedDeclKind::Asm;
838   if (isa<UsingDirectiveDecl>(D))
839     return UnnamedDeclKind::UsingDirective;
840   // Everything else either introduces one or more names or is ill-formed.
841   return std::nullopt;
842 }
843 
844 unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
845   switch (UDK) {
846   case UnnamedDeclKind::Empty:
847   case UnnamedDeclKind::StaticAssert:
848     // Allow empty-declarations and static_asserts in an export block as an
849     // extension.
850     return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
851 
852   case UnnamedDeclKind::UsingDirective:
853     // Allow exporting using-directives as an extension.
854     return diag::ext_export_using_directive;
855 
856   case UnnamedDeclKind::Namespace:
857     // Anonymous namespace with no content.
858     return diag::introduces_no_names;
859 
860   case UnnamedDeclKind::Context:
861     // Allow exporting DeclContexts that transitively contain no declarations
862     // as an extension.
863     return diag::ext_export_no_names;
864 
865   case UnnamedDeclKind::Asm:
866     return diag::err_export_no_name;
867   }
868   llvm_unreachable("unknown kind");
869 }
870 
871 static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
872                                     SourceLocation BlockStart) {
873   S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
874       << (unsigned)UDK;
875   if (BlockStart.isValid())
876     S.Diag(BlockStart, diag::note_export);
877 }
878 
879 /// Check that it's valid to export \p D.
880 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
881   // C++2a [module.interface]p3:
882   //   An exported declaration shall declare at least one name
883   if (auto UDK = getUnnamedDeclKind(D))
884     diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
885 
886   //   [...] shall not declare a name with internal linkage.
887   bool HasName = false;
888   if (auto *ND = dyn_cast<NamedDecl>(D)) {
889     // Don't diagnose anonymous union objects; we'll diagnose their members
890     // instead.
891     HasName = (bool)ND->getDeclName();
892     if (HasName && ND->getFormalLinkage() == InternalLinkage) {
893       S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
894       if (BlockStart.isValid())
895         S.Diag(BlockStart, diag::note_export);
896     }
897   }
898 
899   // C++2a [module.interface]p5:
900   //   all entities to which all of the using-declarators ultimately refer
901   //   shall have been introduced with a name having external linkage
902   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
903     NamedDecl *Target = USD->getUnderlyingDecl();
904     Linkage Lk = Target->getFormalLinkage();
905     if (Lk == InternalLinkage || Lk == ModuleLinkage) {
906       S.Diag(USD->getLocation(), diag::err_export_using_internal)
907           << (Lk == InternalLinkage ? 0 : 1) << Target;
908       S.Diag(Target->getLocation(), diag::note_using_decl_target);
909       if (BlockStart.isValid())
910         S.Diag(BlockStart, diag::note_export);
911     }
912   }
913 
914   // Recurse into namespace-scope DeclContexts. (Only namespace-scope
915   // declarations are exported.).
916   if (auto *DC = dyn_cast<DeclContext>(D)) {
917     if (isa<NamespaceDecl>(D) && DC->decls().empty()) {
918       if (!HasName)
919         // We don't allow an empty anonymous namespace (we don't allow decls
920         // in them either, but that's handled in the recursion).
921         diagExportedUnnamedDecl(S, UnnamedDeclKind::Namespace, D, BlockStart);
922       // We allow an empty named namespace decl.
923     } else if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
924       return checkExportedDeclContext(S, DC, BlockStart);
925   }
926   return false;
927 }
928 
929 /// Check that it's valid to export all the declarations in \p DC.
930 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
931                                      SourceLocation BlockStart) {
932   bool AllUnnamed = true;
933   for (auto *D : DC->decls())
934     AllUnnamed &= checkExportedDecl(S, D, BlockStart);
935   return AllUnnamed;
936 }
937 
938 /// Complete the definition of an export declaration.
939 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
940   auto *ED = cast<ExportDecl>(D);
941   if (RBraceLoc.isValid())
942     ED->setRBraceLoc(RBraceLoc);
943 
944   PopDeclContext();
945 
946   if (!D->isInvalidDecl()) {
947     SourceLocation BlockStart =
948         ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
949     for (auto *Child : ED->decls()) {
950       if (checkExportedDecl(*this, Child, BlockStart)) {
951         // If a top-level child is a linkage-spec declaration, it might contain
952         // no declarations (transitively), in which case it's ill-formed.
953         diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
954                                 BlockStart);
955       }
956       if (auto *FD = dyn_cast<FunctionDecl>(Child)) {
957         // [dcl.inline]/7
958         // If an inline function or variable that is attached to a named module
959         // is declared in a definition domain, it shall be defined in that
960         // domain.
961         // So, if the current declaration does not have a definition, we must
962         // check at the end of the TU (or when the PMF starts) to see that we
963         // have a definition at that point.
964         if (FD->isInlineSpecified() && !FD->isDefined())
965           PendingInlineFuncDecls.insert(FD);
966       }
967     }
968   }
969 
970   return D;
971 }
972 
973 Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) {
974   // We shouldn't create new global module fragment if there is already
975   // one.
976   if (!TheGlobalModuleFragment) {
977     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
978     TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
979         BeginLoc, getCurrentModule());
980   }
981 
982   assert(TheGlobalModuleFragment && "module creation should not fail");
983 
984   // Enter the scope of the global module.
985   ModuleScopes.push_back({BeginLoc, TheGlobalModuleFragment,
986                           /*ModuleInterface=*/false,
987                           /*OuterVisibleModules=*/{}});
988   VisibleModules.setVisible(TheGlobalModuleFragment, BeginLoc);
989 
990   return TheGlobalModuleFragment;
991 }
992 
993 void Sema::PopGlobalModuleFragment() {
994   assert(!ModuleScopes.empty() &&
995          getCurrentModule()->isExplicitGlobalModule() &&
996          "left the wrong module scope, which is not global module fragment");
997   ModuleScopes.pop_back();
998 }
999 
1000 Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc,
1001                                                bool IsExported) {
1002   Module **M = IsExported ? &TheExportedImplicitGlobalModuleFragment
1003                           : &TheImplicitGlobalModuleFragment;
1004   if (!*M) {
1005     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
1006     *M = Map.createImplicitGlobalModuleFragmentForModuleUnit(
1007         BeginLoc, IsExported, getCurrentModule());
1008   }
1009   assert(*M && "module creation should not fail");
1010 
1011   // Enter the scope of the global module.
1012   ModuleScopes.push_back({BeginLoc, *M,
1013                           /*ModuleInterface=*/false,
1014                           /*OuterVisibleModules=*/{}});
1015   VisibleModules.setVisible(*M, BeginLoc);
1016   return *M;
1017 }
1018 
1019 void Sema::PopImplicitGlobalModuleFragment() {
1020   assert(!ModuleScopes.empty() &&
1021          getCurrentModule()->isImplicitGlobalModule() &&
1022          "left the wrong module scope, which is not global module fragment");
1023   ModuleScopes.pop_back();
1024 }
1025