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