1 //===--- SemaModule.cpp - Semantic Analysis for Modules -------------------===//
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
7 //===----------------------------------------------------------------------===//
9 // This file implements semantic analysis for modules (C++ modules syntax,
10 // Objective-C modules syntax, and Clang header modules).
12 //===----------------------------------------------------------------------===//
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"
21 using namespace clang
;
24 static void checkModuleImportContext(Sema
&S
, Module
*M
,
25 SourceLocation ImportLoc
, DeclContext
*DC
,
26 bool FromInclude
= false) {
27 SourceLocation ExternCLoc
;
29 if (auto *LSD
= dyn_cast
<LinkageSpecDecl
>(DC
)) {
30 switch (LSD
->getLanguage()) {
31 case LinkageSpecLanguageIDs::C
:
32 if (ExternCLoc
.isInvalid())
33 ExternCLoc
= LSD
->getBeginLoc();
35 case LinkageSpecLanguageIDs::CXX
:
38 DC
= LSD
->getParent();
41 while (isa
<LinkageSpecDecl
>(DC
) || isa
<ExportDecl
>(DC
))
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
)
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
);
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
) {
68 for (auto &Piece
: Path
) {
71 Name
+= Piece
.first
->getName();
77 Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc
) {
78 // We start in the global module;
79 Module
*GlobalModule
=
80 PushGlobalModuleFragment(ModuleLoc
);
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.
90 // So the declations in the global module shouldn't be visible by default.
91 TU
->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported
);
92 TU
->setLocalOwningModule(GlobalModule
);
94 // FIXME: Consider creating an explicit representation of this declaration.
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());
104 StringRef HUName
= getLangOpts().CurrentModule
;
105 if (HUName
.empty()) {
107 SourceMgr
.getFileEntryRefForID(SourceMgr
.getMainFileID())->getName();
108 const_cast<LangOptions
&>(getLangOpts()).CurrentModule
= HUName
.str();
111 // TODO: Make the C++20 header lookup independent.
112 // When the input is pre-processed source, we need a file ref to the original
113 // file for the header map.
114 auto F
= SourceMgr
.getFileManager().getOptionalFileRef(HUName
);
115 // For the sake of error recovery (if someone has moved the original header
116 // after creating the pre-processed output) fall back to obtaining the file
117 // ref for the input file, which must be present.
119 F
= SourceMgr
.getFileEntryRefForID(SourceMgr
.getMainFileID());
120 assert(F
&& "failed to find the header unit source?");
121 Module::Header H
{HUName
.str(), HUName
.str(), *F
};
122 auto &Map
= PP
.getHeaderSearchInfo().getModuleMap();
123 Module
*Mod
= Map
.createHeaderUnit(StartOfTU
, HUName
, H
);
124 assert(Mod
&& "module creation should not fail");
125 ModuleScopes
.push_back({}); // No GMF
126 ModuleScopes
.back().BeginLoc
= StartOfTU
;
127 ModuleScopes
.back().Module
= Mod
;
128 ModuleScopes
.back().ModuleInterface
= true;
129 VisibleModules
.setVisible(Mod
, StartOfTU
);
131 // From now on, we have an owning module for all declarations we see.
132 // All of these are implicitly exported.
133 auto *TU
= Context
.getTranslationUnitDecl();
134 TU
->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible
);
135 TU
->setLocalOwningModule(Mod
);
138 /// Tests whether the given identifier is reserved as a module name and
139 /// diagnoses if it is. Returns true if a diagnostic is emitted and false
141 static bool DiagReservedModuleName(Sema
&S
, const IdentifierInfo
*II
,
142 SourceLocation Loc
) {
149 if (II
->isStr("module") || II
->isStr("import"))
151 else if (II
->isReserved(S
.getLangOpts()) !=
152 ReservedIdentifierStatus::NotReserved
)
155 // If the identifier is reserved (not invalid) but is in a system header,
156 // we do not diagnose (because we expect system headers to use reserved
158 if (Reason
== Reserved
&& S
.getSourceManager().isInSystemHeader(Loc
))
165 return S
.Diag(Loc
, diag::err_invalid_module_name
) << II
;
167 S
.Diag(Loc
, diag::warn_reserved_module_name
) << II
;
170 llvm_unreachable("fell off a fully covered switch");
174 Sema::ActOnModuleDecl(SourceLocation StartLoc
, SourceLocation ModuleLoc
,
175 ModuleDeclKind MDK
, ModuleIdPath Path
,
176 ModuleIdPath Partition
, ModuleImportState
&ImportState
) {
177 assert(getLangOpts().CPlusPlusModules
&&
178 "should only have module decl in standard C++ modules");
180 bool IsFirstDecl
= ImportState
== ModuleImportState::FirstDecl
;
181 bool SeenGMF
= ImportState
== ModuleImportState::GlobalFragment
;
182 // If any of the steps here fail, we count that as invalidating C++20
184 ImportState
= ModuleImportState::NotACXX20Module
;
186 bool IsPartition
= !Partition
.empty();
189 case ModuleDeclKind::Implementation
:
190 MDK
= ModuleDeclKind::PartitionImplementation
;
192 case ModuleDeclKind::Interface
:
193 MDK
= ModuleDeclKind::PartitionInterface
;
196 llvm_unreachable("how did we get a partition type set?");
199 // A (non-partition) module implementation unit requires that we are not
200 // compiling a module of any kind. A partition implementation emits an
201 // interface (and the AST for the implementation), which will subsequently
202 // be consumed to emit a binary.
203 // A module interface unit requires that we are not compiling a module map.
204 switch (getLangOpts().getCompilingModule()) {
205 case LangOptions::CMK_None
:
206 // It's OK to compile a module interface as a normal translation unit.
209 case LangOptions::CMK_ModuleInterface
:
210 if (MDK
!= ModuleDeclKind::Implementation
)
213 // We were asked to compile a module interface unit but this is a module
214 // implementation unit.
215 Diag(ModuleLoc
, diag::err_module_interface_implementation_mismatch
)
216 << FixItHint::CreateInsertion(ModuleLoc
, "export ");
217 MDK
= ModuleDeclKind::Interface
;
220 case LangOptions::CMK_ModuleMap
:
221 Diag(ModuleLoc
, diag::err_module_decl_in_module_map_module
);
224 case LangOptions::CMK_HeaderUnit
:
225 Diag(ModuleLoc
, diag::err_module_decl_in_header_unit
);
229 assert(ModuleScopes
.size() <= 1 && "expected to be at global module scope");
231 // FIXME: Most of this work should be done by the preprocessor rather than
232 // here, in order to support macro import.
234 // Only one module-declaration is permitted per source file.
235 if (isCurrentModulePurview()) {
236 Diag(ModuleLoc
, diag::err_module_redeclaration
);
237 Diag(VisibleModules
.getImportLoc(ModuleScopes
.back().Module
),
238 diag::note_prev_module_declaration
);
242 assert((!getLangOpts().CPlusPlusModules
||
243 SeenGMF
== (bool)this->TheGlobalModuleFragment
) &&
244 "mismatched global module state");
246 // In C++20, the module-declaration must be the first declaration if there
247 // is no global module fragment.
248 if (getLangOpts().CPlusPlusModules
&& !IsFirstDecl
&& !SeenGMF
) {
249 Diag(ModuleLoc
, diag::err_module_decl_not_at_start
);
250 SourceLocation BeginLoc
=
252 ? SourceMgr
.getLocForStartOfFile(SourceMgr
.getMainFileID())
253 : ModuleScopes
.back().BeginLoc
;
254 if (BeginLoc
.isValid()) {
255 Diag(BeginLoc
, diag::note_global_module_introducer_missing
)
256 << FixItHint::CreateInsertion(BeginLoc
, "module;\n");
260 // C++23 [module.unit]p1: ... The identifiers module and import shall not
261 // appear as identifiers in a module-name or module-partition. All
262 // module-names either beginning with an identifier consisting of std
263 // followed by zero or more digits or containing a reserved identifier
264 // ([lex.name]) are reserved and shall not be specified in a
265 // module-declaration; no diagnostic is required.
267 // Test the first part of the path to see if it's std[0-9]+ but allow the
268 // name in a system header.
269 StringRef FirstComponentName
= Path
[0].first
->getName();
270 if (!getSourceManager().isInSystemHeader(Path
[0].second
) &&
271 (FirstComponentName
== "std" ||
272 (FirstComponentName
.startswith("std") &&
273 llvm::all_of(FirstComponentName
.drop_front(3), &llvm::isDigit
))))
274 Diag(Path
[0].second
, diag::warn_reserved_module_name
) << Path
[0].first
;
276 // Then test all of the components in the path to see if any of them are
277 // using another kind of reserved or invalid identifier.
278 for (auto Part
: Path
) {
279 if (DiagReservedModuleName(*this, Part
.first
, Part
.second
))
283 // Flatten the dots in a module name. Unlike Clang's hierarchical module map
284 // modules, the dots here are just another character that can appear in a
286 std::string ModuleName
= stringFromPath(Path
);
289 ModuleName
+= stringFromPath(Partition
);
291 // If a module name was explicitly specified on the command line, it must be
293 if (!getLangOpts().CurrentModule
.empty() &&
294 getLangOpts().CurrentModule
!= ModuleName
) {
295 Diag(Path
.front().second
, diag::err_current_module_name_mismatch
)
296 << SourceRange(Path
.front().second
, IsPartition
297 ? Partition
.back().second
298 : Path
.back().second
)
299 << getLangOpts().CurrentModule
;
302 const_cast<LangOptions
&>(getLangOpts()).CurrentModule
= ModuleName
;
304 auto &Map
= PP
.getHeaderSearchInfo().getModuleMap();
305 Module
*Mod
; // The module we are creating.
306 Module
*Interface
= nullptr; // The interface for an implementation.
308 case ModuleDeclKind::Interface
:
309 case ModuleDeclKind::PartitionInterface
: {
310 // We can't have parsed or imported a definition of this module or parsed a
311 // module map defining it already.
312 if (auto *M
= Map
.findModule(ModuleName
)) {
313 Diag(Path
[0].second
, diag::err_module_redefinition
) << ModuleName
;
314 if (M
->DefinitionLoc
.isValid())
315 Diag(M
->DefinitionLoc
, diag::note_prev_module_definition
);
316 else if (OptionalFileEntryRef FE
= M
->getASTFile())
317 Diag(M
->DefinitionLoc
, diag::note_prev_module_definition_from_ast_file
)
323 // Create a Module for the module that we're defining.
324 Mod
= Map
.createModuleForInterfaceUnit(ModuleLoc
, ModuleName
);
325 if (MDK
== ModuleDeclKind::PartitionInterface
)
326 Mod
->Kind
= Module::ModulePartitionInterface
;
327 assert(Mod
&& "module creation should not fail");
331 case ModuleDeclKind::Implementation
: {
332 // C++20 A module-declaration that contains neither an export-
333 // keyword nor a module-partition implicitly imports the primary
334 // module interface unit of the module as if by a module-import-
336 std::pair
<IdentifierInfo
*, SourceLocation
> ModuleNameLoc(
337 PP
.getIdentifierInfo(ModuleName
), Path
[0].second
);
339 // The module loader will assume we're trying to import the module that
340 // we're building if `LangOpts.CurrentModule` equals to 'ModuleName'.
341 // Change the value for `LangOpts.CurrentModule` temporarily to make the
342 // module loader work properly.
343 const_cast<LangOptions
&>(getLangOpts()).CurrentModule
= "";
344 Interface
= getModuleLoader().loadModule(ModuleLoc
, {ModuleNameLoc
},
346 /*IsInclusionDirective=*/false);
347 const_cast<LangOptions
&>(getLangOpts()).CurrentModule
= ModuleName
;
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
);
354 Mod
= Map
.createModuleForImplementationUnit(ModuleLoc
, ModuleName
);
358 case ModuleDeclKind::PartitionImplementation
:
359 // Create an interface, but note that it is an implementation
361 Mod
= Map
.createModuleForInterfaceUnit(ModuleLoc
, ModuleName
);
362 Mod
->Kind
= Module::ModulePartitionImplementation
;
366 if (!this->TheGlobalModuleFragment
) {
367 ModuleScopes
.push_back({});
368 if (getLangOpts().ModulesLocalVisibility
)
369 ModuleScopes
.back().OuterVisibleModules
= std::move(VisibleModules
);
371 // We're done with the global module fragment now.
372 ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global
);
375 // Switch from the global module fragment (if any) to the named module.
376 ModuleScopes
.back().BeginLoc
= StartLoc
;
377 ModuleScopes
.back().Module
= Mod
;
378 ModuleScopes
.back().ModuleInterface
= MDK
!= ModuleDeclKind::Implementation
;
379 VisibleModules
.setVisible(Mod
, ModuleLoc
);
381 // From now on, we have an owning module for all declarations we see.
382 // In C++20 modules, those declaration would be reachable when imported
383 // unless explicitily exported.
384 // Otherwise, those declarations are module-private unless explicitly
386 auto *TU
= Context
.getTranslationUnitDecl();
387 TU
->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ReachableWhenImported
);
388 TU
->setLocalOwningModule(Mod
);
390 // We are in the module purview, but before any other (non import)
391 // statements, so imports are allowed.
392 ImportState
= ModuleImportState::ImportAllowed
;
394 getASTContext().setCurrentNamedModule(Mod
);
396 // We already potentially made an implicit import (in the case of a module
397 // implementation unit importing its interface). Make this module visible
398 // and return the import decl to be added to the current TU.
401 VisibleModules
.setVisible(Interface
, ModuleLoc
);
402 VisibleModules
.makeTransitiveImportsVisible(Interface
, ModuleLoc
);
404 // Make the import decl for the interface in the impl module.
405 ImportDecl
*Import
= ImportDecl::Create(Context
, CurContext
, ModuleLoc
,
406 Interface
, Path
[0].second
);
407 CurContext
->addDecl(Import
);
409 // Sequence initialization of the imported module before that of the current
411 Context
.addModuleInitializer(ModuleScopes
.back().Module
, Import
);
412 Mod
->Imports
.insert(Interface
); // As if we imported it.
413 // Also save this as a shortcut to checking for decls in the interface
414 ThePrimaryInterface
= Interface
;
415 // If we made an implicit import of the module interface, then return the
416 // imported module decl.
417 return ConvertDeclToDeclGroup(Import
);
424 Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc
,
425 SourceLocation PrivateLoc
) {
426 // C++20 [basic.link]/2:
427 // A private-module-fragment shall appear only in a primary module
429 switch (ModuleScopes
.empty() ? Module::ExplicitGlobalModuleFragment
430 : ModuleScopes
.back().Module
->Kind
) {
431 case Module::ModuleMapModule
:
432 case Module::ExplicitGlobalModuleFragment
:
433 case Module::ImplicitGlobalModuleFragment
:
434 case Module::ModulePartitionImplementation
:
435 case Module::ModulePartitionInterface
:
436 case Module::ModuleHeaderUnit
:
437 Diag(PrivateLoc
, diag::err_private_module_fragment_not_module
);
440 case Module::PrivateModuleFragment
:
441 Diag(PrivateLoc
, diag::err_private_module_fragment_redefined
);
442 Diag(ModuleScopes
.back().BeginLoc
, diag::note_previous_definition
);
445 case Module::ModuleImplementationUnit
:
446 Diag(PrivateLoc
, diag::err_private_module_fragment_not_module_interface
);
447 Diag(ModuleScopes
.back().BeginLoc
,
448 diag::note_not_module_interface_add_export
)
449 << FixItHint::CreateInsertion(ModuleScopes
.back().BeginLoc
, "export ");
452 case Module::ModuleInterfaceUnit
:
456 // FIXME: Check that this translation unit does not import any partitions;
457 // such imports would violate [basic.link]/2's "shall be the only module unit"
460 // We've finished the public fragment of the translation unit.
461 ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal
);
463 auto &Map
= PP
.getHeaderSearchInfo().getModuleMap();
464 Module
*PrivateModuleFragment
=
465 Map
.createPrivateModuleFragmentForInterfaceUnit(
466 ModuleScopes
.back().Module
, PrivateLoc
);
467 assert(PrivateModuleFragment
&& "module creation should not fail");
469 // Enter the scope of the private module fragment.
470 ModuleScopes
.push_back({});
471 ModuleScopes
.back().BeginLoc
= ModuleLoc
;
472 ModuleScopes
.back().Module
= PrivateModuleFragment
;
473 ModuleScopes
.back().ModuleInterface
= true;
474 VisibleModules
.setVisible(PrivateModuleFragment
, ModuleLoc
);
476 // All declarations created from now on are scoped to the private module
477 // fragment (and are neither visible nor reachable in importers of the module
479 auto *TU
= Context
.getTranslationUnitDecl();
480 TU
->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate
);
481 TU
->setLocalOwningModule(PrivateModuleFragment
);
483 // FIXME: Consider creating an explicit representation of this declaration.
487 DeclResult
Sema::ActOnModuleImport(SourceLocation StartLoc
,
488 SourceLocation ExportLoc
,
489 SourceLocation ImportLoc
, ModuleIdPath Path
,
491 assert((!IsPartition
|| getLangOpts().CPlusPlusModules
) &&
492 "partition seen in non-C++20 code?");
494 // For a C++20 module name, flatten into a single identifier with the source
495 // location of the first component.
496 std::pair
<IdentifierInfo
*, SourceLocation
> ModuleNameLoc
;
498 std::string ModuleName
;
500 // We already checked that we are in a module purview in the parser.
501 assert(!ModuleScopes
.empty() && "in a module purview, but no module?");
502 Module
*NamedMod
= ModuleScopes
.back().Module
;
503 // If we are importing into a partition, find the owning named module,
504 // otherwise, the name of the importing named module.
505 ModuleName
= NamedMod
->getPrimaryModuleInterfaceName().str();
507 ModuleName
+= stringFromPath(Path
);
508 ModuleNameLoc
= {PP
.getIdentifierInfo(ModuleName
), Path
[0].second
};
509 Path
= ModuleIdPath(ModuleNameLoc
);
510 } else if (getLangOpts().CPlusPlusModules
) {
511 ModuleName
= stringFromPath(Path
);
512 ModuleNameLoc
= {PP
.getIdentifierInfo(ModuleName
), Path
[0].second
};
513 Path
= ModuleIdPath(ModuleNameLoc
);
516 // Diagnose self-import before attempting a load.
518 // A module implementation unit of a module M that is not a module partition
519 // shall not contain a module-import-declaration nominating M.
520 // (for an implementation, the module interface is imported implicitly,
521 // but that's handled in the module decl code).
523 if (getLangOpts().CPlusPlusModules
&& isCurrentModulePurview() &&
524 getCurrentModule()->Name
== ModuleName
) {
525 Diag(ImportLoc
, diag::err_module_self_import_cxx20
)
526 << ModuleName
<< !ModuleScopes
.back().ModuleInterface
;
530 Module
*Mod
= getModuleLoader().loadModule(
531 ImportLoc
, Path
, Module::AllVisible
, /*IsInclusionDirective=*/false);
535 if (!Mod
->isInterfaceOrPartition() && !ModuleName
.empty()) {
536 Diag(ImportLoc
, diag::err_module_import_non_interface_nor_parition
)
541 return ActOnModuleImport(StartLoc
, ExportLoc
, ImportLoc
, Mod
, Path
);
544 /// Determine whether \p D is lexically within an export-declaration.
545 static const ExportDecl
*getEnclosingExportDecl(const Decl
*D
) {
546 for (auto *DC
= D
->getLexicalDeclContext(); DC
; DC
= DC
->getLexicalParent())
547 if (auto *ED
= dyn_cast
<ExportDecl
>(DC
))
552 DeclResult
Sema::ActOnModuleImport(SourceLocation StartLoc
,
553 SourceLocation ExportLoc
,
554 SourceLocation ImportLoc
, Module
*Mod
,
556 if (Mod
->isHeaderUnit())
557 Diag(ImportLoc
, diag::warn_experimental_header_unit
);
559 VisibleModules
.setVisible(Mod
, ImportLoc
);
561 checkModuleImportContext(*this, Mod
, ImportLoc
, CurContext
);
563 // FIXME: we should support importing a submodule within a different submodule
564 // of the same top-level module. Until we do, make it an error rather than
565 // silently ignoring the import.
566 // FIXME: Should we warn on a redundant import of the current module?
567 if (Mod
->isForBuilding(getLangOpts())) {
568 Diag(ImportLoc
, getLangOpts().isCompilingModule()
569 ? diag::err_module_self_import
570 : diag::err_module_import_in_implementation
)
571 << Mod
->getFullModuleName() << getLangOpts().CurrentModule
;
574 SmallVector
<SourceLocation
, 2> IdentifierLocs
;
577 // If this was a header import, pad out with dummy locations.
578 // FIXME: Pass in and use the location of the header-name token in this
580 for (Module
*ModCheck
= Mod
; ModCheck
; ModCheck
= ModCheck
->Parent
)
581 IdentifierLocs
.push_back(SourceLocation());
582 } else if (getLangOpts().CPlusPlusModules
&& !Mod
->Parent
) {
583 // A single identifier for the whole name.
584 IdentifierLocs
.push_back(Path
[0].second
);
586 Module
*ModCheck
= Mod
;
587 for (unsigned I
= 0, N
= Path
.size(); I
!= N
; ++I
) {
588 // If we've run out of module parents, just drop the remaining
589 // identifiers. We need the length to be consistent.
592 ModCheck
= ModCheck
->Parent
;
594 IdentifierLocs
.push_back(Path
[I
].second
);
598 ImportDecl
*Import
= ImportDecl::Create(Context
, CurContext
, StartLoc
,
599 Mod
, IdentifierLocs
);
600 CurContext
->addDecl(Import
);
602 // Sequence initialization of the imported module before that of the current
604 if (!ModuleScopes
.empty())
605 Context
.addModuleInitializer(ModuleScopes
.back().Module
, Import
);
607 // A module (partition) implementation unit shall not be exported.
608 if (getLangOpts().CPlusPlusModules
&& ExportLoc
.isValid() &&
609 Mod
->Kind
== Module::ModuleKind::ModulePartitionImplementation
) {
610 Diag(ExportLoc
, diag::err_export_partition_impl
)
611 << SourceRange(ExportLoc
, Path
.back().second
);
612 } else if (!ModuleScopes
.empty() &&
613 (ModuleScopes
.back().ModuleInterface
||
614 (getLangOpts().CPlusPlusModules
&&
615 ModuleScopes
.back().Module
->isGlobalModule()))) {
616 // Re-export the module if the imported module is exported.
617 // Note that we don't need to add re-exported module to Imports field
618 // since `Exports` implies the module is imported already.
619 if (ExportLoc
.isValid() || getEnclosingExportDecl(Import
))
620 getCurrentModule()->Exports
.emplace_back(Mod
, false);
622 getCurrentModule()->Imports
.insert(Mod
);
623 } else if (ExportLoc
.isValid()) {
624 // [module.interface]p1:
625 // An export-declaration shall inhabit a namespace scope and appear in the
626 // purview of a module interface unit.
627 Diag(ExportLoc
, diag::err_export_not_in_module_interface
);
633 void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc
, Module
*Mod
) {
634 checkModuleImportContext(*this, Mod
, DirectiveLoc
, CurContext
, true);
635 BuildModuleInclude(DirectiveLoc
, Mod
);
638 void Sema::BuildModuleInclude(SourceLocation DirectiveLoc
, Module
*Mod
) {
639 // Determine whether we're in the #include buffer for a module. The #includes
640 // in that buffer do not qualify as module imports; they're just an
641 // implementation detail of us building the module.
643 // FIXME: Should we even get ActOnModuleInclude calls for those?
644 bool IsInModuleIncludes
=
645 TUKind
== TU_Module
&&
646 getSourceManager().isWrittenInMainFile(DirectiveLoc
);
648 // If we are really importing a module (not just checking layering) due to an
649 // #include in the main file, synthesize an ImportDecl.
650 if (getLangOpts().Modules
&& !IsInModuleIncludes
) {
651 TranslationUnitDecl
*TU
= getASTContext().getTranslationUnitDecl();
652 ImportDecl
*ImportD
= ImportDecl::CreateImplicit(getASTContext(), TU
,
655 if (!ModuleScopes
.empty())
656 Context
.addModuleInitializer(ModuleScopes
.back().Module
, ImportD
);
657 TU
->addDecl(ImportD
);
658 Consumer
.HandleImplicitImportDecl(ImportD
);
661 getModuleLoader().makeModuleVisible(Mod
, Module::AllVisible
, DirectiveLoc
);
662 VisibleModules
.setVisible(Mod
, DirectiveLoc
);
664 if (getLangOpts().isCompilingModule()) {
665 Module
*ThisModule
= PP
.getHeaderSearchInfo().lookupModule(
666 getLangOpts().CurrentModule
, DirectiveLoc
, false, false);
668 assert(ThisModule
&& "was expecting a module if building one");
672 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc
, Module
*Mod
) {
673 checkModuleImportContext(*this, Mod
, DirectiveLoc
, CurContext
, true);
675 ModuleScopes
.push_back({});
676 ModuleScopes
.back().Module
= Mod
;
677 if (getLangOpts().ModulesLocalVisibility
)
678 ModuleScopes
.back().OuterVisibleModules
= std::move(VisibleModules
);
680 VisibleModules
.setVisible(Mod
, DirectiveLoc
);
682 // The enclosing context is now part of this module.
683 // FIXME: Consider creating a child DeclContext to hold the entities
684 // lexically within the module.
685 if (getLangOpts().trackLocalOwningModule()) {
686 for (auto *DC
= CurContext
; DC
; DC
= DC
->getLexicalParent()) {
687 cast
<Decl
>(DC
)->setModuleOwnershipKind(
688 getLangOpts().ModulesLocalVisibility
689 ? Decl::ModuleOwnershipKind::VisibleWhenImported
690 : Decl::ModuleOwnershipKind::Visible
);
691 cast
<Decl
>(DC
)->setLocalOwningModule(Mod
);
696 void Sema::ActOnModuleEnd(SourceLocation EomLoc
, Module
*Mod
) {
697 if (getLangOpts().ModulesLocalVisibility
) {
698 VisibleModules
= std::move(ModuleScopes
.back().OuterVisibleModules
);
699 // Leaving a module hides namespace names, so our visible namespace cache
700 // is now out of date.
701 VisibleNamespaceCache
.clear();
704 assert(!ModuleScopes
.empty() && ModuleScopes
.back().Module
== Mod
&&
705 "left the wrong module scope");
706 ModuleScopes
.pop_back();
708 // We got to the end of processing a local module. Create an
709 // ImportDecl as we would for an imported module.
710 FileID File
= getSourceManager().getFileID(EomLoc
);
711 SourceLocation DirectiveLoc
;
712 if (EomLoc
== getSourceManager().getLocForEndOfFile(File
)) {
713 // We reached the end of a #included module header. Use the #include loc.
714 assert(File
!= getSourceManager().getMainFileID() &&
715 "end of submodule in main source file");
716 DirectiveLoc
= getSourceManager().getIncludeLoc(File
);
718 // We reached an EOM pragma. Use the pragma location.
719 DirectiveLoc
= EomLoc
;
721 BuildModuleInclude(DirectiveLoc
, Mod
);
723 // Any further declarations are in whatever module we returned to.
724 if (getLangOpts().trackLocalOwningModule()) {
725 // The parser guarantees that this is the same context that we entered
726 // the module within.
727 for (auto *DC
= CurContext
; DC
; DC
= DC
->getLexicalParent()) {
728 cast
<Decl
>(DC
)->setLocalOwningModule(getCurrentModule());
729 if (!getCurrentModule())
730 cast
<Decl
>(DC
)->setModuleOwnershipKind(
731 Decl::ModuleOwnershipKind::Unowned
);
736 void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc
,
738 // Bail if we're not allowed to implicitly import a module here.
739 if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery
||
740 VisibleModules
.isVisible(Mod
))
743 // Create the implicit import declaration.
744 TranslationUnitDecl
*TU
= getASTContext().getTranslationUnitDecl();
745 ImportDecl
*ImportD
= ImportDecl::CreateImplicit(getASTContext(), TU
,
747 TU
->addDecl(ImportD
);
748 Consumer
.HandleImplicitImportDecl(ImportD
);
750 // Make the module visible.
751 getModuleLoader().makeModuleVisible(Mod
, Module::AllVisible
, Loc
);
752 VisibleModules
.setVisible(Mod
, Loc
);
755 /// We have parsed the start of an export declaration, including the '{'
757 Decl
*Sema::ActOnStartExportDecl(Scope
*S
, SourceLocation ExportLoc
,
758 SourceLocation LBraceLoc
) {
759 ExportDecl
*D
= ExportDecl::Create(Context
, CurContext
, ExportLoc
);
761 // Set this temporarily so we know the export-declaration was braced.
762 D
->setRBraceLoc(LBraceLoc
);
764 CurContext
->addDecl(D
);
765 PushDeclContext(S
, D
);
767 // C++2a [module.interface]p1:
768 // An export-declaration shall appear only [...] in the purview of a module
769 // interface unit. An export-declaration shall not appear directly or
770 // indirectly within [...] a private-module-fragment.
771 if (!isCurrentModulePurview()) {
772 Diag(ExportLoc
, diag::err_export_not_in_module_interface
) << 0;
775 } else if (!ModuleScopes
.back().ModuleInterface
) {
776 Diag(ExportLoc
, diag::err_export_not_in_module_interface
) << 1;
777 Diag(ModuleScopes
.back().BeginLoc
,
778 diag::note_not_module_interface_add_export
)
779 << FixItHint::CreateInsertion(ModuleScopes
.back().BeginLoc
, "export ");
782 } else if (ModuleScopes
.back().Module
->Kind
==
783 Module::PrivateModuleFragment
) {
784 Diag(ExportLoc
, diag::err_export_in_private_module_fragment
);
785 Diag(ModuleScopes
.back().BeginLoc
, diag::note_private_module_fragment
);
790 for (const DeclContext
*DC
= CurContext
; DC
; DC
= DC
->getLexicalParent()) {
791 if (const auto *ND
= dyn_cast
<NamespaceDecl
>(DC
)) {
792 // An export-declaration shall not appear directly or indirectly within
793 // an unnamed namespace [...]
794 if (ND
->isAnonymousNamespace()) {
795 Diag(ExportLoc
, diag::err_export_within_anonymous_namespace
);
796 Diag(ND
->getLocation(), diag::note_anonymous_namespace
);
797 // Don't diagnose internal-linkage declarations in this region.
802 // A declaration is exported if it is [...] a namespace-definition
803 // that contains an exported declaration.
805 // Defer exporting the namespace until after we leave it, in order to
806 // avoid marking all subsequent declarations in the namespace as exported.
807 if (!DeferredExportedNamespaces
.insert(ND
).second
)
812 // [...] its declaration or declaration-seq shall not contain an
813 // export-declaration.
814 if (auto *ED
= getEnclosingExportDecl(D
)) {
815 Diag(ExportLoc
, diag::err_export_within_export
);
817 Diag(ED
->getLocation(), diag::note_export
);
822 D
->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported
);
826 static bool checkExportedDecl(Sema
&, Decl
*, SourceLocation
);
828 /// Check that it's valid to export all the declarations in \p DC.
829 static bool checkExportedDeclContext(Sema
&S
, DeclContext
*DC
,
830 SourceLocation BlockStart
) {
831 bool AllUnnamed
= true;
832 for (auto *D
: DC
->decls())
833 AllUnnamed
&= checkExportedDecl(S
, D
, BlockStart
);
837 /// Check that it's valid to export \p D.
838 static bool checkExportedDecl(Sema
&S
, Decl
*D
, SourceLocation BlockStart
) {
840 // C++20 [module.interface]p3:
841 // [...] it shall not declare a name with internal linkage.
842 bool HasName
= false;
843 if (auto *ND
= dyn_cast
<NamedDecl
>(D
)) {
844 // Don't diagnose anonymous union objects; we'll diagnose their members
846 HasName
= (bool)ND
->getDeclName();
847 if (HasName
&& ND
->getFormalLinkage() == Linkage::Internal
) {
848 S
.Diag(ND
->getLocation(), diag::err_export_internal
) << ND
;
849 if (BlockStart
.isValid())
850 S
.Diag(BlockStart
, diag::note_export
);
855 // C++2a [module.interface]p5:
856 // all entities to which all of the using-declarators ultimately refer
857 // shall have been introduced with a name having external linkage
858 if (auto *USD
= dyn_cast
<UsingShadowDecl
>(D
)) {
859 NamedDecl
*Target
= USD
->getUnderlyingDecl();
860 Linkage Lk
= Target
->getFormalLinkage();
861 if (Lk
== Linkage::Internal
|| Lk
== Linkage::Module
) {
862 S
.Diag(USD
->getLocation(), diag::err_export_using_internal
)
863 << (Lk
== Linkage::Internal
? 0 : 1) << Target
;
864 S
.Diag(Target
->getLocation(), diag::note_using_decl_target
);
865 if (BlockStart
.isValid())
866 S
.Diag(BlockStart
, diag::note_export
);
871 // Recurse into namespace-scope DeclContexts. (Only namespace-scope
872 // declarations are exported).
873 if (auto *DC
= dyn_cast
<DeclContext
>(D
)) {
874 if (!isa
<NamespaceDecl
>(D
))
877 if (auto *ND
= dyn_cast
<NamedDecl
>(D
)) {
878 if (!ND
->getDeclName()) {
879 S
.Diag(ND
->getLocation(), diag::err_export_anon_ns_internal
);
880 if (BlockStart
.isValid())
881 S
.Diag(BlockStart
, diag::note_export
);
883 } else if (!DC
->decls().empty() &&
884 DC
->getRedeclContext()->isFileContext()) {
885 return checkExportedDeclContext(S
, DC
, BlockStart
);
892 /// Complete the definition of an export declaration.
893 Decl
*Sema::ActOnFinishExportDecl(Scope
*S
, Decl
*D
, SourceLocation RBraceLoc
) {
894 auto *ED
= cast
<ExportDecl
>(D
);
895 if (RBraceLoc
.isValid())
896 ED
->setRBraceLoc(RBraceLoc
);
900 if (!D
->isInvalidDecl()) {
901 SourceLocation BlockStart
=
902 ED
->hasBraces() ? ED
->getBeginLoc() : SourceLocation();
903 for (auto *Child
: ED
->decls()) {
904 checkExportedDecl(*this, Child
, BlockStart
);
905 if (auto *FD
= dyn_cast
<FunctionDecl
>(Child
)) {
907 // If an inline function or variable that is attached to a named module
908 // is declared in a definition domain, it shall be defined in that
910 // So, if the current declaration does not have a definition, we must
911 // check at the end of the TU (or when the PMF starts) to see that we
912 // have a definition at that point.
913 if (FD
->isInlineSpecified() && !FD
->isDefined())
914 PendingInlineFuncDecls
.insert(FD
);
922 Module
*Sema::PushGlobalModuleFragment(SourceLocation BeginLoc
) {
923 // We shouldn't create new global module fragment if there is already
925 if (!TheGlobalModuleFragment
) {
926 ModuleMap
&Map
= PP
.getHeaderSearchInfo().getModuleMap();
927 TheGlobalModuleFragment
= Map
.createGlobalModuleFragmentForModuleUnit(
928 BeginLoc
, getCurrentModule());
931 assert(TheGlobalModuleFragment
&& "module creation should not fail");
933 // Enter the scope of the global module.
934 ModuleScopes
.push_back({BeginLoc
, TheGlobalModuleFragment
,
935 /*ModuleInterface=*/false,
936 /*OuterVisibleModules=*/{}});
937 VisibleModules
.setVisible(TheGlobalModuleFragment
, BeginLoc
);
939 return TheGlobalModuleFragment
;
942 void Sema::PopGlobalModuleFragment() {
943 assert(!ModuleScopes
.empty() &&
944 getCurrentModule()->isExplicitGlobalModule() &&
945 "left the wrong module scope, which is not global module fragment");
946 ModuleScopes
.pop_back();
949 Module
*Sema::PushImplicitGlobalModuleFragment(SourceLocation BeginLoc
,
951 Module
**M
= IsExported
? &TheExportedImplicitGlobalModuleFragment
952 : &TheImplicitGlobalModuleFragment
;
954 ModuleMap
&Map
= PP
.getHeaderSearchInfo().getModuleMap();
955 *M
= Map
.createImplicitGlobalModuleFragmentForModuleUnit(
956 BeginLoc
, IsExported
, getCurrentModule());
958 assert(*M
&& "module creation should not fail");
960 // Enter the scope of the global module.
961 ModuleScopes
.push_back({BeginLoc
, *M
,
962 /*ModuleInterface=*/false,
963 /*OuterVisibleModules=*/{}});
964 VisibleModules
.setVisible(*M
, BeginLoc
);
968 void Sema::PopImplicitGlobalModuleFragment() {
969 assert(!ModuleScopes
.empty() &&
970 getCurrentModule()->isImplicitGlobalModule() &&
971 "left the wrong module scope, which is not global module fragment");
972 ModuleScopes
.pop_back();