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 #include <optional> 19 20 using namespace clang; 21 using namespace sema; 22 23 static void checkModuleImportContext(Sema &S, Module *M, 24 SourceLocation ImportLoc, DeclContext *DC, 25 bool FromInclude = false) { 26 SourceLocation ExternCLoc; 27 28 if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) { 29 switch (LSD->getLanguage()) { 30 case LinkageSpecDecl::lang_c: 31 if (ExternCLoc.isInvalid()) 32 ExternCLoc = LSD->getBeginLoc(); 33 break; 34 case LinkageSpecDecl::lang_cxx: 35 break; 36 } 37 DC = LSD->getParent(); 38 } 39 40 while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC)) 41 DC = DC->getParent(); 42 43 if (!isa<TranslationUnitDecl>(DC)) { 44 S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M)) 45 ? diag::ext_module_import_not_at_top_level_noop 46 : diag::err_module_import_not_at_top_level_fatal) 47 << M->getFullModuleName() << DC; 48 S.Diag(cast<Decl>(DC)->getBeginLoc(), 49 diag::note_module_import_not_at_top_level) 50 << DC; 51 } else if (!M->IsExternC && ExternCLoc.isValid()) { 52 S.Diag(ImportLoc, diag::ext_module_import_in_extern_c) 53 << M->getFullModuleName(); 54 S.Diag(ExternCLoc, diag::note_extern_c_begins_here); 55 } 56 } 57 58 // We represent the primary and partition names as 'Paths' which are sections 59 // of the hierarchical access path for a clang module. However for C++20 60 // the periods in a name are just another character, and we will need to 61 // flatten them into a string. 62 static std::string stringFromPath(ModuleIdPath Path) { 63 std::string Name; 64 if (Path.empty()) 65 return Name; 66 67 for (auto &Piece : Path) { 68 if (!Name.empty()) 69 Name += "."; 70 Name += Piece.first->getName(); 71 } 72 return Name; 73 } 74 75 Sema::DeclGroupPtrTy 76 Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) { 77 // We start in the global module; 78 Module *GlobalModule = 79 PushGlobalModuleFragment(ModuleLoc); 80 81 // All declarations created from now on are owned by the global module. 82 auto *TU = Context.getTranslationUnitDecl(); 83 // [module.global.frag]p2 84 // A global-module-fragment specifies the contents of the global module 85 // fragment for a module unit. The global module fragment can be used to 86 // provide declarations that are attached to the global module and usable 87 // within the module unit. 88 // 89 // So the declations in the global module shouldn't be visible by default. 90 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported); 91 TU->setLocalOwningModule(GlobalModule); 92 93 // FIXME: Consider creating an explicit representation of this declaration. 94 return nullptr; 95 } 96 97 void Sema::HandleStartOfHeaderUnit() { 98 assert(getLangOpts().CPlusPlusModules && 99 "Header units are only valid for C++20 modules"); 100 SourceLocation StartOfTU = 101 SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()); 102 103 StringRef HUName = getLangOpts().CurrentModule; 104 if (HUName.empty()) { 105 HUName = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())->getName(); 106 const_cast<LangOptions &>(getLangOpts()).CurrentModule = HUName.str(); 107 } 108 109 // TODO: Make the C++20 header lookup independent. 110 // When the input is pre-processed source, we need a file ref to the original 111 // file for the header map. 112 auto F = SourceMgr.getFileManager().getOptionalFileRef(HUName); 113 // For the sake of error recovery (if someone has moved the original header 114 // after creating the pre-processed output) fall back to obtaining the file 115 // ref for the input file, which must be present. 116 if (!F) 117 F = SourceMgr.getFileEntryRefForID(SourceMgr.getMainFileID()); 118 assert(F && "failed to find the header unit source?"); 119 Module::Header H{HUName.str(), HUName.str(), *F}; 120 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 121 Module *Mod = Map.createHeaderUnit(StartOfTU, HUName, H); 122 assert(Mod && "module creation should not fail"); 123 ModuleScopes.push_back({}); // No GMF 124 ModuleScopes.back().BeginLoc = StartOfTU; 125 ModuleScopes.back().Module = Mod; 126 ModuleScopes.back().ModuleInterface = true; 127 VisibleModules.setVisible(Mod, StartOfTU); 128 129 // From now on, we have an owning module for all declarations we see. 130 // All of these are implicitly exported. 131 auto *TU = Context.getTranslationUnitDecl(); 132 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible); 133 TU->setLocalOwningModule(Mod); 134 } 135 136 /// Tests whether the given identifier is reserved as a module name and 137 /// diagnoses if it is. Returns true if a diagnostic is emitted and false 138 /// otherwise. 139 static bool DiagReservedModuleName(Sema &S, const IdentifierInfo *II, 140 SourceLocation Loc) { 141 enum { 142 Valid = -1, 143 Invalid = 0, 144 Reserved = 1, 145 } Reason = Valid; 146 147 if (II->isStr("module") || II->isStr("import")) 148 Reason = Invalid; 149 else if (II->isReserved(S.getLangOpts()) != 150 ReservedIdentifierStatus::NotReserved) 151 Reason = Reserved; 152 153 // If the identifier is reserved (not invalid) but is in a system header, 154 // we do not diagnose (because we expect system headers to use reserved 155 // identifiers). 156 if (Reason == Reserved && S.getSourceManager().isInSystemHeader(Loc)) 157 Reason = Valid; 158 159 switch (Reason) { 160 case Valid: 161 return false; 162 case Invalid: 163 return S.Diag(Loc, diag::err_invalid_module_name) << II; 164 case Reserved: 165 return S.Diag(Loc, diag::warn_reserved_module_name) << II; 166 } 167 llvm_unreachable("fell off a fully covered switch"); 168 } 169 170 Sema::DeclGroupPtrTy 171 Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, 172 ModuleDeclKind MDK, ModuleIdPath Path, 173 ModuleIdPath Partition, ModuleImportState &ImportState) { 174 assert(getLangOpts().CPlusPlusModules && 175 "should only have module decl in standard C++ modules"); 176 177 bool IsFirstDecl = ImportState == ModuleImportState::FirstDecl; 178 bool SeenGMF = ImportState == ModuleImportState::GlobalFragment; 179 // If any of the steps here fail, we count that as invalidating C++20 180 // module state; 181 ImportState = ModuleImportState::NotACXX20Module; 182 183 bool IsPartition = !Partition.empty(); 184 if (IsPartition) 185 switch (MDK) { 186 case ModuleDeclKind::Implementation: 187 MDK = ModuleDeclKind::PartitionImplementation; 188 break; 189 case ModuleDeclKind::Interface: 190 MDK = ModuleDeclKind::PartitionInterface; 191 break; 192 default: 193 llvm_unreachable("how did we get a partition type set?"); 194 } 195 196 // A (non-partition) module implementation unit requires that we are not 197 // compiling a module of any kind. A partition implementation emits an 198 // interface (and the AST for the implementation), which will subsequently 199 // be consumed to emit a binary. 200 // A module interface unit requires that we are not compiling a module map. 201 switch (getLangOpts().getCompilingModule()) { 202 case LangOptions::CMK_None: 203 // It's OK to compile a module interface as a normal translation unit. 204 break; 205 206 case LangOptions::CMK_ModuleInterface: 207 if (MDK != ModuleDeclKind::Implementation) 208 break; 209 210 // We were asked to compile a module interface unit but this is a module 211 // implementation unit. 212 Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch) 213 << FixItHint::CreateInsertion(ModuleLoc, "export "); 214 MDK = ModuleDeclKind::Interface; 215 break; 216 217 case LangOptions::CMK_ModuleMap: 218 Diag(ModuleLoc, diag::err_module_decl_in_module_map_module); 219 return nullptr; 220 221 case LangOptions::CMK_HeaderUnit: 222 Diag(ModuleLoc, diag::err_module_decl_in_header_unit); 223 return nullptr; 224 } 225 226 assert(ModuleScopes.size() <= 1 && "expected to be at global module scope"); 227 228 // FIXME: Most of this work should be done by the preprocessor rather than 229 // here, in order to support macro import. 230 231 // Only one module-declaration is permitted per source file. 232 if (isCurrentModulePurview()) { 233 Diag(ModuleLoc, diag::err_module_redeclaration); 234 Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module), 235 diag::note_prev_module_declaration); 236 return nullptr; 237 } 238 239 assert((!getLangOpts().CPlusPlusModules || 240 SeenGMF == (bool)this->TheGlobalModuleFragment) && 241 "mismatched global module state"); 242 243 // In C++20, the module-declaration must be the first declaration if there 244 // is no global module fragment. 245 if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !SeenGMF) { 246 Diag(ModuleLoc, diag::err_module_decl_not_at_start); 247 SourceLocation BeginLoc = 248 ModuleScopes.empty() 249 ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID()) 250 : ModuleScopes.back().BeginLoc; 251 if (BeginLoc.isValid()) { 252 Diag(BeginLoc, diag::note_global_module_introducer_missing) 253 << FixItHint::CreateInsertion(BeginLoc, "module;\n"); 254 } 255 } 256 257 // C++2b [module.unit]p1: ... The identifiers module and import shall not 258 // appear as identifiers in a module-name or module-partition. All 259 // module-names either beginning with an identifier consisting of std 260 // followed by zero or more digits or containing a reserved identifier 261 // ([lex.name]) are reserved and shall not be specified in a 262 // module-declaration; no diagnostic is required. 263 264 // Test the first part of the path to see if it's std[0-9]+ but allow the 265 // name in a system header. 266 StringRef FirstComponentName = Path[0].first->getName(); 267 if (!getSourceManager().isInSystemHeader(Path[0].second) && 268 (FirstComponentName == "std" || 269 (FirstComponentName.startswith("std") && 270 llvm::all_of(FirstComponentName.drop_front(3), &llvm::isDigit)))) { 271 Diag(Path[0].second, diag::warn_reserved_module_name) << Path[0].first; 272 return nullptr; 273 } 274 275 // Then test all of the components in the path to see if any of them are 276 // using another kind of reserved or invalid identifier. 277 for (auto Part : Path) { 278 if (DiagReservedModuleName(*this, Part.first, Part.second)) 279 return nullptr; 280 } 281 282 // Flatten the dots in a module name. Unlike Clang's hierarchical module map 283 // modules, the dots here are just another character that can appear in a 284 // module name. 285 std::string ModuleName = stringFromPath(Path); 286 if (IsPartition) { 287 ModuleName += ":"; 288 ModuleName += stringFromPath(Partition); 289 } 290 // If a module name was explicitly specified on the command line, it must be 291 // correct. 292 if (!getLangOpts().CurrentModule.empty() && 293 getLangOpts().CurrentModule != ModuleName) { 294 Diag(Path.front().second, diag::err_current_module_name_mismatch) 295 << SourceRange(Path.front().second, IsPartition 296 ? Partition.back().second 297 : Path.back().second) 298 << getLangOpts().CurrentModule; 299 return nullptr; 300 } 301 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 302 303 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 304 Module *Mod; // The module we are creating. 305 Module *Interface = nullptr; // The interface for an implementation. 306 switch (MDK) { 307 case ModuleDeclKind::Interface: 308 case ModuleDeclKind::PartitionInterface: { 309 // We can't have parsed or imported a definition of this module or parsed a 310 // module map defining it already. 311 if (auto *M = Map.findModule(ModuleName)) { 312 Diag(Path[0].second, diag::err_module_redefinition) << ModuleName; 313 if (M->DefinitionLoc.isValid()) 314 Diag(M->DefinitionLoc, diag::note_prev_module_definition); 315 else if (OptionalFileEntryRef FE = M->getASTFile()) 316 Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file) 317 << FE->getName(); 318 Mod = M; 319 break; 320 } 321 322 // Create a Module for the module that we're defining. 323 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 324 if (MDK == ModuleDeclKind::PartitionInterface) 325 Mod->Kind = Module::ModulePartitionInterface; 326 assert(Mod && "module creation should not fail"); 327 break; 328 } 329 330 case ModuleDeclKind::Implementation: { 331 // C++20 A module-declaration that contains neither an export- 332 // keyword nor a module-partition implicitly imports the primary 333 // module interface unit of the module as if by a module-import- 334 // declaration. 335 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc( 336 PP.getIdentifierInfo(ModuleName), Path[0].second); 337 338 // The module loader will assume we're trying to import the module that 339 // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'. 340 // Change the value for `LangOpts.CurrentModule` temporarily to make the 341 // module loader work properly. 342 const_cast<LangOptions &>(getLangOpts()).CurrentModule = ""; 343 Interface = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc}, 344 Module::AllVisible, 345 /*IsInclusionDirective=*/false); 346 const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName; 347 348 if (!Interface) { 349 Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName; 350 // Create an empty module interface unit for error recovery. 351 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 352 } else { 353 Mod = Map.createModuleForImplementationUnit(ModuleLoc, ModuleName); 354 } 355 } break; 356 357 case ModuleDeclKind::PartitionImplementation: 358 // Create an interface, but note that it is an implementation 359 // unit. 360 Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName); 361 Mod->Kind = Module::ModulePartitionImplementation; 362 break; 363 } 364 365 if (!this->TheGlobalModuleFragment) { 366 ModuleScopes.push_back({}); 367 if (getLangOpts().ModulesLocalVisibility) 368 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 369 } else { 370 // We're done with the global module fragment now. 371 ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global); 372 } 373 374 // Switch from the global module fragment (if any) to the named module. 375 ModuleScopes.back().BeginLoc = StartLoc; 376 ModuleScopes.back().Module = Mod; 377 ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation; 378 VisibleModules.setVisible(Mod, ModuleLoc); 379 380 // From now on, we have an owning module for all declarations we see. 381 // In C++20 modules, those declaration would be reachable when imported 382 // unless explicitily exported. 383 // Otherwise, those declarations are module-private unless explicitly 384 // exported. 385 auto *TU = Context.getTranslationUnitDecl(); 386 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported); 387 TU->setLocalOwningModule(Mod); 388 389 // We are in the module purview, but before any other (non import) 390 // statements, so imports are allowed. 391 ImportState = ModuleImportState::ImportAllowed; 392 393 getASTContext().setNamedModuleForCodeGen(Mod); 394 395 // We already potentially made an implicit import (in the case of a module 396 // implementation unit importing its interface). Make this module visible 397 // and return the import decl to be added to the current TU. 398 if (Interface) { 399 400 VisibleModules.setVisible(Interface, ModuleLoc); 401 402 // Make the import decl for the interface in the impl module. 403 ImportDecl *Import = ImportDecl::Create(Context, CurContext, ModuleLoc, 404 Interface, Path[0].second); 405 CurContext->addDecl(Import); 406 407 // Sequence initialization of the imported module before that of the current 408 // module, if any. 409 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 410 Mod->Imports.insert(Interface); // As if we imported it. 411 // Also save this as a shortcut to checking for decls in the interface 412 ThePrimaryInterface = Interface; 413 // If we made an implicit import of the module interface, then return the 414 // imported module decl. 415 return ConvertDeclToDeclGroup(Import); 416 } 417 418 return nullptr; 419 } 420 421 Sema::DeclGroupPtrTy 422 Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, 423 SourceLocation PrivateLoc) { 424 // C++20 [basic.link]/2: 425 // A private-module-fragment shall appear only in a primary module 426 // interface unit. 427 switch (ModuleScopes.empty() ? Module::ExplicitGlobalModuleFragment 428 : ModuleScopes.back().Module->Kind) { 429 case Module::ModuleMapModule: 430 case Module::ExplicitGlobalModuleFragment: 431 case Module::ImplicitGlobalModuleFragment: 432 case Module::ModulePartitionImplementation: 433 case Module::ModulePartitionInterface: 434 case Module::ModuleHeaderUnit: 435 Diag(PrivateLoc, diag::err_private_module_fragment_not_module); 436 return nullptr; 437 438 case Module::PrivateModuleFragment: 439 Diag(PrivateLoc, diag::err_private_module_fragment_redefined); 440 Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition); 441 return nullptr; 442 443 case Module::ModuleImplementationUnit: 444 Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface); 445 Diag(ModuleScopes.back().BeginLoc, 446 diag::note_not_module_interface_add_export) 447 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export "); 448 return nullptr; 449 450 case Module::ModuleInterfaceUnit: 451 break; 452 } 453 454 // FIXME: Check that this translation unit does not import any partitions; 455 // such imports would violate [basic.link]/2's "shall be the only module unit" 456 // restriction. 457 458 // We've finished the public fragment of the translation unit. 459 ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal); 460 461 auto &Map = PP.getHeaderSearchInfo().getModuleMap(); 462 Module *PrivateModuleFragment = 463 Map.createPrivateModuleFragmentForInterfaceUnit( 464 ModuleScopes.back().Module, PrivateLoc); 465 assert(PrivateModuleFragment && "module creation should not fail"); 466 467 // Enter the scope of the private module fragment. 468 ModuleScopes.push_back({}); 469 ModuleScopes.back().BeginLoc = ModuleLoc; 470 ModuleScopes.back().Module = PrivateModuleFragment; 471 ModuleScopes.back().ModuleInterface = true; 472 VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc); 473 474 // All declarations created from now on are scoped to the private module 475 // fragment (and are neither visible nor reachable in importers of the module 476 // interface). 477 auto *TU = Context.getTranslationUnitDecl(); 478 TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate); 479 TU->setLocalOwningModule(PrivateModuleFragment); 480 481 // FIXME: Consider creating an explicit representation of this declaration. 482 return nullptr; 483 } 484 485 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 486 SourceLocation ExportLoc, 487 SourceLocation ImportLoc, ModuleIdPath Path, 488 bool IsPartition) { 489 assert((!IsPartition || getLangOpts().CPlusPlusModules) && 490 "partition seen in non-C++20 code?"); 491 492 // For a C++20 module name, flatten into a single identifier with the source 493 // location of the first component. 494 std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc; 495 496 std::string ModuleName; 497 if (IsPartition) { 498 // We already checked that we are in a module purview in the parser. 499 assert(!ModuleScopes.empty() && "in a module purview, but no module?"); 500 Module *NamedMod = ModuleScopes.back().Module; 501 // If we are importing into a partition, find the owning named module, 502 // otherwise, the name of the importing named module. 503 ModuleName = NamedMod->getPrimaryModuleInterfaceName().str(); 504 ModuleName += ":"; 505 ModuleName += stringFromPath(Path); 506 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second}; 507 Path = ModuleIdPath(ModuleNameLoc); 508 } else if (getLangOpts().CPlusPlusModules) { 509 ModuleName = stringFromPath(Path); 510 ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second}; 511 Path = ModuleIdPath(ModuleNameLoc); 512 } 513 514 // Diagnose self-import before attempting a load. 515 // [module.import]/9 516 // A module implementation unit of a module M that is not a module partition 517 // shall not contain a module-import-declaration nominating M. 518 // (for an implementation, the module interface is imported implicitly, 519 // but that's handled in the module decl code). 520 521 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview() && 522 getCurrentModule()->Name == ModuleName) { 523 Diag(ImportLoc, diag::err_module_self_import_cxx20) 524 << ModuleName << !ModuleScopes.back().ModuleInterface; 525 return true; 526 } 527 528 Module *Mod = getModuleLoader().loadModule( 529 ImportLoc, Path, Module::AllVisible, /*IsInclusionDirective=*/false); 530 if (!Mod) 531 return true; 532 533 return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path); 534 } 535 536 /// Determine whether \p D is lexically within an export-declaration. 537 static const ExportDecl *getEnclosingExportDecl(const Decl *D) { 538 for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent()) 539 if (auto *ED = dyn_cast<ExportDecl>(DC)) 540 return ED; 541 return nullptr; 542 } 543 544 DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc, 545 SourceLocation ExportLoc, 546 SourceLocation ImportLoc, Module *Mod, 547 ModuleIdPath Path) { 548 VisibleModules.setVisible(Mod, ImportLoc); 549 550 checkModuleImportContext(*this, Mod, ImportLoc, CurContext); 551 552 // FIXME: we should support importing a submodule within a different submodule 553 // of the same top-level module. Until we do, make it an error rather than 554 // silently ignoring the import. 555 // FIXME: Should we warn on a redundant import of the current module? 556 if (Mod->isForBuilding(getLangOpts())) { 557 Diag(ImportLoc, getLangOpts().isCompilingModule() 558 ? diag::err_module_self_import 559 : diag::err_module_import_in_implementation) 560 << Mod->getFullModuleName() << getLangOpts().CurrentModule; 561 } 562 563 SmallVector<SourceLocation, 2> IdentifierLocs; 564 565 if (Path.empty()) { 566 // If this was a header import, pad out with dummy locations. 567 // FIXME: Pass in and use the location of the header-name token in this 568 // case. 569 for (Module *ModCheck = Mod; ModCheck; ModCheck = ModCheck->Parent) 570 IdentifierLocs.push_back(SourceLocation()); 571 } else if (getLangOpts().CPlusPlusModules && !Mod->Parent) { 572 // A single identifier for the whole name. 573 IdentifierLocs.push_back(Path[0].second); 574 } else { 575 Module *ModCheck = Mod; 576 for (unsigned I = 0, N = Path.size(); I != N; ++I) { 577 // If we've run out of module parents, just drop the remaining 578 // identifiers. We need the length to be consistent. 579 if (!ModCheck) 580 break; 581 ModCheck = ModCheck->Parent; 582 583 IdentifierLocs.push_back(Path[I].second); 584 } 585 } 586 587 ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc, 588 Mod, IdentifierLocs); 589 CurContext->addDecl(Import); 590 591 // Sequence initialization of the imported module before that of the current 592 // module, if any. 593 if (!ModuleScopes.empty()) 594 Context.addModuleInitializer(ModuleScopes.back().Module, Import); 595 596 // A module (partition) implementation unit shall not be exported. 597 if (getLangOpts().CPlusPlusModules && ExportLoc.isValid() && 598 Mod->Kind == Module::ModuleKind::ModulePartitionImplementation) { 599 Diag(ExportLoc, diag::err_export_partition_impl) 600 << SourceRange(ExportLoc, Path.back().second); 601 } else if (!ModuleScopes.empty() && 602 (ModuleScopes.back().ModuleInterface || 603 (getLangOpts().CPlusPlusModules && 604 ModuleScopes.back().Module->isGlobalModule()))) { 605 // Re-export the module if the imported module is exported. 606 // Note that we don't need to add re-exported module to Imports field 607 // since `Exports` implies the module is imported already. 608 if (ExportLoc.isValid() || getEnclosingExportDecl(Import)) 609 getCurrentModule()->Exports.emplace_back(Mod, false); 610 else 611 getCurrentModule()->Imports.insert(Mod); 612 } else if (ExportLoc.isValid()) { 613 // [module.interface]p1: 614 // An export-declaration shall inhabit a namespace scope and appear in the 615 // purview of a module interface unit. 616 Diag(ExportLoc, diag::err_export_not_in_module_interface); 617 } 618 619 return Import; 620 } 621 622 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 623 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 624 BuildModuleInclude(DirectiveLoc, Mod); 625 } 626 627 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) { 628 // Determine whether we're in the #include buffer for a module. The #includes 629 // in that buffer do not qualify as module imports; they're just an 630 // implementation detail of us building the module. 631 // 632 // FIXME: Should we even get ActOnModuleInclude calls for those? 633 bool IsInModuleIncludes = 634 TUKind == TU_Module && 635 getSourceManager().isWrittenInMainFile(DirectiveLoc); 636 637 bool ShouldAddImport = !IsInModuleIncludes; 638 639 // If this module import was due to an inclusion directive, create an 640 // implicit import declaration to capture it in the AST. 641 if (ShouldAddImport) { 642 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 643 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 644 DirectiveLoc, Mod, 645 DirectiveLoc); 646 if (!ModuleScopes.empty()) 647 Context.addModuleInitializer(ModuleScopes.back().Module, ImportD); 648 TU->addDecl(ImportD); 649 Consumer.HandleImplicitImportDecl(ImportD); 650 } 651 652 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc); 653 VisibleModules.setVisible(Mod, DirectiveLoc); 654 655 if (getLangOpts().isCompilingModule()) { 656 Module *ThisModule = PP.getHeaderSearchInfo().lookupModule( 657 getLangOpts().CurrentModule, DirectiveLoc, false, false); 658 (void)ThisModule; 659 assert(ThisModule && "was expecting a module if building one"); 660 } 661 } 662 663 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) { 664 checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true); 665 666 ModuleScopes.push_back({}); 667 ModuleScopes.back().Module = Mod; 668 if (getLangOpts().ModulesLocalVisibility) 669 ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules); 670 671 VisibleModules.setVisible(Mod, DirectiveLoc); 672 673 // The enclosing context is now part of this module. 674 // FIXME: Consider creating a child DeclContext to hold the entities 675 // lexically within the module. 676 if (getLangOpts().trackLocalOwningModule()) { 677 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 678 cast<Decl>(DC)->setModuleOwnershipKind( 679 getLangOpts().ModulesLocalVisibility 680 ? Decl::ModuleOwnershipKind::VisibleWhenImported 681 : Decl::ModuleOwnershipKind::Visible); 682 cast<Decl>(DC)->setLocalOwningModule(Mod); 683 } 684 } 685 } 686 687 void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) { 688 if (getLangOpts().ModulesLocalVisibility) { 689 VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules); 690 // Leaving a module hides namespace names, so our visible namespace cache 691 // is now out of date. 692 VisibleNamespaceCache.clear(); 693 } 694 695 assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod && 696 "left the wrong module scope"); 697 ModuleScopes.pop_back(); 698 699 // We got to the end of processing a local module. Create an 700 // ImportDecl as we would for an imported module. 701 FileID File = getSourceManager().getFileID(EomLoc); 702 SourceLocation DirectiveLoc; 703 if (EomLoc == getSourceManager().getLocForEndOfFile(File)) { 704 // We reached the end of a #included module header. Use the #include loc. 705 assert(File != getSourceManager().getMainFileID() && 706 "end of submodule in main source file"); 707 DirectiveLoc = getSourceManager().getIncludeLoc(File); 708 } else { 709 // We reached an EOM pragma. Use the pragma location. 710 DirectiveLoc = EomLoc; 711 } 712 BuildModuleInclude(DirectiveLoc, Mod); 713 714 // Any further declarations are in whatever module we returned to. 715 if (getLangOpts().trackLocalOwningModule()) { 716 // The parser guarantees that this is the same context that we entered 717 // the module within. 718 for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) { 719 cast<Decl>(DC)->setLocalOwningModule(getCurrentModule()); 720 if (!getCurrentModule()) 721 cast<Decl>(DC)->setModuleOwnershipKind( 722 Decl::ModuleOwnershipKind::Unowned); 723 } 724 } 725 } 726 727 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc, 728 Module *Mod) { 729 // Bail if we're not allowed to implicitly import a module here. 730 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery || 731 VisibleModules.isVisible(Mod)) 732 return; 733 734 // Create the implicit import declaration. 735 TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl(); 736 ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU, 737 Loc, Mod, Loc); 738 TU->addDecl(ImportD); 739 Consumer.HandleImplicitImportDecl(ImportD); 740 741 // Make the module visible. 742 getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc); 743 VisibleModules.setVisible(Mod, Loc); 744 } 745 746 /// We have parsed the start of an export declaration, including the '{' 747 /// (if present). 748 Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, 749 SourceLocation LBraceLoc) { 750 ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc); 751 752 // Set this temporarily so we know the export-declaration was braced. 753 D->setRBraceLoc(LBraceLoc); 754 755 CurContext->addDecl(D); 756 PushDeclContext(S, D); 757 758 // C++2a [module.interface]p1: 759 // An export-declaration shall appear only [...] in the purview of a module 760 // interface unit. An export-declaration shall not appear directly or 761 // indirectly within [...] a private-module-fragment. 762 if (!isCurrentModulePurview()) { 763 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0; 764 D->setInvalidDecl(); 765 return D; 766 } else if (!ModuleScopes.back().ModuleInterface) { 767 Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1; 768 Diag(ModuleScopes.back().BeginLoc, 769 diag::note_not_module_interface_add_export) 770 << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export "); 771 D->setInvalidDecl(); 772 return D; 773 } else if (ModuleScopes.back().Module->Kind == 774 Module::PrivateModuleFragment) { 775 Diag(ExportLoc, diag::err_export_in_private_module_fragment); 776 Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment); 777 D->setInvalidDecl(); 778 return D; 779 } 780 781 for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) { 782 if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) { 783 // An export-declaration shall not appear directly or indirectly within 784 // an unnamed namespace [...] 785 if (ND->isAnonymousNamespace()) { 786 Diag(ExportLoc, diag::err_export_within_anonymous_namespace); 787 Diag(ND->getLocation(), diag::note_anonymous_namespace); 788 // Don't diagnose internal-linkage declarations in this region. 789 D->setInvalidDecl(); 790 return D; 791 } 792 793 // A declaration is exported if it is [...] a namespace-definition 794 // that contains an exported declaration. 795 // 796 // Defer exporting the namespace until after we leave it, in order to 797 // avoid marking all subsequent declarations in the namespace as exported. 798 if (!DeferredExportedNamespaces.insert(ND).second) 799 break; 800 } 801 } 802 803 // [...] its declaration or declaration-seq shall not contain an 804 // export-declaration. 805 if (auto *ED = getEnclosingExportDecl(D)) { 806 Diag(ExportLoc, diag::err_export_within_export); 807 if (ED->hasBraces()) 808 Diag(ED->getLocation(), diag::note_export); 809 D->setInvalidDecl(); 810 return D; 811 } 812 813 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported); 814 return D; 815 } 816 817 static bool checkExportedDeclContext(Sema &S, DeclContext *DC, 818 SourceLocation BlockStart); 819 820 namespace { 821 enum class UnnamedDeclKind { 822 Empty, 823 StaticAssert, 824 Asm, 825 UsingDirective, 826 Namespace, 827 Context 828 }; 829 } 830 831 static std::optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) { 832 if (isa<EmptyDecl>(D)) 833 return UnnamedDeclKind::Empty; 834 if (isa<StaticAssertDecl>(D)) 835 return UnnamedDeclKind::StaticAssert; 836 if (isa<FileScopeAsmDecl>(D)) 837 return UnnamedDeclKind::Asm; 838 if (isa<UsingDirectiveDecl>(D)) 839 return UnnamedDeclKind::UsingDirective; 840 // Everything else either introduces one or more names or is ill-formed. 841 return std::nullopt; 842 } 843 844 unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) { 845 switch (UDK) { 846 case UnnamedDeclKind::Empty: 847 case UnnamedDeclKind::StaticAssert: 848 // Allow empty-declarations and static_asserts in an export block as an 849 // extension. 850 return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name; 851 852 case UnnamedDeclKind::UsingDirective: 853 // Allow exporting using-directives as an extension. 854 return diag::ext_export_using_directive; 855 856 case UnnamedDeclKind::Namespace: 857 // Anonymous namespace with no content. 858 return diag::introduces_no_names; 859 860 case UnnamedDeclKind::Context: 861 // Allow exporting DeclContexts that transitively contain no declarations 862 // as an extension. 863 return diag::ext_export_no_names; 864 865 case UnnamedDeclKind::Asm: 866 return diag::err_export_no_name; 867 } 868 llvm_unreachable("unknown kind"); 869 } 870 871 static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D, 872 SourceLocation BlockStart) { 873 S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid())) 874 << (unsigned)UDK; 875 if (BlockStart.isValid()) 876 S.Diag(BlockStart, diag::note_export); 877 } 878 879 /// Check that it's valid to export \p D. 880 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) { 881 // C++2a [module.interface]p3: 882 // An exported declaration shall declare at least one name 883 if (auto UDK = getUnnamedDeclKind(D)) 884 diagExportedUnnamedDecl(S, *UDK, D, BlockStart); 885 886 // [...] shall not declare a name with internal linkage. 887 bool HasName = false; 888 if (auto *ND = dyn_cast<NamedDecl>(D)) { 889 // Don't diagnose anonymous union objects; we'll diagnose their members 890 // instead. 891 HasName = (bool)ND->getDeclName(); 892 if (HasName && ND->getFormalLinkage() == InternalLinkage) { 893 S.Diag(ND->getLocation(), diag::err_export_internal) << ND; 894 if (BlockStart.isValid()) 895 S.Diag(BlockStart, diag::note_export); 896 } 897 } 898 899 // C++2a [module.interface]p5: 900 // all entities to which all of the using-declarators ultimately refer 901 // shall have been introduced with a name having external linkage 902 if (auto *USD = dyn_cast<UsingShadowDecl>(D)) { 903 NamedDecl *Target = USD->getUnderlyingDecl(); 904 Linkage Lk = Target->getFormalLinkage(); 905 if (Lk == InternalLinkage || Lk == ModuleLinkage) { 906 S.Diag(USD->getLocation(), diag::err_export_using_internal) 907 << (Lk == InternalLinkage ? 0 : 1) << Target; 908 S.Diag(Target->getLocation(), diag::note_using_decl_target); 909 if (BlockStart.isValid()) 910 S.Diag(BlockStart, diag::note_export); 911 } 912 } 913 914 // Recurse into namespace-scope DeclContexts. (Only namespace-scope 915 // declarations are exported.). 916 if (auto *DC = dyn_cast<DeclContext>(D)) { 917 if (isa<NamespaceDecl>(D) && DC->decls().empty()) { 918 if (!HasName) 919 // We don't allow an empty anonymous namespace (we don't allow decls 920 // in them either, but that's handled in the recursion). 921 diagExportedUnnamedDecl(S, UnnamedDeclKind::Namespace, D, BlockStart); 922 // We allow an empty named namespace decl. 923 } else if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D)) 924 return checkExportedDeclContext(S, DC, BlockStart); 925 } 926 return false; 927 } 928 929 /// Check that it's valid to export all the declarations in \p DC. 930 static bool checkExportedDeclContext(Sema &S, DeclContext *DC, 931 SourceLocation BlockStart) { 932 bool AllUnnamed = true; 933 for (auto *D : DC->decls()) 934 AllUnnamed &= checkExportedDecl(S, D, BlockStart); 935 return AllUnnamed; 936 } 937 938 /// Complete the definition of an export declaration. 939 Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) { 940 auto *ED = cast<ExportDecl>(D); 941 if (RBraceLoc.isValid()) 942 ED->setRBraceLoc(RBraceLoc); 943 944 PopDeclContext(); 945 946 if (!D->isInvalidDecl()) { 947 SourceLocation BlockStart = 948 ED->hasBraces() ? ED->getBeginLoc() : SourceLocation(); 949 for (auto *Child : ED->decls()) { 950 if (checkExportedDecl(*this, Child, BlockStart)) { 951 // If a top-level child is a linkage-spec declaration, it might contain 952 // no declarations (transitively), in which case it's ill-formed. 953 diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child, 954 BlockStart); 955 } 956 if (auto *FD = dyn_cast<FunctionDecl>(Child)) { 957 // [dcl.inline]/7 958 // If an inline function or variable that is attached to a named module 959 // is declared in a definition domain, it shall be defined in that 960 // domain. 961 // So, if the current declaration does not have a definition, we must 962 // check at the end of the TU (or when the PMF starts) to see that we 963 // have a definition at that point. 964 if (FD->isInlineSpecified() && !FD->isDefined()) 965 PendingInlineFuncDecls.insert(FD); 966 } 967 } 968 } 969 970 return D; 971 } 972 973 Module *Sema::PushGlobalModuleFragment(SourceLocation BeginLoc) { 974 // We shouldn't create new global module fragment if there is already 975 // one. 976 if (!TheGlobalModuleFragment) { 977 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap(); 978 TheGlobalModuleFragment = Map.createGlobalModuleFragmentForModuleUnit( 979 BeginLoc, getCurrentModule()); 980 } 981 982 assert(TheGlobalModuleFragment && "module creation should not fail"); 983 984 // Enter the scope of the global module. 985 ModuleScopes.push_back({BeginLoc, TheGlobalModuleFragment, 986 /*ModuleInterface=*/false, 987 /*OuterVisibleModules=*/{}}); 988 VisibleModules.setVisible(TheGlobalModuleFragment, BeginLoc); 989 990 return TheGlobalModuleFragment; 991 } 992 993 void Sema::PopGlobalModuleFragment() { 994 assert(!ModuleScopes.empty() && 995 getCurrentModule()->isExplicitGlobalModule() && 996 "left the wrong module scope, which is not global module fragment"); 997 ModuleScopes.pop_back(); 998 } 999 1000 Module *Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc, 1001 bool IsExported) { 1002 Module **M = IsExported ? &TheExportedImplicitGlobalModuleFragment 1003 : &TheImplicitGlobalModuleFragment; 1004 if (!*M) { 1005 ModuleMap &Map = PP.getHeaderSearchInfo().getModuleMap(); 1006 *M = Map.createImplicitGlobalModuleFragmentForModuleUnit( 1007 BeginLoc, IsExported, getCurrentModule()); 1008 } 1009 assert(*M && "module creation should not fail"); 1010 1011 // Enter the scope of the global module. 1012 ModuleScopes.push_back({BeginLoc, *M, 1013 /*ModuleInterface=*/false, 1014 /*OuterVisibleModules=*/{}}); 1015 VisibleModules.setVisible(*M, BeginLoc); 1016 return *M; 1017 } 1018 1019 void Sema::PopImplicitGlobalModuleFragment() { 1020 assert(!ModuleScopes.empty() && 1021 getCurrentModule()->isImplicitGlobalModule() && 1022 "left the wrong module scope, which is not global module fragment"); 1023 ModuleScopes.pop_back(); 1024 } 1025 1026 bool Sema::isModuleUnitOfCurrentTU(const Module *M) const { 1027 assert(M); 1028 1029 Module *CurrentModuleUnit = getCurrentModule(); 1030 1031 // If we are not in a module currently, M must not be the module unit of 1032 // current TU. 1033 if (!CurrentModuleUnit) 1034 return false; 1035 1036 return M->isSubModuleOf(CurrentModuleUnit->getTopLevelModule()); 1037 } 1038