SemaModule.cpp 27 KB

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