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