xref: /llvm-project/clang/lib/Sema/SemaModule.cpp (revision 75fbb5d2238f1824f03d205b699061a115d5effc)
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     std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
341         PP.getIdentifierInfo(ModuleName), Path[0].second);
342     // C++20 A module-declaration that contains neither an export-
343     // keyword nor a module-partition implicitly imports the primary
344     // module interface unit of the module as if by a module-import-
345     // declaration.
346     Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
347                                        Module::AllVisible,
348                                        /*IsInclusionDirective=*/false);
349     if (!Mod) {
350       Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
351       // Create an empty module interface unit for error recovery.
352       Mod = Map.createModuleForInterfaceUnit(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->GlobalModuleFragment) {
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   ModuleScopes.back().IsPartition = IsPartition;
378   VisibleModules.setVisible(Mod, ModuleLoc);
379 
380   // From now on, we have an owning module for all declarations we see.
381   // In C++20 modules, those declaration would be reachable when imported
382   // unless explicitily exported.
383   // Otherwise, those declarations are module-private unless explicitly
384   // exported.
385   auto *TU = Context.getTranslationUnitDecl();
386   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported);
387   TU->setLocalOwningModule(Mod);
388 
389   // We are in the module purview, but before any other (non import)
390   // statements, so imports are allowed.
391   ImportState = ModuleImportState::ImportAllowed;
392 
393   // For an implementation, We already made an implicit import (its interface).
394   // Make and return the import decl to be added to the current TU.
395   if (MDK == ModuleDeclKind::Implementation) {
396     // Make the import decl for the interface.
397     ImportDecl *Import =
398         ImportDecl::Create(Context, CurContext, ModuleLoc, Mod, Path[0].second);
399     // and return it to be added.
400     return ConvertDeclToDeclGroup(Import);
401   }
402 
403   // FIXME: Create a ModuleDecl.
404   return nullptr;
405 }
406 
407 Sema::DeclGroupPtrTy
408 Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
409                                      SourceLocation PrivateLoc) {
410   // C++20 [basic.link]/2:
411   //   A private-module-fragment shall appear only in a primary module
412   //   interface unit.
413   switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
414                                : ModuleScopes.back().Module->Kind) {
415   case Module::ModuleMapModule:
416   case Module::GlobalModuleFragment:
417   case Module::ModulePartitionImplementation:
418   case Module::ModulePartitionInterface:
419   case Module::ModuleHeaderUnit:
420     Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
421     return nullptr;
422 
423   case Module::PrivateModuleFragment:
424     Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
425     Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
426     return nullptr;
427 
428   case Module::ModuleInterfaceUnit:
429     break;
430   }
431 
432   if (!ModuleScopes.back().ModuleInterface) {
433     Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
434     Diag(ModuleScopes.back().BeginLoc,
435          diag::note_not_module_interface_add_export)
436         << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
437     return nullptr;
438   }
439 
440   // FIXME: Check this isn't a module interface partition.
441   // FIXME: Check that this translation unit does not import any partitions;
442   // such imports would violate [basic.link]/2's "shall be the only module unit"
443   // restriction.
444 
445   // We've finished the public fragment of the translation unit.
446   ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
447 
448   auto &Map = PP.getHeaderSearchInfo().getModuleMap();
449   Module *PrivateModuleFragment =
450       Map.createPrivateModuleFragmentForInterfaceUnit(
451           ModuleScopes.back().Module, PrivateLoc);
452   assert(PrivateModuleFragment && "module creation should not fail");
453 
454   // Enter the scope of the private module fragment.
455   ModuleScopes.push_back({});
456   ModuleScopes.back().BeginLoc = ModuleLoc;
457   ModuleScopes.back().Module = PrivateModuleFragment;
458   ModuleScopes.back().ModuleInterface = true;
459   VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
460 
461   // All declarations created from now on are scoped to the private module
462   // fragment (and are neither visible nor reachable in importers of the module
463   // interface).
464   auto *TU = Context.getTranslationUnitDecl();
465   TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
466   TU->setLocalOwningModule(PrivateModuleFragment);
467 
468   // FIXME: Consider creating an explicit representation of this declaration.
469   return nullptr;
470 }
471 
472 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
473                                    SourceLocation ExportLoc,
474                                    SourceLocation ImportLoc, ModuleIdPath Path,
475                                    bool IsPartition) {
476 
477   bool Cxx20Mode = getLangOpts().CPlusPlusModules || getLangOpts().ModulesTS;
478   assert((!IsPartition || Cxx20Mode) && "partition seen in non-C++20 code?");
479 
480   // For a C++20 module name, flatten into a single identifier with the source
481   // location of the first component.
482   std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
483 
484   std::string ModuleName;
485   if (IsPartition) {
486     // We already checked that we are in a module purview in the parser.
487     assert(!ModuleScopes.empty() && "in a module purview, but no module?");
488     Module *NamedMod = ModuleScopes.back().Module;
489     // If we are importing into a partition, find the owning named module,
490     // otherwise, the name of the importing named module.
491     ModuleName = NamedMod->getPrimaryModuleInterfaceName().str();
492     ModuleName += ":";
493     ModuleName += stringFromPath(Path);
494     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
495     Path = ModuleIdPath(ModuleNameLoc);
496   } else if (Cxx20Mode) {
497     ModuleName = stringFromPath(Path);
498     ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
499     Path = ModuleIdPath(ModuleNameLoc);
500   }
501 
502   // Diagnose self-import before attempting a load.
503   // [module.import]/9
504   // A module implementation unit of a module M that is not a module partition
505   // shall not contain a module-import-declaration nominating M.
506   // (for an implementation, the module interface is imported implicitly,
507   //  but that's handled in the module decl code).
508 
509   if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() &&
510       getCurrentModule()->Name == ModuleName) {
511     Diag(ImportLoc, diag::err_module_self_import_cxx20)
512         << ModuleName << !ModuleScopes.back().ModuleInterface;
513     return true;
514   }
515 
516   Module *Mod = getModuleLoader().loadModule(
517       ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false);
518   if (!Mod)
519     return true;
520 
521   return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
522 }
523 
524 /// Determine whether \p D is lexically within an export-declaration.
525 static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
526   for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
527     if (auto *ED = dyn_cast<ExportDecl>(DC))
528       return ED;
529   return nullptr;
530 }
531 
532 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
533                                    SourceLocation ExportLoc,
534                                    SourceLocation ImportLoc, Module *Mod,
535                                    ModuleIdPath Path) {
536   VisibleModules.setVisible(Mod, ImportLoc);
537 
538   checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
539 
540   // FIXME: we should support importing a submodule within a different submodule
541   // of the same top-level module. Until we do, make it an error rather than
542   // silently ignoring the import.
543   // FIXME: Should we warn on a redundant import of the current module?
544   if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
545       (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
546     Diag(ImportLoc, getLangOpts().isCompilingModule()
547                         ? diag::err_module_self_import
548                         : diag::err_module_import_in_implementation)
549         << Mod->getFullModuleName() << getLangOpts().CurrentModule;
550   }
551 
552   SmallVector<SourceLocation, 2> IdentifierLocs;
553 
554   if (Path.empty()) {
555     // If this was a header import, pad out with dummy locations.
556     // FIXME: Pass in and use the location of the header-name token in this
557     // case.
558     for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent)
559       IdentifierLocs.push_back(SourceLocation());
560   } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) {
561     // A single identifier for the whole name.
562     IdentifierLocs.push_back(Path[0].second);
563   } else {
564     Module *ModCheck = Mod;
565     for (unsigned I = 0, N = Path.size(); I != N; ++I) {
566       // If we've run out of module parents, just drop the remaining
567       // identifiers.  We need the length to be consistent.
568       if (!ModCheck)
569         break;
570       ModCheck = ModCheck->Parent;
571 
572       IdentifierLocs.push_back(Path[I].second);
573     }
574   }
575 
576   ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
577                                           Mod, IdentifierLocs);
578   CurContext->addDecl(Import);
579 
580   // Sequence initialization of the imported module before that of the current
581   // module, if any.
582   if (!ModuleScopes.empty())
583     Context.addModuleInitializer(ModuleScopes.back().Module, Import);
584 
585   // A module (partition) implementation unit shall not be exported.
586   if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() &&
587       Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) {
588     Diag(ExportLoc, diag::err_export_partition_impl)
589         << SourceRange(ExportLoc, Path.back().second);
590   } else if (!ModuleScopes.empty() &&
591              (ModuleScopes.back().ModuleInterface ||
592               (getLangOpts().CPlusPlusModules &&
593                ModuleScopes.back().Module->isGlobalModule()))) {
594     assert((!ModuleScopes.back().Module->isGlobalModule() ||
595             Mod->Kind == Module::ModuleKind::ModuleHeaderUnit) &&
596            "should only be importing a header unit into the GMF");
597     // Re-export the module if the imported module is exported.
598     // Note that we don't need to add re-exported module to Imports field
599     // since `Exports` implies the module is imported already.
600     if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
601       getCurrentModule()->Exports.emplace_back(Mod, false);
602     else
603       getCurrentModule()->Imports.insert(Mod);
604   } else if (ExportLoc.isValid()) {
605     // [module.interface]p1:
606     // An export-declaration shall inhabit a namespace scope and appear in the
607     // purview of a module interface unit.
608     Diag(ExportLoc, diag::err_export_not_in_module_interface)
609         << (!ModuleScopes.empty() &&
610             !ModuleScopes.back().ImplicitGlobalModuleFragment);
611   }
612 
613   // In some cases we need to know if an entity was present in a directly-
614   // imported module (as opposed to a transitive import).  This avoids
615   // searching both Imports and Exports.
616   DirectModuleImports.insert(Mod);
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                                        bool IsImplicit) {
974   // We shouldn't create new global module fragment if there is already
975   // one.
976   if (!GlobalModuleFragment) {
977     ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
978     GlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit(
979         BeginLoc, getCurrentModule());
980   }
981 
982   assert(GlobalModuleFragment && "module creation should not fail");
983 
984   // Enter the scope of the global module.
985   ModuleScopes.push_back({BeginLoc, GlobalModuleFragment,
986                           /*ModuleInterface=*/false,
987                           /*IsPartition=*/false,
988                           /*ImplicitGlobalModuleFragment=*/IsImplicit,
989                           /*OuterVisibleModules=*/{}});
990   VisibleModules.setVisible(GlobalModuleFragment, BeginLoc);
991 
992   return GlobalModuleFragment;
993 }
994 
995 void Sema::PopGlobalModuleFragment() {
996   assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
997          "left the wrong module scope, which is not global module fragment");
998   ModuleScopes.pop_back();
999 }
1000 
1001 bool Sema::isModuleUnitOfCurrentTU(const Module *M) const {
1002   assert(M);
1003 
1004   Module *CurrentModuleUnit = getCurrentModule();
1005 
1006   // If we are not in a module currently, M must not be the module unit of
1007   // current TU.
1008   if (!CurrentModuleUnit)
1009     return false;
1010 
1011   return M->isSubModuleOf(CurrentModuleUnit->getTopLevelModule());
1012 }
1013