SemaModule.cpp 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742
  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. using namespace clang;
  18. using namespace sema;
  19. static void checkModuleImportContext(Sema &S, Module *M,
  20. SourceLocation ImportLoc, DeclContext *DC,
  21. bool FromInclude = false) {
  22. SourceLocation ExternCLoc;
  23. if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
  24. switch (LSD->getLanguage()) {
  25. case LinkageSpecDecl::lang_c:
  26. if (ExternCLoc.isInvalid())
  27. ExternCLoc = LSD->getBeginLoc();
  28. break;
  29. case LinkageSpecDecl::lang_cxx:
  30. break;
  31. }
  32. DC = LSD->getParent();
  33. }
  34. while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
  35. DC = DC->getParent();
  36. if (!isa<TranslationUnitDecl>(DC)) {
  37. S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
  38. ? diag::ext_module_import_not_at_top_level_noop
  39. : diag::err_module_import_not_at_top_level_fatal)
  40. << M->getFullModuleName() << DC;
  41. S.Diag(cast<Decl>(DC)->getBeginLoc(),
  42. diag::note_module_import_not_at_top_level)
  43. << DC;
  44. } else if (!M->IsExternC && ExternCLoc.isValid()) {
  45. S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
  46. << M->getFullModuleName();
  47. S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
  48. }
  49. }
  50. Sema::DeclGroupPtrTy
  51. Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
  52. if (!ModuleScopes.empty() &&
  53. ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
  54. // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
  55. // already implicitly entering the global module fragment. That's OK.
  56. assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
  57. "unexpectedly encountered multiple global module fragment decls");
  58. ModuleScopes.back().BeginLoc = ModuleLoc;
  59. return nullptr;
  60. }
  61. // We start in the global module; all those declarations are implicitly
  62. // module-private (though they do not have module linkage).
  63. Module *GlobalModule =
  64. PushGlobalModuleFragment(ModuleLoc, /*IsImplicit=*/false);
  65. // All declarations created from now on are owned by the global module.
  66. auto *TU = Context.getTranslationUnitDecl();
  67. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
  68. TU->setLocalOwningModule(GlobalModule);
  69. // FIXME: Consider creating an explicit representation of this declaration.
  70. return nullptr;
  71. }
  72. Sema::DeclGroupPtrTy
  73. Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
  74. ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl) {
  75. assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
  76. "should only have module decl in Modules TS or C++20");
  77. // A module implementation unit requires that we are not compiling a module
  78. // of any kind. A module interface unit requires that we are not compiling a
  79. // module map.
  80. switch (getLangOpts().getCompilingModule()) {
  81. case LangOptions::CMK_None:
  82. // It's OK to compile a module interface as a normal translation unit.
  83. break;
  84. case LangOptions::CMK_ModuleInterface:
  85. if (MDK != ModuleDeclKind::Implementation)
  86. break;
  87. // We were asked to compile a module interface unit but this is a module
  88. // implementation unit. That indicates the 'export' is missing.
  89. Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
  90. << FixItHint::CreateInsertion(ModuleLoc, "export ");
  91. MDK = ModuleDeclKind::Interface;
  92. break;
  93. case LangOptions::CMK_ModuleMap:
  94. Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
  95. return nullptr;
  96. case LangOptions::CMK_HeaderModule:
  97. Diag(ModuleLoc, diag::err_module_decl_in_header_module);
  98. return nullptr;
  99. }
  100. assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
  101. // FIXME: Most of this work should be done by the preprocessor rather than
  102. // here, in order to support macro import.
  103. // Only one module-declaration is permitted per source file.
  104. if (!ModuleScopes.empty() &&
  105. ModuleScopes.back().Module->isModulePurview()) {
  106. Diag(ModuleLoc, diag::err_module_redeclaration);
  107. Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
  108. diag::note_prev_module_declaration);
  109. return nullptr;
  110. }
  111. // Find the global module fragment we're adopting into this module, if any.
  112. Module *GlobalModuleFragment = nullptr;
  113. if (!ModuleScopes.empty() &&
  114. ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
  115. GlobalModuleFragment = ModuleScopes.back().Module;
  116. // In C++20, the module-declaration must be the first declaration if there
  117. // is no global module fragment.
  118. if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !GlobalModuleFragment) {
  119. Diag(ModuleLoc, diag::err_module_decl_not_at_start);
  120. SourceLocation BeginLoc =
  121. ModuleScopes.empty()
  122. ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
  123. : ModuleScopes.back().BeginLoc;
  124. if (BeginLoc.isValid()) {
  125. Diag(BeginLoc, diag::note_global_module_introducer_missing)
  126. << FixItHint::CreateInsertion(BeginLoc, "module;\n");
  127. }
  128. }
  129. // Flatten the dots in a module name. Unlike Clang's hierarchical module map
  130. // modules, the dots here are just another character that can appear in a
  131. // module name.
  132. std::string ModuleName;
  133. for (auto &Piece : Path) {
  134. if (!ModuleName.empty())
  135. ModuleName += ".";
  136. ModuleName += Piece.first->getName();
  137. }
  138. // If a module name was explicitly specified on the command line, it must be
  139. // correct.
  140. if (!getLangOpts().CurrentModule.empty() &&
  141. getLangOpts().CurrentModule != ModuleName) {
  142. Diag(Path.front().second, diag::err_current_module_name_mismatch)
  143. << SourceRange(Path.front().second, Path.back().second)
  144. << getLangOpts().CurrentModule;
  145. return nullptr;
  146. }
  147. const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
  148. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  149. Module *Mod;
  150. switch (MDK) {
  151. case ModuleDeclKind::Interface: {
  152. // We can't have parsed or imported a definition of this module or parsed a
  153. // module map defining it already.
  154. if (auto *M = Map.findModule(ModuleName)) {
  155. Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
  156. if (M->DefinitionLoc.isValid())
  157. Diag(M->DefinitionLoc, diag::note_prev_module_definition);
  158. else if (Optional<FileEntryRef> FE = M->getASTFile())
  159. Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
  160. << FE->getName();
  161. Mod = M;
  162. break;
  163. }
  164. // Create a Module for the module that we're defining.
  165. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  166. GlobalModuleFragment);
  167. assert(Mod && "module creation should not fail");
  168. break;
  169. }
  170. case ModuleDeclKind::Implementation:
  171. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
  172. PP.getIdentifierInfo(ModuleName), Path[0].second);
  173. Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
  174. Module::AllVisible,
  175. /*IsInclusionDirective=*/false);
  176. if (!Mod) {
  177. Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
  178. // Create an empty module interface unit for error recovery.
  179. Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
  180. GlobalModuleFragment);
  181. }
  182. break;
  183. }
  184. if (!GlobalModuleFragment) {
  185. ModuleScopes.push_back({});
  186. if (getLangOpts().ModulesLocalVisibility)
  187. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  188. } else {
  189. // We're done with the global module fragment now.
  190. ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
  191. }
  192. // Switch from the global module fragment (if any) to the named module.
  193. ModuleScopes.back().BeginLoc = StartLoc;
  194. ModuleScopes.back().Module = Mod;
  195. ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
  196. VisibleModules.setVisible(Mod, ModuleLoc);
  197. // From now on, we have an owning module for all declarations we see.
  198. // However, those declarations are module-private unless explicitly
  199. // exported.
  200. auto *TU = Context.getTranslationUnitDecl();
  201. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  202. TU->setLocalOwningModule(Mod);
  203. // FIXME: Create a ModuleDecl.
  204. return nullptr;
  205. }
  206. Sema::DeclGroupPtrTy
  207. Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
  208. SourceLocation PrivateLoc) {
  209. // C++20 [basic.link]/2:
  210. // A private-module-fragment shall appear only in a primary module
  211. // interface unit.
  212. switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
  213. : ModuleScopes.back().Module->Kind) {
  214. case Module::ModuleMapModule:
  215. case Module::GlobalModuleFragment:
  216. Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
  217. return nullptr;
  218. case Module::PrivateModuleFragment:
  219. Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
  220. Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
  221. return nullptr;
  222. case Module::ModuleInterfaceUnit:
  223. break;
  224. }
  225. if (!ModuleScopes.back().ModuleInterface) {
  226. Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
  227. Diag(ModuleScopes.back().BeginLoc,
  228. diag::note_not_module_interface_add_export)
  229. << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
  230. return nullptr;
  231. }
  232. // FIXME: Check this isn't a module interface partition.
  233. // FIXME: Check that this translation unit does not import any partitions;
  234. // such imports would violate [basic.link]/2's "shall be the only module unit"
  235. // restriction.
  236. // We've finished the public fragment of the translation unit.
  237. ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
  238. auto &Map = PP.getHeaderSearchInfo().getModuleMap();
  239. Module *PrivateModuleFragment =
  240. Map.createPrivateModuleFragmentForInterfaceUnit(
  241. ModuleScopes.back().Module, PrivateLoc);
  242. assert(PrivateModuleFragment && "module creation should not fail");
  243. // Enter the scope of the private module fragment.
  244. ModuleScopes.push_back({});
  245. ModuleScopes.back().BeginLoc = ModuleLoc;
  246. ModuleScopes.back().Module = PrivateModuleFragment;
  247. ModuleScopes.back().ModuleInterface = true;
  248. VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
  249. // All declarations created from now on are scoped to the private module
  250. // fragment (and are neither visible nor reachable in importers of the module
  251. // interface).
  252. auto *TU = Context.getTranslationUnitDecl();
  253. TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
  254. TU->setLocalOwningModule(PrivateModuleFragment);
  255. // FIXME: Consider creating an explicit representation of this declaration.
  256. return nullptr;
  257. }
  258. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  259. SourceLocation ExportLoc,
  260. SourceLocation ImportLoc,
  261. ModuleIdPath Path) {
  262. // Flatten the module path for a Modules TS module name.
  263. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
  264. if (getLangOpts().ModulesTS) {
  265. std::string ModuleName;
  266. for (auto &Piece : Path) {
  267. if (!ModuleName.empty())
  268. ModuleName += ".";
  269. ModuleName += Piece.first->getName();
  270. }
  271. ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
  272. Path = ModuleIdPath(ModuleNameLoc);
  273. }
  274. Module *Mod =
  275. getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
  276. /*IsInclusionDirective=*/false);
  277. if (!Mod)
  278. return true;
  279. return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
  280. }
  281. /// Determine whether \p D is lexically within an export-declaration.
  282. static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
  283. for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
  284. if (auto *ED = dyn_cast<ExportDecl>(DC))
  285. return ED;
  286. return nullptr;
  287. }
  288. DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
  289. SourceLocation ExportLoc,
  290. SourceLocation ImportLoc,
  291. Module *Mod, ModuleIdPath Path) {
  292. VisibleModules.setVisible(Mod, ImportLoc);
  293. checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
  294. // FIXME: we should support importing a submodule within a different submodule
  295. // of the same top-level module. Until we do, make it an error rather than
  296. // silently ignoring the import.
  297. // Import-from-implementation is valid in the Modules TS. FIXME: Should we
  298. // warn on a redundant import of the current module?
  299. // FIXME: Import of a module from an implementation partition of the same
  300. // module is permitted.
  301. if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
  302. (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
  303. Diag(ImportLoc, getLangOpts().isCompilingModule()
  304. ? diag::err_module_self_import
  305. : diag::err_module_import_in_implementation)
  306. << Mod->getFullModuleName() << getLangOpts().CurrentModule;
  307. }
  308. SmallVector<SourceLocation, 2> IdentifierLocs;
  309. Module *ModCheck = Mod;
  310. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  311. // If we've run out of module parents, just drop the remaining identifiers.
  312. // We need the length to be consistent.
  313. if (!ModCheck)
  314. break;
  315. ModCheck = ModCheck->Parent;
  316. IdentifierLocs.push_back(Path[I].second);
  317. }
  318. // If this was a header import, pad out with dummy locations.
  319. // FIXME: Pass in and use the location of the header-name token in this case.
  320. if (Path.empty()) {
  321. for (; ModCheck; ModCheck = ModCheck->Parent) {
  322. IdentifierLocs.push_back(SourceLocation());
  323. }
  324. }
  325. ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
  326. Mod, IdentifierLocs);
  327. CurContext->addDecl(Import);
  328. // Sequence initialization of the imported module before that of the current
  329. // module, if any.
  330. if (!ModuleScopes.empty())
  331. Context.addModuleInitializer(ModuleScopes.back().Module, Import);
  332. if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) {
  333. // Re-export the module if the imported module is exported.
  334. // Note that we don't need to add re-exported module to Imports field
  335. // since `Exports` implies the module is imported already.
  336. if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
  337. getCurrentModule()->Exports.emplace_back(Mod, false);
  338. else
  339. getCurrentModule()->Imports.insert(Mod);
  340. } else if (ExportLoc.isValid()) {
  341. // [module.interface]p1:
  342. // An export-declaration shall inhabit a namespace scope and appear in the
  343. // purview of a module interface unit.
  344. Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
  345. }
  346. return Import;
  347. }
  348. void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  349. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  350. BuildModuleInclude(DirectiveLoc, Mod);
  351. }
  352. void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
  353. // Determine whether we're in the #include buffer for a module. The #includes
  354. // in that buffer do not qualify as module imports; they're just an
  355. // implementation detail of us building the module.
  356. //
  357. // FIXME: Should we even get ActOnModuleInclude calls for those?
  358. bool IsInModuleIncludes =
  359. TUKind == TU_Module &&
  360. getSourceManager().isWrittenInMainFile(DirectiveLoc);
  361. bool ShouldAddImport = !IsInModuleIncludes;
  362. // If this module import was due to an inclusion directive, create an
  363. // implicit import declaration to capture it in the AST.
  364. if (ShouldAddImport) {
  365. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  366. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  367. DirectiveLoc, Mod,
  368. DirectiveLoc);
  369. if (!ModuleScopes.empty())
  370. Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
  371. TU->addDecl(ImportD);
  372. Consumer.HandleImplicitImportDecl(ImportD);
  373. }
  374. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
  375. VisibleModules.setVisible(Mod, DirectiveLoc);
  376. }
  377. void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
  378. checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
  379. ModuleScopes.push_back({});
  380. ModuleScopes.back().Module = Mod;
  381. if (getLangOpts().ModulesLocalVisibility)
  382. ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
  383. VisibleModules.setVisible(Mod, DirectiveLoc);
  384. // The enclosing context is now part of this module.
  385. // FIXME: Consider creating a child DeclContext to hold the entities
  386. // lexically within the module.
  387. if (getLangOpts().trackLocalOwningModule()) {
  388. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  389. cast<Decl>(DC)->setModuleOwnershipKind(
  390. getLangOpts().ModulesLocalVisibility
  391. ? Decl::ModuleOwnershipKind::VisibleWhenImported
  392. : Decl::ModuleOwnershipKind::Visible);
  393. cast<Decl>(DC)->setLocalOwningModule(Mod);
  394. }
  395. }
  396. }
  397. void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
  398. if (getLangOpts().ModulesLocalVisibility) {
  399. VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
  400. // Leaving a module hides namespace names, so our visible namespace cache
  401. // is now out of date.
  402. VisibleNamespaceCache.clear();
  403. }
  404. assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
  405. "left the wrong module scope");
  406. ModuleScopes.pop_back();
  407. // We got to the end of processing a local module. Create an
  408. // ImportDecl as we would for an imported module.
  409. FileID File = getSourceManager().getFileID(EomLoc);
  410. SourceLocation DirectiveLoc;
  411. if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
  412. // We reached the end of a #included module header. Use the #include loc.
  413. assert(File != getSourceManager().getMainFileID() &&
  414. "end of submodule in main source file");
  415. DirectiveLoc = getSourceManager().getIncludeLoc(File);
  416. } else {
  417. // We reached an EOM pragma. Use the pragma location.
  418. DirectiveLoc = EomLoc;
  419. }
  420. BuildModuleInclude(DirectiveLoc, Mod);
  421. // Any further declarations are in whatever module we returned to.
  422. if (getLangOpts().trackLocalOwningModule()) {
  423. // The parser guarantees that this is the same context that we entered
  424. // the module within.
  425. for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  426. cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
  427. if (!getCurrentModule())
  428. cast<Decl>(DC)->setModuleOwnershipKind(
  429. Decl::ModuleOwnershipKind::Unowned);
  430. }
  431. }
  432. }
  433. void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
  434. Module *Mod) {
  435. // Bail if we're not allowed to implicitly import a module here.
  436. if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
  437. VisibleModules.isVisible(Mod))
  438. return;
  439. // Create the implicit import declaration.
  440. TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
  441. ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
  442. Loc, Mod, Loc);
  443. TU->addDecl(ImportD);
  444. Consumer.HandleImplicitImportDecl(ImportD);
  445. // Make the module visible.
  446. getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
  447. VisibleModules.setVisible(Mod, Loc);
  448. }
  449. /// We have parsed the start of an export declaration, including the '{'
  450. /// (if present).
  451. Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
  452. SourceLocation LBraceLoc) {
  453. ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
  454. // Set this temporarily so we know the export-declaration was braced.
  455. D->setRBraceLoc(LBraceLoc);
  456. CurContext->addDecl(D);
  457. PushDeclContext(S, D);
  458. // C++2a [module.interface]p1:
  459. // An export-declaration shall appear only [...] in the purview of a module
  460. // interface unit. An export-declaration shall not appear directly or
  461. // indirectly within [...] a private-module-fragment.
  462. if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
  463. Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
  464. D->setInvalidDecl();
  465. return D;
  466. } else if (!ModuleScopes.back().ModuleInterface) {
  467. Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
  468. Diag(ModuleScopes.back().BeginLoc,
  469. diag::note_not_module_interface_add_export)
  470. << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
  471. D->setInvalidDecl();
  472. return D;
  473. } else if (ModuleScopes.back().Module->Kind ==
  474. Module::PrivateModuleFragment) {
  475. Diag(ExportLoc, diag::err_export_in_private_module_fragment);
  476. Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
  477. D->setInvalidDecl();
  478. return D;
  479. }
  480. for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
  481. if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
  482. // An export-declaration shall not appear directly or indirectly within
  483. // an unnamed namespace [...]
  484. if (ND->isAnonymousNamespace()) {
  485. Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
  486. Diag(ND->getLocation(), diag::note_anonymous_namespace);
  487. // Don't diagnose internal-linkage declarations in this region.
  488. D->setInvalidDecl();
  489. return D;
  490. }
  491. // A declaration is exported if it is [...] a namespace-definition
  492. // that contains an exported declaration.
  493. //
  494. // Defer exporting the namespace until after we leave it, in order to
  495. // avoid marking all subsequent declarations in the namespace as exported.
  496. if (!DeferredExportedNamespaces.insert(ND).second)
  497. break;
  498. }
  499. }
  500. // [...] its declaration or declaration-seq shall not contain an
  501. // export-declaration.
  502. if (auto *ED = getEnclosingExportDecl(D)) {
  503. Diag(ExportLoc, diag::err_export_within_export);
  504. if (ED->hasBraces())
  505. Diag(ED->getLocation(), diag::note_export);
  506. D->setInvalidDecl();
  507. return D;
  508. }
  509. D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
  510. return D;
  511. }
  512. static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
  513. SourceLocation BlockStart);
  514. namespace {
  515. enum class UnnamedDeclKind {
  516. Empty,
  517. StaticAssert,
  518. Asm,
  519. UsingDirective,
  520. Context
  521. };
  522. }
  523. static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
  524. if (isa<EmptyDecl>(D))
  525. return UnnamedDeclKind::Empty;
  526. if (isa<StaticAssertDecl>(D))
  527. return UnnamedDeclKind::StaticAssert;
  528. if (isa<FileScopeAsmDecl>(D))
  529. return UnnamedDeclKind::Asm;
  530. if (isa<UsingDirectiveDecl>(D))
  531. return UnnamedDeclKind::UsingDirective;
  532. // Everything else either introduces one or more names or is ill-formed.
  533. return llvm::None;
  534. }
  535. unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
  536. switch (UDK) {
  537. case UnnamedDeclKind::Empty:
  538. case UnnamedDeclKind::StaticAssert:
  539. // Allow empty-declarations and static_asserts in an export block as an
  540. // extension.
  541. return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
  542. case UnnamedDeclKind::UsingDirective:
  543. // Allow exporting using-directives as an extension.
  544. return diag::ext_export_using_directive;
  545. case UnnamedDeclKind::Context:
  546. // Allow exporting DeclContexts that transitively contain no declarations
  547. // as an extension.
  548. return diag::ext_export_no_names;
  549. case UnnamedDeclKind::Asm:
  550. return diag::err_export_no_name;
  551. }
  552. llvm_unreachable("unknown kind");
  553. }
  554. static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
  555. SourceLocation BlockStart) {
  556. S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
  557. << (unsigned)UDK;
  558. if (BlockStart.isValid())
  559. S.Diag(BlockStart, diag::note_export);
  560. }
  561. /// Check that it's valid to export \p D.
  562. static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
  563. // C++2a [module.interface]p3:
  564. // An exported declaration shall declare at least one name
  565. if (auto UDK = getUnnamedDeclKind(D))
  566. diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
  567. // [...] shall not declare a name with internal linkage.
  568. if (auto *ND = dyn_cast<NamedDecl>(D)) {
  569. // Don't diagnose anonymous union objects; we'll diagnose their members
  570. // instead.
  571. if (ND->getDeclName() && ND->getFormalLinkage() == InternalLinkage) {
  572. S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
  573. if (BlockStart.isValid())
  574. S.Diag(BlockStart, diag::note_export);
  575. }
  576. }
  577. // C++2a [module.interface]p5:
  578. // all entities to which all of the using-declarators ultimately refer
  579. // shall have been introduced with a name having external linkage
  580. if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
  581. NamedDecl *Target = USD->getUnderlyingDecl();
  582. if (Target->getFormalLinkage() == InternalLinkage) {
  583. S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
  584. S.Diag(Target->getLocation(), diag::note_using_decl_target);
  585. if (BlockStart.isValid())
  586. S.Diag(BlockStart, diag::note_export);
  587. }
  588. }
  589. // Recurse into namespace-scope DeclContexts. (Only namespace-scope
  590. // declarations are exported.)
  591. if (auto *DC = dyn_cast<DeclContext>(D))
  592. if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
  593. return checkExportedDeclContext(S, DC, BlockStart);
  594. return false;
  595. }
  596. /// Check that it's valid to export all the declarations in \p DC.
  597. static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
  598. SourceLocation BlockStart) {
  599. bool AllUnnamed = true;
  600. for (auto *D : DC->decls())
  601. AllUnnamed &= checkExportedDecl(S, D, BlockStart);
  602. return AllUnnamed;
  603. }
  604. /// Complete the definition of an export declaration.
  605. Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
  606. auto *ED = cast<ExportDecl>(D);
  607. if (RBraceLoc.isValid())
  608. ED->setRBraceLoc(RBraceLoc);
  609. PopDeclContext();
  610. if (!D->isInvalidDecl()) {
  611. SourceLocation BlockStart =
  612. ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
  613. for (auto *Child : ED->decls()) {
  614. if (checkExportedDecl(*this, Child, BlockStart)) {
  615. // If a top-level child is a linkage-spec declaration, it might contain
  616. // no declarations (transitively), in which case it's ill-formed.
  617. diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
  618. BlockStart);
  619. }
  620. }
  621. }
  622. return D;
  623. }
  624. Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc,
  625. bool IsImplicit) {
  626. ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap();
  627. Module *GlobalModule =
  628. Map.createGlobalModuleFragmentForModuleUnit(BeginLoc, getCurrentModule());
  629. assert(GlobalModule && "module creation should not fail");
  630. // Enter the scope of the global module.
  631. ModuleScopes.push_back({BeginLoc, GlobalModule,
  632. /*ModuleInterface=*/false,
  633. /*ImplicitGlobalModuleFragment=*/IsImplicit,
  634. /*VisibleModuleSet*/{}});
  635. VisibleModules.setVisible(GlobalModule, BeginLoc);
  636. return GlobalModule;
  637. }
  638. void Sema::PopGlobalModuleFragment() {
  639. assert(!ModuleScopes.empty() && getCurrentModule()->isGlobalModule() &&
  640. "left the wrong module scope, which is not global module fragment");
  641. ModuleScopes.pop_back();
  642. }