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