SemaModule.cpp 39 KB

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