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/Serialization/ASTBitCodes.h"
18 #include "clang/Sema/Sema.h"
19 #include "clang/Sema/CodeCompleteConsumer.h"
20 #include "clang/Lex/ModuleLoader.h"
21 #include "clang/Lex/PreprocessingRecord.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/SourceManager.h"
24 #include "clang/Basic/FileManager.h"
25 #include "clang/Basic/FileSystemOptions.h"
26 #include "clang-c/Index.h"
27 #include "llvm/ADT/IntrusiveRefCntPtr.h"
28 #include "llvm/ADT/OwningPtr.h"
29 #include "llvm/ADT/SmallVector.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/Support/Path.h"
37 #include <sys/types.h>
46 class CodeCompleteConsumer;
47 class CompilerInvocation;
48 class CompilerInstance;
50 class DiagnosticsEngine;
57 class ASTFrontendAction;
59 /// \brief Utility class for loading a ASTContext from an AST file.
61 class ASTUnit : public ModuleLoader {
63 IntrusiveRefCntPtr<LangOptions> LangOpts;
64 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
65 IntrusiveRefCntPtr<FileManager> FileMgr;
66 IntrusiveRefCntPtr<SourceManager> SourceMgr;
67 OwningPtr<HeaderSearch> HeaderInfo;
68 IntrusiveRefCntPtr<TargetInfo> Target;
69 IntrusiveRefCntPtr<Preprocessor> PP;
70 IntrusiveRefCntPtr<ASTContext> Ctx;
73 FileSystemOptions FileSystemOpts;
75 /// \brief The AST consumer that received information about the translation
76 /// unit as it was parsed or loaded.
77 OwningPtr<ASTConsumer> Consumer;
79 /// \brief The semantic analysis object used to type-check the translation
81 OwningPtr<Sema> TheSema;
83 /// Optional owned invocation, just used to make the invocation used in
84 /// LoadFromCommandLine available.
85 IntrusiveRefCntPtr<CompilerInvocation> Invocation;
87 /// \brief The set of target features.
89 /// FIXME: each time we reparse, we need to restore the set of target
90 /// features from this vector, because TargetInfo::CreateTargetInfo()
91 /// mangles the target options in place. Yuck!
92 std::vector<std::string> TargetFeatures;
94 // OnlyLocalDecls - when true, walking this AST should only visit declarations
95 // that come from the AST itself, not from included precompiled headers.
96 // FIXME: This is temporary; eventually, CIndex will always do this.
99 /// \brief Whether to capture any diagnostics produced.
100 bool CaptureDiagnostics;
102 /// \brief Track whether the main file was loaded from an AST or not.
105 /// \brief What kind of translation unit this AST represents.
106 TranslationUnitKind TUKind;
108 /// \brief Whether we should time each operation.
111 /// \brief Whether the ASTUnit should delete the remapped buffers.
112 bool OwnsRemappedFileBuffers;
114 /// Track the top-level decls which appeared in an ASTUnit which was loaded
115 /// from a source file.
117 // FIXME: This is just an optimization hack to avoid deserializing large parts
118 // of a PCH file when using the Index library on an ASTUnit loaded from
119 // source. In the long term we should make the Index library use efficient and
120 // more scalable search mechanisms.
121 std::vector<Decl*> TopLevelDecls;
123 /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
124 typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
125 typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
127 /// \brief Map from FileID to the file-level declarations that it contains.
128 /// The files and decls are only local (and non-preamble) ones.
129 FileDeclsTy FileDecls;
131 /// The name of the original source file used to generate this ASTUnit.
132 std::string OriginalSourceFile;
134 /// \brief The set of diagnostics produced when creating the preamble.
135 SmallVector<StoredDiagnostic, 4> PreambleDiagnostics;
137 /// \brief The set of diagnostics produced when creating this
138 /// translation unit.
139 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
141 /// \brief The set of diagnostics produced when failing to parse, e.g. due
142 /// to failure to load the PCH.
143 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
145 /// \brief The number of stored diagnostics that come from the driver
148 /// Diagnostics that come from the driver are retained from one parse to
150 unsigned NumStoredDiagnosticsFromDriver;
152 /// \brief Counter that determines when we want to try building a
153 /// precompiled preamble.
155 /// If zero, we will never build a precompiled preamble. Otherwise,
156 /// it's treated as a counter that decrements each time we reparse
157 /// without the benefit of a precompiled preamble. When it hits 1,
158 /// we'll attempt to rebuild the precompiled header. This way, if
159 /// building the precompiled preamble fails, we won't try again for
160 /// some number of calls.
161 unsigned PreambleRebuildCounter;
165 const FileEntry *File;
166 std::vector<char> Buffer;
167 mutable unsigned NumLines;
170 PreambleData() : File(0), NumLines(0) { }
172 void assign(const FileEntry *F, const char *begin, const char *end) {
174 Buffer.assign(begin, end);
178 void clear() { Buffer.clear(); File = 0; NumLines = 0; }
180 size_t size() const { return Buffer.size(); }
181 bool empty() const { return Buffer.empty(); }
183 const char *getBufferStart() const { return &Buffer[0]; }
185 unsigned getNumLines() const {
192 SourceRange getSourceRange(const SourceManager &SM) const {
193 SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
194 return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
198 void countLines() const;
201 const PreambleData &getPreambleData() const {
207 /// \brief The contents of the preamble that has been precompiled to
209 PreambleData Preamble;
211 /// \brief Whether the preamble ends at the start of a new line.
213 /// Used to inform the lexer as to whether it's starting at the beginning of
214 /// a line after skipping the preamble.
215 bool PreambleEndsAtStartOfLine;
217 /// \brief The size of the source buffer that we've reserved for the main
218 /// file within the precompiled preamble.
219 unsigned PreambleReservedSize;
221 /// \brief Keeps track of the files that were used when computing the
222 /// preamble, with both their buffer size and their modification time.
224 /// If any of the files have changed from one compile to the next,
225 /// the preamble must be thrown away.
226 llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble;
228 /// \brief When non-NULL, this is the buffer used to store the contents of
229 /// the main file when it has been padded for use with the precompiled
231 llvm::MemoryBuffer *SavedMainFileBuffer;
233 /// \brief When non-NULL, this is the buffer used to store the
234 /// contents of the preamble when it has been padded to build the
235 /// precompiled preamble.
236 llvm::MemoryBuffer *PreambleBuffer;
238 /// \brief The number of warnings that occurred while parsing the preamble.
240 /// This value will be used to restore the state of the \c DiagnosticsEngine
241 /// object when re-using the precompiled preamble. Note that only the
242 /// number of warnings matters, since we will not save the preamble
243 /// when any errors are present.
244 unsigned NumWarningsInPreamble;
246 /// \brief A list of the serialization ID numbers for each of the top-level
247 /// declarations parsed within the precompiled preamble.
248 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
250 /// \brief Whether we should be caching code-completion results.
251 bool ShouldCacheCodeCompletionResults;
253 /// \brief The language options used when we load an AST file.
254 LangOptions ASTFileLangOpts;
256 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
257 const char **ArgBegin, const char **ArgEnd,
258 ASTUnit &AST, bool CaptureDiagnostics);
260 void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
261 SourceManager &SrcMan,
262 const SmallVectorImpl<StoredDiagnostic> &Diags,
263 SmallVectorImpl<StoredDiagnostic> &Out);
265 void clearFileLevelDecls();
268 /// \brief A cached code-completion result, which may be introduced in one of
269 /// many different contexts.
270 struct CachedCodeCompletionResult {
271 /// \brief The code-completion string corresponding to this completion
273 CodeCompletionString *Completion;
275 /// \brief A bitmask that indicates which code-completion contexts should
276 /// contain this completion result.
278 /// The bits in the bitmask correspond to the values of
279 /// CodeCompleteContext::Kind. To map from a completion context kind to a
280 /// bit, subtract one from the completion context kind and shift 1 by that
281 /// number of bits. Many completions can occur in several different
283 unsigned ShowInContexts;
285 /// \brief The priority given to this code-completion result.
288 /// \brief The libclang cursor kind corresponding to this code-completion
292 /// \brief The availability of this code-completion result.
293 CXAvailabilityKind Availability;
295 /// \brief The simplified type class for a non-macro completion result.
296 SimplifiedTypeClass TypeClass;
298 /// \brief The type of a non-macro completion result, stored as a unique
299 /// integer used by the string map of cached completion types.
301 /// This value will be zero if the type is not known, or a unique value
302 /// determined by the formatted type string. Se \c CachedCompletionTypes
303 /// for more information.
307 /// \brief Retrieve the mapping from formatted type names to unique type
309 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
310 return CachedCompletionTypes;
313 /// \brief Retrieve the allocator used to cache global code completions.
314 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
315 getCachedCompletionAllocator() {
316 return CachedCompletionAllocator;
319 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
321 CCTUInfo.reset(new CodeCompletionTUInfo(
322 new GlobalCodeCompletionAllocator));
327 /// \brief Allocator used to store cached code completions.
328 IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
329 CachedCompletionAllocator;
331 OwningPtr<CodeCompletionTUInfo> CCTUInfo;
333 /// \brief The set of cached code-completion results.
334 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
336 /// \brief A mapping from the formatted type name to a unique number for that
337 /// type, which is used for type equality comparisons.
338 llvm::StringMap<unsigned> CachedCompletionTypes;
340 /// \brief A string hash of the top-level declaration and macro definition
341 /// names processed the last time that we reparsed the file.
343 /// This hash value is used to determine when we need to refresh the
344 /// global code-completion cache.
345 unsigned CompletionCacheTopLevelHashValue;
347 /// \brief A string hash of the top-level declaration and macro definition
348 /// names processed the last time that we reparsed the precompiled preamble.
350 /// This hash value is used to determine when we need to refresh the
351 /// global code-completion cache after a rebuild of the precompiled preamble.
352 unsigned PreambleTopLevelHashValue;
354 /// \brief The current hash value for the top-level declaration and macro
356 unsigned CurrentTopLevelHashValue;
358 /// \brief Bit used by CIndex to mark when a translation unit may be in an
359 /// inconsistent state, and is not safe to free.
360 unsigned UnsafeToFree : 1;
362 /// \brief Cache any "global" code-completion results, so that we can avoid
363 /// recomputing them with each completion.
364 void CacheCodeCompletionResults();
366 /// \brief Clear out and deallocate
367 void ClearCachedCompletionResults();
369 ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT
370 ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT
372 explicit ASTUnit(bool MainFileIsAST);
374 void CleanTemporaryFiles();
375 bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
377 std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
378 ComputePreamble(CompilerInvocation &Invocation,
379 unsigned MaxLines, bool &CreatedBuffer);
381 llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
382 const CompilerInvocation &PreambleInvocationIn,
383 bool AllowRebuild = true,
384 unsigned MaxLines = 0);
385 void RealizeTopLevelDeclsFromPreamble();
387 /// \brief Transfers ownership of the objects (like SourceManager) from
388 /// \param CI to this ASTUnit.
389 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
391 /// \brief Allows us to assert that ASTUnit is not being used concurrently,
392 /// which is not supported.
394 /// Clients should create instances of the ConcurrencyCheck class whenever
395 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
396 /// just about any usage.
397 /// Becomes a noop in release mode; only useful for debug mode checking.
398 class ConcurrencyState {
399 void *Mutex; // a llvm::sys::MutexImpl in debug;
408 ConcurrencyState ConcurrencyCheckValue;
411 class ConcurrencyCheck {
415 explicit ConcurrencyCheck(ASTUnit &Self)
418 Self.ConcurrencyCheckValue.start();
420 ~ConcurrencyCheck() {
421 Self.ConcurrencyCheckValue.finish();
424 friend class ConcurrencyCheck;
428 bool isMainFileAST() const { return MainFileIsAST; }
430 bool isUnsafeToFree() const { return UnsafeToFree; }
431 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
433 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
434 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
436 const SourceManager &getSourceManager() const { return *SourceMgr; }
437 SourceManager &getSourceManager() { return *SourceMgr; }
439 const Preprocessor &getPreprocessor() const { return *PP; }
440 Preprocessor &getPreprocessor() { return *PP; }
442 const ASTContext &getASTContext() const { return *Ctx; }
443 ASTContext &getASTContext() { return *Ctx; }
445 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
446 void setPreprocessor(Preprocessor *pp);
448 bool hasSema() const { return TheSema; }
449 Sema &getSema() const {
450 assert(TheSema && "ASTUnit does not have a Sema object!");
454 const FileManager &getFileManager() const { return *FileMgr; }
455 FileManager &getFileManager() { return *FileMgr; }
457 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
459 const std::string &getOriginalSourceFileName();
461 /// \brief Add a temporary file that the ASTUnit depends on.
463 /// This file will be erased when the ASTUnit is destroyed.
464 void addTemporaryFile(const llvm::sys::Path &TempFile);
466 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
468 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
469 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
471 StringRef getMainFileName() const;
473 typedef std::vector<Decl *>::iterator top_level_iterator;
475 top_level_iterator top_level_begin() {
476 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
477 if (!TopLevelDeclsInPreamble.empty())
478 RealizeTopLevelDeclsFromPreamble();
479 return TopLevelDecls.begin();
482 top_level_iterator top_level_end() {
483 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
484 if (!TopLevelDeclsInPreamble.empty())
485 RealizeTopLevelDeclsFromPreamble();
486 return TopLevelDecls.end();
489 std::size_t top_level_size() const {
490 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
491 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
494 bool top_level_empty() const {
495 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
496 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
499 /// \brief Add a new top-level declaration.
500 void addTopLevelDecl(Decl *D) {
501 TopLevelDecls.push_back(D);
504 /// \brief Add a new local file-level declaration.
505 void addFileLevelDecl(Decl *D);
507 /// \brief Get the decls that are contained in a file in the Offset/Length
508 /// range. \arg Length can be 0 to indicate a point at \arg Offset instead of
510 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
511 SmallVectorImpl<Decl *> &Decls);
513 /// \brief Add a new top-level declaration, identified by its ID in
514 /// the precompiled preamble.
515 void addTopLevelDeclFromPreamble(serialization::DeclID D) {
516 TopLevelDeclsInPreamble.push_back(D);
519 /// \brief Retrieve a reference to the current top-level name hash value.
521 /// Note: This is used internally by the top-level tracking action
522 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
524 /// \brief Get the source location for the given file:line:col triplet.
526 /// The difference with SourceManager::getLocation is that this method checks
527 /// whether the requested location points inside the precompiled preamble
528 /// in which case the returned source location will be a "loaded" one.
529 SourceLocation getLocation(const FileEntry *File,
530 unsigned Line, unsigned Col) const;
532 /// \brief Get the source location for the given file:offset pair.
533 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
535 /// \brief If \arg Loc is a loaded location from the preamble, returns
536 /// the corresponding local location of the main file, otherwise it returns
538 SourceLocation mapLocationFromPreamble(SourceLocation Loc);
540 /// \brief If \arg Loc is a local location of the main file but inside the
541 /// preamble chunk, returns the corresponding loaded location from the
542 /// preamble, otherwise it returns \arg Loc.
543 SourceLocation mapLocationToPreamble(SourceLocation Loc);
545 bool isInPreambleFileID(SourceLocation Loc);
546 bool isInMainFileID(SourceLocation Loc);
547 SourceLocation getStartOfMainFileID();
548 SourceLocation getEndOfPreambleFileID();
550 /// \brief \see mapLocationFromPreamble.
551 SourceRange mapRangeFromPreamble(SourceRange R) {
552 return SourceRange(mapLocationFromPreamble(R.getBegin()),
553 mapLocationFromPreamble(R.getEnd()));
556 /// \brief \see mapLocationToPreamble.
557 SourceRange mapRangeToPreamble(SourceRange R) {
558 return SourceRange(mapLocationToPreamble(R.getBegin()),
559 mapLocationToPreamble(R.getEnd()));
562 // Retrieve the diagnostics associated with this AST
563 typedef StoredDiagnostic *stored_diag_iterator;
564 typedef const StoredDiagnostic *stored_diag_const_iterator;
565 stored_diag_const_iterator stored_diag_begin() const {
566 return StoredDiagnostics.begin();
568 stored_diag_iterator stored_diag_begin() {
569 return StoredDiagnostics.begin();
571 stored_diag_const_iterator stored_diag_end() const {
572 return StoredDiagnostics.end();
574 stored_diag_iterator stored_diag_end() {
575 return StoredDiagnostics.end();
577 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
579 stored_diag_iterator stored_diag_afterDriver_begin() {
580 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
581 NumStoredDiagnosticsFromDriver = 0;
582 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
585 typedef std::vector<CachedCodeCompletionResult>::iterator
586 cached_completion_iterator;
588 cached_completion_iterator cached_completion_begin() {
589 return CachedCompletionResults.begin();
592 cached_completion_iterator cached_completion_end() {
593 return CachedCompletionResults.end();
596 unsigned cached_completion_size() const {
597 return CachedCompletionResults.size();
600 llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
601 std::string *ErrorStr = 0);
603 /// \brief Determine what kind of translation unit this AST represents.
604 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
606 typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
608 /// \brief A mapping from a file name to the memory buffer that stores the
609 /// remapped contents of that file.
610 typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
612 /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
613 static ASTUnit *create(CompilerInvocation *CI,
614 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
615 bool CaptureDiagnostics = false);
617 /// \brief Create a ASTUnit from an AST file.
619 /// \param Filename - The AST file to load.
621 /// \param Diags - The diagnostics engine to use for reporting errors; its
622 /// lifetime is expected to extend past that of the returned ASTUnit.
624 /// \returns - The initialized ASTUnit or null if the AST failed to load.
625 static ASTUnit *LoadFromASTFile(const std::string &Filename,
626 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
627 const FileSystemOptions &FileSystemOpts,
628 bool OnlyLocalDecls = false,
629 RemappedFile *RemappedFiles = 0,
630 unsigned NumRemappedFiles = 0,
631 bool CaptureDiagnostics = false,
632 bool AllowPCHWithCompilerErrors = false);
635 /// \brief Helper function for \c LoadFromCompilerInvocation() and
636 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
638 /// \param PrecompilePreamble Whether to precompile the preamble of this
639 /// translation unit, to improve the performance of reparsing.
641 /// \returns \c true if a catastrophic failure occurred (which means that the
642 /// \c ASTUnit itself is invalid), or \c false otherwise.
643 bool LoadFromCompilerInvocation(bool PrecompilePreamble);
647 /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
648 /// object, by invoking the optionally provided ASTFrontendAction.
650 /// \param CI - The compiler invocation to use; it must have exactly one input
651 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
653 /// \param Diags - The diagnostics engine to use for reporting errors; its
654 /// lifetime is expected to extend past that of the returned ASTUnit.
656 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
659 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
662 /// \param Persistent - if true the returned ASTUnit will be complete.
663 /// false means the caller is only interested in getting info through the
664 /// provided \see Action.
666 /// \param ErrAST - If non-null and parsing failed without any AST to return
667 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
668 /// mainly to allow the caller to see the diagnostics.
669 /// This will only receive an ASTUnit if a new one was created. If an already
670 /// created ASTUnit was passed in \param Unit then the caller can check that.
672 static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
673 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
674 ASTFrontendAction *Action = 0,
676 bool Persistent = true,
677 StringRef ResourceFilesPath = StringRef(),
678 bool OnlyLocalDecls = false,
679 bool CaptureDiagnostics = false,
680 bool PrecompilePreamble = false,
681 bool CacheCodeCompletionResults = false,
682 OwningPtr<ASTUnit> *ErrAST = 0);
684 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
685 /// CompilerInvocation object.
687 /// \param CI - The compiler invocation to use; it must have exactly one input
688 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
690 /// \param Diags - The diagnostics engine to use for reporting errors; its
691 /// lifetime is expected to extend past that of the returned ASTUnit.
693 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
694 // shouldn't need to specify them at construction time.
695 static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
696 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
697 bool OnlyLocalDecls = false,
698 bool CaptureDiagnostics = false,
699 bool PrecompilePreamble = false,
700 TranslationUnitKind TUKind = TU_Complete,
701 bool CacheCodeCompletionResults = false);
703 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
704 /// arguments, which must specify exactly one source file.
706 /// \param ArgBegin - The beginning of the argument vector.
708 /// \param ArgEnd - The end of the argument vector.
710 /// \param Diags - The diagnostics engine to use for reporting errors; its
711 /// lifetime is expected to extend past that of the returned ASTUnit.
713 /// \param ResourceFilesPath - The path to the compiler resource files.
715 /// \param ErrAST - If non-null and parsing failed without any AST to return
716 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
717 /// mainly to allow the caller to see the diagnostics.
719 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
720 // shouldn't need to specify them at construction time.
721 static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
723 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
724 StringRef ResourceFilesPath,
725 bool OnlyLocalDecls = false,
726 bool CaptureDiagnostics = false,
727 RemappedFile *RemappedFiles = 0,
728 unsigned NumRemappedFiles = 0,
729 bool RemappedFilesKeepOriginalName = true,
730 bool PrecompilePreamble = false,
731 TranslationUnitKind TUKind = TU_Complete,
732 bool CacheCodeCompletionResults = false,
733 bool AllowPCHWithCompilerErrors = false,
734 bool SkipFunctionBodies = false,
735 OwningPtr<ASTUnit> *ErrAST = 0);
737 /// \brief Reparse the source files using the same command-line options that
738 /// were originally used to produce this translation unit.
740 /// \returns True if a failure occurred that causes the ASTUnit not to
741 /// contain any translation-unit information, false otherwise.
742 bool Reparse(RemappedFile *RemappedFiles = 0,
743 unsigned NumRemappedFiles = 0);
745 /// \brief Perform code completion at the given file, line, and
746 /// column within this translation unit.
748 /// \param File The file in which code completion will occur.
750 /// \param Line The line at which code completion will occur.
752 /// \param Column The column at which code completion will occur.
754 /// \param IncludeMacros Whether to include macros in the code-completion
757 /// \param IncludeCodePatterns Whether to include code patterns (such as a
758 /// for loop) in the code-completion results.
760 /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
761 /// OwnedBuffers parameters are all disgusting hacks. They will go away.
762 void CodeComplete(StringRef File, unsigned Line, unsigned Column,
763 RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
764 bool IncludeMacros, bool IncludeCodePatterns,
765 CodeCompleteConsumer &Consumer,
766 DiagnosticsEngine &Diag, LangOptions &LangOpts,
767 SourceManager &SourceMgr, FileManager &FileMgr,
768 SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
769 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
771 /// \brief Save this translation unit to a file with the given name.
773 /// \returns An indication of whether the save was successful or not.
774 CXSaveError Save(StringRef File);
776 /// \brief Serialize this translation unit with the given output stream.
778 /// \returns True if an error occurred, false otherwise.
779 bool serialize(raw_ostream &OS);
781 virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
782 Module::NameVisibilityKind Visibility,
783 bool IsInclusionDirective) {
784 // ASTUnit doesn't know how to load modules (not that this matters).