xref: /llvm-project/clang/lib/Sema/SemaModule.cpp (revision 999ead9dc9080cf95445149e6dae1de087ef90b8)
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; all those declarations are implicitly
78   // module-private (though they do not have module linkage).
79   Module *GlobalModule =
80       PushGlobalModuleFragment(ModuleLoc, /*IsImplicit=*/false);
81 
82   // All declarations created from now on are owned by the global module.
83   auto *TU = Context.getTranslationUnitDecl();
84   // [module.global.frag]p2
85   // A global-module-fragment specifies the contents of the global module
86   // fragment for a module unit. The global module fragment can be used to
87   // provide declarations that are attached to the global module and usable
88   // within the module unit.
89   //
90   // So the declations in the global module shouldn't be visible by default.
91   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
92   TU->setLocalOwningModule(GlobalModule);
93 
94   // FIXME: Consider creating an explicit representation of this declaration.
95   return nullptr;
96 }
97 
98 void Sema::HandleStartOfHeaderUnit() {
99   assert(getLangOpts().CPlusPlusModules &&
100          "Header units are only valid for C++20 modules");
101   SourceLocation StartOfTU =
102       SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
103 
104   StringRef HUName = getLangOpts().CurrentModule;
105   if (HUName.empty()) {
106     HUName = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())->getName();
107     const_cast<LangOptions &>(getLangOpts()).CurrentModule = HUName.str();
108   }
109 
110   // TODO: Make the C++20 header lookup independent.
111   // When the input is pre-processed source, we need a file ref to the original
112   // file for the header map.
113   auto F = SourceMgr.getFileManager().getOptionalFileRef(HUName);
114   // For the sake of error recovery (if someone has moved the original header
115   // after creating the pre-processed output) fall back to obtaining the file
116   // ref for the input file, which must be present.
117   if (!F)
118     F = SourceMgr.getFileEntryRefForID(SourceMgr.getMainFileID());
119   assert(F && "failed to find the header unit source?");
120   Module::Header H{HUName.str(), HUName.str(), *F};
121   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
122   Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H);
123   assert(Mod && "module creation should not fail");
124   ModuleScopes.push_back({}); // No GMF
125   ModuleScopes.back().BeginLoc = StartOfTU;
126   ModuleScopes.back().Module = Mod;
127   ModuleScopes.back().ModuleInterface = true;
128   VisibleModules.setVisible(Mod, StartOfTU);
129 
130   // From now on, we have an owning module for all declarations we see.
131   // All of these are implicitly exported.
132   auto *TU = Context.getTranslationUnitDecl();
133   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
134   TU->setLocalOwningModule(Mod);
135 }
136 
137 /// Tests whether the given identifier is reserved as a module name and
138 /// diagnoses if it is. Returns true if a diagnostic is emitted and false
139 /// otherwise.
140 static bool DiagReservedModuleName(Sema &S, const IdentifierInfo *II,
141                                    SourceLocation Loc) {
142   enum {
143     Valid = -1,
144     Invalid = 0,
145     Reserved = 1,
146   } Reason = Valid;
147 
148   if (II->isStr("module") || II->isStr("import"))
149     Reason = Invalid;
150   else if (II->isReserved(S.getLangOpts()) !=
151            ReservedIdentifierStatus::NotReserved)
152     Reason = Reserved;
153 
154   // If the identifier is reserved (not invalid) but is in a system header,
155   // we do not diagnose (because we expect system headers to use reserved
156   // identifiers).
157   if (Reason == Reserved && S.getSourceManager().isInSystemHeader(Loc))
158     Reason = Valid;
159 
160   if (Reason != Valid) {
161     S.Diag(Loc, diag::err_invalid_module_name) << II << (int)Reason;
162     return true;
163   }
164   return false;
165 }
166 
167 Sema::DeclGroupPtrTy
168 Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
169                       ModuleDeclKind MDK, ModuleIdPath Path,
170                       ModuleIdPath Partition, ModuleImportState &ImportState) {
171   assert(getLangOpts().CPlusPlusModules &&
172          "should only have module decl in standard C++ modules");
173 
174   bool IsFirstDecl = ImportState == ModuleImportState::FirstDecl;
175   bool SeenGMF = ImportState == ModuleImportState::GlobalFragment;
176   // If any of the steps here fail, we count that as invalidating C++20
177   // module state;
178   ImportState = ModuleImportState::NotACXX20Module;
179 
180   bool IsPartition = !Partition.empty();
181   if (IsPartition)
182     switch (MDK) {
183     case ModuleDeclKind::Implementation:
184       MDK = ModuleDeclKind::PartitionImplementation;
185       break;
186     case ModuleDeclKind::Interface:
187       MDK = ModuleDeclKind::PartitionInterface;
188       break;
189     default:
190       llvm_unreachable("how did we get a partition type set?");
191     }
192 
193   // A (non-partition) module implementation unit requires that we are not
194   // compiling a module of any kind.  A partition implementation emits an
195   // interface (and the AST for the implementation), which will subsequently
196   // be consumed to emit a binary.
197   // A module interface unit requires that we are not compiling a module map.
198   switch (getLangOpts().getCompilingModule()) {
199   case LangOptions::CMK_None:
200     // It's OK to compile a module interface as a normal translation unit.
201     break;
202 
203   case LangOptions::CMK_ModuleInterface:
204     if (MDK != ModuleDeclKind::Implementation)
205       break;
206 
207     // We were asked to compile a module interface unit but this is a module
208     // implementation unit.
209     Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
210       << FixItHint::CreateInsertion(ModuleLoc, "export ");
211     MDK = ModuleDeclKind::Interface;
212     break;
213 
214   case LangOptions::CMK_ModuleMap:
215     Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
216     return nullptr;
217 
218   case LangOptions::CMK_HeaderUnit:
219     Diag(ModuleLoc, diag::err_module_decl_in_header_unit);
220     return nullptr;
221   }
222 
223   assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
224 
225   // FIXME: Most of this work should be done by the preprocessor rather than
226   // here, in order to support macro import.
227 
228   // Only one module-declaration is permitted per source file.
229   if (isCurrentModulePurview()) {
230     Diag(ModuleLoc, diag::err_module_redeclaration);
231     Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
232          diag::note_prev_module_declaration);
233     return nullptr;
234   }
235 
236   assert((!getLangOpts().CPlusPlusModules ||
237           SeenGMF == (bool)this->GlobalModuleFragment) &&
238          "mismatched global module state");
239 
240   // In C++20, the module-declaration must be the first declaration if there
241   // is no global module fragment.
242   if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !SeenGMF) {
243     Diag(ModuleLoc, diag::err_module_decl_not_at_start);
244     SourceLocation BeginLoc =
245         ModuleScopes.empty()
246             ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
247             : ModuleScopes.back().BeginLoc;
248     if (BeginLoc.isValid()) {
249       Diag(BeginLoc, diag::note_global_module_introducer_missing)
250           << FixItHint::CreateInsertion(BeginLoc, "module;\n");
251     }
252   }
253 
254   // C++2b [module.unit]p1: ... The identifiers module and import shall not
255   // appear as identifiers in a module-name or module-partition. All
256   // module-names either beginning with an identifier consisting of std
257   // followed by zero or more digits or containing a reserved identifier
258   // ([lex.name]) are reserved and shall not be specified in a
259   // module-declaration; no diagnostic is required.
260 
261   // Test the first part of the path to see if it's std[0-9]+ but allow the
262   // name in a system header.
263   StringRef FirstComponentName = Path[0].first->getName();
264   if (!getSourceManager().isInSystemHeader(Path[0].second) &&
265       (FirstComponentName == "std" ||
266        (FirstComponentName.startswith("std") &&
267         llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit)))) {
268     Diag(Path[0].second, diag::err_invalid_module_name)
269         << Path[0].first << /*reserved*/ 1;
270     return nullptr;
271   }
272 
273   // Then test all of the components in the path to see if any of them are
274   // using another kind of reserved or invalid identifier.
275   for (auto Part : Path) {
276     if (DiagReservedModuleName(*this, Part.first, Part.second))
277       return nullptr;
278   }
279 
280   // Flatten the dots in a module name. Unlike Clang's hierarchical module map
281   // modules, the dots here are just another character that can appear in a
282   // module name.
283   std::string ModuleName = stringFromPath(Path);
284   if (IsPartition) {
285     ModuleName += ":";
286     ModuleName += stringFromPath(Partition);
287   }
288   // If a module name was explicitly specified on the command line, it must be
289   // correct.
290   if (!getLangOpts().CurrentModule.empty() &&
291       getLangOpts().CurrentModule != ModuleName) {
292     Diag(Path.front().second, diag::err_current_module_name_mismatch)
293         << SourceRange(Path.front().second, IsPartition
294                                                 ? Partition.back().second
295                                                 : Path.back().second)
296         << getLangOpts().CurrentModule;
297     return nullptr;
298   }
299   const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
300 
301   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
302   Module *Mod;
303 
304   switch (MDK) {
305   case ModuleDeclKind::Interface:
306   case ModuleDeclKind::PartitionInterface: {
307     // We can't have parsed or imported a definition of this module or parsed a
308     // module map defining it already.
309     if (auto *M = Map.findModule(ModuleName)) {
310       Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
311       if (M->DefinitionLoc.isValid())
312         Diag(M->DefinitionLoc, diag::note_prev_module_definition);
313       else if (OptionalFileEntryRef FE = M->getASTFile())
314         Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
315             << FE->getName();
316       Mod = M;
317       break;
318     }
319 
320     // Create a Module for the module that we're defining.
321     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
322     if (MDK == ModuleDeclKind::PartitionInterface)
323       Mod->Kind = Module::ModulePartitionInterface;
324     assert(Mod && "module creation should not fail");
325     break;
326   }
327 
328   case ModuleDeclKind::Implementation: {
329     // C++20 A module-declaration that contains neither an export-
330     // keyword nor a module-partition implicitly imports the primary
331     // module interface unit of the module as if by a module-import-
332     // declaration.
333     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
334         PP.getIdentifierInfo(ModuleName), Path[0].second);
335 
336     // The module loader will assume we're trying to import the module that
337     // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
338     // Change the value for `LangOpts.CurrentModule` temporarily to make the
339     // module loader work properly.
340     const_cast<LangOptions&>(getLangOpts()).CurrentModule = "";
341     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
342                                        Module::AllVisible,
343                                        /*IsInclusionDirective=*/false);
344     const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
345 
346     if (!Mod) {
347       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
348       // Create an empty module interface unit for error recovery.
349       Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
350     }
351 
352   } break;
353 
354   case ModuleDeclKind::PartitionImplementation:
355     // Create an interface, but note that it is an implementation
356     // unit.
357     Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName);
358     Mod->Kind = Module::ModulePartitionImplementation;
359     break;
360   }
361 
362   if (!this->GlobalModuleFragment) {
363     ModuleScopes.push_back({});
364     if (getLangOpts().ModulesLocalVisibility)
365       ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
366   } else {
367     // We're done with the global module fragment now.
368     ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
369   }
370 
371   // Switch from the global module fragment (if any) to the named module.
372   ModuleScopes.back().BeginLoc = StartLoc;
373   ModuleScopes.back().Module = Mod;
374   ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
375   VisibleModules.setVisible(Mod, ModuleLoc);
376 
377   // From now on, we have an owning module for all declarations we see.
378   // In C++20 modules, those declaration would be reachable when imported
379   // unless explicitily exported.
380   // Otherwise, those declarations are module-private unless explicitly
381   // exported.
382   auto *TU = Context.getTranslationUnitDecl();
383   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
384   TU->setLocalOwningModule(Mod);
385 
386   // We are in the module purview, but before any other (non import)
387   // statements, so imports are allowed.
388   ImportState = ModuleImportState::ImportAllowed;
389 
390   // For an implementation, We already made an implicit import (its interface).
391   // Make and return the import decl to be added to the current TU.
392   if (MDK == ModuleDeclKind::Implementation) {
393     // Make the import decl for the interface.
394     ImportDecl *Import =
395         ImportDecl::Create(Context, CurContext, ModuleLoc, Mod, Path[0].second);
396     // and return it to be added.
397     return ConvertDeclToDeclGroup(Import);
398   }
399 
400   getASTContext().setNamedModuleForCodeGen(Mod);
401 
402   // FIXME: Create a ModuleDecl.
403   return nullptr;
404 }
405 
406 Sema::DeclGroupPtrTy
407 Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
408                                      SourceLocation PrivateLoc) {
409   // C++20 [basic.link]/2:
410   //   A private-module-fragment shall appear only in a primary module
411   //   interface unit.
412   switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
413                                : ModuleScopes.back().Module->Kind) {
414   case Module::ModuleMapModule:
415   case Module::GlobalModuleFragment:
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   // In some cases we need to know if an entity was present in a directly-
606   // imported module (as opposed to a transitive import).  This avoids
607   // searching both Imports and Exports.
608   DirectModuleImports.insert(Mod);
609 
610   return Import;
611 }
612 
613 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
614   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
615   BuildModuleInclude(DirectiveLoc, Mod);
616 }
617 
618 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
619   // Determine whether we're in the #include buffer for a module. The #includes
620   // in that buffer do not qualify as module imports; they're just an
621   // implementation detail of us building the module.
622   //
623   // FIXME: Should we even get ActOnModuleInclude calls for those?
624   bool IsInModuleIncludes =
625       TUKind == TU_Module &&
626       getSourceManager().isWrittenInMainFile(DirectiveLoc);
627 
628   bool ShouldAddImport = !IsInModuleIncludes;
629 
630   // If this module import was due to an inclusion directive, create an
631   // implicit import declaration to capture it in the AST.
632   if (ShouldAddImport) {
633     TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
634     ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
635                                                      DirectiveLoc, Mod,
636                                                      DirectiveLoc);
637     if (!ModuleScopes.empty())
638       Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
639     TU->addDecl(ImportD);
640     Consumer.HandleImplicitImportDecl(ImportD);
641   }
642 
643   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
644   VisibleModules.setVisible(Mod, DirectiveLoc);
645 
646   if (getLangOpts().isCompilingModule()) {
647     Module *ThisModule = PP.getHeaderSearchInfo().lookupModule(
648         getLangOpts().CurrentModule, DirectiveLoc, false, false);
649     (void)ThisModule;
650     assert(ThisModule && "was expecting a module if building one");
651   }
652 }
653 
654 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
655   checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
656 
657   ModuleScopes.push_back({});
658   ModuleScopes.back().Module = Mod;
659   if (getLangOpts().ModulesLocalVisibility)
660     ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
661 
662   VisibleModules.setVisible(Mod, DirectiveLoc);
663 
664   // The enclosing context is now part of this module.
665   // FIXME: Consider creating a child DeclContext to hold the entities
666   // lexically within the module.
667   if (getLangOpts().trackLocalOwningModule()) {
668     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
669       cast<Decl>(DC)->setModuleOwnershipKind(
670           getLangOpts().ModulesLocalVisibility
671               ? Decl::ModuleOwnershipKind::VisibleWhenImported
672               : Decl::ModuleOwnershipKind::Visible);
673       cast<Decl>(DC)->setLocalOwningModule(Mod);
674     }
675   }
676 }
677 
678 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
679   if (getLangOpts().ModulesLocalVisibility) {
680     VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
681     // Leaving a module hides namespace names, so our visible namespace cache
682     // is now out of date.
683     VisibleNamespaceCache.clear();
684   }
685 
686   assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
687          "left the wrong module scope");
688   ModuleScopes.pop_back();
689 
690   // We got to the end of processing a local module. Create an
691   // ImportDecl as we would for an imported module.
692   FileID File = getSourceManager().getFileID(EomLoc);
693   SourceLocation DirectiveLoc;
694   if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
695     // We reached the end of a #included module header. Use the #include loc.
696     assert(File != getSourceManager().getMainFileID() &&
697            "end of submodule in main source file");
698     DirectiveLoc = getSourceManager().getIncludeLoc(File);
699   } else {
700     // We reached an EOM pragma. Use the pragma location.
701     DirectiveLoc = EomLoc;
702   }
703   BuildModuleInclude(DirectiveLoc, Mod);
704 
705   // Any further declarations are in whatever module we returned to.
706   if (getLangOpts().trackLocalOwningModule()) {
707     // The parser guarantees that this is the same context that we entered
708     // the module within.
709     for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
710       cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
711       if (!getCurrentModule())
712         cast<Decl>(DC)->setModuleOwnershipKind(
713             Decl::ModuleOwnershipKind::Unowned);
714     }
715   }
716 }
717 
718 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
719                                                       Module *Mod) {
720   // Bail if we're not allowed to implicitly import a module here.
721   if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
722       VisibleModules.isVisible(Mod))
723     return;
724 
725   // Create the implicit import declaration.
726   TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
727   ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
728                                                    Loc, Mod, Loc);
729   TU->addDecl(ImportD);
730   Consumer.HandleImplicitImportDecl(ImportD);
731 
732   // Make the module visible.
733   getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
734   VisibleModules.setVisible(Mod, Loc);
735 }
736 
737 /// We have parsed the start of an export declaration, including the '{'
738 /// (if present).
739 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
740                                  SourceLocation LBraceLoc) {
741   ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
742 
743   // Set this temporarily so we know the export-declaration was braced.
744   D->setRBraceLoc(LBraceLoc);
745 
746   CurContext->addDecl(D);
747   PushDeclContext(S, D);
748 
749   // C++2a [module.interface]p1:
750   //   An export-declaration shall appear only [...] in the purview of a module
751   //   interface unit. An export-declaration shall not appear directly or
752   //   indirectly within [...] a private-module-fragment.
753   if (!isCurrentModulePurview()) {
754     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
755     D->setInvalidDecl();
756     return D;
757   } else if (!ModuleScopes.back().ModuleInterface) {
758     Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
759     Diag(ModuleScopes.back().BeginLoc,
760          diag::note_not_module_interface_add_export)
761         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
762     D->setInvalidDecl();
763     return D;
764   } else if (ModuleScopes.back().Module->Kind ==
765              Module::PrivateModuleFragment) {
766     Diag(ExportLoc, diag::err_export_in_private_module_fragment);
767     Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
768     D->setInvalidDecl();
769     return D;
770   }
771 
772   for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
773     if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
774       //   An export-declaration shall not appear directly or indirectly within
775       //   an unnamed namespace [...]
776       if (ND->isAnonymousNamespace()) {
777         Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
778         Diag(ND->getLocation(), diag::note_anonymous_namespace);
779         // Don't diagnose internal-linkage declarations in this region.
780         D->setInvalidDecl();
781         return D;
782       }
783 
784       //   A declaration is exported if it is [...] a namespace-definition
785       //   that contains an exported declaration.
786       //
787       // Defer exporting the namespace until after we leave it, in order to
788       // avoid marking all subsequent declarations in the namespace as exported.
789       if (!DeferredExportedNamespaces.insert(ND).second)
790         break;
791     }
792   }
793 
794   //   [...] its declaration or declaration-seq shall not contain an
795   //   export-declaration.
796   if (auto *ED = getEnclosingExportDecl(D)) {
797     Diag(ExportLoc, diag::err_export_within_export);
798     if (ED->hasBraces())
799       Diag(ED->getLocation(), diag::note_export);
800     D->setInvalidDecl();
801     return D;
802   }
803 
804   D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
805   return D;
806 }
807 
808 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
809                                      SourceLocation BlockStart);
810 
811 namespace {
812 enum class UnnamedDeclKind {
813   Empty,
814   StaticAssert,
815   Asm,
816   UsingDirective,
817   Namespace,
818   Context
819 };
820 }
821 
822 static std::optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
823   if (isa<EmptyDecl>(D))
824     return UnnamedDeclKind::Empty;
825   if (isa<StaticAssertDecl>(D))
826     return UnnamedDeclKind::StaticAssert;
827   if (isa<FileScopeAsmDecl>(D))
828     return UnnamedDeclKind::Asm;
829   if (isa<UsingDirectiveDecl>(D))
830     return UnnamedDeclKind::UsingDirective;
831   // Everything else either introduces one or more names or is ill-formed.
832   return std::nullopt;
833 }
834 
835 unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
836   switch (UDK) {
837   case UnnamedDeclKind::Empty:
838   case UnnamedDeclKind::StaticAssert:
839     // Allow empty-declarations and static_asserts in an export block as an
840     // extension.
841     return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
842 
843   case UnnamedDeclKind::UsingDirective:
844     // Allow exporting using-directives as an extension.
845     return diag::ext_export_using_directive;
846 
847   case UnnamedDeclKind::Namespace:
848     // Anonymous namespace with no content.
849     return diag::introduces_no_names;
850 
851   case UnnamedDeclKind::Context:
852     // Allow exporting DeclContexts that transitively contain no declarations
853     // as an extension.
854     return diag::ext_export_no_names;
855 
856   case UnnamedDeclKind::Asm:
857     return diag::err_export_no_name;
858   }
859   llvm_unreachable("unknown kind");
860 }
861 
862 static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
863                                     SourceLocation BlockStart) {
864   S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
865       << (unsigned)UDK;
866   if (BlockStart.isValid())
867     S.Diag(BlockStart, diag::note_export);
868 }
869 
870 /// Check that it's valid to export \p D.
871 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
872   // C++2a [module.interface]p3:
873   //   An exported declaration shall declare at least one name
874   if (auto UDK = getUnnamedDeclKind(D))
875     diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
876 
877   //   [...] shall not declare a name with internal linkage.
878   bool HasName = false;
879   if (auto *ND = dyn_cast<NamedDecl>(D)) {
880     // Don't diagnose anonymous union objects; we'll diagnose their members
881     // instead.
882     HasName = (bool)ND->getDeclName();
883     if (HasName && ND->getFormalLinkage() == InternalLinkage) {
884       S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
885       if (BlockStart.isValid())
886         S.Diag(BlockStart, diag::note_export);
887     }
888   }
889 
890   // C++2a [module.interface]p5:
891   //   all entities to which all of the using-declarators ultimately refer
892   //   shall have been introduced with a name having external linkage
893   if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
894     NamedDecl *Target = USD->getUnderlyingDecl();
895     Linkage Lk = Target->getFormalLinkage();
896     if (Lk == InternalLinkage || Lk == ModuleLinkage) {
897       S.Diag(USD->getLocation(), diag::err_export_using_internal)
898           << (Lk == InternalLinkage ? 0 : 1) << Target;
899       S.Diag(Target->getLocation(), diag::note_using_decl_target);
900       if (BlockStart.isValid())
901         S.Diag(BlockStart, diag::note_export);
902     }
903   }
904 
905   // Recurse into namespace-scope DeclContexts. (Only namespace-scope
906   // declarations are exported.).
907   if (auto *DC = dyn_cast<DeclContext>(D)) {
908     if (isa<NamespaceDecl>(D) && DC->decls().empty()) {
909       if (!HasName)
910         // We don't allow an empty anonymous namespace (we don't allow decls
911         // in them either, but that's handled in the recursion).
912         diagExportedUnnamedDecl(S, UnnamedDeclKind::Namespace, D, BlockStart);
913       // We allow an empty named namespace decl.
914     } else if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
915       return checkExportedDeclContext(S, DC, BlockStart);
916   }
917   return false;
918 }
919 
920 /// Check that it's valid to export all the declarations in \p DC.
921 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
922                                      SourceLocation BlockStart) {
923   bool AllUnnamed = true;
924   for (auto *D : DC->decls())
925     AllUnnamed &= checkExportedDecl(S, D, BlockStart);
926   return AllUnnamed;
927 }
928 
929 /// Complete the definition of an export declaration.
930 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
931   auto *ED = cast<ExportDecl>(D);
932   if (RBraceLoc.isValid())
933     ED->setRBraceLoc(RBraceLoc);
934 
935   PopDeclContext();
936 
937   if (!D->isInvalidDecl()) {
938     SourceLocation BlockStart =
939         ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
940     for (auto *Child : ED->decls()) {
941       if (checkExportedDecl(*this, Child, BlockStart)) {
942         // If a top-level child is a linkage-spec declaration, it might contain
943         // no declarations (transitively), in which case it's ill-formed.
944         diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
945                                 BlockStart);
946       }
947       if (auto *FD = dyn_cast<FunctionDecl>(Child)) {
948         // [dcl.inline]/7
949         // If an inline function or variable that is attached to a named module
950         // is declared in a definition domain, it shall be defined in that
951         // domain.
952         // So, if the current declaration does not have a definition, we must
953         // check at the end of the TU (or when the PMF starts) to see that we
954         // have a definition at that point.
955         if (FD->isInlineSpecified() && !FD->isDefined())
956           PendingInlineFuncDecls.insert(FD);
957       }
958     }
959   }
960 
961   return D;
962 }
963 
964 Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc,
965                                        bool IsImplicit) {
966   // We shouldn't create new global module fragment if there is already
967   // one.
968   if (!GlobalModuleFragment) {
969     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
970     GlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
971         BeginLoc, getCurrentModule());
972   }
973 
974   assert(GlobalModuleFragment && "module creation should not fail");
975 
976   // Enter the scope of the global module.
977   ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
978                           /*ModuleInterface=*/false,
979                           /*OuterVisibleModules=*/{}});
980   VisibleModules.setVisible(GlobalModuleFragment, BeginLoc);
981 
982   return GlobalModuleFragment;
983 }
984 
985 void Sema::PopGlobalModuleFragment() {
986   assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
987          "left the wrong module scope, which is not global module fragment");
988   ModuleScopes.pop_back();
989 }
990 
991 bool Sema::isModuleUnitOfCurrentTU(const Module *M) const {
992   assert(M);
993 
994   Module *CurrentModuleUnit = getCurrentModule();
995 
996   // If we are not in a module currently, M must not be the module unit of
997   // current TU.
998   if (!CurrentModuleUnit)
999     return false;
1000 
1001   return M->isSubModuleOf(CurrentModuleUnit->getTopLevelModule());
1002 }
1003