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;
55 class MemoryBufferCache;
57 class PreprocessorOptions;
58 class PCHContainerOperations;
59 class PCHContainerReader;
62 class ASTDeserializationListener;
68 /// \brief Utility class for loading a ASTContext from an AST file.
72 struct StandaloneFixIt {
73 std::pair<unsigned, unsigned> RemoveRange;
74 std::pair<unsigned, unsigned> InsertFromRange;
75 std::string CodeToInsert;
76 bool BeforePreviousInsertions;
79 struct StandaloneDiagnostic {
81 DiagnosticsEngine::Level Level;
85 std::vector<std::pair<unsigned, unsigned> > Ranges;
86 std::vector<StandaloneFixIt> FixIts;
90 std::shared_ptr<LangOptions> LangOpts;
91 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
92 IntrusiveRefCntPtr<FileManager> FileMgr;
93 IntrusiveRefCntPtr<SourceManager> SourceMgr;
94 IntrusiveRefCntPtr<MemoryBufferCache> PCMCache;
95 std::unique_ptr<HeaderSearch> HeaderInfo;
96 IntrusiveRefCntPtr<TargetInfo> Target;
97 std::shared_ptr<Preprocessor> PP;
98 IntrusiveRefCntPtr<ASTContext> Ctx;
99 std::shared_ptr<TargetOptions> TargetOpts;
100 std::shared_ptr<HeaderSearchOptions> HSOpts;
101 std::shared_ptr<PreprocessorOptions> PPOpts;
102 IntrusiveRefCntPtr<ASTReader> Reader;
103 bool HadModuleLoaderFatalFailure;
105 struct ASTWriterData;
106 std::unique_ptr<ASTWriterData> WriterData;
108 FileSystemOptions FileSystemOpts;
110 /// \brief The AST consumer that received information about the translation
111 /// unit as it was parsed or loaded.
112 std::unique_ptr<ASTConsumer> Consumer;
114 /// \brief The semantic analysis object used to type-check the translation
116 std::unique_ptr<Sema> TheSema;
118 /// Optional owned invocation, just used to make the invocation used in
119 /// LoadFromCommandLine available.
120 std::shared_ptr<CompilerInvocation> Invocation;
122 /// Fake module loader: the AST unit doesn't need to load any modules.
123 TrivialModuleLoader ModuleLoader;
125 // OnlyLocalDecls - when true, walking this AST should only visit declarations
126 // that come from the AST itself, not from included precompiled headers.
127 // FIXME: This is temporary; eventually, CIndex will always do this.
130 /// \brief Whether to capture any diagnostics produced.
131 bool CaptureDiagnostics;
133 /// \brief Track whether the main file was loaded from an AST or not.
136 /// \brief What kind of translation unit this AST represents.
137 TranslationUnitKind TUKind;
139 /// \brief Whether we should time each operation.
142 /// \brief Whether the ASTUnit should delete the remapped buffers.
143 bool OwnsRemappedFileBuffers;
145 /// Track the top-level decls which appeared in an ASTUnit which was loaded
146 /// from a source file.
148 // FIXME: This is just an optimization hack to avoid deserializing large parts
149 // of a PCH file when using the Index library on an ASTUnit loaded from
150 // source. In the long term we should make the Index library use efficient and
151 // more scalable search mechanisms.
152 std::vector<Decl*> TopLevelDecls;
154 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
155 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
156 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
158 /// \brief Map from FileID to the file-level declarations that it contains.
159 /// The files and decls are only local (and non-preamble) ones.
160 FileDeclsTy FileDecls;
162 /// The name of the original source file used to generate this ASTUnit.
163 std::string OriginalSourceFile;
165 /// \brief The set of diagnostics produced when creating the preamble.
166 SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
168 /// \brief The set of diagnostics produced when creating this
169 /// translation unit.
170 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
172 /// \brief The set of diagnostics produced when failing to parse, e.g. due
173 /// to failure to load the PCH.
174 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
176 /// \brief The number of stored diagnostics that come from the driver
179 /// Diagnostics that come from the driver are retained from one parse to
181 unsigned NumStoredDiagnosticsFromDriver;
183 /// \brief Counter that determines when we want to try building a
184 /// precompiled preamble.
186 /// If zero, we will never build a precompiled preamble. Otherwise,
187 /// it's treated as a counter that decrements each time we reparse
188 /// without the benefit of a precompiled preamble. When it hits 1,
189 /// we'll attempt to rebuild the precompiled header. This way, if
190 /// building the precompiled preamble fails, we won't try again for
191 /// some number of calls.
192 unsigned PreambleRebuildCounter;
194 /// \brief Cache pairs "filename - source location"
196 /// Cache contains only source locations from preamble so it is
197 /// guaranteed that they stay valid when the SourceManager is recreated.
198 /// This cache is used when loading preambule to increase performance
199 /// of that loading. It must be cleared when preamble is recreated.
200 llvm::StringMap<SourceLocation> PreambleSrcLocCache;
204 const FileEntry *File;
205 std::vector<char> Buffer;
206 mutable unsigned NumLines;
209 PreambleData() : File(nullptr), NumLines(0) { }
211 void assign(const FileEntry *F, const char *begin, const char *end) {
213 Buffer.assign(begin, end);
217 void clear() { Buffer.clear(); File = nullptr; NumLines = 0; }
219 size_t size() const { return Buffer.size(); }
220 bool empty() const { return Buffer.empty(); }
222 const char *getBufferStart() const { return &Buffer[0]; }
224 unsigned getNumLines() const {
231 SourceRange getSourceRange(const SourceManager &SM) const {
232 SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
233 return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
237 void countLines() const;
240 const PreambleData &getPreambleData() const {
244 /// Data used to determine if a file used in the preamble has been changed.
245 struct PreambleFileHash {
246 /// All files have size set.
249 /// Modification time is set for files that are on disk. For memory
250 /// buffers it is zero.
253 /// Memory buffers have MD5 instead of modification time. We don't
254 /// compute MD5 for on-disk files because we hope that modification time is
255 /// enough to tell if the file was changed.
256 llvm::MD5::MD5Result MD5;
258 static PreambleFileHash createForFile(off_t Size, time_t ModTime);
259 static PreambleFileHash
260 createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
262 friend bool operator==(const PreambleFileHash &LHS,
263 const PreambleFileHash &RHS);
265 friend bool operator!=(const PreambleFileHash &LHS,
266 const PreambleFileHash &RHS) {
267 return !(LHS == RHS);
272 /// \brief The contents of the preamble that has been precompiled to
274 PreambleData Preamble;
276 /// \brief Whether the preamble ends at the start of a new line.
278 /// Used to inform the lexer as to whether it's starting at the beginning of
279 /// a line after skipping the preamble.
280 bool PreambleEndsAtStartOfLine;
282 /// \brief Keeps track of the files that were used when computing the
283 /// preamble, with both their buffer size and their modification time.
285 /// If any of the files have changed from one compile to the next,
286 /// the preamble must be thrown away.
287 llvm::StringMap<PreambleFileHash> FilesInPreamble;
289 /// \brief When non-NULL, this is the buffer used to store the contents of
290 /// the main file when it has been padded for use with the precompiled
292 std::unique_ptr<llvm::MemoryBuffer> SavedMainFileBuffer;
294 /// \brief When non-NULL, this is the buffer used to store the
295 /// contents of the preamble when it has been padded to build the
296 /// precompiled preamble.
297 std::unique_ptr<llvm::MemoryBuffer> PreambleBuffer;
299 /// \brief The number of warnings that occurred while parsing the preamble.
301 /// This value will be used to restore the state of the \c DiagnosticsEngine
302 /// object when re-using the precompiled preamble. Note that only the
303 /// number of warnings matters, since we will not save the preamble
304 /// when any errors are present.
305 unsigned NumWarningsInPreamble;
307 /// \brief A list of the serialization ID numbers for each of the top-level
308 /// declarations parsed within the precompiled preamble.
309 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
311 /// \brief Whether we should be caching code-completion results.
312 bool ShouldCacheCodeCompletionResults : 1;
314 /// \brief Whether to include brief documentation within the set of code
315 /// completions cached.
316 bool IncludeBriefCommentsInCodeCompletion : 1;
318 /// \brief True if non-system source files should be treated as volatile
319 /// (likely to change while trying to use them).
320 bool UserFilesAreVolatile : 1;
322 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
323 ASTUnit &AST, bool CaptureDiagnostics);
325 void TranslateStoredDiagnostics(FileManager &FileMgr,
326 SourceManager &SrcMan,
327 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
328 SmallVectorImpl<StoredDiagnostic> &Out);
330 void clearFileLevelDecls();
333 /// \brief A cached code-completion result, which may be introduced in one of
334 /// many different contexts.
335 struct CachedCodeCompletionResult {
336 /// \brief The code-completion string corresponding to this completion
338 CodeCompletionString *Completion;
340 /// \brief A bitmask that indicates which code-completion contexts should
341 /// contain this completion result.
343 /// The bits in the bitmask correspond to the values of
344 /// CodeCompleteContext::Kind. To map from a completion context kind to a
345 /// bit, shift 1 by that number of bits. Many completions can occur in
346 /// several different contexts.
347 uint64_t ShowInContexts;
349 /// \brief The priority given to this code-completion result.
352 /// \brief The libclang cursor kind corresponding to this code-completion
356 /// \brief The availability of this code-completion result.
357 CXAvailabilityKind Availability;
359 /// \brief The simplified type class for a non-macro completion result.
360 SimplifiedTypeClass TypeClass;
362 /// \brief The type of a non-macro completion result, stored as a unique
363 /// integer used by the string map of cached completion types.
365 /// This value will be zero if the type is not known, or a unique value
366 /// determined by the formatted type string. Se \c CachedCompletionTypes
367 /// for more information.
371 /// \brief Retrieve the mapping from formatted type names to unique type
373 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
374 return CachedCompletionTypes;
377 /// \brief Retrieve the allocator used to cache global code completions.
378 std::shared_ptr<GlobalCodeCompletionAllocator>
379 getCachedCompletionAllocator() {
380 return CachedCompletionAllocator;
383 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
385 CCTUInfo = llvm::make_unique<CodeCompletionTUInfo>(
386 std::make_shared<GlobalCodeCompletionAllocator>());
391 /// \brief Allocator used to store cached code completions.
392 std::shared_ptr<GlobalCodeCompletionAllocator> CachedCompletionAllocator;
394 std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
396 /// \brief The set of cached code-completion results.
397 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
399 /// \brief A mapping from the formatted type name to a unique number for that
400 /// type, which is used for type equality comparisons.
401 llvm::StringMap<unsigned> CachedCompletionTypes;
403 /// \brief A string hash of the top-level declaration and macro definition
404 /// names processed the last time that we reparsed the file.
406 /// This hash value is used to determine when we need to refresh the
407 /// global code-completion cache.
408 unsigned CompletionCacheTopLevelHashValue;
410 /// \brief A string hash of the top-level declaration and macro definition
411 /// names processed the last time that we reparsed the precompiled preamble.
413 /// This hash value is used to determine when we need to refresh the
414 /// global code-completion cache after a rebuild of the precompiled preamble.
415 unsigned PreambleTopLevelHashValue;
417 /// \brief The current hash value for the top-level declaration and macro
419 unsigned CurrentTopLevelHashValue;
421 /// \brief Bit used by CIndex to mark when a translation unit may be in an
422 /// inconsistent state, and is not safe to free.
423 unsigned UnsafeToFree : 1;
425 /// \brief Cache any "global" code-completion results, so that we can avoid
426 /// recomputing them with each completion.
427 void CacheCodeCompletionResults();
429 /// \brief Clear out and deallocate
430 void ClearCachedCompletionResults();
432 ASTUnit(const ASTUnit &) = delete;
433 void operator=(const ASTUnit &) = delete;
435 explicit ASTUnit(bool MainFileIsAST);
437 bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
438 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
439 IntrusiveRefCntPtr<vfs::FileSystem> VFS);
441 struct ComputedPreamble {
442 llvm::MemoryBuffer *Buffer;
443 std::unique_ptr<llvm::MemoryBuffer> Owner;
445 bool PreambleEndsAtStartOfLine;
446 ComputedPreamble(llvm::MemoryBuffer *Buffer,
447 std::unique_ptr<llvm::MemoryBuffer> Owner, unsigned Size,
448 bool PreambleEndsAtStartOfLine)
449 : Buffer(Buffer), Owner(std::move(Owner)), Size(Size),
450 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
452 ComputedPreamble ComputePreamble(CompilerInvocation &Invocation,
454 IntrusiveRefCntPtr<vfs::FileSystem> VFS);
456 std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
457 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
458 const CompilerInvocation &PreambleInvocationIn,
459 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild = true,
460 unsigned MaxLines = 0);
461 void RealizeTopLevelDeclsFromPreamble();
463 /// \brief Transfers ownership of the objects (like SourceManager) from
464 /// \param CI to this ASTUnit.
465 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
467 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
468 /// which is not supported.
470 /// Clients should create instances of the ConcurrencyCheck class whenever
471 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
472 /// just about any usage.
473 /// Becomes a noop in release mode; only useful for debug mode checking.
474 class ConcurrencyState {
475 void *Mutex; // a llvm::sys::MutexImpl in debug;
484 ConcurrencyState ConcurrencyCheckValue;
487 class ConcurrencyCheck {
491 explicit ConcurrencyCheck(ASTUnit &Self)
494 Self.ConcurrencyCheckValue.start();
496 ~ConcurrencyCheck() {
497 Self.ConcurrencyCheckValue.finish();
500 friend class ConcurrencyCheck;
504 bool isMainFileAST() const { return MainFileIsAST; }
506 bool isUnsafeToFree() const { return UnsafeToFree; }
507 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
509 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
510 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
512 const SourceManager &getSourceManager() const { return *SourceMgr; }
513 SourceManager &getSourceManager() { return *SourceMgr; }
515 const Preprocessor &getPreprocessor() const { return *PP; }
516 Preprocessor &getPreprocessor() { return *PP; }
517 std::shared_ptr<Preprocessor> getPreprocessorPtr() const { return PP; }
519 const ASTContext &getASTContext() const { return *Ctx; }
520 ASTContext &getASTContext() { return *Ctx; }
522 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
523 void setPreprocessor(std::shared_ptr<Preprocessor> pp);
525 bool hasSema() const { return (bool)TheSema; }
526 Sema &getSema() const {
527 assert(TheSema && "ASTUnit does not have a Sema object!");
531 const LangOptions &getLangOpts() const {
532 assert(LangOpts && "ASTUnit does not have language options");
536 const HeaderSearchOptions &getHeaderSearchOpts() const {
537 assert(HSOpts && "ASTUnit does not have header search options");
541 const PreprocessorOptions &getPreprocessorOpts() const {
542 assert(PPOpts && "ASTUnit does not have preprocessor options");
546 const FileManager &getFileManager() const { return *FileMgr; }
547 FileManager &getFileManager() { return *FileMgr; }
549 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
551 IntrusiveRefCntPtr<ASTReader> getASTReader() const;
553 StringRef getOriginalSourceFileName() {
554 return OriginalSourceFile;
557 ASTMutationListener *getASTMutationListener();
558 ASTDeserializationListener *getDeserializationListener();
560 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
562 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
563 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
565 StringRef getMainFileName() const;
567 /// \brief If this ASTUnit came from an AST file, returns the filename for it.
568 StringRef getASTFileName() const;
570 typedef std::vector<Decl *>::iterator top_level_iterator;
572 top_level_iterator top_level_begin() {
573 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
574 if (!TopLevelDeclsInPreamble.empty())
575 RealizeTopLevelDeclsFromPreamble();
576 return TopLevelDecls.begin();
579 top_level_iterator top_level_end() {
580 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
581 if (!TopLevelDeclsInPreamble.empty())
582 RealizeTopLevelDeclsFromPreamble();
583 return TopLevelDecls.end();
586 std::size_t top_level_size() const {
587 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
588 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
591 bool top_level_empty() const {
592 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
593 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
596 /// \brief Add a new top-level declaration.
597 void addTopLevelDecl(Decl *D) {
598 TopLevelDecls.push_back(D);
601 /// \brief Add a new local file-level declaration.
602 void addFileLevelDecl(Decl *D);
604 /// \brief Get the decls that are contained in a file in the Offset/Length
605 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
607 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
608 SmallVectorImpl<Decl *> &Decls);
610 /// \brief Add a new top-level declaration, identified by its ID in
611 /// the precompiled preamble.
612 void addTopLevelDeclFromPreamble(serialization::DeclID D) {
613 TopLevelDeclsInPreamble.push_back(D);
616 /// \brief Retrieve a reference to the current top-level name hash value.
618 /// Note: This is used internally by the top-level tracking action
619 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
621 /// \brief Get the source location for the given file:line:col triplet.
623 /// The difference with SourceManager::getLocation is that this method checks
624 /// whether the requested location points inside the precompiled preamble
625 /// in which case the returned source location will be a "loaded" one.
626 SourceLocation getLocation(const FileEntry *File,
627 unsigned Line, unsigned Col) const;
629 /// \brief Get the source location for the given file:offset pair.
630 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
632 /// \brief If \p Loc is a loaded location from the preamble, returns
633 /// the corresponding local location of the main file, otherwise it returns
635 SourceLocation mapLocationFromPreamble(SourceLocation Loc);
637 /// \brief If \p Loc is a local location of the main file but inside the
638 /// preamble chunk, returns the corresponding loaded location from the
639 /// preamble, otherwise it returns \p Loc.
640 SourceLocation mapLocationToPreamble(SourceLocation Loc);
642 bool isInPreambleFileID(SourceLocation Loc);
643 bool isInMainFileID(SourceLocation Loc);
644 SourceLocation getStartOfMainFileID();
645 SourceLocation getEndOfPreambleFileID();
647 /// \see mapLocationFromPreamble.
648 SourceRange mapRangeFromPreamble(SourceRange R) {
649 return SourceRange(mapLocationFromPreamble(R.getBegin()),
650 mapLocationFromPreamble(R.getEnd()));
653 /// \see mapLocationToPreamble.
654 SourceRange mapRangeToPreamble(SourceRange R) {
655 return SourceRange(mapLocationToPreamble(R.getBegin()),
656 mapLocationToPreamble(R.getEnd()));
659 // Retrieve the diagnostics associated with this AST
660 typedef StoredDiagnostic *stored_diag_iterator;
661 typedef const StoredDiagnostic *stored_diag_const_iterator;
662 stored_diag_const_iterator stored_diag_begin() const {
663 return StoredDiagnostics.begin();
665 stored_diag_iterator stored_diag_begin() {
666 return StoredDiagnostics.begin();
668 stored_diag_const_iterator stored_diag_end() const {
669 return StoredDiagnostics.end();
671 stored_diag_iterator stored_diag_end() {
672 return StoredDiagnostics.end();
674 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
676 stored_diag_iterator stored_diag_afterDriver_begin() {
677 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
678 NumStoredDiagnosticsFromDriver = 0;
679 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
682 typedef std::vector<CachedCodeCompletionResult>::iterator
683 cached_completion_iterator;
685 cached_completion_iterator cached_completion_begin() {
686 return CachedCompletionResults.begin();
689 cached_completion_iterator cached_completion_end() {
690 return CachedCompletionResults.end();
693 unsigned cached_completion_size() const {
694 return CachedCompletionResults.size();
697 /// \brief Returns an iterator range for the local preprocessing entities
698 /// of the local Preprocessor, if this is a parsed source file, or the loaded
699 /// preprocessing entities of the primary module if this is an AST file.
700 llvm::iterator_range<PreprocessingRecord::iterator>
701 getLocalPreprocessingEntities() const;
703 /// \brief Type for a function iterating over a number of declarations.
704 /// \returns true to continue iteration and false to abort.
705 typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
707 /// \brief Iterate over local declarations (locally parsed if this is a parsed
708 /// source file or the loaded declarations of the primary module if this is an
710 /// \returns true if the iteration was complete or false if it was aborted.
711 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
713 /// \brief Get the PCH file if one was included.
714 const FileEntry *getPCHFile();
716 /// \brief Returns true if the ASTUnit was constructed from a serialized
720 std::unique_ptr<llvm::MemoryBuffer>
721 getBufferForFile(StringRef Filename, std::string *ErrorStr = nullptr);
723 /// \brief Determine what kind of translation unit this AST represents.
724 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
726 /// \brief Determine the input kind this AST unit represents.
727 InputKind getInputKind() const;
729 /// \brief A mapping from a file name to the memory buffer that stores the
730 /// remapped contents of that file.
731 typedef std::pair<std::string, llvm::MemoryBuffer *> RemappedFile;
733 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
734 static std::unique_ptr<ASTUnit>
735 create(std::shared_ptr<CompilerInvocation> CI,
736 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool CaptureDiagnostics,
737 bool UserFilesAreVolatile);
739 /// \brief Create a ASTUnit from an AST file.
741 /// \param Filename - The AST file to load.
743 /// \param PCHContainerRdr - The PCHContainerOperations to use for loading and
744 /// creating modules.
745 /// \param Diags - The diagnostics engine to use for reporting errors; its
746 /// lifetime is expected to extend past that of the returned ASTUnit.
748 /// \returns - The initialized ASTUnit or null if the AST failed to load.
749 static std::unique_ptr<ASTUnit> LoadFromASTFile(
750 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
751 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
752 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false,
753 bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None,
754 bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
755 bool UserFilesAreVolatile = false);
758 /// \brief Helper function for \c LoadFromCompilerInvocation() and
759 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
761 /// \param PrecompilePreambleAfterNParses After how many parses the preamble
762 /// of this translation unit should be precompiled, to improve the performance
763 /// of reparsing. Set to zero to disable preambles.
765 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
766 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
767 /// for it to be loaded correctly, VFS should have access to it(i.e., be an
768 /// overlay over RealFileSystem).
770 /// \returns \c true if a catastrophic failure occurred (which means that the
771 /// \c ASTUnit itself is invalid), or \c false otherwise.
772 bool LoadFromCompilerInvocation(
773 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
774 unsigned PrecompilePreambleAfterNParses,
775 IntrusiveRefCntPtr<vfs::FileSystem> VFS);
779 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
780 /// object, by invoking the optionally provided ASTFrontendAction.
782 /// \param CI - The compiler invocation to use; it must have exactly one input
783 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
785 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
786 /// creating modules.
788 /// \param Diags - The diagnostics engine to use for reporting errors; its
789 /// lifetime is expected to extend past that of the returned ASTUnit.
791 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
794 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
797 /// \param Persistent - if true the returned ASTUnit will be complete.
798 /// false means the caller is only interested in getting info through the
799 /// provided \see Action.
801 /// \param ErrAST - If non-null and parsing failed without any AST to return
802 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
803 /// mainly to allow the caller to see the diagnostics.
804 /// This will only receive an ASTUnit if a new one was created. If an already
805 /// created ASTUnit was passed in \p Unit then the caller can check that.
807 static ASTUnit *LoadFromCompilerInvocationAction(
808 std::shared_ptr<CompilerInvocation> CI,
809 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
810 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
811 FrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
812 bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
813 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
814 unsigned PrecompilePreambleAfterNParses = 0,
815 bool CacheCodeCompletionResults = false,
816 bool IncludeBriefCommentsInCodeCompletion = false,
817 bool UserFilesAreVolatile = false,
818 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
820 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
821 /// CompilerInvocation object.
823 /// \param CI - The compiler invocation to use; it must have exactly one input
824 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
826 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
827 /// creating modules.
829 /// \param Diags - The diagnostics engine to use for reporting errors; its
830 /// lifetime is expected to extend past that of the returned ASTUnit.
832 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
833 // shouldn't need to specify them at construction time.
834 static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
835 std::shared_ptr<CompilerInvocation> CI,
836 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
837 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
838 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
839 unsigned PrecompilePreambleAfterNParses = 0,
840 TranslationUnitKind TUKind = TU_Complete,
841 bool CacheCodeCompletionResults = false,
842 bool IncludeBriefCommentsInCodeCompletion = false,
843 bool UserFilesAreVolatile = false);
845 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
846 /// arguments, which must specify exactly one source file.
848 /// \param ArgBegin - The beginning of the argument vector.
850 /// \param ArgEnd - The end of the argument vector.
852 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
853 /// creating modules.
855 /// \param Diags - The diagnostics engine to use for reporting errors; its
856 /// lifetime is expected to extend past that of the returned ASTUnit.
858 /// \param ResourceFilesPath - The path to the compiler resource files.
860 /// \param ModuleFormat - If provided, uses the specific module format.
862 /// \param ErrAST - If non-null and parsing failed without any AST to return
863 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
864 /// mainly to allow the caller to see the diagnostics.
866 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
867 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
868 /// for it to be loaded correctly, VFS should have access to it(i.e., be an
869 /// overlay over RealFileSystem). RealFileSystem will be used if \p VFS is nullptr.
871 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
872 // shouldn't need to specify them at construction time.
873 static ASTUnit *LoadFromCommandLine(
874 const char **ArgBegin, const char **ArgEnd,
875 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
876 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
877 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
878 ArrayRef<RemappedFile> RemappedFiles = None,
879 bool RemappedFilesKeepOriginalName = true,
880 unsigned PrecompilePreambleAfterNParses = 0,
881 TranslationUnitKind TUKind = TU_Complete,
882 bool CacheCodeCompletionResults = false,
883 bool IncludeBriefCommentsInCodeCompletion = false,
884 bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
885 bool SingleFileParse = false,
886 bool UserFilesAreVolatile = false, bool ForSerialization = false,
887 llvm::Optional<StringRef> ModuleFormat = llvm::None,
888 std::unique_ptr<ASTUnit> *ErrAST = nullptr,
889 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
891 /// \brief Reparse the source files using the same command-line options that
892 /// were originally used to produce this translation unit.
894 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
895 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
896 /// for it to be loaded correctly, VFS should give an access to this(i.e. be an
897 /// overlay over RealFileSystem). FileMgr->getVirtualFileSystem() will be used if
898 /// \p VFS is nullptr.
900 /// \returns True if a failure occurred that causes the ASTUnit not to
901 /// contain any translation-unit information, false otherwise.
902 bool Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
903 ArrayRef<RemappedFile> RemappedFiles = None,
904 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
906 /// \brief Free data that will be re-generated on the next parse.
908 /// Preamble-related data is not affected.
909 void ResetForParse();
911 /// \brief Perform code completion at the given file, line, and
912 /// column within this translation unit.
914 /// \param File The file in which code completion will occur.
916 /// \param Line The line at which code completion will occur.
918 /// \param Column The column at which code completion will occur.
920 /// \param IncludeMacros Whether to include macros in the code-completion
923 /// \param IncludeCodePatterns Whether to include code patterns (such as a
924 /// for loop) in the code-completion results.
926 /// \param IncludeBriefComments Whether to include brief documentation within
927 /// the set of code completions returned.
929 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
930 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
931 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
932 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
933 bool IncludeCodePatterns, bool IncludeBriefComments,
934 CodeCompleteConsumer &Consumer,
935 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
936 DiagnosticsEngine &Diag, LangOptions &LangOpts,
937 SourceManager &SourceMgr, FileManager &FileMgr,
938 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
939 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
941 /// \brief Save this translation unit to a file with the given name.
943 /// \returns true if there was a file error or false if the save was
945 bool Save(StringRef File);
947 /// \brief Serialize this translation unit with the given output stream.
949 /// \returns True if an error occurred, false otherwise.
950 bool serialize(raw_ostream &OS);