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 PCHContainerOperations;
56 class PCHContainerReader;
59 class ASTDeserializationListener;
61 /// \brief Utility class for loading a ASTContext from an AST file.
63 class ASTUnit : public ModuleLoader {
65 struct StandaloneFixIt {
66 std::pair<unsigned, unsigned> RemoveRange;
67 std::pair<unsigned, unsigned> InsertFromRange;
68 std::string CodeToInsert;
69 bool BeforePreviousInsertions;
72 struct StandaloneDiagnostic {
74 DiagnosticsEngine::Level Level;
78 std::vector<std::pair<unsigned, unsigned> > Ranges;
79 std::vector<StandaloneFixIt> FixIts;
83 std::shared_ptr<LangOptions> LangOpts;
84 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
85 IntrusiveRefCntPtr<FileManager> FileMgr;
86 IntrusiveRefCntPtr<SourceManager> SourceMgr;
87 std::unique_ptr<HeaderSearch> HeaderInfo;
88 IntrusiveRefCntPtr<TargetInfo> Target;
89 IntrusiveRefCntPtr<Preprocessor> PP;
90 IntrusiveRefCntPtr<ASTContext> Ctx;
91 std::shared_ptr<TargetOptions> TargetOpts;
92 IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
93 IntrusiveRefCntPtr<ASTReader> Reader;
94 bool HadModuleLoaderFatalFailure;
97 std::unique_ptr<ASTWriterData> WriterData;
99 FileSystemOptions FileSystemOpts;
101 /// \brief The AST consumer that received information about the translation
102 /// unit as it was parsed or loaded.
103 std::unique_ptr<ASTConsumer> Consumer;
105 /// \brief The semantic analysis object used to type-check the translation
107 std::unique_ptr<Sema> TheSema;
109 /// Optional owned invocation, just used to make the invocation used in
110 /// LoadFromCommandLine available.
111 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
113 // OnlyLocalDecls - when true, walking this AST should only visit declarations
114 // that come from the AST itself, not from included precompiled headers.
115 // FIXME: This is temporary; eventually, CIndex will always do this.
118 /// \brief Whether to capture any diagnostics produced.
119 bool CaptureDiagnostics;
121 /// \brief Track whether the main file was loaded from an AST or not.
124 /// \brief What kind of translation unit this AST represents.
125 TranslationUnitKind TUKind;
127 /// \brief Whether we should time each operation.
130 /// \brief Whether the ASTUnit should delete the remapped buffers.
131 bool OwnsRemappedFileBuffers;
133 /// Track the top-level decls which appeared in an ASTUnit which was loaded
134 /// from a source file.
136 // FIXME: This is just an optimization hack to avoid deserializing large parts
137 // of a PCH file when using the Index library on an ASTUnit loaded from
138 // source. In the long term we should make the Index library use efficient and
139 // more scalable search mechanisms.
140 std::vector<Decl*> TopLevelDecls;
142 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
143 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
144 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
146 /// \brief Map from FileID to the file-level declarations that it contains.
147 /// The files and decls are only local (and non-preamble) ones.
148 FileDeclsTy FileDecls;
150 /// The name of the original source file used to generate this ASTUnit.
151 std::string OriginalSourceFile;
153 /// \brief The set of diagnostics produced when creating the preamble.
154 SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
156 /// \brief The set of diagnostics produced when creating this
157 /// translation unit.
158 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
160 /// \brief The set of diagnostics produced when failing to parse, e.g. due
161 /// to failure to load the PCH.
162 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
164 /// \brief The number of stored diagnostics that come from the driver
167 /// Diagnostics that come from the driver are retained from one parse to
169 unsigned NumStoredDiagnosticsFromDriver;
171 /// \brief Counter that determines when we want to try building a
172 /// precompiled preamble.
174 /// If zero, we will never build a precompiled preamble. Otherwise,
175 /// it's treated as a counter that decrements each time we reparse
176 /// without the benefit of a precompiled preamble. When it hits 1,
177 /// we'll attempt to rebuild the precompiled header. This way, if
178 /// building the precompiled preamble fails, we won't try again for
179 /// some number of calls.
180 unsigned PreambleRebuildCounter;
184 const FileEntry *File;
185 std::vector<char> Buffer;
186 mutable unsigned NumLines;
189 PreambleData() : File(nullptr), NumLines(0) { }
191 void assign(const FileEntry *F, const char *begin, const char *end) {
193 Buffer.assign(begin, end);
197 void clear() { Buffer.clear(); File = nullptr; NumLines = 0; }
199 size_t size() const { return Buffer.size(); }
200 bool empty() const { return Buffer.empty(); }
202 const char *getBufferStart() const { return &Buffer[0]; }
204 unsigned getNumLines() const {
211 SourceRange getSourceRange(const SourceManager &SM) const {
212 SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
213 return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
217 void countLines() const;
220 const PreambleData &getPreambleData() const {
224 /// Data used to determine if a file used in the preamble has been changed.
225 struct PreambleFileHash {
226 /// All files have size set.
229 /// Modification time is set for files that are on disk. For memory
230 /// buffers it is zero.
233 /// Memory buffers have MD5 instead of modification time. We don't
234 /// compute MD5 for on-disk files because we hope that modification time is
235 /// enough to tell if the file was changed.
236 llvm::MD5::MD5Result MD5;
238 static PreambleFileHash createForFile(off_t Size, time_t ModTime);
239 static PreambleFileHash
240 createForMemoryBuffer(const llvm::MemoryBuffer *Buffer);
242 friend bool operator==(const PreambleFileHash &LHS,
243 const PreambleFileHash &RHS);
245 friend bool operator!=(const PreambleFileHash &LHS,
246 const PreambleFileHash &RHS) {
247 return !(LHS == RHS);
252 /// \brief The contents of the preamble that has been precompiled to
254 PreambleData Preamble;
256 /// \brief Whether the preamble ends at the start of a new line.
258 /// Used to inform the lexer as to whether it's starting at the beginning of
259 /// a line after skipping the preamble.
260 bool PreambleEndsAtStartOfLine;
262 /// \brief Keeps track of the files that were used when computing the
263 /// preamble, with both their buffer size and their modification time.
265 /// If any of the files have changed from one compile to the next,
266 /// the preamble must be thrown away.
267 llvm::StringMap<PreambleFileHash> FilesInPreamble;
269 /// \brief When non-NULL, this is the buffer used to store the contents of
270 /// the main file when it has been padded for use with the precompiled
272 std::unique_ptr<llvm::MemoryBuffer> SavedMainFileBuffer;
274 /// \brief When non-NULL, this is the buffer used to store the
275 /// contents of the preamble when it has been padded to build the
276 /// precompiled preamble.
277 std::unique_ptr<llvm::MemoryBuffer> PreambleBuffer;
279 /// \brief The number of warnings that occurred while parsing the preamble.
281 /// This value will be used to restore the state of the \c DiagnosticsEngine
282 /// object when re-using the precompiled preamble. Note that only the
283 /// number of warnings matters, since we will not save the preamble
284 /// when any errors are present.
285 unsigned NumWarningsInPreamble;
287 /// \brief A list of the serialization ID numbers for each of the top-level
288 /// declarations parsed within the precompiled preamble.
289 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
291 /// \brief Whether we should be caching code-completion results.
292 bool ShouldCacheCodeCompletionResults : 1;
294 /// \brief Whether to include brief documentation within the set of code
295 /// completions cached.
296 bool IncludeBriefCommentsInCodeCompletion : 1;
298 /// \brief True if non-system source files should be treated as volatile
299 /// (likely to change while trying to use them).
300 bool UserFilesAreVolatile : 1;
302 /// \brief The language options used when we load an AST file.
303 LangOptions ASTFileLangOpts;
305 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
306 ASTUnit &AST, bool CaptureDiagnostics);
308 void TranslateStoredDiagnostics(FileManager &FileMgr,
309 SourceManager &SrcMan,
310 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
311 SmallVectorImpl<StoredDiagnostic> &Out);
313 void clearFileLevelDecls();
316 /// \brief A cached code-completion result, which may be introduced in one of
317 /// many different contexts.
318 struct CachedCodeCompletionResult {
319 /// \brief The code-completion string corresponding to this completion
321 CodeCompletionString *Completion;
323 /// \brief A bitmask that indicates which code-completion contexts should
324 /// contain this completion result.
326 /// The bits in the bitmask correspond to the values of
327 /// CodeCompleteContext::Kind. To map from a completion context kind to a
328 /// bit, shift 1 by that number of bits. Many completions can occur in
329 /// several different contexts.
330 uint64_t ShowInContexts;
332 /// \brief The priority given to this code-completion result.
335 /// \brief The libclang cursor kind corresponding to this code-completion
339 /// \brief The availability of this code-completion result.
340 CXAvailabilityKind Availability;
342 /// \brief The simplified type class for a non-macro completion result.
343 SimplifiedTypeClass TypeClass;
345 /// \brief The type of a non-macro completion result, stored as a unique
346 /// integer used by the string map of cached completion types.
348 /// This value will be zero if the type is not known, or a unique value
349 /// determined by the formatted type string. Se \c CachedCompletionTypes
350 /// for more information.
354 /// \brief Retrieve the mapping from formatted type names to unique type
356 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
357 return CachedCompletionTypes;
360 /// \brief Retrieve the allocator used to cache global code completions.
361 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
362 getCachedCompletionAllocator() {
363 return CachedCompletionAllocator;
366 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
368 CCTUInfo.reset(new CodeCompletionTUInfo(
369 new GlobalCodeCompletionAllocator));
374 /// \brief Allocator used to store cached code completions.
375 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
376 CachedCompletionAllocator;
378 std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
380 /// \brief The set of cached code-completion results.
381 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
383 /// \brief A mapping from the formatted type name to a unique number for that
384 /// type, which is used for type equality comparisons.
385 llvm::StringMap<unsigned> CachedCompletionTypes;
387 /// \brief A string hash of the top-level declaration and macro definition
388 /// names processed the last time that we reparsed the file.
390 /// This hash value is used to determine when we need to refresh the
391 /// global code-completion cache.
392 unsigned CompletionCacheTopLevelHashValue;
394 /// \brief A string hash of the top-level declaration and macro definition
395 /// names processed the last time that we reparsed the precompiled preamble.
397 /// This hash value is used to determine when we need to refresh the
398 /// global code-completion cache after a rebuild of the precompiled preamble.
399 unsigned PreambleTopLevelHashValue;
401 /// \brief The current hash value for the top-level declaration and macro
403 unsigned CurrentTopLevelHashValue;
405 /// \brief Bit used by CIndex to mark when a translation unit may be in an
406 /// inconsistent state, and is not safe to free.
407 unsigned UnsafeToFree : 1;
409 /// \brief Cache any "global" code-completion results, so that we can avoid
410 /// recomputing them with each completion.
411 void CacheCodeCompletionResults();
413 /// \brief Clear out and deallocate
414 void ClearCachedCompletionResults();
416 ASTUnit(const ASTUnit &) = delete;
417 void operator=(const ASTUnit &) = delete;
419 explicit ASTUnit(bool MainFileIsAST);
421 void CleanTemporaryFiles();
422 bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
423 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer);
425 struct ComputedPreamble {
426 llvm::MemoryBuffer *Buffer;
427 std::unique_ptr<llvm::MemoryBuffer> Owner;
429 bool PreambleEndsAtStartOfLine;
430 ComputedPreamble(llvm::MemoryBuffer *Buffer,
431 std::unique_ptr<llvm::MemoryBuffer> Owner, unsigned Size,
432 bool PreambleEndsAtStartOfLine)
433 : Buffer(Buffer), Owner(std::move(Owner)), Size(Size),
434 PreambleEndsAtStartOfLine(PreambleEndsAtStartOfLine) {}
436 ComputedPreamble ComputePreamble(CompilerInvocation &Invocation,
439 std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
440 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
441 const CompilerInvocation &PreambleInvocationIn, bool AllowRebuild = true,
442 unsigned MaxLines = 0);
443 void RealizeTopLevelDeclsFromPreamble();
445 /// \brief Transfers ownership of the objects (like SourceManager) from
446 /// \param CI to this ASTUnit.
447 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
449 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
450 /// which is not supported.
452 /// Clients should create instances of the ConcurrencyCheck class whenever
453 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
454 /// just about any usage.
455 /// Becomes a noop in release mode; only useful for debug mode checking.
456 class ConcurrencyState {
457 void *Mutex; // a llvm::sys::MutexImpl in debug;
466 ConcurrencyState ConcurrencyCheckValue;
469 class ConcurrencyCheck {
473 explicit ConcurrencyCheck(ASTUnit &Self)
476 Self.ConcurrencyCheckValue.start();
478 ~ConcurrencyCheck() {
479 Self.ConcurrencyCheckValue.finish();
482 friend class ConcurrencyCheck;
486 bool isMainFileAST() const { return MainFileIsAST; }
488 bool isUnsafeToFree() const { return UnsafeToFree; }
489 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
491 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
492 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
494 const SourceManager &getSourceManager() const { return *SourceMgr; }
495 SourceManager &getSourceManager() { return *SourceMgr; }
497 const Preprocessor &getPreprocessor() const { return *PP; }
498 Preprocessor &getPreprocessor() { return *PP; }
500 const ASTContext &getASTContext() const { return *Ctx; }
501 ASTContext &getASTContext() { return *Ctx; }
503 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
504 void setPreprocessor(Preprocessor *pp);
506 bool hasSema() const { return (bool)TheSema; }
507 Sema &getSema() const {
508 assert(TheSema && "ASTUnit does not have a Sema object!");
512 const LangOptions &getLangOpts() const {
513 assert(LangOpts && " ASTUnit does not have language options");
517 const FileManager &getFileManager() const { return *FileMgr; }
518 FileManager &getFileManager() { return *FileMgr; }
520 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
522 StringRef getOriginalSourceFileName() {
523 return OriginalSourceFile;
526 ASTMutationListener *getASTMutationListener();
527 ASTDeserializationListener *getDeserializationListener();
529 /// \brief Add a temporary file that the ASTUnit depends on.
531 /// This file will be erased when the ASTUnit is destroyed.
532 void addTemporaryFile(StringRef TempFile);
534 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
536 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
537 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
539 StringRef getMainFileName() const;
541 /// \brief If this ASTUnit came from an AST file, returns the filename for it.
542 StringRef getASTFileName() const;
544 typedef std::vector<Decl *>::iterator top_level_iterator;
546 top_level_iterator top_level_begin() {
547 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
548 if (!TopLevelDeclsInPreamble.empty())
549 RealizeTopLevelDeclsFromPreamble();
550 return TopLevelDecls.begin();
553 top_level_iterator top_level_end() {
554 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
555 if (!TopLevelDeclsInPreamble.empty())
556 RealizeTopLevelDeclsFromPreamble();
557 return TopLevelDecls.end();
560 std::size_t top_level_size() const {
561 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
562 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
565 bool top_level_empty() const {
566 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
567 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
570 /// \brief Add a new top-level declaration.
571 void addTopLevelDecl(Decl *D) {
572 TopLevelDecls.push_back(D);
575 /// \brief Add a new local file-level declaration.
576 void addFileLevelDecl(Decl *D);
578 /// \brief Get the decls that are contained in a file in the Offset/Length
579 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
581 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
582 SmallVectorImpl<Decl *> &Decls);
584 /// \brief Add a new top-level declaration, identified by its ID in
585 /// the precompiled preamble.
586 void addTopLevelDeclFromPreamble(serialization::DeclID D) {
587 TopLevelDeclsInPreamble.push_back(D);
590 /// \brief Retrieve a reference to the current top-level name hash value.
592 /// Note: This is used internally by the top-level tracking action
593 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
595 /// \brief Get the source location for the given file:line:col triplet.
597 /// The difference with SourceManager::getLocation is that this method checks
598 /// whether the requested location points inside the precompiled preamble
599 /// in which case the returned source location will be a "loaded" one.
600 SourceLocation getLocation(const FileEntry *File,
601 unsigned Line, unsigned Col) const;
603 /// \brief Get the source location for the given file:offset pair.
604 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
606 /// \brief If \p Loc is a loaded location from the preamble, returns
607 /// the corresponding local location of the main file, otherwise it returns
609 SourceLocation mapLocationFromPreamble(SourceLocation Loc);
611 /// \brief If \p Loc is a local location of the main file but inside the
612 /// preamble chunk, returns the corresponding loaded location from the
613 /// preamble, otherwise it returns \p Loc.
614 SourceLocation mapLocationToPreamble(SourceLocation Loc);
616 bool isInPreambleFileID(SourceLocation Loc);
617 bool isInMainFileID(SourceLocation Loc);
618 SourceLocation getStartOfMainFileID();
619 SourceLocation getEndOfPreambleFileID();
621 /// \see mapLocationFromPreamble.
622 SourceRange mapRangeFromPreamble(SourceRange R) {
623 return SourceRange(mapLocationFromPreamble(R.getBegin()),
624 mapLocationFromPreamble(R.getEnd()));
627 /// \see mapLocationToPreamble.
628 SourceRange mapRangeToPreamble(SourceRange R) {
629 return SourceRange(mapLocationToPreamble(R.getBegin()),
630 mapLocationToPreamble(R.getEnd()));
633 // Retrieve the diagnostics associated with this AST
634 typedef StoredDiagnostic *stored_diag_iterator;
635 typedef const StoredDiagnostic *stored_diag_const_iterator;
636 stored_diag_const_iterator stored_diag_begin() const {
637 return StoredDiagnostics.begin();
639 stored_diag_iterator stored_diag_begin() {
640 return StoredDiagnostics.begin();
642 stored_diag_const_iterator stored_diag_end() const {
643 return StoredDiagnostics.end();
645 stored_diag_iterator stored_diag_end() {
646 return StoredDiagnostics.end();
648 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
650 stored_diag_iterator stored_diag_afterDriver_begin() {
651 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
652 NumStoredDiagnosticsFromDriver = 0;
653 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
656 typedef std::vector<CachedCodeCompletionResult>::iterator
657 cached_completion_iterator;
659 cached_completion_iterator cached_completion_begin() {
660 return CachedCompletionResults.begin();
663 cached_completion_iterator cached_completion_end() {
664 return CachedCompletionResults.end();
667 unsigned cached_completion_size() const {
668 return CachedCompletionResults.size();
671 /// \brief Returns an iterator range for the local preprocessing entities
672 /// of the local Preprocessor, if this is a parsed source file, or the loaded
673 /// preprocessing entities of the primary module if this is an AST file.
674 llvm::iterator_range<PreprocessingRecord::iterator>
675 getLocalPreprocessingEntities() const;
677 /// \brief Type for a function iterating over a number of declarations.
678 /// \returns true to continue iteration and false to abort.
679 typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
681 /// \brief Iterate over local declarations (locally parsed if this is a parsed
682 /// source file or the loaded declarations of the primary module if this is an
684 /// \returns true if the iteration was complete or false if it was aborted.
685 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
687 /// \brief Get the PCH file if one was included.
688 const FileEntry *getPCHFile();
690 /// \brief Returns true if the ASTUnit was constructed from a serialized
694 std::unique_ptr<llvm::MemoryBuffer>
695 getBufferForFile(StringRef Filename, std::string *ErrorStr = nullptr);
697 /// \brief Determine what kind of translation unit this AST represents.
698 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
700 /// \brief A mapping from a file name to the memory buffer that stores the
701 /// remapped contents of that file.
702 typedef std::pair<std::string, llvm::MemoryBuffer *> RemappedFile;
704 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
705 static ASTUnit *create(CompilerInvocation *CI,
706 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
707 bool CaptureDiagnostics,
708 bool UserFilesAreVolatile);
710 /// \brief Create a ASTUnit from an AST file.
712 /// \param Filename - The AST file to load.
714 /// \param PCHContainerRdr - The PCHContainerOperations to use for loading and
715 /// creating modules.
716 /// \param Diags - The diagnostics engine to use for reporting errors; its
717 /// lifetime is expected to extend past that of the returned ASTUnit.
719 /// \returns - The initialized ASTUnit or null if the AST failed to load.
720 static std::unique_ptr<ASTUnit> LoadFromASTFile(
721 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
722 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
723 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false,
724 bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None,
725 bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
726 bool UserFilesAreVolatile = false);
729 /// \brief Helper function for \c LoadFromCompilerInvocation() and
730 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
732 /// \param PrecompilePreambleAfterNParses After how many parses the preamble
733 /// of this translation unit should be precompiled, to improve the performance
734 /// of reparsing. Set to zero to disable preambles.
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(
739 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
740 unsigned PrecompilePreambleAfterNParses);
744 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
745 /// object, by invoking the optionally provided ASTFrontendAction.
747 /// \param CI - The compiler invocation to use; it must have exactly one input
748 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
750 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
751 /// creating modules.
753 /// \param Diags - The diagnostics engine to use for reporting errors; its
754 /// lifetime is expected to extend past that of the returned ASTUnit.
756 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
759 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
762 /// \param Persistent - if true the returned ASTUnit will be complete.
763 /// false means the caller is only interested in getting info through the
764 /// provided \see Action.
766 /// \param ErrAST - If non-null and parsing failed without any AST to return
767 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
768 /// mainly to allow the caller to see the diagnostics.
769 /// This will only receive an ASTUnit if a new one was created. If an already
770 /// created ASTUnit was passed in \p Unit then the caller can check that.
772 static ASTUnit *LoadFromCompilerInvocationAction(
773 CompilerInvocation *CI,
774 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
775 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
776 FrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
777 bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
778 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
779 unsigned PrecompilePreambleAfterNParses = 0,
780 bool CacheCodeCompletionResults = false,
781 bool IncludeBriefCommentsInCodeCompletion = false,
782 bool UserFilesAreVolatile = false,
783 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
785 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
786 /// CompilerInvocation object.
788 /// \param CI - The compiler invocation to use; it must have exactly one input
789 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
791 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
792 /// creating modules.
794 /// \param Diags - The diagnostics engine to use for reporting errors; its
795 /// lifetime is expected to extend past that of the returned ASTUnit.
797 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
798 // shouldn't need to specify them at construction time.
799 static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
800 CompilerInvocation *CI,
801 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
802 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
803 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
804 unsigned PrecompilePreambleAfterNParses = 0,
805 TranslationUnitKind TUKind = TU_Complete,
806 bool CacheCodeCompletionResults = false,
807 bool IncludeBriefCommentsInCodeCompletion = false,
808 bool UserFilesAreVolatile = false);
810 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
811 /// arguments, which must specify exactly one source file.
813 /// \param ArgBegin - The beginning of the argument vector.
815 /// \param ArgEnd - The end of the argument vector.
817 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
818 /// creating modules.
820 /// \param Diags - The diagnostics engine to use for reporting errors; its
821 /// lifetime is expected to extend past that of the returned ASTUnit.
823 /// \param ResourceFilesPath - The path to the compiler resource files.
825 /// \param ModuleFormat - If provided, uses the specific module format.
827 /// \param ErrAST - If non-null and parsing failed without any AST to return
828 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
829 /// mainly to allow the caller to see the diagnostics.
831 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
832 // shouldn't need to specify them at construction time.
833 static ASTUnit *LoadFromCommandLine(
834 const char **ArgBegin, const char **ArgEnd,
835 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
836 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, StringRef ResourceFilesPath,
837 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
838 ArrayRef<RemappedFile> RemappedFiles = None,
839 bool RemappedFilesKeepOriginalName = true,
840 unsigned PrecompilePreambleAfterNParses = 0,
841 TranslationUnitKind TUKind = TU_Complete,
842 bool CacheCodeCompletionResults = false,
843 bool IncludeBriefCommentsInCodeCompletion = false,
844 bool AllowPCHWithCompilerErrors = false, bool SkipFunctionBodies = false,
845 bool UserFilesAreVolatile = false, bool ForSerialization = false,
846 llvm::Optional<StringRef> ModuleFormat = llvm::None,
847 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
849 /// \brief Reparse the source files using the same command-line options that
850 /// were originally used to produce this translation unit.
852 /// \returns True if a failure occurred that causes the ASTUnit not to
853 /// contain any translation-unit information, false otherwise.
854 bool Reparse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
855 ArrayRef<RemappedFile> RemappedFiles = None);
857 /// \brief Perform code completion at the given file, line, and
858 /// column within this translation unit.
860 /// \param File The file in which code completion will occur.
862 /// \param Line The line at which code completion will occur.
864 /// \param Column The column at which code completion will occur.
866 /// \param IncludeMacros Whether to include macros in the code-completion
869 /// \param IncludeCodePatterns Whether to include code patterns (such as a
870 /// for loop) in the code-completion results.
872 /// \param IncludeBriefComments Whether to include brief documentation within
873 /// the set of code completions returned.
875 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
876 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
877 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
878 ArrayRef<RemappedFile> RemappedFiles, bool IncludeMacros,
879 bool IncludeCodePatterns, bool IncludeBriefComments,
880 CodeCompleteConsumer &Consumer,
881 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
882 DiagnosticsEngine &Diag, LangOptions &LangOpts,
883 SourceManager &SourceMgr, FileManager &FileMgr,
884 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
885 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
887 /// \brief Save this translation unit to a file with the given name.
889 /// \returns true if there was a file error or false if the save was
891 bool Save(StringRef File);
893 /// \brief Serialize this translation unit with the given output stream.
895 /// \returns True if an error occurred, false otherwise.
896 bool serialize(raw_ostream &OS);
898 ModuleLoadResult loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
899 Module::NameVisibilityKind Visibility,
900 bool IsInclusionDirective) override {
901 // ASTUnit doesn't know how to load modules (not that this matters).
902 return ModuleLoadResult();
905 void makeModuleVisible(Module *Mod, Module::NameVisibilityKind Visibility,
906 SourceLocation ImportLoc) override {}
908 GlobalModuleIndex *loadGlobalModuleIndex(SourceLocation TriggerLoc) override
910 bool lookupMissingImports(StringRef Name, SourceLocation TriggerLoc) override