1 //===--- ASTUnit.h - ASTUnit utility ----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit utility class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H
15 #define LLVM_CLANG_FRONTEND_ASTUNIT_H
17 #include "clang-c/Index.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/FileSystemOptions.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "clang/Lex/HeaderSearchOptions.h"
25 #include "clang/Lex/ModuleLoader.h"
26 #include "clang/Lex/PreprocessingRecord.h"
27 #include "clang/Sema/CodeCompleteConsumer.h"
28 #include "clang/Serialization/ASTBitCodes.h"
29 #include "llvm/ADT/IntrusiveRefCntPtr.h"
30 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/ADT/StringMap.h"
32 #include "llvm/Support/MD5.h"
33 #include "llvm/Support/Path.h"
38 #include <sys/types.h>
50 class CodeCompleteConsumer;
51 class CompilerInvocation;
52 class CompilerInstance;
54 class DiagnosticsEngine;
59 class PCHContainerOperations;
60 class PCHContainerReader;
63 class ASTFrontendAction;
64 class ASTDeserializationListener;
66 /// \brief Utility class for loading a ASTContext from an AST file.
68 class ASTUnit : public ModuleLoader {
70 struct StandaloneFixIt {
71 std::pair<unsigned, unsigned> RemoveRange;
72 std::pair<unsigned, unsigned> InsertFromRange;
73 std::string CodeToInsert;
74 bool BeforePreviousInsertions;
77 struct StandaloneDiagnostic {
79 DiagnosticsEngine::Level Level;
83 std::vector<std::pair<unsigned, unsigned> > Ranges;
84 std::vector<StandaloneFixIt> FixIts;
88 std::shared_ptr<LangOptions> LangOpts;
89 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
90 IntrusiveRefCntPtr<FileManager> FileMgr;
91 IntrusiveRefCntPtr<SourceManager> SourceMgr;
92 std::unique_ptr<HeaderSearch> HeaderInfo;
93 IntrusiveRefCntPtr<TargetInfo> Target;
94 IntrusiveRefCntPtr<Preprocessor> PP;
95 IntrusiveRefCntPtr<ASTContext> Ctx;
96 std::shared_ptr<TargetOptions> TargetOpts;
97 IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
98 IntrusiveRefCntPtr<ASTReader> Reader;
99 bool HadModuleLoaderFatalFailure;
101 struct ASTWriterData;
102 std::unique_ptr<ASTWriterData> WriterData;
104 FileSystemOptions FileSystemOpts;
106 /// \brief The AST consumer that received information about the translation
107 /// unit as it was parsed or loaded.
108 std::unique_ptr<ASTConsumer> Consumer;
110 /// \brief The semantic analysis object used to type-check the translation
112 std::unique_ptr<Sema> TheSema;
114 /// Optional owned invocation, just used to make the invocation used in
115 /// LoadFromCommandLine available.
116 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
118 // OnlyLocalDecls - when true, walking this AST should only visit declarations
119 // that come from the AST itself, not from included precompiled headers.
120 // FIXME: This is temporary; eventually, CIndex will always do this.
123 /// \brief Whether to capture any diagnostics produced.
124 bool CaptureDiagnostics;
126 /// \brief Track whether the main file was loaded from an AST or not.
129 /// \brief What kind of translation unit this AST represents.
130 TranslationUnitKind TUKind;
132 /// \brief Whether we should time each operation.
135 /// \brief Whether the ASTUnit should delete the remapped buffers.
136 bool OwnsRemappedFileBuffers;
138 /// Track the top-level decls which appeared in an ASTUnit which was loaded
139 /// from a source file.
141 // FIXME: This is just an optimization hack to avoid deserializing large parts
142 // of a PCH file when using the Index library on an ASTUnit loaded from
143 // source. In the long term we should make the Index library use efficient and
144 // more scalable search mechanisms.
145 std::vector<Decl*> TopLevelDecls;
147 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
148 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
149 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
151 /// \brief Map from FileID to the file-level declarations that it contains.
152 /// The files and decls are only local (and non-preamble) ones.
153 FileDeclsTy FileDecls;
155 /// The name of the original source file used to generate this ASTUnit.
156 std::string OriginalSourceFile;
158 /// \brief The set of diagnostics produced when creating the preamble.
159 SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
161 /// \brief The set of diagnostics produced when creating this
162 /// translation unit.
163 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
165 /// \brief The set of diagnostics produced when failing to parse, e.g. due
166 /// to failure to load the PCH.
167 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
169 /// \brief The number of stored diagnostics that come from the driver
172 /// Diagnostics that come from the driver are retained from one parse to
174 unsigned NumStoredDiagnosticsFromDriver;
176 /// \brief Counter that determines when we want to try building a
177 /// precompiled preamble.
179 /// If zero, we will never build a precompiled preamble. Otherwise,
180 /// it's treated as a counter that decrements each time we reparse
181 /// without the benefit of a precompiled preamble. When it hits 1,
182 /// we'll attempt to rebuild the precompiled header. This way, if
183 /// building the precompiled preamble fails, we won't try again for
184 /// some number of calls.
185 unsigned PreambleRebuildCounter;
189 const FileEntry *File;
190 std::vector<char> Buffer;
191 mutable unsigned NumLines;
194 PreambleData() : File(nullptr), NumLines(0) { }
196 void assign(const FileEntry *F, const char *begin, const char *end) {
198 Buffer.assign(begin, end);
202 void clear() { Buffer.clear(); File = nullptr; NumLines = 0; }
204 size_t size() const { return Buffer.size(); }
205 bool empty() const { return Buffer.empty(); }
207 const char *getBufferStart() const { return &Buffer[0]; }
209 unsigned getNumLines() const {
216 SourceRange getSourceRange(const SourceManager &SM) const {
217 SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
218 return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
222 void countLines() const;
225 const PreambleData &getPreambleData() const {
229 /// Data used to determine if a file used in the preamble has been changed.
230 struct PreambleFileHash {
231 /// All files have size set.
234 /// Modification time is set for files that are on disk. For memory
235 /// buffers it is zero.
238 /// Memory buffers have MD5 instead of modification time. We don't
239 /// compute MD5 for on-disk files because we hope that modification time is
240 /// enough to tell if the file was changed.
241 llvm::MD5::MD5Result MD5;
243 static PreambleFileHash createForFile(off_t Size, time_t ModTime);
244 static PreambleFileHash
245 createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
247 friend bool operator==(const PreambleFileHash &LHS,
248 const PreambleFileHash &RHS);
250 friend bool operator!=(const PreambleFileHash &LHS,
251 const PreambleFileHash &RHS) {
252 return !(LHS == RHS);
257 /// \brief The contents of the preamble that has been precompiled to
259 PreambleData Preamble;
261 /// \brief Whether the preamble ends at the start of a new line.
263 /// Used to inform the lexer as to whether it's starting at the beginning of
264 /// a line after skipping the preamble.
265 bool PreambleEndsAtStartOfLine;
267 /// \brief Keeps track of the files that were used when computing the
268 /// preamble, with both their buffer size and their modification time.
270 /// If any of the files have changed from one compile to the next,
271 /// the preamble must be thrown away.
272 llvm::StringMap<PreambleFileHash> FilesInPreamble;
274 /// \brief When non-NULL, this is the buffer used to store the contents of
275 /// the main file when it has been padded for use with the precompiled
277 std::unique_ptr<llvm::MemoryBuffer> SavedMainFileBuffer;
279 /// \brief When non-NULL, this is the buffer used to store the
280 /// contents of the preamble when it has been padded to build the
281 /// precompiled preamble.
282 std::unique_ptr<llvm::MemoryBuffer> PreambleBuffer;
284 /// \brief The number of warnings that occurred while parsing the preamble.
286 /// This value will be used to restore the state of the \c DiagnosticsEngine
287 /// object when re-using the precompiled preamble. Note that only the
288 /// number of warnings matters, since we will not save the preamble
289 /// when any errors are present.
290 unsigned NumWarningsInPreamble;
292 /// \brief A list of the serialization ID numbers for each of the top-level
293 /// declarations parsed within the precompiled preamble.
294 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
296 /// \brief Whether we should be caching code-completion results.
297 bool ShouldCacheCodeCompletionResults : 1;
299 /// \brief Whether to include brief documentation within the set of code
300 /// completions cached.
301 bool IncludeBriefCommentsInCodeCompletion : 1;
303 /// \brief True if non-system source files should be treated as volatile
304 /// (likely to change while trying to use them).
305 bool UserFilesAreVolatile : 1;
307 /// \brief The language options used when we load an AST file.
308 LangOptions ASTFileLangOpts;
310 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
311 ASTUnit &AST, bool CaptureDiagnostics);
313 void TranslateStoredDiagnostics(FileManager &FileMgr,
314 SourceManager &SrcMan,
315 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
316 SmallVectorImpl<StoredDiagnostic> &Out);
318 void clearFileLevelDecls();
321 /// \brief A cached code-completion result, which may be introduced in one of
322 /// many different contexts.
323 struct CachedCodeCompletionResult {
324 /// \brief The code-completion string corresponding to this completion
326 CodeCompletionString *Completion;
328 /// \brief A bitmask that indicates which code-completion contexts should
329 /// contain this completion result.
331 /// The bits in the bitmask correspond to the values of
332 /// CodeCompleteContext::Kind. To map from a completion context kind to a
333 /// bit, shift 1 by that number of bits. Many completions can occur in
334 /// several different contexts.
335 uint64_t ShowInContexts;
337 /// \brief The priority given to this code-completion result.
340 /// \brief The libclang cursor kind corresponding to this code-completion
344 /// \brief The availability of this code-completion result.
345 CXAvailabilityKind Availability;
347 /// \brief The simplified type class for a non-macro completion result.
348 SimplifiedTypeClass TypeClass;
350 /// \brief The type of a non-macro completion result, stored as a unique
351 /// integer used by the string map of cached completion types.
353 /// This value will be zero if the type is not known, or a unique value
354 /// determined by the formatted type string. Se \c CachedCompletionTypes
355 /// for more information.
359 /// \brief Retrieve the mapping from formatted type names to unique type
361 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
362 return CachedCompletionTypes;
365 /// \brief Retrieve the allocator used to cache global code completions.
366 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
367 getCachedCompletionAllocator() {
368 return CachedCompletionAllocator;
371 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
373 CCTUInfo.reset(new CodeCompletionTUInfo(
374 new GlobalCodeCompletionAllocator));
379 /// \brief Allocator used to store cached code completions.
380 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
381 CachedCompletionAllocator;
383 std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
385 /// \brief The set of cached code-completion results.
386 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
388 /// \brief A mapping from the formatted type name to a unique number for that
389 /// type, which is used for type equality comparisons.
390 llvm::StringMap<unsigned> CachedCompletionTypes;
392 /// \brief A string hash of the top-level declaration and macro definition
393 /// names processed the last time that we reparsed the file.
395 /// This hash value is used to determine when we need to refresh the
396 /// global code-completion cache.
397 unsigned CompletionCacheTopLevelHashValue;
399 /// \brief A string hash of the top-level declaration and macro definition
400 /// names processed the last time that we reparsed the precompiled preamble.
402 /// This hash value is used to determine when we need to refresh the
403 /// global code-completion cache after a rebuild of the precompiled preamble.
404 unsigned PreambleTopLevelHashValue;
406 /// \brief The current hash value for the top-level declaration and macro
408 unsigned CurrentTopLevelHashValue;
410 /// \brief Bit used by CIndex to mark when a translation unit may be in an
411 /// inconsistent state, and is not safe to free.
412 unsigned UnsafeToFree : 1;
414 /// \brief Cache any "global" code-completion results, so that we can avoid
415 /// recomputing them with each completion.
416 void CacheCodeCompletionResults();
418 /// \brief Clear out and deallocate
419 void ClearCachedCompletionResults();
421 ASTUnit(const ASTUnit &) = delete;
422 void operator=(const ASTUnit &) = delete;
424 explicit ASTUnit(bool MainFileIsAST);
426 void CleanTemporaryFiles();
427 bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
428 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer);
430 struct ComputedPreamble {
431 llvm::MemoryBuffer *Buffer;
432 std::unique_ptr<llvm::MemoryBuffer> Owner;
434 bool PreambleEndsAtStartOfLine;
435 ComputedPreamble(llvm::MemoryBuffer *Buffer,
436 std::unique_ptr<llvm::MemoryBuffer> Owner, unsigned Size,
437 bool PreambleEndsAtStartOfLine)
438 : Buffer(Buffer), Owner(std::move(Owner)), Size(Size),
439 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
440 ComputedPreamble(ComputedPreamble &&C)
441 : Buffer(C.Buffer), Owner(std::move(C.Owner)), Size(C.Size),
442 PreambleEndsAtStartOfLine(C.PreambleEndsAtStartOfLine) {}
444 ComputedPreamble ComputePreamble(CompilerInvocation &Invocation,
447 std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
448 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
449 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild = true,
450 unsigned MaxLines = 0);
451 void RealizeTopLevelDeclsFromPreamble();
453 /// \brief Transfers ownership of the objects (like SourceManager) from
454 /// \param CI to this ASTUnit.
455 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
457 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
458 /// which is not supported.
460 /// Clients should create instances of the ConcurrencyCheck class whenever
461 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
462 /// just about any usage.
463 /// Becomes a noop in release mode; only useful for debug mode checking.
464 class ConcurrencyState {
465 void *Mutex; // a llvm::sys::MutexImpl in debug;
474 ConcurrencyState ConcurrencyCheckValue;
477 class ConcurrencyCheck {
481 explicit ConcurrencyCheck(ASTUnit &Self)
484 Self.ConcurrencyCheckValue.start();
486 ~ConcurrencyCheck() {
487 Self.ConcurrencyCheckValue.finish();
490 friend class ConcurrencyCheck;
494 bool isMainFileAST() const { return MainFileIsAST; }
496 bool isUnsafeToFree() const { return UnsafeToFree; }
497 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
499 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
500 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
502 const SourceManager &getSourceManager() const { return *SourceMgr; }
503 SourceManager &getSourceManager() { return *SourceMgr; }
505 const Preprocessor &getPreprocessor() const { return *PP; }
506 Preprocessor &getPreprocessor() { return *PP; }
508 const ASTContext &getASTContext() const { return *Ctx; }
509 ASTContext &getASTContext() { return *Ctx; }
511 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
512 void setPreprocessor(Preprocessor *pp);
514 bool hasSema() const { return (bool)TheSema; }
515 Sema &getSema() const {
516 assert(TheSema && "ASTUnit does not have a Sema object!");
520 const LangOptions &getLangOpts() const {
521 assert(LangOpts && " ASTUnit does not have language options");
525 const FileManager &getFileManager() const { return *FileMgr; }
526 FileManager &getFileManager() { return *FileMgr; }
528 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
530 StringRef getOriginalSourceFileName() {
531 return OriginalSourceFile;
534 ASTMutationListener *getASTMutationListener();
535 ASTDeserializationListener *getDeserializationListener();
537 /// \brief Add a temporary file that the ASTUnit depends on.
539 /// This file will be erased when the ASTUnit is destroyed.
540 void addTemporaryFile(StringRef TempFile);
542 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
544 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
545 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
547 StringRef getMainFileName() const;
549 /// \brief If this ASTUnit came from an AST file, returns the filename for it.
550 StringRef getASTFileName() const;
552 typedef std::vector<Decl *>::iterator top_level_iterator;
554 top_level_iterator top_level_begin() {
555 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
556 if (!TopLevelDeclsInPreamble.empty())
557 RealizeTopLevelDeclsFromPreamble();
558 return TopLevelDecls.begin();
561 top_level_iterator top_level_end() {
562 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
563 if (!TopLevelDeclsInPreamble.empty())
564 RealizeTopLevelDeclsFromPreamble();
565 return TopLevelDecls.end();
568 std::size_t top_level_size() const {
569 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
570 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
573 bool top_level_empty() const {
574 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
575 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
578 /// \brief Add a new top-level declaration.
579 void addTopLevelDecl(Decl *D) {
580 TopLevelDecls.push_back(D);
583 /// \brief Add a new local file-level declaration.
584 void addFileLevelDecl(Decl *D);
586 /// \brief Get the decls that are contained in a file in the Offset/Length
587 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
589 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
590 SmallVectorImpl<Decl *> &Decls);
592 /// \brief Add a new top-level declaration, identified by its ID in
593 /// the precompiled preamble.
594 void addTopLevelDeclFromPreamble(serialization::DeclID D) {
595 TopLevelDeclsInPreamble.push_back(D);
598 /// \brief Retrieve a reference to the current top-level name hash value.
600 /// Note: This is used internally by the top-level tracking action
601 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
603 /// \brief Get the source location for the given file:line:col triplet.
605 /// The difference with SourceManager::getLocation is that this method checks
606 /// whether the requested location points inside the precompiled preamble
607 /// in which case the returned source location will be a "loaded" one.
608 SourceLocation getLocation(const FileEntry *File,
609 unsigned Line, unsigned Col) const;
611 /// \brief Get the source location for the given file:offset pair.
612 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
614 /// \brief If \p Loc is a loaded location from the preamble, returns
615 /// the corresponding local location of the main file, otherwise it returns
617 SourceLocation mapLocationFromPreamble(SourceLocation Loc);
619 /// \brief If \p Loc is a local location of the main file but inside the
620 /// preamble chunk, returns the corresponding loaded location from the
621 /// preamble, otherwise it returns \p Loc.
622 SourceLocation mapLocationToPreamble(SourceLocation Loc);
624 bool isInPreambleFileID(SourceLocation Loc);
625 bool isInMainFileID(SourceLocation Loc);
626 SourceLocation getStartOfMainFileID();
627 SourceLocation getEndOfPreambleFileID();
629 /// \see mapLocationFromPreamble.
630 SourceRange mapRangeFromPreamble(SourceRange R) {
631 return SourceRange(mapLocationFromPreamble(R.getBegin()),
632 mapLocationFromPreamble(R.getEnd()));
635 /// \see mapLocationToPreamble.
636 SourceRange mapRangeToPreamble(SourceRange R) {
637 return SourceRange(mapLocationToPreamble(R.getBegin()),
638 mapLocationToPreamble(R.getEnd()));
641 // Retrieve the diagnostics associated with this AST
642 typedef StoredDiagnostic *stored_diag_iterator;
643 typedef const StoredDiagnostic *stored_diag_const_iterator;
644 stored_diag_const_iterator stored_diag_begin() const {
645 return StoredDiagnostics.begin();
647 stored_diag_iterator stored_diag_begin() {
648 return StoredDiagnostics.begin();
650 stored_diag_const_iterator stored_diag_end() const {
651 return StoredDiagnostics.end();
653 stored_diag_iterator stored_diag_end() {
654 return StoredDiagnostics.end();
656 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
658 stored_diag_iterator stored_diag_afterDriver_begin() {
659 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
660 NumStoredDiagnosticsFromDriver = 0;
661 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
664 typedef std::vector<CachedCodeCompletionResult>::iterator
665 cached_completion_iterator;
667 cached_completion_iterator cached_completion_begin() {
668 return CachedCompletionResults.begin();
671 cached_completion_iterator cached_completion_end() {
672 return CachedCompletionResults.end();
675 unsigned cached_completion_size() const {
676 return CachedCompletionResults.size();
679 /// \brief Returns an iterator range for the local preprocessing entities
680 /// of the local Preprocessor, if this is a parsed source file, or the loaded
681 /// preprocessing entities of the primary module if this is an AST file.
682 llvm::iterator_range<PreprocessingRecord::iterator>
683 getLocalPreprocessingEntities() const;
685 /// \brief Type for a function iterating over a number of declarations.
686 /// \returns true to continue iteration and false to abort.
687 typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
689 /// \brief Iterate over local declarations (locally parsed if this is a parsed
690 /// source file or the loaded declarations of the primary module if this is an
692 /// \returns true if the iteration was complete or false if it was aborted.
693 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
695 /// \brief Get the PCH file if one was included.
696 const FileEntry *getPCHFile();
698 /// \brief Returns true if the ASTUnit was constructed from a serialized
702 std::unique_ptr<llvm::MemoryBuffer>
703 getBufferForFile(StringRef Filename, std::string *ErrorStr = nullptr);
705 /// \brief Determine what kind of translation unit this AST represents.
706 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
708 /// \brief A mapping from a file name to the memory buffer that stores the
709 /// remapped contents of that file.
710 typedef std::pair<std::string, llvm::MemoryBuffer *> RemappedFile;
712 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
713 static ASTUnit *create(CompilerInvocation *CI,
714 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
715 bool CaptureDiagnostics,
716 bool UserFilesAreVolatile);
718 /// \brief Create a ASTUnit from an AST file.
720 /// \param Filename - The AST file to load.
722 /// \param PCHContainerRdr - The PCHContainerOperations to use for loading and
723 /// creating modules.
724 /// \param Diags - The diagnostics engine to use for reporting errors; its
725 /// lifetime is expected to extend past that of the returned ASTUnit.
727 /// \returns - The initialized ASTUnit or null if the AST failed to load.
728 static std::unique_ptr<ASTUnit> LoadFromASTFile(
729 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
730 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
731 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false,
732 bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None,
733 bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
734 bool UserFilesAreVolatile = false);
737 /// \brief Helper function for \c LoadFromCompilerInvocation() and
738 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
740 /// \param PrecompilePreambleAfterNParses After how many parses the preamble
741 /// of this translation unit should be precompiled, to improve the performance
742 /// of reparsing. Set to zero to disable preambles.
744 /// \returns \c true if a catastrophic failure occurred (which means that the
745 /// \c ASTUnit itself is invalid), or \c false otherwise.
746 bool LoadFromCompilerInvocation(
747 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
748 unsigned PrecompilePreambleAfterNParses);
752 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
753 /// object, by invoking the optionally provided ASTFrontendAction.
755 /// \param CI - The compiler invocation to use; it must have exactly one input
756 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
758 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
759 /// creating modules.
761 /// \param Diags - The diagnostics engine to use for reporting errors; its
762 /// lifetime is expected to extend past that of the returned ASTUnit.
764 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
767 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
770 /// \param Persistent - if true the returned ASTUnit will be complete.
771 /// false means the caller is only interested in getting info through the
772 /// provided \see Action.
774 /// \param ErrAST - If non-null and parsing failed without any AST to return
775 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
776 /// mainly to allow the caller to see the diagnostics.
777 /// This will only receive an ASTUnit if a new one was created. If an already
778 /// created ASTUnit was passed in \p Unit then the caller can check that.
780 static ASTUnit *LoadFromCompilerInvocationAction(
781 CompilerInvocation *CI,
782 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
783 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
784 ASTFrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
785 bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
786 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
787 unsigned PrecompilePreambleAfterNParses = 0,
788 bool CacheCodeCompletionResults = false,
789 bool IncludeBriefCommentsInCodeCompletion = false,
790 bool UserFilesAreVolatile = false,
791 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
793 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
794 /// CompilerInvocation object.
796 /// \param CI - The compiler invocation to use; it must have exactly one input
797 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
799 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
800 /// creating modules.
802 /// \param Diags - The diagnostics engine to use for reporting errors; its
803 /// lifetime is expected to extend past that of the returned ASTUnit.
805 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
806 // shouldn't need to specify them at construction time.
807 static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
808 CompilerInvocation *CI,
809 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
810 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
811 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
812 unsigned PrecompilePreambleAfterNParses = 0,
813 TranslationUnitKind TUKind = TU_Complete,
814 bool CacheCodeCompletionResults = false,
815 bool IncludeBriefCommentsInCodeCompletion = false,
816 bool UserFilesAreVolatile = false);
818 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
819 /// arguments, which must specify exactly one source file.
821 /// \param ArgBegin - The beginning of the argument vector.
823 /// \param ArgEnd - The end of the argument vector.
825 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
826 /// creating modules.
828 /// \param Diags - The diagnostics engine to use for reporting errors; its
829 /// lifetime is expected to extend past that of the returned ASTUnit.
831 /// \param ResourceFilesPath - The path to the compiler resource files.
833 /// \param ModuleFormat - If provided, uses the specific module format.
835 /// \param ErrAST - If non-null and parsing failed without any AST to return
836 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
837 /// mainly to allow the caller to see the diagnostics.
839 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
840 // shouldn't need to specify them at construction time.
841 static ASTUnit *LoadFromCommandLine(
842 const char **ArgBegin, const char **ArgEnd,
843 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
844 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
845 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
846 ArrayRef<RemappedFile> RemappedFiles = None,
847 bool RemappedFilesKeepOriginalName = true,
848 unsigned PrecompilePreambleAfterNParses = 0,
849 TranslationUnitKind TUKind = TU_Complete,
850 bool CacheCodeCompletionResults = false,
851 bool IncludeBriefCommentsInCodeCompletion = false,
852 bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
853 bool UserFilesAreVolatile = false, bool ForSerialization = false,
854 llvm::Optional<StringRef> ModuleFormat = llvm::None,
855 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
857 /// \brief Reparse the source files using the same command-line options that
858 /// were originally used to produce this translation unit.
860 /// \returns True if a failure occurred that causes the ASTUnit not to
861 /// contain any translation-unit information, false otherwise.
862 bool Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
863 ArrayRef<RemappedFile> RemappedFiles = None);
865 /// \brief Perform code completion at the given file, line, and
866 /// column within this translation unit.
868 /// \param File The file in which code completion will occur.
870 /// \param Line The line at which code completion will occur.
872 /// \param Column The column at which code completion will occur.
874 /// \param IncludeMacros Whether to include macros in the code-completion
877 /// \param IncludeCodePatterns Whether to include code patterns (such as a
878 /// for loop) in the code-completion results.
880 /// \param IncludeBriefComments Whether to include brief documentation within
881 /// the set of code completions returned.
883 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
884 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
885 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
886 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
887 bool IncludeCodePatterns, bool IncludeBriefComments,
888 CodeCompleteConsumer &Consumer,
889 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
890 DiagnosticsEngine &Diag, LangOptions &LangOpts,
891 SourceManager &SourceMgr, FileManager &FileMgr,
892 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
893 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
895 /// \brief Save this translation unit to a file with the given name.
897 /// \returns true if there was a file error or false if the save was
899 bool Save(StringRef File);
901 /// \brief Serialize this translation unit with the given output stream.
903 /// \returns True if an error occurred, false otherwise.
904 bool serialize(raw_ostream &OS);
906 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
907 Module::NameVisibilityKind Visibility,
908 bool IsInclusionDirective) override {
909 // ASTUnit doesn't know how to load modules (not that this matters).
910 return ModuleLoadResult();
913 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
914 SourceLocation ImportLoc) override {}
916 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
918 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override