1 //===--- ASTUnit.h - ASTUnit utility ----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit utility class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H
15 #define LLVM_CLANG_FRONTEND_ASTUNIT_H
17 #include "clang-c/Index.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Basic/FileSystemOptions.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/SourceManager.h"
22 #include "clang/Basic/TargetOptions.h"
23 #include "clang/Lex/HeaderSearchOptions.h"
24 #include "clang/Lex/ModuleLoader.h"
25 #include "clang/Lex/PreprocessingRecord.h"
26 #include "clang/Sema/CodeCompleteConsumer.h"
27 #include "clang/Serialization/ASTBitCodes.h"
28 #include "llvm/ADT/IntrusiveRefCntPtr.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/Support/MD5.h"
35 #include <sys/types.h>
47 class CompilerInvocation;
48 class CompilerInstance;
50 class DiagnosticsEngine;
54 class MemoryBufferCache;
56 class PCHContainerOperations;
57 class PCHContainerReader;
60 class ASTDeserializationListener;
62 /// \brief Utility class for loading a ASTContext from an AST file.
64 class ASTUnit : public ModuleLoader {
66 struct StandaloneFixIt {
67 std::pair<unsigned, unsigned> RemoveRange;
68 std::pair<unsigned, unsigned> InsertFromRange;
69 std::string CodeToInsert;
70 bool BeforePreviousInsertions;
73 struct StandaloneDiagnostic {
75 DiagnosticsEngine::Level Level;
79 std::vector<std::pair<unsigned, unsigned> > Ranges;
80 std::vector<StandaloneFixIt> FixIts;
84 std::shared_ptr<LangOptions> LangOpts;
85 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
86 IntrusiveRefCntPtr<FileManager> FileMgr;
87 IntrusiveRefCntPtr<SourceManager> SourceMgr;
88 IntrusiveRefCntPtr<MemoryBufferCache> PCMCache;
89 std::unique_ptr<HeaderSearch> HeaderInfo;
90 IntrusiveRefCntPtr<TargetInfo> Target;
91 std::shared_ptr<Preprocessor> PP;
92 IntrusiveRefCntPtr<ASTContext> Ctx;
93 std::shared_ptr<TargetOptions> TargetOpts;
94 std::shared_ptr<HeaderSearchOptions> HSOpts;
95 IntrusiveRefCntPtr<ASTReader> Reader;
96 bool HadModuleLoaderFatalFailure;
99 std::unique_ptr<ASTWriterData> WriterData;
101 FileSystemOptions FileSystemOpts;
103 /// \brief The AST consumer that received information about the translation
104 /// unit as it was parsed or loaded.
105 std::unique_ptr<ASTConsumer> Consumer;
107 /// \brief The semantic analysis object used to type-check the translation
109 std::unique_ptr<Sema> TheSema;
111 /// Optional owned invocation, just used to make the invocation used in
112 /// LoadFromCommandLine available.
113 std::shared_ptr<CompilerInvocation> Invocation;
115 // OnlyLocalDecls - when true, walking this AST should only visit declarations
116 // that come from the AST itself, not from included precompiled headers.
117 // FIXME: This is temporary; eventually, CIndex will always do this.
120 /// \brief Whether to capture any diagnostics produced.
121 bool CaptureDiagnostics;
123 /// \brief Track whether the main file was loaded from an AST or not.
126 /// \brief What kind of translation unit this AST represents.
127 TranslationUnitKind TUKind;
129 /// \brief Whether we should time each operation.
132 /// \brief Whether the ASTUnit should delete the remapped buffers.
133 bool OwnsRemappedFileBuffers;
135 /// Track the top-level decls which appeared in an ASTUnit which was loaded
136 /// from a source file.
138 // FIXME: This is just an optimization hack to avoid deserializing large parts
139 // of a PCH file when using the Index library on an ASTUnit loaded from
140 // source. In the long term we should make the Index library use efficient and
141 // more scalable search mechanisms.
142 std::vector<Decl*> TopLevelDecls;
144 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
145 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
146 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
148 /// \brief Map from FileID to the file-level declarations that it contains.
149 /// The files and decls are only local (and non-preamble) ones.
150 FileDeclsTy FileDecls;
152 /// The name of the original source file used to generate this ASTUnit.
153 std::string OriginalSourceFile;
155 /// \brief The set of diagnostics produced when creating the preamble.
156 SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
158 /// \brief The set of diagnostics produced when creating this
159 /// translation unit.
160 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
162 /// \brief The set of diagnostics produced when failing to parse, e.g. due
163 /// to failure to load the PCH.
164 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
166 /// \brief The number of stored diagnostics that come from the driver
169 /// Diagnostics that come from the driver are retained from one parse to
171 unsigned NumStoredDiagnosticsFromDriver;
173 /// \brief Counter that determines when we want to try building a
174 /// precompiled preamble.
176 /// If zero, we will never build a precompiled preamble. Otherwise,
177 /// it's treated as a counter that decrements each time we reparse
178 /// without the benefit of a precompiled preamble. When it hits 1,
179 /// we'll attempt to rebuild the precompiled header. This way, if
180 /// building the precompiled preamble fails, we won't try again for
181 /// some number of calls.
182 unsigned PreambleRebuildCounter;
186 const FileEntry *File;
187 std::vector<char> Buffer;
188 mutable unsigned NumLines;
191 PreambleData() : File(nullptr), NumLines(0) { }
193 void assign(const FileEntry *F, const char *begin, const char *end) {
195 Buffer.assign(begin, end);
199 void clear() { Buffer.clear(); File = nullptr; NumLines = 0; }
201 size_t size() const { return Buffer.size(); }
202 bool empty() const { return Buffer.empty(); }
204 const char *getBufferStart() const { return &Buffer[0]; }
206 unsigned getNumLines() const {
213 SourceRange getSourceRange(const SourceManager &SM) const {
214 SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
215 return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
219 void countLines() const;
222 const PreambleData &getPreambleData() const {
226 /// Data used to determine if a file used in the preamble has been changed.
227 struct PreambleFileHash {
228 /// All files have size set.
231 /// Modification time is set for files that are on disk. For memory
232 /// buffers it is zero.
235 /// Memory buffers have MD5 instead of modification time. We don't
236 /// compute MD5 for on-disk files because we hope that modification time is
237 /// enough to tell if the file was changed.
238 llvm::MD5::MD5Result MD5;
240 static PreambleFileHash createForFile(off_t Size, time_t ModTime);
241 static PreambleFileHash
242 createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
244 friend bool operator==(const PreambleFileHash &LHS,
245 const PreambleFileHash &RHS);
247 friend bool operator!=(const PreambleFileHash &LHS,
248 const PreambleFileHash &RHS) {
249 return !(LHS == RHS);
254 /// \brief The contents of the preamble that has been precompiled to
256 PreambleData Preamble;
258 /// \brief Whether the preamble ends at the start of a new line.
260 /// Used to inform the lexer as to whether it's starting at the beginning of
261 /// a line after skipping the preamble.
262 bool PreambleEndsAtStartOfLine;
264 /// \brief Keeps track of the files that were used when computing the
265 /// preamble, with both their buffer size and their modification time.
267 /// If any of the files have changed from one compile to the next,
268 /// the preamble must be thrown away.
269 llvm::StringMap<PreambleFileHash> FilesInPreamble;
271 /// \brief When non-NULL, this is the buffer used to store the contents of
272 /// the main file when it has been padded for use with the precompiled
274 std::unique_ptr<llvm::MemoryBuffer> SavedMainFileBuffer;
276 /// \brief When non-NULL, this is the buffer used to store the
277 /// contents of the preamble when it has been padded to build the
278 /// precompiled preamble.
279 std::unique_ptr<llvm::MemoryBuffer> PreambleBuffer;
281 /// \brief The number of warnings that occurred while parsing the preamble.
283 /// This value will be used to restore the state of the \c DiagnosticsEngine
284 /// object when re-using the precompiled preamble. Note that only the
285 /// number of warnings matters, since we will not save the preamble
286 /// when any errors are present.
287 unsigned NumWarningsInPreamble;
289 /// \brief A list of the serialization ID numbers for each of the top-level
290 /// declarations parsed within the precompiled preamble.
291 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
293 /// \brief Whether we should be caching code-completion results.
294 bool ShouldCacheCodeCompletionResults : 1;
296 /// \brief Whether to include brief documentation within the set of code
297 /// completions cached.
298 bool IncludeBriefCommentsInCodeCompletion : 1;
300 /// \brief True if non-system source files should be treated as volatile
301 /// (likely to change while trying to use them).
302 bool UserFilesAreVolatile : 1;
304 /// \brief The language options used when we load an AST file.
305 LangOptions ASTFileLangOpts;
307 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
308 ASTUnit &AST, bool CaptureDiagnostics);
310 void TranslateStoredDiagnostics(FileManager &FileMgr,
311 SourceManager &SrcMan,
312 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
313 SmallVectorImpl<StoredDiagnostic> &Out);
315 void clearFileLevelDecls();
318 /// \brief A cached code-completion result, which may be introduced in one of
319 /// many different contexts.
320 struct CachedCodeCompletionResult {
321 /// \brief The code-completion string corresponding to this completion
323 CodeCompletionString *Completion;
325 /// \brief A bitmask that indicates which code-completion contexts should
326 /// contain this completion result.
328 /// The bits in the bitmask correspond to the values of
329 /// CodeCompleteContext::Kind. To map from a completion context kind to a
330 /// bit, shift 1 by that number of bits. Many completions can occur in
331 /// several different contexts.
332 uint64_t ShowInContexts;
334 /// \brief The priority given to this code-completion result.
337 /// \brief The libclang cursor kind corresponding to this code-completion
341 /// \brief The availability of this code-completion result.
342 CXAvailabilityKind Availability;
344 /// \brief The simplified type class for a non-macro completion result.
345 SimplifiedTypeClass TypeClass;
347 /// \brief The type of a non-macro completion result, stored as a unique
348 /// integer used by the string map of cached completion types.
350 /// This value will be zero if the type is not known, or a unique value
351 /// determined by the formatted type string. Se \c CachedCompletionTypes
352 /// for more information.
356 /// \brief Retrieve the mapping from formatted type names to unique type
358 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
359 return CachedCompletionTypes;
362 /// \brief Retrieve the allocator used to cache global code completions.
363 std::shared_ptr<GlobalCodeCompletionAllocator>
364 getCachedCompletionAllocator() {
365 return CachedCompletionAllocator;
368 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
370 CCTUInfo = llvm::make_unique<CodeCompletionTUInfo>(
371 std::make_shared<GlobalCodeCompletionAllocator>());
376 /// \brief Allocator used to store cached code completions.
377 std::shared_ptr<GlobalCodeCompletionAllocator> CachedCompletionAllocator;
379 std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
381 /// \brief The set of cached code-completion results.
382 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
384 /// \brief A mapping from the formatted type name to a unique number for that
385 /// type, which is used for type equality comparisons.
386 llvm::StringMap<unsigned> CachedCompletionTypes;
388 /// \brief A string hash of the top-level declaration and macro definition
389 /// names processed the last time that we reparsed the file.
391 /// This hash value is used to determine when we need to refresh the
392 /// global code-completion cache.
393 unsigned CompletionCacheTopLevelHashValue;
395 /// \brief A string hash of the top-level declaration and macro definition
396 /// names processed the last time that we reparsed the precompiled preamble.
398 /// This hash value is used to determine when we need to refresh the
399 /// global code-completion cache after a rebuild of the precompiled preamble.
400 unsigned PreambleTopLevelHashValue;
402 /// \brief The current hash value for the top-level declaration and macro
404 unsigned CurrentTopLevelHashValue;
406 /// \brief Bit used by CIndex to mark when a translation unit may be in an
407 /// inconsistent state, and is not safe to free.
408 unsigned UnsafeToFree : 1;
410 /// \brief Cache any "global" code-completion results, so that we can avoid
411 /// recomputing them with each completion.
412 void CacheCodeCompletionResults();
414 /// \brief Clear out and deallocate
415 void ClearCachedCompletionResults();
417 ASTUnit(const ASTUnit &) = delete;
418 void operator=(const ASTUnit &) = delete;
420 explicit ASTUnit(bool MainFileIsAST);
422 void CleanTemporaryFiles();
423 bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
424 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer);
426 struct ComputedPreamble {
427 llvm::MemoryBuffer *Buffer;
428 std::unique_ptr<llvm::MemoryBuffer> Owner;
430 bool PreambleEndsAtStartOfLine;
431 ComputedPreamble(llvm::MemoryBuffer *Buffer,
432 std::unique_ptr<llvm::MemoryBuffer> Owner, unsigned Size,
433 bool PreambleEndsAtStartOfLine)
434 : Buffer(Buffer), Owner(std::move(Owner)), Size(Size),
435 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
437 ComputedPreamble ComputePreamble(CompilerInvocation &Invocation,
440 std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
441 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
442 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild = true,
443 unsigned MaxLines = 0);
444 void RealizeTopLevelDeclsFromPreamble();
446 /// \brief Transfers ownership of the objects (like SourceManager) from
447 /// \param CI to this ASTUnit.
448 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
450 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
451 /// which is not supported.
453 /// Clients should create instances of the ConcurrencyCheck class whenever
454 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
455 /// just about any usage.
456 /// Becomes a noop in release mode; only useful for debug mode checking.
457 class ConcurrencyState {
458 void *Mutex; // a llvm::sys::MutexImpl in debug;
467 ConcurrencyState ConcurrencyCheckValue;
470 class ConcurrencyCheck {
474 explicit ConcurrencyCheck(ASTUnit &Self)
477 Self.ConcurrencyCheckValue.start();
479 ~ConcurrencyCheck() {
480 Self.ConcurrencyCheckValue.finish();
483 friend class ConcurrencyCheck;
487 bool isMainFileAST() const { return MainFileIsAST; }
489 bool isUnsafeToFree() const { return UnsafeToFree; }
490 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
492 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
493 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
495 const SourceManager &getSourceManager() const { return *SourceMgr; }
496 SourceManager &getSourceManager() { return *SourceMgr; }
498 const Preprocessor &getPreprocessor() const { return *PP; }
499 Preprocessor &getPreprocessor() { return *PP; }
500 std::shared_ptr<Preprocessor> getPreprocessorPtr() const { return PP; }
502 const ASTContext &getASTContext() const { return *Ctx; }
503 ASTContext &getASTContext() { return *Ctx; }
505 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
506 void setPreprocessor(std::shared_ptr<Preprocessor> pp);
508 bool hasSema() const { return (bool)TheSema; }
509 Sema &getSema() const {
510 assert(TheSema && "ASTUnit does not have a Sema object!");
514 const LangOptions &getLangOpts() const {
515 assert(LangOpts && " ASTUnit does not have language options");
519 const FileManager &getFileManager() const { return *FileMgr; }
520 FileManager &getFileManager() { return *FileMgr; }
522 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
524 IntrusiveRefCntPtr<ASTReader> getASTReader() const;
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 llvm::iterator_range<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 std::unique_ptr<ASTUnit>
710 create(std::shared_ptr<CompilerInvocation> CI,
711 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool CaptureDiagnostics,
712 bool UserFilesAreVolatile);
714 /// \brief Create a ASTUnit from an AST file.
716 /// \param Filename - The AST file to load.
718 /// \param PCHContainerRdr - The PCHContainerOperations to use for loading and
719 /// creating modules.
720 /// \param Diags - The diagnostics engine to use for reporting errors; its
721 /// lifetime is expected to extend past that of the returned ASTUnit.
723 /// \returns - The initialized ASTUnit or null if the AST failed to load.
724 static std::unique_ptr<ASTUnit> LoadFromASTFile(
725 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
726 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
727 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false,
728 bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None,
729 bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
730 bool UserFilesAreVolatile = false);
733 /// \brief Helper function for \c LoadFromCompilerInvocation() and
734 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
736 /// \param PrecompilePreambleAfterNParses After how many parses the preamble
737 /// of this translation unit should be precompiled, to improve the performance
738 /// of reparsing. Set to zero to disable preambles.
740 /// \returns \c true if a catastrophic failure occurred (which means that the
741 /// \c ASTUnit itself is invalid), or \c false otherwise.
742 bool LoadFromCompilerInvocation(
743 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
744 unsigned PrecompilePreambleAfterNParses);
748 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
749 /// object, by invoking the optionally provided ASTFrontendAction.
751 /// \param CI - The compiler invocation to use; it must have exactly one input
752 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
754 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
755 /// creating modules.
757 /// \param Diags - The diagnostics engine to use for reporting errors; its
758 /// lifetime is expected to extend past that of the returned ASTUnit.
760 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
763 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
766 /// \param Persistent - if true the returned ASTUnit will be complete.
767 /// false means the caller is only interested in getting info through the
768 /// provided \see Action.
770 /// \param ErrAST - If non-null and parsing failed without any AST to return
771 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
772 /// mainly to allow the caller to see the diagnostics.
773 /// This will only receive an ASTUnit if a new one was created. If an already
774 /// created ASTUnit was passed in \p Unit then the caller can check that.
776 static ASTUnit *LoadFromCompilerInvocationAction(
777 std::shared_ptr<CompilerInvocation> CI,
778 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
779 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
780 FrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
781 bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
782 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
783 unsigned PrecompilePreambleAfterNParses = 0,
784 bool CacheCodeCompletionResults = false,
785 bool IncludeBriefCommentsInCodeCompletion = false,
786 bool UserFilesAreVolatile = false,
787 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
789 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
790 /// CompilerInvocation object.
792 /// \param CI - The compiler invocation to use; it must have exactly one input
793 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
795 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
796 /// creating modules.
798 /// \param Diags - The diagnostics engine to use for reporting errors; its
799 /// lifetime is expected to extend past that of the returned ASTUnit.
801 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
802 // shouldn't need to specify them at construction time.
803 static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
804 std::shared_ptr<CompilerInvocation> CI,
805 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
806 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
807 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
808 unsigned PrecompilePreambleAfterNParses = 0,
809 TranslationUnitKind TUKind = TU_Complete,
810 bool CacheCodeCompletionResults = false,
811 bool IncludeBriefCommentsInCodeCompletion = false,
812 bool UserFilesAreVolatile = false);
814 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
815 /// arguments, which must specify exactly one source file.
817 /// \param ArgBegin - The beginning of the argument vector.
819 /// \param ArgEnd - The end of the argument vector.
821 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
822 /// creating modules.
824 /// \param Diags - The diagnostics engine to use for reporting errors; its
825 /// lifetime is expected to extend past that of the returned ASTUnit.
827 /// \param ResourceFilesPath - The path to the compiler resource files.
829 /// \param ModuleFormat - If provided, uses the specific module format.
831 /// \param ErrAST - If non-null and parsing failed without any AST to return
832 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
833 /// mainly to allow the caller to see the diagnostics.
835 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
836 // shouldn't need to specify them at construction time.
837 static ASTUnit *LoadFromCommandLine(
838 const char **ArgBegin, const char **ArgEnd,
839 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
840 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
841 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
842 ArrayRef<RemappedFile> RemappedFiles = None,
843 bool RemappedFilesKeepOriginalName = true,
844 unsigned PrecompilePreambleAfterNParses = 0,
845 TranslationUnitKind TUKind = TU_Complete,
846 bool CacheCodeCompletionResults = false,
847 bool IncludeBriefCommentsInCodeCompletion = false,
848 bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
849 bool UserFilesAreVolatile = false, bool ForSerialization = false,
850 llvm::Optional<StringRef> ModuleFormat = llvm::None,
851 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
853 /// \brief Reparse the source files using the same command-line options that
854 /// were originally used to produce this translation unit.
856 /// \returns True if a failure occurred that causes the ASTUnit not to
857 /// contain any translation-unit information, false otherwise.
858 bool Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
859 ArrayRef<RemappedFile> RemappedFiles = None);
861 /// \brief Perform code completion at the given file, line, and
862 /// column within this translation unit.
864 /// \param File The file in which code completion will occur.
866 /// \param Line The line at which code completion will occur.
868 /// \param Column The column at which code completion will occur.
870 /// \param IncludeMacros Whether to include macros in the code-completion
873 /// \param IncludeCodePatterns Whether to include code patterns (such as a
874 /// for loop) in the code-completion results.
876 /// \param IncludeBriefComments Whether to include brief documentation within
877 /// the set of code completions returned.
879 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
880 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
881 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
882 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
883 bool IncludeCodePatterns, bool IncludeBriefComments,
884 CodeCompleteConsumer &Consumer,
885 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
886 DiagnosticsEngine &Diag, LangOptions &LangOpts,
887 SourceManager &SourceMgr, FileManager &FileMgr,
888 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
889 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
891 /// \brief Save this translation unit to a file with the given name.
893 /// \returns true if there was a file error or false if the save was
895 bool Save(StringRef File);
897 /// \brief Serialize this translation unit with the given output stream.
899 /// \returns True if an error occurred, false otherwise.
900 bool serialize(raw_ostream &OS);
902 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
903 Module::NameVisibilityKind Visibility,
904 bool IsInclusionDirective) override {
905 // ASTUnit doesn't know how to load modules (not that this matters).
906 return ModuleLoadResult();
909 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
910 SourceLocation ImportLoc) override {}
912 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
914 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override