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