17330f729Sjoerg //===--- SemaModule.cpp - Semantic Analysis for Modules -------------------===//
27330f729Sjoerg //
37330f729Sjoerg // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
47330f729Sjoerg // See https://llvm.org/LICENSE.txt for license information.
57330f729Sjoerg // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
67330f729Sjoerg //
77330f729Sjoerg //===----------------------------------------------------------------------===//
87330f729Sjoerg //
97330f729Sjoerg // This file implements semantic analysis for modules (C++ modules syntax,
107330f729Sjoerg // Objective-C modules syntax, and Clang header modules).
117330f729Sjoerg //
127330f729Sjoerg //===----------------------------------------------------------------------===//
137330f729Sjoerg
147330f729Sjoerg #include "clang/AST/ASTConsumer.h"
157330f729Sjoerg #include "clang/Lex/HeaderSearch.h"
167330f729Sjoerg #include "clang/Lex/Preprocessor.h"
177330f729Sjoerg #include "clang/Sema/SemaInternal.h"
187330f729Sjoerg
197330f729Sjoerg using namespace clang;
207330f729Sjoerg using namespace sema;
217330f729Sjoerg
checkModuleImportContext(Sema & S,Module * M,SourceLocation ImportLoc,DeclContext * DC,bool FromInclude=false)227330f729Sjoerg static void checkModuleImportContext(Sema &S, Module *M,
237330f729Sjoerg SourceLocation ImportLoc, DeclContext *DC,
247330f729Sjoerg bool FromInclude = false) {
257330f729Sjoerg SourceLocation ExternCLoc;
267330f729Sjoerg
277330f729Sjoerg if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
287330f729Sjoerg switch (LSD->getLanguage()) {
297330f729Sjoerg case LinkageSpecDecl::lang_c:
307330f729Sjoerg if (ExternCLoc.isInvalid())
317330f729Sjoerg ExternCLoc = LSD->getBeginLoc();
327330f729Sjoerg break;
337330f729Sjoerg case LinkageSpecDecl::lang_cxx:
347330f729Sjoerg break;
357330f729Sjoerg }
367330f729Sjoerg DC = LSD->getParent();
377330f729Sjoerg }
387330f729Sjoerg
397330f729Sjoerg while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
407330f729Sjoerg DC = DC->getParent();
417330f729Sjoerg
427330f729Sjoerg if (!isa<TranslationUnitDecl>(DC)) {
437330f729Sjoerg S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
447330f729Sjoerg ? diag::ext_module_import_not_at_top_level_noop
457330f729Sjoerg : diag::err_module_import_not_at_top_level_fatal)
467330f729Sjoerg << M->getFullModuleName() << DC;
477330f729Sjoerg S.Diag(cast<Decl>(DC)->getBeginLoc(),
487330f729Sjoerg diag::note_module_import_not_at_top_level)
497330f729Sjoerg << DC;
507330f729Sjoerg } else if (!M->IsExternC && ExternCLoc.isValid()) {
517330f729Sjoerg S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
527330f729Sjoerg << M->getFullModuleName();
537330f729Sjoerg S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
547330f729Sjoerg }
557330f729Sjoerg }
567330f729Sjoerg
577330f729Sjoerg Sema::DeclGroupPtrTy
ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)587330f729Sjoerg Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
597330f729Sjoerg if (!ModuleScopes.empty() &&
607330f729Sjoerg ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
617330f729Sjoerg // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
627330f729Sjoerg // already implicitly entering the global module fragment. That's OK.
637330f729Sjoerg assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
647330f729Sjoerg "unexpectedly encountered multiple global module fragment decls");
657330f729Sjoerg ModuleScopes.back().BeginLoc = ModuleLoc;
667330f729Sjoerg return nullptr;
677330f729Sjoerg }
687330f729Sjoerg
697330f729Sjoerg // We start in the global module; all those declarations are implicitly
707330f729Sjoerg // module-private (though they do not have module linkage).
717330f729Sjoerg auto &Map = PP.getHeaderSearchInfo().getModuleMap();
727330f729Sjoerg auto *GlobalModule = Map.createGlobalModuleFragmentForModuleUnit(ModuleLoc);
737330f729Sjoerg assert(GlobalModule && "module creation should not fail");
747330f729Sjoerg
757330f729Sjoerg // Enter the scope of the global module.
767330f729Sjoerg ModuleScopes.push_back({});
777330f729Sjoerg ModuleScopes.back().BeginLoc = ModuleLoc;
787330f729Sjoerg ModuleScopes.back().Module = GlobalModule;
797330f729Sjoerg VisibleModules.setVisible(GlobalModule, ModuleLoc);
807330f729Sjoerg
817330f729Sjoerg // All declarations created from now on are owned by the global module.
827330f729Sjoerg auto *TU = Context.getTranslationUnitDecl();
837330f729Sjoerg TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
847330f729Sjoerg TU->setLocalOwningModule(GlobalModule);
857330f729Sjoerg
867330f729Sjoerg // FIXME: Consider creating an explicit representation of this declaration.
877330f729Sjoerg return nullptr;
887330f729Sjoerg }
897330f729Sjoerg
907330f729Sjoerg Sema::DeclGroupPtrTy
ActOnModuleDecl(SourceLocation StartLoc,SourceLocation ModuleLoc,ModuleDeclKind MDK,ModuleIdPath Path,bool IsFirstDecl)917330f729Sjoerg Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
927330f729Sjoerg ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl) {
937330f729Sjoerg assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
947330f729Sjoerg "should only have module decl in Modules TS or C++20");
957330f729Sjoerg
967330f729Sjoerg // A module implementation unit requires that we are not compiling a module
977330f729Sjoerg // of any kind. A module interface unit requires that we are not compiling a
987330f729Sjoerg // module map.
997330f729Sjoerg switch (getLangOpts().getCompilingModule()) {
1007330f729Sjoerg case LangOptions::CMK_None:
1017330f729Sjoerg // It's OK to compile a module interface as a normal translation unit.
1027330f729Sjoerg break;
1037330f729Sjoerg
1047330f729Sjoerg case LangOptions::CMK_ModuleInterface:
1057330f729Sjoerg if (MDK != ModuleDeclKind::Implementation)
1067330f729Sjoerg break;
1077330f729Sjoerg
1087330f729Sjoerg // We were asked to compile a module interface unit but this is a module
1097330f729Sjoerg // implementation unit. That indicates the 'export' is missing.
1107330f729Sjoerg Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
1117330f729Sjoerg << FixItHint::CreateInsertion(ModuleLoc, "export ");
1127330f729Sjoerg MDK = ModuleDeclKind::Interface;
1137330f729Sjoerg break;
1147330f729Sjoerg
1157330f729Sjoerg case LangOptions::CMK_ModuleMap:
1167330f729Sjoerg Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
1177330f729Sjoerg return nullptr;
1187330f729Sjoerg
1197330f729Sjoerg case LangOptions::CMK_HeaderModule:
1207330f729Sjoerg Diag(ModuleLoc, diag::err_module_decl_in_header_module);
1217330f729Sjoerg return nullptr;
1227330f729Sjoerg }
1237330f729Sjoerg
1247330f729Sjoerg assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
1257330f729Sjoerg
1267330f729Sjoerg // FIXME: Most of this work should be done by the preprocessor rather than
1277330f729Sjoerg // here, in order to support macro import.
1287330f729Sjoerg
1297330f729Sjoerg // Only one module-declaration is permitted per source file.
1307330f729Sjoerg if (!ModuleScopes.empty() &&
1317330f729Sjoerg ModuleScopes.back().Module->isModulePurview()) {
1327330f729Sjoerg Diag(ModuleLoc, diag::err_module_redeclaration);
1337330f729Sjoerg Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
1347330f729Sjoerg diag::note_prev_module_declaration);
1357330f729Sjoerg return nullptr;
1367330f729Sjoerg }
1377330f729Sjoerg
1387330f729Sjoerg // Find the global module fragment we're adopting into this module, if any.
1397330f729Sjoerg Module *GlobalModuleFragment = nullptr;
1407330f729Sjoerg if (!ModuleScopes.empty() &&
1417330f729Sjoerg ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
1427330f729Sjoerg GlobalModuleFragment = ModuleScopes.back().Module;
1437330f729Sjoerg
1447330f729Sjoerg // In C++20, the module-declaration must be the first declaration if there
1457330f729Sjoerg // is no global module fragment.
1467330f729Sjoerg if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !GlobalModuleFragment) {
1477330f729Sjoerg Diag(ModuleLoc, diag::err_module_decl_not_at_start);
1487330f729Sjoerg SourceLocation BeginLoc =
1497330f729Sjoerg ModuleScopes.empty()
1507330f729Sjoerg ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
1517330f729Sjoerg : ModuleScopes.back().BeginLoc;
1527330f729Sjoerg if (BeginLoc.isValid()) {
1537330f729Sjoerg Diag(BeginLoc, diag::note_global_module_introducer_missing)
1547330f729Sjoerg << FixItHint::CreateInsertion(BeginLoc, "module;\n");
1557330f729Sjoerg }
1567330f729Sjoerg }
1577330f729Sjoerg
1587330f729Sjoerg // Flatten the dots in a module name. Unlike Clang's hierarchical module map
1597330f729Sjoerg // modules, the dots here are just another character that can appear in a
1607330f729Sjoerg // module name.
1617330f729Sjoerg std::string ModuleName;
1627330f729Sjoerg for (auto &Piece : Path) {
1637330f729Sjoerg if (!ModuleName.empty())
1647330f729Sjoerg ModuleName += ".";
1657330f729Sjoerg ModuleName += Piece.first->getName();
1667330f729Sjoerg }
1677330f729Sjoerg
1687330f729Sjoerg // If a module name was explicitly specified on the command line, it must be
1697330f729Sjoerg // correct.
1707330f729Sjoerg if (!getLangOpts().CurrentModule.empty() &&
1717330f729Sjoerg getLangOpts().CurrentModule != ModuleName) {
1727330f729Sjoerg Diag(Path.front().second, diag::err_current_module_name_mismatch)
1737330f729Sjoerg << SourceRange(Path.front().second, Path.back().second)
1747330f729Sjoerg << getLangOpts().CurrentModule;
1757330f729Sjoerg return nullptr;
1767330f729Sjoerg }
1777330f729Sjoerg const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
1787330f729Sjoerg
1797330f729Sjoerg auto &Map = PP.getHeaderSearchInfo().getModuleMap();
1807330f729Sjoerg Module *Mod;
1817330f729Sjoerg
1827330f729Sjoerg switch (MDK) {
1837330f729Sjoerg case ModuleDeclKind::Interface: {
1847330f729Sjoerg // We can't have parsed or imported a definition of this module or parsed a
1857330f729Sjoerg // module map defining it already.
1867330f729Sjoerg if (auto *M = Map.findModule(ModuleName)) {
1877330f729Sjoerg Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
1887330f729Sjoerg if (M->DefinitionLoc.isValid())
1897330f729Sjoerg Diag(M->DefinitionLoc, diag::note_prev_module_definition);
190*e038c9c4Sjoerg else if (Optional<FileEntryRef> FE = M->getASTFile())
1917330f729Sjoerg Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
1927330f729Sjoerg << FE->getName();
1937330f729Sjoerg Mod = M;
1947330f729Sjoerg break;
1957330f729Sjoerg }
1967330f729Sjoerg
1977330f729Sjoerg // Create a Module for the module that we're defining.
1987330f729Sjoerg Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
1997330f729Sjoerg GlobalModuleFragment);
2007330f729Sjoerg assert(Mod && "module creation should not fail");
2017330f729Sjoerg break;
2027330f729Sjoerg }
2037330f729Sjoerg
2047330f729Sjoerg case ModuleDeclKind::Implementation:
2057330f729Sjoerg std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
2067330f729Sjoerg PP.getIdentifierInfo(ModuleName), Path[0].second);
2077330f729Sjoerg Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
2087330f729Sjoerg Module::AllVisible,
2097330f729Sjoerg /*IsInclusionDirective=*/false);
2107330f729Sjoerg if (!Mod) {
2117330f729Sjoerg Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
2127330f729Sjoerg // Create an empty module interface unit for error recovery.
2137330f729Sjoerg Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
2147330f729Sjoerg GlobalModuleFragment);
2157330f729Sjoerg }
2167330f729Sjoerg break;
2177330f729Sjoerg }
2187330f729Sjoerg
2197330f729Sjoerg if (!GlobalModuleFragment) {
2207330f729Sjoerg ModuleScopes.push_back({});
2217330f729Sjoerg if (getLangOpts().ModulesLocalVisibility)
2227330f729Sjoerg ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
2237330f729Sjoerg } else {
2247330f729Sjoerg // We're done with the global module fragment now.
2257330f729Sjoerg ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
2267330f729Sjoerg }
2277330f729Sjoerg
2287330f729Sjoerg // Switch from the global module fragment (if any) to the named module.
2297330f729Sjoerg ModuleScopes.back().BeginLoc = StartLoc;
2307330f729Sjoerg ModuleScopes.back().Module = Mod;
2317330f729Sjoerg ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
2327330f729Sjoerg VisibleModules.setVisible(Mod, ModuleLoc);
2337330f729Sjoerg
2347330f729Sjoerg // From now on, we have an owning module for all declarations we see.
2357330f729Sjoerg // However, those declarations are module-private unless explicitly
2367330f729Sjoerg // exported.
2377330f729Sjoerg auto *TU = Context.getTranslationUnitDecl();
2387330f729Sjoerg TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
2397330f729Sjoerg TU->setLocalOwningModule(Mod);
2407330f729Sjoerg
2417330f729Sjoerg // FIXME: Create a ModuleDecl.
2427330f729Sjoerg return nullptr;
2437330f729Sjoerg }
2447330f729Sjoerg
2457330f729Sjoerg Sema::DeclGroupPtrTy
ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,SourceLocation PrivateLoc)2467330f729Sjoerg Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
2477330f729Sjoerg SourceLocation PrivateLoc) {
2487330f729Sjoerg // C++20 [basic.link]/2:
2497330f729Sjoerg // A private-module-fragment shall appear only in a primary module
2507330f729Sjoerg // interface unit.
2517330f729Sjoerg switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
2527330f729Sjoerg : ModuleScopes.back().Module->Kind) {
2537330f729Sjoerg case Module::ModuleMapModule:
2547330f729Sjoerg case Module::GlobalModuleFragment:
2557330f729Sjoerg Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
2567330f729Sjoerg return nullptr;
2577330f729Sjoerg
2587330f729Sjoerg case Module::PrivateModuleFragment:
2597330f729Sjoerg Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
2607330f729Sjoerg Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
2617330f729Sjoerg return nullptr;
2627330f729Sjoerg
2637330f729Sjoerg case Module::ModuleInterfaceUnit:
2647330f729Sjoerg break;
2657330f729Sjoerg }
2667330f729Sjoerg
2677330f729Sjoerg if (!ModuleScopes.back().ModuleInterface) {
2687330f729Sjoerg Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
2697330f729Sjoerg Diag(ModuleScopes.back().BeginLoc,
2707330f729Sjoerg diag::note_not_module_interface_add_export)
2717330f729Sjoerg << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
2727330f729Sjoerg return nullptr;
2737330f729Sjoerg }
2747330f729Sjoerg
2757330f729Sjoerg // FIXME: Check this isn't a module interface partition.
2767330f729Sjoerg // FIXME: Check that this translation unit does not import any partitions;
2777330f729Sjoerg // such imports would violate [basic.link]/2's "shall be the only module unit"
2787330f729Sjoerg // restriction.
2797330f729Sjoerg
2807330f729Sjoerg // We've finished the public fragment of the translation unit.
2817330f729Sjoerg ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
2827330f729Sjoerg
2837330f729Sjoerg auto &Map = PP.getHeaderSearchInfo().getModuleMap();
2847330f729Sjoerg Module *PrivateModuleFragment =
2857330f729Sjoerg Map.createPrivateModuleFragmentForInterfaceUnit(
2867330f729Sjoerg ModuleScopes.back().Module, PrivateLoc);
2877330f729Sjoerg assert(PrivateModuleFragment && "module creation should not fail");
2887330f729Sjoerg
2897330f729Sjoerg // Enter the scope of the private module fragment.
2907330f729Sjoerg ModuleScopes.push_back({});
2917330f729Sjoerg ModuleScopes.back().BeginLoc = ModuleLoc;
2927330f729Sjoerg ModuleScopes.back().Module = PrivateModuleFragment;
2937330f729Sjoerg ModuleScopes.back().ModuleInterface = true;
2947330f729Sjoerg VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
2957330f729Sjoerg
2967330f729Sjoerg // All declarations created from now on are scoped to the private module
2977330f729Sjoerg // fragment (and are neither visible nor reachable in importers of the module
2987330f729Sjoerg // interface).
2997330f729Sjoerg auto *TU = Context.getTranslationUnitDecl();
3007330f729Sjoerg TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
3017330f729Sjoerg TU->setLocalOwningModule(PrivateModuleFragment);
3027330f729Sjoerg
3037330f729Sjoerg // FIXME: Consider creating an explicit representation of this declaration.
3047330f729Sjoerg return nullptr;
3057330f729Sjoerg }
3067330f729Sjoerg
ActOnModuleImport(SourceLocation StartLoc,SourceLocation ExportLoc,SourceLocation ImportLoc,ModuleIdPath Path)3077330f729Sjoerg DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
3087330f729Sjoerg SourceLocation ExportLoc,
3097330f729Sjoerg SourceLocation ImportLoc,
3107330f729Sjoerg ModuleIdPath Path) {
3117330f729Sjoerg // Flatten the module path for a Modules TS module name.
3127330f729Sjoerg std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
3137330f729Sjoerg if (getLangOpts().ModulesTS) {
3147330f729Sjoerg std::string ModuleName;
3157330f729Sjoerg for (auto &Piece : Path) {
3167330f729Sjoerg if (!ModuleName.empty())
3177330f729Sjoerg ModuleName += ".";
3187330f729Sjoerg ModuleName += Piece.first->getName();
3197330f729Sjoerg }
3207330f729Sjoerg ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
3217330f729Sjoerg Path = ModuleIdPath(ModuleNameLoc);
3227330f729Sjoerg }
3237330f729Sjoerg
3247330f729Sjoerg Module *Mod =
3257330f729Sjoerg getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
3267330f729Sjoerg /*IsInclusionDirective=*/false);
3277330f729Sjoerg if (!Mod)
3287330f729Sjoerg return true;
3297330f729Sjoerg
3307330f729Sjoerg return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
3317330f729Sjoerg }
3327330f729Sjoerg
3337330f729Sjoerg /// Determine whether \p D is lexically within an export-declaration.
getEnclosingExportDecl(const Decl * D)3347330f729Sjoerg static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
3357330f729Sjoerg for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
3367330f729Sjoerg if (auto *ED = dyn_cast<ExportDecl>(DC))
3377330f729Sjoerg return ED;
3387330f729Sjoerg return nullptr;
3397330f729Sjoerg }
3407330f729Sjoerg
ActOnModuleImport(SourceLocation StartLoc,SourceLocation ExportLoc,SourceLocation ImportLoc,Module * Mod,ModuleIdPath Path)3417330f729Sjoerg DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
3427330f729Sjoerg SourceLocation ExportLoc,
3437330f729Sjoerg SourceLocation ImportLoc,
3447330f729Sjoerg Module *Mod, ModuleIdPath Path) {
3457330f729Sjoerg VisibleModules.setVisible(Mod, ImportLoc);
3467330f729Sjoerg
3477330f729Sjoerg checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
3487330f729Sjoerg
3497330f729Sjoerg // FIXME: we should support importing a submodule within a different submodule
3507330f729Sjoerg // of the same top-level module. Until we do, make it an error rather than
3517330f729Sjoerg // silently ignoring the import.
3527330f729Sjoerg // Import-from-implementation is valid in the Modules TS. FIXME: Should we
3537330f729Sjoerg // warn on a redundant import of the current module?
3547330f729Sjoerg // FIXME: Import of a module from an implementation partition of the same
3557330f729Sjoerg // module is permitted.
3567330f729Sjoerg if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
3577330f729Sjoerg (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
3587330f729Sjoerg Diag(ImportLoc, getLangOpts().isCompilingModule()
3597330f729Sjoerg ? diag::err_module_self_import
3607330f729Sjoerg : diag::err_module_import_in_implementation)
3617330f729Sjoerg << Mod->getFullModuleName() << getLangOpts().CurrentModule;
3627330f729Sjoerg }
3637330f729Sjoerg
3647330f729Sjoerg SmallVector<SourceLocation, 2> IdentifierLocs;
3657330f729Sjoerg Module *ModCheck = Mod;
3667330f729Sjoerg for (unsigned I = 0, N = Path.size(); I != N; ++I) {
3677330f729Sjoerg // If we've run out of module parents, just drop the remaining identifiers.
3687330f729Sjoerg // We need the length to be consistent.
3697330f729Sjoerg if (!ModCheck)
3707330f729Sjoerg break;
3717330f729Sjoerg ModCheck = ModCheck->Parent;
3727330f729Sjoerg
3737330f729Sjoerg IdentifierLocs.push_back(Path[I].second);
3747330f729Sjoerg }
3757330f729Sjoerg
3767330f729Sjoerg // If this was a header import, pad out with dummy locations.
3777330f729Sjoerg // FIXME: Pass in and use the location of the header-name token in this case.
3787330f729Sjoerg if (Path.empty()) {
3797330f729Sjoerg for (; ModCheck; ModCheck = ModCheck->Parent) {
3807330f729Sjoerg IdentifierLocs.push_back(SourceLocation());
3817330f729Sjoerg }
3827330f729Sjoerg }
3837330f729Sjoerg
3847330f729Sjoerg ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
3857330f729Sjoerg Mod, IdentifierLocs);
3867330f729Sjoerg CurContext->addDecl(Import);
3877330f729Sjoerg
3887330f729Sjoerg // Sequence initialization of the imported module before that of the current
3897330f729Sjoerg // module, if any.
3907330f729Sjoerg if (!ModuleScopes.empty())
3917330f729Sjoerg Context.addModuleInitializer(ModuleScopes.back().Module, Import);
3927330f729Sjoerg
3937330f729Sjoerg // Re-export the module if needed.
3947330f729Sjoerg if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) {
3957330f729Sjoerg if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
3967330f729Sjoerg getCurrentModule()->Exports.emplace_back(Mod, false);
3977330f729Sjoerg } else if (ExportLoc.isValid()) {
3987330f729Sjoerg Diag(ExportLoc, diag::err_export_not_in_module_interface);
3997330f729Sjoerg }
4007330f729Sjoerg
4017330f729Sjoerg return Import;
4027330f729Sjoerg }
4037330f729Sjoerg
ActOnModuleInclude(SourceLocation DirectiveLoc,Module * Mod)4047330f729Sjoerg void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
4057330f729Sjoerg checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
4067330f729Sjoerg BuildModuleInclude(DirectiveLoc, Mod);
4077330f729Sjoerg }
4087330f729Sjoerg
BuildModuleInclude(SourceLocation DirectiveLoc,Module * Mod)4097330f729Sjoerg void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
4107330f729Sjoerg // Determine whether we're in the #include buffer for a module. The #includes
4117330f729Sjoerg // in that buffer do not qualify as module imports; they're just an
4127330f729Sjoerg // implementation detail of us building the module.
4137330f729Sjoerg //
4147330f729Sjoerg // FIXME: Should we even get ActOnModuleInclude calls for those?
4157330f729Sjoerg bool IsInModuleIncludes =
4167330f729Sjoerg TUKind == TU_Module &&
4177330f729Sjoerg getSourceManager().isWrittenInMainFile(DirectiveLoc);
4187330f729Sjoerg
4197330f729Sjoerg bool ShouldAddImport = !IsInModuleIncludes;
4207330f729Sjoerg
4217330f729Sjoerg // If this module import was due to an inclusion directive, create an
4227330f729Sjoerg // implicit import declaration to capture it in the AST.
4237330f729Sjoerg if (ShouldAddImport) {
4247330f729Sjoerg TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
4257330f729Sjoerg ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
4267330f729Sjoerg DirectiveLoc, Mod,
4277330f729Sjoerg DirectiveLoc);
4287330f729Sjoerg if (!ModuleScopes.empty())
4297330f729Sjoerg Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
4307330f729Sjoerg TU->addDecl(ImportD);
4317330f729Sjoerg Consumer.HandleImplicitImportDecl(ImportD);
4327330f729Sjoerg }
4337330f729Sjoerg
4347330f729Sjoerg getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
4357330f729Sjoerg VisibleModules.setVisible(Mod, DirectiveLoc);
4367330f729Sjoerg }
4377330f729Sjoerg
ActOnModuleBegin(SourceLocation DirectiveLoc,Module * Mod)4387330f729Sjoerg void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
4397330f729Sjoerg checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
4407330f729Sjoerg
4417330f729Sjoerg ModuleScopes.push_back({});
4427330f729Sjoerg ModuleScopes.back().Module = Mod;
4437330f729Sjoerg if (getLangOpts().ModulesLocalVisibility)
4447330f729Sjoerg ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
4457330f729Sjoerg
4467330f729Sjoerg VisibleModules.setVisible(Mod, DirectiveLoc);
4477330f729Sjoerg
4487330f729Sjoerg // The enclosing context is now part of this module.
4497330f729Sjoerg // FIXME: Consider creating a child DeclContext to hold the entities
4507330f729Sjoerg // lexically within the module.
4517330f729Sjoerg if (getLangOpts().trackLocalOwningModule()) {
4527330f729Sjoerg for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
4537330f729Sjoerg cast<Decl>(DC)->setModuleOwnershipKind(
4547330f729Sjoerg getLangOpts().ModulesLocalVisibility
4557330f729Sjoerg ? Decl::ModuleOwnershipKind::VisibleWhenImported
4567330f729Sjoerg : Decl::ModuleOwnershipKind::Visible);
4577330f729Sjoerg cast<Decl>(DC)->setLocalOwningModule(Mod);
4587330f729Sjoerg }
4597330f729Sjoerg }
4607330f729Sjoerg }
4617330f729Sjoerg
ActOnModuleEnd(SourceLocation EomLoc,Module * Mod)4627330f729Sjoerg void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
4637330f729Sjoerg if (getLangOpts().ModulesLocalVisibility) {
4647330f729Sjoerg VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
4657330f729Sjoerg // Leaving a module hides namespace names, so our visible namespace cache
4667330f729Sjoerg // is now out of date.
4677330f729Sjoerg VisibleNamespaceCache.clear();
4687330f729Sjoerg }
4697330f729Sjoerg
4707330f729Sjoerg assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
4717330f729Sjoerg "left the wrong module scope");
4727330f729Sjoerg ModuleScopes.pop_back();
4737330f729Sjoerg
4747330f729Sjoerg // We got to the end of processing a local module. Create an
4757330f729Sjoerg // ImportDecl as we would for an imported module.
4767330f729Sjoerg FileID File = getSourceManager().getFileID(EomLoc);
4777330f729Sjoerg SourceLocation DirectiveLoc;
4787330f729Sjoerg if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
4797330f729Sjoerg // We reached the end of a #included module header. Use the #include loc.
4807330f729Sjoerg assert(File != getSourceManager().getMainFileID() &&
4817330f729Sjoerg "end of submodule in main source file");
4827330f729Sjoerg DirectiveLoc = getSourceManager().getIncludeLoc(File);
4837330f729Sjoerg } else {
4847330f729Sjoerg // We reached an EOM pragma. Use the pragma location.
4857330f729Sjoerg DirectiveLoc = EomLoc;
4867330f729Sjoerg }
4877330f729Sjoerg BuildModuleInclude(DirectiveLoc, Mod);
4887330f729Sjoerg
4897330f729Sjoerg // Any further declarations are in whatever module we returned to.
4907330f729Sjoerg if (getLangOpts().trackLocalOwningModule()) {
4917330f729Sjoerg // The parser guarantees that this is the same context that we entered
4927330f729Sjoerg // the module within.
4937330f729Sjoerg for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
4947330f729Sjoerg cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
4957330f729Sjoerg if (!getCurrentModule())
4967330f729Sjoerg cast<Decl>(DC)->setModuleOwnershipKind(
4977330f729Sjoerg Decl::ModuleOwnershipKind::Unowned);
4987330f729Sjoerg }
4997330f729Sjoerg }
5007330f729Sjoerg }
5017330f729Sjoerg
createImplicitModuleImportForErrorRecovery(SourceLocation Loc,Module * Mod)5027330f729Sjoerg void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
5037330f729Sjoerg Module *Mod) {
5047330f729Sjoerg // Bail if we're not allowed to implicitly import a module here.
5057330f729Sjoerg if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
5067330f729Sjoerg VisibleModules.isVisible(Mod))
5077330f729Sjoerg return;
5087330f729Sjoerg
5097330f729Sjoerg // Create the implicit import declaration.
5107330f729Sjoerg TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
5117330f729Sjoerg ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
5127330f729Sjoerg Loc, Mod, Loc);
5137330f729Sjoerg TU->addDecl(ImportD);
5147330f729Sjoerg Consumer.HandleImplicitImportDecl(ImportD);
5157330f729Sjoerg
5167330f729Sjoerg // Make the module visible.
5177330f729Sjoerg getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
5187330f729Sjoerg VisibleModules.setVisible(Mod, Loc);
5197330f729Sjoerg }
5207330f729Sjoerg
5217330f729Sjoerg /// We have parsed the start of an export declaration, including the '{'
5227330f729Sjoerg /// (if present).
ActOnStartExportDecl(Scope * S,SourceLocation ExportLoc,SourceLocation LBraceLoc)5237330f729Sjoerg Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
5247330f729Sjoerg SourceLocation LBraceLoc) {
5257330f729Sjoerg ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
5267330f729Sjoerg
5277330f729Sjoerg // Set this temporarily so we know the export-declaration was braced.
5287330f729Sjoerg D->setRBraceLoc(LBraceLoc);
5297330f729Sjoerg
5307330f729Sjoerg // C++2a [module.interface]p1:
5317330f729Sjoerg // An export-declaration shall appear only [...] in the purview of a module
5327330f729Sjoerg // interface unit. An export-declaration shall not appear directly or
5337330f729Sjoerg // indirectly within [...] a private-module-fragment.
5347330f729Sjoerg if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
5357330f729Sjoerg Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
5367330f729Sjoerg } else if (!ModuleScopes.back().ModuleInterface) {
5377330f729Sjoerg Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
5387330f729Sjoerg Diag(ModuleScopes.back().BeginLoc,
5397330f729Sjoerg diag::note_not_module_interface_add_export)
5407330f729Sjoerg << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
5417330f729Sjoerg } else if (ModuleScopes.back().Module->Kind ==
5427330f729Sjoerg Module::PrivateModuleFragment) {
5437330f729Sjoerg Diag(ExportLoc, diag::err_export_in_private_module_fragment);
5447330f729Sjoerg Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
5457330f729Sjoerg }
5467330f729Sjoerg
5477330f729Sjoerg for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
5487330f729Sjoerg if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
5497330f729Sjoerg // An export-declaration shall not appear directly or indirectly within
5507330f729Sjoerg // an unnamed namespace [...]
5517330f729Sjoerg if (ND->isAnonymousNamespace()) {
5527330f729Sjoerg Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
5537330f729Sjoerg Diag(ND->getLocation(), diag::note_anonymous_namespace);
5547330f729Sjoerg // Don't diagnose internal-linkage declarations in this region.
5557330f729Sjoerg D->setInvalidDecl();
5567330f729Sjoerg break;
5577330f729Sjoerg }
5587330f729Sjoerg
5597330f729Sjoerg // A declaration is exported if it is [...] a namespace-definition
5607330f729Sjoerg // that contains an exported declaration.
5617330f729Sjoerg //
5627330f729Sjoerg // Defer exporting the namespace until after we leave it, in order to
5637330f729Sjoerg // avoid marking all subsequent declarations in the namespace as exported.
5647330f729Sjoerg if (!DeferredExportedNamespaces.insert(ND).second)
5657330f729Sjoerg break;
5667330f729Sjoerg }
5677330f729Sjoerg }
5687330f729Sjoerg
5697330f729Sjoerg // [...] its declaration or declaration-seq shall not contain an
5707330f729Sjoerg // export-declaration.
5717330f729Sjoerg if (auto *ED = getEnclosingExportDecl(D)) {
5727330f729Sjoerg Diag(ExportLoc, diag::err_export_within_export);
5737330f729Sjoerg if (ED->hasBraces())
5747330f729Sjoerg Diag(ED->getLocation(), diag::note_export);
5757330f729Sjoerg }
5767330f729Sjoerg
5777330f729Sjoerg CurContext->addDecl(D);
5787330f729Sjoerg PushDeclContext(S, D);
5797330f729Sjoerg D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
5807330f729Sjoerg return D;
5817330f729Sjoerg }
5827330f729Sjoerg
5837330f729Sjoerg static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
5847330f729Sjoerg SourceLocation BlockStart);
5857330f729Sjoerg
5867330f729Sjoerg namespace {
5877330f729Sjoerg enum class UnnamedDeclKind {
5887330f729Sjoerg Empty,
5897330f729Sjoerg StaticAssert,
5907330f729Sjoerg Asm,
5917330f729Sjoerg UsingDirective,
5927330f729Sjoerg Context
5937330f729Sjoerg };
5947330f729Sjoerg }
5957330f729Sjoerg
getUnnamedDeclKind(Decl * D)5967330f729Sjoerg static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
5977330f729Sjoerg if (isa<EmptyDecl>(D))
5987330f729Sjoerg return UnnamedDeclKind::Empty;
5997330f729Sjoerg if (isa<StaticAssertDecl>(D))
6007330f729Sjoerg return UnnamedDeclKind::StaticAssert;
6017330f729Sjoerg if (isa<FileScopeAsmDecl>(D))
6027330f729Sjoerg return UnnamedDeclKind::Asm;
6037330f729Sjoerg if (isa<UsingDirectiveDecl>(D))
6047330f729Sjoerg return UnnamedDeclKind::UsingDirective;
6057330f729Sjoerg // Everything else either introduces one or more names or is ill-formed.
6067330f729Sjoerg return llvm::None;
6077330f729Sjoerg }
6087330f729Sjoerg
getUnnamedDeclDiag(UnnamedDeclKind UDK,bool InBlock)6097330f729Sjoerg unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
6107330f729Sjoerg switch (UDK) {
6117330f729Sjoerg case UnnamedDeclKind::Empty:
6127330f729Sjoerg case UnnamedDeclKind::StaticAssert:
6137330f729Sjoerg // Allow empty-declarations and static_asserts in an export block as an
6147330f729Sjoerg // extension.
6157330f729Sjoerg return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
6167330f729Sjoerg
6177330f729Sjoerg case UnnamedDeclKind::UsingDirective:
6187330f729Sjoerg // Allow exporting using-directives as an extension.
6197330f729Sjoerg return diag::ext_export_using_directive;
6207330f729Sjoerg
6217330f729Sjoerg case UnnamedDeclKind::Context:
6227330f729Sjoerg // Allow exporting DeclContexts that transitively contain no declarations
6237330f729Sjoerg // as an extension.
6247330f729Sjoerg return diag::ext_export_no_names;
6257330f729Sjoerg
6267330f729Sjoerg case UnnamedDeclKind::Asm:
6277330f729Sjoerg return diag::err_export_no_name;
6287330f729Sjoerg }
6297330f729Sjoerg llvm_unreachable("unknown kind");
6307330f729Sjoerg }
6317330f729Sjoerg
diagExportedUnnamedDecl(Sema & S,UnnamedDeclKind UDK,Decl * D,SourceLocation BlockStart)6327330f729Sjoerg static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
6337330f729Sjoerg SourceLocation BlockStart) {
6347330f729Sjoerg S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
6357330f729Sjoerg << (unsigned)UDK;
6367330f729Sjoerg if (BlockStart.isValid())
6377330f729Sjoerg S.Diag(BlockStart, diag::note_export);
6387330f729Sjoerg }
6397330f729Sjoerg
6407330f729Sjoerg /// Check that it's valid to export \p D.
checkExportedDecl(Sema & S,Decl * D,SourceLocation BlockStart)6417330f729Sjoerg static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
6427330f729Sjoerg // C++2a [module.interface]p3:
6437330f729Sjoerg // An exported declaration shall declare at least one name
6447330f729Sjoerg if (auto UDK = getUnnamedDeclKind(D))
6457330f729Sjoerg diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
6467330f729Sjoerg
6477330f729Sjoerg // [...] shall not declare a name with internal linkage.
6487330f729Sjoerg if (auto *ND = dyn_cast<NamedDecl>(D)) {
6497330f729Sjoerg // Don't diagnose anonymous union objects; we'll diagnose their members
6507330f729Sjoerg // instead.
6517330f729Sjoerg if (ND->getDeclName() && ND->getFormalLinkage() == InternalLinkage) {
6527330f729Sjoerg S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
6537330f729Sjoerg if (BlockStart.isValid())
6547330f729Sjoerg S.Diag(BlockStart, diag::note_export);
6557330f729Sjoerg }
6567330f729Sjoerg }
6577330f729Sjoerg
6587330f729Sjoerg // C++2a [module.interface]p5:
6597330f729Sjoerg // all entities to which all of the using-declarators ultimately refer
6607330f729Sjoerg // shall have been introduced with a name having external linkage
6617330f729Sjoerg if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
6627330f729Sjoerg NamedDecl *Target = USD->getUnderlyingDecl();
6637330f729Sjoerg if (Target->getFormalLinkage() == InternalLinkage) {
6647330f729Sjoerg S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
6657330f729Sjoerg S.Diag(Target->getLocation(), diag::note_using_decl_target);
6667330f729Sjoerg if (BlockStart.isValid())
6677330f729Sjoerg S.Diag(BlockStart, diag::note_export);
6687330f729Sjoerg }
6697330f729Sjoerg }
6707330f729Sjoerg
6717330f729Sjoerg // Recurse into namespace-scope DeclContexts. (Only namespace-scope
6727330f729Sjoerg // declarations are exported.)
6737330f729Sjoerg if (auto *DC = dyn_cast<DeclContext>(D))
6747330f729Sjoerg if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
6757330f729Sjoerg return checkExportedDeclContext(S, DC, BlockStart);
6767330f729Sjoerg return false;
6777330f729Sjoerg }
6787330f729Sjoerg
6797330f729Sjoerg /// Check that it's valid to export all the declarations in \p DC.
checkExportedDeclContext(Sema & S,DeclContext * DC,SourceLocation BlockStart)6807330f729Sjoerg static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
6817330f729Sjoerg SourceLocation BlockStart) {
6827330f729Sjoerg bool AllUnnamed = true;
6837330f729Sjoerg for (auto *D : DC->decls())
6847330f729Sjoerg AllUnnamed &= checkExportedDecl(S, D, BlockStart);
6857330f729Sjoerg return AllUnnamed;
6867330f729Sjoerg }
6877330f729Sjoerg
6887330f729Sjoerg /// Complete the definition of an export declaration.
ActOnFinishExportDecl(Scope * S,Decl * D,SourceLocation RBraceLoc)6897330f729Sjoerg Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
6907330f729Sjoerg auto *ED = cast<ExportDecl>(D);
6917330f729Sjoerg if (RBraceLoc.isValid())
6927330f729Sjoerg ED->setRBraceLoc(RBraceLoc);
6937330f729Sjoerg
6947330f729Sjoerg PopDeclContext();
6957330f729Sjoerg
6967330f729Sjoerg if (!D->isInvalidDecl()) {
6977330f729Sjoerg SourceLocation BlockStart =
6987330f729Sjoerg ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
6997330f729Sjoerg for (auto *Child : ED->decls()) {
7007330f729Sjoerg if (checkExportedDecl(*this, Child, BlockStart)) {
7017330f729Sjoerg // If a top-level child is a linkage-spec declaration, it might contain
7027330f729Sjoerg // no declarations (transitively), in which case it's ill-formed.
7037330f729Sjoerg diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
7047330f729Sjoerg BlockStart);
7057330f729Sjoerg }
7067330f729Sjoerg }
7077330f729Sjoerg }
7087330f729Sjoerg
7097330f729Sjoerg return D;
7107330f729Sjoerg }
711