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;
61 class ASTFrontendAction;
62 class ASTDeserializationListener;
64 /// \brief Utility class for loading a ASTContext from an AST file.
66 class ASTUnit : public ModuleLoader {
68 struct StandaloneFixIt {
69 std::pair<unsigned, unsigned> RemoveRange;
70 std::pair<unsigned, unsigned> InsertFromRange;
71 std::string CodeToInsert;
72 bool BeforePreviousInsertions;
75 struct StandaloneDiagnostic {
77 DiagnosticsEngine::Level Level;
81 std::vector<std::pair<unsigned, unsigned> > Ranges;
82 std::vector<StandaloneFixIt> FixIts;
86 std::shared_ptr<LangOptions> LangOpts;
87 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
88 IntrusiveRefCntPtr<FileManager> FileMgr;
89 IntrusiveRefCntPtr<SourceManager> SourceMgr;
90 std::unique_ptr<HeaderSearch> HeaderInfo;
91 IntrusiveRefCntPtr<TargetInfo> Target;
92 IntrusiveRefCntPtr<Preprocessor> PP;
93 IntrusiveRefCntPtr<ASTContext> Ctx;
94 std::shared_ptr<TargetOptions> TargetOpts;
95 IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
96 IntrusiveRefCntPtr<ASTReader> Reader;
97 bool HadModuleLoaderFatalFailure;
100 std::unique_ptr<ASTWriterData> WriterData;
102 FileSystemOptions FileSystemOpts;
104 /// \brief The AST consumer that received information about the translation
105 /// unit as it was parsed or loaded.
106 std::unique_ptr<ASTConsumer> Consumer;
108 /// \brief The semantic analysis object used to type-check the translation
110 std::unique_ptr<Sema> TheSema;
112 /// Optional owned invocation, just used to make the invocation used in
113 /// LoadFromCommandLine available.
114 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
116 // OnlyLocalDecls - when true, walking this AST should only visit declarations
117 // that come from the AST itself, not from included precompiled headers.
118 // FIXME: This is temporary; eventually, CIndex will always do this.
121 /// \brief Whether to capture any diagnostics produced.
122 bool CaptureDiagnostics;
124 /// \brief Track whether the main file was loaded from an AST or not.
127 /// \brief What kind of translation unit this AST represents.
128 TranslationUnitKind TUKind;
130 /// \brief Whether we should time each operation.
133 /// \brief Whether the ASTUnit should delete the remapped buffers.
134 bool OwnsRemappedFileBuffers;
136 /// Track the top-level decls which appeared in an ASTUnit which was loaded
137 /// from a source file.
139 // FIXME: This is just an optimization hack to avoid deserializing large parts
140 // of a PCH file when using the Index library on an ASTUnit loaded from
141 // source. In the long term we should make the Index library use efficient and
142 // more scalable search mechanisms.
143 std::vector<Decl*> TopLevelDecls;
145 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
146 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
147 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
149 /// \brief Map from FileID to the file-level declarations that it contains.
150 /// The files and decls are only local (and non-preamble) ones.
151 FileDeclsTy FileDecls;
153 /// The name of the original source file used to generate this ASTUnit.
154 std::string OriginalSourceFile;
156 /// \brief The set of diagnostics produced when creating the preamble.
157 SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
159 /// \brief The set of diagnostics produced when creating this
160 /// translation unit.
161 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
163 /// \brief The set of diagnostics produced when failing to parse, e.g. due
164 /// to failure to load the PCH.
165 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
167 /// \brief The number of stored diagnostics that come from the driver
170 /// Diagnostics that come from the driver are retained from one parse to
172 unsigned NumStoredDiagnosticsFromDriver;
174 /// \brief Counter that determines when we want to try building a
175 /// precompiled preamble.
177 /// If zero, we will never build a precompiled preamble. Otherwise,
178 /// it's treated as a counter that decrements each time we reparse
179 /// without the benefit of a precompiled preamble. When it hits 1,
180 /// we'll attempt to rebuild the precompiled header. This way, if
181 /// building the precompiled preamble fails, we won't try again for
182 /// some number of calls.
183 unsigned PreambleRebuildCounter;
187 const FileEntry *File;
188 std::vector<char> Buffer;
189 mutable unsigned NumLines;
192 PreambleData() : File(nullptr), NumLines(0) { }
194 void assign(const FileEntry *F, const char *begin, const char *end) {
196 Buffer.assign(begin, end);
200 void clear() { Buffer.clear(); File = nullptr; NumLines = 0; }
202 size_t size() const { return Buffer.size(); }
203 bool empty() const { return Buffer.empty(); }
205 const char *getBufferStart() const { return &Buffer[0]; }
207 unsigned getNumLines() const {
214 SourceRange getSourceRange(const SourceManager &SM) const {
215 SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
216 return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
220 void countLines() const;
223 const PreambleData &getPreambleData() const {
227 /// Data used to determine if a file used in the preamble has been changed.
228 struct PreambleFileHash {
229 /// All files have size set.
232 /// Modification time is set for files that are on disk. For memory
233 /// buffers it is zero.
236 /// Memory buffers have MD5 instead of modification time. We don't
237 /// compute MD5 for on-disk files because we hope that modification time is
238 /// enough to tell if the file was changed.
239 llvm::MD5::MD5Result MD5;
241 static PreambleFileHash createForFile(off_t Size, time_t ModTime);
242 static PreambleFileHash
243 createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
245 friend bool operator==(const PreambleFileHash &LHS,
246 const PreambleFileHash &RHS);
248 friend bool operator!=(const PreambleFileHash &LHS,
249 const PreambleFileHash &RHS) {
250 return !(LHS == RHS);
255 /// \brief The contents of the preamble that has been precompiled to
257 PreambleData Preamble;
259 /// \brief Whether the preamble ends at the start of a new line.
261 /// Used to inform the lexer as to whether it's starting at the beginning of
262 /// a line after skipping the preamble.
263 bool PreambleEndsAtStartOfLine;
265 /// \brief Keeps track of the files that were used when computing the
266 /// preamble, with both their buffer size and their modification time.
268 /// If any of the files have changed from one compile to the next,
269 /// the preamble must be thrown away.
270 llvm::StringMap<PreambleFileHash> FilesInPreamble;
272 /// \brief When non-NULL, this is the buffer used to store the contents of
273 /// the main file when it has been padded for use with the precompiled
275 llvm::MemoryBuffer *SavedMainFileBuffer;
277 /// \brief When non-NULL, this is the buffer used to store the
278 /// contents of the preamble when it has been padded to build the
279 /// precompiled preamble.
280 llvm::MemoryBuffer *PreambleBuffer;
282 /// \brief The number of warnings that occurred while parsing the preamble.
284 /// This value will be used to restore the state of the \c DiagnosticsEngine
285 /// object when re-using the precompiled preamble. Note that only the
286 /// number of warnings matters, since we will not save the preamble
287 /// when any errors are present.
288 unsigned NumWarningsInPreamble;
290 /// \brief A list of the serialization ID numbers for each of the top-level
291 /// declarations parsed within the precompiled preamble.
292 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
294 /// \brief Whether we should be caching code-completion results.
295 bool ShouldCacheCodeCompletionResults : 1;
297 /// \brief Whether to include brief documentation within the set of code
298 /// completions cached.
299 bool IncludeBriefCommentsInCodeCompletion : 1;
301 /// \brief True if non-system source files should be treated as volatile
302 /// (likely to change while trying to use them).
303 bool UserFilesAreVolatile : 1;
305 /// \brief The language options used when we load an AST file.
306 LangOptions ASTFileLangOpts;
308 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
309 const char **ArgBegin, const char **ArgEnd,
310 ASTUnit &AST, bool CaptureDiagnostics);
312 void TranslateStoredDiagnostics(FileManager &FileMgr,
313 SourceManager &SrcMan,
314 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
315 SmallVectorImpl<StoredDiagnostic> &Out);
317 void clearFileLevelDecls();
320 /// \brief A cached code-completion result, which may be introduced in one of
321 /// many different contexts.
322 struct CachedCodeCompletionResult {
323 /// \brief The code-completion string corresponding to this completion
325 CodeCompletionString *Completion;
327 /// \brief A bitmask that indicates which code-completion contexts should
328 /// contain this completion result.
330 /// The bits in the bitmask correspond to the values of
331 /// CodeCompleteContext::Kind. To map from a completion context kind to a
332 /// bit, shift 1 by that number of bits. Many completions can occur in
333 /// several different contexts.
334 uint64_t ShowInContexts;
336 /// \brief The priority given to this code-completion result.
339 /// \brief The libclang cursor kind corresponding to this code-completion
343 /// \brief The availability of this code-completion result.
344 CXAvailabilityKind Availability;
346 /// \brief The simplified type class for a non-macro completion result.
347 SimplifiedTypeClass TypeClass;
349 /// \brief The type of a non-macro completion result, stored as a unique
350 /// integer used by the string map of cached completion types.
352 /// This value will be zero if the type is not known, or a unique value
353 /// determined by the formatted type string. Se \c CachedCompletionTypes
354 /// for more information.
358 /// \brief Retrieve the mapping from formatted type names to unique type
360 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
361 return CachedCompletionTypes;
364 /// \brief Retrieve the allocator used to cache global code completions.
365 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
366 getCachedCompletionAllocator() {
367 return CachedCompletionAllocator;
370 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
372 CCTUInfo.reset(new CodeCompletionTUInfo(
373 new GlobalCodeCompletionAllocator));
378 /// \brief Allocator used to store cached code completions.
379 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
380 CachedCompletionAllocator;
382 std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
384 /// \brief The set of cached code-completion results.
385 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
387 /// \brief A mapping from the formatted type name to a unique number for that
388 /// type, which is used for type equality comparisons.
389 llvm::StringMap<unsigned> CachedCompletionTypes;
391 /// \brief A string hash of the top-level declaration and macro definition
392 /// names processed the last time that we reparsed the file.
394 /// This hash value is used to determine when we need to refresh the
395 /// global code-completion cache.
396 unsigned CompletionCacheTopLevelHashValue;
398 /// \brief A string hash of the top-level declaration and macro definition
399 /// names processed the last time that we reparsed the precompiled preamble.
401 /// This hash value is used to determine when we need to refresh the
402 /// global code-completion cache after a rebuild of the precompiled preamble.
403 unsigned PreambleTopLevelHashValue;
405 /// \brief The current hash value for the top-level declaration and macro
407 unsigned CurrentTopLevelHashValue;
409 /// \brief Bit used by CIndex to mark when a translation unit may be in an
410 /// inconsistent state, and is not safe to free.
411 unsigned UnsafeToFree : 1;
413 /// \brief Cache any "global" code-completion results, so that we can avoid
414 /// recomputing them with each completion.
415 void CacheCodeCompletionResults();
417 /// \brief Clear out and deallocate
418 void ClearCachedCompletionResults();
420 ASTUnit(const ASTUnit &) LLVM_DELETED_FUNCTION;
421 void operator=(const ASTUnit &) LLVM_DELETED_FUNCTION;
423 explicit ASTUnit(bool MainFileIsAST);
425 void CleanTemporaryFiles();
426 bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
428 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
429 ComputePreamble(CompilerInvocation &Invocation,
430 unsigned MaxLines, bool &CreatedBuffer);
432 llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
433 const CompilerInvocation &PreambleInvocationIn,
434 bool AllowRebuild = true,
435 unsigned MaxLines = 0);
436 void RealizeTopLevelDeclsFromPreamble();
438 /// \brief Transfers ownership of the objects (like SourceManager) from
439 /// \param CI to this ASTUnit.
440 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
442 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
443 /// which is not supported.
445 /// Clients should create instances of the ConcurrencyCheck class whenever
446 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
447 /// just about any usage.
448 /// Becomes a noop in release mode; only useful for debug mode checking.
449 class ConcurrencyState {
450 void *Mutex; // a llvm::sys::MutexImpl in debug;
459 ConcurrencyState ConcurrencyCheckValue;
462 class ConcurrencyCheck {
466 explicit ConcurrencyCheck(ASTUnit &Self)
469 Self.ConcurrencyCheckValue.start();
471 ~ConcurrencyCheck() {
472 Self.ConcurrencyCheckValue.finish();
475 friend class ConcurrencyCheck;
479 bool isMainFileAST() const { return MainFileIsAST; }
481 bool isUnsafeToFree() const { return UnsafeToFree; }
482 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
484 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
485 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
487 const SourceManager &getSourceManager() const { return *SourceMgr; }
488 SourceManager &getSourceManager() { return *SourceMgr; }
490 const Preprocessor &getPreprocessor() const { return *PP; }
491 Preprocessor &getPreprocessor() { return *PP; }
493 const ASTContext &getASTContext() const { return *Ctx; }
494 ASTContext &getASTContext() { return *Ctx; }
496 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
497 void setPreprocessor(Preprocessor *pp);
499 bool hasSema() const { return (bool)TheSema; }
500 Sema &getSema() const {
501 assert(TheSema && "ASTUnit does not have a Sema object!");
505 const LangOptions &getLangOpts() const {
506 assert(LangOpts && " ASTUnit does not have language options");
510 const FileManager &getFileManager() const { return *FileMgr; }
511 FileManager &getFileManager() { return *FileMgr; }
513 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
515 StringRef getOriginalSourceFileName() {
516 return OriginalSourceFile;
519 ASTMutationListener *getASTMutationListener();
520 ASTDeserializationListener *getDeserializationListener();
522 /// \brief Add a temporary file that the ASTUnit depends on.
524 /// This file will be erased when the ASTUnit is destroyed.
525 void addTemporaryFile(StringRef TempFile);
527 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
529 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
530 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
532 StringRef getMainFileName() const;
534 /// \brief If this ASTUnit came from an AST file, returns the filename for it.
535 StringRef getASTFileName() const;
537 typedef std::vector<Decl *>::iterator top_level_iterator;
539 top_level_iterator top_level_begin() {
540 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
541 if (!TopLevelDeclsInPreamble.empty())
542 RealizeTopLevelDeclsFromPreamble();
543 return TopLevelDecls.begin();
546 top_level_iterator top_level_end() {
547 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
548 if (!TopLevelDeclsInPreamble.empty())
549 RealizeTopLevelDeclsFromPreamble();
550 return TopLevelDecls.end();
553 std::size_t top_level_size() const {
554 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
555 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
558 bool top_level_empty() const {
559 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
560 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
563 /// \brief Add a new top-level declaration.
564 void addTopLevelDecl(Decl *D) {
565 TopLevelDecls.push_back(D);
568 /// \brief Add a new local file-level declaration.
569 void addFileLevelDecl(Decl *D);
571 /// \brief Get the decls that are contained in a file in the Offset/Length
572 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
574 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
575 SmallVectorImpl<Decl *> &Decls);
577 /// \brief Add a new top-level declaration, identified by its ID in
578 /// the precompiled preamble.
579 void addTopLevelDeclFromPreamble(serialization::DeclID D) {
580 TopLevelDeclsInPreamble.push_back(D);
583 /// \brief Retrieve a reference to the current top-level name hash value.
585 /// Note: This is used internally by the top-level tracking action
586 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
588 /// \brief Get the source location for the given file:line:col triplet.
590 /// The difference with SourceManager::getLocation is that this method checks
591 /// whether the requested location points inside the precompiled preamble
592 /// in which case the returned source location will be a "loaded" one.
593 SourceLocation getLocation(const FileEntry *File,
594 unsigned Line, unsigned Col) const;
596 /// \brief Get the source location for the given file:offset pair.
597 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
599 /// \brief If \p Loc is a loaded location from the preamble, returns
600 /// the corresponding local location of the main file, otherwise it returns
602 SourceLocation mapLocationFromPreamble(SourceLocation Loc);
604 /// \brief If \p Loc is a local location of the main file but inside the
605 /// preamble chunk, returns the corresponding loaded location from the
606 /// preamble, otherwise it returns \p Loc.
607 SourceLocation mapLocationToPreamble(SourceLocation Loc);
609 bool isInPreambleFileID(SourceLocation Loc);
610 bool isInMainFileID(SourceLocation Loc);
611 SourceLocation getStartOfMainFileID();
612 SourceLocation getEndOfPreambleFileID();
614 /// \see mapLocationFromPreamble.
615 SourceRange mapRangeFromPreamble(SourceRange R) {
616 return SourceRange(mapLocationFromPreamble(R.getBegin()),
617 mapLocationFromPreamble(R.getEnd()));
620 /// \see mapLocationToPreamble.
621 SourceRange mapRangeToPreamble(SourceRange R) {
622 return SourceRange(mapLocationToPreamble(R.getBegin()),
623 mapLocationToPreamble(R.getEnd()));
626 // Retrieve the diagnostics associated with this AST
627 typedef StoredDiagnostic *stored_diag_iterator;
628 typedef const StoredDiagnostic *stored_diag_const_iterator;
629 stored_diag_const_iterator stored_diag_begin() const {
630 return StoredDiagnostics.begin();
632 stored_diag_iterator stored_diag_begin() {
633 return StoredDiagnostics.begin();
635 stored_diag_const_iterator stored_diag_end() const {
636 return StoredDiagnostics.end();
638 stored_diag_iterator stored_diag_end() {
639 return StoredDiagnostics.end();
641 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
643 stored_diag_iterator stored_diag_afterDriver_begin() {
644 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
645 NumStoredDiagnosticsFromDriver = 0;
646 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
649 typedef std::vector<CachedCodeCompletionResult>::iterator
650 cached_completion_iterator;
652 cached_completion_iterator cached_completion_begin() {
653 return CachedCompletionResults.begin();
656 cached_completion_iterator cached_completion_end() {
657 return CachedCompletionResults.end();
660 unsigned cached_completion_size() const {
661 return CachedCompletionResults.size();
664 /// \brief Returns an iterator range for the local preprocessing entities
665 /// of the local Preprocessor, if this is a parsed source file, or the loaded
666 /// preprocessing entities of the primary module if this is an AST file.
667 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
668 getLocalPreprocessingEntities() const;
670 /// \brief Type for a function iterating over a number of declarations.
671 /// \returns true to continue iteration and false to abort.
672 typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
674 /// \brief Iterate over local declarations (locally parsed if this is a parsed
675 /// source file or the loaded declarations of the primary module if this is an
677 /// \returns true if the iteration was complete or false if it was aborted.
678 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
680 /// \brief Get the PCH file if one was included.
681 const FileEntry *getPCHFile();
683 /// \brief Returns true if the ASTUnit was constructed from a serialized
687 llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
688 std::string *ErrorStr = nullptr);
690 /// \brief Determine what kind of translation unit this AST represents.
691 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
693 /// \brief A mapping from a file name to the memory buffer that stores the
694 /// remapped contents of that file.
695 typedef std::pair<std::string, llvm::MemoryBuffer *> RemappedFile;
697 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
698 static ASTUnit *create(CompilerInvocation *CI,
699 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
700 bool CaptureDiagnostics,
701 bool UserFilesAreVolatile);
703 /// \brief Create a ASTUnit from an AST file.
705 /// \param Filename - The AST file to load.
707 /// \param Diags - The diagnostics engine to use for reporting errors; its
708 /// lifetime is expected to extend past that of the returned ASTUnit.
710 /// \returns - The initialized ASTUnit or null if the AST failed to load.
711 static ASTUnit *LoadFromASTFile(const std::string &Filename,
712 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
713 const FileSystemOptions &FileSystemOpts,
714 bool OnlyLocalDecls = false,
715 ArrayRef<RemappedFile> RemappedFiles = None,
716 bool CaptureDiagnostics = false,
717 bool AllowPCHWithCompilerErrors = false,
718 bool UserFilesAreVolatile = false);
721 /// \brief Helper function for \c LoadFromCompilerInvocation() and
722 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
724 /// \param PrecompilePreamble Whether to precompile the preamble of this
725 /// translation unit, to improve the performance of reparsing.
727 /// \returns \c true if a catastrophic failure occurred (which means that the
728 /// \c ASTUnit itself is invalid), or \c false otherwise.
729 bool LoadFromCompilerInvocation(bool PrecompilePreamble);
733 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
734 /// object, by invoking the optionally provided ASTFrontendAction.
736 /// \param CI - The compiler invocation to use; it must have exactly one input
737 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
739 /// \param Diags - The diagnostics engine to use for reporting errors; its
740 /// lifetime is expected to extend past that of the returned ASTUnit.
742 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
745 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
748 /// \param Persistent - if true the returned ASTUnit will be complete.
749 /// false means the caller is only interested in getting info through the
750 /// provided \see Action.
752 /// \param ErrAST - If non-null and parsing failed without any AST to return
753 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
754 /// mainly to allow the caller to see the diagnostics.
755 /// This will only receive an ASTUnit if a new one was created. If an already
756 /// created ASTUnit was passed in \p Unit then the caller can check that.
758 static ASTUnit *LoadFromCompilerInvocationAction(
759 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
760 ASTFrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
761 bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
762 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
763 bool PrecompilePreamble = false, bool CacheCodeCompletionResults = false,
764 bool IncludeBriefCommentsInCodeCompletion = false,
765 bool UserFilesAreVolatile = false,
766 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
768 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
769 /// CompilerInvocation object.
771 /// \param CI - The compiler invocation to use; it must have exactly one input
772 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
774 /// \param Diags - The diagnostics engine to use for reporting errors; its
775 /// lifetime is expected to extend past that of the returned ASTUnit.
777 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
778 // shouldn't need to specify them at construction time.
779 static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
780 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
781 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
782 bool PrecompilePreamble = false, TranslationUnitKind TUKind = TU_Complete,
783 bool CacheCodeCompletionResults = false,
784 bool IncludeBriefCommentsInCodeCompletion = false,
785 bool UserFilesAreVolatile = false);
787 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
788 /// arguments, which must specify exactly one source file.
790 /// \param ArgBegin - The beginning of the argument vector.
792 /// \param ArgEnd - The end of the argument vector.
794 /// \param Diags - The diagnostics engine to use for reporting errors; its
795 /// lifetime is expected to extend past that of the returned ASTUnit.
797 /// \param ResourceFilesPath - The path to the compiler resource files.
799 /// \param ErrAST - If non-null and parsing failed without any AST to return
800 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
801 /// mainly to allow the caller to see the diagnostics.
803 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
804 // shouldn't need to specify them at construction time.
805 static ASTUnit *LoadFromCommandLine(
806 const char **ArgBegin, const char **ArgEnd,
807 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
808 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
809 ArrayRef<RemappedFile> RemappedFiles = None,
810 bool RemappedFilesKeepOriginalName = true,
811 bool PrecompilePreamble = false, TranslationUnitKind TUKind = TU_Complete,
812 bool CacheCodeCompletionResults = false,
813 bool IncludeBriefCommentsInCodeCompletion = false,
814 bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
815 bool UserFilesAreVolatile = false, bool ForSerialization = false,
816 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
818 /// \brief Reparse the source files using the same command-line options that
819 /// were originally used to produce this translation unit.
821 /// \returns True if a failure occurred that causes the ASTUnit not to
822 /// contain any translation-unit information, false otherwise.
823 bool Reparse(ArrayRef<RemappedFile> RemappedFiles = None);
825 /// \brief Perform code completion at the given file, line, and
826 /// column within this translation unit.
828 /// \param File The file in which code completion will occur.
830 /// \param Line The line at which code completion will occur.
832 /// \param Column The column at which code completion will occur.
834 /// \param IncludeMacros Whether to include macros in the code-completion
837 /// \param IncludeCodePatterns Whether to include code patterns (such as a
838 /// for loop) in the code-completion results.
840 /// \param IncludeBriefComments Whether to include brief documentation within
841 /// the set of code completions returned.
843 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
844 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
845 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
846 ArrayRef<RemappedFile> RemappedFiles,
847 bool IncludeMacros, bool IncludeCodePatterns,
848 bool IncludeBriefComments,
849 CodeCompleteConsumer &Consumer,
850 DiagnosticsEngine &Diag, LangOptions &LangOpts,
851 SourceManager &SourceMgr, FileManager &FileMgr,
852 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
853 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
855 /// \brief Save this translation unit to a file with the given name.
857 /// \returns true if there was a file error or false if the save was
859 bool Save(StringRef File);
861 /// \brief Serialize this translation unit with the given output stream.
863 /// \returns True if an error occurred, false otherwise.
864 bool serialize(raw_ostream &OS);
866 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
867 Module::NameVisibilityKind Visibility,
868 bool IsInclusionDirective) override {
869 // ASTUnit doesn't know how to load modules (not that this matters).
870 return ModuleLoadResult();
873 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
874 SourceLocation ImportLoc, bool Complain) override {}
876 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
878 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override