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