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