1//===- ModuleMap.cpp - Describe the layout of 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 defines the ModuleMap implementation, which describes the layout
10// of a module as it relates to headers.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/Lex/ModuleMap.h"
15#include "clang/Basic/CharInfo.h"
16#include "clang/Basic/Diagnostic.h"
17#include "clang/Basic/FileManager.h"
18#include "clang/Basic/LLVM.h"
19#include "clang/Basic/LangOptions.h"
20#include "clang/Basic/Module.h"
21#include "clang/Basic/SourceLocation.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/TargetInfo.h"
24#include "clang/Lex/HeaderSearch.h"
25#include "clang/Lex/HeaderSearchOptions.h"
26#include "clang/Lex/LexDiagnostic.h"
27#include "clang/Lex/ModuleMapFile.h"
28#include "llvm/ADT/DenseMap.h"
29#include "llvm/ADT/STLExtras.h"
30#include "llvm/ADT/SmallPtrSet.h"
31#include "llvm/ADT/SmallVector.h"
32#include "llvm/ADT/StringMap.h"
33#include "llvm/ADT/StringRef.h"
34#include "llvm/ADT/StringSwitch.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/ErrorHandling.h"
37#include "llvm/Support/Path.h"
38#include "llvm/Support/VirtualFileSystem.h"
39#include "llvm/Support/raw_ostream.h"
40#include <cassert>
41#include <cstring>
42#include <optional>
43#include <string>
44#include <system_error>
45#include <utility>
46
47using namespace clang;
48
49void ModuleMapCallbacks::anchor() {}
50
51void ModuleMap::resolveLinkAsDependencies(Module *Mod) {
52 auto PendingLinkAs = PendingLinkAsModule.find(Key: Mod->Name);
53 if (PendingLinkAs != PendingLinkAsModule.end()) {
54 for (auto &Name : PendingLinkAs->second) {
55 auto *M = findModule(Name: Name.getKey());
56 if (M)
57 M->UseExportAsModuleLinkName = true;
58 }
59 }
60}
61
62void ModuleMap::addLinkAsDependency(Module *Mod) {
63 if (findModule(Name: Mod->ExportAsModule))
64 Mod->UseExportAsModuleLinkName = true;
65 else
66 PendingLinkAsModule[Mod->ExportAsModule].insert(key: Mod->Name);
67}
68
69Module::HeaderKind ModuleMap::headerRoleToKind(ModuleHeaderRole Role) {
70 switch ((int)Role) {
71 case NormalHeader:
72 return Module::HK_Normal;
73 case PrivateHeader:
74 return Module::HK_Private;
75 case TextualHeader:
76 return Module::HK_Textual;
77 case PrivateHeader | TextualHeader:
78 return Module::HK_PrivateTextual;
79 case ExcludedHeader:
80 return Module::HK_Excluded;
81 }
82 llvm_unreachable("unknown header role");
83}
84
85ModuleMap::ModuleHeaderRole
86ModuleMap::headerKindToRole(Module::HeaderKind Kind) {
87 switch ((int)Kind) {
88 case Module::HK_Normal:
89 return NormalHeader;
90 case Module::HK_Private:
91 return PrivateHeader;
92 case Module::HK_Textual:
93 return TextualHeader;
94 case Module::HK_PrivateTextual:
95 return ModuleHeaderRole(PrivateHeader | TextualHeader);
96 case Module::HK_Excluded:
97 return ExcludedHeader;
98 }
99 llvm_unreachable("unknown header kind");
100}
101
102bool ModuleMap::isModular(ModuleHeaderRole Role) {
103 return !(Role & (ModuleMap::TextualHeader | ModuleMap::ExcludedHeader));
104}
105
106Module::ExportDecl
107ModuleMap::resolveExport(Module *Mod,
108 const Module::UnresolvedExportDecl &Unresolved,
109 bool Complain) const {
110 // We may have just a wildcard.
111 if (Unresolved.Id.empty()) {
112 assert(Unresolved.Wildcard && "Invalid unresolved export");
113 return Module::ExportDecl(nullptr, true);
114 }
115
116 // Resolve the module-id.
117 Module *Context = resolveModuleId(Id: Unresolved.Id, Mod, Complain);
118 if (!Context)
119 return {};
120
121 return Module::ExportDecl(Context, Unresolved.Wildcard);
122}
123
124Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
125 bool Complain) const {
126 // Find the starting module.
127 Module *Context = lookupModuleUnqualified(Name: Id[0].first, Context: Mod);
128 if (!Context) {
129 if (Complain)
130 Diags.Report(Loc: Id[0].second, DiagID: diag::err_mmap_missing_module_unqualified)
131 << Id[0].first << Mod->getFullModuleName();
132
133 return nullptr;
134 }
135
136 // Dig into the module path.
137 for (unsigned I = 1, N = Id.size(); I != N; ++I) {
138 Module *Sub = lookupModuleQualified(Name: Id[I].first, Context);
139 if (!Sub) {
140 if (Complain)
141 Diags.Report(Loc: Id[I].second, DiagID: diag::err_mmap_missing_module_qualified)
142 << Id[I].first << Context->getFullModuleName()
143 << SourceRange(Id[0].second, Id[I-1].second);
144
145 return nullptr;
146 }
147
148 Context = Sub;
149 }
150
151 return Context;
152}
153
154/// Append to \p Paths the set of paths needed to get to the
155/// subframework in which the given module lives.
156static void appendSubframeworkPaths(Module *Mod,
157 SmallVectorImpl<char> &Path) {
158 // Collect the framework names from the given module to the top-level module.
159 SmallVector<StringRef, 2> Paths;
160 for (; Mod; Mod = Mod->Parent) {
161 if (Mod->IsFramework)
162 Paths.push_back(Elt: Mod->Name);
163 }
164
165 if (Paths.empty())
166 return;
167
168 // Add Frameworks/Name.framework for each subframework.
169 for (StringRef Framework : llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Paths)))
170 llvm::sys::path::append(path&: Path, a: "Frameworks", b: Framework + ".framework");
171}
172
173OptionalFileEntryRef ModuleMap::findHeader(
174 Module *M, const Module::UnresolvedHeaderDirective &Header,
175 SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework) {
176 // Search for the header file within the module's home directory.
177 auto Directory = M->Directory;
178 SmallString<128> FullPathName(Directory->getName());
179
180 auto GetFile = [&](StringRef Filename) -> OptionalFileEntryRef {
181 auto File =
182 expectedToOptional(E: SourceMgr.getFileManager().getFileRef(Filename));
183 if (!File || (Header.Size && File->getSize() != *Header.Size) ||
184 (Header.ModTime && File->getModificationTime() != *Header.ModTime))
185 return std::nullopt;
186 return *File;
187 };
188
189 auto GetFrameworkFile = [&]() -> OptionalFileEntryRef {
190 unsigned FullPathLength = FullPathName.size();
191 appendSubframeworkPaths(Mod: M, Path&: RelativePathName);
192 unsigned RelativePathLength = RelativePathName.size();
193
194 // Check whether this file is in the public headers.
195 llvm::sys::path::append(path&: RelativePathName, a: "Headers", b: Header.FileName);
196 llvm::sys::path::append(path&: FullPathName, a: RelativePathName);
197 if (auto File = GetFile(FullPathName))
198 return File;
199
200 // Check whether this file is in the private headers.
201 // Ideally, private modules in the form 'FrameworkName.Private' should
202 // be defined as 'module FrameworkName.Private', and not as
203 // 'framework module FrameworkName.Private', since a 'Private.Framework'
204 // does not usually exist. However, since both are currently widely used
205 // for private modules, make sure we find the right path in both cases.
206 if (M->IsFramework && M->Name == "Private")
207 RelativePathName.clear();
208 else
209 RelativePathName.resize(N: RelativePathLength);
210 FullPathName.resize(N: FullPathLength);
211 llvm::sys::path::append(path&: RelativePathName, a: "PrivateHeaders",
212 b: Header.FileName);
213 llvm::sys::path::append(path&: FullPathName, a: RelativePathName);
214 return GetFile(FullPathName);
215 };
216
217 if (llvm::sys::path::is_absolute(path: Header.FileName)) {
218 RelativePathName.clear();
219 RelativePathName.append(in_start: Header.FileName.begin(), in_end: Header.FileName.end());
220 return GetFile(Header.FileName);
221 }
222
223 if (M->isPartOfFramework())
224 return GetFrameworkFile();
225
226 // Lookup for normal headers.
227 llvm::sys::path::append(path&: RelativePathName, a: Header.FileName);
228 llvm::sys::path::append(path&: FullPathName, a: RelativePathName);
229 auto NormalHdrFile = GetFile(FullPathName);
230
231 if (!NormalHdrFile && Directory->getName().ends_with(Suffix: ".framework")) {
232 // The lack of 'framework' keyword in a module declaration it's a simple
233 // mistake we can diagnose when the header exists within the proper
234 // framework style path.
235 FullPathName.assign(RHS: Directory->getName());
236 RelativePathName.clear();
237 if (GetFrameworkFile()) {
238 Diags.Report(Loc: Header.FileNameLoc,
239 DiagID: diag::warn_mmap_incomplete_framework_module_declaration)
240 << Header.FileName << M->getFullModuleName();
241 NeedsFramework = true;
242 }
243 return std::nullopt;
244 }
245
246 return NormalHdrFile;
247}
248
249/// Determine whether the given file name is the name of a builtin
250/// header, supplied by Clang to replace, override, or augment existing system
251/// headers.
252static bool isBuiltinHeaderName(StringRef FileName) {
253 return llvm::StringSwitch<bool>(FileName)
254 .Case(S: "float.h", Value: true)
255 .Case(S: "iso646.h", Value: true)
256 .Case(S: "limits.h", Value: true)
257 .Case(S: "stdalign.h", Value: true)
258 .Case(S: "stdarg.h", Value: true)
259 .Case(S: "stdatomic.h", Value: true)
260 .Case(S: "stdbool.h", Value: true)
261 .Case(S: "stdckdint.h", Value: true)
262 .Case(S: "stdcountof.h", Value: true)
263 .Case(S: "stddef.h", Value: true)
264 .Case(S: "stdint.h", Value: true)
265 .Case(S: "tgmath.h", Value: true)
266 .Case(S: "unwind.h", Value: true)
267 .Default(Value: false);
268}
269
270/// Determine whether the given module name is the name of a builtin
271/// module that is cyclic with a system module on some platforms.
272static bool isBuiltInModuleName(StringRef ModuleName) {
273 return llvm::StringSwitch<bool>(ModuleName)
274 .Case(S: "_Builtin_float", Value: true)
275 .Case(S: "_Builtin_inttypes", Value: true)
276 .Case(S: "_Builtin_iso646", Value: true)
277 .Case(S: "_Builtin_limits", Value: true)
278 .Case(S: "_Builtin_stdalign", Value: true)
279 .Case(S: "_Builtin_stdarg", Value: true)
280 .Case(S: "_Builtin_stdatomic", Value: true)
281 .Case(S: "_Builtin_stdbool", Value: true)
282 .Case(S: "_Builtin_stddef", Value: true)
283 .Case(S: "_Builtin_stdint", Value: true)
284 .Case(S: "_Builtin_stdnoreturn", Value: true)
285 .Case(S: "_Builtin_tgmath", Value: true)
286 .Case(S: "_Builtin_unwind", Value: true)
287 .Default(Value: false);
288}
289
290void ModuleMap::resolveHeader(Module *Mod,
291 const Module::UnresolvedHeaderDirective &Header,
292 bool &NeedsFramework) {
293 SmallString<128> RelativePathName;
294 if (OptionalFileEntryRef File =
295 findHeader(M: Mod, Header, RelativePathName, NeedsFramework)) {
296 if (Header.IsUmbrella) {
297 const DirectoryEntry *UmbrellaDir = &File->getDir().getDirEntry();
298 if (Module *UmbrellaMod = UmbrellaDirs[UmbrellaDir])
299 Diags.Report(Loc: Header.FileNameLoc, DiagID: diag::err_mmap_umbrella_clash)
300 << UmbrellaMod->getFullModuleName();
301 else
302 // Record this umbrella header.
303 setUmbrellaHeaderAsWritten(Mod, UmbrellaHeader: *File, NameAsWritten: Header.FileName,
304 PathRelativeToRootModuleDirectory: RelativePathName.str());
305 } else {
306 Module::Header H = {.NameAsWritten: Header.FileName, .PathRelativeToRootModuleDirectory: std::string(RelativePathName),
307 .Entry: *File};
308 addHeader(Mod, Header: H, Role: headerKindToRole(Kind: Header.Kind));
309 }
310 } else if (Header.HasBuiltinHeader && !Header.Size && !Header.ModTime) {
311 // There's a builtin header but no corresponding on-disk header. Assume
312 // this was supposed to modularize the builtin header alone.
313 } else if (Header.Kind == Module::HK_Excluded) {
314 // Ignore missing excluded header files. They're optional anyway.
315 } else {
316 // If we find a module that has a missing header, we mark this module as
317 // unavailable and store the header directive for displaying diagnostics.
318 Mod->MissingHeaders.push_back(Elt: Header);
319 // A missing header with stat information doesn't make the module
320 // unavailable; this keeps our behavior consistent as headers are lazily
321 // resolved. (Such a module still can't be built though, except from
322 // preprocessed source.)
323 if (!Header.Size && !Header.ModTime)
324 Mod->markUnavailable(/*Unimportable=*/false);
325 }
326}
327
328bool ModuleMap::resolveAsBuiltinHeader(
329 Module *Mod, const Module::UnresolvedHeaderDirective &Header) {
330 if (Header.Kind == Module::HK_Excluded ||
331 llvm::sys::path::is_absolute(path: Header.FileName) ||
332 Mod->isPartOfFramework() || !Mod->IsSystem || Header.IsUmbrella ||
333 !BuiltinIncludeDir || BuiltinIncludeDir == Mod->Directory ||
334 !LangOpts.BuiltinHeadersInSystemModules || !isBuiltinHeaderName(FileName: Header.FileName))
335 return false;
336
337 // This is a system module with a top-level header. This header
338 // may have a counterpart (or replacement) in the set of headers
339 // supplied by Clang. Find that builtin header.
340 SmallString<128> Path;
341 llvm::sys::path::append(path&: Path, a: BuiltinIncludeDir->getName(), b: Header.FileName);
342 auto File = SourceMgr.getFileManager().getOptionalFileRef(Filename: Path);
343 if (!File)
344 return false;
345
346 Module::Header H = {.NameAsWritten: Header.FileName, .PathRelativeToRootModuleDirectory: Header.FileName, .Entry: *File};
347 auto Role = headerKindToRole(Kind: Header.Kind);
348 addHeader(Mod, Header: H, Role);
349 return true;
350}
351
352ModuleMap::ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
353 const LangOptions &LangOpts, const TargetInfo *Target,
354 HeaderSearch &HeaderInfo)
355 : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
356 HeaderInfo(HeaderInfo) {
357}
358
359ModuleMap::~ModuleMap() = default;
360
361void ModuleMap::setTarget(const TargetInfo &Target) {
362 assert((!this->Target || this->Target == &Target) &&
363 "Improper target override");
364 this->Target = &Target;
365}
366
367/// "Sanitize" a filename so that it can be used as an identifier.
368static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
369 SmallVectorImpl<char> &Buffer) {
370 if (Name.empty())
371 return Name;
372
373 if (!isValidAsciiIdentifier(S: Name)) {
374 // If we don't already have something with the form of an identifier,
375 // create a buffer with the sanitized name.
376 Buffer.clear();
377 if (isDigit(c: Name[0]))
378 Buffer.push_back(Elt: '_');
379 Buffer.reserve(N: Buffer.size() + Name.size());
380 for (unsigned I = 0, N = Name.size(); I != N; ++I) {
381 if (isAsciiIdentifierContinue(c: Name[I]))
382 Buffer.push_back(Elt: Name[I]);
383 else
384 Buffer.push_back(Elt: '_');
385 }
386
387 Name = StringRef(Buffer.data(), Buffer.size());
388 }
389
390 while (llvm::StringSwitch<bool>(Name)
391#define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
392#define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
393#include "clang/Basic/TokenKinds.def"
394 .Default(Value: false)) {
395 if (Name.data() != Buffer.data())
396 Buffer.append(in_start: Name.begin(), in_end: Name.end());
397 Buffer.push_back(Elt: '_');
398 Name = StringRef(Buffer.data(), Buffer.size());
399 }
400
401 return Name;
402}
403
404bool ModuleMap::isBuiltinHeader(FileEntryRef File) {
405 return File.getDir() == BuiltinIncludeDir && LangOpts.BuiltinHeadersInSystemModules &&
406 isBuiltinHeaderName(FileName: llvm::sys::path::filename(path: File.getName()));
407}
408
409bool ModuleMap::shouldImportRelativeToBuiltinIncludeDir(StringRef FileName,
410 Module *Module) const {
411 return LangOpts.BuiltinHeadersInSystemModules && BuiltinIncludeDir &&
412 Module->IsSystem && !Module->isPartOfFramework() &&
413 isBuiltinHeaderName(FileName);
414}
415
416ModuleMap::HeadersMap::iterator ModuleMap::findKnownHeader(FileEntryRef File) {
417 resolveHeaderDirectives(File);
418 HeadersMap::iterator Known = Headers.find(Val: File);
419 if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
420 Known == Headers.end() && ModuleMap::isBuiltinHeader(File)) {
421 HeaderInfo.loadTopLevelSystemModules();
422 return Headers.find(Val: File);
423 }
424 return Known;
425}
426
427ModuleMap::KnownHeader ModuleMap::findHeaderInUmbrellaDirs(
428 FileEntryRef File, SmallVectorImpl<DirectoryEntryRef> &IntermediateDirs) {
429 if (UmbrellaDirs.empty())
430 return {};
431
432 OptionalDirectoryEntryRef Dir = File.getDir();
433
434 // Note: as an egregious but useful hack we use the real path here, because
435 // frameworks moving from top-level frameworks to embedded frameworks tend
436 // to be symlinked from the top-level location to the embedded location,
437 // and we need to resolve lookups as if we had found the embedded location.
438 StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir: *Dir);
439
440 // Keep walking up the directory hierarchy, looking for a directory with
441 // an umbrella header.
442 do {
443 auto KnownDir = UmbrellaDirs.find(Val: *Dir);
444 if (KnownDir != UmbrellaDirs.end())
445 return KnownHeader(KnownDir->second, NormalHeader);
446
447 IntermediateDirs.push_back(Elt: *Dir);
448
449 // Retrieve our parent path.
450 DirName = llvm::sys::path::parent_path(path: DirName);
451 if (DirName.empty())
452 break;
453
454 // Resolve the parent path to a directory entry.
455 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName);
456 } while (Dir);
457 return {};
458}
459
460static bool violatesPrivateInclude(Module *RequestingModule,
461 const FileEntry *IncFileEnt,
462 ModuleMap::KnownHeader Header) {
463#ifndef NDEBUG
464 if (Header.getRole() & ModuleMap::PrivateHeader) {
465 // Check for consistency between the module header role
466 // as obtained from the lookup and as obtained from the module.
467 // This check is not cheap, so enable it only for debugging.
468 bool IsPrivate = false;
469 ArrayRef<Module::Header> HeaderList[] = {
470 Header.getModule()->getHeaders(Module::HK_Private),
471 Header.getModule()->getHeaders(Module::HK_PrivateTextual)};
472 for (auto Hs : HeaderList)
473 IsPrivate |= llvm::any_of(
474 Hs, [&](const Module::Header &H) { return H.Entry == IncFileEnt; });
475 assert(IsPrivate && "inconsistent headers and roles");
476 }
477#endif
478 return !Header.isAccessibleFrom(M: RequestingModule);
479}
480
481static Module *getTopLevelOrNull(Module *M) {
482 return M ? M->getTopLevelModule() : nullptr;
483}
484
485void ModuleMap::diagnoseHeaderInclusion(Module *RequestingModule,
486 bool RequestingModuleIsModuleInterface,
487 SourceLocation FilenameLoc,
488 StringRef Filename, FileEntryRef File) {
489 // No errors for indirect modules. This may be a bit of a problem for modules
490 // with no source files.
491 if (getTopLevelOrNull(M: RequestingModule) != getTopLevelOrNull(M: SourceModule))
492 return;
493
494 if (RequestingModule) {
495 resolveUses(Mod: RequestingModule, /*Complain=*/false);
496 resolveHeaderDirectives(Mod: RequestingModule, /*File=*/std::nullopt);
497 }
498
499 bool Excluded = false;
500 Module *Private = nullptr;
501 Module *NotUsed = nullptr;
502
503 HeadersMap::iterator Known = findKnownHeader(File);
504 if (Known != Headers.end()) {
505 for (const KnownHeader &Header : Known->second) {
506 // Excluded headers don't really belong to a module.
507 if (Header.getRole() == ModuleMap::ExcludedHeader) {
508 Excluded = true;
509 continue;
510 }
511
512 // Remember private headers for later printing of a diagnostic.
513 if (violatesPrivateInclude(RequestingModule, IncFileEnt: File, Header)) {
514 Private = Header.getModule();
515 continue;
516 }
517
518 // If uses need to be specified explicitly, we are only allowed to return
519 // modules that are explicitly used by the requesting module.
520 if (RequestingModule && LangOpts.ModulesDeclUse &&
521 !RequestingModule->directlyUses(Requested: Header.getModule())) {
522 NotUsed = Header.getModule();
523 continue;
524 }
525
526 // We have found a module that we can happily use.
527 return;
528 }
529
530 Excluded = true;
531 }
532
533 // We have found a header, but it is private.
534 if (Private) {
535 Diags.Report(Loc: FilenameLoc, DiagID: diag::warn_use_of_private_header_outside_module)
536 << Filename;
537 return;
538 }
539
540 // We have found a module, but we don't use it.
541 if (NotUsed) {
542 Diags.Report(Loc: FilenameLoc, DiagID: diag::err_undeclared_use_of_module_indirect)
543 << RequestingModule->getTopLevelModule()->Name << Filename
544 << NotUsed->Name;
545 return;
546 }
547
548 if (Excluded || isHeaderInUmbrellaDirs(File))
549 return;
550
551 // At this point, only non-modular includes remain.
552
553 if (RequestingModule && LangOpts.ModulesStrictDeclUse) {
554 Diags.Report(Loc: FilenameLoc, DiagID: diag::err_undeclared_use_of_module)
555 << RequestingModule->getTopLevelModule()->Name << Filename;
556 } else if (RequestingModule && RequestingModuleIsModuleInterface &&
557 LangOpts.isCompilingModule()) {
558 // Do not diagnose when we are not compiling a module.
559 diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
560 diag::warn_non_modular_include_in_framework_module :
561 diag::warn_non_modular_include_in_module;
562 Diags.Report(Loc: FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
563 << File.getName();
564 }
565}
566
567static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New,
568 const ModuleMap::KnownHeader &Old) {
569 // Prefer available modules.
570 // FIXME: Considering whether the module is available rather than merely
571 // importable is non-hermetic and can result in surprising behavior for
572 // prebuilt modules. Consider only checking for importability here.
573 if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
574 return true;
575
576 // Prefer a public header over a private header.
577 if ((New.getRole() & ModuleMap::PrivateHeader) !=
578 (Old.getRole() & ModuleMap::PrivateHeader))
579 return !(New.getRole() & ModuleMap::PrivateHeader);
580
581 // Prefer a non-textual header over a textual header.
582 if ((New.getRole() & ModuleMap::TextualHeader) !=
583 (Old.getRole() & ModuleMap::TextualHeader))
584 return !(New.getRole() & ModuleMap::TextualHeader);
585
586 // Prefer a non-excluded header over an excluded header.
587 if ((New.getRole() == ModuleMap::ExcludedHeader) !=
588 (Old.getRole() == ModuleMap::ExcludedHeader))
589 return New.getRole() != ModuleMap::ExcludedHeader;
590
591 // Don't have a reason to choose between these. Just keep the first one.
592 return false;
593}
594
595ModuleMap::KnownHeader ModuleMap::findModuleForHeader(FileEntryRef File,
596 bool AllowTextual,
597 bool AllowExcluded) {
598 auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
599 if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
600 return {};
601 return R;
602 };
603
604 HeadersMap::iterator Known = findKnownHeader(File);
605 if (Known != Headers.end()) {
606 ModuleMap::KnownHeader Result;
607 // Iterate over all modules that 'File' is part of to find the best fit.
608 for (KnownHeader &H : Known->second) {
609 // Cannot use a module if the header is excluded in it.
610 if (!AllowExcluded && H.getRole() == ModuleMap::ExcludedHeader)
611 continue;
612 // Prefer a header from the source module over all others.
613 if (H.getModule()->getTopLevelModule() == SourceModule)
614 return MakeResult(H);
615 if (!Result || isBetterKnownHeader(New: H, Old: Result))
616 Result = H;
617 }
618 return MakeResult(Result);
619 }
620
621 return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
622}
623
624ModuleMap::KnownHeader
625ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File) {
626 assert(!Headers.count(File) && "already have a module for this header");
627
628 SmallVector<DirectoryEntryRef, 2> SkippedDirs;
629 KnownHeader H = findHeaderInUmbrellaDirs(File, IntermediateDirs&: SkippedDirs);
630 if (H) {
631 Module *Result = H.getModule();
632
633 // Search up the module stack until we find a module with an umbrella
634 // directory.
635 Module *UmbrellaModule = Result;
636 while (!UmbrellaModule->getEffectiveUmbrellaDir() && UmbrellaModule->Parent)
637 UmbrellaModule = UmbrellaModule->Parent;
638
639 if (UmbrellaModule->InferSubmodules) {
640 FileID UmbrellaModuleMap = getModuleMapFileIDForUniquing(M: UmbrellaModule);
641
642 // Infer submodules for each of the directories we found between
643 // the directory of the umbrella header and the directory where
644 // the actual header is located.
645 bool Explicit = UmbrellaModule->InferExplicitSubmodules;
646
647 for (DirectoryEntryRef SkippedDir : llvm::reverse(C&: SkippedDirs)) {
648 // Find or create the module that corresponds to this directory name.
649 SmallString<32> NameBuf;
650 StringRef Name = sanitizeFilenameAsIdentifier(
651 Name: llvm::sys::path::stem(path: SkippedDir.getName()), Buffer&: NameBuf);
652 Result = findOrCreateModuleFirst(Name, Parent: Result, /*IsFramework=*/false,
653 IsExplicit: Explicit);
654 setInferredModuleAllowedBy(M: Result, ModMapFID: UmbrellaModuleMap);
655
656 // Associate the module and the directory.
657 UmbrellaDirs[SkippedDir] = Result;
658
659 // If inferred submodules export everything they import, add a
660 // wildcard to the set of exports.
661 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
662 Result->Exports.push_back(Elt: Module::ExportDecl(nullptr, true));
663 }
664
665 // Infer a submodule with the same name as this header file.
666 SmallString<32> NameBuf;
667 StringRef Name = sanitizeFilenameAsIdentifier(
668 Name: llvm::sys::path::stem(path: File.getName()), Buffer&: NameBuf);
669 Result = findOrCreateModuleFirst(Name, Parent: Result, /*IsFramework=*/false,
670 IsExplicit: Explicit);
671 setInferredModuleAllowedBy(M: Result, ModMapFID: UmbrellaModuleMap);
672 Result->addTopHeader(File);
673
674 // If inferred submodules export everything they import, add a
675 // wildcard to the set of exports.
676 if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
677 Result->Exports.push_back(Elt: Module::ExportDecl(nullptr, true));
678 } else {
679 // Record each of the directories we stepped through as being part of
680 // the module we found, since the umbrella header covers them all.
681 for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
682 UmbrellaDirs[SkippedDirs[I]] = Result;
683 }
684
685 KnownHeader Header(Result, NormalHeader);
686 Headers[File].push_back(Elt: Header);
687 return Header;
688 }
689
690 return {};
691}
692
693ArrayRef<ModuleMap::KnownHeader>
694ModuleMap::findAllModulesForHeader(FileEntryRef File) {
695 HeadersMap::iterator Known = findKnownHeader(File);
696 if (Known != Headers.end())
697 return Known->second;
698
699 if (findOrCreateModuleForHeaderInUmbrellaDir(File))
700 return Headers.find(Val: File)->second;
701
702 return {};
703}
704
705ArrayRef<ModuleMap::KnownHeader>
706ModuleMap::findResolvedModulesForHeader(FileEntryRef File) const {
707 // FIXME: Is this necessary?
708 resolveHeaderDirectives(File);
709 auto It = Headers.find(Val: File);
710 if (It == Headers.end())
711 return {};
712 return It->second;
713}
714
715bool ModuleMap::isHeaderInUnavailableModule(FileEntryRef Header) const {
716 return isHeaderUnavailableInModule(Header, RequestingModule: nullptr);
717}
718
719bool ModuleMap::isHeaderUnavailableInModule(
720 FileEntryRef Header, const Module *RequestingModule) const {
721 resolveHeaderDirectives(File: Header);
722 HeadersMap::const_iterator Known = Headers.find(Val: Header);
723 if (Known != Headers.end()) {
724 for (SmallVectorImpl<KnownHeader>::const_iterator
725 I = Known->second.begin(),
726 E = Known->second.end();
727 I != E; ++I) {
728
729 if (I->getRole() == ModuleMap::ExcludedHeader)
730 continue;
731
732 if (I->isAvailable() &&
733 (!RequestingModule ||
734 I->getModule()->isSubModuleOf(Other: RequestingModule))) {
735 // When no requesting module is available, the caller is looking if a
736 // header is part a module by only looking into the module map. This is
737 // done by warn_uncovered_module_header checks; don't consider textual
738 // headers part of it in this mode, otherwise we get misleading warnings
739 // that a umbrella header is not including a textual header.
740 if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader)
741 continue;
742 return false;
743 }
744 }
745 return true;
746 }
747
748 OptionalDirectoryEntryRef Dir = Header.getDir();
749 SmallVector<DirectoryEntryRef, 2> SkippedDirs;
750 StringRef DirName = Dir->getName();
751
752 auto IsUnavailable = [&](const Module *M) {
753 return !M->isAvailable() && (!RequestingModule ||
754 M->isSubModuleOf(Other: RequestingModule));
755 };
756
757 // Keep walking up the directory hierarchy, looking for a directory with
758 // an umbrella header.
759 do {
760 auto KnownDir = UmbrellaDirs.find(Val: *Dir);
761 if (KnownDir != UmbrellaDirs.end()) {
762 Module *Found = KnownDir->second;
763 if (IsUnavailable(Found))
764 return true;
765
766 // Search up the module stack until we find a module with an umbrella
767 // directory.
768 Module *UmbrellaModule = Found;
769 while (!UmbrellaModule->getEffectiveUmbrellaDir() &&
770 UmbrellaModule->Parent)
771 UmbrellaModule = UmbrellaModule->Parent;
772
773 if (UmbrellaModule->InferSubmodules) {
774 for (DirectoryEntryRef SkippedDir : llvm::reverse(C&: SkippedDirs)) {
775 // Find or create the module that corresponds to this directory name.
776 SmallString<32> NameBuf;
777 StringRef Name = sanitizeFilenameAsIdentifier(
778 Name: llvm::sys::path::stem(path: SkippedDir.getName()), Buffer&: NameBuf);
779 Found = lookupModuleQualified(Name, Context: Found);
780 if (!Found)
781 return false;
782 if (IsUnavailable(Found))
783 return true;
784 }
785
786 // Infer a submodule with the same name as this header file.
787 SmallString<32> NameBuf;
788 StringRef Name = sanitizeFilenameAsIdentifier(
789 Name: llvm::sys::path::stem(path: Header.getName()),
790 Buffer&: NameBuf);
791 Found = lookupModuleQualified(Name, Context: Found);
792 if (!Found)
793 return false;
794 }
795
796 return IsUnavailable(Found);
797 }
798
799 SkippedDirs.push_back(Elt: *Dir);
800
801 // Retrieve our parent path.
802 DirName = llvm::sys::path::parent_path(path: DirName);
803 if (DirName.empty())
804 break;
805
806 // Resolve the parent path to a directory entry.
807 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName);
808 } while (Dir);
809
810 return false;
811}
812
813Module *ModuleMap::findModule(StringRef Name) const {
814 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Key: Name);
815 if (Known != Modules.end())
816 return Known->getValue();
817
818 return nullptr;
819}
820
821Module *ModuleMap::findOrInferSubmodule(Module *Parent, StringRef Name) {
822 if (Module *SubM = Parent->findSubmodule(Name))
823 return SubM;
824 if (!Parent->InferSubmodules)
825 return nullptr;
826 Module *Result = new (ModulesAlloc.Allocate())
827 Module(ModuleConstructorTag{}, Name, SourceLocation(), Parent, false,
828 Parent->InferExplicitSubmodules, 0);
829 Result->InferExplicitSubmodules = Parent->InferExplicitSubmodules;
830 Result->InferSubmodules = Parent->InferSubmodules;
831 Result->InferExportWildcard = Parent->InferExportWildcard;
832 if (Result->InferExportWildcard)
833 Result->Exports.push_back(Elt: Module::ExportDecl(nullptr, true));
834 return Result;
835}
836
837Module *ModuleMap::lookupModuleUnqualified(StringRef Name,
838 Module *Context) const {
839 for(; Context; Context = Context->Parent) {
840 if (Module *Sub = lookupModuleQualified(Name, Context))
841 return Sub;
842 }
843
844 return findModule(Name);
845}
846
847Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
848 if (!Context)
849 return findModule(Name);
850
851 return Context->findSubmodule(Name);
852}
853
854std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name,
855 Module *Parent,
856 bool IsFramework,
857 bool IsExplicit) {
858 // Try to find an existing module with this name.
859 if (Module *Sub = lookupModuleQualified(Name, Context: Parent))
860 return std::make_pair(x&: Sub, y: false);
861
862 // Create a new module with this name.
863 Module *M = createModule(Name, Parent, IsFramework, IsExplicit);
864 return std::make_pair(x&: M, y: true);
865}
866
867Module *ModuleMap::createModule(StringRef Name, Module *Parent,
868 bool IsFramework, bool IsExplicit) {
869 assert(lookupModuleQualified(Name, Parent) == nullptr &&
870 "Creating duplicate submodule");
871
872 Module *Result = new (ModulesAlloc.Allocate())
873 Module(ModuleConstructorTag{}, Name, SourceLocation(), Parent,
874 IsFramework, IsExplicit, NumCreatedModules++);
875 if (!Parent) {
876 if (LangOpts.CurrentModule == Name)
877 SourceModule = Result;
878 Modules[Name] = Result;
879 ModuleScopeIDs[Result] = CurrentModuleScopeID;
880 }
881 return Result;
882}
883
884Module *ModuleMap::createGlobalModuleFragmentForModuleUnit(SourceLocation Loc,
885 Module *Parent) {
886 auto *Result = new (ModulesAlloc.Allocate()) Module(
887 ModuleConstructorTag{}, "<global>", Loc, Parent, /*IsFramework=*/false,
888 /*IsExplicit=*/true, NumCreatedModules++);
889 Result->Kind = Module::ExplicitGlobalModuleFragment;
890 // If the created module isn't owned by a parent, send it to PendingSubmodules
891 // to wait for its parent.
892 if (!Result->Parent)
893 PendingSubmodules.emplace_back(Args&: Result);
894 return Result;
895}
896
897Module *
898ModuleMap::createImplicitGlobalModuleFragmentForModuleUnit(SourceLocation Loc,
899 Module *Parent) {
900 assert(Parent && "We should only create an implicit global module fragment "
901 "in a module purview");
902 // Note: Here the `IsExplicit` parameter refers to the semantics in clang
903 // modules. All the non-explicit submodules in clang modules will be exported
904 // too. Here we simplify the implementation by using the concept.
905 auto *Result = new (ModulesAlloc.Allocate())
906 Module(ModuleConstructorTag{}, "<implicit global>", Loc, Parent,
907 /*IsFramework=*/false, /*IsExplicit=*/false, NumCreatedModules++);
908 Result->Kind = Module::ImplicitGlobalModuleFragment;
909 return Result;
910}
911
912Module *
913ModuleMap::createPrivateModuleFragmentForInterfaceUnit(Module *Parent,
914 SourceLocation Loc) {
915 auto *Result = new (ModulesAlloc.Allocate()) Module(
916 ModuleConstructorTag{}, "<private>", Loc, Parent, /*IsFramework=*/false,
917 /*IsExplicit=*/true, NumCreatedModules++);
918 Result->Kind = Module::PrivateModuleFragment;
919 return Result;
920}
921
922Module *ModuleMap::createModuleUnitWithKind(SourceLocation Loc, StringRef Name,
923 Module::ModuleKind Kind) {
924 auto *Result = new (ModulesAlloc.Allocate())
925 Module(ModuleConstructorTag{}, Name, Loc, nullptr, /*IsFramework=*/false,
926 /*IsExplicit=*/false, NumCreatedModules++);
927 Result->Kind = Kind;
928
929 // Reparent any current global module fragment as a submodule of this module.
930 for (auto &Submodule : PendingSubmodules)
931 Submodule->setParent(Result);
932 PendingSubmodules.clear();
933 return Result;
934}
935
936Module *ModuleMap::createModuleForInterfaceUnit(SourceLocation Loc,
937 StringRef Name) {
938 assert(LangOpts.CurrentModule == Name && "module name mismatch");
939 assert(!Modules[Name] && "redefining existing module");
940
941 auto *Result =
942 createModuleUnitWithKind(Loc, Name, Kind: Module::ModuleInterfaceUnit);
943 Modules[Name] = SourceModule = Result;
944
945 // Mark the main source file as being within the newly-created module so that
946 // declarations and macros are properly visibility-restricted to it.
947 auto MainFile = SourceMgr.getFileEntryRefForID(FID: SourceMgr.getMainFileID());
948 assert(MainFile && "no input file for module interface");
949 Headers[*MainFile].push_back(Elt: KnownHeader(Result, PrivateHeader));
950
951 return Result;
952}
953
954Module *ModuleMap::createModuleForImplementationUnit(SourceLocation Loc,
955 StringRef Name) {
956 assert(LangOpts.CurrentModule == Name && "module name mismatch");
957 // The interface for this implementation must exist and be loaded.
958 assert(Modules[Name] && Modules[Name]->Kind == Module::ModuleInterfaceUnit &&
959 "creating implementation module without an interface");
960
961 // Create an entry in the modules map to own the implementation unit module.
962 // User module names must not start with a period (so that this cannot clash
963 // with any legal user-defined module name).
964 StringRef IName = ".ImplementationUnit";
965 assert(!Modules[IName] && "multiple implementation units?");
966
967 auto *Result =
968 createModuleUnitWithKind(Loc, Name, Kind: Module::ModuleImplementationUnit);
969 Modules[IName] = SourceModule = Result;
970
971 // Check that the main file is present.
972 assert(SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) &&
973 "no input file for module implementation");
974
975 return Result;
976}
977
978Module *ModuleMap::createHeaderUnit(SourceLocation Loc, StringRef Name,
979 Module::Header H) {
980 assert(LangOpts.CurrentModule == Name && "module name mismatch");
981 assert(!Modules[Name] && "redefining existing module");
982
983 auto *Result = new (ModulesAlloc.Allocate())
984 Module(ModuleConstructorTag{}, Name, Loc, nullptr, /*IsFramework=*/false,
985 /*IsExplicit=*/false, NumCreatedModules++);
986 Result->Kind = Module::ModuleHeaderUnit;
987 Modules[Name] = SourceModule = Result;
988 addHeader(Mod: Result, Header: H, Role: NormalHeader);
989 return Result;
990}
991
992/// For a framework module, infer the framework against which we
993/// should link.
994static void inferFrameworkLink(Module *Mod) {
995 assert(Mod->IsFramework && "Can only infer linking for framework modules");
996 assert(!Mod->isSubFramework() &&
997 "Can only infer linking for top-level frameworks");
998
999 StringRef FrameworkName(Mod->Name);
1000 FrameworkName.consume_back(Suffix: "_Private");
1001 Mod->LinkLibraries.push_back(Elt: Module::LinkLibrary(FrameworkName.str(),
1002 /*IsFramework=*/true));
1003}
1004
1005Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
1006 bool IsSystem, Module *Parent) {
1007 Attributes Attrs;
1008 Attrs.IsSystem = IsSystem;
1009 return inferFrameworkModule(FrameworkDir, Attrs, Parent);
1010}
1011
1012Module *ModuleMap::inferFrameworkModule(DirectoryEntryRef FrameworkDir,
1013 Attributes Attrs, Module *Parent) {
1014 // Note: as an egregious but useful hack we use the real path here, because
1015 // we might be looking at an embedded framework that symlinks out to a
1016 // top-level framework, and we need to infer as if we were naming the
1017 // top-level framework.
1018 StringRef FrameworkDirName =
1019 SourceMgr.getFileManager().getCanonicalName(Dir: FrameworkDir);
1020
1021 // In case this is a case-insensitive filesystem, use the canonical
1022 // directory name as the ModuleName, since modules are case-sensitive.
1023 // FIXME: we should be able to give a fix-it hint for the correct spelling.
1024 SmallString<32> ModuleNameStorage;
1025 StringRef ModuleName = sanitizeFilenameAsIdentifier(
1026 Name: llvm::sys::path::stem(path: FrameworkDirName), Buffer&: ModuleNameStorage);
1027
1028 // Check whether we've already found this module.
1029 if (Module *Mod = lookupModuleQualified(Name: ModuleName, Context: Parent))
1030 return Mod;
1031
1032 FileManager &FileMgr = SourceMgr.getFileManager();
1033
1034 // If the framework has a parent path from which we're allowed to infer
1035 // a framework module, do so.
1036 FileID ModuleMapFID;
1037 if (!Parent) {
1038 // Determine whether we're allowed to infer a module map.
1039 bool canInfer = false;
1040 if (llvm::sys::path::has_parent_path(path: FrameworkDirName)) {
1041 // Figure out the parent path.
1042 StringRef Parent = llvm::sys::path::parent_path(path: FrameworkDirName);
1043 if (auto ParentDir = FileMgr.getOptionalDirectoryRef(DirName: Parent)) {
1044 // Check whether we have already looked into the parent directory
1045 // for a module map.
1046 llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
1047 inferred = InferredDirectories.find(Val: *ParentDir);
1048 if (inferred == InferredDirectories.end()) {
1049 // We haven't looked here before. Load a module map, if there is
1050 // one.
1051 bool IsFrameworkDir = Parent.ends_with(Suffix: ".framework");
1052 if (OptionalFileEntryRef ModMapFile =
1053 HeaderInfo.lookupModuleMapFile(Dir: *ParentDir, IsFramework: IsFrameworkDir)) {
1054 // TODO: Parsing a module map should populate `InferredDirectories`
1055 // so we don't need to do a full load here.
1056 parseAndLoadModuleMapFile(File: *ModMapFile, IsSystem: Attrs.IsSystem, HomeDir: *ParentDir);
1057 inferred = InferredDirectories.find(Val: *ParentDir);
1058 }
1059
1060 if (inferred == InferredDirectories.end())
1061 inferred = InferredDirectories.insert(
1062 KV: std::make_pair(x&: *ParentDir, y: InferredDirectory())).first;
1063 }
1064
1065 if (inferred->second.InferModules) {
1066 // We're allowed to infer for this directory, but make sure it's okay
1067 // to infer this particular module.
1068 StringRef Name = llvm::sys::path::stem(path: FrameworkDirName);
1069 canInfer =
1070 !llvm::is_contained(Range: inferred->second.ExcludedModules, Element: Name);
1071
1072 Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
1073 Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
1074 Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
1075 Attrs.NoUndeclaredIncludes |=
1076 inferred->second.Attrs.NoUndeclaredIncludes;
1077 ModuleMapFID = inferred->second.ModuleMapFID;
1078 }
1079 }
1080 }
1081
1082 // If we're not allowed to infer a framework module, don't.
1083 if (!canInfer)
1084 return nullptr;
1085 } else {
1086 ModuleMapFID = getModuleMapFileIDForUniquing(M: Parent);
1087 }
1088
1089 // Look for an umbrella header.
1090 SmallString<128> UmbrellaName = FrameworkDir.getName();
1091 llvm::sys::path::append(path&: UmbrellaName, a: "Headers", b: ModuleName + ".h");
1092 auto UmbrellaHeader = FileMgr.getOptionalFileRef(Filename: UmbrellaName);
1093
1094 // FIXME: If there's no umbrella header, we could probably scan the
1095 // framework to load *everything*. But, it's not clear that this is a good
1096 // idea.
1097 if (!UmbrellaHeader)
1098 return nullptr;
1099
1100 Module *Result = new (ModulesAlloc.Allocate())
1101 Module(ModuleConstructorTag{}, ModuleName, SourceLocation(), Parent,
1102 /*IsFramework=*/true, /*IsExplicit=*/false, NumCreatedModules++);
1103 setInferredModuleAllowedBy(M: Result, ModMapFID: ModuleMapFID);
1104 if (!Parent) {
1105 if (LangOpts.CurrentModule == ModuleName)
1106 SourceModule = Result;
1107 Modules[ModuleName] = Result;
1108 ModuleScopeIDs[Result] = CurrentModuleScopeID;
1109 }
1110
1111 Result->IsSystem |= Attrs.IsSystem;
1112 Result->IsExternC |= Attrs.IsExternC;
1113 Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
1114 Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
1115 Result->Directory = FrameworkDir;
1116
1117 // Chop off the first framework bit, as that is implied.
1118 StringRef RelativePath = UmbrellaName.str().substr(
1119 Start: Result->getTopLevelModule()->Directory->getName().size());
1120 RelativePath = llvm::sys::path::relative_path(path: RelativePath);
1121
1122 // umbrella header "umbrella-header-name"
1123 setUmbrellaHeaderAsWritten(Mod: Result, UmbrellaHeader: *UmbrellaHeader, NameAsWritten: ModuleName + ".h",
1124 PathRelativeToRootModuleDirectory: RelativePath);
1125
1126 // export *
1127 Result->Exports.push_back(Elt: Module::ExportDecl(nullptr, true));
1128
1129 // module * { export * }
1130 Result->InferSubmodules = true;
1131 Result->InferExportWildcard = true;
1132
1133 // Look for subframeworks.
1134 std::error_code EC;
1135 SmallString<128> SubframeworksDirName = FrameworkDir.getName();
1136 llvm::sys::path::append(path&: SubframeworksDirName, a: "Frameworks");
1137 llvm::sys::path::native(path&: SubframeworksDirName);
1138 llvm::vfs::FileSystem &FS = FileMgr.getVirtualFileSystem();
1139 for (llvm::vfs::directory_iterator
1140 Dir = FS.dir_begin(Dir: SubframeworksDirName, EC),
1141 DirEnd;
1142 Dir != DirEnd && !EC; Dir.increment(EC)) {
1143 if (!StringRef(Dir->path()).ends_with(Suffix: ".framework"))
1144 continue;
1145
1146 if (auto SubframeworkDir = FileMgr.getOptionalDirectoryRef(DirName: Dir->path())) {
1147 // Note: as an egregious but useful hack, we use the real path here and
1148 // check whether it is actually a subdirectory of the parent directory.
1149 // This will not be the case if the 'subframework' is actually a symlink
1150 // out to a top-level framework.
1151 StringRef SubframeworkDirName =
1152 FileMgr.getCanonicalName(Dir: *SubframeworkDir);
1153 bool FoundParent = false;
1154 do {
1155 // Get the parent directory name.
1156 SubframeworkDirName
1157 = llvm::sys::path::parent_path(path: SubframeworkDirName);
1158 if (SubframeworkDirName.empty())
1159 break;
1160
1161 if (auto SubDir =
1162 FileMgr.getOptionalDirectoryRef(DirName: SubframeworkDirName)) {
1163 if (*SubDir == FrameworkDir) {
1164 FoundParent = true;
1165 break;
1166 }
1167 }
1168 } while (true);
1169
1170 if (!FoundParent)
1171 continue;
1172
1173 // FIXME: Do we want to warn about subframeworks without umbrella headers?
1174 inferFrameworkModule(FrameworkDir: *SubframeworkDir, Attrs, Parent: Result);
1175 }
1176 }
1177
1178 // If the module is a top-level framework, automatically link against the
1179 // framework.
1180 if (!Result->isSubFramework())
1181 inferFrameworkLink(Mod: Result);
1182
1183 return Result;
1184}
1185
1186Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework,
1187 Module *ShadowingModule) {
1188
1189 // Create a new module with this name.
1190 Module *Result = new (ModulesAlloc.Allocate())
1191 Module(ModuleConstructorTag{}, Name, SourceLocation(), /*Parent=*/nullptr,
1192 IsFramework, /*IsExplicit=*/false, NumCreatedModules++);
1193 Result->ShadowingModule = ShadowingModule;
1194 Result->markUnavailable(/*Unimportable*/true);
1195 ModuleScopeIDs[Result] = CurrentModuleScopeID;
1196 ShadowModules.push_back(Elt: Result);
1197
1198 return Result;
1199}
1200
1201void ModuleMap::setUmbrellaHeaderAsWritten(
1202 Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten,
1203 const Twine &PathRelativeToRootModuleDirectory) {
1204 Headers[UmbrellaHeader].push_back(Elt: KnownHeader(Mod, NormalHeader));
1205 Mod->Umbrella = UmbrellaHeader;
1206 Mod->UmbrellaAsWritten = NameAsWritten.str();
1207 Mod->UmbrellaRelativeToRootModuleDirectory =
1208 PathRelativeToRootModuleDirectory.str();
1209 UmbrellaDirs[UmbrellaHeader.getDir()] = Mod;
1210
1211 // Notify callbacks that we just added a new header.
1212 for (const auto &Cb : Callbacks)
1213 Cb->moduleMapAddUmbrellaHeader(Header: UmbrellaHeader);
1214}
1215
1216void ModuleMap::setUmbrellaDirAsWritten(
1217 Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten,
1218 const Twine &PathRelativeToRootModuleDirectory) {
1219 Mod->Umbrella = UmbrellaDir;
1220 Mod->UmbrellaAsWritten = NameAsWritten.str();
1221 Mod->UmbrellaRelativeToRootModuleDirectory =
1222 PathRelativeToRootModuleDirectory.str();
1223 UmbrellaDirs[UmbrellaDir] = Mod;
1224}
1225
1226void ModuleMap::addUnresolvedHeader(Module *Mod,
1227 Module::UnresolvedHeaderDirective Header,
1228 bool &NeedsFramework) {
1229 // If there is a builtin counterpart to this file, add it now so it can
1230 // wrap the system header.
1231 if (resolveAsBuiltinHeader(Mod, Header)) {
1232 // If we have both a builtin and system version of the file, the
1233 // builtin version may want to inject macros into the system header, so
1234 // force the system header to be treated as a textual header in this
1235 // case.
1236 Header.Kind = headerRoleToKind(Role: ModuleMap::ModuleHeaderRole(
1237 headerKindToRole(Kind: Header.Kind) | ModuleMap::TextualHeader));
1238 Header.HasBuiltinHeader = true;
1239 }
1240
1241 // If possible, don't stat the header until we need to. This requires the
1242 // user to have provided us with some stat information about the file.
1243 // FIXME: Add support for lazily stat'ing umbrella headers and excluded
1244 // headers.
1245 if ((Header.Size || Header.ModTime) && !Header.IsUmbrella &&
1246 Header.Kind != Module::HK_Excluded) {
1247 // We expect more variation in mtime than size, so if we're given both,
1248 // use the mtime as the key.
1249 if (Header.ModTime)
1250 LazyHeadersByModTime[*Header.ModTime].push_back(NewVal: Mod);
1251 else
1252 LazyHeadersBySize[*Header.Size].push_back(NewVal: Mod);
1253 Mod->UnresolvedHeaders.push_back(Elt: Header);
1254 return;
1255 }
1256
1257 // We don't have stat information or can't defer looking this file up.
1258 // Perform the lookup now.
1259 resolveHeader(Mod, Header, NeedsFramework);
1260}
1261
1262void ModuleMap::resolveHeaderDirectives(const FileEntry *File) const {
1263 auto BySize = LazyHeadersBySize.find(Val: File->getSize());
1264 if (BySize != LazyHeadersBySize.end()) {
1265 for (auto *M : BySize->second)
1266 resolveHeaderDirectives(Mod: M, File);
1267 LazyHeadersBySize.erase(I: BySize);
1268 }
1269
1270 auto ByModTime = LazyHeadersByModTime.find(Val: File->getModificationTime());
1271 if (ByModTime != LazyHeadersByModTime.end()) {
1272 for (auto *M : ByModTime->second)
1273 resolveHeaderDirectives(Mod: M, File);
1274 LazyHeadersByModTime.erase(I: ByModTime);
1275 }
1276}
1277
1278void ModuleMap::resolveHeaderDirectives(
1279 Module *Mod, std::optional<const FileEntry *> File) const {
1280 bool NeedsFramework = false;
1281 SmallVector<Module::UnresolvedHeaderDirective, 1> NewHeaders;
1282 const auto Size = File ? (*File)->getSize() : 0;
1283 const auto ModTime = File ? (*File)->getModificationTime() : 0;
1284
1285 for (auto &Header : Mod->UnresolvedHeaders) {
1286 if (File && ((Header.ModTime && Header.ModTime != ModTime) ||
1287 (Header.Size && Header.Size != Size)))
1288 NewHeaders.push_back(Elt: Header);
1289 else
1290 // This operation is logically const; we're just changing how we represent
1291 // the header information for this file.
1292 const_cast<ModuleMap *>(this)->resolveHeader(Mod, Header, NeedsFramework);
1293 }
1294 Mod->UnresolvedHeaders.swap(RHS&: NewHeaders);
1295}
1296
1297void ModuleMap::addHeader(Module *Mod, Module::Header Header,
1298 ModuleHeaderRole Role, bool Imported) {
1299 KnownHeader KH(Mod, Role);
1300
1301 FileEntryRef HeaderEntry = Header.Entry;
1302
1303 // Only add each header to the headers list once.
1304 // FIXME: Should we diagnose if a header is listed twice in the
1305 // same module definition?
1306 auto &HeaderList = Headers[HeaderEntry];
1307 if (llvm::is_contained(Range&: HeaderList, Element: KH))
1308 return;
1309
1310 HeaderList.push_back(Elt: KH);
1311 Mod->addHeader(HK: headerRoleToKind(Role), H: std::move(Header));
1312
1313 bool isCompilingModuleHeader = Mod->isForBuilding(LangOpts);
1314 if (!Imported || isCompilingModuleHeader) {
1315 // When we import HeaderFileInfo, the external source is expected to
1316 // set the isModuleHeader flag itself.
1317 HeaderInfo.MarkFileModuleHeader(FE: HeaderEntry, Role, isCompilingModuleHeader);
1318 }
1319
1320 // Notify callbacks that we just added a new header.
1321 for (const auto &Cb : Callbacks)
1322 Cb->moduleMapAddHeader(Filename: HeaderEntry.getName());
1323}
1324
1325bool ModuleMap::parseModuleMapFile(FileEntryRef File, bool IsSystem,
1326 DirectoryEntryRef Dir, FileID ID,
1327 SourceLocation ExternModuleLoc) {
1328 llvm::DenseMap<const FileEntry *, const modulemap::ModuleMapFile *>::iterator
1329 Known = ParsedModuleMap.find(Val: File);
1330 if (Known != ParsedModuleMap.end())
1331 return Known->second == nullptr;
1332
1333 // If the module map file wasn't already entered, do so now.
1334 if (ID.isInvalid()) {
1335 FileID &LocalFID = ModuleMapLocalFileID[File];
1336 if (LocalFID.isInvalid()) {
1337 auto FileCharacter =
1338 IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap;
1339 LocalFID = SourceMgr.createFileID(SourceFile: File, IncludePos: ExternModuleLoc, FileCharacter);
1340 }
1341 ID = LocalFID;
1342 }
1343
1344 std::optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(FID: ID);
1345 if (!Buffer) {
1346 ParsedModuleMap[File] = nullptr;
1347 return true;
1348 }
1349
1350 Diags.Report(DiagID: diag::remark_mmap_parse) << File.getName();
1351 std::optional<modulemap::ModuleMapFile> MaybeMMF =
1352 modulemap::parseModuleMap(ID, Dir, SM&: SourceMgr, Diags, IsSystem, Offset: nullptr);
1353
1354 if (!MaybeMMF) {
1355 ParsedModuleMap[File] = nullptr;
1356 return true;
1357 }
1358
1359 ParsedModuleMaps.push_back(
1360 x: std::make_unique<modulemap::ModuleMapFile>(args: std::move(*MaybeMMF)));
1361 const modulemap::ModuleMapFile &MMF = *ParsedModuleMaps.back();
1362 std::vector<const modulemap::ExternModuleDecl *> PendingExternalModuleMaps;
1363 for (const auto &Decl : MMF.Decls) {
1364 std::visit(visitor: llvm::makeVisitor(
1365 Callables: [&](const modulemap::ModuleDecl &MD) {
1366 // Only use the first part of the name even for submodules.
1367 // This will correctly load the submodule declarations when
1368 // the module is loaded.
1369 auto &ModuleDecls =
1370 ParsedModules[StringRef(MD.Id.front().first)];
1371 ModuleDecls.push_back(Elt: std::pair(&MMF, &MD));
1372 },
1373 Callables: [&](const modulemap::ExternModuleDecl &EMD) {
1374 PendingExternalModuleMaps.push_back(x: &EMD);
1375 }),
1376 variants: Decl);
1377 }
1378
1379 for (const modulemap::ExternModuleDecl *EMD : PendingExternalModuleMaps) {
1380 StringRef FileNameRef = EMD->Path;
1381 SmallString<128> ModuleMapFileName;
1382 if (llvm::sys::path::is_relative(path: FileNameRef)) {
1383 ModuleMapFileName += Dir.getName();
1384 llvm::sys::path::append(path&: ModuleMapFileName, a: EMD->Path);
1385 FileNameRef = ModuleMapFileName;
1386 }
1387
1388 if (auto EFile =
1389 SourceMgr.getFileManager().getOptionalFileRef(Filename: FileNameRef)) {
1390 parseModuleMapFile(File: *EFile, IsSystem, Dir: EFile->getDir(), ID: FileID(),
1391 ExternModuleLoc);
1392 }
1393 }
1394
1395 ParsedModuleMap[File] = &MMF;
1396
1397 for (const auto &Cb : Callbacks)
1398 Cb->moduleMapFileRead(FileStart: SourceLocation(), File, IsSystem);
1399
1400 return false;
1401}
1402
1403FileID ModuleMap::getContainingModuleMapFileID(const Module *Module) const {
1404 if (Module->DefinitionLoc.isInvalid())
1405 return {};
1406
1407 return SourceMgr.getFileID(SpellingLoc: Module->DefinitionLoc);
1408}
1409
1410OptionalFileEntryRef
1411ModuleMap::getContainingModuleMapFile(const Module *Module) const {
1412 return SourceMgr.getFileEntryRefForID(FID: getContainingModuleMapFileID(Module));
1413}
1414
1415FileID ModuleMap::getModuleMapFileIDForUniquing(const Module *M) const {
1416 if (M->IsInferred) {
1417 assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
1418 return InferredModuleAllowedBy.find(Val: M)->second;
1419 }
1420 return getContainingModuleMapFileID(Module: M);
1421}
1422
1423OptionalFileEntryRef
1424ModuleMap::getModuleMapFileForUniquing(const Module *M) const {
1425 return SourceMgr.getFileEntryRefForID(FID: getModuleMapFileIDForUniquing(M));
1426}
1427
1428void ModuleMap::setInferredModuleAllowedBy(Module *M, FileID ModMapFID) {
1429 M->IsInferred = true;
1430 InferredModuleAllowedBy[M] = ModMapFID;
1431}
1432
1433std::error_code
1434ModuleMap::canonicalizeModuleMapPath(SmallVectorImpl<char> &Path) {
1435 StringRef Dir = llvm::sys::path::parent_path(path: {Path.data(), Path.size()});
1436
1437 // Do not canonicalize within the framework; the module map loader expects
1438 // Modules/ not Versions/A/Modules.
1439 if (llvm::sys::path::filename(path: Dir) == "Modules") {
1440 StringRef Parent = llvm::sys::path::parent_path(path: Dir);
1441 if (Parent.ends_with(Suffix: ".framework"))
1442 Dir = Parent;
1443 }
1444
1445 FileManager &FM = SourceMgr.getFileManager();
1446 auto DirEntry = FM.getDirectoryRef(DirName: Dir.empty() ? "." : Dir);
1447 if (!DirEntry)
1448 return llvm::errorToErrorCode(Err: DirEntry.takeError());
1449
1450 // Canonicalize the directory.
1451 StringRef CanonicalDir = FM.getCanonicalName(Dir: *DirEntry);
1452 if (CanonicalDir != Dir)
1453 llvm::sys::path::replace_path_prefix(Path, OldPrefix: Dir, NewPrefix: CanonicalDir);
1454
1455 // In theory, the filename component should also be canonicalized if it
1456 // on a case-insensitive filesystem. However, the extra canonicalization is
1457 // expensive and if clang looked up the filename it will always be lowercase.
1458
1459 // Remove ., remove redundant separators, and switch to native separators.
1460 // This is needed for separators between CanonicalDir and the filename.
1461 llvm::sys::path::remove_dots(path&: Path);
1462
1463 return std::error_code();
1464}
1465
1466void ModuleMap::addAdditionalModuleMapFile(const Module *M,
1467 FileEntryRef ModuleMap) {
1468 AdditionalModMaps[M].insert(V: ModuleMap);
1469}
1470
1471LLVM_DUMP_METHOD void ModuleMap::dump() {
1472 llvm::errs() << "Modules:";
1473 for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
1474 MEnd = Modules.end();
1475 M != MEnd; ++M)
1476 M->getValue()->print(OS&: llvm::errs(), Indent: 2);
1477
1478 llvm::errs() << "Headers:";
1479 for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
1480 H != HEnd; ++H) {
1481 llvm::errs() << " \"" << H->first.getName() << "\" -> ";
1482 for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
1483 E = H->second.end();
1484 I != E; ++I) {
1485 if (I != H->second.begin())
1486 llvm::errs() << ",";
1487 llvm::errs() << I->getModule()->getFullModuleName();
1488 }
1489 llvm::errs() << "\n";
1490 }
1491}
1492
1493bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
1494 auto Unresolved = std::move(Mod->UnresolvedExports);
1495 Mod->UnresolvedExports.clear();
1496 for (auto &UE : Unresolved) {
1497 Module::ExportDecl Export = resolveExport(Mod, Unresolved: UE, Complain);
1498 if (Export.getPointer() || Export.getInt())
1499 Mod->Exports.push_back(Elt: Export);
1500 else
1501 Mod->UnresolvedExports.push_back(Elt: UE);
1502 }
1503 return !Mod->UnresolvedExports.empty();
1504}
1505
1506bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
1507 auto *Top = Mod->getTopLevelModule();
1508 auto Unresolved = std::move(Top->UnresolvedDirectUses);
1509 Top->UnresolvedDirectUses.clear();
1510 for (auto &UDU : Unresolved) {
1511 Module *DirectUse = resolveModuleId(Id: UDU, Mod: Top, Complain);
1512 if (DirectUse)
1513 Top->DirectUses.push_back(Elt: DirectUse);
1514 else
1515 Top->UnresolvedDirectUses.push_back(Elt: UDU);
1516 }
1517 return !Top->UnresolvedDirectUses.empty();
1518}
1519
1520bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
1521 auto Unresolved = std::move(Mod->UnresolvedConflicts);
1522 Mod->UnresolvedConflicts.clear();
1523 for (auto &UC : Unresolved) {
1524 if (Module *OtherMod = resolveModuleId(Id: UC.Id, Mod, Complain)) {
1525 Module::Conflict Conflict;
1526 Conflict.Other = OtherMod;
1527 Conflict.Message = UC.Message;
1528 Mod->Conflicts.push_back(x: Conflict);
1529 } else
1530 Mod->UnresolvedConflicts.push_back(x: UC);
1531 }
1532 return !Mod->UnresolvedConflicts.empty();
1533}
1534
1535//----------------------------------------------------------------------------//
1536// Module map file loader
1537//----------------------------------------------------------------------------//
1538
1539namespace clang {
1540class ModuleMapLoader {
1541 SourceManager &SourceMgr;
1542
1543 DiagnosticsEngine &Diags;
1544 ModuleMap &Map;
1545
1546 /// The current module map file.
1547 FileID ModuleMapFID;
1548
1549 /// Source location of most recent loaded module declaration
1550 SourceLocation CurrModuleDeclLoc;
1551
1552 /// The directory that file names in this module map file should
1553 /// be resolved relative to.
1554 DirectoryEntryRef Directory;
1555
1556 /// Whether this module map is in a system header directory.
1557 bool IsSystem;
1558
1559 /// Whether an error occurred.
1560 bool HadError = false;
1561
1562 /// The active module.
1563 Module *ActiveModule = nullptr;
1564
1565 /// Whether a module uses the 'requires excluded' hack to mark its
1566 /// contents as 'textual'.
1567 ///
1568 /// On older Darwin SDK versions, 'requires excluded' is used to mark the
1569 /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
1570 /// non-modular headers. For backwards compatibility, we continue to
1571 /// support this idiom for just these modules, and map the headers to
1572 /// 'textual' to match the original intent.
1573 llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
1574
1575 void handleModuleDecl(const modulemap::ModuleDecl &MD);
1576 void handleExternModuleDecl(const modulemap::ExternModuleDecl &EMD);
1577 void handleRequiresDecl(const modulemap::RequiresDecl &RD);
1578 void handleHeaderDecl(const modulemap::HeaderDecl &HD);
1579 void handleUmbrellaDirDecl(const modulemap::UmbrellaDirDecl &UDD);
1580 void handleExportDecl(const modulemap::ExportDecl &ED);
1581 void handleExportAsDecl(const modulemap::ExportAsDecl &EAD);
1582 void handleUseDecl(const modulemap::UseDecl &UD);
1583 void handleLinkDecl(const modulemap::LinkDecl &LD);
1584 void handleConfigMacros(const modulemap::ConfigMacrosDecl &CMD);
1585 void handleConflict(const modulemap::ConflictDecl &CD);
1586 void handleInferredModuleDecl(const modulemap::ModuleDecl &MD);
1587
1588 /// Private modules are canonicalized as Foo_Private. Clang provides extra
1589 /// module map search logic to find the appropriate private module when PCH
1590 /// is used with implicit module maps. Warn when private modules are written
1591 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1592 void diagnosePrivateModules(SourceLocation StartLoc);
1593
1594 using Attributes = ModuleMap::Attributes;
1595
1596public:
1597 ModuleMapLoader(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
1598 ModuleMap &Map, FileID ModuleMapFID,
1599 DirectoryEntryRef Directory, bool IsSystem)
1600 : SourceMgr(SourceMgr), Diags(Diags), Map(Map),
1601 ModuleMapFID(ModuleMapFID), Directory(Directory), IsSystem(IsSystem) {}
1602
1603 bool loadModuleDecl(const modulemap::ModuleDecl &MD);
1604 bool loadExternModuleDecl(const modulemap::ExternModuleDecl &EMD);
1605 bool parseAndLoadModuleMapFile(const modulemap::ModuleMapFile &MMF);
1606};
1607
1608} // namespace clang
1609
1610/// Private modules are canonicalized as Foo_Private. Clang provides extra
1611/// module map search logic to find the appropriate private module when PCH
1612/// is used with implicit module maps. Warn when private modules are written
1613/// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1614void ModuleMapLoader::diagnosePrivateModules(SourceLocation StartLoc) {
1615 auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical,
1616 const Module *M, SourceRange ReplLoc) {
1617 auto D = Diags.Report(Loc: ActiveModule->DefinitionLoc,
1618 DiagID: diag::note_mmap_rename_top_level_private_module);
1619 D << BadName << M->Name;
1620 D << FixItHint::CreateReplacement(RemoveRange: ReplLoc, Code: Canonical);
1621 };
1622
1623 for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
1624 auto const *M = E->getValue();
1625 if (M->Directory != ActiveModule->Directory)
1626 continue;
1627
1628 SmallString<128> FullName(ActiveModule->getFullModuleName());
1629 if (!FullName.starts_with(Prefix: M->Name) && !FullName.ends_with(Suffix: "Private"))
1630 continue;
1631 SmallString<128> FixedPrivModDecl;
1632 SmallString<128> Canonical(M->Name);
1633 Canonical.append(RHS: "_Private");
1634
1635 // Foo.Private -> Foo_Private
1636 if (ActiveModule->Parent && ActiveModule->Name == "Private" && !M->Parent &&
1637 M->Name == ActiveModule->Parent->Name) {
1638 Diags.Report(Loc: ActiveModule->DefinitionLoc,
1639 DiagID: diag::warn_mmap_mismatched_private_submodule)
1640 << FullName;
1641
1642 SourceLocation FixItInitBegin = CurrModuleDeclLoc;
1643 if (StartLoc.isValid())
1644 FixItInitBegin = StartLoc;
1645
1646 if (ActiveModule->Parent->IsFramework)
1647 FixedPrivModDecl.append(RHS: "framework ");
1648 FixedPrivModDecl.append(RHS: "module ");
1649 FixedPrivModDecl.append(RHS: Canonical);
1650
1651 GenNoteAndFixIt(FullName, FixedPrivModDecl, M,
1652 SourceRange(FixItInitBegin, ActiveModule->DefinitionLoc));
1653 continue;
1654 }
1655
1656 // FooPrivate and whatnots -> Foo_Private
1657 if (!ActiveModule->Parent && !M->Parent && M->Name != ActiveModule->Name &&
1658 ActiveModule->Name != Canonical) {
1659 Diags.Report(Loc: ActiveModule->DefinitionLoc,
1660 DiagID: diag::warn_mmap_mismatched_private_module_name)
1661 << ActiveModule->Name;
1662 GenNoteAndFixIt(ActiveModule->Name, Canonical, M,
1663 SourceRange(ActiveModule->DefinitionLoc));
1664 }
1665 }
1666}
1667
1668void ModuleMapLoader::handleModuleDecl(const modulemap::ModuleDecl &MD) {
1669 if (MD.Id.front().first == "*")
1670 return handleInferredModuleDecl(MD);
1671
1672 CurrModuleDeclLoc = MD.Location;
1673
1674 Module *PreviousActiveModule = ActiveModule;
1675 if (MD.Id.size() > 1) {
1676 // This module map defines a submodule. Go find the module of which it
1677 // is a submodule.
1678 ActiveModule = nullptr;
1679 const Module *TopLevelModule = nullptr;
1680 for (unsigned I = 0, N = MD.Id.size() - 1; I != N; ++I) {
1681 if (Module *Next =
1682 Map.lookupModuleQualified(Name: MD.Id[I].first, Context: ActiveModule)) {
1683 if (I == 0)
1684 TopLevelModule = Next;
1685 ActiveModule = Next;
1686 continue;
1687 }
1688
1689 Diags.Report(Loc: MD.Id[I].second, DiagID: diag::err_mmap_missing_parent_module)
1690 << MD.Id[I].first << (ActiveModule != nullptr)
1691 << (ActiveModule
1692 ? ActiveModule->getTopLevelModule()->getFullModuleName()
1693 : "");
1694 HadError = true;
1695 }
1696
1697 if (TopLevelModule &&
1698 ModuleMapFID != Map.getContainingModuleMapFileID(Module: TopLevelModule)) {
1699 assert(ModuleMapFID !=
1700 Map.getModuleMapFileIDForUniquing(TopLevelModule) &&
1701 "submodule defined in same file as 'module *' that allowed its "
1702 "top-level module");
1703 Map.addAdditionalModuleMapFile(
1704 M: TopLevelModule, ModuleMap: *SourceMgr.getFileEntryRefForID(FID: ModuleMapFID));
1705 }
1706 }
1707
1708 StringRef ModuleName = MD.Id.back().first;
1709 SourceLocation ModuleNameLoc = MD.Id.back().second;
1710
1711 // Determine whether this (sub)module has already been defined.
1712 Module *ShadowingModule = nullptr;
1713 if (Module *Existing = Map.lookupModuleQualified(Name: ModuleName, Context: ActiveModule)) {
1714 // We might see a (re)definition of a module that we already have a
1715 // definition for in four cases:
1716 // - If we loaded one definition from an AST file and we've just found a
1717 // corresponding definition in a module map file, or
1718 bool LoadedFromASTFile = Existing->IsFromModuleFile;
1719 // - If we previously inferred this module from different module map file.
1720 bool Inferred = Existing->IsInferred;
1721 // - If we're building a framework that vends a module map, we might've
1722 // previously seen the one in intermediate products and now the system
1723 // one.
1724 // FIXME: If we're parsing module map file that looks like this:
1725 // framework module FW { ... }
1726 // module FW.Sub { ... }
1727 // We can't check the framework qualifier, since it's not attached to
1728 // the definition of Sub. Checking that qualifier on \c Existing is
1729 // not correct either, since we might've previously seen:
1730 // module FW { ... }
1731 // module FW.Sub { ... }
1732 // We should enforce consistency of redefinitions so that we can rely
1733 // that \c Existing is part of a framework iff the redefinition of FW
1734 // we have just skipped had it too. Once we do that, stop checking
1735 // the local framework qualifier and only rely on \c Existing.
1736 bool PartOfFramework = MD.Framework || Existing->isPartOfFramework();
1737 // - If we're building a (preprocessed) module and we've just loaded the
1738 // module map file from which it was created.
1739 bool ParsedAsMainInput =
1740 Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap &&
1741 Map.LangOpts.CurrentModule == ModuleName &&
1742 SourceMgr.getDecomposedLoc(Loc: ModuleNameLoc).first !=
1743 SourceMgr.getDecomposedLoc(Loc: Existing->DefinitionLoc).first;
1744 // TODO: Remove this check when we can avoid loading module maps multiple
1745 // times.
1746 bool SameModuleDecl = ModuleNameLoc == Existing->DefinitionLoc;
1747 if (LoadedFromASTFile || Inferred || PartOfFramework || ParsedAsMainInput ||
1748 SameModuleDecl) {
1749 ActiveModule = PreviousActiveModule;
1750 // Skip the module definition.
1751 return;
1752 }
1753
1754 if (!Existing->Parent && Map.mayShadowNewModule(ExistingModule: Existing)) {
1755 ShadowingModule = Existing;
1756 } else {
1757 // This is not a shawdowed module decl, it is an illegal redefinition.
1758 Diags.Report(Loc: ModuleNameLoc, DiagID: diag::err_mmap_module_redefinition)
1759 << ModuleName;
1760 Diags.Report(Loc: Existing->DefinitionLoc, DiagID: diag::note_mmap_prev_definition);
1761 HadError = true;
1762 return;
1763 }
1764 }
1765
1766 // Start defining this module.
1767 if (ShadowingModule) {
1768 ActiveModule =
1769 Map.createShadowedModule(Name: ModuleName, IsFramework: MD.Framework, ShadowingModule);
1770 } else {
1771 ActiveModule = Map.findOrCreateModuleFirst(Name: ModuleName, Parent: ActiveModule,
1772 IsFramework: MD.Framework, IsExplicit: MD.Explicit);
1773 }
1774
1775 ActiveModule->DefinitionLoc = ModuleNameLoc;
1776 if (MD.Attrs.IsSystem || IsSystem)
1777 ActiveModule->IsSystem = true;
1778 if (MD.Attrs.IsExternC)
1779 ActiveModule->IsExternC = true;
1780 if (MD.Attrs.NoUndeclaredIncludes)
1781 ActiveModule->NoUndeclaredIncludes = true;
1782 ActiveModule->Directory = Directory;
1783
1784 StringRef MapFileName(
1785 SourceMgr.getFileEntryRefForID(FID: ModuleMapFID)->getName());
1786 if (MapFileName.ends_with(Suffix: "module.private.modulemap") ||
1787 MapFileName.ends_with(Suffix: "module_private.map")) {
1788 ActiveModule->ModuleMapIsPrivate = true;
1789 }
1790
1791 // Private modules named as FooPrivate, Foo.Private or similar are likely a
1792 // user error; provide warnings, notes and fixits to direct users to use
1793 // Foo_Private instead.
1794 SourceLocation StartLoc =
1795 SourceMgr.getLocForStartOfFile(FID: SourceMgr.getMainFileID());
1796 if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
1797 !Diags.isIgnored(DiagID: diag::warn_mmap_mismatched_private_submodule,
1798 Loc: StartLoc) &&
1799 !Diags.isIgnored(DiagID: diag::warn_mmap_mismatched_private_module_name,
1800 Loc: StartLoc) &&
1801 ActiveModule->ModuleMapIsPrivate)
1802 diagnosePrivateModules(StartLoc: MD.Location);
1803
1804 for (const modulemap::Decl &Decl : MD.Decls) {
1805 std::visit(
1806 visitor: llvm::makeVisitor(
1807 Callables: [&](const modulemap::RequiresDecl &RD) { handleRequiresDecl(RD); },
1808 Callables: [&](const modulemap::HeaderDecl &HD) { handleHeaderDecl(HD); },
1809 Callables: [&](const modulemap::UmbrellaDirDecl &UDD) {
1810 handleUmbrellaDirDecl(UDD);
1811 },
1812 Callables: [&](const modulemap::ModuleDecl &MD) { handleModuleDecl(MD); },
1813 Callables: [&](const modulemap::ExportDecl &ED) { handleExportDecl(ED); },
1814 Callables: [&](const modulemap::ExportAsDecl &EAD) {
1815 handleExportAsDecl(EAD);
1816 },
1817 Callables: [&](const modulemap::ExternModuleDecl &EMD) {
1818 handleExternModuleDecl(EMD);
1819 },
1820 Callables: [&](const modulemap::UseDecl &UD) { handleUseDecl(UD); },
1821 Callables: [&](const modulemap::LinkDecl &LD) { handleLinkDecl(LD); },
1822 Callables: [&](const modulemap::ConfigMacrosDecl &CMD) {
1823 handleConfigMacros(CMD);
1824 },
1825 Callables: [&](const modulemap::ConflictDecl &CD) { handleConflict(CD); },
1826 Callables: [&](const modulemap::ExcludeDecl &ED) {
1827 Diags.Report(Loc: ED.Location, DiagID: diag::err_mmap_expected_member);
1828 }),
1829 variants: Decl);
1830 }
1831
1832 // If the active module is a top-level framework, and there are no link
1833 // libraries, automatically link against the framework.
1834 if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
1835 ActiveModule->LinkLibraries.empty())
1836 inferFrameworkLink(Mod: ActiveModule);
1837
1838 // If the module meets all requirements but is still unavailable, mark the
1839 // whole tree as unavailable to prevent it from building.
1840 if (!ActiveModule->IsAvailable && !ActiveModule->IsUnimportable &&
1841 ActiveModule->Parent) {
1842 ActiveModule->getTopLevelModule()->markUnavailable(/*Unimportable=*/false);
1843 ActiveModule->getTopLevelModule()->MissingHeaders.append(
1844 in_start: ActiveModule->MissingHeaders.begin(), in_end: ActiveModule->MissingHeaders.end());
1845 }
1846
1847 // We're done parsing this module. Pop back to the previous module.
1848 ActiveModule = PreviousActiveModule;
1849}
1850
1851void ModuleMapLoader::handleExternModuleDecl(
1852 const modulemap::ExternModuleDecl &EMD) {
1853 StringRef FileNameRef = EMD.Path;
1854 SmallString<128> ModuleMapFileName;
1855 if (llvm::sys::path::is_relative(path: FileNameRef)) {
1856 ModuleMapFileName += Directory.getName();
1857 llvm::sys::path::append(path&: ModuleMapFileName, a: EMD.Path);
1858 FileNameRef = ModuleMapFileName;
1859 }
1860 if (auto File = SourceMgr.getFileManager().getOptionalFileRef(Filename: FileNameRef))
1861 Map.parseAndLoadModuleMapFile(
1862 File: *File, IsSystem,
1863 HomeDir: Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
1864 ? Directory
1865 : File->getDir(),
1866 ID: FileID(), Offset: nullptr, ExternModuleLoc: EMD.Location);
1867}
1868
1869/// Whether to add the requirement \p Feature to the module \p M.
1870///
1871/// This preserves backwards compatibility for two hacks in the Darwin system
1872/// module map files:
1873///
1874/// 1. The use of 'requires excluded' to make headers non-modular, which
1875/// should really be mapped to 'textual' now that we have this feature. We
1876/// drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
1877/// true. Later, this bit will be used to map all the headers inside this
1878/// module to 'textual'.
1879///
1880/// This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
1881///
1882/// 2. Removes a bogus cplusplus requirement from IOKit.avc. This requirement
1883/// was never correct and causes issues now that we check it, so drop it.
1884static bool shouldAddRequirement(Module *M, StringRef Feature,
1885 bool &IsRequiresExcludedHack) {
1886 if (Feature == "excluded" &&
1887 (M->fullModuleNameIs(nameParts: {"Darwin", "C", "excluded"}) ||
1888 M->fullModuleNameIs(nameParts: {"Tcl", "Private"}))) {
1889 IsRequiresExcludedHack = true;
1890 return false;
1891 } else if (Feature == "cplusplus" && M->fullModuleNameIs(nameParts: {"IOKit", "avc"})) {
1892 return false;
1893 }
1894
1895 return true;
1896}
1897
1898void ModuleMapLoader::handleRequiresDecl(const modulemap::RequiresDecl &RD) {
1899
1900 for (const modulemap::RequiresFeature &RF : RD.Features) {
1901 bool IsRequiresExcludedHack = false;
1902 bool ShouldAddRequirement =
1903 shouldAddRequirement(M: ActiveModule, Feature: RF.Feature, IsRequiresExcludedHack);
1904
1905 if (IsRequiresExcludedHack)
1906 UsesRequiresExcludedHack.insert(Ptr: ActiveModule);
1907
1908 if (ShouldAddRequirement) {
1909 // Add this feature.
1910 ActiveModule->addRequirement(Feature: RF.Feature, RequiredState: RF.RequiredState, LangOpts: Map.LangOpts,
1911 Target: *Map.Target);
1912 }
1913 }
1914}
1915
1916void ModuleMapLoader::handleHeaderDecl(const modulemap::HeaderDecl &HD) {
1917 // We've already consumed the first token.
1918 ModuleMap::ModuleHeaderRole Role = ModuleMap::NormalHeader;
1919
1920 if (HD.Private) {
1921 Role = ModuleMap::PrivateHeader;
1922 } else if (HD.Excluded) {
1923 Role = ModuleMap::ExcludedHeader;
1924 }
1925
1926 if (HD.Textual)
1927 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1928
1929 if (UsesRequiresExcludedHack.count(Ptr: ActiveModule)) {
1930 // Mark this header 'textual' (see doc comment for
1931 // Module::UsesRequiresExcludedHack).
1932 Role = ModuleMap::ModuleHeaderRole(Role | ModuleMap::TextualHeader);
1933 }
1934
1935 Module::UnresolvedHeaderDirective Header;
1936 Header.FileName = HD.Path;
1937 Header.FileNameLoc = HD.PathLoc;
1938 Header.IsUmbrella = HD.Umbrella;
1939 Header.Kind = Map.headerRoleToKind(Role);
1940
1941 // Check whether we already have an umbrella.
1942 if (Header.IsUmbrella &&
1943 !std::holds_alternative<std::monostate>(v: ActiveModule->Umbrella)) {
1944 Diags.Report(Loc: Header.FileNameLoc, DiagID: diag::err_mmap_umbrella_clash)
1945 << ActiveModule->getFullModuleName();
1946 HadError = true;
1947 return;
1948 }
1949
1950 if (HD.Size)
1951 Header.Size = HD.Size;
1952 if (HD.MTime)
1953 Header.ModTime = HD.MTime;
1954
1955 bool NeedsFramework = false;
1956 // Don't add headers to the builtin modules if the builtin headers belong to
1957 // the system modules, with the exception of __stddef_max_align_t.h which
1958 // always had its own module.
1959 if (!Map.LangOpts.BuiltinHeadersInSystemModules ||
1960 !isBuiltInModuleName(ModuleName: ActiveModule->getTopLevelModuleName()) ||
1961 ActiveModule->fullModuleNameIs(nameParts: {"_Builtin_stddef", "max_align_t"}))
1962 Map.addUnresolvedHeader(Mod: ActiveModule, Header: std::move(Header), NeedsFramework);
1963
1964 if (NeedsFramework)
1965 Diags.Report(Loc: CurrModuleDeclLoc, DiagID: diag::note_mmap_add_framework_keyword)
1966 << ActiveModule->getFullModuleName()
1967 << FixItHint::CreateReplacement(RemoveRange: CurrModuleDeclLoc, Code: "framework module");
1968}
1969
1970static bool compareModuleHeaders(const Module::Header &A,
1971 const Module::Header &B) {
1972 return A.NameAsWritten < B.NameAsWritten;
1973}
1974
1975void ModuleMapLoader::handleUmbrellaDirDecl(
1976 const modulemap::UmbrellaDirDecl &UDD) {
1977 std::string DirName = std::string(UDD.Path);
1978 std::string DirNameAsWritten = DirName;
1979
1980 // Check whether we already have an umbrella.
1981 if (!std::holds_alternative<std::monostate>(v: ActiveModule->Umbrella)) {
1982 Diags.Report(Loc: UDD.Location, DiagID: diag::err_mmap_umbrella_clash)
1983 << ActiveModule->getFullModuleName();
1984 HadError = true;
1985 return;
1986 }
1987
1988 // Look for this file.
1989 OptionalDirectoryEntryRef Dir;
1990 if (llvm::sys::path::is_absolute(path: DirName)) {
1991 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName);
1992 } else {
1993 SmallString<128> PathName;
1994 PathName = Directory.getName();
1995 llvm::sys::path::append(path&: PathName, a: DirName);
1996 Dir = SourceMgr.getFileManager().getOptionalDirectoryRef(DirName: PathName);
1997 }
1998
1999 if (!Dir) {
2000 Diags.Report(Loc: UDD.Location, DiagID: diag::warn_mmap_umbrella_dir_not_found)
2001 << DirName;
2002 return;
2003 }
2004
2005 if (UsesRequiresExcludedHack.count(Ptr: ActiveModule)) {
2006 // Mark this header 'textual' (see doc comment for
2007 // ModuleMapLoader::UsesRequiresExcludedHack). Although iterating over the
2008 // directory is relatively expensive, in practice this only applies to the
2009 // uncommonly used Tcl module on Darwin platforms.
2010 std::error_code EC;
2011 SmallVector<Module::Header, 6> Headers;
2012 llvm::vfs::FileSystem &FS =
2013 SourceMgr.getFileManager().getVirtualFileSystem();
2014 for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
2015 I != E && !EC; I.increment(EC)) {
2016 if (auto FE = SourceMgr.getFileManager().getOptionalFileRef(Filename: I->path())) {
2017 Module::Header Header = {.NameAsWritten: "", .PathRelativeToRootModuleDirectory: std::string(I->path()), .Entry: *FE};
2018 Headers.push_back(Elt: std::move(Header));
2019 }
2020 }
2021
2022 // Sort header paths so that the pcm doesn't depend on iteration order.
2023 llvm::stable_sort(Range&: Headers, C: compareModuleHeaders);
2024
2025 for (auto &Header : Headers)
2026 Map.addHeader(Mod: ActiveModule, Header: std::move(Header), Role: ModuleMap::TextualHeader);
2027 return;
2028 }
2029
2030 if (Module *OwningModule = Map.UmbrellaDirs[*Dir]) {
2031 Diags.Report(Loc: UDD.Location, DiagID: diag::err_mmap_umbrella_clash)
2032 << OwningModule->getFullModuleName();
2033 HadError = true;
2034 return;
2035 }
2036
2037 // Record this umbrella directory.
2038 Map.setUmbrellaDirAsWritten(Mod: ActiveModule, UmbrellaDir: *Dir, NameAsWritten: DirNameAsWritten, PathRelativeToRootModuleDirectory: DirName);
2039}
2040
2041void ModuleMapLoader::handleExportDecl(const modulemap::ExportDecl &ED) {
2042 Module::UnresolvedExportDecl Unresolved = {.ExportLoc: ED.Location, .Id: ED.Id, .Wildcard: ED.Wildcard};
2043 ActiveModule->UnresolvedExports.push_back(Elt: Unresolved);
2044}
2045
2046void ModuleMapLoader::handleExportAsDecl(const modulemap::ExportAsDecl &EAD) {
2047 const auto &ModName = EAD.Id.front();
2048
2049 if (!ActiveModule->ExportAsModule.empty()) {
2050 if (ActiveModule->ExportAsModule == ModName.first) {
2051 Diags.Report(Loc: ModName.second, DiagID: diag::warn_mmap_redundant_export_as)
2052 << ActiveModule->Name << ModName.first;
2053 } else {
2054 Diags.Report(Loc: ModName.second, DiagID: diag::err_mmap_conflicting_export_as)
2055 << ActiveModule->Name << ActiveModule->ExportAsModule
2056 << ModName.first;
2057 }
2058 }
2059
2060 ActiveModule->ExportAsModule = ModName.first;
2061 Map.addLinkAsDependency(Mod: ActiveModule);
2062}
2063
2064void ModuleMapLoader::handleUseDecl(const modulemap::UseDecl &UD) {
2065 if (ActiveModule->Parent)
2066 Diags.Report(Loc: UD.Location, DiagID: diag::err_mmap_use_decl_submodule);
2067 else
2068 ActiveModule->UnresolvedDirectUses.push_back(Elt: UD.Id);
2069}
2070
2071void ModuleMapLoader::handleLinkDecl(const modulemap::LinkDecl &LD) {
2072 ActiveModule->LinkLibraries.push_back(
2073 Elt: Module::LinkLibrary(std::string{LD.Library}, LD.Framework));
2074}
2075
2076void ModuleMapLoader::handleConfigMacros(
2077 const modulemap::ConfigMacrosDecl &CMD) {
2078 if (ActiveModule->Parent) {
2079 Diags.Report(Loc: CMD.Location, DiagID: diag::err_mmap_config_macro_submodule);
2080 return;
2081 }
2082
2083 // TODO: Is this really the behavior we want for multiple config_macros
2084 // declarations? If any of them are exhaustive then all of them are.
2085 if (CMD.Exhaustive) {
2086 ActiveModule->ConfigMacrosExhaustive = true;
2087 }
2088 ActiveModule->ConfigMacros.insert(position: ActiveModule->ConfigMacros.end(),
2089 first: CMD.Macros.begin(), last: CMD.Macros.end());
2090}
2091
2092void ModuleMapLoader::handleConflict(const modulemap::ConflictDecl &CD) {
2093 Module::UnresolvedConflict Conflict;
2094
2095 Conflict.Id = CD.Id;
2096 Conflict.Message = CD.Message;
2097
2098 // FIXME: when we move to C++20 we should consider using emplace_back
2099 ActiveModule->UnresolvedConflicts.push_back(x: std::move(Conflict));
2100}
2101
2102void ModuleMapLoader::handleInferredModuleDecl(
2103 const modulemap::ModuleDecl &MD) {
2104 SourceLocation StarLoc = MD.Id.front().second;
2105
2106 // Inferred modules must be submodules.
2107 if (!ActiveModule && !MD.Framework) {
2108 Diags.Report(Loc: StarLoc, DiagID: diag::err_mmap_top_level_inferred_submodule);
2109 return;
2110 }
2111
2112 if (ActiveModule) {
2113 // Inferred modules must have umbrella directories.
2114 if (ActiveModule->IsAvailable && !ActiveModule->getEffectiveUmbrellaDir()) {
2115 Diags.Report(Loc: StarLoc, DiagID: diag::err_mmap_inferred_no_umbrella);
2116 return;
2117 }
2118
2119 // Check for redefinition of an inferred module.
2120 if (ActiveModule->InferSubmodules) {
2121 Diags.Report(Loc: StarLoc, DiagID: diag::err_mmap_inferred_redef);
2122 if (ActiveModule->InferredSubmoduleLoc.isValid())
2123 Diags.Report(Loc: ActiveModule->InferredSubmoduleLoc,
2124 DiagID: diag::note_mmap_prev_definition);
2125 return;
2126 }
2127
2128 // Check for the 'framework' keyword, which is not permitted here.
2129 if (MD.Framework) {
2130 Diags.Report(Loc: StarLoc, DiagID: diag::err_mmap_inferred_framework_submodule);
2131 return;
2132 }
2133 } else if (MD.Explicit) {
2134 Diags.Report(Loc: StarLoc, DiagID: diag::err_mmap_explicit_inferred_framework);
2135 return;
2136 }
2137
2138 if (ActiveModule) {
2139 // Note that we have an inferred submodule.
2140 ActiveModule->InferSubmodules = true;
2141 ActiveModule->InferredSubmoduleLoc = StarLoc;
2142 ActiveModule->InferExplicitSubmodules = MD.Explicit;
2143 } else {
2144 // We'll be inferring framework modules for this directory.
2145 auto &InfDir = Map.InferredDirectories[Directory];
2146 InfDir.InferModules = true;
2147 InfDir.Attrs = MD.Attrs;
2148 InfDir.ModuleMapFID = ModuleMapFID;
2149 // FIXME: Handle the 'framework' keyword.
2150 }
2151
2152 for (const modulemap::Decl &Decl : MD.Decls) {
2153 std::visit(
2154 visitor: llvm::makeVisitor(
2155 Callables: [&](const auto &Other) {
2156 Diags.Report(Other.Location,
2157 diag::err_mmap_expected_inferred_member)
2158 << (ActiveModule != nullptr);
2159 },
2160 Callables: [&](const modulemap::ExcludeDecl &ED) {
2161 // Only inferred frameworks can have exclude decls
2162 if (ActiveModule) {
2163 Diags.Report(Loc: ED.Location,
2164 DiagID: diag::err_mmap_expected_inferred_member)
2165 << (ActiveModule != nullptr);
2166 HadError = true;
2167 return;
2168 }
2169 Map.InferredDirectories[Directory].ExcludedModules.emplace_back(
2170 Args: ED.Module);
2171 },
2172 Callables: [&](const modulemap::ExportDecl &ED) {
2173 // Only inferred submodules can have export decls
2174 if (!ActiveModule) {
2175 Diags.Report(Loc: ED.Location,
2176 DiagID: diag::err_mmap_expected_inferred_member)
2177 << (ActiveModule != nullptr);
2178 HadError = true;
2179 return;
2180 }
2181
2182 if (ED.Wildcard && ED.Id.size() == 0)
2183 ActiveModule->InferExportWildcard = true;
2184 else
2185 Diags.Report(Loc: ED.Id.front().second,
2186 DiagID: diag::err_mmap_expected_export_wildcard);
2187 }),
2188 variants: Decl);
2189 }
2190}
2191
2192bool ModuleMapLoader::loadModuleDecl(const modulemap::ModuleDecl &MD) {
2193 handleModuleDecl(MD);
2194 return HadError;
2195}
2196
2197bool ModuleMapLoader::loadExternModuleDecl(
2198 const modulemap::ExternModuleDecl &EMD) {
2199 handleExternModuleDecl(EMD);
2200 return HadError;
2201}
2202
2203bool ModuleMapLoader::parseAndLoadModuleMapFile(
2204 const modulemap::ModuleMapFile &MMF) {
2205 for (const auto &Decl : MMF.Decls) {
2206 std::visit(
2207 visitor: llvm::makeVisitor(
2208 Callables: [&](const modulemap::ModuleDecl &MD) { handleModuleDecl(MD); },
2209 Callables: [&](const modulemap::ExternModuleDecl &EMD) {
2210 handleExternModuleDecl(EMD);
2211 }),
2212 variants: Decl);
2213 }
2214 return HadError;
2215}
2216
2217Module *ModuleMap::findOrLoadModule(StringRef Name) {
2218 llvm::StringMap<Module *>::const_iterator Known = Modules.find(Key: Name);
2219 if (Known != Modules.end())
2220 return Known->getValue();
2221
2222 auto ParsedMod = ParsedModules.find(Key: Name);
2223 if (ParsedMod == ParsedModules.end())
2224 return nullptr;
2225
2226 Diags.Report(DiagID: diag::remark_mmap_load_module) << Name;
2227
2228 for (const auto &ModuleDecl : ParsedMod->second) {
2229 const modulemap::ModuleMapFile &MMF = *ModuleDecl.first;
2230 ModuleMapLoader Loader(SourceMgr, Diags, const_cast<ModuleMap &>(*this),
2231 MMF.ID, *MMF.Dir, MMF.IsSystem);
2232 if (Loader.loadModuleDecl(MD: *ModuleDecl.second))
2233 return nullptr;
2234 }
2235
2236 return findModule(Name);
2237}
2238
2239bool ModuleMap::parseAndLoadModuleMapFile(FileEntryRef File, bool IsSystem,
2240 DirectoryEntryRef Dir, FileID ID,
2241 unsigned *Offset,
2242 SourceLocation ExternModuleLoc) {
2243 assert(Target && "Missing target information");
2244 llvm::DenseMap<const FileEntry *, bool>::iterator Known =
2245 LoadedModuleMap.find(Val: File);
2246 if (Known != LoadedModuleMap.end())
2247 return Known->second;
2248
2249 // If the module map file wasn't already entered, do so now.
2250 if (ID.isInvalid()) {
2251 // TODO: The way we compute affecting module maps requires this to be a
2252 // local FileID. This should be changed to reuse loaded FileIDs when
2253 // available, and change the way that affecting module maps are
2254 // computed to not require this.
2255 FileID &LocalFID = ModuleMapLocalFileID[File];
2256 if (LocalFID.isInvalid()) {
2257 auto FileCharacter =
2258 IsSystem ? SrcMgr::C_System_ModuleMap : SrcMgr::C_User_ModuleMap;
2259 LocalFID = SourceMgr.createFileID(SourceFile: File, IncludePos: ExternModuleLoc, FileCharacter);
2260 }
2261 ID = LocalFID;
2262 }
2263
2264 assert(Target && "Missing target information");
2265 std::optional<llvm::MemoryBufferRef> Buffer = SourceMgr.getBufferOrNone(FID: ID);
2266 if (!Buffer)
2267 return LoadedModuleMap[File] = true;
2268 assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
2269 "invalid buffer offset");
2270
2271 std::optional<modulemap::ModuleMapFile> MMF =
2272 modulemap::parseModuleMap(ID, Dir, SM&: SourceMgr, Diags, IsSystem, Offset);
2273 bool Result = false;
2274 if (MMF) {
2275 Diags.Report(DiagID: diag::remark_mmap_load) << File.getName();
2276 ModuleMapLoader Loader(SourceMgr, Diags, *this, ID, Dir, IsSystem);
2277 Result = Loader.parseAndLoadModuleMapFile(MMF: *MMF);
2278 }
2279 LoadedModuleMap[File] = Result;
2280
2281 // Notify callbacks that we observed it.
2282 // FIXME: We should only report module maps that were actually used.
2283 for (const auto &Cb : Callbacks)
2284 Cb->moduleMapFileRead(FileStart: MMF ? MMF->Start : SourceLocation(), File, IsSystem);
2285
2286 return Result;
2287}
2288