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