clang  10.0.0svn
SemaModule.cpp
Go to the documentation of this file.
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"
18 
19 using namespace clang;
20 using namespace sema;
21 
23  SourceLocation ImportLoc, DeclContext *DC,
24  bool FromInclude = false) {
25  SourceLocation ExternCLoc;
26 
27  if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
28  switch (LSD->getLanguage()) {
30  if (ExternCLoc.isInvalid())
31  ExternCLoc = LSD->getBeginLoc();
32  break;
36  break;
37  }
38  DC = LSD->getParent();
39  }
40 
41  while (isa<LinkageSpecDecl>(DC) || isa<ExportDecl>(DC))
42  DC = DC->getParent();
43 
44  if (!isa<TranslationUnitDecl>(DC)) {
45  S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
46  ? diag::ext_module_import_not_at_top_level_noop
47  : diag::err_module_import_not_at_top_level_fatal)
48  << M->getFullModuleName() << DC;
49  S.Diag(cast<Decl>(DC)->getBeginLoc(),
50  diag::note_module_import_not_at_top_level)
51  << DC;
52  } else if (!M->IsExternC && ExternCLoc.isValid()) {
53  S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
54  << M->getFullModuleName();
55  S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
56  }
57 }
58 
61  if (!ModuleScopes.empty() &&
62  ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment) {
63  // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
64  // already implicitly entering the global module fragment. That's OK.
65  assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
66  "unexpectedly encountered multiple global module fragment decls");
67  ModuleScopes.back().BeginLoc = ModuleLoc;
68  return nullptr;
69  }
70 
71  // We start in the global module; all those declarations are implicitly
72  // module-private (though they do not have module linkage).
73  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
74  auto *GlobalModule = Map.createGlobalModuleFragmentForModuleUnit(ModuleLoc);
75  assert(GlobalModule && "module creation should not fail");
76 
77  // Enter the scope of the global module.
78  ModuleScopes.push_back({});
79  ModuleScopes.back().BeginLoc = ModuleLoc;
80  ModuleScopes.back().Module = GlobalModule;
81  VisibleModules.setVisible(GlobalModule, ModuleLoc);
82 
83  // All declarations created from now on are owned by the global module.
84  auto *TU = Context.getTranslationUnitDecl();
86  TU->setLocalOwningModule(GlobalModule);
87 
88  // FIXME: Consider creating an explicit representation of this declaration.
89  return nullptr;
90 }
91 
94  ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl) {
95  assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
96  "should only have module decl in Modules TS or C++20");
97 
98  // A module implementation unit requires that we are not compiling a module
99  // of any kind. A module interface unit requires that we are not compiling a
100  // module map.
101  switch (getLangOpts().getCompilingModule()) {
103  // It's OK to compile a module interface as a normal translation unit.
104  break;
105 
107  if (MDK != ModuleDeclKind::Implementation)
108  break;
109 
110  // We were asked to compile a module interface unit but this is a module
111  // implementation unit. That indicates the 'export' is missing.
112  Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
113  << FixItHint::CreateInsertion(ModuleLoc, "export ");
114  MDK = ModuleDeclKind::Interface;
115  break;
116 
118  Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
119  return nullptr;
120 
122  Diag(ModuleLoc, diag::err_module_decl_in_header_module);
123  return nullptr;
124  }
125 
126  assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
127 
128  // FIXME: Most of this work should be done by the preprocessor rather than
129  // here, in order to support macro import.
130 
131  // Only one module-declaration is permitted per source file.
132  if (!ModuleScopes.empty() &&
133  ModuleScopes.back().Module->isModulePurview()) {
134  Diag(ModuleLoc, diag::err_module_redeclaration);
135  Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
136  diag::note_prev_module_declaration);
137  return nullptr;
138  }
139 
140  // Find the global module fragment we're adopting into this module, if any.
141  Module *GlobalModuleFragment = nullptr;
142  if (!ModuleScopes.empty() &&
143  ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment)
144  GlobalModuleFragment = ModuleScopes.back().Module;
145 
146  // In C++20, the module-declaration must be the first declaration if there
147  // is no global module fragment.
148  if (getLangOpts().CPlusPlusModules && !IsFirstDecl && !GlobalModuleFragment) {
149  Diag(ModuleLoc, diag::err_module_decl_not_at_start);
150  SourceLocation BeginLoc =
151  ModuleScopes.empty()
152  ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
153  : ModuleScopes.back().BeginLoc;
154  if (BeginLoc.isValid()) {
155  Diag(BeginLoc, diag::note_global_module_introducer_missing)
156  << FixItHint::CreateInsertion(BeginLoc, "module;\n");
157  }
158  }
159 
160  // Flatten the dots in a module name. Unlike Clang's hierarchical module map
161  // modules, the dots here are just another character that can appear in a
162  // module name.
163  std::string ModuleName;
164  for (auto &Piece : Path) {
165  if (!ModuleName.empty())
166  ModuleName += ".";
167  ModuleName += Piece.first->getName();
168  }
169 
170  // If a module name was explicitly specified on the command line, it must be
171  // correct.
172  if (!getLangOpts().CurrentModule.empty() &&
173  getLangOpts().CurrentModule != ModuleName) {
174  Diag(Path.front().second, diag::err_current_module_name_mismatch)
175  << SourceRange(Path.front().second, Path.back().second)
176  << getLangOpts().CurrentModule;
177  return nullptr;
178  }
179  const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
180 
181  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
182  Module *Mod;
183 
184  switch (MDK) {
185  case ModuleDeclKind::Interface: {
186  // We can't have parsed or imported a definition of this module or parsed a
187  // module map defining it already.
188  if (auto *M = Map.findModule(ModuleName)) {
189  Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
190  if (M->DefinitionLoc.isValid())
191  Diag(M->DefinitionLoc, diag::note_prev_module_definition);
192  else if (const auto *FE = M->getASTFile())
193  Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
194  << FE->getName();
195  Mod = M;
196  break;
197  }
198 
199  // Create a Module for the module that we're defining.
200  Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
201  GlobalModuleFragment);
202  assert(Mod && "module creation should not fail");
203  break;
204  }
205 
206  case ModuleDeclKind::Implementation:
207  std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
208  PP.getIdentifierInfo(ModuleName), Path[0].second);
209  Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
211  /*IsInclusionDirective=*/false);
212  if (!Mod) {
213  Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
214  // Create an empty module interface unit for error recovery.
215  Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
216  GlobalModuleFragment);
217  }
218  break;
219  }
220 
221  if (!GlobalModuleFragment) {
222  ModuleScopes.push_back({});
223  if (getLangOpts().ModulesLocalVisibility)
224  ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
225  } else {
226  // We're done with the global module fragment now.
227  ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
228  }
229 
230  // Switch from the global module fragment (if any) to the named module.
231  ModuleScopes.back().BeginLoc = StartLoc;
232  ModuleScopes.back().Module = Mod;
233  ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
234  VisibleModules.setVisible(Mod, ModuleLoc);
235 
236  // From now on, we have an owning module for all declarations we see.
237  // However, those declarations are module-private unless explicitly
238  // exported.
239  auto *TU = Context.getTranslationUnitDecl();
241  TU->setLocalOwningModule(Mod);
242 
243  // FIXME: Create a ModuleDecl.
244  return nullptr;
245 }
246 
249  SourceLocation PrivateLoc) {
250  // C++20 [basic.link]/2:
251  // A private-module-fragment shall appear only in a primary module
252  // interface unit.
253  switch (ModuleScopes.empty() ? Module::GlobalModuleFragment
254  : ModuleScopes.back().Module->Kind) {
257  Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
258  return nullptr;
259 
261  Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
262  Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
263  return nullptr;
264 
266  break;
267  }
268 
269  if (!ModuleScopes.back().ModuleInterface) {
270  Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
271  Diag(ModuleScopes.back().BeginLoc,
272  diag::note_not_module_interface_add_export)
273  << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
274  return nullptr;
275  }
276 
277  // FIXME: Check this isn't a module interface partition.
278  // FIXME: Check that this translation unit does not import any partitions;
279  // such imports would violate [basic.link]/2's "shall be the only module unit"
280  // restriction.
281 
282  // We've finished the public fragment of the translation unit.
283  ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
284 
285  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
286  Module *PrivateModuleFragment =
287  Map.createPrivateModuleFragmentForInterfaceUnit(
288  ModuleScopes.back().Module, PrivateLoc);
289  assert(PrivateModuleFragment && "module creation should not fail");
290 
291  // Enter the scope of the private module fragment.
292  ModuleScopes.push_back({});
293  ModuleScopes.back().BeginLoc = ModuleLoc;
294  ModuleScopes.back().Module = PrivateModuleFragment;
295  ModuleScopes.back().ModuleInterface = true;
296  VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
297 
298  // All declarations created from now on are scoped to the private module
299  // fragment (and are neither visible nor reachable in importers of the module
300  // interface).
301  auto *TU = Context.getTranslationUnitDecl();
303  TU->setLocalOwningModule(PrivateModuleFragment);
304 
305  // FIXME: Consider creating an explicit representation of this declaration.
306  return nullptr;
307 }
308 
310  SourceLocation ExportLoc,
311  SourceLocation ImportLoc,
312  ModuleIdPath Path) {
313  // Flatten the module path for a Modules TS module name.
314  std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
315  if (getLangOpts().ModulesTS) {
316  std::string ModuleName;
317  for (auto &Piece : Path) {
318  if (!ModuleName.empty())
319  ModuleName += ".";
320  ModuleName += Piece.first->getName();
321  }
322  ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
323  Path = ModuleIdPath(ModuleNameLoc);
324  }
325 
326  Module *Mod =
327  getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
328  /*IsInclusionDirective=*/false);
329  if (!Mod)
330  return true;
331 
332  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
333 }
334 
335 /// Determine whether \p D is lexically within an export-declaration.
336 static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
337  for (auto *DC = D->getLexicalDeclContext(); DC; DC = DC->getLexicalParent())
338  if (auto *ED = dyn_cast<ExportDecl>(DC))
339  return ED;
340  return nullptr;
341 }
342 
344  SourceLocation ExportLoc,
345  SourceLocation ImportLoc,
346  Module *Mod, ModuleIdPath Path) {
347  VisibleModules.setVisible(Mod, ImportLoc);
348 
349  checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
350 
351  // FIXME: we should support importing a submodule within a different submodule
352  // of the same top-level module. Until we do, make it an error rather than
353  // silently ignoring the import.
354  // Import-from-implementation is valid in the Modules TS. FIXME: Should we
355  // warn on a redundant import of the current module?
356  // FIXME: Import of a module from an implementation partition of the same
357  // module is permitted.
358  if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
359  (getLangOpts().isCompilingModule() || !getLangOpts().ModulesTS)) {
360  Diag(ImportLoc, getLangOpts().isCompilingModule()
361  ? diag::err_module_self_import
362  : diag::err_module_import_in_implementation)
363  << Mod->getFullModuleName() << getLangOpts().CurrentModule;
364  }
365 
366  SmallVector<SourceLocation, 2> IdentifierLocs;
367  Module *ModCheck = Mod;
368  for (unsigned I = 0, N = Path.size(); I != N; ++I) {
369  // If we've run out of module parents, just drop the remaining identifiers.
370  // We need the length to be consistent.
371  if (!ModCheck)
372  break;
373  ModCheck = ModCheck->Parent;
374 
375  IdentifierLocs.push_back(Path[I].second);
376  }
377 
378  // If this was a header import, pad out with dummy locations.
379  // FIXME: Pass in and use the location of the header-name token in this case.
380  if (Path.empty()) {
381  for (; ModCheck; ModCheck = ModCheck->Parent) {
382  IdentifierLocs.push_back(SourceLocation());
383  }
384  }
385 
386  ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
387  Mod, IdentifierLocs);
388  CurContext->addDecl(Import);
389 
390  // Sequence initialization of the imported module before that of the current
391  // module, if any.
392  if (!ModuleScopes.empty())
393  Context.addModuleInitializer(ModuleScopes.back().Module, Import);
394 
395  // Re-export the module if needed.
396  if (!ModuleScopes.empty() && ModuleScopes.back().ModuleInterface) {
397  if (ExportLoc.isValid() || getEnclosingExportDecl(Import))
398  getCurrentModule()->Exports.emplace_back(Mod, false);
399  } else if (ExportLoc.isValid()) {
400  Diag(ExportLoc, diag::err_export_not_in_module_interface);
401  }
402 
403  return Import;
404 }
405 
407  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
408  BuildModuleInclude(DirectiveLoc, Mod);
409 }
410 
412  // Determine whether we're in the #include buffer for a module. The #includes
413  // in that buffer do not qualify as module imports; they're just an
414  // implementation detail of us building the module.
415  //
416  // FIXME: Should we even get ActOnModuleInclude calls for those?
417  bool IsInModuleIncludes =
418  TUKind == TU_Module &&
419  getSourceManager().isWrittenInMainFile(DirectiveLoc);
420 
421  bool ShouldAddImport = !IsInModuleIncludes;
422 
423  // If this module import was due to an inclusion directive, create an
424  // implicit import declaration to capture it in the AST.
425  if (ShouldAddImport) {
426  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
427  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
428  DirectiveLoc, Mod,
429  DirectiveLoc);
430  if (!ModuleScopes.empty())
431  Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
432  TU->addDecl(ImportD);
433  Consumer.HandleImplicitImportDecl(ImportD);
434  }
435 
436  getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
437  VisibleModules.setVisible(Mod, DirectiveLoc);
438 }
439 
440 void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
441  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
442 
443  ModuleScopes.push_back({});
444  ModuleScopes.back().Module = Mod;
445  if (getLangOpts().ModulesLocalVisibility)
446  ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
447 
448  VisibleModules.setVisible(Mod, DirectiveLoc);
449 
450  // The enclosing context is now part of this module.
451  // FIXME: Consider creating a child DeclContext to hold the entities
452  // lexically within the module.
453  if (getLangOpts().trackLocalOwningModule()) {
454  for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
455  cast<Decl>(DC)->setModuleOwnershipKind(
456  getLangOpts().ModulesLocalVisibility
459  cast<Decl>(DC)->setLocalOwningModule(Mod);
460  }
461  }
462 }
463 
465  if (getLangOpts().ModulesLocalVisibility) {
466  VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
467  // Leaving a module hides namespace names, so our visible namespace cache
468  // is now out of date.
469  VisibleNamespaceCache.clear();
470  }
471 
472  assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
473  "left the wrong module scope");
474  ModuleScopes.pop_back();
475 
476  // We got to the end of processing a local module. Create an
477  // ImportDecl as we would for an imported module.
478  FileID File = getSourceManager().getFileID(EomLoc);
479  SourceLocation DirectiveLoc;
480  if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
481  // We reached the end of a #included module header. Use the #include loc.
482  assert(File != getSourceManager().getMainFileID() &&
483  "end of submodule in main source file");
484  DirectiveLoc = getSourceManager().getIncludeLoc(File);
485  } else {
486  // We reached an EOM pragma. Use the pragma location.
487  DirectiveLoc = EomLoc;
488  }
489  BuildModuleInclude(DirectiveLoc, Mod);
490 
491  // Any further declarations are in whatever module we returned to.
492  if (getLangOpts().trackLocalOwningModule()) {
493  // The parser guarantees that this is the same context that we entered
494  // the module within.
495  for (auto *DC = CurContext; DC; DC = DC->getLexicalParent()) {
496  cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
497  if (!getCurrentModule())
498  cast<Decl>(DC)->setModuleOwnershipKind(
500  }
501  }
502 }
503 
505  Module *Mod) {
506  // Bail if we're not allowed to implicitly import a module here.
507  if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
508  VisibleModules.isVisible(Mod))
509  return;
510 
511  // Create the implicit import declaration.
512  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
513  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
514  Loc, Mod, Loc);
515  TU->addDecl(ImportD);
516  Consumer.HandleImplicitImportDecl(ImportD);
517 
518  // Make the module visible.
519  getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
520  VisibleModules.setVisible(Mod, Loc);
521 }
522 
523 /// We have parsed the start of an export declaration, including the '{'
524 /// (if present).
526  SourceLocation LBraceLoc) {
527  ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
528 
529  // Set this temporarily so we know the export-declaration was braced.
530  D->setRBraceLoc(LBraceLoc);
531 
532  // C++2a [module.interface]p1:
533  // An export-declaration shall appear only [...] in the purview of a module
534  // interface unit. An export-declaration shall not appear directly or
535  // indirectly within [...] a private-module-fragment.
536  if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
537  Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
538  } else if (!ModuleScopes.back().ModuleInterface) {
539  Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
540  Diag(ModuleScopes.back().BeginLoc,
541  diag::note_not_module_interface_add_export)
542  << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
543  } else if (ModuleScopes.back().Module->Kind ==
545  Diag(ExportLoc, diag::err_export_in_private_module_fragment);
546  Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
547  }
548 
549  for (const DeclContext *DC = CurContext; DC; DC = DC->getLexicalParent()) {
550  if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
551  // An export-declaration shall not appear directly or indirectly within
552  // an unnamed namespace [...]
553  if (ND->isAnonymousNamespace()) {
554  Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
555  Diag(ND->getLocation(), diag::note_anonymous_namespace);
556  // Don't diagnose internal-linkage declarations in this region.
557  D->setInvalidDecl();
558  break;
559  }
560 
561  // A declaration is exported if it is [...] a namespace-definition
562  // that contains an exported declaration.
563  //
564  // Defer exporting the namespace until after we leave it, in order to
565  // avoid marking all subsequent declarations in the namespace as exported.
566  if (!DeferredExportedNamespaces.insert(ND).second)
567  break;
568  }
569  }
570 
571  // [...] its declaration or declaration-seq shall not contain an
572  // export-declaration.
573  if (auto *ED = getEnclosingExportDecl(D)) {
574  Diag(ExportLoc, diag::err_export_within_export);
575  if (ED->hasBraces())
576  Diag(ED->getLocation(), diag::note_export);
577  }
578 
579  CurContext->addDecl(D);
580  PushDeclContext(S, D);
582  return D;
583 }
584 
585 static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
586  SourceLocation BlockStart);
587 
588 namespace {
589 enum class UnnamedDeclKind {
590  Empty,
591  StaticAssert,
592  Asm,
593  UsingDirective,
594  Context
595 };
596 }
597 
599  if (isa<EmptyDecl>(D))
600  return UnnamedDeclKind::Empty;
601  if (isa<StaticAssertDecl>(D))
602  return UnnamedDeclKind::StaticAssert;
603  if (isa<FileScopeAsmDecl>(D))
604  return UnnamedDeclKind::Asm;
605  if (isa<UsingDirectiveDecl>(D))
606  return UnnamedDeclKind::UsingDirective;
607  // Everything else either introduces one or more names or is ill-formed.
608  return llvm::None;
609 }
610 
611 unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
612  switch (UDK) {
613  case UnnamedDeclKind::Empty:
614  case UnnamedDeclKind::StaticAssert:
615  // Allow empty-declarations and static_asserts in an export block as an
616  // extension.
617  return InBlock ? diag::ext_export_no_name_block : diag::err_export_no_name;
618 
619  case UnnamedDeclKind::UsingDirective:
620  // Allow exporting using-directives as an extension.
621  return diag::ext_export_using_directive;
622 
623  case UnnamedDeclKind::Context:
624  // Allow exporting DeclContexts that transitively contain no declarations
625  // as an extension.
626  return diag::ext_export_no_names;
627 
629  return diag::err_export_no_name;
630  }
631  llvm_unreachable("unknown kind");
632 }
633 
635  SourceLocation BlockStart) {
636  S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
637  << (unsigned)UDK;
638  if (BlockStart.isValid())
639  S.Diag(BlockStart, diag::note_export);
640 }
641 
642 /// Check that it's valid to export \p D.
643 static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
644  // C++2a [module.interface]p3:
645  // An exported declaration shall declare at least one name
646  if (auto UDK = getUnnamedDeclKind(D))
647  diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
648 
649  // [...] shall not declare a name with internal linkage.
650  if (auto *ND = dyn_cast<NamedDecl>(D)) {
651  // Don't diagnose anonymous union objects; we'll diagnose their members
652  // instead.
653  if (ND->getDeclName() && ND->getFormalLinkage() == InternalLinkage) {
654  S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
655  if (BlockStart.isValid())
656  S.Diag(BlockStart, diag::note_export);
657  }
658  }
659 
660  // C++2a [module.interface]p5:
661  // all entities to which all of the using-declarators ultimately refer
662  // shall have been introduced with a name having external linkage
663  if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
664  NamedDecl *Target = USD->getUnderlyingDecl();
665  if (Target->getFormalLinkage() == InternalLinkage) {
666  S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
667  S.Diag(Target->getLocation(), diag::note_using_decl_target);
668  if (BlockStart.isValid())
669  S.Diag(BlockStart, diag::note_export);
670  }
671  }
672 
673  // Recurse into namespace-scope DeclContexts. (Only namespace-scope
674  // declarations are exported.)
675  if (auto *DC = dyn_cast<DeclContext>(D))
676  if (DC->getRedeclContext()->isFileContext() && !isa<EnumDecl>(D))
677  return checkExportedDeclContext(S, DC, BlockStart);
678  return false;
679 }
680 
681 /// Check that it's valid to export all the declarations in \p DC.
683  SourceLocation BlockStart) {
684  bool AllUnnamed = true;
685  for (auto *D : DC->decls())
686  AllUnnamed &= checkExportedDecl(S, D, BlockStart);
687  return AllUnnamed;
688 }
689 
690 /// Complete the definition of an export declaration.
692  auto *ED = cast<ExportDecl>(D);
693  if (RBraceLoc.isValid())
694  ED->setRBraceLoc(RBraceLoc);
695 
696  PopDeclContext();
697 
698  if (!D->isInvalidDecl()) {
699  SourceLocation BlockStart =
700  ED->hasBraces() ? ED->getBeginLoc() : SourceLocation();
701  for (auto *Child : ED->decls()) {
702  if (checkExportedDecl(*this, Child, BlockStart)) {
703  // If a top-level child is a linkage-spec declaration, it might contain
704  // no declarations (transitively), in which case it's ill-formed.
705  diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
706  BlockStart);
707  }
708  }
709  }
710 
711  return D;
712 }
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
DeclResult ActOnModuleImport(SourceLocation StartLoc, SourceLocation ExportLoc, SourceLocation ImportLoc, ModuleIdPath Path)
The parser has processed a module import declaration.
Definition: SemaModule.cpp:309
DeclGroupPtrTy ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc, SourceLocation PrivateLoc)
The parser has processed a private-module-fragment declaration that begins the definition of the priv...
Definition: SemaModule.cpp:248
This declaration has an owning module, but is only visible to lookups that occur within that module...
static llvm::Optional< UnnamedDeclKind > getUnnamedDeclKind(Decl *D)
Definition: SemaModule.cpp:598
unsigned IsExternC
Whether this is an &#39;extern "C"&#39; module (which implicitly puts all headers in it within an &#39;extern "C"...
Definition: Module.h:237
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition: Sema.h:1375
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:88
bool isModuleVisible(const Module *M, bool ModulePrivate=false)
Wrapper for void* pointer.
Definition: Ownership.h:50
This is a module that was defined by a module map and built out of header files.
Definition: Module.h:75
static void checkModuleImportContext(Sema &S, Module *M, SourceLocation ImportLoc, DeclContext *DC, bool FromInclude=false)
Definition: SemaModule.cpp:22
Compiling a C++ modules TS module interface unit.
Definition: LangOptions.h:84
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition: DeclBase.h:2028
bool isInvalidDecl() const
Definition: DeclBase.h:553
This is the private module fragment within some C++ module.
Definition: Module.h:84
Linkage getFormalLinkage() const
Get the linkage from a semantic point of view.
Definition: Decl.h:378
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
ArrayRef< std::pair< IdentifierInfo *, SourceLocation > > ModuleIdPath
A sequence of identifier/location pairs used to describe a particular module or submodule, e.g., std.vector.
Definition: ModuleLoader.h:32
Compiling a module from a module map.
Definition: LangOptions.h:78
Describes a module or submodule.
Definition: Module.h:64
StringRef getTopLevelModuleName() const
Retrieve the name of the top-level module.
Definition: Module.h:467
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:213
Module * Parent
The parent of this module.
Definition: Module.h:92
void ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
The parser has processed a module import translated from a #include or similar preprocessing directiv...
Definition: SemaModule.cpp:406
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:40
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC)...
Definition: DeclBase.h:828
static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart)
Check that it&#39;s valid to export D.
Definition: SemaModule.cpp:643
static ImportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, ArrayRef< SourceLocation > IdentifierLocs)
Create a new module import declaration.
Definition: Decl.cpp:4853
Sema - This implements semantic analysis and AST building for C.
Definition: Sema.h:331
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:1795
ModuleDeclKind
Definition: Sema.h:2330
Compiling a module from a list of header files.
Definition: LangOptions.h:81
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:132
Defines the clang::Preprocessor interface.
Not compiling a module interface at all.
Definition: LangOptions.h:75
bool isFileContext() const
Definition: DeclBase.h:1849
UnnamedDeclKind
Definition: SemaModule.cpp:589
Decl * ActOnFinishExportDecl(Scope *S, Decl *ExportDecl, SourceLocation RBraceLoc)
Complete the definition of an export declaration.
Definition: SemaModule.cpp:691
Module(StringRef Name, SourceLocation DefinitionLoc, Module *Parent, bool IsFramework, bool IsExplicit, unsigned VisibilityID)
Construct a new module or submodule.
Definition: Module.cpp:37
This declaration has an owning module, and is visible when that module is imported.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:1779
void BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod)
Definition: SemaModule.cpp:411
Represents a C++ Modules TS module export declaration.
Definition: Decl.h:4310
This declaration has an owning module, but is globally visible (typically because its owning module i...
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
Definition: Ownership.h:153
Encodes a location in the source.
static ExportDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation ExportLoc)
Definition: Decl.cpp:4899
void setModuleOwnershipKind(ModuleOwnershipKind MOK)
Set whether this declaration is hidden from name lookup.
Definition: DeclBase.h:791
static bool checkExportedDeclContext(Sema &S, DeclContext *DC, SourceLocation BlockStart)
Check that it&#39;s valid to export all the declarations in DC.
Definition: SemaModule.cpp:682
DeclGroupPtrTy ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc)
The parser has processed a global-module-fragment declaration that begins the definition of the globa...
Definition: SemaModule.cpp:60
This is a fragment of the global module within some C++ module.
Definition: Module.h:81
Decl * ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc, SourceLocation LBraceLoc)
We have parsed the start of an export declaration, including the &#39;{&#39; (if present).
Definition: SemaModule.cpp:525
static ImportDecl * CreateImplicit(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, Module *Imported, SourceLocation EndLoc)
Create a new module import declaration for an implicitly-generated import.
Definition: Decl.cpp:4861
Describes a module import declaration, which makes the contents of the named module visible in the cu...
Definition: Decl.h:4245
void createImplicitModuleImportForErrorRecovery(SourceLocation Loc, Module *Mod)
Create an implicit import of the given module at the given source location, for error recovery...
Definition: SemaModule.cpp:504
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1271
void ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod)
The parsed has entered a submodule.
Definition: SemaModule.cpp:440
unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock)
Definition: SemaModule.cpp:611
This declaration is not owned by a module.
All of the names in this module are visible.
Definition: Module.h:277
Assembly: we accept this only so that we can preprocess it.
static const ExportDecl * getEnclosingExportDecl(const Decl *D)
Determine whether D is lexically within an export-declaration.
Definition: SemaModule.cpp:336
DeclContext * getRedeclContext()
getRedeclContext - Retrieve the context in which an entity conflicts with other entities of the same ...
Definition: DeclBase.cpp:1744
DeclGroupPtrTy ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc, ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl)
The parser has processed a module-declaration that begins the definition of a module interface or imp...
Definition: SemaModule.cpp:93
Internal linkage, which indicates that the entity can be referred to from within the translation unit...
Definition: Linkage.h:31
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition: Diagnostic.h:92
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1521
static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D, SourceLocation BlockStart)
Definition: SemaModule.cpp:634
void setRBraceLoc(SourceLocation L)
Definition: Decl.h:4330
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1008
void addModuleInitializer(Module *M, Decl *Init)
Add a declaration to the list of declarations that are initialized for a module.
The top declaration context.
Definition: Decl.h:107
void ActOnModuleEnd(SourceLocation DirectiveLoc, Module *Mod)
The parser has left a submodule.
Definition: SemaModule.cpp:464
A trivial tuple used to represent a source range.
This represents a decl that may have a name.
Definition: Decl.h:248
TranslationUnitDecl * getTranslationUnitDecl()
Definition: DeclBase.cpp:362
SourceLocation getLocation() const
Definition: DeclBase.h:429
This is a C++ Modules TS module interface unit.
Definition: Module.h:78
The translation unit is a module.
Definition: LangOptions.h:387