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