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