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