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 14 #include "clang/AST/ASTConsumer.h" 15 #include "clang/Lex/HeaderSearch.h" 16 #include "clang/Lex/Preprocessor.h" 17 #include "clang/Sema/SemaInternal.h" 18 19 using namespace clang; 20 using namespace sema; 21 22 static void checkModuleImportContext(Sema &S, Module *M, 23 SourceLocation ImportLoc, DeclContext *DC, 24 bool FromInclude = false) { 25 SourceLocation ExternCLoc; 26 27 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 28 switch (LSD->getLanguage()) { 29 case LinkageSpecDecl::lang_c: 30 if (ExternCLoc.isInvalid()) 31 ExternCLoc = LSD->getBeginLoc(); 32 break; 33 case LinkageSpecDecl::lang_cxx: 34 break; 35 } 36 DC = LSD->getParent(); 37 } 38 39 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 40 DC = DC->getParent(); 41 42 if (!isa<TranslationUnitDecl>(DC)) { 43 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 44 ? diag::ext_module_import_not_at_top_level_noop 45 : diag::err_module_import_not_at_top_level_fatal) 46 << M->getFullModuleName() << DC; 47 S.Diag(cast<Decl>(DC)->getBeginLoc(), 48 diag::note_module_import_not_at_top_level) 49 << DC; 50 } else if (!M->IsExternC && ExternCLoc.isValid()) { 51 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 52 << M->getFullModuleName(); 53 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 54 } 55 } 56 57 Sema::DeclGroupPtrTy 58 Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) { 59 if (!ModuleScopes.empty() && 60 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) { 61 // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after 62 // already implicitly entering the global module fragment. That's OK. 63 assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS && 64 "unexpectedly encountered multiple global module fragment decls"); 65 ModuleScopes.back().BeginLoc = ModuleLoc; 66 return nullptr; 67 } 68 69 // We start in the global module; all those declarations are implicitly 70 // module-private (though they do not have module linkage). 71 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 72 auto *GlobalModule = Map.createGlobalModuleForInterfaceUnit(ModuleLoc); 73 assert(GlobalModule && "module creation should not fail"); 74 75 // Enter the scope of the global module. 76 ModuleScopes.push_back({}); 77 ModuleScopes.back().BeginLoc = ModuleLoc; 78 ModuleScopes.back().Module = GlobalModule; 79 VisibleModules.setVisible(GlobalModule, ModuleLoc); 80 81 // All declarations created from now on are owned by the global module. 82 auto *TU = Context.getTranslationUnitDecl(); 83 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible); 84 TU->setLocalOwningModule(GlobalModule); 85 86 // FIXME: Consider creating an explicit representation of this declaration. 87 return nullptr; 88 } 89 90 Sema::DeclGroupPtrTy 91 Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, 92 ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl) { 93 assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) && 94 "should only have module decl in Modules TS or C++20"); 95 96 // A module implementation unit requires that we are not compiling a module 97 // of any kind. A module interface unit requires that we are not compiling a 98 // module map. 99 switch (getLangOpts().getCompilingModule()) { 100 case LangOptions::CMK_None: 101 // It's OK to compile a module interface as a normal translation unit. 102 break; 103 104 case LangOptions::CMK_ModuleInterface: 105 if (MDK != ModuleDeclKind::Implementation) 106 break; 107 108 // We were asked to compile a module interface unit but this is a module 109 // implementation unit. That indicates the 'export' is missing. 110 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 111 << FixItHint::CreateInsertion(ModuleLoc, "export "); 112 MDK = ModuleDeclKind::Interface; 113 break; 114 115 case LangOptions::CMK_ModuleMap: 116 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 117 return nullptr; 118 119 case LangOptions::CMK_HeaderModule: 120 Diag(ModuleLoc, diag::err_module_decl_in_header_module); 121 return nullptr; 122 } 123 124 assert(ModuleScopes.size() <= 1 && "expected to be at global module scope"); 125 126 // FIXME: Most of this work should be done by the preprocessor rather than 127 // here, in order to support macro import. 128 129 // Only one module-declaration is permitted per source file. 130 if (!ModuleScopes.empty() && 131 ModuleScopes.back().Module->Kind == Module::ModuleInterfaceUnit) { 132 Diag(ModuleLoc, diag::err_module_redeclaration); 133 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 134 diag::note_prev_module_declaration); 135 return nullptr; 136 } 137 138 // Find the global module fragment we're adopting into this module, if any. 139 Module *GlobalModuleFragment = nullptr; 140 if (!ModuleScopes.empty() && 141 ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) 142 GlobalModuleFragment = ModuleScopes.back().Module; 143 144 // In C++20, the module-declaration must be the first declaration if there 145 // is no global module fragment. 146 if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !GlobalModuleFragment) { 147 Diag(ModuleLoc, diag::err_module_decl_not_at_start); 148 SourceLocation BeginLoc = 149 ModuleScopes.empty() 150 ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()) 151 : ModuleScopes.back().BeginLoc; 152 if (BeginLoc.isValid()) { 153 Diag(BeginLoc, diag::note_global_module_introducer_missing) 154 << FixItHint::CreateInsertion(BeginLoc, "module;\n"); 155 } 156 } 157 158 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 159 // modules, the dots here are just another character that can appear in a 160 // module name. 161 std::string ModuleName; 162 for (auto &Piece : Path) { 163 if (!ModuleName.empty()) 164 ModuleName += "."; 165 ModuleName += Piece.first->getName(); 166 } 167 168 // If a module name was explicitly specified on the command line, it must be 169 // correct. 170 if (!getLangOpts().CurrentModule.empty() && 171 getLangOpts().CurrentModule != ModuleName) { 172 Diag(Path.front().second, diag::err_current_module_name_mismatch) 173 << SourceRange(Path.front().second, Path.back().second) 174 << getLangOpts().CurrentModule; 175 return nullptr; 176 } 177 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 178 179 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 180 Module *Mod; 181 182 switch (MDK) { 183 case ModuleDeclKind::Interface: { 184 // We can't have parsed or imported a definition of this module or parsed a 185 // module map defining it already. 186 if (auto *M = Map.findModule(ModuleName)) { 187 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 188 if (M->DefinitionLoc.isValid()) 189 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 190 else if (const auto *FE = M->getASTFile()) 191 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 192 << FE->getName(); 193 Mod = M; 194 break; 195 } 196 197 // Create a Module for the module that we're defining. 198 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 199 GlobalModuleFragment); 200 assert(Mod && "module creation should not fail"); 201 break; 202 } 203 204 case ModuleDeclKind::Implementation: 205 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 206 PP.getIdentifierInfo(ModuleName), Path[0].second); 207 Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc}, 208 Module::AllVisible, 209 /*IsIncludeDirective=*/false); 210 if (!Mod) { 211 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 212 // Create an empty module interface unit for error recovery. 213 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName, 214 GlobalModuleFragment); 215 } 216 break; 217 } 218 219 if (!GlobalModuleFragment) { 220 ModuleScopes.push_back({}); 221 if (getLangOpts().ModulesLocalVisibility) 222 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 223 } 224 225 // Switch from the global module fragment (if any) to the named module. 226 ModuleScopes.back().BeginLoc = StartLoc; 227 ModuleScopes.back().Module = Mod; 228 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 229 VisibleModules.setVisible(Mod, ModuleLoc); 230 231 // From now on, we have an owning module for all declarations we see. 232 // However, those declarations are module-private unless explicitly 233 // exported. 234 auto *TU = Context.getTranslationUnitDecl(); 235 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 236 TU->setLocalOwningModule(Mod); 237 238 // FIXME: Create a ModuleDecl. 239 return nullptr; 240 } 241 242 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 243 SourceLocation ExportLoc, 244 SourceLocation ImportLoc, 245 ModuleIdPath Path) { 246 // Flatten the module path for a Modules TS module name. 247 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc; 248 if (getLangOpts().ModulesTS) { 249 std::string ModuleName; 250 for (auto &Piece : Path) { 251 if (!ModuleName.empty()) 252 ModuleName += "."; 253 ModuleName += Piece.first->getName(); 254 } 255 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second}; 256 Path = ModuleIdPath(ModuleNameLoc); 257 } 258 259 Module *Mod = 260 getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible, 261 /*IsIncludeDirective=*/false); 262 if (!Mod) 263 return true; 264 265 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path); 266 } 267 268 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 269 SourceLocation ExportLoc, 270 SourceLocation ImportLoc, 271 Module *Mod, ModuleIdPath Path) { 272 VisibleModules.setVisible(Mod, ImportLoc); 273 274 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 275 276 // FIXME: we should support importing a submodule within a different submodule 277 // of the same top-level module. Until we do, make it an error rather than 278 // silently ignoring the import. 279 // Import-from-implementation is valid in the Modules TS. FIXME: Should we 280 // warn on a redundant import of the current module? 281 // FIXME: Import of a module from an implementation partition of the same 282 // module is permitted. 283 if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule && 284 (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) { 285 Diag(ImportLoc, getLangOpts().isCompilingModule() 286 ? diag::err_module_self_import 287 : diag::err_module_import_in_implementation) 288 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 289 } 290 291 SmallVector<SourceLocation, 2> IdentifierLocs; 292 Module *ModCheck = Mod; 293 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 294 // If we've run out of module parents, just drop the remaining identifiers. 295 // We need the length to be consistent. 296 if (!ModCheck) 297 break; 298 ModCheck = ModCheck->Parent; 299 300 IdentifierLocs.push_back(Path[I].second); 301 } 302 303 // If this was a header import, pad out with dummy locations. 304 // FIXME: Pass in and use the location of the header-name token in this case. 305 if (Path.empty()) { 306 for (; ModCheck; ModCheck = ModCheck->Parent) { 307 IdentifierLocs.push_back(SourceLocation()); 308 } 309 } 310 311 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 312 Mod, IdentifierLocs); 313 CurContext->addDecl(Import); 314 315 // Sequence initialization of the imported module before that of the current 316 // module, if any. 317 if (!ModuleScopes.empty()) 318 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 319 320 // Re-export the module if needed. 321 if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) { 322 if (ExportLoc.isValid() || Import->isExported()) 323 getCurrentModule()->Exports.emplace_back(Mod, false); 324 } else if (ExportLoc.isValid()) { 325 Diag(ExportLoc, diag::err_export_not_in_module_interface); 326 } 327 328 return Import; 329 } 330 331 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 332 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 333 BuildModuleInclude(DirectiveLoc, Mod); 334 } 335 336 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 337 // Determine whether we're in the #include buffer for a module. The #includes 338 // in that buffer do not qualify as module imports; they're just an 339 // implementation detail of us building the module. 340 // 341 // FIXME: Should we even get ActOnModuleInclude calls for those? 342 bool IsInModuleIncludes = 343 TUKind == TU_Module && 344 getSourceManager().isWrittenInMainFile(DirectiveLoc); 345 346 bool ShouldAddImport = !IsInModuleIncludes; 347 348 // If this module import was due to an inclusion directive, create an 349 // implicit import declaration to capture it in the AST. 350 if (ShouldAddImport) { 351 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 352 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 353 DirectiveLoc, Mod, 354 DirectiveLoc); 355 if (!ModuleScopes.empty()) 356 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 357 TU->addDecl(ImportD); 358 Consumer.HandleImplicitImportDecl(ImportD); 359 } 360 361 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 362 VisibleModules.setVisible(Mod, DirectiveLoc); 363 } 364 365 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 366 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 367 368 ModuleScopes.push_back({}); 369 ModuleScopes.back().Module = Mod; 370 if (getLangOpts().ModulesLocalVisibility) 371 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 372 373 VisibleModules.setVisible(Mod, DirectiveLoc); 374 375 // The enclosing context is now part of this module. 376 // FIXME: Consider creating a child DeclContext to hold the entities 377 // lexically within the module. 378 if (getLangOpts().trackLocalOwningModule()) { 379 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 380 cast<Decl>(DC)->setModuleOwnershipKind( 381 getLangOpts().ModulesLocalVisibility 382 ? Decl::ModuleOwnershipKind::VisibleWhenImported 383 : Decl::ModuleOwnershipKind::Visible); 384 cast<Decl>(DC)->setLocalOwningModule(Mod); 385 } 386 } 387 } 388 389 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 390 if (getLangOpts().ModulesLocalVisibility) { 391 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 392 // Leaving a module hides namespace names, so our visible namespace cache 393 // is now out of date. 394 VisibleNamespaceCache.clear(); 395 } 396 397 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 398 "left the wrong module scope"); 399 ModuleScopes.pop_back(); 400 401 // We got to the end of processing a local module. Create an 402 // ImportDecl as we would for an imported module. 403 FileID File = getSourceManager().getFileID(EomLoc); 404 SourceLocation DirectiveLoc; 405 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 406 // We reached the end of a #included module header. Use the #include loc. 407 assert(File != getSourceManager().getMainFileID() && 408 "end of submodule in main source file"); 409 DirectiveLoc = getSourceManager().getIncludeLoc(File); 410 } else { 411 // We reached an EOM pragma. Use the pragma location. 412 DirectiveLoc = EomLoc; 413 } 414 BuildModuleInclude(DirectiveLoc, Mod); 415 416 // Any further declarations are in whatever module we returned to. 417 if (getLangOpts().trackLocalOwningModule()) { 418 // The parser guarantees that this is the same context that we entered 419 // the module within. 420 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 421 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 422 if (!getCurrentModule()) 423 cast<Decl>(DC)->setModuleOwnershipKind( 424 Decl::ModuleOwnershipKind::Unowned); 425 } 426 } 427 } 428 429 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 430 Module *Mod) { 431 // Bail if we're not allowed to implicitly import a module here. 432 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 433 VisibleModules.isVisible(Mod)) 434 return; 435 436 // Create the implicit import declaration. 437 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 438 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 439 Loc, Mod, Loc); 440 TU->addDecl(ImportD); 441 Consumer.HandleImplicitImportDecl(ImportD); 442 443 // Make the module visible. 444 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 445 VisibleModules.setVisible(Mod, Loc); 446 } 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 454 // C++ Modules TS draft: 455 // An export-declaration shall appear in the purview of a module other than 456 // the global module. 457 if (ModuleScopes.empty() || !ModuleScopes.back().ModuleInterface) 458 Diag(ExportLoc, diag::err_export_not_in_module_interface); 459 460 // An export-declaration [...] shall not contain more than one 461 // export keyword. 462 // 463 // The intent here is that an export-declaration cannot appear within another 464 // export-declaration. 465 if (D->isExported()) 466 Diag(ExportLoc, diag::err_export_within_export); 467 468 CurContext->addDecl(D); 469 PushDeclContext(S, D); 470 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 471 return D; 472 } 473 474 /// Complete the definition of an export declaration. 475 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 476 auto *ED = cast<ExportDecl>(D); 477 if (RBraceLoc.isValid()) 478 ED->setRBraceLoc(RBraceLoc); 479 480 // FIXME: Diagnose export of internal-linkage declaration (including 481 // anonymous namespace). 482 483 PopDeclContext(); 484 return D; 485 } 486