SemaModule.cpp 27 KB

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