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