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