clang 18.0.0git
ModuleMap.h
Go to the documentation of this file.
1//===- ModuleMap.h - Describe the layout of modules -------------*- C++ -*-===//
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 interface, which describes the layout of a
10// module as it relates to headers.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_LEX_MODULEMAP_H
15#define LLVM_CLANG_LEX_MODULEMAP_H
16
19#include "clang/Basic/Module.h"
21#include "llvm/ADT/ArrayRef.h"
22#include "llvm/ADT/DenseMap.h"
23#include "llvm/ADT/PointerIntPair.h"
24#include "llvm/ADT/SmallPtrSet.h"
25#include "llvm/ADT/SmallVector.h"
26#include "llvm/ADT/StringMap.h"
27#include "llvm/ADT/StringRef.h"
28#include "llvm/ADT/StringSet.h"
29#include "llvm/ADT/TinyPtrVector.h"
30#include "llvm/ADT/Twine.h"
31#include <ctime>
32#include <memory>
33#include <optional>
34#include <string>
35#include <utility>
36
37namespace clang {
38
39class DiagnosticsEngine;
40class DirectoryEntry;
41class FileEntry;
42class FileManager;
43class HeaderSearch;
44class SourceManager;
45
46/// A mechanism to observe the actions of the module map parser as it
47/// reads module map files.
49 virtual void anchor();
50
51public:
52 virtual ~ModuleMapCallbacks() = default;
53
54 /// Called when a module map file has been read.
55 ///
56 /// \param FileStart A SourceLocation referring to the start of the file's
57 /// contents.
58 /// \param File The file itself.
59 /// \param IsSystem Whether this is a module map from a system include path.
61 bool IsSystem) {}
62
63 /// Called when a header is added during module map parsing.
64 ///
65 /// \param Filename The header file itself.
66 virtual void moduleMapAddHeader(StringRef Filename) {}
67
68 /// Called when an umbrella header is added during module map parsing.
69 ///
70 /// \param Header The umbrella header to collect.
72};
73
74class ModuleMap {
75 SourceManager &SourceMgr;
76 DiagnosticsEngine &Diags;
77 const LangOptions &LangOpts;
78 const TargetInfo *Target;
79 HeaderSearch &HeaderInfo;
80
82
83 /// The directory used for Clang-supplied, builtin include headers,
84 /// such as "stdint.h".
86
87 /// Language options used to parse the module map itself.
88 ///
89 /// These are always simple C language options.
90 LangOptions MMapLangOpts;
91
92 /// The module that the main source file is associated with (the module
93 /// named LangOpts::CurrentModule, if we've loaded it).
94 Module *SourceModule = nullptr;
95
96 /// Submodules of the current module that have not yet been attached to it.
97 /// (Ownership is transferred if/when we create an enclosing module.)
99
100 /// The top-level modules that are known.
101 llvm::StringMap<Module *> Modules;
102
103 /// Module loading cache that includes submodules, indexed by IdentifierInfo.
104 /// nullptr is stored for modules that are known to fail to load.
105 llvm::DenseMap<const IdentifierInfo *, Module *> CachedModuleLoads;
106
107 /// Shadow modules created while building this module map.
108 llvm::SmallVector<Module*, 2> ShadowModules;
109
110 /// The number of modules we have created in total.
111 unsigned NumCreatedModules = 0;
112
113 /// In case a module has a export_as entry, it might have a pending link
114 /// name to be determined if that module is imported.
115 llvm::StringMap<llvm::StringSet<>> PendingLinkAsModule;
116
117public:
118 /// Use PendingLinkAsModule information to mark top level link names that
119 /// are going to be replaced by export_as aliases.
121
122 /// Make module to use export_as as the link dependency name if enough
123 /// information is available or add it to a pending list otherwise.
124 void addLinkAsDependency(Module *Mod);
125
126 /// Flags describing the role of a module header.
128 /// This header is normally included in the module.
130
131 /// This header is included but private.
133
134 /// This header is part of the module (for layering purposes) but
135 /// should be textually included.
137
138 /// This header is explicitly excluded from the module.
140
141 // Caution: Adding an enumerator needs other changes.
142 // Adjust the number of bits for KnownHeader::Storage.
143 // Adjust the HeaderFileInfoTrait::ReadData streaming.
144 // Adjust the HeaderFileInfoTrait::EmitData streaming.
145 // Adjust ModuleMap::addHeader.
146 };
147
148 /// Convert a header kind to a role. Requires Kind to not be HK_Excluded.
150
151 /// Convert a header role to a kind.
153
154 /// Check if the header with the given role is a modular one.
155 static bool isModular(ModuleHeaderRole Role);
156
157 /// A header that is known to reside within a given module,
158 /// whether it was included or excluded.
160 llvm::PointerIntPair<Module *, 3, ModuleHeaderRole> Storage;
161
162 public:
163 KnownHeader() : Storage(nullptr, NormalHeader) {}
164 KnownHeader(Module *M, ModuleHeaderRole Role) : Storage(M, Role) {}
165
166 friend bool operator==(const KnownHeader &A, const KnownHeader &B) {
167 return A.Storage == B.Storage;
168 }
169 friend bool operator!=(const KnownHeader &A, const KnownHeader &B) {
170 return A.Storage != B.Storage;
171 }
172
173 /// Retrieve the module the header is stored in.
174 Module *getModule() const { return Storage.getPointer(); }
175
176 /// The role of this header within the module.
177 ModuleHeaderRole getRole() const { return Storage.getInt(); }
178
179 /// Whether this header is available in the module.
180 bool isAvailable() const {
181 return getRole() != ExcludedHeader && getModule()->isAvailable();
182 }
183
184 /// Whether this header is accessible from the specified module.
185 bool isAccessibleFrom(Module *M) const {
186 return !(getRole() & PrivateHeader) ||
188 }
189
190 // Whether this known header is valid (i.e., it has an
191 // associated module).
192 explicit operator bool() const {
193 return Storage.getPointer() != nullptr;
194 }
195 };
196
198
199private:
200 friend class ModuleMapParser;
201
202 using HeadersMap = llvm::DenseMap<FileEntryRef, SmallVector<KnownHeader, 1>>;
203
204 /// Mapping from each header to the module that owns the contents of
205 /// that header.
206 HeadersMap Headers;
207
208 /// Map from file sizes to modules with lazy header directives of that size.
209 mutable llvm::DenseMap<off_t, llvm::TinyPtrVector<Module*>> LazyHeadersBySize;
210
211 /// Map from mtimes to modules with lazy header directives with those mtimes.
212 mutable llvm::DenseMap<time_t, llvm::TinyPtrVector<Module*>>
213 LazyHeadersByModTime;
214
215 /// Mapping from directories with umbrella headers to the module
216 /// that is generated from the umbrella header.
217 ///
218 /// This mapping is used to map headers that haven't explicitly been named
219 /// in the module map over to the module that includes them via its umbrella
220 /// header.
221 llvm::DenseMap<const DirectoryEntry *, Module *> UmbrellaDirs;
222
223 /// A generation counter that is used to test whether modules of the
224 /// same name may shadow or are illegal redefinitions.
225 ///
226 /// Modules from earlier scopes may shadow modules from later ones.
227 /// Modules from the same scope may not have the same name.
228 unsigned CurrentModuleScopeID = 0;
229
230 llvm::DenseMap<Module *, unsigned> ModuleScopeIDs;
231
232 /// The set of attributes that can be attached to a module.
233 struct Attributes {
234 /// Whether this is a system module.
235 unsigned IsSystem : 1;
236
237 /// Whether this is an extern "C" module.
238 unsigned IsExternC : 1;
239
240 /// Whether this is an exhaustive set of configuration macros.
241 unsigned IsExhaustive : 1;
242
243 /// Whether files in this module can only include non-modular headers
244 /// and headers from used modules.
245 unsigned NoUndeclaredIncludes : 1;
246
247 Attributes()
248 : IsSystem(false), IsExternC(false), IsExhaustive(false),
249 NoUndeclaredIncludes(false) {}
250 };
251
252 /// A directory for which framework modules can be inferred.
253 struct InferredDirectory {
254 /// Whether to infer modules from this directory.
255 unsigned InferModules : 1;
256
257 /// The attributes to use for inferred modules.
258 Attributes Attrs;
259
260 /// If \c InferModules is non-zero, the module map file that allowed
261 /// inferred modules. Otherwise, nullopt.
262 OptionalFileEntryRef ModuleMapFile;
263
264 /// The names of modules that cannot be inferred within this
265 /// directory.
266 SmallVector<std::string, 2> ExcludedModules;
267
268 InferredDirectory() : InferModules(false) {}
269 };
270
271 /// A mapping from directories to information about inferring
272 /// framework modules from within those directories.
273 llvm::DenseMap<const DirectoryEntry *, InferredDirectory> InferredDirectories;
274
275 /// A mapping from an inferred module to the module map that allowed the
276 /// inference.
277 // FIXME: Consider making the values non-optional.
278 llvm::DenseMap<const Module *, OptionalFileEntryRef> InferredModuleAllowedBy;
279
280 llvm::DenseMap<const Module *, AdditionalModMapsSet> AdditionalModMaps;
281
282 /// Describes whether we haved parsed a particular file as a module
283 /// map.
284 llvm::DenseMap<const FileEntry *, bool> ParsedModuleMap;
285
286 /// Resolve the given export declaration into an actual export
287 /// declaration.
288 ///
289 /// \param Mod The module in which we're resolving the export declaration.
290 ///
291 /// \param Unresolved The export declaration to resolve.
292 ///
293 /// \param Complain Whether this routine should complain about unresolvable
294 /// exports.
295 ///
296 /// \returns The resolved export declaration, which will have a NULL pointer
297 /// if the export could not be resolved.
299 resolveExport(Module *Mod, const Module::UnresolvedExportDecl &Unresolved,
300 bool Complain) const;
301
302 /// Resolve the given module id to an actual module.
303 ///
304 /// \param Id The module-id to resolve.
305 ///
306 /// \param Mod The module in which we're resolving the module-id.
307 ///
308 /// \param Complain Whether this routine should complain about unresolvable
309 /// module-ids.
310 ///
311 /// \returns The resolved module, or null if the module-id could not be
312 /// resolved.
313 Module *resolveModuleId(const ModuleId &Id, Module *Mod, bool Complain) const;
314
315 /// Add an unresolved header to a module.
316 ///
317 /// \param Mod The module in which we're adding the unresolved header
318 /// directive.
319 /// \param Header The unresolved header directive.
320 /// \param NeedsFramework If Mod is not a framework but a missing header would
321 /// be found in case Mod was, set it to true. False otherwise.
322 void addUnresolvedHeader(Module *Mod,
323 Module::UnresolvedHeaderDirective Header,
324 bool &NeedsFramework);
325
326 /// Look up the given header directive to find an actual header file.
327 ///
328 /// \param M The module in which we're resolving the header directive.
329 /// \param Header The header directive to resolve.
330 /// \param RelativePathName Filled in with the relative path name from the
331 /// module to the resolved header.
332 /// \param NeedsFramework If M is not a framework but a missing header would
333 /// be found in case M was, set it to true. False otherwise.
334 /// \return The resolved file, if any.
336 findHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
337 SmallVectorImpl<char> &RelativePathName, bool &NeedsFramework);
338
339 /// Resolve the given header directive.
340 ///
341 /// \param M The module in which we're resolving the header directive.
342 /// \param Header The header directive to resolve.
343 /// \param NeedsFramework If M is not a framework but a missing header would
344 /// be found in case M was, set it to true. False otherwise.
345 void resolveHeader(Module *M, const Module::UnresolvedHeaderDirective &Header,
346 bool &NeedsFramework);
347
348 /// Attempt to resolve the specified header directive as naming a builtin
349 /// header.
350 /// \return \c true if a corresponding builtin header was found.
351 bool resolveAsBuiltinHeader(Module *M,
352 const Module::UnresolvedHeaderDirective &Header);
353
354 /// Looks up the modules that \p File corresponds to.
355 ///
356 /// If \p File represents a builtin header within Clang's builtin include
357 /// directory, this also loads all of the module maps to see if it will get
358 /// associated with a specific module (e.g. in /usr/include).
359 HeadersMap::iterator findKnownHeader(FileEntryRef File);
360
361 /// Searches for a module whose umbrella directory contains \p File.
362 ///
363 /// \param File The header to search for.
364 ///
365 /// \param IntermediateDirs On success, contains the set of directories
366 /// searched before finding \p File.
367 KnownHeader findHeaderInUmbrellaDirs(
368 FileEntryRef File, SmallVectorImpl<DirectoryEntryRef> &IntermediateDirs);
369
370 /// Given that \p File is not in the Headers map, look it up within
371 /// umbrella directories and find or create a module for it.
372 KnownHeader findOrCreateModuleForHeaderInUmbrellaDir(FileEntryRef File);
373
374 /// A convenience method to determine if \p File is (possibly nested)
375 /// in an umbrella directory.
376 bool isHeaderInUmbrellaDirs(FileEntryRef File) {
377 SmallVector<DirectoryEntryRef, 2> IntermediateDirs;
378 return static_cast<bool>(findHeaderInUmbrellaDirs(File, IntermediateDirs));
379 }
380
381 Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, Attributes Attrs,
382 Module *Parent);
383
384public:
385 /// Construct a new module map.
386 ///
387 /// \param SourceMgr The source manager used to find module files and headers.
388 /// This source manager should be shared with the header-search mechanism,
389 /// since they will refer to the same headers.
390 ///
391 /// \param Diags A diagnostic engine used for diagnostics.
392 ///
393 /// \param LangOpts Language options for this translation unit.
394 ///
395 /// \param Target The target for this translation unit.
396 ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags,
397 const LangOptions &LangOpts, const TargetInfo *Target,
398 HeaderSearch &HeaderInfo);
399
400 /// Destroy the module map.
401 ~ModuleMap();
402
403 /// Set the target information.
404 void setTarget(const TargetInfo &Target);
405
406 /// Set the directory that contains Clang-supplied include
407 /// files, such as our stdarg.h or tgmath.h.
409 BuiltinIncludeDir = Dir;
410 }
411
412 /// Get the directory that contains Clang-supplied include files.
414 return BuiltinIncludeDir;
415 }
416
417 /// Is this a compiler builtin header?
419
420 /// Add a module map callback.
421 void addModuleMapCallbacks(std::unique_ptr<ModuleMapCallbacks> Callback) {
422 Callbacks.push_back(std::move(Callback));
423 }
424
425 /// Retrieve the module that owns the given header file, if any. Note that
426 /// this does not implicitly load module maps, except for builtin headers,
427 /// and does not consult the external source. (Those checks are the
428 /// responsibility of \ref HeaderSearch.)
429 ///
430 /// \param File The header file that is likely to be included.
431 ///
432 /// \param AllowTextual If \c true and \p File is a textual header, return
433 /// its owning module. Otherwise, no KnownHeader will be returned if the
434 /// file is only known as a textual header.
435 ///
436 /// \returns The module KnownHeader, which provides the module that owns the
437 /// given header file. The KnownHeader is default constructed to indicate
438 /// that no module owns this header file.
439 KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual = false,
440 bool AllowExcluded = false);
441
442 /// Retrieve all the modules that contain the given header file. Note that
443 /// this does not implicitly load module maps, except for builtin headers,
444 /// and does not consult the external source. (Those checks are the
445 /// responsibility of \ref HeaderSearch.)
446 ///
447 /// Typically, \ref findModuleForHeader should be used instead, as it picks
448 /// the preferred module for the header.
450
451 /// Like \ref findAllModulesForHeader, but do not attempt to infer module
452 /// ownership from umbrella headers if we've not already done so.
454
455 /// Resolve all lazy header directives for the specified file.
456 ///
457 /// This ensures that the HeaderFileInfo on HeaderSearch is up to date. This
458 /// is effectively internal, but is exposed so HeaderSearch can call it.
459 void resolveHeaderDirectives(const FileEntry *File) const;
460
461 /// Resolve lazy header directives for the specified module. If File is
462 /// provided, only headers with same size and modtime are resolved. If File
463 /// is not set, all headers are resolved.
465 std::optional<const FileEntry *> File) const;
466
467 /// Reports errors if a module must not include a specific file.
468 ///
469 /// \param RequestingModule The module including a file.
470 ///
471 /// \param RequestingModuleIsModuleInterface \c true if the inclusion is in
472 /// the interface of RequestingModule, \c false if it's in the
473 /// implementation of RequestingModule. Value is ignored and
474 /// meaningless if RequestingModule is nullptr.
475 ///
476 /// \param FilenameLoc The location of the inclusion's filename.
477 ///
478 /// \param Filename The included filename as written.
479 ///
480 /// \param File The included file.
481 void diagnoseHeaderInclusion(Module *RequestingModule,
482 bool RequestingModuleIsModuleInterface,
483 SourceLocation FilenameLoc, StringRef Filename,
485
486 /// Determine whether the given header is part of a module
487 /// marked 'unavailable'.
488 bool isHeaderInUnavailableModule(FileEntryRef Header) const;
489
490 /// Determine whether the given header is unavailable as part
491 /// of the specified module.
493 const Module *RequestingModule) const;
494
495 /// Retrieve a module with the given name.
496 ///
497 /// \param Name The name of the module to look up.
498 ///
499 /// \returns The named module, if known; otherwise, returns null.
500 Module *findModule(StringRef Name) const;
501
502 /// Retrieve a module with the given name using lexical name lookup,
503 /// starting at the given context.
504 ///
505 /// \param Name The name of the module to look up.
506 ///
507 /// \param Context The module context, from which we will perform lexical
508 /// name lookup.
509 ///
510 /// \returns The named module, if known; otherwise, returns null.
511 Module *lookupModuleUnqualified(StringRef Name, Module *Context) const;
512
513 /// Retrieve a module with the given name within the given context,
514 /// using direct (qualified) name lookup.
515 ///
516 /// \param Name The name of the module to look up.
517 ///
518 /// \param Context The module for which we will look for a submodule. If
519 /// null, we will look for a top-level module.
520 ///
521 /// \returns The named submodule, if known; otherwose, returns null.
522 Module *lookupModuleQualified(StringRef Name, Module *Context) const;
523
524 /// Find a new module or submodule, or create it if it does not already
525 /// exist.
526 ///
527 /// \param Name The name of the module to find or create.
528 ///
529 /// \param Parent The module that will act as the parent of this submodule,
530 /// or nullptr to indicate that this is a top-level module.
531 ///
532 /// \param IsFramework Whether this is a framework module.
533 ///
534 /// \param IsExplicit Whether this is an explicit submodule.
535 ///
536 /// \returns The found or newly-created module, along with a boolean value
537 /// that will be true if the module is newly-created.
538 std::pair<Module *, bool> findOrCreateModule(StringRef Name, Module *Parent,
539 bool IsFramework,
540 bool IsExplicit);
541
542 /// Create a global module fragment for a C++ module unit.
543 ///
544 /// We model the global module fragment as a submodule of the module
545 /// interface unit. Unfortunately, we can't create the module interface
546 /// unit's Module until later, because we don't know what it will be called
547 /// usually. See C++20 [module.unit]/7.2 for the case we could know its
548 /// parent.
550 Module *Parent = nullptr);
552 SourceLocation Loc, bool IsExported, Module *Parent = nullptr);
553
554 /// Create a global module fragment for a C++ module interface unit.
556 SourceLocation Loc);
557
558 /// Create a new C++ module with the specified kind, and reparent any pending
559 /// global module fragment(s) to it.
561 Module::ModuleKind Kind);
562
563 /// Create a new module for a C++ module interface unit.
564 /// The module must not already exist, and will be configured for the current
565 /// compilation.
566 ///
567 /// Note that this also sets the current module to the newly-created module.
568 ///
569 /// \returns The newly-created module.
571
572 /// Create a new module for a C++ module implementation unit.
573 /// The interface module for this implementation (implicitly imported) must
574 /// exist and be loaded and present in the modules map.
575 ///
576 /// \returns The newly-created module.
578
579 /// Create a C++20 header unit.
580 Module *createHeaderUnit(SourceLocation Loc, StringRef Name,
582
583 /// Infer the contents of a framework module map from the given
584 /// framework directory.
585 Module *inferFrameworkModule(DirectoryEntryRef FrameworkDir, bool IsSystem,
586 Module *Parent);
587
588 /// Create a new top-level module that is shadowed by
589 /// \p ShadowingModule.
590 Module *createShadowedModule(StringRef Name, bool IsFramework,
591 Module *ShadowingModule);
592
593 /// Creates a new declaration scope for module names, allowing
594 /// previously defined modules to shadow definitions from the new scope.
595 ///
596 /// \note Module names from earlier scopes will shadow names from the new
597 /// scope, which is the opposite of how shadowing works for variables.
598 void finishModuleDeclarationScope() { CurrentModuleScopeID += 1; }
599
600 bool mayShadowNewModule(Module *ExistingModule) {
601 assert(!ExistingModule->Parent && "expected top-level module");
602 assert(ModuleScopeIDs.count(ExistingModule) && "unknown module");
603 return ModuleScopeIDs[ExistingModule] < CurrentModuleScopeID;
604 }
605
606 /// Check whether a framework module can be inferred in the given directory.
608 auto It = InferredDirectories.find(Dir);
609 return It != InferredDirectories.end() && It->getSecond().InferModules;
610 }
611
612 /// Retrieve the module map file containing the definition of the given
613 /// module.
614 ///
615 /// \param Module The module whose module map file will be returned, if known.
616 ///
617 /// \returns The file entry for the module map file containing the given
618 /// module, or nullptr if the module definition was inferred.
620
621 /// Get the module map file that (along with the module name) uniquely
622 /// identifies this module.
623 ///
624 /// The particular module that \c Name refers to may depend on how the module
625 /// was found in header search. However, the combination of \c Name and
626 /// this module map will be globally unique for top-level modules. In the case
627 /// of inferred modules, returns the module map that allowed the inference
628 /// (e.g. contained 'module *'). Otherwise, returns
629 /// getContainingModuleMapFile().
631
633
634 /// Canonicalize \p Path in a manner suitable for a module map file. In
635 /// particular, this canonicalizes the parent directory separately from the
636 /// filename so that it does not affect header resolution relative to the
637 /// modulemap.
638 ///
639 /// \returns an error code if any filesystem operations failed. In this case
640 /// \p Path is not modified.
642
643 /// Get any module map files other than getModuleMapFileForUniquing(M)
644 /// that define submodules of a top-level module \p M. This is cheaper than
645 /// getting the module map file for each submodule individually, since the
646 /// expected number of results is very small.
648 auto I = AdditionalModMaps.find(M);
649 if (I == AdditionalModMaps.end())
650 return nullptr;
651 return &I->second;
652 }
653
655
656 /// Resolve all of the unresolved exports in the given module.
657 ///
658 /// \param Mod The module whose exports should be resolved.
659 ///
660 /// \param Complain Whether to emit diagnostics for failures.
661 ///
662 /// \returns true if any errors were encountered while resolving exports,
663 /// false otherwise.
664 bool resolveExports(Module *Mod, bool Complain);
665
666 /// Resolve all of the unresolved uses in the given module.
667 ///
668 /// \param Mod The module whose uses should be resolved.
669 ///
670 /// \param Complain Whether to emit diagnostics for failures.
671 ///
672 /// \returns true if any errors were encountered while resolving uses,
673 /// false otherwise.
674 bool resolveUses(Module *Mod, bool Complain);
675
676 /// Resolve all of the unresolved conflicts in the given module.
677 ///
678 /// \param Mod The module whose conflicts should be resolved.
679 ///
680 /// \param Complain Whether to emit diagnostics for failures.
681 ///
682 /// \returns true if any errors were encountered while resolving conflicts,
683 /// false otherwise.
684 bool resolveConflicts(Module *Mod, bool Complain);
685
686 /// Sets the umbrella header of the given module to the given header.
687 void
689 const Twine &NameAsWritten,
690 const Twine &PathRelativeToRootModuleDirectory);
691
692 /// Sets the umbrella directory of the given module to the given directory.
693 void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir,
694 const Twine &NameAsWritten,
695 const Twine &PathRelativeToRootModuleDirectory);
696
697 /// Adds this header to the given module.
698 /// \param Role The role of the header wrt the module.
699 void addHeader(Module *Mod, Module::Header Header,
700 ModuleHeaderRole Role, bool Imported = false);
701
702 /// Parse the given module map file, and record any modules we
703 /// encounter.
704 ///
705 /// \param File The file to be parsed.
706 ///
707 /// \param IsSystem Whether this module map file is in a system header
708 /// directory, and therefore should be considered a system module.
709 ///
710 /// \param HomeDir The directory in which relative paths within this module
711 /// map file will be resolved.
712 ///
713 /// \param ID The FileID of the file to process, if we've already entered it.
714 ///
715 /// \param Offset [inout] On input the offset at which to start parsing. On
716 /// output, the offset at which the module map terminated.
717 ///
718 /// \param ExternModuleLoc The location of the "extern module" declaration
719 /// that caused us to load this module map file, if any.
720 ///
721 /// \returns true if an error occurred, false otherwise.
722 bool parseModuleMapFile(FileEntryRef File, bool IsSystem,
723 DirectoryEntryRef HomeDir, FileID ID = FileID(),
724 unsigned *Offset = nullptr,
725 SourceLocation ExternModuleLoc = SourceLocation());
726
727 /// Dump the contents of the module map, for debugging purposes.
728 void dump();
729
730 using module_iterator = llvm::StringMap<Module *>::const_iterator;
731
732 module_iterator module_begin() const { return Modules.begin(); }
733 module_iterator module_end() const { return Modules.end(); }
734 llvm::iterator_range<module_iterator> modules() const {
735 return {module_begin(), module_end()};
736 }
737
738 /// Cache a module load. M might be nullptr.
740 CachedModuleLoads[&II] = M;
741 }
742
743 /// Return a cached module load.
744 std::optional<Module *> getCachedModuleLoad(const IdentifierInfo &II) {
745 auto I = CachedModuleLoads.find(&II);
746 if (I == CachedModuleLoads.end())
747 return std::nullopt;
748 return I->second;
749 }
750};
751
752} // namespace clang
753
754#endif // LLVM_CLANG_LEX_MODULEMAP_H
NodeId Parent
Definition: ASTDiff.cpp:191
int Id
Definition: ASTDiff.cpp:190
static char ID
Definition: Arena.cpp:163
StringRef Filename
Definition: Format.cpp:2936
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Defines the clang::LangOptions interface.
Defines the clang::Module class, which describes a module in the source code.
Defines the clang::SourceLocation class and associated facilities.
Concrete class used by the front-end to report problems and issues.
Definition: Diagnostic.h:192
A reference to a DirectoryEntry that includes the name of the directory as it was accessed by the Fil...
Cached information about one directory (either on disk or in the virtual file system).
A reference to a FileEntry that includes the name of the file as it was accessed by the FileManager's...
Definition: FileEntry.h:57
Cached information about one file (either on disk or in the virtual file system).
Definition: FileEntry.h:397
An opaque identifier used by SourceManager which refers to a source file (MemoryBuffer) along with it...
Encapsulates the information needed to find the file referenced by a #include or #include_next,...
Definition: HeaderSearch.h:223
One of these records is kept for each identifier that is lexed.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:83
A mechanism to observe the actions of the module map parser as it reads module map files.
Definition: ModuleMap.h:48
virtual void moduleMapFileRead(SourceLocation FileStart, FileEntryRef File, bool IsSystem)
Called when a module map file has been read.
Definition: ModuleMap.h:60
virtual ~ModuleMapCallbacks()=default
virtual void moduleMapAddHeader(StringRef Filename)
Called when a header is added during module map parsing.
Definition: ModuleMap.h:66
virtual void moduleMapAddUmbrellaHeader(FileEntryRef Header)
Called when an umbrella header is added during module map parsing.
Definition: ModuleMap.h:71
A header that is known to reside within a given module, whether it was included or excluded.
Definition: ModuleMap.h:159
KnownHeader(Module *M, ModuleHeaderRole Role)
Definition: ModuleMap.h:164
bool isAccessibleFrom(Module *M) const
Whether this header is accessible from the specified module.
Definition: ModuleMap.h:185
ModuleHeaderRole getRole() const
The role of this header within the module.
Definition: ModuleMap.h:177
friend bool operator!=(const KnownHeader &A, const KnownHeader &B)
Definition: ModuleMap.h:169
friend bool operator==(const KnownHeader &A, const KnownHeader &B)
Definition: ModuleMap.h:166
Module * getModule() const
Retrieve the module the header is stored in.
Definition: ModuleMap.h:174
bool isAvailable() const
Whether this header is available in the module.
Definition: ModuleMap.h:180
Module * createShadowedModule(StringRef Name, bool IsFramework, Module *ShadowingModule)
Create a new top-level module that is shadowed by ShadowingModule.
Definition: ModuleMap.cpp:1165
bool resolveExports(Module *Mod, bool Complain)
Resolve all of the unresolved exports in the given module.
Definition: ModuleMap.cpp:1387
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
void dump()
Dump the contents of the module map, for debugging purposes.
Definition: ModuleMap.cpp:1365
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:845
llvm::StringMap< Module * >::const_iterator module_iterator
Definition: ModuleMap.h:730
void setUmbrellaDirAsWritten(Module *Mod, DirectoryEntryRef UmbrellaDir, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella directory of the given module to the given directory.
Definition: ModuleMap.cpp:1195
void diagnoseHeaderInclusion(Module *RequestingModule, bool RequestingModuleIsModuleInterface, SourceLocation FilenameLoc, StringRef Filename, FileEntryRef File)
Reports errors if a module must not include a specific file.
Definition: ModuleMap.cpp:489
void addAdditionalModuleMapFile(const Module *M, FileEntryRef ModuleMap)
Definition: ModuleMap.cpp:1360
OptionalFileEntryRef getContainingModuleMapFile(const Module *Module) const
Retrieve the module map file containing the definition of the given module.
Definition: ModuleMap.cpp:1304
static Module::HeaderKind headerRoleToKind(ModuleHeaderRole Role)
Convert a header role to a kind.
Definition: ModuleMap.cpp:76
Module * findModule(StringRef Name) const
Retrieve a module with the given name.
Definition: ModuleMap.cpp:820
void finishModuleDeclarationScope()
Creates a new declaration scope for module names, allowing previously defined modules to shadow defin...
Definition: ModuleMap.h:598
bool canInferFrameworkModule(const DirectoryEntry *Dir) const
Check whether a framework module can be inferred in the given directory.
Definition: ModuleMap.h:607
bool mayShadowNewModule(Module *ExistingModule)
Definition: ModuleMap.h:600
KnownHeader findModuleForHeader(FileEntryRef File, bool AllowTextual=false, bool AllowExcluded=false)
Retrieve the module that owns the given header file, if any.
Definition: ModuleMap.cpp:599
Module * createHeaderUnit(SourceLocation Loc, StringRef Name, Module::Header H)
Create a C++20 header unit.
Definition: ModuleMap.cpp:960
void addModuleMapCallbacks(std::unique_ptr< ModuleMapCallbacks > Callback)
Add a module map callback.
Definition: ModuleMap.h:421
void setBuiltinIncludeDir(DirectoryEntryRef Dir)
Set the directory that contains Clang-supplied include files, such as our stdarg.h or tgmath....
Definition: ModuleMap.h:408
static bool isModular(ModuleHeaderRole Role)
Check if the header with the given role is a modular one.
Definition: ModuleMap.cpp:109
void setInferredModuleAllowedBy(Module *M, OptionalFileEntryRef ModMap)
Definition: ModuleMap.cpp:1321
bool resolveConflicts(Module *Mod, bool Complain)
Resolve all of the unresolved conflicts in the given module.
Definition: ModuleMap.cpp:1413
bool isHeaderUnavailableInModule(FileEntryRef Header, const Module *RequestingModule) const
Determine whether the given header is unavailable as part of the specified module.
Definition: ModuleMap.cpp:726
void resolveHeaderDirectives(const FileEntry *File) const
Resolve all lazy header directives for the specified file.
Definition: ModuleMap.cpp:1241
const DirectoryEntry * getBuiltinDir() const
Get the directory that contains Clang-supplied include files.
Definition: ModuleMap.h:413
module_iterator module_begin() const
Definition: ModuleMap.h:732
ArrayRef< KnownHeader > findResolvedModulesForHeader(FileEntryRef File) const
Like findAllModulesForHeader, but do not attempt to infer module ownership from umbrella headers if w...
Definition: ModuleMap.cpp:713
OptionalFileEntryRef getModuleMapFileForUniquing(const Module *M) const
Get the module map file that (along with the module name) uniquely identifies this module.
Definition: ModuleMap.cpp:1313
Module * createModuleForImplementationUnit(SourceLocation Loc, StringRef Name)
Create a new module for a C++ module implementation unit.
Definition: ModuleMap.cpp:936
ModuleMap(SourceManager &SourceMgr, DiagnosticsEngine &Diags, const LangOptions &LangOpts, const TargetInfo *Target, HeaderSearch &HeaderInfo)
Construct a new module map.
Definition: ModuleMap.cpp:357
std::optional< Module * > getCachedModuleLoad(const IdentifierInfo &II)
Return a cached module load.
Definition: ModuleMap.h:744
std::error_code canonicalizeModuleMapPath(SmallVectorImpl< char > &Path)
Canonicalize Path in a manner suitable for a module map file.
Definition: ModuleMap.cpp:1328
void setUmbrellaHeaderAsWritten(Module *Mod, FileEntryRef UmbrellaHeader, const Twine &NameAsWritten, const Twine &PathRelativeToRootModuleDirectory)
Sets the umbrella header of the given module to the given header.
Definition: ModuleMap.cpp:1180
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:828
bool isBuiltinHeader(FileEntryRef File)
Is this a compiler builtin header?
Definition: ModuleMap.cpp:415
module_iterator module_end() const
Definition: ModuleMap.h:733
AdditionalModMapsSet * getAdditionalModuleMapFiles(const Module *M)
Get any module map files other than getModuleMapFileForUniquing(M) that define submodules of a top-le...
Definition: ModuleMap.h:647
bool isHeaderInUnavailableModule(FileEntryRef Header) const
Determine whether the given header is part of a module marked 'unavailable'.
Definition: ModuleMap.cpp:722
bool parseModuleMapFile(FileEntryRef File, bool IsSystem, DirectoryEntryRef 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:3102
Module * createImplicitGlobalModuleFragmentForModuleUnit(SourceLocation Loc, bool IsExported, Module *Parent=nullptr)
Definition: ModuleMap.cpp:877
~ModuleMap()
Destroy the module map.
Definition: ModuleMap.cpp:365
Module * createGlobalModuleFragmentForModuleUnit(SourceLocation Loc, Module *Parent=nullptr)
Create a global module fragment for a C++ module unit.
Definition: ModuleMap.cpp:865
void setTarget(const TargetInfo &Target)
Set the target information.
Definition: ModuleMap.cpp:372
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:838
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
void cacheModuleLoad(const IdentifierInfo &II, Module *M)
Cache a module load. M might be nullptr.
Definition: ModuleMap.h:739
ModuleHeaderRole
Flags describing the role of a module header.
Definition: ModuleMap.h:127
@ PrivateHeader
This header is included but private.
Definition: ModuleMap.h:132
@ ExcludedHeader
This header is explicitly excluded from the module.
Definition: ModuleMap.h:139
@ NormalHeader
This header is normally included in the module.
Definition: ModuleMap.h:129
@ TextualHeader
This header is part of the module (for layering purposes) but should be textually included.
Definition: ModuleMap.h:136
Module * createModuleForInterfaceUnit(SourceLocation Loc, StringRef Name)
Create a new module for a C++ module interface unit.
Definition: ModuleMap.cpp:918
void addHeader(Module *Mod, Module::Header Header, ModuleHeaderRole Role, bool Imported=false)
Adds this header to the given module.
Definition: ModuleMap.cpp:1276
Module * createPrivateModuleFragmentForInterfaceUnit(Module *Parent, SourceLocation Loc)
Create a global module fragment for a C++ module interface unit.
Definition: ModuleMap.cpp:893
ArrayRef< KnownHeader > findAllModulesForHeader(FileEntryRef File)
Retrieve all the modules that contain the given header file.
Definition: ModuleMap.cpp:701
Module * createModuleUnitWithKind(SourceLocation Loc, StringRef Name, Module::ModuleKind Kind)
Create a new C++ module with the specified kind, and reparent any pending global module fragment(s) t...
Definition: ModuleMap.cpp:902
static ModuleHeaderRole headerKindToRole(Module::HeaderKind Kind)
Convert a header kind to a role. Requires Kind to not be HK_Excluded.
Definition: ModuleMap.cpp:93
llvm::iterator_range< module_iterator > modules() const
Definition: ModuleMap.h:734
bool resolveUses(Module *Mod, bool Complain)
Resolve all of the unresolved uses in the given module.
Definition: ModuleMap.cpp:1400
Describes a module or submodule.
Definition: Module.h:104
Module * Parent
The parent of this module.
Definition: Module.h:153
bool isAvailable() const
Determine whether this module is available for use within the current translation unit.
Definition: Module.h:509
llvm::PointerIntPair< Module *, 1, bool > ExportDecl
Describes an exported module.
Definition: Module.h:392
Module * getTopLevelModule()
Retrieve the top-level module for this (sub)module, which may be this module.
Definition: Module.h:641
Wrapper around OptionalDirectoryEntryRef that degrades to 'const DirectoryEntry*',...
Encodes a location in the source.
This class handles loading and caching of source files into memory.
Exposes information about the current target.
Definition: TargetInfo.h:207
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition: FileEntry.h:202
SmallVector< std::pair< std::string, SourceLocation >, 2 > ModuleId
Describes the name of a module.
Definition: Module.h:53
#define false
Definition: stdbool.h:22
#define bool
Definition: stdbool.h:20
Information about a header directive as found in the module map file.
Definition: Module.h:247