1 //===--- ASTUnit.h - ASTUnit utility ----------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit utility class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H
15 #define LLVM_CLANG_FRONTEND_ASTUNIT_H
17 #include "clang-c/Index.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Basic/FileManager.h"
20 #include "clang/Basic/FileSystemOptions.h"
21 #include "clang/Basic/LangOptions.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "clang/Lex/HeaderSearchOptions.h"
25 #include "clang/Lex/ModuleLoader.h"
26 #include "clang/Lex/PreprocessingRecord.h"
27 #include "clang/Sema/CodeCompleteConsumer.h"
28 #include "clang/Serialization/ASTBitCodes.h"
29 #include "llvm/ADT/IntrusiveRefCntPtr.h"
30 #include "llvm/ADT/OwningPtr.h"
31 #include "llvm/ADT/SmallVector.h"
32 #include "llvm/ADT/StringMap.h"
33 #include "llvm/Support/Path.h"
37 #include <sys/types.h>
49 class CodeCompleteConsumer;
50 class CompilerInvocation;
51 class CompilerInstance;
53 class DiagnosticsEngine;
60 class ASTFrontendAction;
61 class ASTDeserializationListener;
63 /// \brief Utility class for loading a ASTContext from an AST file.
65 class ASTUnit : public ModuleLoader {
67 IntrusiveRefCntPtr<LangOptions> LangOpts;
68 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
69 IntrusiveRefCntPtr<FileManager> FileMgr;
70 IntrusiveRefCntPtr<SourceManager> SourceMgr;
71 OwningPtr<HeaderSearch> HeaderInfo;
72 IntrusiveRefCntPtr<TargetInfo> Target;
73 IntrusiveRefCntPtr<Preprocessor> PP;
74 IntrusiveRefCntPtr<ASTContext> Ctx;
75 IntrusiveRefCntPtr<TargetOptions> TargetOpts;
76 IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
78 bool HadModuleLoaderFatalFailure;
81 OwningPtr<ASTWriterData> WriterData;
83 FileSystemOptions FileSystemOpts;
85 /// \brief The AST consumer that received information about the translation
86 /// unit as it was parsed or loaded.
87 OwningPtr<ASTConsumer> Consumer;
89 /// \brief The semantic analysis object used to type-check the translation
91 OwningPtr<Sema> TheSema;
93 /// Optional owned invocation, just used to make the invocation used in
94 /// LoadFromCommandLine available.
95 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
97 // OnlyLocalDecls - when true, walking this AST should only visit declarations
98 // that come from the AST itself, not from included precompiled headers.
99 // FIXME: This is temporary; eventually, CIndex will always do this.
102 /// \brief Whether to capture any diagnostics produced.
103 bool CaptureDiagnostics;
105 /// \brief Track whether the main file was loaded from an AST or not.
108 /// \brief What kind of translation unit this AST represents.
109 TranslationUnitKind TUKind;
111 /// \brief Whether we should time each operation.
114 /// \brief Whether the ASTUnit should delete the remapped buffers.
115 bool OwnsRemappedFileBuffers;
117 /// Track the top-level decls which appeared in an ASTUnit which was loaded
118 /// from a source file.
120 // FIXME: This is just an optimization hack to avoid deserializing large parts
121 // of a PCH file when using the Index library on an ASTUnit loaded from
122 // source. In the long term we should make the Index library use efficient and
123 // more scalable search mechanisms.
124 std::vector<Decl*> TopLevelDecls;
126 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
127 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
128 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
130 /// \brief Map from FileID to the file-level declarations that it contains.
131 /// The files and decls are only local (and non-preamble) ones.
132 FileDeclsTy FileDecls;
134 /// The name of the original source file used to generate this ASTUnit.
135 std::string OriginalSourceFile;
137 /// \brief The set of diagnostics produced when creating the preamble.
138 SmallVector<StoredDiagnostic, 4> PreambleDiagnostics;
140 /// \brief The set of diagnostics produced when creating this
141 /// translation unit.
142 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
144 /// \brief The set of diagnostics produced when failing to parse, e.g. due
145 /// to failure to load the PCH.
146 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
148 /// \brief The number of stored diagnostics that come from the driver
151 /// Diagnostics that come from the driver are retained from one parse to
153 unsigned NumStoredDiagnosticsFromDriver;
155 /// \brief Counter that determines when we want to try building a
156 /// precompiled preamble.
158 /// If zero, we will never build a precompiled preamble. Otherwise,
159 /// it's treated as a counter that decrements each time we reparse
160 /// without the benefit of a precompiled preamble. When it hits 1,
161 /// we'll attempt to rebuild the precompiled header. This way, if
162 /// building the precompiled preamble fails, we won't try again for
163 /// some number of calls.
164 unsigned PreambleRebuildCounter;
168 const FileEntry *File;
169 std::vector<char> Buffer;
170 mutable unsigned NumLines;
173 PreambleData() : File(0), NumLines(0) { }
175 void assign(const FileEntry *F, const char *begin, const char *end) {
177 Buffer.assign(begin, end);
181 void clear() { Buffer.clear(); File = 0; NumLines = 0; }
183 size_t size() const { return Buffer.size(); }
184 bool empty() const { return Buffer.empty(); }
186 const char *getBufferStart() const { return &Buffer[0]; }
188 unsigned getNumLines() const {
195 SourceRange getSourceRange(const SourceManager &SM) const {
196 SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
197 return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
201 void countLines() const;
204 const PreambleData &getPreambleData() const {
210 /// \brief The contents of the preamble that has been precompiled to
212 PreambleData Preamble;
214 /// \brief Whether the preamble ends at the start of a new line.
216 /// Used to inform the lexer as to whether it's starting at the beginning of
217 /// a line after skipping the preamble.
218 bool PreambleEndsAtStartOfLine;
220 /// \brief The size of the source buffer that we've reserved for the main
221 /// file within the precompiled preamble.
222 unsigned PreambleReservedSize;
224 /// \brief Keeps track of the files that were used when computing the
225 /// preamble, with both their buffer size and their modification time.
227 /// If any of the files have changed from one compile to the next,
228 /// the preamble must be thrown away.
229 llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble;
231 /// \brief When non-NULL, this is the buffer used to store the contents of
232 /// the main file when it has been padded for use with the precompiled
234 llvm::MemoryBuffer *SavedMainFileBuffer;
236 /// \brief When non-NULL, this is the buffer used to store the
237 /// contents of the preamble when it has been padded to build the
238 /// precompiled preamble.
239 llvm::MemoryBuffer *PreambleBuffer;
241 /// \brief The number of warnings that occurred while parsing the preamble.
243 /// This value will be used to restore the state of the \c DiagnosticsEngine
244 /// object when re-using the precompiled preamble. Note that only the
245 /// number of warnings matters, since we will not save the preamble
246 /// when any errors are present.
247 unsigned NumWarningsInPreamble;
249 /// \brief A list of the serialization ID numbers for each of the top-level
250 /// declarations parsed within the precompiled preamble.
251 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
253 /// \brief Whether we should be caching code-completion results.
254 bool ShouldCacheCodeCompletionResults : 1;
256 /// \brief Whether to include brief documentation within the set of code
257 /// completions cached.
258 bool IncludeBriefCommentsInCodeCompletion : 1;
260 /// \brief True if non-system source files should be treated as volatile
261 /// (likely to change while trying to use them).
262 bool UserFilesAreVolatile : 1;
264 /// \brief The language options used when we load an AST file.
265 LangOptions ASTFileLangOpts;
267 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
268 const char **ArgBegin, const char **ArgEnd,
269 ASTUnit &AST, bool CaptureDiagnostics);
271 void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
272 SourceManager &SrcMan,
273 const SmallVectorImpl<StoredDiagnostic> &Diags,
274 SmallVectorImpl<StoredDiagnostic> &Out);
276 void clearFileLevelDecls();
279 /// \brief A cached code-completion result, which may be introduced in one of
280 /// many different contexts.
281 struct CachedCodeCompletionResult {
282 /// \brief The code-completion string corresponding to this completion
284 CodeCompletionString *Completion;
286 /// \brief A bitmask that indicates which code-completion contexts should
287 /// contain this completion result.
289 /// The bits in the bitmask correspond to the values of
290 /// CodeCompleteContext::Kind. To map from a completion context kind to a
291 /// bit, shift 1 by that number of bits. Many completions can occur in
292 /// several different contexts.
293 uint64_t ShowInContexts;
295 /// \brief The priority given to this code-completion result.
298 /// \brief The libclang cursor kind corresponding to this code-completion
302 /// \brief The availability of this code-completion result.
303 CXAvailabilityKind Availability;
305 /// \brief The simplified type class for a non-macro completion result.
306 SimplifiedTypeClass TypeClass;
308 /// \brief The type of a non-macro completion result, stored as a unique
309 /// integer used by the string map of cached completion types.
311 /// This value will be zero if the type is not known, or a unique value
312 /// determined by the formatted type string. Se \c CachedCompletionTypes
313 /// for more information.
317 /// \brief Retrieve the mapping from formatted type names to unique type
319 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
320 return CachedCompletionTypes;
323 /// \brief Retrieve the allocator used to cache global code completions.
324 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
325 getCachedCompletionAllocator() {
326 return CachedCompletionAllocator;
329 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
331 CCTUInfo.reset(new CodeCompletionTUInfo(
332 new GlobalCodeCompletionAllocator));
337 /// \brief Allocator used to store cached code completions.
338 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
339 CachedCompletionAllocator;
341 OwningPtr<CodeCompletionTUInfo> CCTUInfo;
343 /// \brief The set of cached code-completion results.
344 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
346 /// \brief A mapping from the formatted type name to a unique number for that
347 /// type, which is used for type equality comparisons.
348 llvm::StringMap<unsigned> CachedCompletionTypes;
350 /// \brief A string hash of the top-level declaration and macro definition
351 /// names processed the last time that we reparsed the file.
353 /// This hash value is used to determine when we need to refresh the
354 /// global code-completion cache.
355 unsigned CompletionCacheTopLevelHashValue;
357 /// \brief A string hash of the top-level declaration and macro definition
358 /// names processed the last time that we reparsed the precompiled preamble.
360 /// This hash value is used to determine when we need to refresh the
361 /// global code-completion cache after a rebuild of the precompiled preamble.
362 unsigned PreambleTopLevelHashValue;
364 /// \brief The current hash value for the top-level declaration and macro
366 unsigned CurrentTopLevelHashValue;
368 /// \brief Bit used by CIndex to mark when a translation unit may be in an
369 /// inconsistent state, and is not safe to free.
370 unsigned UnsafeToFree : 1;
372 /// \brief Cache any "global" code-completion results, so that we can avoid
373 /// recomputing them with each completion.
374 void CacheCodeCompletionResults();
376 /// \brief Clear out and deallocate
377 void ClearCachedCompletionResults();
379 ASTUnit(const ASTUnit &) LLVM_DELETED_FUNCTION;
380 void operator=(const ASTUnit &) LLVM_DELETED_FUNCTION;
382 explicit ASTUnit(bool MainFileIsAST);
384 void CleanTemporaryFiles();
385 bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
387 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
388 ComputePreamble(CompilerInvocation &Invocation,
389 unsigned MaxLines, bool &CreatedBuffer);
391 llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
392 const CompilerInvocation &PreambleInvocationIn,
393 bool AllowRebuild = true,
394 unsigned MaxLines = 0);
395 void RealizeTopLevelDeclsFromPreamble();
397 /// \brief Transfers ownership of the objects (like SourceManager) from
398 /// \param CI to this ASTUnit.
399 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
401 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
402 /// which is not supported.
404 /// Clients should create instances of the ConcurrencyCheck class whenever
405 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
406 /// just about any usage.
407 /// Becomes a noop in release mode; only useful for debug mode checking.
408 class ConcurrencyState {
410 void *Mutex; // a llvm::sys::MutexImpl in debug;
420 ConcurrencyState ConcurrencyCheckValue;
423 class ConcurrencyCheck {
427 explicit ConcurrencyCheck(ASTUnit &Self)
430 Self.ConcurrencyCheckValue.start();
432 ~ConcurrencyCheck() {
433 Self.ConcurrencyCheckValue.finish();
436 friend class ConcurrencyCheck;
440 bool isMainFileAST() const { return MainFileIsAST; }
442 bool isUnsafeToFree() const { return UnsafeToFree; }
443 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
445 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
446 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
448 const SourceManager &getSourceManager() const { return *SourceMgr; }
449 SourceManager &getSourceManager() { return *SourceMgr; }
451 const Preprocessor &getPreprocessor() const { return *PP; }
452 Preprocessor &getPreprocessor() { return *PP; }
454 const ASTContext &getASTContext() const { return *Ctx; }
455 ASTContext &getASTContext() { return *Ctx; }
457 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
458 void setPreprocessor(Preprocessor *pp);
460 bool hasSema() const { return TheSema.isValid(); }
461 Sema &getSema() const {
462 assert(TheSema && "ASTUnit does not have a Sema object!");
466 const FileManager &getFileManager() const { return *FileMgr; }
467 FileManager &getFileManager() { return *FileMgr; }
469 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
471 StringRef getOriginalSourceFileName() {
472 return OriginalSourceFile;
475 ASTMutationListener *getASTMutationListener();
476 ASTDeserializationListener *getDeserializationListener();
478 /// \brief Add a temporary file that the ASTUnit depends on.
480 /// This file will be erased when the ASTUnit is destroyed.
481 void addTemporaryFile(StringRef TempFile);
483 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
485 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
486 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
488 StringRef getMainFileName() const;
490 /// \brief If this ASTUnit came from an AST file, returns the filename for it.
491 StringRef getASTFileName() const;
493 typedef std::vector<Decl *>::iterator top_level_iterator;
495 top_level_iterator top_level_begin() {
496 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
497 if (!TopLevelDeclsInPreamble.empty())
498 RealizeTopLevelDeclsFromPreamble();
499 return TopLevelDecls.begin();
502 top_level_iterator top_level_end() {
503 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
504 if (!TopLevelDeclsInPreamble.empty())
505 RealizeTopLevelDeclsFromPreamble();
506 return TopLevelDecls.end();
509 std::size_t top_level_size() const {
510 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
511 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
514 bool top_level_empty() const {
515 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
516 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
519 /// \brief Add a new top-level declaration.
520 void addTopLevelDecl(Decl *D) {
521 TopLevelDecls.push_back(D);
524 /// \brief Add a new local file-level declaration.
525 void addFileLevelDecl(Decl *D);
527 /// \brief Get the decls that are contained in a file in the Offset/Length
528 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
530 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
531 SmallVectorImpl<Decl *> &Decls);
533 /// \brief Add a new top-level declaration, identified by its ID in
534 /// the precompiled preamble.
535 void addTopLevelDeclFromPreamble(serialization::DeclID D) {
536 TopLevelDeclsInPreamble.push_back(D);
539 /// \brief Retrieve a reference to the current top-level name hash value.
541 /// Note: This is used internally by the top-level tracking action
542 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
544 /// \brief Get the source location for the given file:line:col triplet.
546 /// The difference with SourceManager::getLocation is that this method checks
547 /// whether the requested location points inside the precompiled preamble
548 /// in which case the returned source location will be a "loaded" one.
549 SourceLocation getLocation(const FileEntry *File,
550 unsigned Line, unsigned Col) const;
552 /// \brief Get the source location for the given file:offset pair.
553 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
555 /// \brief If \p Loc is a loaded location from the preamble, returns
556 /// the corresponding local location of the main file, otherwise it returns
558 SourceLocation mapLocationFromPreamble(SourceLocation Loc);
560 /// \brief If \p Loc is a local location of the main file but inside the
561 /// preamble chunk, returns the corresponding loaded location from the
562 /// preamble, otherwise it returns \p Loc.
563 SourceLocation mapLocationToPreamble(SourceLocation Loc);
565 bool isInPreambleFileID(SourceLocation Loc);
566 bool isInMainFileID(SourceLocation Loc);
567 SourceLocation getStartOfMainFileID();
568 SourceLocation getEndOfPreambleFileID();
570 /// \see mapLocationFromPreamble.
571 SourceRange mapRangeFromPreamble(SourceRange R) {
572 return SourceRange(mapLocationFromPreamble(R.getBegin()),
573 mapLocationFromPreamble(R.getEnd()));
576 /// \see mapLocationToPreamble.
577 SourceRange mapRangeToPreamble(SourceRange R) {
578 return SourceRange(mapLocationToPreamble(R.getBegin()),
579 mapLocationToPreamble(R.getEnd()));
582 // Retrieve the diagnostics associated with this AST
583 typedef StoredDiagnostic *stored_diag_iterator;
584 typedef const StoredDiagnostic *stored_diag_const_iterator;
585 stored_diag_const_iterator stored_diag_begin() const {
586 return StoredDiagnostics.begin();
588 stored_diag_iterator stored_diag_begin() {
589 return StoredDiagnostics.begin();
591 stored_diag_const_iterator stored_diag_end() const {
592 return StoredDiagnostics.end();
594 stored_diag_iterator stored_diag_end() {
595 return StoredDiagnostics.end();
597 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
599 stored_diag_iterator stored_diag_afterDriver_begin() {
600 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
601 NumStoredDiagnosticsFromDriver = 0;
602 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
605 typedef std::vector<CachedCodeCompletionResult>::iterator
606 cached_completion_iterator;
608 cached_completion_iterator cached_completion_begin() {
609 return CachedCompletionResults.begin();
612 cached_completion_iterator cached_completion_end() {
613 return CachedCompletionResults.end();
616 unsigned cached_completion_size() const {
617 return CachedCompletionResults.size();
620 /// \brief Returns an iterator range for the local preprocessing entities
621 /// of the local Preprocessor, if this is a parsed source file, or the loaded
622 /// preprocessing entities of the primary module if this is an AST file.
623 std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
624 getLocalPreprocessingEntities() const;
626 /// \brief Type for a function iterating over a number of declarations.
627 /// \returns true to continue iteration and false to abort.
628 typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
630 /// \brief Iterate over local declarations (locally parsed if this is a parsed
631 /// source file or the loaded declarations of the primary module if this is an
633 /// \returns true if the iteration was complete or false if it was aborted.
634 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
636 /// \brief Get the PCH file if one was included.
637 const FileEntry *getPCHFile();
639 /// \brief Returns true if the ASTUnit was constructed from a serialized
643 llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
644 std::string *ErrorStr = 0);
646 /// \brief Determine what kind of translation unit this AST represents.
647 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
649 typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
651 /// \brief A mapping from a file name to the memory buffer that stores the
652 /// remapped contents of that file.
653 typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
655 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
656 static ASTUnit *create(CompilerInvocation *CI,
657 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
658 bool CaptureDiagnostics,
659 bool UserFilesAreVolatile);
661 /// \brief Create a ASTUnit from an AST file.
663 /// \param Filename - The AST file to load.
665 /// \param Diags - The diagnostics engine to use for reporting errors; its
666 /// lifetime is expected to extend past that of the returned ASTUnit.
668 /// \returns - The initialized ASTUnit or null if the AST failed to load.
669 static ASTUnit *LoadFromASTFile(const std::string &Filename,
670 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
671 const FileSystemOptions &FileSystemOpts,
672 bool OnlyLocalDecls = false,
673 RemappedFile *RemappedFiles = 0,
674 unsigned NumRemappedFiles = 0,
675 bool CaptureDiagnostics = false,
676 bool AllowPCHWithCompilerErrors = false,
677 bool UserFilesAreVolatile = false);
680 /// \brief Helper function for \c LoadFromCompilerInvocation() and
681 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
683 /// \param PrecompilePreamble Whether to precompile the preamble of this
684 /// translation unit, to improve the performance of reparsing.
686 /// \returns \c true if a catastrophic failure occurred (which means that the
687 /// \c ASTUnit itself is invalid), or \c false otherwise.
688 bool LoadFromCompilerInvocation(bool PrecompilePreamble);
692 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
693 /// object, by invoking the optionally provided ASTFrontendAction.
695 /// \param CI - The compiler invocation to use; it must have exactly one input
696 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
698 /// \param Diags - The diagnostics engine to use for reporting errors; its
699 /// lifetime is expected to extend past that of the returned ASTUnit.
701 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
704 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
707 /// \param Persistent - if true the returned ASTUnit will be complete.
708 /// false means the caller is only interested in getting info through the
709 /// provided \see Action.
711 /// \param ErrAST - If non-null and parsing failed without any AST to return
712 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
713 /// mainly to allow the caller to see the diagnostics.
714 /// This will only receive an ASTUnit if a new one was created. If an already
715 /// created ASTUnit was passed in \p Unit then the caller can check that.
717 static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
718 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
719 ASTFrontendAction *Action = 0,
721 bool Persistent = true,
722 StringRef ResourceFilesPath = StringRef(),
723 bool OnlyLocalDecls = false,
724 bool CaptureDiagnostics = false,
725 bool PrecompilePreamble = false,
726 bool CacheCodeCompletionResults = false,
727 bool IncludeBriefCommentsInCodeCompletion = false,
728 bool UserFilesAreVolatile = false,
729 OwningPtr<ASTUnit> *ErrAST = 0);
731 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
732 /// CompilerInvocation object.
734 /// \param CI - The compiler invocation to use; it must have exactly one input
735 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
737 /// \param Diags - The diagnostics engine to use for reporting errors; its
738 /// lifetime is expected to extend past that of the returned ASTUnit.
740 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
741 // shouldn't need to specify them at construction time.
742 static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
743 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
744 bool OnlyLocalDecls = false,
745 bool CaptureDiagnostics = false,
746 bool PrecompilePreamble = false,
747 TranslationUnitKind TUKind = TU_Complete,
748 bool CacheCodeCompletionResults = false,
749 bool IncludeBriefCommentsInCodeCompletion = false,
750 bool UserFilesAreVolatile = false);
752 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
753 /// arguments, which must specify exactly one source file.
755 /// \param ArgBegin - The beginning of the argument vector.
757 /// \param ArgEnd - The end of the argument vector.
759 /// \param Diags - The diagnostics engine to use for reporting errors; its
760 /// lifetime is expected to extend past that of the returned ASTUnit.
762 /// \param ResourceFilesPath - The path to the compiler resource files.
764 /// \param ErrAST - If non-null and parsing failed without any AST to return
765 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
766 /// mainly to allow the caller to see the diagnostics.
768 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
769 // shouldn't need to specify them at construction time.
770 static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
772 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
773 StringRef ResourceFilesPath,
774 bool OnlyLocalDecls = false,
775 bool CaptureDiagnostics = false,
776 RemappedFile *RemappedFiles = 0,
777 unsigned NumRemappedFiles = 0,
778 bool RemappedFilesKeepOriginalName = true,
779 bool PrecompilePreamble = false,
780 TranslationUnitKind TUKind = TU_Complete,
781 bool CacheCodeCompletionResults = false,
782 bool IncludeBriefCommentsInCodeCompletion = false,
783 bool AllowPCHWithCompilerErrors = false,
784 bool SkipFunctionBodies = false,
785 bool UserFilesAreVolatile = false,
786 bool ForSerialization = false,
787 OwningPtr<ASTUnit> *ErrAST = 0);
789 /// \brief Reparse the source files using the same command-line options that
790 /// were originally used to produce this translation unit.
792 /// \returns True if a failure occurred that causes the ASTUnit not to
793 /// contain any translation-unit information, false otherwise.
794 bool Reparse(RemappedFile *RemappedFiles = 0,
795 unsigned NumRemappedFiles = 0);
797 /// \brief Perform code completion at the given file, line, and
798 /// column within this translation unit.
800 /// \param File The file in which code completion will occur.
802 /// \param Line The line at which code completion will occur.
804 /// \param Column The column at which code completion will occur.
806 /// \param IncludeMacros Whether to include macros in the code-completion
809 /// \param IncludeCodePatterns Whether to include code patterns (such as a
810 /// for loop) in the code-completion results.
812 /// \param IncludeBriefComments Whether to include brief documentation within
813 /// the set of code completions returned.
815 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
816 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
817 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
818 RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
819 bool IncludeMacros, bool IncludeCodePatterns,
820 bool IncludeBriefComments,
821 CodeCompleteConsumer &Consumer,
822 DiagnosticsEngine &Diag, LangOptions &LangOpts,
823 SourceManager &SourceMgr, FileManager &FileMgr,
824 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
825 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
827 /// \brief Save this translation unit to a file with the given name.
829 /// \returns true if there was a file error or false if the save was
831 bool Save(StringRef File);
833 /// \brief Serialize this translation unit with the given output stream.
835 /// \returns True if an error occurred, false otherwise.
836 bool serialize(raw_ostream &OS);
838 virtual ModuleLoadResult loadModule(SourceLocation ImportLoc,
840 Module::NameVisibilityKind Visibility,
841 bool IsInclusionDirective) {
842 // ASTUnit doesn't know how to load modules (not that this matters).
843 return ModuleLoadResult();
846 virtual void makeModuleVisible(Module *Mod,
847 Module::NameVisibilityKind Visibility,
848 SourceLocation ImportLoc,