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 std::unique_ptr<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 std::unique_ptr<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 ASTUnit &AST, bool CaptureDiagnostics);
311 void TranslateStoredDiagnostics(FileManager &FileMgr,
312 SourceManager &SrcMan,
313 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
314 SmallVectorImpl<StoredDiagnostic> &Out);
316 void clearFileLevelDecls();
319 /// \brief A cached code-completion result, which may be introduced in one of
320 /// many different contexts.
321 struct CachedCodeCompletionResult {
322 /// \brief The code-completion string corresponding to this completion
324 CodeCompletionString *Completion;
326 /// \brief A bitmask that indicates which code-completion contexts should
327 /// contain this completion result.
329 /// The bits in the bitmask correspond to the values of
330 /// CodeCompleteContext::Kind. To map from a completion context kind to a
331 /// bit, shift 1 by that number of bits. Many completions can occur in
332 /// several different contexts.
333 uint64_t ShowInContexts;
335 /// \brief The priority given to this code-completion result.
338 /// \brief The libclang cursor kind corresponding to this code-completion
342 /// \brief The availability of this code-completion result.
343 CXAvailabilityKind Availability;
345 /// \brief The simplified type class for a non-macro completion result.
346 SimplifiedTypeClass TypeClass;
348 /// \brief The type of a non-macro completion result, stored as a unique
349 /// integer used by the string map of cached completion types.
351 /// This value will be zero if the type is not known, or a unique value
352 /// determined by the formatted type string. Se \c CachedCompletionTypes
353 /// for more information.
357 /// \brief Retrieve the mapping from formatted type names to unique type
359 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
360 return CachedCompletionTypes;
363 /// \brief Retrieve the allocator used to cache global code completions.
364 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
365 getCachedCompletionAllocator() {
366 return CachedCompletionAllocator;
369 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
371 CCTUInfo.reset(new CodeCompletionTUInfo(
372 new GlobalCodeCompletionAllocator));
377 /// \brief Allocator used to store cached code completions.
378 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
379 CachedCompletionAllocator;
381 std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
383 /// \brief The set of cached code-completion results.
384 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
386 /// \brief A mapping from the formatted type name to a unique number for that
387 /// type, which is used for type equality comparisons.
388 llvm::StringMap<unsigned> CachedCompletionTypes;
390 /// \brief A string hash of the top-level declaration and macro definition
391 /// names processed the last time that we reparsed the file.
393 /// This hash value is used to determine when we need to refresh the
394 /// global code-completion cache.
395 unsigned CompletionCacheTopLevelHashValue;
397 /// \brief A string hash of the top-level declaration and macro definition
398 /// names processed the last time that we reparsed the precompiled preamble.
400 /// This hash value is used to determine when we need to refresh the
401 /// global code-completion cache after a rebuild of the precompiled preamble.
402 unsigned PreambleTopLevelHashValue;
404 /// \brief The current hash value for the top-level declaration and macro
406 unsigned CurrentTopLevelHashValue;
408 /// \brief Bit used by CIndex to mark when a translation unit may be in an
409 /// inconsistent state, and is not safe to free.
410 unsigned UnsafeToFree : 1;
412 /// \brief Cache any "global" code-completion results, so that we can avoid
413 /// recomputing them with each completion.
414 void CacheCodeCompletionResults();
416 /// \brief Clear out and deallocate
417 void ClearCachedCompletionResults();
419 ASTUnit(const ASTUnit &) LLVM_DELETED_FUNCTION;
420 void operator=(const ASTUnit &) LLVM_DELETED_FUNCTION;
422 explicit ASTUnit(bool MainFileIsAST);
424 void CleanTemporaryFiles();
425 bool Parse(std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer);
427 struct ComputedPreamble {
428 llvm::MemoryBuffer *Buffer;
429 std::unique_ptr<llvm::MemoryBuffer> Owner;
431 bool PreambleEndsAtStartOfLine;
432 ComputedPreamble(llvm::MemoryBuffer *Buffer,
433 std::unique_ptr<llvm::MemoryBuffer> Owner, unsigned Size,
434 bool PreambleEndsAtStartOfLine)
435 : Buffer(Buffer), Owner(std::move(Owner)), Size(Size),
436 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
437 ComputedPreamble(ComputedPreamble &&C)
438 : Buffer(C.Buffer), Owner(std::move(C.Owner)), Size(C.Size),
439 PreambleEndsAtStartOfLine(C.PreambleEndsAtStartOfLine) {}
441 ComputedPreamble ComputePreamble(CompilerInvocation &Invocation,
444 std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
445 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild = true,
446 unsigned MaxLines = 0);
447 void RealizeTopLevelDeclsFromPreamble();
449 /// \brief Transfers ownership of the objects (like SourceManager) from
450 /// \param CI to this ASTUnit.
451 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
453 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
454 /// which is not supported.
456 /// Clients should create instances of the ConcurrencyCheck class whenever
457 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
458 /// just about any usage.
459 /// Becomes a noop in release mode; only useful for debug mode checking.
460 class ConcurrencyState {
461 void *Mutex; // a llvm::sys::MutexImpl in debug;
470 ConcurrencyState ConcurrencyCheckValue;
473 class ConcurrencyCheck {
477 explicit ConcurrencyCheck(ASTUnit &Self)
480 Self.ConcurrencyCheckValue.start();
482 ~ConcurrencyCheck() {
483 Self.ConcurrencyCheckValue.finish();
486 friend class ConcurrencyCheck;
490 bool isMainFileAST() const { return MainFileIsAST; }
492 bool isUnsafeToFree() const { return UnsafeToFree; }
493 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
495 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
496 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
498 const SourceManager &getSourceManager() const { return *SourceMgr; }
499 SourceManager &getSourceManager() { return *SourceMgr; }
501 const Preprocessor &getPreprocessor() const { return *PP; }
502 Preprocessor &getPreprocessor() { return *PP; }
504 const ASTContext &getASTContext() const { return *Ctx; }
505 ASTContext &getASTContext() { return *Ctx; }
507 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
508 void setPreprocessor(Preprocessor *pp);
510 bool hasSema() const { return (bool)TheSema; }
511 Sema &getSema() const {
512 assert(TheSema && "ASTUnit does not have a Sema object!");
516 const LangOptions &getLangOpts() const {
517 assert(LangOpts && " ASTUnit does not have language options");
521 const FileManager &getFileManager() const { return *FileMgr; }
522 FileManager &getFileManager() { return *FileMgr; }
524 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
526 StringRef getOriginalSourceFileName() {
527 return OriginalSourceFile;
530 ASTMutationListener *getASTMutationListener();
531 ASTDeserializationListener *getDeserializationListener();
533 /// \brief Add a temporary file that the ASTUnit depends on.
535 /// This file will be erased when the ASTUnit is destroyed.
536 void addTemporaryFile(StringRef TempFile);
538 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
540 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
541 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
543 StringRef getMainFileName() const;
545 /// \brief If this ASTUnit came from an AST file, returns the filename for it.
546 StringRef getASTFileName() const;
548 typedef std::vector<Decl *>::iterator top_level_iterator;
550 top_level_iterator top_level_begin() {
551 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
552 if (!TopLevelDeclsInPreamble.empty())
553 RealizeTopLevelDeclsFromPreamble();
554 return TopLevelDecls.begin();
557 top_level_iterator top_level_end() {
558 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
559 if (!TopLevelDeclsInPreamble.empty())
560 RealizeTopLevelDeclsFromPreamble();
561 return TopLevelDecls.end();
564 std::size_t top_level_size() const {
565 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
566 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
569 bool top_level_empty() const {
570 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
571 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
574 /// \brief Add a new top-level declaration.
575 void addTopLevelDecl(Decl *D) {
576 TopLevelDecls.push_back(D);
579 /// \brief Add a new local file-level declaration.
580 void addFileLevelDecl(Decl *D);
582 /// \brief Get the decls that are contained in a file in the Offset/Length
583 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
585 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
586 SmallVectorImpl<Decl *> &Decls);
588 /// \brief Add a new top-level declaration, identified by its ID in
589 /// the precompiled preamble.
590 void addTopLevelDeclFromPreamble(serialization::DeclID D) {
591 TopLevelDeclsInPreamble.push_back(D);
594 /// \brief Retrieve a reference to the current top-level name hash value.
596 /// Note: This is used internally by the top-level tracking action
597 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
599 /// \brief Get the source location for the given file:line:col triplet.
601 /// The difference with SourceManager::getLocation is that this method checks
602 /// whether the requested location points inside the precompiled preamble
603 /// in which case the returned source location will be a "loaded" one.
604 SourceLocation getLocation(const FileEntry *File,
605 unsigned Line, unsigned Col) const;
607 /// \brief Get the source location for the given file:offset pair.
608 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
610 /// \brief If \p Loc is a loaded location from the preamble, returns
611 /// the corresponding local location of the main file, otherwise it returns
613 SourceLocation mapLocationFromPreamble(SourceLocation Loc);
615 /// \brief If \p Loc is a local location of the main file but inside the
616 /// preamble chunk, returns the corresponding loaded location from the
617 /// preamble, otherwise it returns \p Loc.
618 SourceLocation mapLocationToPreamble(SourceLocation Loc);
620 bool isInPreambleFileID(SourceLocation Loc);
621 bool isInMainFileID(SourceLocation Loc);
622 SourceLocation getStartOfMainFileID();
623 SourceLocation getEndOfPreambleFileID();
625 /// \see mapLocationFromPreamble.
626 SourceRange mapRangeFromPreamble(SourceRange R) {
627 return SourceRange(mapLocationFromPreamble(R.getBegin()),
628 mapLocationFromPreamble(R.getEnd()));
631 /// \see mapLocationToPreamble.
632 SourceRange mapRangeToPreamble(SourceRange R) {
633 return SourceRange(mapLocationToPreamble(R.getBegin()),
634 mapLocationToPreamble(R.getEnd()));
637 // Retrieve the diagnostics associated with this AST
638 typedef StoredDiagnostic *stored_diag_iterator;
639 typedef const StoredDiagnostic *stored_diag_const_iterator;
640 stored_diag_const_iterator stored_diag_begin() const {
641 return StoredDiagnostics.begin();
643 stored_diag_iterator stored_diag_begin() {
644 return StoredDiagnostics.begin();
646 stored_diag_const_iterator stored_diag_end() const {
647 return StoredDiagnostics.end();
649 stored_diag_iterator stored_diag_end() {
650 return StoredDiagnostics.end();
652 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
654 stored_diag_iterator stored_diag_afterDriver_begin() {
655 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
656 NumStoredDiagnosticsFromDriver = 0;
657 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
660 typedef std::vector<CachedCodeCompletionResult>::iterator
661 cached_completion_iterator;
663 cached_completion_iterator cached_completion_begin() {
664 return CachedCompletionResults.begin();
667 cached_completion_iterator cached_completion_end() {
668 return CachedCompletionResults.end();
671 unsigned cached_completion_size() const {
672 return CachedCompletionResults.size();
675 /// \brief Returns an iterator range for the local preprocessing entities
676 /// of the local Preprocessor, if this is a parsed source file, or the loaded
677 /// preprocessing entities of the primary module if this is an AST file.
678 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
679 getLocalPreprocessingEntities() const;
681 /// \brief Type for a function iterating over a number of declarations.
682 /// \returns true to continue iteration and false to abort.
683 typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
685 /// \brief Iterate over local declarations (locally parsed if this is a parsed
686 /// source file or the loaded declarations of the primary module if this is an
688 /// \returns true if the iteration was complete or false if it was aborted.
689 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
691 /// \brief Get the PCH file if one was included.
692 const FileEntry *getPCHFile();
694 /// \brief Returns true if the ASTUnit was constructed from a serialized
698 std::unique_ptr<llvm::MemoryBuffer>
699 getBufferForFile(StringRef Filename, std::string *ErrorStr = nullptr);
701 /// \brief Determine what kind of translation unit this AST represents.
702 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
704 /// \brief A mapping from a file name to the memory buffer that stores the
705 /// remapped contents of that file.
706 typedef std::pair<std::string, llvm::MemoryBuffer *> RemappedFile;
708 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
709 static ASTUnit *create(CompilerInvocation *CI,
710 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
711 bool CaptureDiagnostics,
712 bool UserFilesAreVolatile);
714 /// \brief Create a ASTUnit from an AST file.
716 /// \param Filename - The AST file to load.
718 /// \param Diags - The diagnostics engine to use for reporting errors; its
719 /// lifetime is expected to extend past that of the returned ASTUnit.
721 /// \returns - The initialized ASTUnit or null if the AST failed to load.
722 static std::unique_ptr<ASTUnit> LoadFromASTFile(
723 const std::string &Filename, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
724 const FileSystemOptions &FileSystemOpts, bool OnlyLocalDecls = false,
725 ArrayRef<RemappedFile> RemappedFiles = None,
726 bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
727 bool UserFilesAreVolatile = false);
730 /// \brief Helper function for \c LoadFromCompilerInvocation() and
731 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
733 /// \param PrecompilePreamble Whether to precompile the preamble of this
734 /// translation unit, to improve the performance of reparsing.
736 /// \returns \c true if a catastrophic failure occurred (which means that the
737 /// \c ASTUnit itself is invalid), or \c false otherwise.
738 bool LoadFromCompilerInvocation(bool PrecompilePreamble);
742 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
743 /// object, by invoking the optionally provided ASTFrontendAction.
745 /// \param CI - The compiler invocation to use; it must have exactly one input
746 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
748 /// \param Diags - The diagnostics engine to use for reporting errors; its
749 /// lifetime is expected to extend past that of the returned ASTUnit.
751 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
754 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
757 /// \param Persistent - if true the returned ASTUnit will be complete.
758 /// false means the caller is only interested in getting info through the
759 /// provided \see Action.
761 /// \param ErrAST - If non-null and parsing failed without any AST to return
762 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
763 /// mainly to allow the caller to see the diagnostics.
764 /// This will only receive an ASTUnit if a new one was created. If an already
765 /// created ASTUnit was passed in \p Unit then the caller can check that.
767 static ASTUnit *LoadFromCompilerInvocationAction(
768 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
769 ASTFrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
770 bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
771 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
772 bool PrecompilePreamble = false, bool CacheCodeCompletionResults = false,
773 bool IncludeBriefCommentsInCodeCompletion = false,
774 bool UserFilesAreVolatile = false,
775 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
777 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
778 /// CompilerInvocation object.
780 /// \param CI - The compiler invocation to use; it must have exactly one input
781 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
783 /// \param Diags - The diagnostics engine to use for reporting errors; its
784 /// lifetime is expected to extend past that of the returned ASTUnit.
786 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
787 // shouldn't need to specify them at construction time.
788 static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
789 CompilerInvocation *CI, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
790 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
791 bool PrecompilePreamble = false, TranslationUnitKind TUKind = TU_Complete,
792 bool CacheCodeCompletionResults = false,
793 bool IncludeBriefCommentsInCodeCompletion = false,
794 bool UserFilesAreVolatile = false);
796 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
797 /// arguments, which must specify exactly one source file.
799 /// \param ArgBegin - The beginning of the argument vector.
801 /// \param ArgEnd - The end of the argument vector.
803 /// \param Diags - The diagnostics engine to use for reporting errors; its
804 /// lifetime is expected to extend past that of the returned ASTUnit.
806 /// \param ResourceFilesPath - The path to the compiler resource files.
808 /// \param ErrAST - If non-null and parsing failed without any AST to return
809 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
810 /// mainly to allow the caller to see the diagnostics.
812 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
813 // shouldn't need to specify them at construction time.
814 static ASTUnit *LoadFromCommandLine(
815 const char **ArgBegin, const char **ArgEnd,
816 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
817 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
818 ArrayRef<RemappedFile> RemappedFiles = None,
819 bool RemappedFilesKeepOriginalName = true,
820 bool PrecompilePreamble = false, TranslationUnitKind TUKind = TU_Complete,
821 bool CacheCodeCompletionResults = false,
822 bool IncludeBriefCommentsInCodeCompletion = false,
823 bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
824 bool UserFilesAreVolatile = false, bool ForSerialization = false,
825 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
827 /// \brief Reparse the source files using the same command-line options that
828 /// were originally used to produce this translation unit.
830 /// \returns True if a failure occurred that causes the ASTUnit not to
831 /// contain any translation-unit information, false otherwise.
832 bool Reparse(ArrayRef<RemappedFile> RemappedFiles = None);
834 /// \brief Perform code completion at the given file, line, and
835 /// column within this translation unit.
837 /// \param File The file in which code completion will occur.
839 /// \param Line The line at which code completion will occur.
841 /// \param Column The column at which code completion will occur.
843 /// \param IncludeMacros Whether to include macros in the code-completion
846 /// \param IncludeCodePatterns Whether to include code patterns (such as a
847 /// for loop) in the code-completion results.
849 /// \param IncludeBriefComments Whether to include brief documentation within
850 /// the set of code completions returned.
852 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
853 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
854 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
855 ArrayRef<RemappedFile> RemappedFiles,
856 bool IncludeMacros, bool IncludeCodePatterns,
857 bool IncludeBriefComments,
858 CodeCompleteConsumer &Consumer,
859 DiagnosticsEngine &Diag, LangOptions &LangOpts,
860 SourceManager &SourceMgr, FileManager &FileMgr,
861 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
862 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
864 /// \brief Save this translation unit to a file with the given name.
866 /// \returns true if there was a file error or false if the save was
868 bool Save(StringRef File);
870 /// \brief Serialize this translation unit with the given output stream.
872 /// \returns True if an error occurred, false otherwise.
873 bool serialize(raw_ostream &OS);
875 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
876 Module::NameVisibilityKind Visibility,
877 bool IsInclusionDirective) override {
878 // ASTUnit doesn't know how to load modules (not that this matters).
879 return ModuleLoadResult();
882 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
883 SourceLocation ImportLoc, bool Complain) override {}
885 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
887 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override