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