clang  9.0.0svn
ModuleMap.cpp
Go to the documentation of this file.
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"
18 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/Module.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Lex/HeaderSearch.h"
27 #include "clang/Lex/Lexer.h"
29 #include "clang/Lex/Token.h"
30 #include "llvm/ADT/DenseMap.h"
31 #include "llvm/ADT/None.h"
32 #include "llvm/ADT/STLExtras.h"
33 #include "llvm/ADT/SmallPtrSet.h"
34 #include "llvm/ADT/SmallString.h"
35 #include "llvm/ADT/SmallVector.h"
36 #include "llvm/ADT/StringMap.h"
37 #include "llvm/ADT/StringRef.h"
38 #include "llvm/ADT/StringSwitch.h"
39 #include "llvm/Support/Allocator.h"
40 #include "llvm/Support/Compiler.h"
41 #include "llvm/Support/ErrorHandling.h"
42 #include "llvm/Support/MemoryBuffer.h"
43 #include "llvm/Support/Path.h"
44 #include "llvm/Support/VirtualFileSystem.h"
45 #include "llvm/Support/raw_ostream.h"
46 #include <algorithm>
47 #include <cassert>
48 #include <cstdint>
49 #include <cstring>
50 #include <string>
51 #include <system_error>
52 #include <utility>
53 
54 using namespace clang;
55 
56 void ModuleMapCallbacks::anchor() {}
57 
59  auto PendingLinkAs = PendingLinkAsModule.find(Mod->Name);
60  if (PendingLinkAs != PendingLinkAsModule.end()) {
61  for (auto &Name : PendingLinkAs->second) {
62  auto *M = findModule(Name.getKey());
63  if (M)
64  M->UseExportAsModuleLinkName = true;
65  }
66  }
67 }
68 
70  if (findModule(Mod->ExportAsModule))
71  Mod->UseExportAsModuleLinkName = true;
72  else
73  PendingLinkAsModule[Mod->ExportAsModule].insert(Mod->Name);
74 }
75 
77  switch ((int)Role) {
78  default: llvm_unreachable("unknown header role");
79  case NormalHeader:
80  return Module::HK_Normal;
81  case PrivateHeader:
82  return Module::HK_Private;
83  case TextualHeader:
84  return Module::HK_Textual;
85  case PrivateHeader | TextualHeader:
87  }
88 }
89 
92  switch ((int)Kind) {
93  case Module::HK_Normal:
94  return NormalHeader;
95  case Module::HK_Private:
96  return PrivateHeader;
97  case Module::HK_Textual:
98  return TextualHeader;
100  return ModuleHeaderRole(PrivateHeader | TextualHeader);
101  case Module::HK_Excluded:
102  llvm_unreachable("unexpected header kind");
103  }
104  llvm_unreachable("unknown header kind");
105 }
106 
108 ModuleMap::resolveExport(Module *Mod,
109  const Module::UnresolvedExportDecl &Unresolved,
110  bool Complain) const {
111  // We may have just a wildcard.
112  if (Unresolved.Id.empty()) {
113  assert(Unresolved.Wildcard && "Invalid unresolved export");
114  return Module::ExportDecl(nullptr, true);
115  }
116 
117  // Resolve the module-id.
118  Module *Context = resolveModuleId(Unresolved.Id, Mod, Complain);
119  if (!Context)
120  return {};
121 
122  return Module::ExportDecl(Context, Unresolved.Wildcard);
123 }
124 
125 Module *ModuleMap::resolveModuleId(const ModuleId &Id, Module *Mod,
126  bool Complain) const {
127  // Find the starting module.
128  Module *Context = lookupModuleUnqualified(Id[0].first, Mod);
129  if (!Context) {
130  if (Complain)
131  Diags.Report(Id[0].second, diag::err_mmap_missing_module_unqualified)
132  << Id[0].first << Mod->getFullModuleName();
133 
134  return nullptr;
135  }
136 
137  // Dig into the module path.
138  for (unsigned I = 1, N = Id.size(); I != N; ++I) {
139  Module *Sub = lookupModuleQualified(Id[I].first, Context);
140  if (!Sub) {
141  if (Complain)
142  Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
143  << Id[I].first << Context->getFullModuleName()
144  << SourceRange(Id[0].second, Id[I-1].second);
145 
146  return nullptr;
147  }
148 
149  Context = Sub;
150  }
151 
152  return Context;
153 }
154 
155 /// Append to \p Paths the set of paths needed to get to the
156 /// subframework in which the given module lives.
158  SmallVectorImpl<char> &Path) {
159  // Collect the framework names from the given module to the top-level module.
161  for (; Mod; Mod = Mod->Parent) {
162  if (Mod->IsFramework)
163  Paths.push_back(Mod->Name);
164  }
165 
166  if (Paths.empty())
167  return;
168 
169  // Add Frameworks/Name.framework for each subframework.
170  for (unsigned I = Paths.size() - 1; I != 0; --I)
171  llvm::sys::path::append(Path, "Frameworks", Paths[I-1] + ".framework");
172 }
173 
174 const FileEntry *ModuleMap::findHeader(
175  Module *M, const Module::UnresolvedHeaderDirective &Header,
176  SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework) {
177  // Search for the header file within the module's home directory.
178  auto *Directory = M->Directory;
179  SmallString<128> FullPathName(Directory->getName());
180 
181  auto GetFile = [&](StringRef Filename) -> const FileEntry * {
182  auto *File = SourceMgr.getFileManager().getFile(Filename);
183  if (!File ||
184  (Header.Size && File->getSize() != *Header.Size) ||
185  (Header.ModTime && File->getModificationTime() != *Header.ModTime))
186  return nullptr;
187  return File;
188  };
189 
190  auto GetFrameworkFile = [&]() -> const FileEntry * {
191  unsigned FullPathLength = FullPathName.size();
192  appendSubframeworkPaths(M, RelativePathName);
193  unsigned RelativePathLength = RelativePathName.size();
194 
195  // Check whether this file is in the public headers.
196  llvm::sys::path::append(RelativePathName, "Headers", Header.FileName);
197  llvm::sys::path::append(FullPathName, RelativePathName);
198  if (auto *File = GetFile(FullPathName))
199  return File;
200 
201  // Check whether this file is in the private headers.
202  // Ideally, private modules in the form 'FrameworkName.Private' should
203  // be defined as 'module FrameworkName.Private', and not as
204  // 'framework module FrameworkName.Private', since a 'Private.Framework'
205  // does not usually exist. However, since both are currently widely used
206  // for private modules, make sure we find the right path in both cases.
207  if (M->IsFramework && M->Name == "Private")
208  RelativePathName.clear();
209  else
210  RelativePathName.resize(RelativePathLength);
211  FullPathName.resize(FullPathLength);
212  llvm::sys::path::append(RelativePathName, "PrivateHeaders",
213  Header.FileName);
214  llvm::sys::path::append(FullPathName, RelativePathName);
215  return GetFile(FullPathName);
216  };
217 
218  if (llvm::sys::path::is_absolute(Header.FileName)) {
219  RelativePathName.clear();
220  RelativePathName.append(Header.FileName.begin(), Header.FileName.end());
221  return GetFile(Header.FileName);
222  }
223 
224  if (M->isPartOfFramework())
225  return GetFrameworkFile();
226 
227  // Lookup for normal headers.
228  llvm::sys::path::append(RelativePathName, Header.FileName);
229  llvm::sys::path::append(FullPathName, RelativePathName);
230  auto *NormalHdrFile = GetFile(FullPathName);
231 
232  if (M && !NormalHdrFile && Directory->getName().endswith(".framework")) {
233  // The lack of 'framework' keyword in a module declaration it's a simple
234  // mistake we can diagnose when the header exists within the proper
235  // framework style path.
236  FullPathName.assign(Directory->getName());
237  RelativePathName.clear();
238  if (GetFrameworkFile()) {
239  Diags.Report(Header.FileNameLoc,
240  diag::warn_mmap_incomplete_framework_module_declaration)
241  << Header.FileName << M->getFullModuleName();
242  NeedsFramework = true;
243  }
244  return nullptr;
245  }
246 
247  return NormalHdrFile;
248 }
249 
250 void ModuleMap::resolveHeader(Module *Mod,
251  const Module::UnresolvedHeaderDirective &Header,
252  bool &NeedsFramework) {
253  SmallString<128> RelativePathName;
254  if (const FileEntry *File =
255  findHeader(Mod, Header, RelativePathName, NeedsFramework)) {
256  if (Header.IsUmbrella) {
257  const DirectoryEntry *UmbrellaDir = File->getDir();
258  if (Module *UmbrellaMod = UmbrellaDirs[UmbrellaDir])
259  Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
260  << UmbrellaMod->getFullModuleName();
261  else
262  // Record this umbrella header.
263  setUmbrellaHeader(Mod, File, RelativePathName.str());
264  } else {
265  Module::Header H = {RelativePathName.str(), File};
266  if (Header.Kind == Module::HK_Excluded)
267  excludeHeader(Mod, H);
268  else
269  addHeader(Mod, H, headerKindToRole(Header.Kind));
270  }
271  } else if (Header.HasBuiltinHeader && !Header.Size && !Header.ModTime) {
272  // There's a builtin header but no corresponding on-disk header. Assume
273  // this was supposed to modularize the builtin header alone.
274  } else if (Header.Kind == Module::HK_Excluded) {
275  // Ignore missing excluded header files. They're optional anyway.
276  } else {
277  // If we find a module that has a missing header, we mark this module as
278  // unavailable and store the header directive for displaying diagnostics.
279  Mod->MissingHeaders.push_back(Header);
280  // A missing header with stat information doesn't make the module
281  // unavailable; this keeps our behavior consistent as headers are lazily
282  // resolved. (Such a module still can't be built though, except from
283  // preprocessed source.)
284  if (!Header.Size && !Header.ModTime)
285  Mod->markUnavailable();
286  }
287 }
288 
289 bool ModuleMap::resolveAsBuiltinHeader(
290  Module *Mod, const Module::UnresolvedHeaderDirective &Header) {
291  if (Header.Kind == Module::HK_Excluded ||
292  llvm::sys::path::is_absolute(Header.FileName) ||
293  Mod->isPartOfFramework() || !Mod->IsSystem || Header.IsUmbrella ||
294  !BuiltinIncludeDir || BuiltinIncludeDir == Mod->Directory ||
295  !isBuiltinHeader(Header.FileName))
296  return false;
297 
298  // This is a system module with a top-level header. This header
299  // may have a counterpart (or replacement) in the set of headers
300  // supplied by Clang. Find that builtin header.
301  SmallString<128> Path;
302  llvm::sys::path::append(Path, BuiltinIncludeDir->getName(), Header.FileName);
303  auto *File = SourceMgr.getFileManager().getFile(Path);
304  if (!File)
305  return false;
306 
307  auto Role = headerKindToRole(Header.Kind);
308  Module::Header H = {Path.str(), File};
309  addHeader(Mod, H, Role);
310  return true;
311 }
312 
314  const LangOptions &LangOpts, const TargetInfo *Target,
315  HeaderSearch &HeaderInfo)
316  : SourceMgr(SourceMgr), Diags(Diags), LangOpts(LangOpts), Target(Target),
317  HeaderInfo(HeaderInfo) {
318  MMapLangOpts.LineComment = true;
319 }
320 
322  for (auto &M : Modules)
323  delete M.getValue();
324  for (auto *M : ShadowModules)
325  delete M;
326 }
327 
328 void ModuleMap::setTarget(const TargetInfo &Target) {
329  assert((!this->Target || this->Target == &Target) &&
330  "Improper target override");
331  this->Target = &Target;
332 }
333 
334 /// "Sanitize" a filename so that it can be used as an identifier.
335 static StringRef sanitizeFilenameAsIdentifier(StringRef Name,
336  SmallVectorImpl<char> &Buffer) {
337  if (Name.empty())
338  return Name;
339 
340  if (!isValidIdentifier(Name)) {
341  // If we don't already have something with the form of an identifier,
342  // create a buffer with the sanitized name.
343  Buffer.clear();
344  if (isDigit(Name[0]))
345  Buffer.push_back('_');
346  Buffer.reserve(Buffer.size() + Name.size());
347  for (unsigned I = 0, N = Name.size(); I != N; ++I) {
348  if (isIdentifierBody(Name[I]))
349  Buffer.push_back(Name[I]);
350  else
351  Buffer.push_back('_');
352  }
353 
354  Name = StringRef(Buffer.data(), Buffer.size());
355  }
356 
357  while (llvm::StringSwitch<bool>(Name)
358 #define KEYWORD(Keyword,Conditions) .Case(#Keyword, true)
359 #define ALIAS(Keyword, AliasOf, Conditions) .Case(Keyword, true)
360 #include "clang/Basic/TokenKinds.def"
361  .Default(false)) {
362  if (Name.data() != Buffer.data())
363  Buffer.append(Name.begin(), Name.end());
364  Buffer.push_back('_');
365  Name = StringRef(Buffer.data(), Buffer.size());
366  }
367 
368  return Name;
369 }
370 
371 /// Determine whether the given file name is the name of a builtin
372 /// header, supplied by Clang to replace, override, or augment existing system
373 /// headers.
374 bool ModuleMap::isBuiltinHeader(StringRef FileName) {
375  return llvm::StringSwitch<bool>(FileName)
376  .Case("float.h", true)
377  .Case("iso646.h", true)
378  .Case("limits.h", true)
379  .Case("stdalign.h", true)
380  .Case("stdarg.h", true)
381  .Case("stdatomic.h", true)
382  .Case("stdbool.h", true)
383  .Case("stddef.h", true)
384  .Case("stdint.h", true)
385  .Case("tgmath.h", true)
386  .Case("unwind.h", true)
387  .Default(false);
388 }
389 
390 ModuleMap::HeadersMap::iterator
391 ModuleMap::findKnownHeader(const FileEntry *File) {
393  HeadersMap::iterator Known = Headers.find(File);
394  if (HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
395  Known == Headers.end() && File->getDir() == BuiltinIncludeDir &&
396  ModuleMap::isBuiltinHeader(llvm::sys::path::filename(File->getName()))) {
397  HeaderInfo.loadTopLevelSystemModules();
398  return Headers.find(File);
399  }
400  return Known;
401 }
402 
404 ModuleMap::findHeaderInUmbrellaDirs(const FileEntry *File,
405  SmallVectorImpl<const DirectoryEntry *> &IntermediateDirs) {
406  if (UmbrellaDirs.empty())
407  return {};
408 
409  const DirectoryEntry *Dir = File->getDir();
410  assert(Dir && "file in no directory");
411 
412  // Note: as an egregious but useful hack we use the real path here, because
413  // frameworks moving from top-level frameworks to embedded frameworks tend
414  // to be symlinked from the top-level location to the embedded location,
415  // and we need to resolve lookups as if we had found the embedded location.
416  StringRef DirName = SourceMgr.getFileManager().getCanonicalName(Dir);
417 
418  // Keep walking up the directory hierarchy, looking for a directory with
419  // an umbrella header.
420  do {
421  auto KnownDir = UmbrellaDirs.find(Dir);
422  if (KnownDir != UmbrellaDirs.end())
423  return KnownHeader(KnownDir->second, NormalHeader);
424 
425  IntermediateDirs.push_back(Dir);
426 
427  // Retrieve our parent path.
428  DirName = llvm::sys::path::parent_path(DirName);
429  if (DirName.empty())
430  break;
431 
432  // Resolve the parent path to a directory entry.
433  Dir = SourceMgr.getFileManager().getDirectory(DirName);
434  } while (Dir);
435  return {};
436 }
437 
438 static bool violatesPrivateInclude(Module *RequestingModule,
439  const FileEntry *IncFileEnt,
440  ModuleMap::KnownHeader Header) {
441 #ifndef NDEBUG
442  if (Header.getRole() & ModuleMap::PrivateHeader) {
443  // Check for consistency between the module header role
444  // as obtained from the lookup and as obtained from the module.
445  // This check is not cheap, so enable it only for debugging.
446  bool IsPrivate = false;
447  SmallVectorImpl<Module::Header> *HeaderList[] = {
450  for (auto *Hs : HeaderList)
451  IsPrivate |=
452  std::find_if(Hs->begin(), Hs->end(), [&](const Module::Header &H) {
453  return H.Entry == IncFileEnt;
454  }) != Hs->end();
455  assert(IsPrivate && "inconsistent headers and roles");
456  }
457 #endif
458  return !Header.isAccessibleFrom(RequestingModule);
459 }
460 
462  return M ? M->getTopLevelModule() : nullptr;
463 }
464 
466  bool RequestingModuleIsModuleInterface,
467  SourceLocation FilenameLoc,
468  StringRef Filename,
469  const FileEntry *File) {
470  // No errors for indirect modules. This may be a bit of a problem for modules
471  // with no source files.
472  if (getTopLevelOrNull(RequestingModule) != getTopLevelOrNull(SourceModule))
473  return;
474 
475  if (RequestingModule) {
476  resolveUses(RequestingModule, /*Complain=*/false);
477  resolveHeaderDirectives(RequestingModule);
478  }
479 
480  bool Excluded = false;
481  Module *Private = nullptr;
482  Module *NotUsed = nullptr;
483 
484  HeadersMap::iterator Known = findKnownHeader(File);
485  if (Known != Headers.end()) {
486  for (const KnownHeader &Header : Known->second) {
487  // Remember private headers for later printing of a diagnostic.
488  if (violatesPrivateInclude(RequestingModule, File, Header)) {
489  Private = Header.getModule();
490  continue;
491  }
492 
493  // If uses need to be specified explicitly, we are only allowed to return
494  // modules that are explicitly used by the requesting module.
495  if (RequestingModule && LangOpts.ModulesDeclUse &&
496  !RequestingModule->directlyUses(Header.getModule())) {
497  NotUsed = Header.getModule();
498  continue;
499  }
500 
501  // We have found a module that we can happily use.
502  return;
503  }
504 
505  Excluded = true;
506  }
507 
508  // We have found a header, but it is private.
509  if (Private) {
510  Diags.Report(FilenameLoc, diag::warn_use_of_private_header_outside_module)
511  << Filename;
512  return;
513  }
514 
515  // We have found a module, but we don't use it.
516  if (NotUsed) {
517  Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
518  << RequestingModule->getTopLevelModule()->Name << Filename;
519  return;
520  }
521 
522  if (Excluded || isHeaderInUmbrellaDirs(File))
523  return;
524 
525  // At this point, only non-modular includes remain.
526 
527  if (RequestingModule && LangOpts.ModulesStrictDeclUse) {
528  Diags.Report(FilenameLoc, diag::err_undeclared_use_of_module)
529  << RequestingModule->getTopLevelModule()->Name << Filename;
530  } else if (RequestingModule && RequestingModuleIsModuleInterface &&
531  LangOpts.isCompilingModule()) {
532  // Do not diagnose when we are not compiling a module.
533  diag::kind DiagID = RequestingModule->getTopLevelModule()->IsFramework ?
534  diag::warn_non_modular_include_in_framework_module :
535  diag::warn_non_modular_include_in_module;
536  Diags.Report(FilenameLoc, DiagID) << RequestingModule->getFullModuleName()
537  << File->getName();
538  }
539 }
540 
542  const ModuleMap::KnownHeader &Old) {
543  // Prefer available modules.
544  if (New.getModule()->isAvailable() && !Old.getModule()->isAvailable())
545  return true;
546 
547  // Prefer a public header over a private header.
548  if ((New.getRole() & ModuleMap::PrivateHeader) !=
550  return !(New.getRole() & ModuleMap::PrivateHeader);
551 
552  // Prefer a non-textual header over a textual header.
553  if ((New.getRole() & ModuleMap::TextualHeader) !=
555  return !(New.getRole() & ModuleMap::TextualHeader);
556 
557  // Don't have a reason to choose between these. Just keep the first one.
558  return false;
559 }
560 
562  bool AllowTextual) {
563  auto MakeResult = [&](ModuleMap::KnownHeader R) -> ModuleMap::KnownHeader {
564  if (!AllowTextual && R.getRole() & ModuleMap::TextualHeader)
565  return {};
566  return R;
567  };
568 
569  HeadersMap::iterator Known = findKnownHeader(File);
570  if (Known != Headers.end()) {
572  // Iterate over all modules that 'File' is part of to find the best fit.
573  for (KnownHeader &H : Known->second) {
574  // Prefer a header from the source module over all others.
575  if (H.getModule()->getTopLevelModule() == SourceModule)
576  return MakeResult(H);
577  if (!Result || isBetterKnownHeader(H, Result))
578  Result = H;
579  }
580  return MakeResult(Result);
581  }
582 
583  return MakeResult(findOrCreateModuleForHeaderInUmbrellaDir(File));
584 }
585 
587 ModuleMap::findOrCreateModuleForHeaderInUmbrellaDir(const FileEntry *File) {
588  assert(!Headers.count(File) && "already have a module for this header");
589 
591  KnownHeader H = findHeaderInUmbrellaDirs(File, SkippedDirs);
592  if (H) {
593  Module *Result = H.getModule();
594 
595  // Search up the module stack until we find a module with an umbrella
596  // directory.
597  Module *UmbrellaModule = Result;
598  while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
599  UmbrellaModule = UmbrellaModule->Parent;
600 
601  if (UmbrellaModule->InferSubmodules) {
602  const FileEntry *UmbrellaModuleMap =
603  getModuleMapFileForUniquing(UmbrellaModule);
604 
605  // Infer submodules for each of the directories we found between
606  // the directory of the umbrella header and the directory where
607  // the actual header is located.
608  bool Explicit = UmbrellaModule->InferExplicitSubmodules;
609 
610  for (unsigned I = SkippedDirs.size(); I != 0; --I) {
611  // Find or create the module that corresponds to this directory name.
612  SmallString<32> NameBuf;
613  StringRef Name = sanitizeFilenameAsIdentifier(
614  llvm::sys::path::stem(SkippedDirs[I-1]->getName()), NameBuf);
615  Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
616  Explicit).first;
617  InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
618  Result->IsInferred = true;
619 
620  // Associate the module and the directory.
621  UmbrellaDirs[SkippedDirs[I-1]] = Result;
622 
623  // If inferred submodules export everything they import, add a
624  // wildcard to the set of exports.
625  if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
626  Result->Exports.push_back(Module::ExportDecl(nullptr, true));
627  }
628 
629  // Infer a submodule with the same name as this header file.
630  SmallString<32> NameBuf;
631  StringRef Name = sanitizeFilenameAsIdentifier(
632  llvm::sys::path::stem(File->getName()), NameBuf);
633  Result = findOrCreateModule(Name, Result, /*IsFramework=*/false,
634  Explicit).first;
635  InferredModuleAllowedBy[Result] = UmbrellaModuleMap;
636  Result->IsInferred = true;
637  Result->addTopHeader(File);
638 
639  // If inferred submodules export everything they import, add a
640  // wildcard to the set of exports.
641  if (UmbrellaModule->InferExportWildcard && Result->Exports.empty())
642  Result->Exports.push_back(Module::ExportDecl(nullptr, true));
643  } else {
644  // Record each of the directories we stepped through as being part of
645  // the module we found, since the umbrella header covers them all.
646  for (unsigned I = 0, N = SkippedDirs.size(); I != N; ++I)
647  UmbrellaDirs[SkippedDirs[I]] = Result;
648  }
649 
650  KnownHeader Header(Result, NormalHeader);
651  Headers[File].push_back(Header);
652  return Header;
653  }
654 
655  return {};
656 }
657 
661  auto It = Headers.find(File);
662  if (It == Headers.end())
663  return None;
664  return It->second;
665 }
666 
668  return isHeaderUnavailableInModule(Header, nullptr);
669 }
670 
671 bool
673  const Module *RequestingModule) const {
674  resolveHeaderDirectives(Header);
675  HeadersMap::const_iterator Known = Headers.find(Header);
676  if (Known != Headers.end()) {
678  I = Known->second.begin(),
679  E = Known->second.end();
680  I != E; ++I) {
681 
682  if (I->isAvailable() &&
683  (!RequestingModule ||
684  I->getModule()->isSubModuleOf(RequestingModule))) {
685  // When no requesting module is available, the caller is looking if a
686  // header is part a module by only looking into the module map. This is
687  // done by warn_uncovered_module_header checks; don't consider textual
688  // headers part of it in this mode, otherwise we get misleading warnings
689  // that a umbrella header is not including a textual header.
690  if (!RequestingModule && I->getRole() == ModuleMap::TextualHeader)
691  continue;
692  return false;
693  }
694  }
695  return true;
696  }
697 
698  const DirectoryEntry *Dir = Header->getDir();
700  StringRef DirName = Dir->getName();
701 
702  auto IsUnavailable = [&](const Module *M) {
703  return !M->isAvailable() && (!RequestingModule ||
704  M->isSubModuleOf(RequestingModule));
705  };
706 
707  // Keep walking up the directory hierarchy, looking for a directory with
708  // an umbrella header.
709  do {
710  llvm::DenseMap<const DirectoryEntry *, Module *>::const_iterator KnownDir
711  = UmbrellaDirs.find(Dir);
712  if (KnownDir != UmbrellaDirs.end()) {
713  Module *Found = KnownDir->second;
714  if (IsUnavailable(Found))
715  return true;
716 
717  // Search up the module stack until we find a module with an umbrella
718  // directory.
719  Module *UmbrellaModule = Found;
720  while (!UmbrellaModule->getUmbrellaDir() && UmbrellaModule->Parent)
721  UmbrellaModule = UmbrellaModule->Parent;
722 
723  if (UmbrellaModule->InferSubmodules) {
724  for (unsigned I = SkippedDirs.size(); I != 0; --I) {
725  // Find or create the module that corresponds to this directory name.
726  SmallString<32> NameBuf;
727  StringRef Name = sanitizeFilenameAsIdentifier(
728  llvm::sys::path::stem(SkippedDirs[I-1]->getName()),
729  NameBuf);
730  Found = lookupModuleQualified(Name, Found);
731  if (!Found)
732  return false;
733  if (IsUnavailable(Found))
734  return true;
735  }
736 
737  // Infer a submodule with the same name as this header file.
738  SmallString<32> NameBuf;
739  StringRef Name = sanitizeFilenameAsIdentifier(
740  llvm::sys::path::stem(Header->getName()),
741  NameBuf);
742  Found = lookupModuleQualified(Name, Found);
743  if (!Found)
744  return false;
745  }
746 
747  return IsUnavailable(Found);
748  }
749 
750  SkippedDirs.push_back(Dir);
751 
752  // Retrieve our parent path.
753  DirName = llvm::sys::path::parent_path(DirName);
754  if (DirName.empty())
755  break;
756 
757  // Resolve the parent path to a directory entry.
758  Dir = SourceMgr.getFileManager().getDirectory(DirName);
759  } while (Dir);
760 
761  return false;
762 }
763 
764 Module *ModuleMap::findModule(StringRef Name) const {
765  llvm::StringMap<Module *>::const_iterator Known = Modules.find(Name);
766  if (Known != Modules.end())
767  return Known->getValue();
768 
769  return nullptr;
770 }
771 
773  Module *Context) const {
774  for(; Context; Context = Context->Parent) {
775  if (Module *Sub = lookupModuleQualified(Name, Context))
776  return Sub;
777  }
778 
779  return findModule(Name);
780 }
781 
782 Module *ModuleMap::lookupModuleQualified(StringRef Name, Module *Context) const{
783  if (!Context)
784  return findModule(Name);
785 
786  return Context->findSubmodule(Name);
787 }
788 
789 std::pair<Module *, bool> ModuleMap::findOrCreateModule(StringRef Name,
790  Module *Parent,
791  bool IsFramework,
792  bool IsExplicit) {
793  // Try to find an existing module with this name.
794  if (Module *Sub = lookupModuleQualified(Name, Parent))
795  return std::make_pair(Sub, false);
796 
797  // Create a new module with this name.
798  Module *Result = new Module(Name, SourceLocation(), Parent, IsFramework,
799  IsExplicit, NumCreatedModules++);
800  if (!Parent) {
801  if (LangOpts.CurrentModule == Name)
802  SourceModule = Result;
803  Modules[Name] = Result;
804  ModuleScopeIDs[Result] = CurrentModuleScopeID;
805  }
806  return std::make_pair(Result, true);
807 }
808 
810  PendingSubmodules.emplace_back(
811  new Module("<global>", Loc, nullptr, /*IsFramework*/ false,
812  /*IsExplicit*/ true, NumCreatedModules++));
813  PendingSubmodules.back()->Kind = Module::GlobalModuleFragment;
814  return PendingSubmodules.back().get();
815 }
816 
818  StringRef Name,
819  Module *GlobalModule) {
820  assert(LangOpts.CurrentModule == Name && "module name mismatch");
821  assert(!Modules[Name] && "redefining existing module");
822 
823  auto *Result =
824  new Module(Name, Loc, nullptr, /*IsFramework*/ false,
825  /*IsExplicit*/ false, NumCreatedModules++);
827  Modules[Name] = SourceModule = Result;
828 
829  // Reparent the current global module fragment as a submodule of this module.
830  for (auto &Submodule : PendingSubmodules) {
831  Submodule->setParent(Result);
832  Submodule.release(); // now owned by parent
833  }
834  PendingSubmodules.clear();
835 
836  // Mark the main source file as being within the newly-created module so that
837  // declarations and macros are properly visibility-restricted to it.
838  auto *MainFile = SourceMgr.getFileEntryForID(SourceMgr.getMainFileID());
839  assert(MainFile && "no input file for module interface");
840  Headers[MainFile].push_back(KnownHeader(Result, PrivateHeader));
841 
842  return Result;
843 }
844 
846  ArrayRef<Module::Header> Headers) {
847  assert(LangOpts.CurrentModule == Name && "module name mismatch");
848  assert(!Modules[Name] && "redefining existing module");
849 
850  auto *Result =
851  new Module(Name, SourceLocation(), nullptr, /*IsFramework*/ false,
852  /*IsExplicit*/ false, NumCreatedModules++);
854  Modules[Name] = SourceModule = Result;
855 
856  for (const Module::Header &H : Headers) {
857  auto *M = new Module(H.NameAsWritten, SourceLocation(), Result,
858  /*IsFramework*/ false,
859  /*IsExplicit*/ true, NumCreatedModules++);
860  // Header modules are implicitly 'export *'.
861  M->Exports.push_back(Module::ExportDecl(nullptr, true));
862  addHeader(M, H, NormalHeader);
863  }
864 
865  return Result;
866 }
867 
868 /// For a framework module, infer the framework against which we
869 /// should link.
870 static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir,
871  FileManager &FileMgr) {
872  assert(Mod->IsFramework && "Can only infer linking for framework modules");
873  assert(!Mod->isSubFramework() &&
874  "Can only infer linking for top-level frameworks");
875 
876  SmallString<128> LibName;
877  LibName += FrameworkDir->getName();
878  llvm::sys::path::append(LibName, Mod->Name);
879 
880  // The library name of a framework has more than one possible extension since
881  // the introduction of the text-based dynamic library format. We need to check
882  // for both before we give up.
883  for (const char *extension : {"", ".tbd"}) {
884  llvm::sys::path::replace_extension(LibName, extension);
885  if (FileMgr.getFile(LibName)) {
886  Mod->LinkLibraries.push_back(Module::LinkLibrary(Mod->Name,
887  /*IsFramework=*/true));
888  return;
889  }
890  }
891 }
892 
893 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
894  bool IsSystem, Module *Parent) {
895  Attributes Attrs;
896  Attrs.IsSystem = IsSystem;
897  return inferFrameworkModule(FrameworkDir, Attrs, Parent);
898 }
899 
900 Module *ModuleMap::inferFrameworkModule(const DirectoryEntry *FrameworkDir,
901  Attributes Attrs, Module *Parent) {
902  // Note: as an egregious but useful hack we use the real path here, because
903  // we might be looking at an embedded framework that symlinks out to a
904  // top-level framework, and we need to infer as if we were naming the
905  // top-level framework.
906  StringRef FrameworkDirName =
907  SourceMgr.getFileManager().getCanonicalName(FrameworkDir);
908 
909  // In case this is a case-insensitive filesystem, use the canonical
910  // directory name as the ModuleName, since modules are case-sensitive.
911  // FIXME: we should be able to give a fix-it hint for the correct spelling.
912  SmallString<32> ModuleNameStorage;
913  StringRef ModuleName = sanitizeFilenameAsIdentifier(
914  llvm::sys::path::stem(FrameworkDirName), ModuleNameStorage);
915 
916  // Check whether we've already found this module.
917  if (Module *Mod = lookupModuleQualified(ModuleName, Parent))
918  return Mod;
919 
920  FileManager &FileMgr = SourceMgr.getFileManager();
921 
922  // If the framework has a parent path from which we're allowed to infer
923  // a framework module, do so.
924  const FileEntry *ModuleMapFile = nullptr;
925  if (!Parent) {
926  // Determine whether we're allowed to infer a module map.
927  bool canInfer = false;
928  if (llvm::sys::path::has_parent_path(FrameworkDirName)) {
929  // Figure out the parent path.
930  StringRef Parent = llvm::sys::path::parent_path(FrameworkDirName);
931  if (const DirectoryEntry *ParentDir = FileMgr.getDirectory(Parent)) {
932  // Check whether we have already looked into the parent directory
933  // for a module map.
934  llvm::DenseMap<const DirectoryEntry *, InferredDirectory>::const_iterator
935  inferred = InferredDirectories.find(ParentDir);
936  if (inferred == InferredDirectories.end()) {
937  // We haven't looked here before. Load a module map, if there is
938  // one.
939  bool IsFrameworkDir = Parent.endswith(".framework");
940  if (const FileEntry *ModMapFile =
941  HeaderInfo.lookupModuleMapFile(ParentDir, IsFrameworkDir)) {
942  parseModuleMapFile(ModMapFile, Attrs.IsSystem, ParentDir);
943  inferred = InferredDirectories.find(ParentDir);
944  }
945 
946  if (inferred == InferredDirectories.end())
947  inferred = InferredDirectories.insert(
948  std::make_pair(ParentDir, InferredDirectory())).first;
949  }
950 
951  if (inferred->second.InferModules) {
952  // We're allowed to infer for this directory, but make sure it's okay
953  // to infer this particular module.
954  StringRef Name = llvm::sys::path::stem(FrameworkDirName);
955  canInfer = std::find(inferred->second.ExcludedModules.begin(),
956  inferred->second.ExcludedModules.end(),
957  Name) == inferred->second.ExcludedModules.end();
958 
959  Attrs.IsSystem |= inferred->second.Attrs.IsSystem;
960  Attrs.IsExternC |= inferred->second.Attrs.IsExternC;
961  Attrs.IsExhaustive |= inferred->second.Attrs.IsExhaustive;
962  Attrs.NoUndeclaredIncludes |=
963  inferred->second.Attrs.NoUndeclaredIncludes;
964  ModuleMapFile = inferred->second.ModuleMapFile;
965  }
966  }
967  }
968 
969  // If we're not allowed to infer a framework module, don't.
970  if (!canInfer)
971  return nullptr;
972  } else
973  ModuleMapFile = getModuleMapFileForUniquing(Parent);
974 
975 
976  // Look for an umbrella header.
977  SmallString<128> UmbrellaName = StringRef(FrameworkDir->getName());
978  llvm::sys::path::append(UmbrellaName, "Headers", ModuleName + ".h");
979  const FileEntry *UmbrellaHeader = FileMgr.getFile(UmbrellaName);
980 
981  // FIXME: If there's no umbrella header, we could probably scan the
982  // framework to load *everything*. But, it's not clear that this is a good
983  // idea.
984  if (!UmbrellaHeader)
985  return nullptr;
986 
987  Module *Result = new Module(ModuleName, SourceLocation(), Parent,
988  /*IsFramework=*/true, /*IsExplicit=*/false,
989  NumCreatedModules++);
990  InferredModuleAllowedBy[Result] = ModuleMapFile;
991  Result->IsInferred = true;
992  if (!Parent) {
993  if (LangOpts.CurrentModule == ModuleName)
994  SourceModule = Result;
995  Modules[ModuleName] = Result;
996  ModuleScopeIDs[Result] = CurrentModuleScopeID;
997  }
998 
999  Result->IsSystem |= Attrs.IsSystem;
1000  Result->IsExternC |= Attrs.IsExternC;
1001  Result->ConfigMacrosExhaustive |= Attrs.IsExhaustive;
1002  Result->NoUndeclaredIncludes |= Attrs.NoUndeclaredIncludes;
1003  Result->Directory = FrameworkDir;
1004 
1005  // umbrella header "umbrella-header-name"
1006  //
1007  // The "Headers/" component of the name is implied because this is
1008  // a framework module.
1009  setUmbrellaHeader(Result, UmbrellaHeader, ModuleName + ".h");
1010 
1011  // export *
1012  Result->Exports.push_back(Module::ExportDecl(nullptr, true));
1013 
1014  // module * { export * }
1015  Result->InferSubmodules = true;
1016  Result->InferExportWildcard = true;
1017 
1018  // Look for subframeworks.
1019  std::error_code EC;
1020  SmallString<128> SubframeworksDirName
1021  = StringRef(FrameworkDir->getName());
1022  llvm::sys::path::append(SubframeworksDirName, "Frameworks");
1023  llvm::sys::path::native(SubframeworksDirName);
1024  llvm::vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
1025  for (llvm::vfs::directory_iterator
1026  Dir = FS.dir_begin(SubframeworksDirName, EC),
1027  DirEnd;
1028  Dir != DirEnd && !EC; Dir.increment(EC)) {
1029  if (!StringRef(Dir->path()).endswith(".framework"))
1030  continue;
1031 
1032  if (const DirectoryEntry *SubframeworkDir =
1033  FileMgr.getDirectory(Dir->path())) {
1034  // Note: as an egregious but useful hack, we use the real path here and
1035  // check whether it is actually a subdirectory of the parent directory.
1036  // This will not be the case if the 'subframework' is actually a symlink
1037  // out to a top-level framework.
1038  StringRef SubframeworkDirName = FileMgr.getCanonicalName(SubframeworkDir);
1039  bool FoundParent = false;
1040  do {
1041  // Get the parent directory name.
1042  SubframeworkDirName
1043  = llvm::sys::path::parent_path(SubframeworkDirName);
1044  if (SubframeworkDirName.empty())
1045  break;
1046 
1047  if (FileMgr.getDirectory(SubframeworkDirName) == FrameworkDir) {
1048  FoundParent = true;
1049  break;
1050  }
1051  } while (true);
1052 
1053  if (!FoundParent)
1054  continue;
1055 
1056  // FIXME: Do we want to warn about subframeworks without umbrella headers?
1057  inferFrameworkModule(SubframeworkDir, Attrs, Result);
1058  }
1059  }
1060 
1061  // If the module is a top-level framework, automatically link against the
1062  // framework.
1063  if (!Result->isSubFramework()) {
1064  inferFrameworkLink(Result, FrameworkDir, FileMgr);
1065  }
1066 
1067  return Result;
1068 }
1069 
1070 Module *ModuleMap::createShadowedModule(StringRef Name, bool IsFramework,
1071  Module *ShadowingModule) {
1072 
1073  // Create a new module with this name.
1074  Module *Result =
1075  new Module(Name, SourceLocation(), /*Parent=*/nullptr, IsFramework,
1076  /*IsExplicit=*/false, NumCreatedModules++);
1077  Result->ShadowingModule = ShadowingModule;
1078  Result->IsAvailable = false;
1079  ModuleScopeIDs[Result] = CurrentModuleScopeID;
1080  ShadowModules.push_back(Result);
1081 
1082  return Result;
1083 }
1084 
1085 void ModuleMap::setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader,
1086  Twine NameAsWritten) {
1087  Headers[UmbrellaHeader].push_back(KnownHeader(Mod, NormalHeader));
1088  Mod->Umbrella = UmbrellaHeader;
1089  Mod->UmbrellaAsWritten = NameAsWritten.str();
1090  UmbrellaDirs[UmbrellaHeader->getDir()] = Mod;
1091 
1092  // Notify callbacks that we just added a new header.
1093  for (const auto &Cb : Callbacks)
1094  Cb->moduleMapAddUmbrellaHeader(&SourceMgr.getFileManager(), UmbrellaHeader);
1095 }
1096 
1097 void ModuleMap::setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir,
1098  Twine NameAsWritten) {
1099  Mod->Umbrella = UmbrellaDir;
1100  Mod->UmbrellaAsWritten = NameAsWritten.str();
1101  UmbrellaDirs[UmbrellaDir] = Mod;
1102 }
1103 
1104 void ModuleMap::addUnresolvedHeader(Module *Mod,
1106  bool &NeedsFramework) {
1107  // If there is a builtin counterpart to this file, add it now so it can
1108  // wrap the system header.
1109  if (resolveAsBuiltinHeader(Mod, Header)) {
1110  // If we have both a builtin and system version of the file, the
1111  // builtin version may want to inject macros into the system header, so
1112  // force the system header to be treated as a textual header in this
1113  // case.
1116  Header.HasBuiltinHeader = true;
1117  }
1118 
1119  // If possible, don't stat the header until we need to. This requires the
1120  // user to have provided us with some stat information about the file.
1121  // FIXME: Add support for lazily stat'ing umbrella headers and excluded
1122  // headers.
1123  if ((Header.Size || Header.ModTime) && !Header.IsUmbrella &&
1124  Header.Kind != Module::HK_Excluded) {
1125  // We expect more variation in mtime than size, so if we're given both,
1126  // use the mtime as the key.
1127  if (Header.ModTime)
1128  LazyHeadersByModTime[*Header.ModTime].push_back(Mod);
1129  else
1130  LazyHeadersBySize[*Header.Size].push_back(Mod);
1131  Mod->UnresolvedHeaders.push_back(Header);
1132  return;
1133  }
1134 
1135  // We don't have stat information or can't defer looking this file up.
1136  // Perform the lookup now.
1137  resolveHeader(Mod, Header, NeedsFramework);
1138 }
1139 
1141  auto BySize = LazyHeadersBySize.find(File->getSize());
1142  if (BySize != LazyHeadersBySize.end()) {
1143  for (auto *M : BySize->second)
1145  LazyHeadersBySize.erase(BySize);
1146  }
1147 
1148  auto ByModTime = LazyHeadersByModTime.find(File->getModificationTime());
1149  if (ByModTime != LazyHeadersByModTime.end()) {
1150  for (auto *M : ByModTime->second)
1152  LazyHeadersByModTime.erase(ByModTime);
1153  }
1154 }
1155 
1157  bool NeedsFramework = false;
1158  for (auto &Header : Mod->UnresolvedHeaders)
1159  // This operation is logically const; we're just changing how we represent
1160  // the header information for this file.
1161  const_cast<ModuleMap*>(this)->resolveHeader(Mod, Header, NeedsFramework);
1162  Mod->UnresolvedHeaders.clear();
1163 }
1164 
1166  ModuleHeaderRole Role, bool Imported) {
1167  KnownHeader KH(Mod, Role);
1168 
1169  // Only add each header to the headers list once.
1170  // FIXME: Should we diagnose if a header is listed twice in the
1171  // same module definition?
1172  auto &HeaderList = Headers[Header.Entry];
1173  for (auto H : HeaderList)
1174  if (H == KH)
1175  return;
1176 
1177  HeaderList.push_back(KH);
1178  Mod->Headers[headerRoleToKind(Role)].push_back(Header);
1179 
1180  bool isCompilingModuleHeader =
1181  LangOpts.isCompilingModule() && Mod->getTopLevelModule() == SourceModule;
1182  if (!Imported || isCompilingModuleHeader) {
1183  // When we import HeaderFileInfo, the external source is expected to
1184  // set the isModuleHeader flag itself.
1185  HeaderInfo.MarkFileModuleHeader(Header.Entry, Role,
1186  isCompilingModuleHeader);
1187  }
1188 
1189  // Notify callbacks that we just added a new header.
1190  for (const auto &Cb : Callbacks)
1191  Cb->moduleMapAddHeader(Header.Entry->getName());
1192 }
1193 
1195  // Add this as a known header so we won't implicitly add it to any
1196  // umbrella directory module.
1197  // FIXME: Should we only exclude it from umbrella modules within the
1198  // specified module?
1199  (void) Headers[Header.Entry];
1200 
1201  Mod->Headers[Module::HK_Excluded].push_back(std::move(Header));
1202 }
1203 
1204 const FileEntry *
1206  if (Module->DefinitionLoc.isInvalid())
1207  return nullptr;
1208 
1209  return SourceMgr.getFileEntryForID(
1210  SourceMgr.getFileID(Module->DefinitionLoc));
1211 }
1212 
1214  if (M->IsInferred) {
1215  assert(InferredModuleAllowedBy.count(M) && "missing inferred module map");
1216  return InferredModuleAllowedBy.find(M)->second;
1217  }
1218  return getContainingModuleMapFile(M);
1219 }
1220 
1222  assert(M->IsInferred && "module not inferred");
1223  InferredModuleAllowedBy[M] = ModMap;
1224 }
1225 
1226 LLVM_DUMP_METHOD void ModuleMap::dump() {
1227  llvm::errs() << "Modules:";
1228  for (llvm::StringMap<Module *>::iterator M = Modules.begin(),
1229  MEnd = Modules.end();
1230  M != MEnd; ++M)
1231  M->getValue()->print(llvm::errs(), 2);
1232 
1233  llvm::errs() << "Headers:";
1234  for (HeadersMap::iterator H = Headers.begin(), HEnd = Headers.end();
1235  H != HEnd; ++H) {
1236  llvm::errs() << " \"" << H->first->getName() << "\" -> ";
1237  for (SmallVectorImpl<KnownHeader>::const_iterator I = H->second.begin(),
1238  E = H->second.end();
1239  I != E; ++I) {
1240  if (I != H->second.begin())
1241  llvm::errs() << ",";
1242  llvm::errs() << I->getModule()->getFullModuleName();
1243  }
1244  llvm::errs() << "\n";
1245  }
1246 }
1247 
1248 bool ModuleMap::resolveExports(Module *Mod, bool Complain) {
1249  auto Unresolved = std::move(Mod->UnresolvedExports);
1250  Mod->UnresolvedExports.clear();
1251  for (auto &UE : Unresolved) {
1252  Module::ExportDecl Export = resolveExport(Mod, UE, Complain);
1253  if (Export.getPointer() || Export.getInt())
1254  Mod->Exports.push_back(Export);
1255  else
1256  Mod->UnresolvedExports.push_back(UE);
1257  }
1258  return !Mod->UnresolvedExports.empty();
1259 }
1260 
1261 bool ModuleMap::resolveUses(Module *Mod, bool Complain) {
1262  auto Unresolved = std::move(Mod->UnresolvedDirectUses);
1263  Mod->UnresolvedDirectUses.clear();
1264  for (auto &UDU : Unresolved) {
1265  Module *DirectUse = resolveModuleId(UDU, Mod, Complain);
1266  if (DirectUse)
1267  Mod->DirectUses.push_back(DirectUse);
1268  else
1269  Mod->UnresolvedDirectUses.push_back(UDU);
1270  }
1271  return !Mod->UnresolvedDirectUses.empty();
1272 }
1273 
1274 bool ModuleMap::resolveConflicts(Module *Mod, bool Complain) {
1275  auto Unresolved = std::move(Mod->UnresolvedConflicts);
1276  Mod->UnresolvedConflicts.clear();
1277  for (auto &UC : Unresolved) {
1278  if (Module *OtherMod = resolveModuleId(UC.Id, Mod, Complain)) {
1279  Module::Conflict Conflict;
1280  Conflict.Other = OtherMod;
1281  Conflict.Message = UC.Message;
1282  Mod->Conflicts.push_back(Conflict);
1283  } else
1284  Mod->UnresolvedConflicts.push_back(UC);
1285  }
1286  return !Mod->UnresolvedConflicts.empty();
1287 }
1288 
1289 //----------------------------------------------------------------------------//
1290 // Module map file parser
1291 //----------------------------------------------------------------------------//
1292 
1293 namespace clang {
1294 
1295  /// A token in a module map file.
1296  struct MMToken {
1297  enum TokenKind {
1325  RSquare
1326  } Kind;
1327 
1328  unsigned Location;
1329  unsigned StringLength;
1330  union {
1331  // If Kind != IntegerLiteral.
1332  const char *StringData;
1333 
1334  // If Kind == IntegerLiteral.
1335  uint64_t IntegerValue;
1336  };
1337 
1338  void clear() {
1339  Kind = EndOfFile;
1340  Location = 0;
1341  StringLength = 0;
1342  StringData = nullptr;
1343  }
1344 
1345  bool is(TokenKind K) const { return Kind == K; }
1346 
1348  return SourceLocation::getFromRawEncoding(Location);
1349  }
1350 
1351  uint64_t getInteger() const {
1352  return Kind == IntegerLiteral ? IntegerValue : 0;
1353  }
1354 
1355  StringRef getString() const {
1356  return Kind == IntegerLiteral ? StringRef()
1357  : StringRef(StringData, StringLength);
1358  }
1359  };
1360 
1362  Lexer &L;
1363  SourceManager &SourceMgr;
1364 
1365  /// Default target information, used only for string literal
1366  /// parsing.
1367  const TargetInfo *Target;
1368 
1369  DiagnosticsEngine &Diags;
1370  ModuleMap &Map;
1371 
1372  /// The current module map file.
1373  const FileEntry *ModuleMapFile;
1374 
1375  /// Source location of most recent parsed module declaration
1376  SourceLocation CurrModuleDeclLoc;
1377 
1378  /// The directory that file names in this module map file should
1379  /// be resolved relative to.
1380  const DirectoryEntry *Directory;
1381 
1382  /// Whether this module map is in a system header directory.
1383  bool IsSystem;
1384 
1385  /// Whether an error occurred.
1386  bool HadError = false;
1387 
1388  /// Stores string data for the various string literals referenced
1389  /// during parsing.
1390  llvm::BumpPtrAllocator StringData;
1391 
1392  /// The current token.
1393  MMToken Tok;
1394 
1395  /// The active module.
1396  Module *ActiveModule = nullptr;
1397 
1398  /// Whether a module uses the 'requires excluded' hack to mark its
1399  /// contents as 'textual'.
1400  ///
1401  /// On older Darwin SDK versions, 'requires excluded' is used to mark the
1402  /// contents of the Darwin.C.excluded (assert.h) and Tcl.Private modules as
1403  /// non-modular headers. For backwards compatibility, we continue to
1404  /// support this idiom for just these modules, and map the headers to
1405  /// 'textual' to match the original intent.
1406  llvm::SmallPtrSet<Module *, 2> UsesRequiresExcludedHack;
1407 
1408  /// Consume the current token and return its location.
1409  SourceLocation consumeToken();
1410 
1411  /// Skip tokens until we reach the a token with the given kind
1412  /// (or the end of the file).
1413  void skipUntil(MMToken::TokenKind K);
1414 
1416 
1417  bool parseModuleId(ModuleId &Id);
1418  void parseModuleDecl();
1419  void parseExternModuleDecl();
1420  void parseRequiresDecl();
1421  void parseHeaderDecl(MMToken::TokenKind, SourceLocation LeadingLoc);
1422  void parseUmbrellaDirDecl(SourceLocation UmbrellaLoc);
1423  void parseExportDecl();
1424  void parseExportAsDecl();
1425  void parseUseDecl();
1426  void parseLinkDecl();
1427  void parseConfigMacros();
1428  void parseConflict();
1429  void parseInferredModuleDecl(bool Framework, bool Explicit);
1430 
1431  /// Private modules are canonicalized as Foo_Private. Clang provides extra
1432  /// module map search logic to find the appropriate private module when PCH
1433  /// is used with implicit module maps. Warn when private modules are written
1434  /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1435  void diagnosePrivateModules(SourceLocation ExplicitLoc,
1436  SourceLocation FrameworkLoc);
1437 
1438  using Attributes = ModuleMap::Attributes;
1439 
1440  bool parseOptionalAttributes(Attributes &Attrs);
1441 
1442  public:
1443  explicit ModuleMapParser(Lexer &L, SourceManager &SourceMgr,
1444  const TargetInfo *Target, DiagnosticsEngine &Diags,
1445  ModuleMap &Map, const FileEntry *ModuleMapFile,
1446  const DirectoryEntry *Directory, bool IsSystem)
1447  : L(L), SourceMgr(SourceMgr), Target(Target), Diags(Diags), Map(Map),
1448  ModuleMapFile(ModuleMapFile), Directory(Directory),
1449  IsSystem(IsSystem) {
1450  Tok.clear();
1451  consumeToken();
1452  }
1453 
1454  bool parseModuleMapFile();
1455 
1456  bool terminatedByDirective() { return false; }
1458  };
1459 
1460 } // namespace clang
1461 
1462 SourceLocation ModuleMapParser::consumeToken() {
1463  SourceLocation Result = Tok.getLocation();
1464 
1465 retry:
1466  Tok.clear();
1467  Token LToken;
1468  L.LexFromRawLexer(LToken);
1469  Tok.Location = LToken.getLocation().getRawEncoding();
1470  switch (LToken.getKind()) {
1471  case tok::raw_identifier: {
1472  StringRef RI = LToken.getRawIdentifier();
1473  Tok.StringData = RI.data();
1474  Tok.StringLength = RI.size();
1475  Tok.Kind = llvm::StringSwitch<MMToken::TokenKind>(RI)
1476  .Case("config_macros", MMToken::ConfigMacros)
1477  .Case("conflict", MMToken::Conflict)
1478  .Case("exclude", MMToken::ExcludeKeyword)
1479  .Case("explicit", MMToken::ExplicitKeyword)
1480  .Case("export", MMToken::ExportKeyword)
1481  .Case("export_as", MMToken::ExportAsKeyword)
1482  .Case("extern", MMToken::ExternKeyword)
1483  .Case("framework", MMToken::FrameworkKeyword)
1484  .Case("header", MMToken::HeaderKeyword)
1485  .Case("link", MMToken::LinkKeyword)
1486  .Case("module", MMToken::ModuleKeyword)
1487  .Case("private", MMToken::PrivateKeyword)
1488  .Case("requires", MMToken::RequiresKeyword)
1489  .Case("textual", MMToken::TextualKeyword)
1490  .Case("umbrella", MMToken::UmbrellaKeyword)
1491  .Case("use", MMToken::UseKeyword)
1492  .Default(MMToken::Identifier);
1493  break;
1494  }
1495 
1496  case tok::comma:
1497  Tok.Kind = MMToken::Comma;
1498  break;
1499 
1500  case tok::eof:
1501  Tok.Kind = MMToken::EndOfFile;
1502  break;
1503 
1504  case tok::l_brace:
1505  Tok.Kind = MMToken::LBrace;
1506  break;
1507 
1508  case tok::l_square:
1509  Tok.Kind = MMToken::LSquare;
1510  break;
1511 
1512  case tok::period:
1513  Tok.Kind = MMToken::Period;
1514  break;
1515 
1516  case tok::r_brace:
1517  Tok.Kind = MMToken::RBrace;
1518  break;
1519 
1520  case tok::r_square:
1521  Tok.Kind = MMToken::RSquare;
1522  break;
1523 
1524  case tok::star:
1525  Tok.Kind = MMToken::Star;
1526  break;
1527 
1528  case tok::exclaim:
1529  Tok.Kind = MMToken::Exclaim;
1530  break;
1531 
1532  case tok::string_literal: {
1533  if (LToken.hasUDSuffix()) {
1534  Diags.Report(LToken.getLocation(), diag::err_invalid_string_udl);
1535  HadError = true;
1536  goto retry;
1537  }
1538 
1539  // Parse the string literal.
1540  LangOptions LangOpts;
1541  StringLiteralParser StringLiteral(LToken, SourceMgr, LangOpts, *Target);
1542  if (StringLiteral.hadError)
1543  goto retry;
1544 
1545  // Copy the string literal into our string data allocator.
1546  unsigned Length = StringLiteral.GetStringLength();
1547  char *Saved = StringData.Allocate<char>(Length + 1);
1548  memcpy(Saved, StringLiteral.GetString().data(), Length);
1549  Saved[Length] = 0;
1550 
1551  // Form the token.
1552  Tok.Kind = MMToken::StringLiteral;
1553  Tok.StringData = Saved;
1554  Tok.StringLength = Length;
1555  break;
1556  }
1557 
1558  case tok::numeric_constant: {
1559  // We don't support any suffixes or other complications.
1560  SmallString<32> SpellingBuffer;
1561  SpellingBuffer.resize(LToken.getLength() + 1);
1562  const char *Start = SpellingBuffer.data();
1563  unsigned Length =
1564  Lexer::getSpelling(LToken, Start, SourceMgr, L.getLangOpts());
1565  uint64_t Value;
1566  if (StringRef(Start, Length).getAsInteger(0, Value)) {
1567  Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
1568  HadError = true;
1569  goto retry;
1570  }
1571 
1573  Tok.IntegerValue = Value;
1574  break;
1575  }
1576 
1577  case tok::comment:
1578  goto retry;
1579 
1580  case tok::hash:
1581  // A module map can be terminated prematurely by
1582  // #pragma clang module contents
1583  // When building the module, we'll treat the rest of the file as the
1584  // contents of the module.
1585  {
1586  auto NextIsIdent = [&](StringRef Str) -> bool {
1587  L.LexFromRawLexer(LToken);
1588  return !LToken.isAtStartOfLine() && LToken.is(tok::raw_identifier) &&
1589  LToken.getRawIdentifier() == Str;
1590  };
1591  if (NextIsIdent("pragma") && NextIsIdent("clang") &&
1592  NextIsIdent("module") && NextIsIdent("contents")) {
1593  Tok.Kind = MMToken::EndOfFile;
1594  break;
1595  }
1596  }
1597  LLVM_FALLTHROUGH;
1598 
1599  default:
1600  Diags.Report(Tok.getLocation(), diag::err_mmap_unknown_token);
1601  HadError = true;
1602  goto retry;
1603  }
1604 
1605  return Result;
1606 }
1607 
1608 void ModuleMapParser::skipUntil(MMToken::TokenKind K) {
1609  unsigned braceDepth = 0;
1610  unsigned squareDepth = 0;
1611  do {
1612  switch (Tok.Kind) {
1613  case MMToken::EndOfFile:
1614  return;
1615 
1616  case MMToken::LBrace:
1617  if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1618  return;
1619 
1620  ++braceDepth;
1621  break;
1622 
1623  case MMToken::LSquare:
1624  if (Tok.is(K) && braceDepth == 0 && squareDepth == 0)
1625  return;
1626 
1627  ++squareDepth;
1628  break;
1629 
1630  case MMToken::RBrace:
1631  if (braceDepth > 0)
1632  --braceDepth;
1633  else if (Tok.is(K))
1634  return;
1635  break;
1636 
1637  case MMToken::RSquare:
1638  if (squareDepth > 0)
1639  --squareDepth;
1640  else if (Tok.is(K))
1641  return;
1642  break;
1643 
1644  default:
1645  if (braceDepth == 0 && squareDepth == 0 && Tok.is(K))
1646  return;
1647  break;
1648  }
1649 
1650  consumeToken();
1651  } while (true);
1652 }
1653 
1654 /// Parse a module-id.
1655 ///
1656 /// module-id:
1657 /// identifier
1658 /// identifier '.' module-id
1659 ///
1660 /// \returns true if an error occurred, false otherwise.
1661 bool ModuleMapParser::parseModuleId(ModuleId &Id) {
1662  Id.clear();
1663  do {
1665  Id.push_back(std::make_pair(Tok.getString(), Tok.getLocation()));
1666  consumeToken();
1667  } else {
1668  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module_name);
1669  return true;
1670  }
1671 
1672  if (!Tok.is(MMToken::Period))
1673  break;
1674 
1675  consumeToken();
1676  } while (true);
1677 
1678  return false;
1679 }
1680 
1681 namespace {
1682 
1683  /// Enumerates the known attributes.
1685  /// An unknown attribute.
1686  AT_unknown,
1687 
1688  /// The 'system' attribute.
1689  AT_system,
1690 
1691  /// The 'extern_c' attribute.
1692  AT_extern_c,
1693 
1694  /// The 'exhaustive' attribute.
1695  AT_exhaustive,
1696 
1697  /// The 'no_undeclared_includes' attribute.
1698  AT_no_undeclared_includes
1699  };
1700 
1701 } // namespace
1702 
1703 /// Private modules are canonicalized as Foo_Private. Clang provides extra
1704 /// module map search logic to find the appropriate private module when PCH
1705 /// is used with implicit module maps. Warn when private modules are written
1706 /// in other ways (FooPrivate and Foo.Private), providing notes and fixits.
1707 void ModuleMapParser::diagnosePrivateModules(SourceLocation ExplicitLoc,
1708  SourceLocation FrameworkLoc) {
1709  auto GenNoteAndFixIt = [&](StringRef BadName, StringRef Canonical,
1710  const Module *M, SourceRange ReplLoc) {
1711  auto D = Diags.Report(ActiveModule->DefinitionLoc,
1712  diag::note_mmap_rename_top_level_private_module);
1713  D << BadName << M->Name;
1714  D << FixItHint::CreateReplacement(ReplLoc, Canonical);
1715  };
1716 
1717  for (auto E = Map.module_begin(); E != Map.module_end(); ++E) {
1718  auto const *M = E->getValue();
1719  if (M->Directory != ActiveModule->Directory)
1720  continue;
1721 
1722  SmallString<128> FullName(ActiveModule->getFullModuleName());
1723  if (!FullName.startswith(M->Name) && !FullName.endswith("Private"))
1724  continue;
1725  SmallString<128> FixedPrivModDecl;
1726  SmallString<128> Canonical(M->Name);
1727  Canonical.append("_Private");
1728 
1729  // Foo.Private -> Foo_Private
1730  if (ActiveModule->Parent && ActiveModule->Name == "Private" && !M->Parent &&
1731  M->Name == ActiveModule->Parent->Name) {
1732  Diags.Report(ActiveModule->DefinitionLoc,
1733  diag::warn_mmap_mismatched_private_submodule)
1734  << FullName;
1735 
1736  SourceLocation FixItInitBegin = CurrModuleDeclLoc;
1737  if (FrameworkLoc.isValid())
1738  FixItInitBegin = FrameworkLoc;
1739  if (ExplicitLoc.isValid())
1740  FixItInitBegin = ExplicitLoc;
1741 
1742  if (FrameworkLoc.isValid() || ActiveModule->Parent->IsFramework)
1743  FixedPrivModDecl.append("framework ");
1744  FixedPrivModDecl.append("module ");
1745  FixedPrivModDecl.append(Canonical);
1746 
1747  GenNoteAndFixIt(FullName, FixedPrivModDecl, M,
1748  SourceRange(FixItInitBegin, ActiveModule->DefinitionLoc));
1749  continue;
1750  }
1751 
1752  // FooPrivate and whatnots -> Foo_Private
1753  if (!ActiveModule->Parent && !M->Parent && M->Name != ActiveModule->Name &&
1754  ActiveModule->Name != Canonical) {
1755  Diags.Report(ActiveModule->DefinitionLoc,
1756  diag::warn_mmap_mismatched_private_module_name)
1757  << ActiveModule->Name;
1758  GenNoteAndFixIt(ActiveModule->Name, Canonical, M,
1759  SourceRange(ActiveModule->DefinitionLoc));
1760  }
1761  }
1762 }
1763 
1764 /// Parse a module declaration.
1765 ///
1766 /// module-declaration:
1767 /// 'extern' 'module' module-id string-literal
1768 /// 'explicit'[opt] 'framework'[opt] 'module' module-id attributes[opt]
1769 /// { module-member* }
1770 ///
1771 /// module-member:
1772 /// requires-declaration
1773 /// header-declaration
1774 /// submodule-declaration
1775 /// export-declaration
1776 /// export-as-declaration
1777 /// link-declaration
1778 ///
1779 /// submodule-declaration:
1780 /// module-declaration
1781 /// inferred-submodule-declaration
1782 void ModuleMapParser::parseModuleDecl() {
1785  if (Tok.is(MMToken::ExternKeyword)) {
1786  parseExternModuleDecl();
1787  return;
1788  }
1789 
1790  // Parse 'explicit' or 'framework' keyword, if present.
1791  SourceLocation ExplicitLoc;
1792  SourceLocation FrameworkLoc;
1793  bool Explicit = false;
1794  bool Framework = false;
1795 
1796  // Parse 'explicit' keyword, if present.
1798  ExplicitLoc = consumeToken();
1799  Explicit = true;
1800  }
1801 
1802  // Parse 'framework' keyword, if present.
1804  FrameworkLoc = consumeToken();
1805  Framework = true;
1806  }
1807 
1808  // Parse 'module' keyword.
1809  if (!Tok.is(MMToken::ModuleKeyword)) {
1810  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
1811  consumeToken();
1812  HadError = true;
1813  return;
1814  }
1815  CurrModuleDeclLoc = consumeToken(); // 'module' keyword
1816 
1817  // If we have a wildcard for the module name, this is an inferred submodule.
1818  // Parse it.
1819  if (Tok.is(MMToken::Star))
1820  return parseInferredModuleDecl(Framework, Explicit);
1821 
1822  // Parse the module name.
1823  ModuleId Id;
1824  if (parseModuleId(Id)) {
1825  HadError = true;
1826  return;
1827  }
1828 
1829  if (ActiveModule) {
1830  if (Id.size() > 1) {
1831  Diags.Report(Id.front().second, diag::err_mmap_nested_submodule_id)
1832  << SourceRange(Id.front().second, Id.back().second);
1833 
1834  HadError = true;
1835  return;
1836  }
1837  } else if (Id.size() == 1 && Explicit) {
1838  // Top-level modules can't be explicit.
1839  Diags.Report(ExplicitLoc, diag::err_mmap_explicit_top_level);
1840  Explicit = false;
1841  ExplicitLoc = SourceLocation();
1842  HadError = true;
1843  }
1844 
1845  Module *PreviousActiveModule = ActiveModule;
1846  if (Id.size() > 1) {
1847  // This module map defines a submodule. Go find the module of which it
1848  // is a submodule.
1849  ActiveModule = nullptr;
1850  const Module *TopLevelModule = nullptr;
1851  for (unsigned I = 0, N = Id.size() - 1; I != N; ++I) {
1852  if (Module *Next = Map.lookupModuleQualified(Id[I].first, ActiveModule)) {
1853  if (I == 0)
1854  TopLevelModule = Next;
1855  ActiveModule = Next;
1856  continue;
1857  }
1858 
1859  if (ActiveModule) {
1860  Diags.Report(Id[I].second, diag::err_mmap_missing_module_qualified)
1861  << Id[I].first
1862  << ActiveModule->getTopLevelModule()->getFullModuleName();
1863  } else {
1864  Diags.Report(Id[I].second, diag::err_mmap_expected_module_name);
1865  }
1866  HadError = true;
1867  return;
1868  }
1869 
1870  if (ModuleMapFile != Map.getContainingModuleMapFile(TopLevelModule)) {
1871  assert(ModuleMapFile != Map.getModuleMapFileForUniquing(TopLevelModule) &&
1872  "submodule defined in same file as 'module *' that allowed its "
1873  "top-level module");
1874  Map.addAdditionalModuleMapFile(TopLevelModule, ModuleMapFile);
1875  }
1876  }
1877 
1878  StringRef ModuleName = Id.back().first;
1879  SourceLocation ModuleNameLoc = Id.back().second;
1880 
1881  // Parse the optional attribute list.
1882  Attributes Attrs;
1883  if (parseOptionalAttributes(Attrs))
1884  return;
1885 
1886  // Parse the opening brace.
1887  if (!Tok.is(MMToken::LBrace)) {
1888  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace)
1889  << ModuleName;
1890  HadError = true;
1891  return;
1892  }
1893  SourceLocation LBraceLoc = consumeToken();
1894 
1895  // Determine whether this (sub)module has already been defined.
1896  Module *ShadowingModule = nullptr;
1897  if (Module *Existing = Map.lookupModuleQualified(ModuleName, ActiveModule)) {
1898  // We might see a (re)definition of a module that we already have a
1899  // definition for in two cases:
1900  // - If we loaded one definition from an AST file and we've just found a
1901  // corresponding definition in a module map file, or
1902  bool LoadedFromASTFile = Existing->DefinitionLoc.isInvalid();
1903  // - If we're building a (preprocessed) module and we've just loaded the
1904  // module map file from which it was created.
1905  bool ParsedAsMainInput =
1906  Map.LangOpts.getCompilingModule() == LangOptions::CMK_ModuleMap &&
1907  Map.LangOpts.CurrentModule == ModuleName &&
1908  SourceMgr.getDecomposedLoc(ModuleNameLoc).first !=
1909  SourceMgr.getDecomposedLoc(Existing->DefinitionLoc).first;
1910  if (!ActiveModule && (LoadedFromASTFile || ParsedAsMainInput)) {
1911  // Skip the module definition.
1912  skipUntil(MMToken::RBrace);
1913  if (Tok.is(MMToken::RBrace))
1914  consumeToken();
1915  else {
1916  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
1917  Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
1918  HadError = true;
1919  }
1920  return;
1921  }
1922 
1923  if (!Existing->Parent && Map.mayShadowNewModule(Existing)) {
1924  ShadowingModule = Existing;
1925  } else {
1926  // This is not a shawdowed module decl, it is an illegal redefinition.
1927  Diags.Report(ModuleNameLoc, diag::err_mmap_module_redefinition)
1928  << ModuleName;
1929  Diags.Report(Existing->DefinitionLoc, diag::note_mmap_prev_definition);
1930 
1931  // Skip the module definition.
1932  skipUntil(MMToken::RBrace);
1933  if (Tok.is(MMToken::RBrace))
1934  consumeToken();
1935 
1936  HadError = true;
1937  return;
1938  }
1939  }
1940 
1941  // Start defining this module.
1942  if (ShadowingModule) {
1943  ActiveModule =
1944  Map.createShadowedModule(ModuleName, Framework, ShadowingModule);
1945  } else {
1946  ActiveModule =
1947  Map.findOrCreateModule(ModuleName, ActiveModule, Framework, Explicit)
1948  .first;
1949  }
1950 
1951  ActiveModule->DefinitionLoc = ModuleNameLoc;
1952  if (Attrs.IsSystem || IsSystem)
1953  ActiveModule->IsSystem = true;
1954  if (Attrs.IsExternC)
1955  ActiveModule->IsExternC = true;
1956  if (Attrs.NoUndeclaredIncludes ||
1957  (!ActiveModule->Parent && ModuleName == "Darwin"))
1958  ActiveModule->NoUndeclaredIncludes = true;
1959  ActiveModule->Directory = Directory;
1960 
1961  StringRef MapFileName(ModuleMapFile->getName());
1962  if (MapFileName.endswith("module.private.modulemap") ||
1963  MapFileName.endswith("module_private.map")) {
1964  ActiveModule->ModuleMapIsPrivate = true;
1965  }
1966 
1967  // Private modules named as FooPrivate, Foo.Private or similar are likely a
1968  // user error; provide warnings, notes and fixits to direct users to use
1969  // Foo_Private instead.
1970  SourceLocation StartLoc =
1971  SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
1972  if (Map.HeaderInfo.getHeaderSearchOpts().ImplicitModuleMaps &&
1973  !Diags.isIgnored(diag::warn_mmap_mismatched_private_submodule,
1974  StartLoc) &&
1975  !Diags.isIgnored(diag::warn_mmap_mismatched_private_module_name,
1976  StartLoc) &&
1977  ActiveModule->ModuleMapIsPrivate)
1978  diagnosePrivateModules(ExplicitLoc, FrameworkLoc);
1979 
1980  bool Done = false;
1981  do {
1982  switch (Tok.Kind) {
1983  case MMToken::EndOfFile:
1984  case MMToken::RBrace:
1985  Done = true;
1986  break;
1987 
1988  case MMToken::ConfigMacros:
1989  parseConfigMacros();
1990  break;
1991 
1992  case MMToken::Conflict:
1993  parseConflict();
1994  break;
1995 
2000  parseModuleDecl();
2001  break;
2002 
2004  parseExportDecl();
2005  break;
2006 
2008  parseExportAsDecl();
2009  break;
2010 
2011  case MMToken::UseKeyword:
2012  parseUseDecl();
2013  break;
2014 
2016  parseRequiresDecl();
2017  break;
2018 
2020  parseHeaderDecl(MMToken::TextualKeyword, consumeToken());
2021  break;
2022 
2023  case MMToken::UmbrellaKeyword: {
2024  SourceLocation UmbrellaLoc = consumeToken();
2026  parseHeaderDecl(MMToken::UmbrellaKeyword, UmbrellaLoc);
2027  else
2028  parseUmbrellaDirDecl(UmbrellaLoc);
2029  break;
2030  }
2031 
2033  parseHeaderDecl(MMToken::ExcludeKeyword, consumeToken());
2034  break;
2035 
2037  parseHeaderDecl(MMToken::PrivateKeyword, consumeToken());
2038  break;
2039 
2041  parseHeaderDecl(MMToken::HeaderKeyword, consumeToken());
2042  break;
2043 
2044  case MMToken::LinkKeyword:
2045  parseLinkDecl();
2046  break;
2047 
2048  default:
2049  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_member);
2050  consumeToken();
2051  break;
2052  }
2053  } while (!Done);
2054 
2055  if (Tok.is(MMToken::RBrace))
2056  consumeToken();
2057  else {
2058  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2059  Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2060  HadError = true;
2061  }
2062 
2063  // If the active module is a top-level framework, and there are no link
2064  // libraries, automatically link against the framework.
2065  if (ActiveModule->IsFramework && !ActiveModule->isSubFramework() &&
2066  ActiveModule->LinkLibraries.empty()) {
2067  inferFrameworkLink(ActiveModule, Directory, SourceMgr.getFileManager());
2068  }
2069 
2070  // If the module meets all requirements but is still unavailable, mark the
2071  // whole tree as unavailable to prevent it from building.
2072  if (!ActiveModule->IsAvailable && !ActiveModule->IsMissingRequirement &&
2073  ActiveModule->Parent) {
2074  ActiveModule->getTopLevelModule()->markUnavailable();
2075  ActiveModule->getTopLevelModule()->MissingHeaders.append(
2076  ActiveModule->MissingHeaders.begin(), ActiveModule->MissingHeaders.end());
2077  }
2078 
2079  // We're done parsing this module. Pop back to the previous module.
2080  ActiveModule = PreviousActiveModule;
2081 }
2082 
2083 /// Parse an extern module declaration.
2084 ///
2085 /// extern module-declaration:
2086 /// 'extern' 'module' module-id string-literal
2087 void ModuleMapParser::parseExternModuleDecl() {
2088  assert(Tok.is(MMToken::ExternKeyword));
2089  SourceLocation ExternLoc = consumeToken(); // 'extern' keyword
2090 
2091  // Parse 'module' keyword.
2092  if (!Tok.is(MMToken::ModuleKeyword)) {
2093  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2094  consumeToken();
2095  HadError = true;
2096  return;
2097  }
2098  consumeToken(); // 'module' keyword
2099 
2100  // Parse the module name.
2101  ModuleId Id;
2102  if (parseModuleId(Id)) {
2103  HadError = true;
2104  return;
2105  }
2106 
2107  // Parse the referenced module map file name.
2108  if (!Tok.is(MMToken::StringLiteral)) {
2109  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_mmap_file);
2110  HadError = true;
2111  return;
2112  }
2113  std::string FileName = Tok.getString();
2114  consumeToken(); // filename
2115 
2116  StringRef FileNameRef = FileName;
2117  SmallString<128> ModuleMapFileName;
2118  if (llvm::sys::path::is_relative(FileNameRef)) {
2119  ModuleMapFileName += Directory->getName();
2120  llvm::sys::path::append(ModuleMapFileName, FileName);
2121  FileNameRef = ModuleMapFileName;
2122  }
2123  if (const FileEntry *File = SourceMgr.getFileManager().getFile(FileNameRef))
2124  Map.parseModuleMapFile(
2125  File, /*IsSystem=*/false,
2126  Map.HeaderInfo.getHeaderSearchOpts().ModuleMapFileHomeIsCwd
2127  ? Directory
2128  : File->getDir(),
2129  FileID(), nullptr, ExternLoc);
2130 }
2131 
2132 /// Whether to add the requirement \p Feature to the module \p M.
2133 ///
2134 /// This preserves backwards compatibility for two hacks in the Darwin system
2135 /// module map files:
2136 ///
2137 /// 1. The use of 'requires excluded' to make headers non-modular, which
2138 /// should really be mapped to 'textual' now that we have this feature. We
2139 /// drop the 'excluded' requirement, and set \p IsRequiresExcludedHack to
2140 /// true. Later, this bit will be used to map all the headers inside this
2141 /// module to 'textual'.
2142 ///
2143 /// This affects Darwin.C.excluded (for assert.h) and Tcl.Private.
2144 ///
2145 /// 2. Removes a bogus cplusplus requirement from IOKit.avc. This requirement
2146 /// was never correct and causes issues now that we check it, so drop it.
2147 static bool shouldAddRequirement(Module *M, StringRef Feature,
2148  bool &IsRequiresExcludedHack) {
2149  if (Feature == "excluded" &&
2150  (M->fullModuleNameIs({"Darwin", "C", "excluded"}) ||
2151  M->fullModuleNameIs({"Tcl", "Private"}))) {
2152  IsRequiresExcludedHack = true;
2153  return false;
2154  } else if (Feature == "cplusplus" && M->fullModuleNameIs({"IOKit", "avc"})) {
2155  return false;
2156  }
2157 
2158  return true;
2159 }
2160 
2161 /// Parse a requires declaration.
2162 ///
2163 /// requires-declaration:
2164 /// 'requires' feature-list
2165 ///
2166 /// feature-list:
2167 /// feature ',' feature-list
2168 /// feature
2169 ///
2170 /// feature:
2171 /// '!'[opt] identifier
2172 void ModuleMapParser::parseRequiresDecl() {
2173  assert(Tok.is(MMToken::RequiresKeyword));
2174 
2175  // Parse 'requires' keyword.
2176  consumeToken();
2177 
2178  // Parse the feature-list.
2179  do {
2180  bool RequiredState = true;
2181  if (Tok.is(MMToken::Exclaim)) {
2182  RequiredState = false;
2183  consumeToken();
2184  }
2185 
2186  if (!Tok.is(MMToken::Identifier)) {
2187  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_feature);
2188  HadError = true;
2189  return;
2190  }
2191 
2192  // Consume the feature name.
2193  std::string Feature = Tok.getString();
2194  consumeToken();
2195 
2196  bool IsRequiresExcludedHack = false;
2197  bool ShouldAddRequirement =
2198  shouldAddRequirement(ActiveModule, Feature, IsRequiresExcludedHack);
2199 
2200  if (IsRequiresExcludedHack)
2201  UsesRequiresExcludedHack.insert(ActiveModule);
2202 
2203  if (ShouldAddRequirement) {
2204  // Add this feature.
2205  ActiveModule->addRequirement(Feature, RequiredState, Map.LangOpts,
2206  *Map.Target);
2207  }
2208 
2209  if (!Tok.is(MMToken::Comma))
2210  break;
2211 
2212  // Consume the comma.
2213  consumeToken();
2214  } while (true);
2215 }
2216 
2217 /// Parse a header declaration.
2218 ///
2219 /// header-declaration:
2220 /// 'textual'[opt] 'header' string-literal
2221 /// 'private' 'textual'[opt] 'header' string-literal
2222 /// 'exclude' 'header' string-literal
2223 /// 'umbrella' 'header' string-literal
2224 ///
2225 /// FIXME: Support 'private textual header'.
2226 void ModuleMapParser::parseHeaderDecl(MMToken::TokenKind LeadingToken,
2227  SourceLocation LeadingLoc) {
2228  // We've already consumed the first token.
2230  if (LeadingToken == MMToken::PrivateKeyword) {
2231  Role = ModuleMap::PrivateHeader;
2232  // 'private' may optionally be followed by 'textual'.
2234  LeadingToken = Tok.Kind;
2235  consumeToken();
2236  }
2237  }
2238 
2239  if (LeadingToken == MMToken::TextualKeyword)
2241 
2242  if (UsesRequiresExcludedHack.count(ActiveModule)) {
2243  // Mark this header 'textual' (see doc comment for
2244  // Module::UsesRequiresExcludedHack).
2246  }
2247 
2248  if (LeadingToken != MMToken::HeaderKeyword) {
2249  if (!Tok.is(MMToken::HeaderKeyword)) {
2250  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2251  << (LeadingToken == MMToken::PrivateKeyword ? "private" :
2252  LeadingToken == MMToken::ExcludeKeyword ? "exclude" :
2253  LeadingToken == MMToken::TextualKeyword ? "textual" : "umbrella");
2254  return;
2255  }
2256  consumeToken();
2257  }
2258 
2259  // Parse the header name.
2260  if (!Tok.is(MMToken::StringLiteral)) {
2261  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2262  << "header";
2263  HadError = true;
2264  return;
2265  }
2267  Header.FileName = Tok.getString();
2268  Header.FileNameLoc = consumeToken();
2269  Header.IsUmbrella = LeadingToken == MMToken::UmbrellaKeyword;
2270  Header.Kind =
2271  (LeadingToken == MMToken::ExcludeKeyword ? Module::HK_Excluded
2272  : Map.headerRoleToKind(Role));
2273 
2274  // Check whether we already have an umbrella.
2275  if (Header.IsUmbrella && ActiveModule->Umbrella) {
2276  Diags.Report(Header.FileNameLoc, diag::err_mmap_umbrella_clash)
2277  << ActiveModule->getFullModuleName();
2278  HadError = true;
2279  return;
2280  }
2281 
2282  // If we were given stat information, parse it so we can skip looking for
2283  // the file.
2284  if (Tok.is(MMToken::LBrace)) {
2285  SourceLocation LBraceLoc = consumeToken();
2286 
2287  while (!Tok.is(MMToken::RBrace) && !Tok.is(MMToken::EndOfFile)) {
2288  enum Attribute { Size, ModTime, Unknown };
2289  StringRef Str = Tok.getString();
2290  SourceLocation Loc = consumeToken();
2291  switch (llvm::StringSwitch<Attribute>(Str)
2292  .Case("size", Size)
2293  .Case("mtime", ModTime)
2294  .Default(Unknown)) {
2295  case Size:
2296  if (Header.Size)
2297  Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
2298  if (!Tok.is(MMToken::IntegerLiteral)) {
2299  Diags.Report(Tok.getLocation(),
2300  diag::err_mmap_invalid_header_attribute_value) << Str;
2301  skipUntil(MMToken::RBrace);
2302  break;
2303  }
2304  Header.Size = Tok.getInteger();
2305  consumeToken();
2306  break;
2307 
2308  case ModTime:
2309  if (Header.ModTime)
2310  Diags.Report(Loc, diag::err_mmap_duplicate_header_attribute) << Str;
2311  if (!Tok.is(MMToken::IntegerLiteral)) {
2312  Diags.Report(Tok.getLocation(),
2313  diag::err_mmap_invalid_header_attribute_value) << Str;
2314  skipUntil(MMToken::RBrace);
2315  break;
2316  }
2317  Header.ModTime = Tok.getInteger();
2318  consumeToken();
2319  break;
2320 
2321  case Unknown:
2322  Diags.Report(Loc, diag::err_mmap_expected_header_attribute);
2323  skipUntil(MMToken::RBrace);
2324  break;
2325  }
2326  }
2327 
2328  if (Tok.is(MMToken::RBrace))
2329  consumeToken();
2330  else {
2331  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2332  Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2333  HadError = true;
2334  }
2335  }
2336 
2337  bool NeedsFramework = false;
2338  Map.addUnresolvedHeader(ActiveModule, std::move(Header), NeedsFramework);
2339 
2340  if (NeedsFramework && ActiveModule)
2341  Diags.Report(CurrModuleDeclLoc, diag::note_mmap_add_framework_keyword)
2342  << ActiveModule->getFullModuleName()
2343  << FixItHint::CreateReplacement(CurrModuleDeclLoc, "framework module");
2344 }
2345 
2347  const Module::Header *B) {
2348  return A->NameAsWritten.compare(B->NameAsWritten);
2349 }
2350 
2351 /// Parse an umbrella directory declaration.
2352 ///
2353 /// umbrella-dir-declaration:
2354 /// umbrella string-literal
2355 void ModuleMapParser::parseUmbrellaDirDecl(SourceLocation UmbrellaLoc) {
2356  // Parse the directory name.
2357  if (!Tok.is(MMToken::StringLiteral)) {
2358  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_header)
2359  << "umbrella";
2360  HadError = true;
2361  return;
2362  }
2363 
2364  std::string DirName = Tok.getString();
2365  SourceLocation DirNameLoc = consumeToken();
2366 
2367  // Check whether we already have an umbrella.
2368  if (ActiveModule->Umbrella) {
2369  Diags.Report(DirNameLoc, diag::err_mmap_umbrella_clash)
2370  << ActiveModule->getFullModuleName();
2371  HadError = true;
2372  return;
2373  }
2374 
2375  // Look for this file.
2376  const DirectoryEntry *Dir = nullptr;
2377  if (llvm::sys::path::is_absolute(DirName))
2378  Dir = SourceMgr.getFileManager().getDirectory(DirName);
2379  else {
2380  SmallString<128> PathName;
2381  PathName = Directory->getName();
2382  llvm::sys::path::append(PathName, DirName);
2383  Dir = SourceMgr.getFileManager().getDirectory(PathName);
2384  }
2385 
2386  if (!Dir) {
2387  Diags.Report(DirNameLoc, diag::warn_mmap_umbrella_dir_not_found)
2388  << DirName;
2389  return;
2390  }
2391 
2392  if (UsesRequiresExcludedHack.count(ActiveModule)) {
2393  // Mark this header 'textual' (see doc comment for
2394  // ModuleMapParser::UsesRequiresExcludedHack). Although iterating over the
2395  // directory is relatively expensive, in practice this only applies to the
2396  // uncommonly used Tcl module on Darwin platforms.
2397  std::error_code EC;
2399  llvm::vfs::FileSystem &FS =
2400  *SourceMgr.getFileManager().getVirtualFileSystem();
2401  for (llvm::vfs::recursive_directory_iterator I(FS, Dir->getName(), EC), E;
2402  I != E && !EC; I.increment(EC)) {
2403  if (const FileEntry *FE = SourceMgr.getFileManager().getFile(I->path())) {
2404 
2405  Module::Header Header = {I->path(), FE};
2406  Headers.push_back(std::move(Header));
2407  }
2408  }
2409 
2410  // Sort header paths so that the pcm doesn't depend on iteration order.
2411  llvm::array_pod_sort(Headers.begin(), Headers.end(), compareModuleHeaders);
2412 
2413  for (auto &Header : Headers)
2414  Map.addHeader(ActiveModule, std::move(Header), ModuleMap::TextualHeader);
2415  return;
2416  }
2417 
2418  if (Module *OwningModule = Map.UmbrellaDirs[Dir]) {
2419  Diags.Report(UmbrellaLoc, diag::err_mmap_umbrella_clash)
2420  << OwningModule->getFullModuleName();
2421  HadError = true;
2422  return;
2423  }
2424 
2425  // Record this umbrella directory.
2426  Map.setUmbrellaDir(ActiveModule, Dir, DirName);
2427 }
2428 
2429 /// Parse a module export declaration.
2430 ///
2431 /// export-declaration:
2432 /// 'export' wildcard-module-id
2433 ///
2434 /// wildcard-module-id:
2435 /// identifier
2436 /// '*'
2437 /// identifier '.' wildcard-module-id
2438 void ModuleMapParser::parseExportDecl() {
2439  assert(Tok.is(MMToken::ExportKeyword));
2440  SourceLocation ExportLoc = consumeToken();
2441 
2442  // Parse the module-id with an optional wildcard at the end.
2443  ModuleId ParsedModuleId;
2444  bool Wildcard = false;
2445  do {
2446  // FIXME: Support string-literal module names here.
2447  if (Tok.is(MMToken::Identifier)) {
2448  ParsedModuleId.push_back(std::make_pair(Tok.getString(),
2449  Tok.getLocation()));
2450  consumeToken();
2451 
2452  if (Tok.is(MMToken::Period)) {
2453  consumeToken();
2454  continue;
2455  }
2456 
2457  break;
2458  }
2459 
2460  if(Tok.is(MMToken::Star)) {
2461  Wildcard = true;
2462  consumeToken();
2463  break;
2464  }
2465 
2466  Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2467  HadError = true;
2468  return;
2469  } while (true);
2470 
2471  Module::UnresolvedExportDecl Unresolved = {
2472  ExportLoc, ParsedModuleId, Wildcard
2473  };
2474  ActiveModule->UnresolvedExports.push_back(Unresolved);
2475 }
2476 
2477 /// Parse a module export_as declaration.
2478 ///
2479 /// export-as-declaration:
2480 /// 'export_as' identifier
2481 void ModuleMapParser::parseExportAsDecl() {
2482  assert(Tok.is(MMToken::ExportAsKeyword));
2483  consumeToken();
2484 
2485  if (!Tok.is(MMToken::Identifier)) {
2486  Diags.Report(Tok.getLocation(), diag::err_mmap_module_id);
2487  HadError = true;
2488  return;
2489  }
2490 
2491  if (ActiveModule->Parent) {
2492  Diags.Report(Tok.getLocation(), diag::err_mmap_submodule_export_as);
2493  consumeToken();
2494  return;
2495  }
2496 
2497  if (!ActiveModule->ExportAsModule.empty()) {
2498  if (ActiveModule->ExportAsModule == Tok.getString()) {
2499  Diags.Report(Tok.getLocation(), diag::warn_mmap_redundant_export_as)
2500  << ActiveModule->Name << Tok.getString();
2501  } else {
2502  Diags.Report(Tok.getLocation(), diag::err_mmap_conflicting_export_as)
2503  << ActiveModule->Name << ActiveModule->ExportAsModule
2504  << Tok.getString();
2505  }
2506  }
2507 
2508  ActiveModule->ExportAsModule = Tok.getString();
2509  Map.addLinkAsDependency(ActiveModule);
2510 
2511  consumeToken();
2512 }
2513 
2514 /// Parse a module use declaration.
2515 ///
2516 /// use-declaration:
2517 /// 'use' wildcard-module-id
2518 void ModuleMapParser::parseUseDecl() {
2519  assert(Tok.is(MMToken::UseKeyword));
2520  auto KWLoc = consumeToken();
2521  // Parse the module-id.
2522  ModuleId ParsedModuleId;
2523  parseModuleId(ParsedModuleId);
2524 
2525  if (ActiveModule->Parent)
2526  Diags.Report(KWLoc, diag::err_mmap_use_decl_submodule);
2527  else
2528  ActiveModule->UnresolvedDirectUses.push_back(ParsedModuleId);
2529 }
2530 
2531 /// Parse a link declaration.
2532 ///
2533 /// module-declaration:
2534 /// 'link' 'framework'[opt] string-literal
2535 void ModuleMapParser::parseLinkDecl() {
2536  assert(Tok.is(MMToken::LinkKeyword));
2537  SourceLocation LinkLoc = consumeToken();
2538 
2539  // Parse the optional 'framework' keyword.
2540  bool IsFramework = false;
2542  consumeToken();
2543  IsFramework = true;
2544  }
2545 
2546  // Parse the library name
2547  if (!Tok.is(MMToken::StringLiteral)) {
2548  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_library_name)
2549  << IsFramework << SourceRange(LinkLoc);
2550  HadError = true;
2551  return;
2552  }
2553 
2554  std::string LibraryName = Tok.getString();
2555  consumeToken();
2556  ActiveModule->LinkLibraries.push_back(Module::LinkLibrary(LibraryName,
2557  IsFramework));
2558 }
2559 
2560 /// Parse a configuration macro declaration.
2561 ///
2562 /// module-declaration:
2563 /// 'config_macros' attributes[opt] config-macro-list?
2564 ///
2565 /// config-macro-list:
2566 /// identifier (',' identifier)?
2567 void ModuleMapParser::parseConfigMacros() {
2568  assert(Tok.is(MMToken::ConfigMacros));
2569  SourceLocation ConfigMacrosLoc = consumeToken();
2570 
2571  // Only top-level modules can have configuration macros.
2572  if (ActiveModule->Parent) {
2573  Diags.Report(ConfigMacrosLoc, diag::err_mmap_config_macro_submodule);
2574  }
2575 
2576  // Parse the optional attributes.
2577  Attributes Attrs;
2578  if (parseOptionalAttributes(Attrs))
2579  return;
2580 
2581  if (Attrs.IsExhaustive && !ActiveModule->Parent) {
2582  ActiveModule->ConfigMacrosExhaustive = true;
2583  }
2584 
2585  // If we don't have an identifier, we're done.
2586  // FIXME: Support macros with the same name as a keyword here.
2587  if (!Tok.is(MMToken::Identifier))
2588  return;
2589 
2590  // Consume the first identifier.
2591  if (!ActiveModule->Parent) {
2592  ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2593  }
2594  consumeToken();
2595 
2596  do {
2597  // If there's a comma, consume it.
2598  if (!Tok.is(MMToken::Comma))
2599  break;
2600  consumeToken();
2601 
2602  // We expect to see a macro name here.
2603  // FIXME: Support macros with the same name as a keyword here.
2604  if (!Tok.is(MMToken::Identifier)) {
2605  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_config_macro);
2606  break;
2607  }
2608 
2609  // Consume the macro name.
2610  if (!ActiveModule->Parent) {
2611  ActiveModule->ConfigMacros.push_back(Tok.getString().str());
2612  }
2613  consumeToken();
2614  } while (true);
2615 }
2616 
2617 /// Format a module-id into a string.
2618 static std::string formatModuleId(const ModuleId &Id) {
2619  std::string result;
2620  {
2621  llvm::raw_string_ostream OS(result);
2622 
2623  for (unsigned I = 0, N = Id.size(); I != N; ++I) {
2624  if (I)
2625  OS << ".";
2626  OS << Id[I].first;
2627  }
2628  }
2629 
2630  return result;
2631 }
2632 
2633 /// Parse a conflict declaration.
2634 ///
2635 /// module-declaration:
2636 /// 'conflict' module-id ',' string-literal
2637 void ModuleMapParser::parseConflict() {
2638  assert(Tok.is(MMToken::Conflict));
2639  SourceLocation ConflictLoc = consumeToken();
2640  Module::UnresolvedConflict Conflict;
2641 
2642  // Parse the module-id.
2643  if (parseModuleId(Conflict.Id))
2644  return;
2645 
2646  // Parse the ','.
2647  if (!Tok.is(MMToken::Comma)) {
2648  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_comma)
2649  << SourceRange(ConflictLoc);
2650  return;
2651  }
2652  consumeToken();
2653 
2654  // Parse the message.
2655  if (!Tok.is(MMToken::StringLiteral)) {
2656  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_conflicts_message)
2657  << formatModuleId(Conflict.Id);
2658  return;
2659  }
2660  Conflict.Message = Tok.getString().str();
2661  consumeToken();
2662 
2663  // Add this unresolved conflict.
2664  ActiveModule->UnresolvedConflicts.push_back(Conflict);
2665 }
2666 
2667 /// Parse an inferred module declaration (wildcard modules).
2668 ///
2669 /// module-declaration:
2670 /// 'explicit'[opt] 'framework'[opt] 'module' * attributes[opt]
2671 /// { inferred-module-member* }
2672 ///
2673 /// inferred-module-member:
2674 /// 'export' '*'
2675 /// 'exclude' identifier
2676 void ModuleMapParser::parseInferredModuleDecl(bool Framework, bool Explicit) {
2677  assert(Tok.is(MMToken::Star));
2678  SourceLocation StarLoc = consumeToken();
2679  bool Failed = false;
2680 
2681  // Inferred modules must be submodules.
2682  if (!ActiveModule && !Framework) {
2683  Diags.Report(StarLoc, diag::err_mmap_top_level_inferred_submodule);
2684  Failed = true;
2685  }
2686 
2687  if (ActiveModule) {
2688  // Inferred modules must have umbrella directories.
2689  if (!Failed && ActiveModule->IsAvailable &&
2690  !ActiveModule->getUmbrellaDir()) {
2691  Diags.Report(StarLoc, diag::err_mmap_inferred_no_umbrella);
2692  Failed = true;
2693  }
2694 
2695  // Check for redefinition of an inferred module.
2696  if (!Failed && ActiveModule->InferSubmodules) {
2697  Diags.Report(StarLoc, diag::err_mmap_inferred_redef);
2698  if (ActiveModule->InferredSubmoduleLoc.isValid())
2699  Diags.Report(ActiveModule->InferredSubmoduleLoc,
2700  diag::note_mmap_prev_definition);
2701  Failed = true;
2702  }
2703 
2704  // Check for the 'framework' keyword, which is not permitted here.
2705  if (Framework) {
2706  Diags.Report(StarLoc, diag::err_mmap_inferred_framework_submodule);
2707  Framework = false;
2708  }
2709  } else if (Explicit) {
2710  Diags.Report(StarLoc, diag::err_mmap_explicit_inferred_framework);
2711  Explicit = false;
2712  }
2713 
2714  // If there were any problems with this inferred submodule, skip its body.
2715  if (Failed) {
2716  if (Tok.is(MMToken::LBrace)) {
2717  consumeToken();
2718  skipUntil(MMToken::RBrace);
2719  if (Tok.is(MMToken::RBrace))
2720  consumeToken();
2721  }
2722  HadError = true;
2723  return;
2724  }
2725 
2726  // Parse optional attributes.
2727  Attributes Attrs;
2728  if (parseOptionalAttributes(Attrs))
2729  return;
2730 
2731  if (ActiveModule) {
2732  // Note that we have an inferred submodule.
2733  ActiveModule->InferSubmodules = true;
2734  ActiveModule->InferredSubmoduleLoc = StarLoc;
2735  ActiveModule->InferExplicitSubmodules = Explicit;
2736  } else {
2737  // We'll be inferring framework modules for this directory.
2738  Map.InferredDirectories[Directory].InferModules = true;
2739  Map.InferredDirectories[Directory].Attrs = Attrs;
2740  Map.InferredDirectories[Directory].ModuleMapFile = ModuleMapFile;
2741  // FIXME: Handle the 'framework' keyword.
2742  }
2743 
2744  // Parse the opening brace.
2745  if (!Tok.is(MMToken::LBrace)) {
2746  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_lbrace_wildcard);
2747  HadError = true;
2748  return;
2749  }
2750  SourceLocation LBraceLoc = consumeToken();
2751 
2752  // Parse the body of the inferred submodule.
2753  bool Done = false;
2754  do {
2755  switch (Tok.Kind) {
2756  case MMToken::EndOfFile:
2757  case MMToken::RBrace:
2758  Done = true;
2759  break;
2760 
2762  if (ActiveModule) {
2763  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2764  << (ActiveModule != nullptr);
2765  consumeToken();
2766  break;
2767  }
2768 
2769  consumeToken();
2770  // FIXME: Support string-literal module names here.
2771  if (!Tok.is(MMToken::Identifier)) {
2772  Diags.Report(Tok.getLocation(), diag::err_mmap_missing_exclude_name);
2773  break;
2774  }
2775 
2776  Map.InferredDirectories[Directory].ExcludedModules
2777  .push_back(Tok.getString());
2778  consumeToken();
2779  break;
2780 
2782  if (!ActiveModule) {
2783  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2784  << (ActiveModule != nullptr);
2785  consumeToken();
2786  break;
2787  }
2788 
2789  consumeToken();
2790  if (Tok.is(MMToken::Star))
2791  ActiveModule->InferExportWildcard = true;
2792  else
2793  Diags.Report(Tok.getLocation(),
2794  diag::err_mmap_expected_export_wildcard);
2795  consumeToken();
2796  break;
2797 
2803  default:
2804  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_inferred_member)
2805  << (ActiveModule != nullptr);
2806  consumeToken();
2807  break;
2808  }
2809  } while (!Done);
2810 
2811  if (Tok.is(MMToken::RBrace))
2812  consumeToken();
2813  else {
2814  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rbrace);
2815  Diags.Report(LBraceLoc, diag::note_mmap_lbrace_match);
2816  HadError = true;
2817  }
2818 }
2819 
2820 /// Parse optional attributes.
2821 ///
2822 /// attributes:
2823 /// attribute attributes
2824 /// attribute
2825 ///
2826 /// attribute:
2827 /// [ identifier ]
2828 ///
2829 /// \param Attrs Will be filled in with the parsed attributes.
2830 ///
2831 /// \returns true if an error occurred, false otherwise.
2832 bool ModuleMapParser::parseOptionalAttributes(Attributes &Attrs) {
2833  bool HadError = false;
2834 
2835  while (Tok.is(MMToken::LSquare)) {
2836  // Consume the '['.
2837  SourceLocation LSquareLoc = consumeToken();
2838 
2839  // Check whether we have an attribute name here.
2840  if (!Tok.is(MMToken::Identifier)) {
2841  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_attribute);
2842  skipUntil(MMToken::RSquare);
2843  if (Tok.is(MMToken::RSquare))
2844  consumeToken();
2845  HadError = true;
2846  }
2847 
2848  // Decode the attribute name.
2849  AttributeKind Attribute
2850  = llvm::StringSwitch<AttributeKind>(Tok.getString())
2851  .Case("exhaustive", AT_exhaustive)
2852  .Case("extern_c", AT_extern_c)
2853  .Case("no_undeclared_includes", AT_no_undeclared_includes)
2854  .Case("system", AT_system)
2855  .Default(AT_unknown);
2856  switch (Attribute) {
2857  case AT_unknown:
2858  Diags.Report(Tok.getLocation(), diag::warn_mmap_unknown_attribute)
2859  << Tok.getString();
2860  break;
2861 
2862  case AT_system:
2863  Attrs.IsSystem = true;
2864  break;
2865 
2866  case AT_extern_c:
2867  Attrs.IsExternC = true;
2868  break;
2869 
2870  case AT_exhaustive:
2871  Attrs.IsExhaustive = true;
2872  break;
2873 
2874  case AT_no_undeclared_includes:
2875  Attrs.NoUndeclaredIncludes = true;
2876  break;
2877  }
2878  consumeToken();
2879 
2880  // Consume the ']'.
2881  if (!Tok.is(MMToken::RSquare)) {
2882  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_rsquare);
2883  Diags.Report(LSquareLoc, diag::note_mmap_lsquare_match);
2884  skipUntil(MMToken::RSquare);
2885  HadError = true;
2886  }
2887 
2888  if (Tok.is(MMToken::RSquare))
2889  consumeToken();
2890  }
2891 
2892  return HadError;
2893 }
2894 
2895 /// Parse a module map file.
2896 ///
2897 /// module-map-file:
2898 /// module-declaration*
2900  do {
2901  switch (Tok.Kind) {
2902  case MMToken::EndOfFile:
2903  return HadError;
2904 
2909  parseModuleDecl();
2910  break;
2911 
2912  case MMToken::Comma:
2913  case MMToken::ConfigMacros:
2914  case MMToken::Conflict:
2915  case MMToken::Exclaim:
2920  case MMToken::Identifier:
2921  case MMToken::LBrace:
2922  case MMToken::LinkKeyword:
2923  case MMToken::LSquare:
2924  case MMToken::Period:
2926  case MMToken::RBrace:
2927  case MMToken::RSquare:
2929  case MMToken::Star:
2934  case MMToken::UseKeyword:
2935  Diags.Report(Tok.getLocation(), diag::err_mmap_expected_module);
2936  HadError = true;
2937  consumeToken();
2938  break;
2939  }
2940  } while (true);
2941 }
2942 
2943 bool ModuleMap::parseModuleMapFile(const FileEntry *File, bool IsSystem,
2944  const DirectoryEntry *Dir, FileID ID,
2945  unsigned *Offset,
2946  SourceLocation ExternModuleLoc) {
2947  assert(Target && "Missing target information");
2948  llvm::DenseMap<const FileEntry *, bool>::iterator Known
2949  = ParsedModuleMap.find(File);
2950  if (Known != ParsedModuleMap.end())
2951  return Known->second;
2952 
2953  // If the module map file wasn't already entered, do so now.
2954  if (ID.isInvalid()) {
2955  auto FileCharacter =
2957  ID = SourceMgr.createFileID(File, ExternModuleLoc, FileCharacter);
2958  }
2959 
2960  assert(Target && "Missing target information");
2961  const llvm::MemoryBuffer *Buffer = SourceMgr.getBuffer(ID);
2962  if (!Buffer)
2963  return ParsedModuleMap[File] = true;
2964  assert((!Offset || *Offset <= Buffer->getBufferSize()) &&
2965  "invalid buffer offset");
2966 
2967  // Parse this module map file.
2968  Lexer L(SourceMgr.getLocForStartOfFile(ID), MMapLangOpts,
2969  Buffer->getBufferStart(),
2970  Buffer->getBufferStart() + (Offset ? *Offset : 0),
2971  Buffer->getBufferEnd());
2972  SourceLocation Start = L.getSourceLocation();
2973  ModuleMapParser Parser(L, SourceMgr, Target, Diags, *this, File, Dir,
2974  IsSystem);
2975  bool Result = Parser.parseModuleMapFile();
2976  ParsedModuleMap[File] = Result;
2977 
2978  if (Offset) {
2979  auto Loc = SourceMgr.getDecomposedLoc(Parser.getLocation());
2980  assert(Loc.first == ID && "stopped in a different file?");
2981  *Offset = Loc.second;
2982  }
2983 
2984  // Notify callbacks that we parsed it.
2985  for (const auto &Cb : Callbacks)
2986  Cb->moduleMapFileRead(Start, *File, IsSystem);
2987 
2988  return Result;
2989 }
unsigned IsAvailable
Whether this module is available in the current translation unit.
Definition: Module.h:212
ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target, HeaderSearch &HeaderInfo)
Construct a new module map.
Definition: ModuleMap.cpp:313
ModuleHeaderRole getRole() const
The role of this header within the module.
Definition: ModuleMap.h:168
static unsigned getSpelling(const Token &Tok, const char *&Buffer, const SourceManager &SourceMgr, const LangOptions &LangOpts, bool *Invalid=nullptr)
getSpelling - This method is used to get the spelling of a token into a preallocated buffer...
Definition: Lexer.cpp:388
void setInferredModuleAllowedBy(Module *M, const FileEntry *ModMap)
Definition: ModuleMap.cpp:1221
SmallVector< UnresolvedExportDecl, 2 > UnresolvedExports
The set of export declarations that have yet to be resolved.
Definition: Module.h:308
SourceLocation getLocation() const
Definition: ModuleMap.cpp:1347
std::string Name
The name of this module.
Definition: Module.h:67
static Module * getTopLevelOrNull(Module *M)
Definition: ModuleMap.cpp:461
This header is included but private.
Definition: ModuleMap.h:128
Lexer - This provides a simple interface that turns a text buffer into a stream of tokens...
Definition: Lexer.h:76
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
SmallVector< UnresolvedHeaderDirective, 1 > MissingHeaders
Headers that are mentioned in the module map file but could not be found on the file system...
Definition: Module.h:187
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:351
bool isSubFramework() const
Determine whether this module is a subframework of another framework.
Definition: Module.h:423
unsigned ImplicitModuleMaps
Implicit module maps.
Implements support for file system lookup, file system caching, and directory search management...
Definition: FileManager.h:120
void dump()
Dump the contents of the module map, for debugging purposes.
Definition: ModuleMap.cpp:1226
Defines the clang::FileManager interface and associated types.
An unresolved conflict with another module.
Definition: Module.h:346
time_t getModificationTime() const
Definition: FileManager.h:91
This header is part of the module (for layering purposes) but should be textually included...
Definition: ModuleMap.h:132
uint64_t IntegerValue
Definition: ModuleMap.cpp:1335
unsigned IsExternC
Whether this is an &#39;extern "C"&#39; module (which implicitly puts all headers in it within an &#39;extern "C"...
Definition: Module.h:230
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {...
Definition: Token.h:94
std::vector< UnresolvedConflict > UnresolvedConflicts
The list of conflicts for which the module-id has not yet been resolved.
Definition: Module.h:356
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:450
Defines the SourceManager interface.
void loadTopLevelSystemModules()
Load all known, top-level system modules.
Defines the clang::Module class, which describes a module in the source code.
void excludeHeader(Module *Mod, Module::Header Header)
Marks this header as being excluded from the given module.
Definition: ModuleMap.cpp:1194
unsigned IsFramework
Whether this is a framework module.
Definition: Module.h:218
const FileEntry * getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module...
Definition: ModuleMap.cpp:1213
ModuleMapParser(Lexer &L, SourceManager &SourceMgr, const TargetInfo *Target, DiagnosticsEngine &Diags, ModuleMap &Map, const FileEntry *ModuleMapFile, const DirectoryEntry *Directory, bool IsSystem)
Definition: ModuleMap.cpp:1443
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Definition: Diagnostic.h:1294
bool isCompilingModule() const
Are we compiling a module interface (.cppm or module map)?
Definition: LangOptions.h:262
Parser - This implements a parser for the C family of languages.
Definition: Parser.h:57
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1261
unsigned Location
Definition: ModuleMap.cpp:1328
const char * StringData
Definition: ModuleMap.cpp:1332
Module * createHeaderModule(StringRef Name, ArrayRef< Module::Header > Headers)
Create a header module from the specified list of headers.
Definition: ModuleMap.cpp:845
const FileEntry * lookupModuleMapFile(const DirectoryEntry *Dir, bool IsFramework)
Try to find a module map file in the given directory, returning nullptr if none is found...
Module * lookupModuleQualified(StringRef Name, Module *Context) const
Retrieve a module with the given name within the given context, using direct (qualified) name lookup...
Definition: ModuleMap.cpp:782
Module * createShadowedModule(StringRef Name, bool IsFramework, Module *ShadowingModule)
Create a new top-level module that is shadowed by ShadowingModule.
Definition: ModuleMap.cpp:1070
static void appendSubframeworkPaths(Module *Mod, SmallVectorImpl< char > &Path)
Append to Paths the set of paths needed to get to the subframework in which the given module lives...
Definition: ModuleMap.cpp:157
bool isPartOfFramework() const
Determine whether this module is a part of a framework, either because it is a framework module or be...
Definition: Module.h:413
tok::TokenKind getKind() const
Definition: Token.h:89
std::string getName(ArrayRef< StringRef > Parts) const
Get the platform-specific name separator.
void markUnavailable(bool MissingRequirement=false)
Mark this module and all of its submodules as unavailable.
Definition: Module.cpp:288
unsigned GetStringLength() const
FileManager & getFileManager() const
A library or framework to link against when an entity from this module is used.
Definition: Module.h:318
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:1274
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1140
static SourceLocation getFromRawEncoding(unsigned Encoding)
Turn a raw encoding of a SourceLocation object into a real SourceLocation.
bool isHeaderUnavailableInModule(const FileEntry *Header, const Module *RequestingModule) const
Determine whether the given header is unavailable as part of the specified module.
Definition: ModuleMap.cpp:672
Token - This structure provides full information about a lexed token.
Definition: Token.h:34
void setUmbrellaDir(Module *Mod, const DirectoryEntry *UmbrellaDir, Twine NameAsWritten)
Sets the umbrella directory of the given module to the given directory.
Definition: ModuleMap.cpp:1097
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:49
Compiling a module from a module map.
Definition: LangOptions.h:78
Describes a module or submodule.
Definition: Module.h:64
bool isAccessibleFrom(Module *M) const
Whether this header is accessible from the specified module.
Definition: ModuleMap.h:176
static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind)
Convert a header kind to a role. Requires Kind to not be HK_Excluded.
Definition: ModuleMap.cpp:91
bool isInvalid() const
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:764
Module * createGlobalModuleForInterfaceUnit(SourceLocation Loc)
Create a &#39;global module&#39; for a C++ Modules TS module interface unit.
Definition: ModuleMap.cpp:809
static bool isBuiltinHeader(StringRef FileName)
Is this a compiler builtin header?
Definition: ModuleMap.cpp:374
unsigned InferExportWildcard
Whether, when inferring submodules, the inferr submodules should export all modules they import (e...
Definition: Module.h:247
std::string getFullModuleName(bool AllowStringLiterals=false) const
Retrieve the full name of this module, including the path from its top-level module.
Definition: Module.cpp:213
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix. ...
Definition: Token.h:290
const FormatToken & Tok
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified...
std::string Message
The message provided to the user when there is a conflict.
Definition: Module.h:364
ModuleId Id
The (unresolved) module id.
Definition: Module.h:348
unsigned StringLength
Definition: ModuleMap.cpp:1329
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:148
bool isSubModuleOf(const Module *Other) const
Determine whether this module is a submodule of the given other module.
Definition: Module.cpp:163
Module * Parent
The parent of this module.
Definition: Module.h:90
unsigned IsInferred
Whether this is an inferred submodule (module * { ... }).
Definition: Module.h:233
Defines the Diagnostic-related interfaces.
void setTarget(const TargetInfo &Target)
Set the target information.
Definition: ModuleMap.cpp:328
unsigned NoUndeclaredIncludes
Whether files in this module can only include non-modular headers and headers from used modules...
Definition: Module.h:258
Encapsulates the information needed to find the file referenced by a #include or #include_next, (sub-)framework lookup, etc.
Definition: HeaderSearch.h:158
StringRef getString() const
Definition: ModuleMap.cpp:1355
const FileEntry * getContainingModuleMapFile(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
Definition: ModuleMap.cpp:1205
unsigned IsSystem
Whether this is a "system" module (which assumes that all headers in it are system headers)...
Definition: Module.h:225
NodeId Parent
Definition: ASTDiff.cpp:191
Module * createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name, Module *GlobalModule)
Create a new module for a C++ Modules TS module interface unit.
Definition: ModuleMap.cpp:817
const FileEntry * getFile(StringRef Filename, bool OpenFile=false, bool CacheFailure=true)
Lookup, cache, and verify the specified file (real or virtual).
static bool violatesPrivateInclude(Module *RequestingModule, const FileEntry *IncFileEnt, ModuleMap::KnownHeader Header)
Definition: ModuleMap.cpp:438
std::string CurrentModule
The name of the current module, of which the main source file is a part.
Definition: LangOptions.h:226
const DirectoryEntry * getDirectory(StringRef DirName, bool CacheFailure=true)
Lookup, cache, and verify the specified directory (real or virtual).
bool parseModuleMapFile(const FileEntry *File, bool IsSystem, const DirectoryEntry *HomeDir, FileID ID=FileID(), unsigned *Offset=nullptr, SourceLocation ExternModuleLoc=SourceLocation())
Parse the given module map file, and record any modules we encounter.
Definition: ModuleMap.cpp:2943
Module * findSubmodule(StringRef Name) const
Find the submodule with the given name.
Definition: Module.cpp:316
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:123
StringRef Filename
Definition: Format.cpp:1628
SmallVector< std::pair< std::string, SourceLocation >, 2 > ModuleId
Describes the name of a module.
Definition: Module.h:51
unsigned Offset
Definition: Format.cpp:1630
Exposes information about the current target.
Definition: TargetInfo.h:161
void diagnoseHeaderInclusion(Module *RequestingModule, bool RequestingModuleIsModuleInterface, SourceLocation FilenameLoc, StringRef Filename, const FileEntry *File)
Reports errors if a module must not include a specific file.
Definition: ModuleMap.cpp:465
Defines the clang::LangOptions interface.
SmallVector< ModuleId, 2 > UnresolvedDirectUses
The set of use declarations that have yet to be resolved.
Definition: Module.h:314
int Id
Definition: ASTDiff.cpp:190
ModuleId Id
The name of the module.
Definition: Module.h:299
const FileEntry * getFileEntryForID(FileID FID) const
Returns the FileEntry record for the provided FileID.
unsigned ConfigMacrosExhaustive
Whether the set of configuration macros is exhaustive.
Definition: Module.h:254
bool UseExportAsModuleLinkName
Autolinking uses the framework name for linking purposes when this is false and the export_as name ot...
Definition: Module.h:339
void print(raw_ostream &OS, unsigned Indent=0) const
Print the module map for this module to the given stream.
Definition: Module.cpp:404
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file. ...
Definition: Token.h:123
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
Definition: ModuleMap.cpp:1248
llvm::SmallVector< LinkLibrary, 2 > LinkLibraries
The set of libraries or frameworks to link against when an entity from this module is used...
Definition: Module.h:335
static int compareModuleHeaders(const Module::Header *A, const Module::Header *B)
Definition: ModuleMap.cpp:2346
HeaderSearchOptions & getHeaderSearchOpts() const
Retrieve the header-search options with which this header search was initialized. ...
Definition: HeaderSearch.h:268
static bool isBetterKnownHeader(const ModuleMap::KnownHeader &New, const ModuleMap::KnownHeader &Old)
Definition: ModuleMap.cpp:541
KnownHeader findModuleForHeader(const FileEntry *File, bool AllowTextual=false)
Retrieve the module that owns the given header file, if any.
Definition: ModuleMap.cpp:561
void setUmbrellaHeader(Module *Mod, const FileEntry *UmbrellaHeader, Twine NameAsWritten)
Sets the umbrella header of the given module to the given header.
Definition: ModuleMap.cpp:1085
static std::string formatModuleId(const ModuleId &Id)
Format a module-id into a string.
Definition: ModuleMap.cpp:2618
std::string NameAsWritten
Definition: Module.h:151
bool isAvailable() const
Determine whether this module is available for use within the current translation unit...
Definition: Module.h:378
Information about a header directive as found in the module map file.
Definition: Module.h:150
The result type of a method or function.
StringRef GetString() const
SmallVector< ExportDecl, 2 > Exports
The set of export declarations.
Definition: Module.h:290
const DirectoryEntry * Directory
The build directory of this module.
Definition: Module.h:95
const DirectoryEntry * getDir() const
Return the directory the file lives in.
Definition: FileManager.h:94
std::pair< Module *, bool > findOrCreateModule(StringRef Name, Module *Parent, bool IsFramework, bool IsExplicit)
Find a new module or submodule, or create it if it does not already exist.
Definition: ModuleMap.cpp:789
static void inferFrameworkLink(Module *Mod, const DirectoryEntry *FrameworkDir, FileManager &FileMgr)
For a framework module, infer the framework against which we should link.
Definition: ModuleMap.cpp:870
bool fullModuleNameIs(ArrayRef< StringRef > nameParts) const
Whether the full name of this module is equal to joining nameParts with "."s.
Definition: Module.cpp:229
SourceLocation getLocation()
Definition: ModuleMap.cpp:1457
Kind
static bool shouldAddRequirement(Module *M, StringRef Feature, bool &IsRequiresExcludedHack)
Whether to add the requirement Feature to the module M.
Definition: ModuleMap.cpp:2147
LLVM_READONLY bool isValidIdentifier(StringRef S, bool AllowDollar=false)
Return true if this is a valid ASCII identifier.
Definition: CharInfo.h:184
static StringRef sanitizeFilenameAsIdentifier(StringRef Name, SmallVectorImpl< char > &Buffer)
"Sanitize" a filename so that it can be used as an identifier.
Definition: ModuleMap.cpp:335
Encodes a location in the source.
StringRef getName() const
Definition: FileManager.h:84
bool is(tok::TokenKind Kind) const
Definition: FormatToken.h:306
std::string ExportAsModule
The module through which entities defined in this module will eventually be exposed, for use in "private" modules.
Definition: Module.h:112
bool is(TokenKind K) const
Definition: ModuleMap.cpp:1345
Cached information about one file (either on disk or in the virtual file system). ...
Definition: FileManager.h:59
SmallVector< Header, 2 > Headers[5]
The headers that are part of this module.
Definition: Module.h:167
const FileEntry * Entry
Definition: Module.h:152
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition: Token.h:265
This is a fragment of the global module within some C++ Modules TS module.
Definition: Module.h:82
Module * lookupModuleUnqualified(StringRef Name, Module *Context) const
Retrieve a module with the given name using lexical name lookup, starting at the given context...
Definition: ModuleMap.cpp:772
bool Wildcard
Whether this export declaration ends in a wildcard, indicating that all of its submodules should be e...
Definition: Module.h:304
static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role)
Convert a header role to a kind.
Definition: ModuleMap.cpp:76
__DEVICE__ void * memcpy(void *__a, const void *__b, size_t __c)
This header is normally included in the module.
Definition: ModuleMap.h:125
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Definition: ModuleMap.cpp:1165
bool parseModuleMapFile()
Parse a module map file.
Definition: ModuleMap.cpp:2899
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
StringRef getCanonicalName(const DirectoryEntry *Dir)
Retrieve the canonical name for a given directory.
A conflict between two modules.
Definition: Module.h:359
SmallVector< UnresolvedHeaderDirective, 1 > UnresolvedHeaders
Headers that are mentioned in the module map file but that we have not yet attempted to resolve to a ...
Definition: Module.h:183
Dataflow Directional Tag Classes.
bool isValid() const
Return true if this is a valid SourceLocation object.
Stored information about a header directive that was found in the module map file but has not been re...
Definition: Module.h:171
llvm::PointerUnion< const DirectoryEntry *, const FileEntry * > Umbrella
The umbrella header or directory.
Definition: Module.h:102
Module * ShadowingModule
A module with the same name that shadows this module.
Definition: Module.h:200
off_t getSize() const
Definition: FileManager.h:87
ArrayRef< KnownHeader > findAllModulesForHeader(const FileEntry *File) const
Retrieve all the modules that contain the given header file.
Definition: ModuleMap.cpp:659
FileID getMainFileID() const
Returns the FileID of the main source file.
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Module.h:287
LLVM_READONLY bool isIdentifierBody(unsigned char c, bool AllowDollar=false)
Returns true if this is a body character of a C identifier, which is [a-zA-Z0-9_].
Definition: CharInfo.h:58
void addTopHeader(const FileEntry *File)
Add a top-level header associated with this module.
Definition: Module.h:495
unsigned getLength() const
Definition: Token.h:126
SourceLocation DefinitionLoc
The location of the module definition.
Definition: Module.h:70
LLVM_READONLY bool isDigit(unsigned char c)
Return true if this character is an ASCII digit: [0-9].
Definition: CharInfo.h:93
FileID getFileID(SourceLocation SpellingLoc) const
Return the FileID for a SourceLocation.
uint64_t getInteger() const
Definition: ModuleMap.cpp:1351
void addLinkAsDependency(Module *Mod)
Make module to use export_as as the link dependency name if enough information is available or add it...
Definition: ModuleMap.cpp:69
A token in a module map file.
Definition: ModuleMap.cpp:1296
std::vector< Conflict > Conflicts
The list of conflicts.
Definition: Module.h:368
void MarkFileModuleHeader(const FileEntry *FE, ModuleMap::ModuleHeaderRole Role, bool isCompilingModuleHeader)
Mark the specified file as part of a module.
SmallVector< Module *, 2 > DirectUses
The directly used modules.
Definition: Module.h:311
Describes an exported module that has not yet been resolved (perhaps because the module it refers to ...
Definition: Module.h:294
DirectoryName getUmbrellaDir() const
Retrieve the directory for which this module serves as the umbrella.
Definition: Module.cpp:238
Cached information about one directory (either on disk or in the virtual file system).
Definition: FileManager.h:45
Defines the clang::SourceLocation class and associated facilities.
unsigned InferSubmodules
Whether we should infer submodules for this module based on the headers.
Definition: Module.h:239
StringRef getRawIdentifier() const
getRawIdentifier - For a raw identifier token (i.e., an identifier lexed in raw mode), returns a reference to the text substring in the buffer if known.
Definition: Token.h:202
Module * getModule() const
Retrieve the module the header is stored in.
Definition: ModuleMap.h:165
StringLiteralParser - This decodes string escape characters and performs wide string analysis and Tra...
unsigned kind
All of the diagnostics that can be emitted by the frontend.
Definition: DiagnosticIDs.h:60
static FixItHint CreateReplacement(CharSourceRange RemoveRange, StringRef Code)
Create a code modification hint that replaces the given source range with the given code string...
Definition: Diagnostic.h:128
bool directlyUses(const Module *Requested) const
Determine whether this module has declared its intention to directly use another module.
Definition: Module.cpp:258
void resolveLinkAsDependencies(Module *Mod)
Use PendingLinkAsModule information to mark top level link names that are going to be replaced by exp...
Definition: ModuleMap.cpp:58
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1599
Defines the clang::TargetInfo interface.
~ModuleMap()
Destroy the module map.
Definition: ModuleMap.cpp:321
bool isHeaderInUnavailableModule(const FileEntry *Header) const
Determine whether the given header is part of a module marked &#39;unavailable&#39;.
Definition: ModuleMap.cpp:667
AttributeKind
Enumerates the known attributes.
Definition: ModuleMap.cpp:1684
std::string UmbrellaAsWritten
The name of the umbrella entry, as written in the module map.
Definition: Module.h:108
Module * Other
The module that this module conflicts with.
Definition: Module.h:361
A trivial tuple used to represent a source range.
A header that is known to reside within a given module, whether it was included or excluded...
Definition: ModuleMap.h:150
This class handles loading and caching of source files into memory.
IntrusiveRefCntPtr< llvm::vfs::FileSystem > getVirtualFileSystem() const
Definition: FileManager.h:224
unsigned InferExplicitSubmodules
Whether, when inferring submodules, the inferred submodules should be explicit.
Definition: Module.h:243
This is a C++ Modules TS module interface unit.
Definition: Module.h:78
StringRef getName() const
Definition: FileManager.h:51