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