Home | History | Annotate | Download | only in Frontend
      1 //===--- ASTUnit.h - ASTUnit utility ----------------------------*- C++ -*-===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 // ASTUnit utility class.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 
     14 #ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H
     15 #define LLVM_CLANG_FRONTEND_ASTUNIT_H
     16 
     17 #include "clang/Index/ASTLocation.h"
     18 #include "clang/Serialization/ASTBitCodes.h"
     19 #include "clang/Sema/Sema.h"
     20 #include "clang/Sema/CodeCompleteConsumer.h"
     21 #include "clang/Lex/ModuleLoader.h"
     22 #include "clang/Lex/PreprocessingRecord.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"
     32 #include <map>
     33 #include <string>
     34 #include <vector>
     35 #include <cassert>
     36 #include <utility>
     37 #include <sys/types.h>
     38 
     39 namespace llvm {
     40   class MemoryBuffer;
     41 }
     42 
     43 namespace clang {
     44 class ASTContext;
     45 class ASTReader;
     46 class CodeCompleteConsumer;
     47 class CompilerInvocation;
     48 class Decl;
     49 class DiagnosticsEngine;
     50 class FileEntry;
     51 class FileManager;
     52 class HeaderSearch;
     53 class Preprocessor;
     54 class SourceManager;
     55 class TargetInfo;
     56 class ASTFrontendAction;
     57 
     58 using namespace idx;
     59 
     60 /// \brief Allocator for a cached set of global code completions.
     61 class GlobalCodeCompletionAllocator
     62   : public CodeCompletionAllocator,
     63     public llvm::RefCountedBase<GlobalCodeCompletionAllocator>
     64 {
     65 
     66 };
     67 
     68 /// \brief Utility class for loading a ASTContext from an AST file.
     69 ///
     70 class ASTUnit : public ModuleLoader {
     71 private:
     72   llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
     73   llvm::IntrusiveRefCntPtr<FileManager>       FileMgr;
     74   llvm::IntrusiveRefCntPtr<SourceManager>     SourceMgr;
     75   llvm::OwningPtr<HeaderSearch>               HeaderInfo;
     76   llvm::IntrusiveRefCntPtr<TargetInfo>        Target;
     77   llvm::IntrusiveRefCntPtr<Preprocessor>      PP;
     78   llvm::IntrusiveRefCntPtr<ASTContext>        Ctx;
     79 
     80   FileSystemOptions FileSystemOpts;
     81 
     82   /// \brief The AST consumer that received information about the translation
     83   /// unit as it was parsed or loaded.
     84   llvm::OwningPtr<ASTConsumer> Consumer;
     85 
     86   /// \brief The semantic analysis object used to type-check the translation
     87   /// unit.
     88   llvm::OwningPtr<Sema> TheSema;
     89 
     90   /// Optional owned invocation, just used to make the invocation used in
     91   /// LoadFromCommandLine available.
     92   llvm::IntrusiveRefCntPtr<CompilerInvocation> Invocation;
     93 
     94   /// \brief The set of target features.
     95   ///
     96   /// FIXME: each time we reparse, we need to restore the set of target
     97   /// features from this vector, because TargetInfo::CreateTargetInfo()
     98   /// mangles the target options in place. Yuck!
     99   std::vector<std::string> TargetFeatures;
    100 
    101   // OnlyLocalDecls - when true, walking this AST should only visit declarations
    102   // that come from the AST itself, not from included precompiled headers.
    103   // FIXME: This is temporary; eventually, CIndex will always do this.
    104   bool                              OnlyLocalDecls;
    105 
    106   /// \brief Whether to capture any diagnostics produced.
    107   bool CaptureDiagnostics;
    108 
    109   /// \brief Track whether the main file was loaded from an AST or not.
    110   bool MainFileIsAST;
    111 
    112   /// \brief What kind of translation unit this AST represents.
    113   TranslationUnitKind TUKind;
    114 
    115   /// \brief Whether we should time each operation.
    116   bool WantTiming;
    117 
    118   /// \brief Whether the ASTUnit should delete the remapped buffers.
    119   bool OwnsRemappedFileBuffers;
    120 
    121   /// Track the top-level decls which appeared in an ASTUnit which was loaded
    122   /// from a source file.
    123   //
    124   // FIXME: This is just an optimization hack to avoid deserializing large parts
    125   // of a PCH file when using the Index library on an ASTUnit loaded from
    126   // source. In the long term we should make the Index library use efficient and
    127   // more scalable search mechanisms.
    128   std::vector<Decl*> TopLevelDecls;
    129 
    130   /// The name of the original source file used to generate this ASTUnit.
    131   std::string OriginalSourceFile;
    132 
    133   // Critical optimization when using clang_getCursor().
    134   ASTLocation LastLoc;
    135 
    136   /// \brief The set of diagnostics produced when creating the preamble.
    137   SmallVector<StoredDiagnostic, 4> PreambleDiagnostics;
    138 
    139   /// \brief The set of diagnostics produced when creating this
    140   /// translation unit.
    141   SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
    142 
    143   /// \brief The number of stored diagnostics that come from the driver
    144   /// itself.
    145   ///
    146   /// Diagnostics that come from the driver are retained from one parse to
    147   /// the next.
    148   unsigned NumStoredDiagnosticsFromDriver;
    149 
    150   /// \brief Temporary files that should be removed when the ASTUnit is
    151   /// destroyed.
    152   SmallVector<llvm::sys::Path, 4> TemporaryFiles;
    153 
    154   /// \brief Counter that determines when we want to try building a
    155   /// precompiled preamble.
    156   ///
    157   /// If zero, we will never build a precompiled preamble. Otherwise,
    158   /// it's treated as a counter that decrements each time we reparse
    159   /// without the benefit of a precompiled preamble. When it hits 1,
    160   /// we'll attempt to rebuild the precompiled header. This way, if
    161   /// building the precompiled preamble fails, we won't try again for
    162   /// some number of calls.
    163   unsigned PreambleRebuildCounter;
    164 
    165   /// \brief The file in which the precompiled preamble is stored.
    166   std::string PreambleFile;
    167 
    168 public:
    169   class PreambleData {
    170     const FileEntry *File;
    171     std::vector<char> Buffer;
    172     mutable unsigned NumLines;
    173 
    174   public:
    175     PreambleData() : File(0), NumLines(0) { }
    176 
    177     void assign(const FileEntry *F, const char *begin, const char *end) {
    178       File = F;
    179       Buffer.assign(begin, end);
    180       NumLines = 0;
    181     }
    182 
    183     void clear() { Buffer.clear(); File = 0; NumLines = 0; }
    184 
    185     size_t size() const { return Buffer.size(); }
    186     bool empty() const { return Buffer.empty(); }
    187 
    188     const char *getBufferStart() const { return &Buffer[0]; }
    189 
    190     unsigned getNumLines() const {
    191       if (NumLines)
    192         return NumLines;
    193       countLines();
    194       return NumLines;
    195     }
    196 
    197     SourceRange getSourceRange(const SourceManager &SM) const {
    198       SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
    199       return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
    200     }
    201 
    202   private:
    203     void countLines() const;
    204   };
    205 
    206   const PreambleData &getPreambleData() const {
    207     return Preamble;
    208   }
    209 
    210 private:
    211 
    212   /// \brief The contents of the preamble that has been precompiled to
    213   /// \c PreambleFile.
    214   PreambleData Preamble;
    215 
    216   /// \brief Whether the preamble ends at the start of a new line.
    217   ///
    218   /// Used to inform the lexer as to whether it's starting at the beginning of
    219   /// a line after skipping the preamble.
    220   bool PreambleEndsAtStartOfLine;
    221 
    222   /// \brief The size of the source buffer that we've reserved for the main
    223   /// file within the precompiled preamble.
    224   unsigned PreambleReservedSize;
    225 
    226   /// \brief Keeps track of the files that were used when computing the
    227   /// preamble, with both their buffer size and their modification time.
    228   ///
    229   /// If any of the files have changed from one compile to the next,
    230   /// the preamble must be thrown away.
    231   llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble;
    232 
    233   /// \brief When non-NULL, this is the buffer used to store the contents of
    234   /// the main file when it has been padded for use with the precompiled
    235   /// preamble.
    236   llvm::MemoryBuffer *SavedMainFileBuffer;
    237 
    238   /// \brief When non-NULL, this is the buffer used to store the
    239   /// contents of the preamble when it has been padded to build the
    240   /// precompiled preamble.
    241   llvm::MemoryBuffer *PreambleBuffer;
    242 
    243   /// \brief The number of warnings that occurred while parsing the preamble.
    244   ///
    245   /// This value will be used to restore the state of the \c DiagnosticsEngine
    246   /// object when re-using the precompiled preamble. Note that only the
    247   /// number of warnings matters, since we will not save the preamble
    248   /// when any errors are present.
    249   unsigned NumWarningsInPreamble;
    250 
    251   /// \brief A list of the serialization ID numbers for each of the top-level
    252   /// declarations parsed within the precompiled preamble.
    253   std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
    254 
    255   /// \brief Whether we should be caching code-completion results.
    256   bool ShouldCacheCodeCompletionResults;
    257 
    258   /// \brief Whether we want to include nested macro expansions in the
    259   /// detailed preprocessing record.
    260   bool NestedMacroExpansions;
    261 
    262   /// \brief The language options used when we load an AST file.
    263   LangOptions ASTFileLangOpts;
    264 
    265   static void ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
    266                              const char **ArgBegin, const char **ArgEnd,
    267                              ASTUnit &AST, bool CaptureDiagnostics);
    268 
    269   void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
    270                                   SourceManager &SrcMan,
    271                       const SmallVectorImpl<StoredDiagnostic> &Diags,
    272                             SmallVectorImpl<StoredDiagnostic> &Out);
    273 
    274 public:
    275   /// \brief A cached code-completion result, which may be introduced in one of
    276   /// many different contexts.
    277   struct CachedCodeCompletionResult {
    278     /// \brief The code-completion string corresponding to this completion
    279     /// result.
    280     CodeCompletionString *Completion;
    281 
    282     /// \brief A bitmask that indicates which code-completion contexts should
    283     /// contain this completion result.
    284     ///
    285     /// The bits in the bitmask correspond to the values of
    286     /// CodeCompleteContext::Kind. To map from a completion context kind to a
    287     /// bit, subtract one from the completion context kind and shift 1 by that
    288     /// number of bits. Many completions can occur in several different
    289     /// contexts.
    290     unsigned ShowInContexts;
    291 
    292     /// \brief The priority given to this code-completion result.
    293     unsigned Priority;
    294 
    295     /// \brief The libclang cursor kind corresponding to this code-completion
    296     /// result.
    297     CXCursorKind Kind;
    298 
    299     /// \brief The availability of this code-completion result.
    300     CXAvailabilityKind Availability;
    301 
    302     /// \brief The simplified type class for a non-macro completion result.
    303     SimplifiedTypeClass TypeClass;
    304 
    305     /// \brief The type of a non-macro completion result, stored as a unique
    306     /// integer used by the string map of cached completion types.
    307     ///
    308     /// This value will be zero if the type is not known, or a unique value
    309     /// determined by the formatted type string. Se \c CachedCompletionTypes
    310     /// for more information.
    311     unsigned Type;
    312   };
    313 
    314   /// \brief Retrieve the mapping from formatted type names to unique type
    315   /// identifiers.
    316   llvm::StringMap<unsigned> &getCachedCompletionTypes() {
    317     return CachedCompletionTypes;
    318   }
    319 
    320   /// \brief Retrieve the allocator used to cache global code completions.
    321   llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
    322   getCachedCompletionAllocator() {
    323     return CachedCompletionAllocator;
    324   }
    325 
    326   /// \brief Retrieve the allocator used to cache global code completions.
    327   /// Creates the allocator if it doesn't already exist.
    328   llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
    329   getCursorCompletionAllocator() {
    330     if (!CursorCompletionAllocator.getPtr()) {
    331       CursorCompletionAllocator = new GlobalCodeCompletionAllocator;
    332     }
    333     return CursorCompletionAllocator;
    334   }
    335 
    336 private:
    337   /// \brief Allocator used to store cached code completions.
    338   llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
    339     CachedCompletionAllocator;
    340 
    341   /// \brief Allocator used to store code completions for arbitrary cursors.
    342   llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
    343     CursorCompletionAllocator;
    344 
    345   /// \brief The set of cached code-completion results.
    346   std::vector<CachedCodeCompletionResult> CachedCompletionResults;
    347 
    348   /// \brief A mapping from the formatted type name to a unique number for that
    349   /// type, which is used for type equality comparisons.
    350   llvm::StringMap<unsigned> CachedCompletionTypes;
    351 
    352   /// \brief A string hash of the top-level declaration and macro definition
    353   /// names processed the last time that we reparsed the file.
    354   ///
    355   /// This hash value is used to determine when we need to refresh the
    356   /// global code-completion cache.
    357   unsigned CompletionCacheTopLevelHashValue;
    358 
    359   /// \brief A string hash of the top-level declaration and macro definition
    360   /// names processed the last time that we reparsed the precompiled preamble.
    361   ///
    362   /// This hash value is used to determine when we need to refresh the
    363   /// global code-completion cache after a rebuild of the precompiled preamble.
    364   unsigned PreambleTopLevelHashValue;
    365 
    366   /// \brief The current hash value for the top-level declaration and macro
    367   /// definition names
    368   unsigned CurrentTopLevelHashValue;
    369 
    370   /// \brief Bit used by CIndex to mark when a translation unit may be in an
    371   /// inconsistent state, and is not safe to free.
    372   unsigned UnsafeToFree : 1;
    373 
    374   /// \brief Cache any "global" code-completion results, so that we can avoid
    375   /// recomputing them with each completion.
    376   void CacheCodeCompletionResults();
    377 
    378   /// \brief Clear out and deallocate
    379   void ClearCachedCompletionResults();
    380 
    381   ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT
    382   ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT
    383 
    384   explicit ASTUnit(bool MainFileIsAST);
    385 
    386   void CleanTemporaryFiles();
    387   bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
    388 
    389   std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
    390   ComputePreamble(CompilerInvocation &Invocation,
    391                   unsigned MaxLines, bool &CreatedBuffer);
    392 
    393   llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
    394                                const CompilerInvocation &PreambleInvocationIn,
    395                                                      bool AllowRebuild = true,
    396                                                         unsigned MaxLines = 0);
    397   void RealizeTopLevelDeclsFromPreamble();
    398 
    399   /// \brief Allows us to assert that ASTUnit is not being used concurrently,
    400   /// which is not supported.
    401   ///
    402   /// Clients should create instances of the ConcurrencyCheck class whenever
    403   /// using the ASTUnit in a way that isn't intended to be concurrent, which is
    404   /// just about any usage.
    405   /// Becomes a noop in release mode; only useful for debug mode checking.
    406   class ConcurrencyState {
    407     void *Mutex; // a llvm::sys::MutexImpl in debug;
    408 
    409   public:
    410     ConcurrencyState();
    411     ~ConcurrencyState();
    412 
    413     void start();
    414     void finish();
    415   };
    416   ConcurrencyState ConcurrencyCheckValue;
    417 
    418 public:
    419   class ConcurrencyCheck {
    420     ASTUnit &Self;
    421 
    422   public:
    423     explicit ConcurrencyCheck(ASTUnit &Self)
    424       : Self(Self)
    425     {
    426       Self.ConcurrencyCheckValue.start();
    427     }
    428     ~ConcurrencyCheck() {
    429       Self.ConcurrencyCheckValue.finish();
    430     }
    431   };
    432   friend class ConcurrencyCheck;
    433 
    434   ~ASTUnit();
    435 
    436   bool isMainFileAST() const { return MainFileIsAST; }
    437 
    438   bool isUnsafeToFree() const { return UnsafeToFree; }
    439   void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
    440 
    441   const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
    442   DiagnosticsEngine &getDiagnostics()             { return *Diagnostics; }
    443 
    444   const SourceManager &getSourceManager() const { return *SourceMgr; }
    445         SourceManager &getSourceManager()       { return *SourceMgr; }
    446 
    447   const Preprocessor &getPreprocessor() const { return *PP; }
    448         Preprocessor &getPreprocessor()       { return *PP; }
    449 
    450   const ASTContext &getASTContext() const { return *Ctx; }
    451         ASTContext &getASTContext()       { return *Ctx; }
    452 
    453   void setASTContext(ASTContext *ctx) { Ctx = ctx; }
    454 
    455   bool hasSema() const { return TheSema; }
    456   Sema &getSema() const {
    457     assert(TheSema && "ASTUnit does not have a Sema object!");
    458     return *TheSema;
    459   }
    460 
    461   const FileManager &getFileManager() const { return *FileMgr; }
    462         FileManager &getFileManager()       { return *FileMgr; }
    463 
    464   const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
    465 
    466   const std::string &getOriginalSourceFileName();
    467 
    468   /// \brief Add a temporary file that the ASTUnit depends on.
    469   ///
    470   /// This file will be erased when the ASTUnit is destroyed.
    471   void addTemporaryFile(const llvm::sys::Path &TempFile) {
    472     TemporaryFiles.push_back(TempFile);
    473   }
    474 
    475   bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
    476 
    477   bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
    478   void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
    479 
    480   void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; }
    481   ASTLocation getLastASTLocation() const { return LastLoc; }
    482 
    483 
    484   StringRef getMainFileName() const;
    485 
    486   typedef std::vector<Decl *>::iterator top_level_iterator;
    487 
    488   top_level_iterator top_level_begin() {
    489     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
    490     if (!TopLevelDeclsInPreamble.empty())
    491       RealizeTopLevelDeclsFromPreamble();
    492     return TopLevelDecls.begin();
    493   }
    494 
    495   top_level_iterator top_level_end() {
    496     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
    497     if (!TopLevelDeclsInPreamble.empty())
    498       RealizeTopLevelDeclsFromPreamble();
    499     return TopLevelDecls.end();
    500   }
    501 
    502   std::size_t top_level_size() const {
    503     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
    504     return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
    505   }
    506 
    507   bool top_level_empty() const {
    508     assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
    509     return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
    510   }
    511 
    512   /// \brief Add a new top-level declaration.
    513   void addTopLevelDecl(Decl *D) {
    514     TopLevelDecls.push_back(D);
    515   }
    516 
    517   /// \brief Add a new top-level declaration, identified by its ID in
    518   /// the precompiled preamble.
    519   void addTopLevelDeclFromPreamble(serialization::DeclID D) {
    520     TopLevelDeclsInPreamble.push_back(D);
    521   }
    522 
    523   /// \brief Retrieve a reference to the current top-level name hash value.
    524   ///
    525   /// Note: This is used internally by the top-level tracking action
    526   unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
    527 
    528   /// \brief Get the source location for the given file:line:col triplet.
    529   ///
    530   /// The difference with SourceManager::getLocation is that this method checks
    531   /// whether the requested location points inside the precompiled preamble
    532   /// in which case the returned source location will be a "loaded" one.
    533   SourceLocation getLocation(const FileEntry *File,
    534                              unsigned Line, unsigned Col) const;
    535 
    536   /// \brief Get the source location for the given file:offset pair.
    537   SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
    538 
    539   /// \brief If \arg Loc is a loaded location from the preamble, returns
    540   /// the corresponding local location of the main file, otherwise it returns
    541   /// \arg Loc.
    542   SourceLocation mapLocationFromPreamble(SourceLocation Loc);
    543 
    544   /// \brief If \arg Loc is a local location of the main file but inside the
    545   /// preamble chunk, returns the corresponding loaded location from the
    546   /// preamble, otherwise it returns \arg Loc.
    547   SourceLocation mapLocationToPreamble(SourceLocation Loc);
    548 
    549   /// \brief \see mapLocationFromPreamble.
    550   SourceRange mapRangeFromPreamble(SourceRange R) {
    551     return SourceRange(mapLocationFromPreamble(R.getBegin()),
    552                        mapLocationFromPreamble(R.getEnd()));
    553   }
    554 
    555   /// \brief \see mapLocationToPreamble.
    556   SourceRange mapRangeToPreamble(SourceRange R) {
    557     return SourceRange(mapLocationToPreamble(R.getBegin()),
    558                        mapLocationToPreamble(R.getEnd()));
    559   }
    560 
    561   // Retrieve the diagnostics associated with this AST
    562   typedef const StoredDiagnostic *stored_diag_iterator;
    563   stored_diag_iterator stored_diag_begin() const {
    564     return StoredDiagnostics.begin();
    565   }
    566   stored_diag_iterator stored_diag_end() const {
    567     return StoredDiagnostics.end();
    568   }
    569   unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
    570 
    571   SmallVector<StoredDiagnostic, 4> &getStoredDiagnostics() {
    572     return StoredDiagnostics;
    573   }
    574 
    575   typedef std::vector<CachedCodeCompletionResult>::iterator
    576     cached_completion_iterator;
    577 
    578   cached_completion_iterator cached_completion_begin() {
    579     return CachedCompletionResults.begin();
    580   }
    581 
    582   cached_completion_iterator cached_completion_end() {
    583     return CachedCompletionResults.end();
    584   }
    585 
    586   unsigned cached_completion_size() const {
    587     return CachedCompletionResults.size();
    588   }
    589 
    590   llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
    591                                        std::string *ErrorStr = 0);
    592 
    593   /// \brief Determine what kind of translation unit this AST represents.
    594   TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
    595 
    596   typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
    597       FilenameOrMemBuf;
    598   /// \brief A mapping from a file name to the memory buffer that stores the
    599   /// remapped contents of that file.
    600   typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
    601 
    602   /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
    603   static ASTUnit *create(CompilerInvocation *CI,
    604                          llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags);
    605 
    606   /// \brief Create a ASTUnit from an AST file.
    607   ///
    608   /// \param Filename - The AST file to load.
    609   ///
    610   /// \param Diags - The diagnostics engine to use for reporting errors; its
    611   /// lifetime is expected to extend past that of the returned ASTUnit.
    612   ///
    613   /// \returns - The initialized ASTUnit or null if the AST failed to load.
    614   static ASTUnit *LoadFromASTFile(const std::string &Filename,
    615                               llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
    616                                   const FileSystemOptions &FileSystemOpts,
    617                                   bool OnlyLocalDecls = false,
    618                                   RemappedFile *RemappedFiles = 0,
    619                                   unsigned NumRemappedFiles = 0,
    620                                   bool CaptureDiagnostics = false);
    621 
    622 private:
    623   /// \brief Helper function for \c LoadFromCompilerInvocation() and
    624   /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
    625   ///
    626   /// \param PrecompilePreamble Whether to precompile the preamble of this
    627   /// translation unit, to improve the performance of reparsing.
    628   ///
    629   /// \returns \c true if a catastrophic failure occurred (which means that the
    630   /// \c ASTUnit itself is invalid), or \c false otherwise.
    631   bool LoadFromCompilerInvocation(bool PrecompilePreamble);
    632 
    633 public:
    634 
    635   /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
    636   /// object, by invoking the optionally provided ASTFrontendAction.
    637   ///
    638   /// \param CI - The compiler invocation to use; it must have exactly one input
    639   /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
    640   ///
    641   /// \param Diags - The diagnostics engine to use for reporting errors; its
    642   /// lifetime is expected to extend past that of the returned ASTUnit.
    643   ///
    644   /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
    645   /// transfered.
    646   ///
    647   /// \param Unit - optionally an already created ASTUnit. Its ownership is not
    648   /// transfered.
    649   static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
    650                               llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
    651                                              ASTFrontendAction *Action = 0,
    652                                              ASTUnit *Unit = 0);
    653 
    654   /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
    655   /// CompilerInvocation object.
    656   ///
    657   /// \param CI - The compiler invocation to use; it must have exactly one input
    658   /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
    659   ///
    660   /// \param Diags - The diagnostics engine to use for reporting errors; its
    661   /// lifetime is expected to extend past that of the returned ASTUnit.
    662   //
    663   // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
    664   // shouldn't need to specify them at construction time.
    665   static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
    666                               llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
    667                                              bool OnlyLocalDecls = false,
    668                                              bool CaptureDiagnostics = false,
    669                                              bool PrecompilePreamble = false,
    670                                       TranslationUnitKind TUKind = TU_Complete,
    671                                        bool CacheCodeCompletionResults = false,
    672                                        bool NestedMacroExpansions = true);
    673 
    674   /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
    675   /// arguments, which must specify exactly one source file.
    676   ///
    677   /// \param ArgBegin - The beginning of the argument vector.
    678   ///
    679   /// \param ArgEnd - The end of the argument vector.
    680   ///
    681   /// \param Diags - The diagnostics engine to use for reporting errors; its
    682   /// lifetime is expected to extend past that of the returned ASTUnit.
    683   ///
    684   /// \param ResourceFilesPath - The path to the compiler resource files.
    685   //
    686   // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
    687   // shouldn't need to specify them at construction time.
    688   static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
    689                                       const char **ArgEnd,
    690                               llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
    691                                       StringRef ResourceFilesPath,
    692                                       bool OnlyLocalDecls = false,
    693                                       bool CaptureDiagnostics = false,
    694                                       RemappedFile *RemappedFiles = 0,
    695                                       unsigned NumRemappedFiles = 0,
    696                                       bool RemappedFilesKeepOriginalName = true,
    697                                       bool PrecompilePreamble = false,
    698                                       TranslationUnitKind TUKind = TU_Complete,
    699                                       bool CacheCodeCompletionResults = false,
    700                                       bool NestedMacroExpansions = true);
    701 
    702   /// \brief Reparse the source files using the same command-line options that
    703   /// were originally used to produce this translation unit.
    704   ///
    705   /// \returns True if a failure occurred that causes the ASTUnit not to
    706   /// contain any translation-unit information, false otherwise.
    707   bool Reparse(RemappedFile *RemappedFiles = 0,
    708                unsigned NumRemappedFiles = 0);
    709 
    710   /// \brief Perform code completion at the given file, line, and
    711   /// column within this translation unit.
    712   ///
    713   /// \param File The file in which code completion will occur.
    714   ///
    715   /// \param Line The line at which code completion will occur.
    716   ///
    717   /// \param Column The column at which code completion will occur.
    718   ///
    719   /// \param IncludeMacros Whether to include macros in the code-completion
    720   /// results.
    721   ///
    722   /// \param IncludeCodePatterns Whether to include code patterns (such as a
    723   /// for loop) in the code-completion results.
    724   ///
    725   /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
    726   /// OwnedBuffers parameters are all disgusting hacks. They will go away.
    727   void CodeComplete(StringRef File, unsigned Line, unsigned Column,
    728                     RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
    729                     bool IncludeMacros, bool IncludeCodePatterns,
    730                     CodeCompleteConsumer &Consumer,
    731                     DiagnosticsEngine &Diag, LangOptions &LangOpts,
    732                     SourceManager &SourceMgr, FileManager &FileMgr,
    733                     SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
    734               SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
    735 
    736   /// \brief Save this translation unit to a file with the given name.
    737   ///
    738   /// \returns An indication of whether the save was successful or not.
    739   CXSaveError Save(StringRef File);
    740 
    741   /// \brief Serialize this translation unit with the given output stream.
    742   ///
    743   /// \returns True if an error occurred, false otherwise.
    744   bool serialize(raw_ostream &OS);
    745 
    746   virtual ModuleKey loadModule(SourceLocation ImportLoc,
    747                                IdentifierInfo &ModuleName,
    748                                SourceLocation ModuleNameLoc) {
    749     // ASTUnit doesn't know how to load modules (not that this matters).
    750     return 0;
    751   }
    752 };
    753 
    754 } // namespace clang
    755 
    756 #endif
    757