Coverage Report

Created: 2024-01-17 10:31

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