clang API Documentation

ASTUnit.h
Go to the documentation of this file.
00001 //===--- ASTUnit.h - ASTUnit utility ----------------------------*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // ASTUnit utility class.
00011 //
00012 //===----------------------------------------------------------------------===//
00013 
00014 #ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H
00015 #define LLVM_CLANG_FRONTEND_ASTUNIT_H
00016 
00017 #include "clang/Serialization/ASTBitCodes.h"
00018 #include "clang/Sema/Sema.h"
00019 #include "clang/Sema/CodeCompleteConsumer.h"
00020 #include "clang/Lex/ModuleLoader.h"
00021 #include "clang/Lex/PreprocessingRecord.h"
00022 #include "clang/Basic/LangOptions.h"
00023 #include "clang/Basic/SourceManager.h"
00024 #include "clang/Basic/FileManager.h"
00025 #include "clang/Basic/FileSystemOptions.h"
00026 #include "clang-c/Index.h"
00027 #include "llvm/ADT/IntrusiveRefCntPtr.h"
00028 #include "llvm/ADT/OwningPtr.h"
00029 #include "llvm/ADT/SmallVector.h"
00030 #include "llvm/ADT/StringMap.h"
00031 #include "llvm/Support/Path.h"
00032 #include <map>
00033 #include <string>
00034 #include <vector>
00035 #include <cassert>
00036 #include <utility>
00037 #include <sys/types.h>
00038 
00039 namespace llvm {
00040   class MemoryBuffer;
00041 }
00042 
00043 namespace clang {
00044 class ASTContext;
00045 class ASTReader;
00046 class CodeCompleteConsumer;
00047 class CompilerInvocation;
00048 class CompilerInstance;
00049 class Decl;
00050 class DiagnosticsEngine;
00051 class FileEntry;
00052 class FileManager;
00053 class HeaderSearch;
00054 class Preprocessor;
00055 class SourceManager;
00056 class TargetInfo;
00057 class ASTFrontendAction;
00058 
00059 /// \brief Utility class for loading a ASTContext from an AST file.
00060 ///
00061 class ASTUnit : public ModuleLoader {
00062 private:
00063   IntrusiveRefCntPtr<LangOptions>       LangOpts;
00064   IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
00065   IntrusiveRefCntPtr<FileManager>       FileMgr;
00066   IntrusiveRefCntPtr<SourceManager>     SourceMgr;
00067   OwningPtr<HeaderSearch>               HeaderInfo;
00068   IntrusiveRefCntPtr<TargetInfo>        Target;
00069   IntrusiveRefCntPtr<Preprocessor>      PP;
00070   IntrusiveRefCntPtr<ASTContext>        Ctx;
00071   ASTReader *Reader;
00072 
00073   FileSystemOptions FileSystemOpts;
00074 
00075   /// \brief The AST consumer that received information about the translation
00076   /// unit as it was parsed or loaded.
00077   OwningPtr<ASTConsumer> Consumer;
00078   
00079   /// \brief The semantic analysis object used to type-check the translation
00080   /// unit.
00081   OwningPtr<Sema> TheSema;
00082   
00083   /// Optional owned invocation, just used to make the invocation used in
00084   /// LoadFromCommandLine available.
00085   IntrusiveRefCntPtr<CompilerInvocation> Invocation;
00086   
00087   /// \brief The set of target features.
00088   ///
00089   /// FIXME: each time we reparse, we need to restore the set of target
00090   /// features from this vector, because TargetInfo::CreateTargetInfo()
00091   /// mangles the target options in place. Yuck!
00092   std::vector<std::string> TargetFeatures;
00093   
00094   // OnlyLocalDecls - when true, walking this AST should only visit declarations
00095   // that come from the AST itself, not from included precompiled headers.
00096   // FIXME: This is temporary; eventually, CIndex will always do this.
00097   bool                              OnlyLocalDecls;
00098 
00099   /// \brief Whether to capture any diagnostics produced.
00100   bool CaptureDiagnostics;
00101 
00102   /// \brief Track whether the main file was loaded from an AST or not.
00103   bool MainFileIsAST;
00104 
00105   /// \brief What kind of translation unit this AST represents.
00106   TranslationUnitKind TUKind;
00107 
00108   /// \brief Whether we should time each operation.
00109   bool WantTiming;
00110 
00111   /// \brief Whether the ASTUnit should delete the remapped buffers.
00112   bool OwnsRemappedFileBuffers;
00113   
00114   /// Track the top-level decls which appeared in an ASTUnit which was loaded
00115   /// from a source file.
00116   //
00117   // FIXME: This is just an optimization hack to avoid deserializing large parts
00118   // of a PCH file when using the Index library on an ASTUnit loaded from
00119   // source. In the long term we should make the Index library use efficient and
00120   // more scalable search mechanisms.
00121   std::vector<Decl*> TopLevelDecls;
00122 
00123   /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
00124   typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
00125   typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
00126 
00127   /// \brief Map from FileID to the file-level declarations that it contains.
00128   /// The files and decls are only local (and non-preamble) ones.
00129   FileDeclsTy FileDecls;
00130   
00131   /// The name of the original source file used to generate this ASTUnit.
00132   std::string OriginalSourceFile;
00133 
00134   /// \brief The set of diagnostics produced when creating the preamble.
00135   SmallVector<StoredDiagnostic, 4> PreambleDiagnostics;
00136 
00137   /// \brief The set of diagnostics produced when creating this
00138   /// translation unit.
00139   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
00140 
00141   /// \brief The set of diagnostics produced when failing to parse, e.g. due
00142   /// to failure to load the PCH.
00143   SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
00144 
00145   /// \brief The number of stored diagnostics that come from the driver
00146   /// itself.
00147   ///
00148   /// Diagnostics that come from the driver are retained from one parse to
00149   /// the next.
00150   unsigned NumStoredDiagnosticsFromDriver;
00151   
00152   /// \brief Counter that determines when we want to try building a
00153   /// precompiled preamble.
00154   ///
00155   /// If zero, we will never build a precompiled preamble. Otherwise,
00156   /// it's treated as a counter that decrements each time we reparse
00157   /// without the benefit of a precompiled preamble. When it hits 1,
00158   /// we'll attempt to rebuild the precompiled header. This way, if
00159   /// building the precompiled preamble fails, we won't try again for
00160   /// some number of calls.
00161   unsigned PreambleRebuildCounter;
00162 
00163 public:
00164   class PreambleData {
00165     const FileEntry *File;
00166     std::vector<char> Buffer;
00167     mutable unsigned NumLines;
00168     
00169   public:
00170     PreambleData() : File(0), NumLines(0) { }
00171     
00172     void assign(const FileEntry *F, const char *begin, const char *end) {
00173       File = F;
00174       Buffer.assign(begin, end);
00175       NumLines = 0;
00176     }
00177 
00178     void clear() { Buffer.clear(); File = 0; NumLines = 0; }
00179 
00180     size_t size() const { return Buffer.size(); }
00181     bool empty() const { return Buffer.empty(); }
00182 
00183     const char *getBufferStart() const { return &Buffer[0]; }
00184 
00185     unsigned getNumLines() const {
00186       if (NumLines)
00187         return NumLines;
00188       countLines();
00189       return NumLines;
00190     }
00191 
00192     SourceRange getSourceRange(const SourceManager &SM) const {
00193       SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
00194       return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
00195     }
00196 
00197   private:
00198     void countLines() const;
00199   };
00200 
00201   const PreambleData &getPreambleData() const {
00202     return Preamble;
00203   }
00204 
00205 private:
00206 
00207   /// \brief The contents of the preamble that has been precompiled to
00208   /// \c PreambleFile.
00209   PreambleData Preamble;
00210 
00211   /// \brief Whether the preamble ends at the start of a new line.
00212   /// 
00213   /// Used to inform the lexer as to whether it's starting at the beginning of
00214   /// a line after skipping the preamble.
00215   bool PreambleEndsAtStartOfLine;
00216   
00217   /// \brief The size of the source buffer that we've reserved for the main 
00218   /// file within the precompiled preamble.
00219   unsigned PreambleReservedSize;
00220 
00221   /// \brief Keeps track of the files that were used when computing the 
00222   /// preamble, with both their buffer size and their modification time.
00223   ///
00224   /// If any of the files have changed from one compile to the next,
00225   /// the preamble must be thrown away.
00226   llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble;
00227 
00228   /// \brief When non-NULL, this is the buffer used to store the contents of
00229   /// the main file when it has been padded for use with the precompiled
00230   /// preamble.
00231   llvm::MemoryBuffer *SavedMainFileBuffer;
00232 
00233   /// \brief When non-NULL, this is the buffer used to store the
00234   /// contents of the preamble when it has been padded to build the
00235   /// precompiled preamble.
00236   llvm::MemoryBuffer *PreambleBuffer;
00237 
00238   /// \brief The number of warnings that occurred while parsing the preamble.
00239   ///
00240   /// This value will be used to restore the state of the \c DiagnosticsEngine
00241   /// object when re-using the precompiled preamble. Note that only the
00242   /// number of warnings matters, since we will not save the preamble
00243   /// when any errors are present.
00244   unsigned NumWarningsInPreamble;
00245 
00246   /// \brief A list of the serialization ID numbers for each of the top-level
00247   /// declarations parsed within the precompiled preamble.
00248   std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
00249   
00250   /// \brief Whether we should be caching code-completion results.
00251   bool ShouldCacheCodeCompletionResults;
00252  
00253   /// \brief The language options used when we load an AST file.
00254   LangOptions ASTFileLangOpts;
00255 
00256   static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
00257                              const char **ArgBegin, const char **ArgEnd,
00258                              ASTUnit &AST, bool CaptureDiagnostics);
00259 
00260   void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
00261                                   SourceManager &SrcMan,
00262                       const SmallVectorImpl<StoredDiagnostic> &Diags,
00263                             SmallVectorImpl<StoredDiagnostic> &Out);
00264 
00265   void clearFileLevelDecls();
00266 
00267 public:
00268   /// \brief A cached code-completion result, which may be introduced in one of
00269   /// many different contexts.
00270   struct CachedCodeCompletionResult {
00271     /// \brief The code-completion string corresponding to this completion
00272     /// result.
00273     CodeCompletionString *Completion;
00274     
00275     /// \brief A bitmask that indicates which code-completion contexts should
00276     /// contain this completion result.
00277     ///
00278     /// The bits in the bitmask correspond to the values of 
00279     /// CodeCompleteContext::Kind. To map from a completion context kind to a 
00280     /// bit, subtract one from the completion context kind and shift 1 by that
00281     /// number of bits. Many completions can occur in several different
00282     /// contexts.
00283     unsigned ShowInContexts;
00284     
00285     /// \brief The priority given to this code-completion result.
00286     unsigned Priority;
00287     
00288     /// \brief The libclang cursor kind corresponding to this code-completion 
00289     /// result.
00290     CXCursorKind Kind;
00291     
00292     /// \brief The availability of this code-completion result.
00293     CXAvailabilityKind Availability;
00294     
00295     /// \brief The simplified type class for a non-macro completion result.
00296     SimplifiedTypeClass TypeClass;
00297     
00298     /// \brief The type of a non-macro completion result, stored as a unique
00299     /// integer used by the string map of cached completion types.
00300     ///
00301     /// This value will be zero if the type is not known, or a unique value
00302     /// determined by the formatted type string. Se \c CachedCompletionTypes
00303     /// for more information.
00304     unsigned Type;
00305   };
00306   
00307   /// \brief Retrieve the mapping from formatted type names to unique type
00308   /// identifiers.
00309   llvm::StringMap<unsigned> &getCachedCompletionTypes() { 
00310     return CachedCompletionTypes; 
00311   }
00312   
00313   /// \brief Retrieve the allocator used to cache global code completions.
00314   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
00315   getCachedCompletionAllocator() {
00316     return CachedCompletionAllocator;
00317   }
00318 
00319   CodeCompletionTUInfo &getCodeCompletionTUInfo() {
00320     if (!CCTUInfo)
00321       CCTUInfo.reset(new CodeCompletionTUInfo(
00322                                             new GlobalCodeCompletionAllocator));
00323     return *CCTUInfo;
00324   }
00325 
00326 private:
00327   /// \brief Allocator used to store cached code completions.
00328   IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
00329     CachedCompletionAllocator;
00330   
00331   OwningPtr<CodeCompletionTUInfo> CCTUInfo;
00332 
00333   /// \brief The set of cached code-completion results.
00334   std::vector<CachedCodeCompletionResult> CachedCompletionResults;
00335   
00336   /// \brief A mapping from the formatted type name to a unique number for that
00337   /// type, which is used for type equality comparisons.
00338   llvm::StringMap<unsigned> CachedCompletionTypes;
00339   
00340   /// \brief A string hash of the top-level declaration and macro definition 
00341   /// names processed the last time that we reparsed the file.
00342   ///
00343   /// This hash value is used to determine when we need to refresh the 
00344   /// global code-completion cache.
00345   unsigned CompletionCacheTopLevelHashValue;
00346 
00347   /// \brief A string hash of the top-level declaration and macro definition 
00348   /// names processed the last time that we reparsed the precompiled preamble.
00349   ///
00350   /// This hash value is used to determine when we need to refresh the 
00351   /// global code-completion cache after a rebuild of the precompiled preamble.
00352   unsigned PreambleTopLevelHashValue;
00353 
00354   /// \brief The current hash value for the top-level declaration and macro
00355   /// definition names
00356   unsigned CurrentTopLevelHashValue;
00357   
00358   /// \brief Bit used by CIndex to mark when a translation unit may be in an
00359   /// inconsistent state, and is not safe to free.
00360   unsigned UnsafeToFree : 1;
00361 
00362   /// \brief Cache any "global" code-completion results, so that we can avoid
00363   /// recomputing them with each completion.
00364   void CacheCodeCompletionResults();
00365   
00366   /// \brief Clear out and deallocate 
00367   void ClearCachedCompletionResults();
00368   
00369   ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT
00370   ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT
00371   
00372   explicit ASTUnit(bool MainFileIsAST);
00373 
00374   void CleanTemporaryFiles();
00375   bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
00376   
00377   std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
00378   ComputePreamble(CompilerInvocation &Invocation, 
00379                   unsigned MaxLines, bool &CreatedBuffer);
00380   
00381   llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
00382                                const CompilerInvocation &PreambleInvocationIn,
00383                                                      bool AllowRebuild = true,
00384                                                         unsigned MaxLines = 0);
00385   void RealizeTopLevelDeclsFromPreamble();
00386 
00387   /// \brief Transfers ownership of the objects (like SourceManager) from
00388   /// \param CI to this ASTUnit.
00389   void transferASTDataFromCompilerInstance(CompilerInstance &CI);
00390 
00391   /// \brief Allows us to assert that ASTUnit is not being used concurrently,
00392   /// which is not supported.
00393   ///
00394   /// Clients should create instances of the ConcurrencyCheck class whenever
00395   /// using the ASTUnit in a way that isn't intended to be concurrent, which is
00396   /// just about any usage.
00397   /// Becomes a noop in release mode; only useful for debug mode checking.
00398   class ConcurrencyState {
00399     void *Mutex; // a llvm::sys::MutexImpl in debug;
00400 
00401   public:
00402     ConcurrencyState();
00403     ~ConcurrencyState();
00404 
00405     void start();
00406     void finish();
00407   };
00408   ConcurrencyState ConcurrencyCheckValue;
00409 
00410 public:
00411   class ConcurrencyCheck {
00412     ASTUnit &Self;
00413     
00414   public:
00415     explicit ConcurrencyCheck(ASTUnit &Self)
00416       : Self(Self) 
00417     { 
00418       Self.ConcurrencyCheckValue.start();
00419     }
00420     ~ConcurrencyCheck() {
00421       Self.ConcurrencyCheckValue.finish();
00422     }
00423   };
00424   friend class ConcurrencyCheck;
00425   
00426   ~ASTUnit();
00427 
00428   bool isMainFileAST() const { return MainFileIsAST; }
00429 
00430   bool isUnsafeToFree() const { return UnsafeToFree; }
00431   void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
00432 
00433   const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
00434   DiagnosticsEngine &getDiagnostics()             { return *Diagnostics; }
00435   
00436   const SourceManager &getSourceManager() const { return *SourceMgr; }
00437         SourceManager &getSourceManager()       { return *SourceMgr; }
00438 
00439   const Preprocessor &getPreprocessor() const { return *PP; }
00440         Preprocessor &getPreprocessor()       { return *PP; }
00441 
00442   const ASTContext &getASTContext() const { return *Ctx; }
00443         ASTContext &getASTContext()       { return *Ctx; }
00444 
00445   void setASTContext(ASTContext *ctx) { Ctx = ctx; }
00446   void setPreprocessor(Preprocessor *pp);
00447 
00448   bool hasSema() const { return TheSema; }
00449   Sema &getSema() const { 
00450     assert(TheSema && "ASTUnit does not have a Sema object!");
00451     return *TheSema; 
00452   }
00453   
00454   const FileManager &getFileManager() const { return *FileMgr; }
00455         FileManager &getFileManager()       { return *FileMgr; }
00456 
00457   const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
00458 
00459   const std::string &getOriginalSourceFileName();
00460 
00461   /// \brief Add a temporary file that the ASTUnit depends on.
00462   ///
00463   /// This file will be erased when the ASTUnit is destroyed.
00464   void addTemporaryFile(const llvm::sys::Path &TempFile);
00465                         
00466   bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
00467 
00468   bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
00469   void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
00470 
00471   StringRef getMainFileName() const;
00472 
00473   typedef std::vector<Decl *>::iterator top_level_iterator;
00474 
00475   top_level_iterator top_level_begin() {
00476     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
00477     if (!TopLevelDeclsInPreamble.empty())
00478       RealizeTopLevelDeclsFromPreamble();
00479     return TopLevelDecls.begin();
00480   }
00481 
00482   top_level_iterator top_level_end() {
00483     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
00484     if (!TopLevelDeclsInPreamble.empty())
00485       RealizeTopLevelDeclsFromPreamble();
00486     return TopLevelDecls.end();
00487   }
00488 
00489   std::size_t top_level_size() const {
00490     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
00491     return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
00492   }
00493 
00494   bool top_level_empty() const {
00495     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
00496     return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
00497   }
00498 
00499   /// \brief Add a new top-level declaration.
00500   void addTopLevelDecl(Decl *D) {
00501     TopLevelDecls.push_back(D);
00502   }
00503 
00504   /// \brief Add a new local file-level declaration.
00505   void addFileLevelDecl(Decl *D);
00506 
00507   /// \brief Get the decls that are contained in a file in the Offset/Length
00508   /// range. \arg Length can be 0 to indicate a point at \arg Offset instead of
00509   /// a range. 
00510   void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
00511                            SmallVectorImpl<Decl *> &Decls);
00512 
00513   /// \brief Add a new top-level declaration, identified by its ID in
00514   /// the precompiled preamble.
00515   void addTopLevelDeclFromPreamble(serialization::DeclID D) {
00516     TopLevelDeclsInPreamble.push_back(D);
00517   }
00518 
00519   /// \brief Retrieve a reference to the current top-level name hash value.
00520   ///
00521   /// Note: This is used internally by the top-level tracking action
00522   unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
00523 
00524   /// \brief Get the source location for the given file:line:col triplet.
00525   ///
00526   /// The difference with SourceManager::getLocation is that this method checks
00527   /// whether the requested location points inside the precompiled preamble
00528   /// in which case the returned source location will be a "loaded" one.
00529   SourceLocation getLocation(const FileEntry *File,
00530                              unsigned Line, unsigned Col) const;
00531 
00532   /// \brief Get the source location for the given file:offset pair.
00533   SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
00534 
00535   /// \brief If \arg Loc is a loaded location from the preamble, returns
00536   /// the corresponding local location of the main file, otherwise it returns
00537   /// \arg Loc.
00538   SourceLocation mapLocationFromPreamble(SourceLocation Loc);
00539 
00540   /// \brief If \arg Loc is a local location of the main file but inside the
00541   /// preamble chunk, returns the corresponding loaded location from the
00542   /// preamble, otherwise it returns \arg Loc.
00543   SourceLocation mapLocationToPreamble(SourceLocation Loc);
00544 
00545   bool isInPreambleFileID(SourceLocation Loc);
00546   bool isInMainFileID(SourceLocation Loc);
00547   SourceLocation getStartOfMainFileID();
00548   SourceLocation getEndOfPreambleFileID();
00549 
00550   /// \brief \see mapLocationFromPreamble.
00551   SourceRange mapRangeFromPreamble(SourceRange R) {
00552     return SourceRange(mapLocationFromPreamble(R.getBegin()),
00553                        mapLocationFromPreamble(R.getEnd()));
00554   }
00555 
00556   /// \brief \see mapLocationToPreamble.
00557   SourceRange mapRangeToPreamble(SourceRange R) {
00558     return SourceRange(mapLocationToPreamble(R.getBegin()),
00559                        mapLocationToPreamble(R.getEnd()));
00560   }
00561   
00562   // Retrieve the diagnostics associated with this AST
00563   typedef StoredDiagnostic *stored_diag_iterator;
00564   typedef const StoredDiagnostic *stored_diag_const_iterator;
00565   stored_diag_const_iterator stored_diag_begin() const { 
00566     return StoredDiagnostics.begin(); 
00567   }
00568   stored_diag_iterator stored_diag_begin() { 
00569     return StoredDiagnostics.begin(); 
00570   }
00571   stored_diag_const_iterator stored_diag_end() const { 
00572     return StoredDiagnostics.end(); 
00573   }
00574   stored_diag_iterator stored_diag_end() { 
00575     return StoredDiagnostics.end(); 
00576   }
00577   unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
00578 
00579   stored_diag_iterator stored_diag_afterDriver_begin() {
00580     if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
00581       NumStoredDiagnosticsFromDriver = 0;
00582     return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver; 
00583   }
00584 
00585   typedef std::vector<CachedCodeCompletionResult>::iterator
00586     cached_completion_iterator;
00587   
00588   cached_completion_iterator cached_completion_begin() {
00589     return CachedCompletionResults.begin();
00590   }
00591 
00592   cached_completion_iterator cached_completion_end() {
00593     return CachedCompletionResults.end();
00594   }
00595 
00596   unsigned cached_completion_size() const { 
00597     return CachedCompletionResults.size(); 
00598   }
00599 
00600   llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
00601                                        std::string *ErrorStr = 0);
00602 
00603   /// \brief Determine what kind of translation unit this AST represents.
00604   TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
00605 
00606   typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
00607       FilenameOrMemBuf;
00608   /// \brief A mapping from a file name to the memory buffer that stores the
00609   /// remapped contents of that file.
00610   typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
00611 
00612   /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation. 
00613   static ASTUnit *create(CompilerInvocation *CI,
00614                          IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
00615                          bool CaptureDiagnostics = false);
00616 
00617   /// \brief Create a ASTUnit from an AST file.
00618   ///
00619   /// \param Filename - The AST file to load.
00620   ///
00621   /// \param Diags - The diagnostics engine to use for reporting errors; its
00622   /// lifetime is expected to extend past that of the returned ASTUnit.
00623   ///
00624   /// \returns - The initialized ASTUnit or null if the AST failed to load.
00625   static ASTUnit *LoadFromASTFile(const std::string &Filename,
00626                               IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
00627                                   const FileSystemOptions &FileSystemOpts,
00628                                   bool OnlyLocalDecls = false,
00629                                   RemappedFile *RemappedFiles = 0,
00630                                   unsigned NumRemappedFiles = 0,
00631                                   bool CaptureDiagnostics = false,
00632                                   bool AllowPCHWithCompilerErrors = false);
00633 
00634 private:
00635   /// \brief Helper function for \c LoadFromCompilerInvocation() and
00636   /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
00637   ///
00638   /// \param PrecompilePreamble Whether to precompile the preamble of this
00639   /// translation unit, to improve the performance of reparsing.
00640   ///
00641   /// \returns \c true if a catastrophic failure occurred (which means that the
00642   /// \c ASTUnit itself is invalid), or \c false otherwise.
00643   bool LoadFromCompilerInvocation(bool PrecompilePreamble);
00644   
00645 public:
00646   
00647   /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
00648   /// object, by invoking the optionally provided ASTFrontendAction. 
00649   ///
00650   /// \param CI - The compiler invocation to use; it must have exactly one input
00651   /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
00652   ///
00653   /// \param Diags - The diagnostics engine to use for reporting errors; its
00654   /// lifetime is expected to extend past that of the returned ASTUnit.
00655   ///
00656   /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
00657   /// transfered.
00658   ///
00659   /// \param Unit - optionally an already created ASTUnit. Its ownership is not
00660   /// transfered.
00661   ///
00662   /// \param Persistent - if true the returned ASTUnit will be complete.
00663   /// false means the caller is only interested in getting info through the
00664   /// provided \see Action.
00665   ///
00666   /// \param ErrAST - If non-null and parsing failed without any AST to return
00667   /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
00668   /// mainly to allow the caller to see the diagnostics.
00669   /// This will only receive an ASTUnit if a new one was created. If an already
00670   /// created ASTUnit was passed in \param Unit then the caller can check that.
00671   ///
00672   static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
00673                               IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
00674                                              ASTFrontendAction *Action = 0,
00675                                              ASTUnit *Unit = 0,
00676                                              bool Persistent = true,
00677                                       StringRef ResourceFilesPath = StringRef(),
00678                                              bool OnlyLocalDecls = false,
00679                                              bool CaptureDiagnostics = false,
00680                                              bool PrecompilePreamble = false,
00681                                        bool CacheCodeCompletionResults = false,
00682                                        OwningPtr<ASTUnit> *ErrAST = 0);
00683 
00684   /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
00685   /// CompilerInvocation object.
00686   ///
00687   /// \param CI - The compiler invocation to use; it must have exactly one input
00688   /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
00689   ///
00690   /// \param Diags - The diagnostics engine to use for reporting errors; its
00691   /// lifetime is expected to extend past that of the returned ASTUnit.
00692   //
00693   // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
00694   // shouldn't need to specify them at construction time.
00695   static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
00696                               IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
00697                                              bool OnlyLocalDecls = false,
00698                                              bool CaptureDiagnostics = false,
00699                                              bool PrecompilePreamble = false,
00700                                       TranslationUnitKind TUKind = TU_Complete,
00701                                        bool CacheCodeCompletionResults = false);
00702 
00703   /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
00704   /// arguments, which must specify exactly one source file.
00705   ///
00706   /// \param ArgBegin - The beginning of the argument vector.
00707   ///
00708   /// \param ArgEnd - The end of the argument vector.
00709   ///
00710   /// \param Diags - The diagnostics engine to use for reporting errors; its
00711   /// lifetime is expected to extend past that of the returned ASTUnit.
00712   ///
00713   /// \param ResourceFilesPath - The path to the compiler resource files.
00714   ///
00715   /// \param ErrAST - If non-null and parsing failed without any AST to return
00716   /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
00717   /// mainly to allow the caller to see the diagnostics.
00718   ///
00719   // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
00720   // shouldn't need to specify them at construction time.
00721   static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
00722                                       const char **ArgEnd,
00723                               IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
00724                                       StringRef ResourceFilesPath,
00725                                       bool OnlyLocalDecls = false,
00726                                       bool CaptureDiagnostics = false,
00727                                       RemappedFile *RemappedFiles = 0,
00728                                       unsigned NumRemappedFiles = 0,
00729                                       bool RemappedFilesKeepOriginalName = true,
00730                                       bool PrecompilePreamble = false,
00731                                       TranslationUnitKind TUKind = TU_Complete,
00732                                       bool CacheCodeCompletionResults = false,
00733                                       bool AllowPCHWithCompilerErrors = false,
00734                                       bool SkipFunctionBodies = false,
00735                                       OwningPtr<ASTUnit> *ErrAST = 0);
00736   
00737   /// \brief Reparse the source files using the same command-line options that
00738   /// were originally used to produce this translation unit.
00739   ///
00740   /// \returns True if a failure occurred that causes the ASTUnit not to
00741   /// contain any translation-unit information, false otherwise.  
00742   bool Reparse(RemappedFile *RemappedFiles = 0,
00743                unsigned NumRemappedFiles = 0);
00744 
00745   /// \brief Perform code completion at the given file, line, and
00746   /// column within this translation unit.
00747   ///
00748   /// \param File The file in which code completion will occur.
00749   ///
00750   /// \param Line The line at which code completion will occur.
00751   ///
00752   /// \param Column The column at which code completion will occur.
00753   ///
00754   /// \param IncludeMacros Whether to include macros in the code-completion 
00755   /// results.
00756   ///
00757   /// \param IncludeCodePatterns Whether to include code patterns (such as a 
00758   /// for loop) in the code-completion results.
00759   ///
00760   /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
00761   /// OwnedBuffers parameters are all disgusting hacks. They will go away.
00762   void CodeComplete(StringRef File, unsigned Line, unsigned Column,
00763                     RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
00764                     bool IncludeMacros, bool IncludeCodePatterns,
00765                     CodeCompleteConsumer &Consumer,
00766                     DiagnosticsEngine &Diag, LangOptions &LangOpts,
00767                     SourceManager &SourceMgr, FileManager &FileMgr,
00768                     SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
00769               SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
00770 
00771   /// \brief Save this translation unit to a file with the given name.
00772   ///
00773   /// \returns An indication of whether the save was successful or not.
00774   CXSaveError Save(StringRef File);
00775 
00776   /// \brief Serialize this translation unit with the given output stream.
00777   ///
00778   /// \returns True if an error occurred, false otherwise.
00779   bool serialize(raw_ostream &OS);
00780   
00781   virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
00782                              Module::NameVisibilityKind Visibility,
00783                              bool IsInclusionDirective) {
00784     // ASTUnit doesn't know how to load modules (not that this matters).
00785     return 0;
00786   }
00787 };
00788 
00789 } // namespace clang
00790 
00791 #endif