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