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/FileSystemOptions.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetOptions.h"
23 #include "clang/Lex/HeaderSearchOptions.h"
24 #include "clang/Lex/ModuleLoader.h"
25 #include "clang/Lex/PreprocessingRecord.h"
26 #include "clang/Sema/CodeCompleteConsumer.h"
27 #include "clang/Serialization/ASTBitCodes.h"
28 #include "llvm/ADT/IntrusiveRefCntPtr.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/Support/MD5.h"
35 #include <sys/types.h>
47 class CompilerInvocation;
48 class CompilerInstance;
50 class DiagnosticsEngine;
54 class MemoryBufferCache;
56 class PCHContainerOperations;
57 class PCHContainerReader;
60 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 IntrusiveRefCntPtr<MemoryBufferCache> PCMCache;
93 std::unique_ptr<HeaderSearch> HeaderInfo;
94 IntrusiveRefCntPtr<TargetInfo> Target;
95 std::shared_ptr<Preprocessor> PP;
96 IntrusiveRefCntPtr<ASTContext> Ctx;
97 std::shared_ptr<TargetOptions> TargetOpts;
98 std::shared_ptr<HeaderSearchOptions> HSOpts;
99 IntrusiveRefCntPtr<ASTReader> Reader;
100 bool HadModuleLoaderFatalFailure;
102 struct ASTWriterData;
103 std::unique_ptr<ASTWriterData> WriterData;
105 FileSystemOptions FileSystemOpts;
107 /// \brief The AST consumer that received information about the translation
108 /// unit as it was parsed or loaded.
109 std::unique_ptr<ASTConsumer> Consumer;
111 /// \brief The semantic analysis object used to type-check the translation
113 std::unique_ptr<Sema> TheSema;
115 /// Optional owned invocation, just used to make the invocation used in
116 /// LoadFromCommandLine available.
117 std::shared_ptr<CompilerInvocation> Invocation;
119 // OnlyLocalDecls - when true, walking this AST should only visit declarations
120 // that come from the AST itself, not from included precompiled headers.
121 // FIXME: This is temporary; eventually, CIndex will always do this.
124 /// \brief Whether to capture any diagnostics produced.
125 bool CaptureDiagnostics;
127 /// \brief Track whether the main file was loaded from an AST or not.
130 /// \brief What kind of translation unit this AST represents.
131 TranslationUnitKind TUKind;
133 /// \brief Whether we should time each operation.
136 /// \brief Whether the ASTUnit should delete the remapped buffers.
137 bool OwnsRemappedFileBuffers;
139 /// Track the top-level decls which appeared in an ASTUnit which was loaded
140 /// from a source file.
142 // FIXME: This is just an optimization hack to avoid deserializing large parts
143 // of a PCH file when using the Index library on an ASTUnit loaded from
144 // source. In the long term we should make the Index library use efficient and
145 // more scalable search mechanisms.
146 std::vector<Decl*> TopLevelDecls;
148 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
149 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
150 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
152 /// \brief Map from FileID to the file-level declarations that it contains.
153 /// The files and decls are only local (and non-preamble) ones.
154 FileDeclsTy FileDecls;
156 /// The name of the original source file used to generate this ASTUnit.
157 std::string OriginalSourceFile;
159 /// \brief The set of diagnostics produced when creating the preamble.
160 SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
162 /// \brief The set of diagnostics produced when creating this
163 /// translation unit.
164 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
166 /// \brief The set of diagnostics produced when failing to parse, e.g. due
167 /// to failure to load the PCH.
168 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
170 /// \brief The number of stored diagnostics that come from the driver
173 /// Diagnostics that come from the driver are retained from one parse to
175 unsigned NumStoredDiagnosticsFromDriver;
177 /// \brief Counter that determines when we want to try building a
178 /// precompiled preamble.
180 /// If zero, we will never build a precompiled preamble. Otherwise,
181 /// it's treated as a counter that decrements each time we reparse
182 /// without the benefit of a precompiled preamble. When it hits 1,
183 /// we'll attempt to rebuild the precompiled header. This way, if
184 /// building the precompiled preamble fails, we won't try again for
185 /// some number of calls.
186 unsigned PreambleRebuildCounter;
190 const FileEntry *File;
191 std::vector<char> Buffer;
192 mutable unsigned NumLines;
195 PreambleData() : File(nullptr), NumLines(0) { }
197 void assign(const FileEntry *F, const char *begin, const char *end) {
199 Buffer.assign(begin, end);
203 void clear() { Buffer.clear(); File = nullptr; NumLines = 0; }
205 size_t size() const { return Buffer.size(); }
206 bool empty() const { return Buffer.empty(); }
208 const char *getBufferStart() const { return &Buffer[0]; }
210 unsigned getNumLines() const {
217 SourceRange getSourceRange(const SourceManager &SM) const {
218 SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
219 return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
223 void countLines() const;
226 const PreambleData &getPreambleData() const {
230 /// Data used to determine if a file used in the preamble has been changed.
231 struct PreambleFileHash {
232 /// All files have size set.
235 /// Modification time is set for files that are on disk. For memory
236 /// buffers it is zero.
239 /// Memory buffers have MD5 instead of modification time. We don't
240 /// compute MD5 for on-disk files because we hope that modification time is
241 /// enough to tell if the file was changed.
242 llvm::MD5::MD5Result MD5;
244 static PreambleFileHash createForFile(off_t Size, time_t ModTime);
245 static PreambleFileHash
246 createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
248 friend bool operator==(const PreambleFileHash &LHS,
249 const PreambleFileHash &RHS);
251 friend bool operator!=(const PreambleFileHash &LHS,
252 const PreambleFileHash &RHS) {
253 return !(LHS == RHS);
258 /// \brief The contents of the preamble that has been precompiled to
260 PreambleData Preamble;
262 /// \brief Whether the preamble ends at the start of a new line.
264 /// Used to inform the lexer as to whether it's starting at the beginning of
265 /// a line after skipping the preamble.
266 bool PreambleEndsAtStartOfLine;
268 /// \brief Keeps track of the files that were used when computing the
269 /// preamble, with both their buffer size and their modification time.
271 /// If any of the files have changed from one compile to the next,
272 /// the preamble must be thrown away.
273 llvm::StringMap<PreambleFileHash> FilesInPreamble;
275 /// \brief When non-NULL, this is the buffer used to store the contents of
276 /// the main file when it has been padded for use with the precompiled
278 std::unique_ptr<llvm::MemoryBuffer> SavedMainFileBuffer;
280 /// \brief When non-NULL, this is the buffer used to store the
281 /// contents of the preamble when it has been padded to build the
282 /// precompiled preamble.
283 std::unique_ptr<llvm::MemoryBuffer> PreambleBuffer;
285 /// \brief The number of warnings that occurred while parsing the preamble.
287 /// This value will be used to restore the state of the \c DiagnosticsEngine
288 /// object when re-using the precompiled preamble. Note that only the
289 /// number of warnings matters, since we will not save the preamble
290 /// when any errors are present.
291 unsigned NumWarningsInPreamble;
293 /// \brief A list of the serialization ID numbers for each of the top-level
294 /// declarations parsed within the precompiled preamble.
295 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
297 /// \brief Whether we should be caching code-completion results.
298 bool ShouldCacheCodeCompletionResults : 1;
300 /// \brief Whether to include brief documentation within the set of code
301 /// completions cached.
302 bool IncludeBriefCommentsInCodeCompletion : 1;
304 /// \brief True if non-system source files should be treated as volatile
305 /// (likely to change while trying to use them).
306 bool UserFilesAreVolatile : 1;
308 /// \brief The language options used when we load an AST file.
309 LangOptions ASTFileLangOpts;
311 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
312 ASTUnit &AST, bool CaptureDiagnostics);
314 void TranslateStoredDiagnostics(FileManager &FileMgr,
315 SourceManager &SrcMan,
316 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
317 SmallVectorImpl<StoredDiagnostic> &Out);
319 void clearFileLevelDecls();
322 /// \brief A cached code-completion result, which may be introduced in one of
323 /// many different contexts.
324 struct CachedCodeCompletionResult {
325 /// \brief The code-completion string corresponding to this completion
327 CodeCompletionString *Completion;
329 /// \brief A bitmask that indicates which code-completion contexts should
330 /// contain this completion result.
332 /// The bits in the bitmask correspond to the values of
333 /// CodeCompleteContext::Kind. To map from a completion context kind to a
334 /// bit, shift 1 by that number of bits. Many completions can occur in
335 /// several different contexts.
336 uint64_t ShowInContexts;
338 /// \brief The priority given to this code-completion result.
341 /// \brief The libclang cursor kind corresponding to this code-completion
345 /// \brief The availability of this code-completion result.
346 CXAvailabilityKind Availability;
348 /// \brief The simplified type class for a non-macro completion result.
349 SimplifiedTypeClass TypeClass;
351 /// \brief The type of a non-macro completion result, stored as a unique
352 /// integer used by the string map of cached completion types.
354 /// This value will be zero if the type is not known, or a unique value
355 /// determined by the formatted type string. Se \c CachedCompletionTypes
356 /// for more information.
360 /// \brief Retrieve the mapping from formatted type names to unique type
362 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
363 return CachedCompletionTypes;
366 /// \brief Retrieve the allocator used to cache global code completions.
367 std::shared_ptr<GlobalCodeCompletionAllocator>
368 getCachedCompletionAllocator() {
369 return CachedCompletionAllocator;
372 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
374 CCTUInfo = llvm::make_unique<CodeCompletionTUInfo>(
375 std::make_shared<GlobalCodeCompletionAllocator>());
380 /// \brief Allocator used to store cached code completions.
381 std::shared_ptr<GlobalCodeCompletionAllocator> 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 bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
427 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
428 IntrusiveRefCntPtr<vfs::FileSystem> VFS);
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) {}
441 ComputedPreamble ComputePreamble(CompilerInvocation &Invocation,
443 IntrusiveRefCntPtr<vfs::FileSystem> VFS);
445 std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
446 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
447 const CompilerInvocation &PreambleInvocationIn,
448 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild = true,
449 unsigned MaxLines = 0);
450 void RealizeTopLevelDeclsFromPreamble();
452 /// \brief Transfers ownership of the objects (like SourceManager) from
453 /// \param CI to this ASTUnit.
454 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
456 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
457 /// which is not supported.
459 /// Clients should create instances of the ConcurrencyCheck class whenever
460 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
461 /// just about any usage.
462 /// Becomes a noop in release mode; only useful for debug mode checking.
463 class ConcurrencyState {
464 void *Mutex; // a llvm::sys::MutexImpl in debug;
473 ConcurrencyState ConcurrencyCheckValue;
476 class ConcurrencyCheck {
480 explicit ConcurrencyCheck(ASTUnit &Self)
483 Self.ConcurrencyCheckValue.start();
485 ~ConcurrencyCheck() {
486 Self.ConcurrencyCheckValue.finish();
489 friend class ConcurrencyCheck;
493 bool isMainFileAST() const { return MainFileIsAST; }
495 bool isUnsafeToFree() const { return UnsafeToFree; }
496 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
498 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
499 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
501 const SourceManager &getSourceManager() const { return *SourceMgr; }
502 SourceManager &getSourceManager() { return *SourceMgr; }
504 const Preprocessor &getPreprocessor() const { return *PP; }
505 Preprocessor &getPreprocessor() { return *PP; }
506 std::shared_ptr<Preprocessor> getPreprocessorPtr() const { return PP; }
508 const ASTContext &getASTContext() const { return *Ctx; }
509 ASTContext &getASTContext() { return *Ctx; }
511 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
512 void setPreprocessor(std::shared_ptr<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 IntrusiveRefCntPtr<ASTReader> getASTReader() const;
532 StringRef getOriginalSourceFileName() {
533 return OriginalSourceFile;
536 ASTMutationListener *getASTMutationListener();
537 ASTDeserializationListener *getDeserializationListener();
539 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
541 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
542 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
544 StringRef getMainFileName() const;
546 /// \brief If this ASTUnit came from an AST file, returns the filename for it.
547 StringRef getASTFileName() const;
549 typedef std::vector<Decl *>::iterator top_level_iterator;
551 top_level_iterator top_level_begin() {
552 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
553 if (!TopLevelDeclsInPreamble.empty())
554 RealizeTopLevelDeclsFromPreamble();
555 return TopLevelDecls.begin();
558 top_level_iterator top_level_end() {
559 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
560 if (!TopLevelDeclsInPreamble.empty())
561 RealizeTopLevelDeclsFromPreamble();
562 return TopLevelDecls.end();
565 std::size_t top_level_size() const {
566 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
567 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
570 bool top_level_empty() const {
571 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
572 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
575 /// \brief Add a new top-level declaration.
576 void addTopLevelDecl(Decl *D) {
577 TopLevelDecls.push_back(D);
580 /// \brief Add a new local file-level declaration.
581 void addFileLevelDecl(Decl *D);
583 /// \brief Get the decls that are contained in a file in the Offset/Length
584 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
586 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
587 SmallVectorImpl<Decl *> &Decls);
589 /// \brief Add a new top-level declaration, identified by its ID in
590 /// the precompiled preamble.
591 void addTopLevelDeclFromPreamble(serialization::DeclID D) {
592 TopLevelDeclsInPreamble.push_back(D);
595 /// \brief Retrieve a reference to the current top-level name hash value.
597 /// Note: This is used internally by the top-level tracking action
598 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
600 /// \brief Get the source location for the given file:line:col triplet.
602 /// The difference with SourceManager::getLocation is that this method checks
603 /// whether the requested location points inside the precompiled preamble
604 /// in which case the returned source location will be a "loaded" one.
605 SourceLocation getLocation(const FileEntry *File,
606 unsigned Line, unsigned Col) const;
608 /// \brief Get the source location for the given file:offset pair.
609 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
611 /// \brief If \p Loc is a loaded location from the preamble, returns
612 /// the corresponding local location of the main file, otherwise it returns
614 SourceLocation mapLocationFromPreamble(SourceLocation Loc);
616 /// \brief If \p Loc is a local location of the main file but inside the
617 /// preamble chunk, returns the corresponding loaded location from the
618 /// preamble, otherwise it returns \p Loc.
619 SourceLocation mapLocationToPreamble(SourceLocation Loc);
621 bool isInPreambleFileID(SourceLocation Loc);
622 bool isInMainFileID(SourceLocation Loc);
623 SourceLocation getStartOfMainFileID();
624 SourceLocation getEndOfPreambleFileID();
626 /// \see mapLocationFromPreamble.
627 SourceRange mapRangeFromPreamble(SourceRange R) {
628 return SourceRange(mapLocationFromPreamble(R.getBegin()),
629 mapLocationFromPreamble(R.getEnd()));
632 /// \see mapLocationToPreamble.
633 SourceRange mapRangeToPreamble(SourceRange R) {
634 return SourceRange(mapLocationToPreamble(R.getBegin()),
635 mapLocationToPreamble(R.getEnd()));
638 // Retrieve the diagnostics associated with this AST
639 typedef StoredDiagnostic *stored_diag_iterator;
640 typedef const StoredDiagnostic *stored_diag_const_iterator;
641 stored_diag_const_iterator stored_diag_begin() const {
642 return StoredDiagnostics.begin();
644 stored_diag_iterator stored_diag_begin() {
645 return StoredDiagnostics.begin();
647 stored_diag_const_iterator stored_diag_end() const {
648 return StoredDiagnostics.end();
650 stored_diag_iterator stored_diag_end() {
651 return StoredDiagnostics.end();
653 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
655 stored_diag_iterator stored_diag_afterDriver_begin() {
656 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
657 NumStoredDiagnosticsFromDriver = 0;
658 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
661 typedef std::vector<CachedCodeCompletionResult>::iterator
662 cached_completion_iterator;
664 cached_completion_iterator cached_completion_begin() {
665 return CachedCompletionResults.begin();
668 cached_completion_iterator cached_completion_end() {
669 return CachedCompletionResults.end();
672 unsigned cached_completion_size() const {
673 return CachedCompletionResults.size();
676 /// \brief Returns an iterator range for the local preprocessing entities
677 /// of the local Preprocessor, if this is a parsed source file, or the loaded
678 /// preprocessing entities of the primary module if this is an AST file.
679 llvm::iterator_range<PreprocessingRecord::iterator>
680 getLocalPreprocessingEntities() const;
682 /// \brief Type for a function iterating over a number of declarations.
683 /// \returns true to continue iteration and false to abort.
684 typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
686 /// \brief Iterate over local declarations (locally parsed if this is a parsed
687 /// source file or the loaded declarations of the primary module if this is an
689 /// \returns true if the iteration was complete or false if it was aborted.
690 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
692 /// \brief Get the PCH file if one was included.
693 const FileEntry *getPCHFile();
695 /// \brief Returns true if the ASTUnit was constructed from a serialized
699 std::unique_ptr<llvm::MemoryBuffer>
700 getBufferForFile(StringRef Filename, std::string *ErrorStr = nullptr);
702 /// \brief Determine what kind of translation unit this AST represents.
703 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
705 /// \brief A mapping from a file name to the memory buffer that stores the
706 /// remapped contents of that file.
707 typedef std::pair<std::string, llvm::MemoryBuffer *> RemappedFile;
709 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
710 static std::unique_ptr<ASTUnit>
711 create(std::shared_ptr<CompilerInvocation> CI,
712 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool CaptureDiagnostics,
713 bool UserFilesAreVolatile);
715 /// \brief Create a ASTUnit from an AST file.
717 /// \param Filename - The AST file to load.
719 /// \param PCHContainerRdr - The PCHContainerOperations to use for loading and
720 /// creating modules.
721 /// \param Diags - The diagnostics engine to use for reporting errors; its
722 /// lifetime is expected to extend past that of the returned ASTUnit.
724 /// \returns - The initialized ASTUnit or null if the AST failed to load.
725 static std::unique_ptr<ASTUnit> LoadFromASTFile(
726 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
727 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
728 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false,
729 bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None,
730 bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
731 bool UserFilesAreVolatile = false);
734 /// \brief Helper function for \c LoadFromCompilerInvocation() and
735 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
737 /// \param PrecompilePreambleAfterNParses After how many parses the preamble
738 /// of this translation unit should be precompiled, to improve the performance
739 /// of reparsing. Set to zero to disable preambles.
741 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
742 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
743 /// for it to be loaded correctly, VFS should have access to it(i.e., be an
744 /// overlay over RealFileSystem).
746 /// \returns \c true if a catastrophic failure occurred (which means that the
747 /// \c ASTUnit itself is invalid), or \c false otherwise.
748 bool LoadFromCompilerInvocation(
749 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
750 unsigned PrecompilePreambleAfterNParses,
751 IntrusiveRefCntPtr<vfs::FileSystem> VFS);
755 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
756 /// object, by invoking the optionally provided ASTFrontendAction.
758 /// \param CI - The compiler invocation to use; it must have exactly one input
759 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
761 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
762 /// creating modules.
764 /// \param Diags - The diagnostics engine to use for reporting errors; its
765 /// lifetime is expected to extend past that of the returned ASTUnit.
767 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
770 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
773 /// \param Persistent - if true the returned ASTUnit will be complete.
774 /// false means the caller is only interested in getting info through the
775 /// provided \see Action.
777 /// \param ErrAST - If non-null and parsing failed without any AST to return
778 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
779 /// mainly to allow the caller to see the diagnostics.
780 /// This will only receive an ASTUnit if a new one was created. If an already
781 /// created ASTUnit was passed in \p Unit then the caller can check that.
783 static ASTUnit *LoadFromCompilerInvocationAction(
784 std::shared_ptr<CompilerInvocation> CI,
785 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
786 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
787 FrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
788 bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
789 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
790 unsigned PrecompilePreambleAfterNParses = 0,
791 bool CacheCodeCompletionResults = false,
792 bool IncludeBriefCommentsInCodeCompletion = false,
793 bool UserFilesAreVolatile = false,
794 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
796 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
797 /// CompilerInvocation object.
799 /// \param CI - The compiler invocation to use; it must have exactly one input
800 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
802 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
803 /// creating modules.
805 /// \param Diags - The diagnostics engine to use for reporting errors; its
806 /// lifetime is expected to extend past that of the returned ASTUnit.
808 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
809 // shouldn't need to specify them at construction time.
810 static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
811 std::shared_ptr<CompilerInvocation> CI,
812 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
813 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
814 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
815 unsigned PrecompilePreambleAfterNParses = 0,
816 TranslationUnitKind TUKind = TU_Complete,
817 bool CacheCodeCompletionResults = false,
818 bool IncludeBriefCommentsInCodeCompletion = false,
819 bool UserFilesAreVolatile = false);
821 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
822 /// arguments, which must specify exactly one source file.
824 /// \param ArgBegin - The beginning of the argument vector.
826 /// \param ArgEnd - The end of the argument vector.
828 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
829 /// creating modules.
831 /// \param Diags - The diagnostics engine to use for reporting errors; its
832 /// lifetime is expected to extend past that of the returned ASTUnit.
834 /// \param ResourceFilesPath - The path to the compiler resource files.
836 /// \param ModuleFormat - If provided, uses the specific module format.
838 /// \param ErrAST - If non-null and parsing failed without any AST to return
839 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
840 /// mainly to allow the caller to see the diagnostics.
842 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
843 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
844 /// for it to be loaded correctly, VFS should have access to it(i.e., be an
845 /// overlay over RealFileSystem). RealFileSystem will be used if \p VFS is nullptr.
847 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
848 // shouldn't need to specify them at construction time.
849 static ASTUnit *LoadFromCommandLine(
850 const char **ArgBegin, const char **ArgEnd,
851 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
852 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
853 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
854 ArrayRef<RemappedFile> RemappedFiles = None,
855 bool RemappedFilesKeepOriginalName = true,
856 unsigned PrecompilePreambleAfterNParses = 0,
857 TranslationUnitKind TUKind = TU_Complete,
858 bool CacheCodeCompletionResults = false,
859 bool IncludeBriefCommentsInCodeCompletion = false,
860 bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
861 bool UserFilesAreVolatile = false, bool ForSerialization = false,
862 llvm::Optional<StringRef> ModuleFormat = llvm::None,
863 std::unique_ptr<ASTUnit> *ErrAST = nullptr,
864 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
866 /// \brief Reparse the source files using the same command-line options that
867 /// were originally used to produce this translation unit.
869 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
870 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
871 /// for it to be loaded correctly, VFS should give an access to this(i.e. be an
872 /// overlay over RealFileSystem). FileMgr->getVirtualFileSystem() will be used if
873 /// \p VFS is nullptr.
875 /// \returns True if a failure occurred that causes the ASTUnit not to
876 /// contain any translation-unit information, false otherwise.
877 bool Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
878 ArrayRef<RemappedFile> RemappedFiles = None,
879 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
881 /// \brief Free data that will be re-generated on the next parse.
883 /// Preamble-related data is not affected.
884 void ResetForParse();
886 /// \brief Perform code completion at the given file, line, and
887 /// column within this translation unit.
889 /// \param File The file in which code completion will occur.
891 /// \param Line The line at which code completion will occur.
893 /// \param Column The column at which code completion will occur.
895 /// \param IncludeMacros Whether to include macros in the code-completion
898 /// \param IncludeCodePatterns Whether to include code patterns (such as a
899 /// for loop) in the code-completion results.
901 /// \param IncludeBriefComments Whether to include brief documentation within
902 /// the set of code completions returned.
904 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
905 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
906 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
907 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
908 bool IncludeCodePatterns, bool IncludeBriefComments,
909 CodeCompleteConsumer &Consumer,
910 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
911 DiagnosticsEngine &Diag, LangOptions &LangOpts,
912 SourceManager &SourceMgr, FileManager &FileMgr,
913 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
914 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
916 /// \brief Save this translation unit to a file with the given name.
918 /// \returns true if there was a file error or false if the save was
920 bool Save(StringRef File);
922 /// \brief Serialize this translation unit with the given output stream.
924 /// \returns True if an error occurred, false otherwise.
925 bool serialize(raw_ostream &OS);
927 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
928 Module::NameVisibilityKind Visibility,
929 bool IsInclusionDirective) override {
930 // ASTUnit doesn't know how to load modules (not that this matters).
931 return ModuleLoadResult();
934 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
935 SourceLocation ImportLoc) override {}
937 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
939 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override