Coverage Report

Created: 2019-07-24 05:18

/Users/buildslave/jenkins/workspace/clang-stage2-coverage-R/llvm/tools/clang/lib/Sema/SemaModule.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- SemaModule.cpp - Semantic Analysis for Modules -------------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
//  This file implements semantic analysis for modules (C++ modules syntax,
10
//  Objective-C modules syntax, and Clang header modules).
11
//
12
//===----------------------------------------------------------------------===//
13
14
#include "clang/AST/ASTConsumer.h"
15
#include "clang/Lex/HeaderSearch.h"
16
#include "clang/Lex/Preprocessor.h"
17
#include "clang/Sema/SemaInternal.h"
18
19
using namespace clang;
20
using namespace sema;
21
22
static void checkModuleImportContext(Sema &S, Module *M,
23
                                     SourceLocation ImportLoc, DeclContext *DC,
24
5.11k
                                     bool FromInclude = false) {
25
5.11k
  SourceLocation ExternCLoc;
26
5.11k
27
5.11k
  if (auto *LSD = dyn_cast<LinkageSpecDecl>(DC)) {
28
30
    switch (LSD->getLanguage()) {
29
30
    case LinkageSpecDecl::lang_c:
30
23
      if (ExternCLoc.isInvalid())
31
23
        ExternCLoc = LSD->getBeginLoc();
32
23
      break;
33
30
    case LinkageSpecDecl::lang_cxx:
34
7
      break;
35
30
    }
36
30
    DC = LSD->getParent();
37
30
  }
38
5.11k
39
5.12k
  
while (5.11k
isa<LinkageSpecDecl>(DC) ||
isa<ExportDecl>(DC)5.11k
)
40
6
    DC = DC->getParent();
41
5.11k
42
5.11k
  if (!isa<TranslationUnitDecl>(DC)) {
43
19
    S.Diag(ImportLoc, (FromInclude && S.isModuleVisible(M))
44
19
                          ? 
diag::ext_module_import_not_at_top_level_noop10
45
19
                          : 
diag::err_module_import_not_at_top_level_fatal9
)
46
19
        << M->getFullModuleName() << DC;
47
19
    S.Diag(cast<Decl>(DC)->getBeginLoc(),
48
19
           diag::note_module_import_not_at_top_level)
49
19
        << DC;
50
5.09k
  } else if (!M->IsExternC && 
ExternCLoc.isValid()4.79k
) {
51
4
    S.Diag(ImportLoc, diag::ext_module_import_in_extern_c)
52
4
      << M->getFullModuleName();
53
4
    S.Diag(ExternCLoc, diag::note_extern_c_begins_here);
54
4
  }
55
5.11k
}
56
57
Sema::DeclGroupPtrTy
58
135
Sema::ActOnGlobalModuleFragmentDecl(SourceLocation ModuleLoc) {
59
135
  if (!ModuleScopes.empty() &&
60
135
      
ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment0
) {
61
0
    // Under -std=c++2a -fmodules-ts, we can find an explicit 'module;' after
62
0
    // already implicitly entering the global module fragment. That's OK.
63
0
    assert(getLangOpts().CPlusPlusModules && getLangOpts().ModulesTS &&
64
0
           "unexpectedly encountered multiple global module fragment decls");
65
0
    ModuleScopes.back().BeginLoc = ModuleLoc;
66
0
    return nullptr;
67
0
  }
68
135
69
135
  // We start in the global module; all those declarations are implicitly
70
135
  // module-private (though they do not have module linkage).
71
135
  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
72
135
  auto *GlobalModule = Map.createGlobalModuleFragmentForModuleUnit(ModuleLoc);
73
135
  assert(GlobalModule && "module creation should not fail");
74
135
75
135
  // Enter the scope of the global module.
76
135
  ModuleScopes.push_back({});
77
135
  ModuleScopes.back().BeginLoc = ModuleLoc;
78
135
  ModuleScopes.back().Module = GlobalModule;
79
135
  VisibleModules.setVisible(GlobalModule, ModuleLoc);
80
135
81
135
  // All declarations created from now on are owned by the global module.
82
135
  auto *TU = Context.getTranslationUnitDecl();
83
135
  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::Visible);
84
135
  TU->setLocalOwningModule(GlobalModule);
85
135
86
135
  // FIXME: Consider creating an explicit representation of this declaration.
87
135
  return nullptr;
88
135
}
89
90
Sema::DeclGroupPtrTy
91
Sema::ActOnModuleDecl(SourceLocation StartLoc, SourceLocation ModuleLoc,
92
111
                      ModuleDeclKind MDK, ModuleIdPath Path, bool IsFirstDecl) {
93
111
  assert((getLangOpts().ModulesTS || getLangOpts().CPlusPlusModules) &&
94
111
         "should only have module decl in Modules TS or C++20");
95
111
96
111
  // A module implementation unit requires that we are not compiling a module
97
111
  // of any kind. A module interface unit requires that we are not compiling a
98
111
  // module map.
99
111
  switch (getLangOpts().getCompilingModule()) {
100
111
  case LangOptions::CMK_None:
101
63
    // It's OK to compile a module interface as a normal translation unit.
102
63
    break;
103
111
104
111
  case LangOptions::CMK_ModuleInterface:
105
48
    if (MDK != ModuleDeclKind::Implementation)
106
47
      break;
107
1
108
1
    // We were asked to compile a module interface unit but this is a module
109
1
    // implementation unit. That indicates the 'export' is missing.
110
1
    Diag(ModuleLoc, diag::err_module_interface_implementation_mismatch)
111
1
      << FixItHint::CreateInsertion(ModuleLoc, "export ");
112
1
    MDK = ModuleDeclKind::Interface;
113
1
    break;
114
1
115
1
  case LangOptions::CMK_ModuleMap:
116
0
    Diag(ModuleLoc, diag::err_module_decl_in_module_map_module);
117
0
    return nullptr;
118
1
119
1
  case LangOptions::CMK_HeaderModule:
120
0
    Diag(ModuleLoc, diag::err_module_decl_in_header_module);
121
0
    return nullptr;
122
111
  }
123
111
124
111
  assert(ModuleScopes.size() <= 1 && "expected to be at global module scope");
125
111
126
111
  // FIXME: Most of this work should be done by the preprocessor rather than
127
111
  // here, in order to support macro import.
128
111
129
111
  // Only one module-declaration is permitted per source file.
130
111
  if (!ModuleScopes.empty() &&
131
111
      
ModuleScopes.back().Module->isModulePurview()89
) {
132
4
    Diag(ModuleLoc, diag::err_module_redeclaration);
133
4
    Diag(VisibleModules.getImportLoc(ModuleScopes.back().Module),
134
4
         diag::note_prev_module_declaration);
135
4
    return nullptr;
136
4
  }
137
107
138
107
  // Find the global module fragment we're adopting into this module, if any.
139
107
  Module *GlobalModuleFragment = nullptr;
140
107
  if (!ModuleScopes.empty() &&
141
107
      
ModuleScopes.back().Module->Kind == Module::GlobalModuleFragment85
)
142
85
    GlobalModuleFragment = ModuleScopes.back().Module;
143
107
144
107
  // In C++20, the module-declaration must be the first declaration if there
145
107
  // is no global module fragment.
146
107
  if (getLangOpts().CPlusPlusModules && 
!IsFirstDecl33
&&
!GlobalModuleFragment13
) {
147
2
    Diag(ModuleLoc, diag::err_module_decl_not_at_start);
148
2
    SourceLocation BeginLoc =
149
2
        ModuleScopes.empty()
150
2
            ? SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID())
151
2
            : 
ModuleScopes.back().BeginLoc0
;
152
2
    if (BeginLoc.isValid()) {
153
2
      Diag(BeginLoc, diag::note_global_module_introducer_missing)
154
2
          << FixItHint::CreateInsertion(BeginLoc, "module;\n");
155
2
    }
156
2
  }
157
107
158
107
  // Flatten the dots in a module name. Unlike Clang's hierarchical module map
159
107
  // modules, the dots here are just another character that can appear in a
160
107
  // module name.
161
107
  std::string ModuleName;
162
112
  for (auto &Piece : Path) {
163
112
    if (!ModuleName.empty())
164
5
      ModuleName += ".";
165
112
    ModuleName += Piece.first->getName();
166
112
  }
167
107
168
107
  // If a module name was explicitly specified on the command line, it must be
169
107
  // correct.
170
107
  if (!getLangOpts().CurrentModule.empty() &&
171
107
      
getLangOpts().CurrentModule != ModuleName0
) {
172
0
    Diag(Path.front().second, diag::err_current_module_name_mismatch)
173
0
        << SourceRange(Path.front().second, Path.back().second)
174
0
        << getLangOpts().CurrentModule;
175
0
    return nullptr;
176
0
  }
177
107
  const_cast<LangOptions&>(getLangOpts()).CurrentModule = ModuleName;
178
107
179
107
  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
180
107
  Module *Mod;
181
107
182
107
  switch (MDK) {
183
107
  case ModuleDeclKind::Interface: {
184
83
    // We can't have parsed or imported a definition of this module or parsed a
185
83
    // module map defining it already.
186
83
    if (auto *M = Map.findModule(ModuleName)) {
187
4
      Diag(Path[0].second, diag::err_module_redefinition) << ModuleName;
188
4
      if (M->DefinitionLoc.isValid())
189
0
        Diag(M->DefinitionLoc, diag::note_prev_module_definition);
190
4
      else if (const auto *FE = M->getASTFile())
191
4
        Diag(M->DefinitionLoc, diag::note_prev_module_definition_from_ast_file)
192
4
            << FE->getName();
193
4
      Mod = M;
194
4
      break;
195
4
    }
196
79
197
79
    // Create a Module for the module that we're defining.
198
79
    Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
199
79
                                           GlobalModuleFragment);
200
79
    assert(Mod && "module creation should not fail");
201
79
    break;
202
79
  }
203
79
204
79
  case ModuleDeclKind::Implementation:
205
24
    std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc(
206
24
        PP.getIdentifierInfo(ModuleName), Path[0].second);
207
24
    Mod = getModuleLoader().loadModule(ModuleLoc, {ModuleNameLoc},
208
24
                                       Module::AllVisible,
209
24
                                       /*IsInclusionDirective=*/false);
210
24
    if (!Mod) {
211
2
      Diag(ModuleLoc, diag::err_module_not_defined) << ModuleName;
212
2
      // Create an empty module interface unit for error recovery.
213
2
      Mod = Map.createModuleForInterfaceUnit(ModuleLoc, ModuleName,
214
2
                                             GlobalModuleFragment);
215
2
    }
216
24
    break;
217
107
  }
218
107
219
107
  if (!GlobalModuleFragment) {
220
22
    ModuleScopes.push_back({});
221
22
    if (getLangOpts().ModulesLocalVisibility)
222
22
      ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
223
85
  } else {
224
85
    // We're done with the global module fragment now.
225
85
    ActOnEndOfTranslationUnitFragment(TUFragmentKind::Global);
226
85
  }
227
107
228
107
  // Switch from the global module fragment (if any) to the named module.
229
107
  ModuleScopes.back().BeginLoc = StartLoc;
230
107
  ModuleScopes.back().Module = Mod;
231
107
  ModuleScopes.back().ModuleInterface = MDK != ModuleDeclKind::Implementation;
232
107
  VisibleModules.setVisible(Mod, ModuleLoc);
233
107
234
107
  // From now on, we have an owning module for all declarations we see.
235
107
  // However, those declarations are module-private unless explicitly
236
107
  // exported.
237
107
  auto *TU = Context.getTranslationUnitDecl();
238
107
  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
239
107
  TU->setLocalOwningModule(Mod);
240
107
241
107
  // FIXME: Create a ModuleDecl.
242
107
  return nullptr;
243
107
}
244
245
Sema::DeclGroupPtrTy
246
Sema::ActOnPrivateModuleFragmentDecl(SourceLocation ModuleLoc,
247
13
                                     SourceLocation PrivateLoc) {
248
13
  // C++20 [basic.link]/2:
249
13
  //   A private-module-fragment shall appear only in a primary module
250
13
  //   interface unit.
251
13
  switch (ModuleScopes.empty() ? 
Module::GlobalModuleFragment1
252
13
                               : 
ModuleScopes.back().Module->Kind12
) {
253
13
  case Module::ModuleMapModule:
254
2
  case Module::GlobalModuleFragment:
255
2
    Diag(PrivateLoc, diag::err_private_module_fragment_not_module);
256
2
    return nullptr;
257
2
258
3
  case Module::PrivateModuleFragment:
259
3
    Diag(PrivateLoc, diag::err_private_module_fragment_redefined);
260
3
    Diag(ModuleScopes.back().BeginLoc, diag::note_previous_definition);
261
3
    return nullptr;
262
2
263
8
  case Module::ModuleInterfaceUnit:
264
8
    break;
265
8
  }
266
8
267
8
  if (!ModuleScopes.back().ModuleInterface) {
268
1
    Diag(PrivateLoc, diag::err_private_module_fragment_not_module_interface);
269
1
    Diag(ModuleScopes.back().BeginLoc,
270
1
         diag::note_not_module_interface_add_export)
271
1
        << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
272
1
    return nullptr;
273
1
  }
274
7
275
7
  // FIXME: Check this isn't a module interface partition.
276
7
  // FIXME: Check that this translation unit does not import any partitions;
277
7
  // such imports would violate [basic.link]/2's "shall be the only module unit"
278
7
  // restriction.
279
7
280
7
  // We've finished the public fragment of the translation unit.
281
7
  ActOnEndOfTranslationUnitFragment(TUFragmentKind::Normal);
282
7
283
7
  auto &Map = PP.getHeaderSearchInfo().getModuleMap();
284
7
  Module *PrivateModuleFragment =
285
7
      Map.createPrivateModuleFragmentForInterfaceUnit(
286
7
          ModuleScopes.back().Module, PrivateLoc);
287
7
  assert(PrivateModuleFragment && "module creation should not fail");
288
7
289
7
  // Enter the scope of the private module fragment.
290
7
  ModuleScopes.push_back({});
291
7
  ModuleScopes.back().BeginLoc = ModuleLoc;
292
7
  ModuleScopes.back().Module = PrivateModuleFragment;
293
7
  ModuleScopes.back().ModuleInterface = true;
294
7
  VisibleModules.setVisible(PrivateModuleFragment, ModuleLoc);
295
7
296
7
  // All declarations created from now on are scoped to the private module
297
7
  // fragment (and are neither visible nor reachable in importers of the module
298
7
  // interface).
299
7
  auto *TU = Context.getTranslationUnitDecl();
300
7
  TU->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
301
7
  TU->setLocalOwningModule(PrivateModuleFragment);
302
7
303
7
  // FIXME: Consider creating an explicit representation of this declaration.
304
7
  return nullptr;
305
7
}
306
307
DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
308
                                   SourceLocation ExportLoc,
309
                                   SourceLocation ImportLoc,
310
899
                                   ModuleIdPath Path) {
311
899
  // Flatten the module path for a Modules TS module name.
312
899
  std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
313
899
  if (getLangOpts().ModulesTS) {
314
68
    std::string ModuleName;
315
75
    for (auto &Piece : Path) {
316
75
      if (!ModuleName.empty())
317
7
        ModuleName += ".";
318
75
      ModuleName += Piece.first->getName();
319
75
    }
320
68
    ModuleNameLoc = {PP.getIdentifierInfo(ModuleName), Path[0].second};
321
68
    Path = ModuleIdPath(ModuleNameLoc);
322
68
  }
323
899
324
899
  Module *Mod =
325
899
      getModuleLoader().loadModule(ImportLoc, Path, Module::AllVisible,
326
899
                                   /*IsInclusionDirective=*/false);
327
899
  if (!Mod)
328
88
    return true;
329
811
330
811
  return ActOnModuleImport(StartLoc, ExportLoc, ImportLoc, Mod, Path);
331
811
}
332
333
/// Determine whether \p D is lexically within an export-declaration.
334
120
static const ExportDecl *getEnclosingExportDecl(const Decl *D) {
335
246
  for (auto *DC = D->getLexicalDeclContext(); DC; 
DC = DC->getLexicalParent()126
)
336
133
    if (auto *ED = dyn_cast<ExportDecl>(DC))
337
7
      return ED;
338
120
  
return nullptr113
;
339
120
}
340
341
DeclResult Sema::ActOnModuleImport(SourceLocation StartLoc,
342
                                   SourceLocation ExportLoc,
343
                                   SourceLocation ImportLoc,
344
813
                                   Module *Mod, ModuleIdPath Path) {
345
813
  VisibleModules.setVisible(Mod, ImportLoc);
346
813
347
813
  checkModuleImportContext(*this, Mod, ImportLoc, CurContext);
348
813
349
813
  // FIXME: we should support importing a submodule within a different submodule
350
813
  // of the same top-level module. Until we do, make it an error rather than
351
813
  // silently ignoring the import.
352
813
  // Import-from-implementation is valid in the Modules TS. FIXME: Should we
353
813
  // warn on a redundant import of the current module?
354
813
  // FIXME: Import of a module from an implementation partition of the same
355
813
  // module is permitted.
356
813
  if (Mod->getTopLevelModuleName() == getLangOpts().CurrentModule &&
357
813
      
(10
getLangOpts().isCompilingModule()10
||
!getLangOpts().ModulesTS9
)) {
358
4
    Diag(ImportLoc, getLangOpts().isCompilingModule()
359
4
                        ? 
diag::err_module_self_import1
360
4
                        : 
diag::err_module_import_in_implementation3
)
361
4
        << Mod->getFullModuleName() << getLangOpts().CurrentModule;
362
4
  }
363
813
364
813
  SmallVector<SourceLocation, 2> IdentifierLocs;
365
813
  Module *ModCheck = Mod;
366
1.77k
  for (unsigned I = 0, N = Path.size(); I != N; 
++I961
) {
367
967
    // If we've run out of module parents, just drop the remaining identifiers.
368
967
    // We need the length to be consistent.
369
967
    if (!ModCheck)
370
6
      break;
371
961
    ModCheck = ModCheck->Parent;
372
961
373
961
    IdentifierLocs.push_back(Path[I].second);
374
961
  }
375
813
376
813
  // If this was a header import, pad out with dummy locations.
377
813
  // FIXME: Pass in and use the location of the header-name token in this case.
378
813
  if (Path.empty()) {
379
6
    for (; ModCheck; 
ModCheck = ModCheck->Parent4
) {
380
4
      IdentifierLocs.push_back(SourceLocation());
381
4
    }
382
2
  }
383
813
384
813
  ImportDecl *Import = ImportDecl::Create(Context, CurContext, StartLoc,
385
813
                                          Mod, IdentifierLocs);
386
813
  CurContext->addDecl(Import);
387
813
388
813
  // Sequence initialization of the imported module before that of the current
389
813
  // module, if any.
390
813
  if (!ModuleScopes.empty())
391
206
    Context.addModuleInitializer(ModuleScopes.back().Module, Import);
392
813
393
813
  // Re-export the module if needed.
394
813
  if (!ModuleScopes.empty() && 
ModuleScopes.back().ModuleInterface206
) {
395
18
    if (ExportLoc.isValid() || 
getEnclosingExportDecl(Import)17
)
396
5
      getCurrentModule()->Exports.emplace_back(Mod, false);
397
795
  } else if (ExportLoc.isValid()) {
398
0
    Diag(ExportLoc, diag::err_export_not_in_module_interface);
399
0
  }
400
813
401
813
  return Import;
402
813
}
403
404
1.51k
void Sema::ActOnModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
405
1.51k
  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
406
1.51k
  BuildModuleInclude(DirectiveLoc, Mod);
407
1.51k
}
408
409
4.29k
void Sema::BuildModuleInclude(SourceLocation DirectiveLoc, Module *Mod) {
410
4.29k
  // Determine whether we're in the #include buffer for a module. The #includes
411
4.29k
  // in that buffer do not qualify as module imports; they're just an
412
4.29k
  // implementation detail of us building the module.
413
4.29k
  //
414
4.29k
  // FIXME: Should we even get ActOnModuleInclude calls for those?
415
4.29k
  bool IsInModuleIncludes =
416
4.29k
      TUKind == TU_Module &&
417
4.29k
      
getSourceManager().isWrittenInMainFile(DirectiveLoc)3.31k
;
418
4.29k
419
4.29k
  bool ShouldAddImport = !IsInModuleIncludes;
420
4.29k
421
4.29k
  // If this module import was due to an inclusion directive, create an
422
4.29k
  // implicit import declaration to capture it in the AST.
423
4.29k
  if (ShouldAddImport) {
424
3.91k
    TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
425
3.91k
    ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
426
3.91k
                                                     DirectiveLoc, Mod,
427
3.91k
                                                     DirectiveLoc);
428
3.91k
    if (!ModuleScopes.empty())
429
1.06k
      Context.addModuleInitializer(ModuleScopes.back().Module, ImportD);
430
3.91k
    TU->addDecl(ImportD);
431
3.91k
    Consumer.HandleImplicitImportDecl(ImportD);
432
3.91k
  }
433
4.29k
434
4.29k
  getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, DirectiveLoc);
435
4.29k
  VisibleModules.setVisible(Mod, DirectiveLoc);
436
4.29k
}
437
438
2.78k
void Sema::ActOnModuleBegin(SourceLocation DirectiveLoc, Module *Mod) {
439
2.78k
  checkModuleImportContext(*this, Mod, DirectiveLoc, CurContext, true);
440
2.78k
441
2.78k
  ModuleScopes.push_back({});
442
2.78k
  ModuleScopes.back().Module = Mod;
443
2.78k
  if (getLangOpts().ModulesLocalVisibility)
444
261
    ModuleScopes.back().OuterVisibleModules = std::move(VisibleModules);
445
2.78k
446
2.78k
  VisibleModules.setVisible(Mod, DirectiveLoc);
447
2.78k
448
2.78k
  // The enclosing context is now part of this module.
449
2.78k
  // FIXME: Consider creating a child DeclContext to hold the entities
450
2.78k
  // lexically within the module.
451
2.78k
  if (getLangOpts().trackLocalOwningModule()) {
452
5.44k
    for (auto *DC = CurContext; DC; 
DC = DC->getLexicalParent()2.73k
) {
453
2.73k
      cast<Decl>(DC)->setModuleOwnershipKind(
454
2.73k
          getLangOpts().ModulesLocalVisibility
455
2.73k
              ? 
Decl::ModuleOwnershipKind::VisibleWhenImported267
456
2.73k
              : 
Decl::ModuleOwnershipKind::Visible2.46k
);
457
2.73k
      cast<Decl>(DC)->setLocalOwningModule(Mod);
458
2.73k
    }
459
2.71k
  }
460
2.78k
}
461
462
2.78k
void Sema::ActOnModuleEnd(SourceLocation EomLoc, Module *Mod) {
463
2.78k
  if (getLangOpts().ModulesLocalVisibility) {
464
261
    VisibleModules = std::move(ModuleScopes.back().OuterVisibleModules);
465
261
    // Leaving a module hides namespace names, so our visible namespace cache
466
261
    // is now out of date.
467
261
    VisibleNamespaceCache.clear();
468
261
  }
469
2.78k
470
2.78k
  assert(!ModuleScopes.empty() && ModuleScopes.back().Module == Mod &&
471
2.78k
         "left the wrong module scope");
472
2.78k
  ModuleScopes.pop_back();
473
2.78k
474
2.78k
  // We got to the end of processing a local module. Create an
475
2.78k
  // ImportDecl as we would for an imported module.
476
2.78k
  FileID File = getSourceManager().getFileID(EomLoc);
477
2.78k
  SourceLocation DirectiveLoc;
478
2.78k
  if (EomLoc == getSourceManager().getLocForEndOfFile(File)) {
479
187
    // We reached the end of a #included module header. Use the #include loc.
480
187
    assert(File != getSourceManager().getMainFileID() &&
481
187
           "end of submodule in main source file");
482
187
    DirectiveLoc = getSourceManager().getIncludeLoc(File);
483
2.60k
  } else {
484
2.60k
    // We reached an EOM pragma. Use the pragma location.
485
2.60k
    DirectiveLoc = EomLoc;
486
2.60k
  }
487
2.78k
  BuildModuleInclude(DirectiveLoc, Mod);
488
2.78k
489
2.78k
  // Any further declarations are in whatever module we returned to.
490
2.78k
  if (getLangOpts().trackLocalOwningModule()) {
491
2.70k
    // The parser guarantees that this is the same context that we entered
492
2.70k
    // the module within.
493
5.43k
    for (auto *DC = CurContext; DC; 
DC = DC->getLexicalParent()2.72k
) {
494
2.72k
      cast<Decl>(DC)->setLocalOwningModule(getCurrentModule());
495
2.72k
      if (!getCurrentModule())
496
2.24k
        cast<Decl>(DC)->setModuleOwnershipKind(
497
2.24k
            Decl::ModuleOwnershipKind::Unowned);
498
2.72k
    }
499
2.70k
  }
500
2.78k
}
501
502
void Sema::createImplicitModuleImportForErrorRecovery(SourceLocation Loc,
503
662
                                                      Module *Mod) {
504
662
  // Bail if we're not allowed to implicitly import a module here.
505
662
  if (isSFINAEContext() || !getLangOpts().ModulesErrorRecovery ||
506
662
      
VisibleModules.isVisible(Mod)53
)
507
610
    return;
508
52
509
52
  // Create the implicit import declaration.
510
52
  TranslationUnitDecl *TU = getASTContext().getTranslationUnitDecl();
511
52
  ImportDecl *ImportD = ImportDecl::CreateImplicit(getASTContext(), TU,
512
52
                                                   Loc, Mod, Loc);
513
52
  TU->addDecl(ImportD);
514
52
  Consumer.HandleImplicitImportDecl(ImportD);
515
52
516
52
  // Make the module visible.
517
52
  getModuleLoader().makeModuleVisible(Mod, Module::AllVisible, Loc);
518
52
  VisibleModules.setVisible(Mod, Loc);
519
52
}
520
521
/// We have parsed the start of an export declaration, including the '{'
522
/// (if present).
523
Decl *Sema::ActOnStartExportDecl(Scope *S, SourceLocation ExportLoc,
524
103
                                 SourceLocation LBraceLoc) {
525
103
  ExportDecl *D = ExportDecl::Create(Context, CurContext, ExportLoc);
526
103
527
103
  // Set this temporarily so we know the export-declaration was braced.
528
103
  D->setRBraceLoc(LBraceLoc);
529
103
530
103
  // C++2a [module.interface]p1:
531
103
  //   An export-declaration shall appear only [...] in the purview of a module
532
103
  //   interface unit. An export-declaration shall not appear directly or
533
103
  //   indirectly within [...] a private-module-fragment.
534
103
  if (ModuleScopes.empty() || !ModuleScopes.back().Module->isModulePurview()) {
535
3
    Diag(ExportLoc, diag::err_export_not_in_module_interface) << 0;
536
100
  } else if (!ModuleScopes.back().ModuleInterface) {
537
3
    Diag(ExportLoc, diag::err_export_not_in_module_interface) << 1;
538
3
    Diag(ModuleScopes.back().BeginLoc,
539
3
         diag::note_not_module_interface_add_export)
540
3
        << FixItHint::CreateInsertion(ModuleScopes.back().BeginLoc, "export ");
541
97
  } else if (ModuleScopes.back().Module->Kind ==
542
97
             Module::PrivateModuleFragment) {
543
1
    Diag(ExportLoc, diag::err_export_in_private_module_fragment);
544
1
    Diag(ModuleScopes.back().BeginLoc, diag::note_private_module_fragment);
545
1
  }
546
103
547
216
  for (const DeclContext *DC = CurContext; DC; 
DC = DC->getLexicalParent()113
) {
548
116
    if (const auto *ND = dyn_cast<NamespaceDecl>(DC)) {
549
12
      //   An export-declaration shall not appear directly or indirectly within
550
12
      //   an unnamed namespace [...]
551
12
      if (ND->isAnonymousNamespace()) {
552
3
        Diag(ExportLoc, diag::err_export_within_anonymous_namespace);
553
3
        Diag(ND->getLocation(), diag::note_anonymous_namespace);
554
3
        // Don't diagnose internal-linkage declarations in this region.
555
3
        D->setInvalidDecl();
556
3
        break;
557
3
      }
558
9
559
9
      //   A declaration is exported if it is [...] a namespace-definition
560
9
      //   that contains an exported declaration.
561
9
      //
562
9
      // Defer exporting the namespace until after we leave it, in order to
563
9
      // avoid marking all subsequent declarations in the namespace as exported.
564
9
      if (!DeferredExportedNamespaces.insert(ND).second)
565
0
        break;
566
9
    }
567
116
  }
568
103
569
103
  //   [...] its declaration or declaration-seq shall not contain an
570
103
  //   export-declaration.
571
103
  if (auto *ED = getEnclosingExportDecl(D)) {
572
3
    Diag(ExportLoc, diag::err_export_within_export);
573
3
    if (ED->hasBraces())
574
2
      Diag(ED->getLocation(), diag::note_export);
575
3
  }
576
103
577
103
  CurContext->addDecl(D);
578
103
  PushDeclContext(S, D);
579
103
  D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
580
103
  return D;
581
103
}
582
583
static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
584
                                     SourceLocation BlockStart);
585
586
namespace {
587
enum class UnnamedDeclKind {
588
  Empty,
589
  StaticAssert,
590
  Asm,
591
  UsingDirective,
592
  Context
593
};
594
}
595
596
252
static llvm::Optional<UnnamedDeclKind> getUnnamedDeclKind(Decl *D) {
597
252
  if (isa<EmptyDecl>(D))
598
5
    return UnnamedDeclKind::Empty;
599
247
  if (isa<StaticAssertDecl>(D))
600
3
    return UnnamedDeclKind::StaticAssert;
601
244
  if (isa<FileScopeAsmDecl>(D))
602
1
    return UnnamedDeclKind::Asm;
603
243
  if (isa<UsingDirectiveDecl>(D))
604
2
    return UnnamedDeclKind::UsingDirective;
605
241
  // Everything else either introduces one or more names or is ill-formed.
606
241
  return llvm::None;
607
241
}
608
609
16
unsigned getUnnamedDeclDiag(UnnamedDeclKind UDK, bool InBlock) {
610
16
  switch (UDK) {
611
16
  case UnnamedDeclKind::Empty:
612
8
  case UnnamedDeclKind::StaticAssert:
613
8
    // Allow empty-declarations and static_asserts in an export block as an
614
8
    // extension.
615
8
    return InBlock ? 
diag::ext_export_no_name_block4
:
diag::err_export_no_name4
;
616
8
617
8
  case UnnamedDeclKind::UsingDirective:
618
2
    // Allow exporting using-directives as an extension.
619
2
    return diag::ext_export_using_directive;
620
8
621
8
  case UnnamedDeclKind::Context:
622
5
    // Allow exporting DeclContexts that transitively contain no declarations
623
5
    // as an extension.
624
5
    return diag::ext_export_no_names;
625
8
626
8
  case UnnamedDeclKind::Asm:
627
1
    return diag::err_export_no_name;
628
0
  }
629
0
  llvm_unreachable("unknown kind");
630
0
}
631
632
static void diagExportedUnnamedDecl(Sema &S, UnnamedDeclKind UDK, Decl *D,
633
16
                                    SourceLocation BlockStart) {
634
16
  S.Diag(D->getLocation(), getUnnamedDeclDiag(UDK, BlockStart.isValid()))
635
16
      << (unsigned)UDK;
636
16
  if (BlockStart.isValid())
637
6
    S.Diag(BlockStart, diag::note_export);
638
16
}
639
640
/// Check that it's valid to export \p D.
641
252
static bool checkExportedDecl(Sema &S, Decl *D, SourceLocation BlockStart) {
642
252
  // C++2a [module.interface]p3:
643
252
  //   An exported declaration shall declare at least one name
644
252
  if (auto UDK = getUnnamedDeclKind(D))
645
11
    diagExportedUnnamedDecl(S, *UDK, D, BlockStart);
646
252
647
252
  //   [...] shall not declare a name with internal linkage.
648
252
  if (auto *ND = dyn_cast<NamedDecl>(D)) {
649
228
    // Don't diagnose anonymous union objects; we'll diagnose their members
650
228
    // instead.
651
228
    if (ND->getDeclName() && 
ND->getFormalLinkage() == InternalLinkage211
) {
652
8
      S.Diag(ND->getLocation(), diag::err_export_internal) << ND;
653
8
      if (BlockStart.isValid())
654
2
        S.Diag(BlockStart, diag::note_export);
655
8
    }
656
228
  }
657
252
658
252
  // C++2a [module.interface]p5:
659
252
  //   all entities to which all of the using-declarators ultimately refer
660
252
  //   shall have been introduced with a name having external linkage
661
252
  if (auto *USD = dyn_cast<UsingShadowDecl>(D)) {
662
38
    NamedDecl *Target = USD->getUnderlyingDecl();
663
38
    if (Target->getFormalLinkage() == InternalLinkage) {
664
19
      S.Diag(USD->getLocation(), diag::err_export_using_internal) << Target;
665
19
      S.Diag(Target->getLocation(), diag::note_using_decl_target);
666
19
      if (BlockStart.isValid())
667
19
        S.Diag(BlockStart, diag::note_export);
668
19
    }
669
38
  }
670
252
671
252
  // Recurse into namespace-scope DeclContexts. (Only namespace-scope
672
252
  // declarations are exported.)
673
252
  if (auto *DC = dyn_cast<DeclContext>(D))
674
64
    if (DC->getRedeclContext()->isFileContext() && 
!isa<EnumDecl>(D)23
)
675
20
      return checkExportedDeclContext(S, DC, BlockStart);
676
232
  return false;
677
232
}
678
679
/// Check that it's valid to export all the declarations in \p DC.
680
static bool checkExportedDeclContext(Sema &S, DeclContext *DC,
681
20
                                     SourceLocation BlockStart) {
682
20
  bool AllUnnamed = true;
683
20
  for (auto *D : DC->decls())
684
50
    AllUnnamed &= checkExportedDecl(S, D, BlockStart);
685
20
  return AllUnnamed;
686
20
}
687
688
/// Complete the definition of an export declaration.
689
103
Decl *Sema::ActOnFinishExportDecl(Scope *S, Decl *D, SourceLocation RBraceLoc) {
690
103
  auto *ED = cast<ExportDecl>(D);
691
103
  if (RBraceLoc.isValid())
692
20
    ED->setRBraceLoc(RBraceLoc);
693
103
694
103
  PopDeclContext();
695
103
696
103
  if (!D->isInvalidDecl()) {
697
100
    SourceLocation BlockStart =
698
100
        ED->hasBraces() ? 
ED->getBeginLoc()20
:
SourceLocation()80
;
699
202
    for (auto *Child : ED->decls()) {
700
202
      if (checkExportedDecl(*this, Child, BlockStart)) {
701
5
        // If a top-level child is a linkage-spec declaration, it might contain
702
5
        // no declarations (transitively), in which case it's ill-formed.
703
5
        diagExportedUnnamedDecl(*this, UnnamedDeclKind::Context, Child,
704
5
                                BlockStart);
705
5
      }
706
202
    }
707
100
  }
708
103
709
103
  return D;
710
103
}