ASTUnit.h revision 5ebcb20b0331a6e64c213f0bb5f4bed9a9e8eb34
19682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//===--- ASTUnit.h - ASTUnit utility ----------------------------*- C++ -*-===//
29682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//
39682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//                     The LLVM Compiler Infrastructure
49682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//
59682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall// This file is distributed under the University of Illinois Open Source
69682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall// License. See LICENSE.TXT for details.
79682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//
89682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//===----------------------------------------------------------------------===//
99682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//
109682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall// ASTUnit utility class.
119682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//
129682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall//===----------------------------------------------------------------------===//
139682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
149682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H
159682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#define LLVM_CLANG_FRONTEND_ASTUNIT_H
169682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
179682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang-c/Index.h"
189682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/AST/ASTContext.h"
199682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Basic/FileManager.h"
209682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Basic/FileSystemOptions.h"
219682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Basic/LangOptions.h"
229682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Basic/SourceManager.h"
239682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Basic/TargetOptions.h"
249682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Lex/HeaderSearchOptions.h"
259682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Lex/ModuleLoader.h"
269682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Lex/PreprocessingRecord.h"
279682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Sema/CodeCompleteConsumer.h"
289682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Sema/Sema.h"
299682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "clang/Serialization/ASTBitCodes.h"
309682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "llvm/ADT/IntrusiveRefCntPtr.h"
319682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "llvm/ADT/OwningPtr.h"
329682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "llvm/ADT/SmallVector.h"
339682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "llvm/ADT/StringMap.h"
349682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include "llvm/Support/Path.h"
359682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include <cassert>
369682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include <map>
379682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include <string>
389682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include <sys/types.h>
399682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include <utility>
409682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall#include <vector>
419682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
429682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallnamespace llvm {
439682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  class MemoryBuffer;
449682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall}
459682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
469682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallnamespace clang {
479682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass ASTContext;
489682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass ASTReader;
499682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass CodeCompleteConsumer;
509682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass CompilerInvocation;
519682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass CompilerInstance;
529682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass Decl;
539682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass DiagnosticsEngine;
549682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass FileEntry;
559682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass FileManager;
569682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass HeaderSearch;
579682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass Preprocessor;
589682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass SourceManager;
599682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass TargetInfo;
609682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass ASTFrontendAction;
619682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass ASTDeserializationListener;
629682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
639682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall/// \brief Utility class for loading a ASTContext from an AST file.
649682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall///
659682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallclass ASTUnit : public ModuleLoader {
669682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallprivate:
679682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<LangOptions>         LangOpts;
689682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<DiagnosticsEngine>   Diagnostics;
699682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<FileManager>         FileMgr;
709682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<SourceManager>       SourceMgr;
719682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  OwningPtr<HeaderSearch>                 HeaderInfo;
729682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<TargetInfo>          Target;
739682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<Preprocessor>        PP;
749682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<ASTContext>          Ctx;
759682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<TargetOptions>       TargetOpts;
769682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<HeaderSearchOptions> HSOpts;
779682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  ASTReader *Reader;
789682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
799682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  struct ASTWriterData;
809682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  OwningPtr<ASTWriterData> WriterData;
819682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
829682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  FileSystemOptions FileSystemOpts;
839682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
849682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The AST consumer that received information about the translation
859682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// unit as it was parsed or loaded.
869682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  OwningPtr<ASTConsumer> Consumer;
879682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
889682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The semantic analysis object used to type-check the translation
899682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// unit.
909682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  OwningPtr<Sema> TheSema;
919682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
929682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// Optional owned invocation, just used to make the invocation used in
939682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// LoadFromCommandLine available.
949682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  IntrusiveRefCntPtr<CompilerInvocation> Invocation;
959682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
969682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  // OnlyLocalDecls - when true, walking this AST should only visit declarations
979682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  // that come from the AST itself, not from included precompiled headers.
989682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  // FIXME: This is temporary; eventually, CIndex will always do this.
999682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool                              OnlyLocalDecls;
1009682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1019682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Whether to capture any diagnostics produced.
1029682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool CaptureDiagnostics;
1039682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1049682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Track whether the main file was loaded from an AST or not.
1059682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool MainFileIsAST;
1069682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1079682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief What kind of translation unit this AST represents.
1089682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  TranslationUnitKind TUKind;
1099682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1109682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Whether we should time each operation.
1119682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool WantTiming;
1129682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1139682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Whether the ASTUnit should delete the remapped buffers.
1149682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool OwnsRemappedFileBuffers;
1159682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1169682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// Track the top-level decls which appeared in an ASTUnit which was loaded
1179682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// from a source file.
1189682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  //
1199682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  // FIXME: This is just an optimization hack to avoid deserializing large parts
1209682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  // of a PCH file when using the Index library on an ASTUnit loaded from
1219682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  // source. In the long term we should make the Index library use efficient and
1229682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  // more scalable search mechanisms.
1239682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  std::vector<Decl*> TopLevelDecls;
1249682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1259682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
1269682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
1279682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
1289682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1299682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Map from FileID to the file-level declarations that it contains.
1309682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// The files and decls are only local (and non-preamble) ones.
1319682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  FileDeclsTy FileDecls;
1329682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1339682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// The name of the original source file used to generate this ASTUnit.
1349682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  std::string OriginalSourceFile;
1359682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1369682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The set of diagnostics produced when creating the preamble.
1379682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  SmallVector<StoredDiagnostic, 4> PreambleDiagnostics;
1389682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1399682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The set of diagnostics produced when creating this
1409682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// translation unit.
1419682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
1429682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1439682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The set of diagnostics produced when failing to parse, e.g. due
1449682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// to failure to load the PCH.
1459682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
1469682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1479682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The number of stored diagnostics that come from the driver
1489682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// itself.
1499682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  ///
1509682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// Diagnostics that come from the driver are retained from one parse to
1519682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// the next.
1529682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  unsigned NumStoredDiagnosticsFromDriver;
1539682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1549682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Counter that determines when we want to try building a
1559682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// precompiled preamble.
1569682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  ///
1579682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// If zero, we will never build a precompiled preamble. Otherwise,
1589682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// it's treated as a counter that decrements each time we reparse
1599682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// without the benefit of a precompiled preamble. When it hits 1,
1609682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// we'll attempt to rebuild the precompiled header. This way, if
1619682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// building the precompiled preamble fails, we won't try again for
1629682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// some number of calls.
1639682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  unsigned PreambleRebuildCounter;
1649682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1659682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallpublic:
1669682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  class PreambleData {
1679682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    const FileEntry *File;
1689682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    std::vector<char> Buffer;
1699682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    mutable unsigned NumLines;
1709682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1719682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  public:
1729682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    PreambleData() : File(0), NumLines(0) { }
1739682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1749682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    void assign(const FileEntry *F, const char *begin, const char *end) {
1759682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall      File = F;
1769682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall      Buffer.assign(begin, end);
1779682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall      NumLines = 0;
1789682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    }
1799682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1809682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    void clear() { Buffer.clear(); File = 0; NumLines = 0; }
1819682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1829682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    size_t size() const { return Buffer.size(); }
1839682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    bool empty() const { return Buffer.empty(); }
1849682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1859682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    const char *getBufferStart() const { return &Buffer[0]; }
1869682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1879682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    unsigned getNumLines() const {
1889682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall      if (NumLines)
1899682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall        return NumLines;
1909682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall      countLines();
1919682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall      return NumLines;
1929682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    }
1939682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1949682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    SourceRange getSourceRange(const SourceManager &SM) const {
1959682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall      SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
1969682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall      return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
1979682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    }
1989682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
1999682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  private:
2009682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    void countLines() const;
2019682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  };
2029682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2039682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  const PreambleData &getPreambleData() const {
2049682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    return Preamble;
2059682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  }
2069682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2079682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallprivate:
2089682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2099682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The contents of the preamble that has been precompiled to
2109682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \c PreambleFile.
2119682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  PreambleData Preamble;
2129682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2139682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Whether the preamble ends at the start of a new line.
2149682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  ///
2159682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// Used to inform the lexer as to whether it's starting at the beginning of
2169682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// a line after skipping the preamble.
2179682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool PreambleEndsAtStartOfLine;
2189682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2199682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The size of the source buffer that we've reserved for the main
2209682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// file within the precompiled preamble.
2219682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  unsigned PreambleReservedSize;
2229682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2239682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Keeps track of the files that were used when computing the
2249682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// preamble, with both their buffer size and their modification time.
2259682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  ///
2269682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// If any of the files have changed from one compile to the next,
2279682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// the preamble must be thrown away.
2289682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble;
2299682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2309682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief When non-NULL, this is the buffer used to store the contents of
2319682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// the main file when it has been padded for use with the precompiled
2329682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// preamble.
2339682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  llvm::MemoryBuffer *SavedMainFileBuffer;
2349682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2359682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief When non-NULL, this is the buffer used to store the
2369682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// contents of the preamble when it has been padded to build the
2379682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// precompiled preamble.
2389682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  llvm::MemoryBuffer *PreambleBuffer;
2399682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2409682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The number of warnings that occurred while parsing the preamble.
2419682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  ///
2429682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// This value will be used to restore the state of the \c DiagnosticsEngine
2439682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// object when re-using the precompiled preamble. Note that only the
2449682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// number of warnings matters, since we will not save the preamble
2459682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// when any errors are present.
2469682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  unsigned NumWarningsInPreamble;
2479682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2489682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief A list of the serialization ID numbers for each of the top-level
2499682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// declarations parsed within the precompiled preamble.
2509682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
2519682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2529682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Whether we should be caching code-completion results.
2539682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool ShouldCacheCodeCompletionResults : 1;
2549682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2559682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief Whether to include brief documentation within the set of code
2569682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// completions cached.
2579682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool IncludeBriefCommentsInCodeCompletion : 1;
2589682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2599682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief True if non-system source files should be treated as volatile
2609682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// (likely to change while trying to use them).
2619682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  bool UserFilesAreVolatile : 1;
2629682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2639682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief The language options used when we load an AST file.
2649682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  LangOptions ASTFileLangOpts;
2659682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2669682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
2679682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall                             const char **ArgBegin, const char **ArgEnd,
2689682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall                             ASTUnit &AST, bool CaptureDiagnostics);
2699682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2709682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
2719682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall                                  SourceManager &SrcMan,
2729682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall                      const SmallVectorImpl<StoredDiagnostic> &Diags,
2739682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall                            SmallVectorImpl<StoredDiagnostic> &Out);
2749682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2759682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  void clearFileLevelDecls();
2769682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall
2779682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hallpublic:
2789682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// \brief A cached code-completion result, which may be introduced in one of
2799682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  /// many different contexts.
2809682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall  struct CachedCodeCompletionResult {
2819682c8870b8ff5e4ac2e4c70b759f791c6f38c1fJesse Hall    /// \brief The code-completion string corresponding to this completion
282    /// result.
283    CodeCompletionString *Completion;
284
285    /// \brief A bitmask that indicates which code-completion contexts should
286    /// contain this completion result.
287    ///
288    /// The bits in the bitmask correspond to the values of
289    /// CodeCompleteContext::Kind. To map from a completion context kind to a
290    /// bit, shift 1 by that number of bits. Many completions can occur in
291    /// several different contexts.
292    uint64_t ShowInContexts;
293
294    /// \brief The priority given to this code-completion result.
295    unsigned Priority;
296
297    /// \brief The libclang cursor kind corresponding to this code-completion
298    /// result.
299    CXCursorKind Kind;
300
301    /// \brief The availability of this code-completion result.
302    CXAvailabilityKind Availability;
303
304    /// \brief The simplified type class for a non-macro completion result.
305    SimplifiedTypeClass TypeClass;
306
307    /// \brief The type of a non-macro completion result, stored as a unique
308    /// integer used by the string map of cached completion types.
309    ///
310    /// This value will be zero if the type is not known, or a unique value
311    /// determined by the formatted type string. Se \c CachedCompletionTypes
312    /// for more information.
313    unsigned Type;
314  };
315
316  /// \brief Retrieve the mapping from formatted type names to unique type
317  /// identifiers.
318  llvm::StringMap<unsigned> &getCachedCompletionTypes() {
319    return CachedCompletionTypes;
320  }
321
322  /// \brief Retrieve the allocator used to cache global code completions.
323  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
324  getCachedCompletionAllocator() {
325    return CachedCompletionAllocator;
326  }
327
328  CodeCompletionTUInfo &getCodeCompletionTUInfo() {
329    if (!CCTUInfo)
330      CCTUInfo.reset(new CodeCompletionTUInfo(
331                                            new GlobalCodeCompletionAllocator));
332    return *CCTUInfo;
333  }
334
335private:
336  /// \brief Allocator used to store cached code completions.
337  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
338    CachedCompletionAllocator;
339
340  OwningPtr<CodeCompletionTUInfo> CCTUInfo;
341
342  /// \brief The set of cached code-completion results.
343  std::vector<CachedCodeCompletionResult> CachedCompletionResults;
344
345  /// \brief A mapping from the formatted type name to a unique number for that
346  /// type, which is used for type equality comparisons.
347  llvm::StringMap<unsigned> CachedCompletionTypes;
348
349  /// \brief A string hash of the top-level declaration and macro definition
350  /// names processed the last time that we reparsed the file.
351  ///
352  /// This hash value is used to determine when we need to refresh the
353  /// global code-completion cache.
354  unsigned CompletionCacheTopLevelHashValue;
355
356  /// \brief A string hash of the top-level declaration and macro definition
357  /// names processed the last time that we reparsed the precompiled preamble.
358  ///
359  /// This hash value is used to determine when we need to refresh the
360  /// global code-completion cache after a rebuild of the precompiled preamble.
361  unsigned PreambleTopLevelHashValue;
362
363  /// \brief The current hash value for the top-level declaration and macro
364  /// definition names
365  unsigned CurrentTopLevelHashValue;
366
367  /// \brief Bit used by CIndex to mark when a translation unit may be in an
368  /// inconsistent state, and is not safe to free.
369  unsigned UnsafeToFree : 1;
370
371  /// \brief Cache any "global" code-completion results, so that we can avoid
372  /// recomputing them with each completion.
373  void CacheCodeCompletionResults();
374
375  /// \brief Clear out and deallocate
376  void ClearCachedCompletionResults();
377
378  ASTUnit(const ASTUnit &) LLVM_DELETED_FUNCTION;
379  void operator=(const ASTUnit &) LLVM_DELETED_FUNCTION;
380
381  explicit ASTUnit(bool MainFileIsAST);
382
383  void CleanTemporaryFiles();
384  bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
385
386  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
387  ComputePreamble(CompilerInvocation &Invocation,
388                  unsigned MaxLines, bool &CreatedBuffer);
389
390  llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
391                               const CompilerInvocation &PreambleInvocationIn,
392                                                     bool AllowRebuild = true,
393                                                        unsigned MaxLines = 0);
394  void RealizeTopLevelDeclsFromPreamble();
395
396  /// \brief Transfers ownership of the objects (like SourceManager) from
397  /// \param CI to this ASTUnit.
398  void transferASTDataFromCompilerInstance(CompilerInstance &CI);
399
400  /// \brief Allows us to assert that ASTUnit is not being used concurrently,
401  /// which is not supported.
402  ///
403  /// Clients should create instances of the ConcurrencyCheck class whenever
404  /// using the ASTUnit in a way that isn't intended to be concurrent, which is
405  /// just about any usage.
406  /// Becomes a noop in release mode; only useful for debug mode checking.
407  class ConcurrencyState {
408#ifndef NDEBUG
409    void *Mutex; // a llvm::sys::MutexImpl in debug;
410#endif
411
412  public:
413    ConcurrencyState();
414    ~ConcurrencyState();
415
416    void start();
417    void finish();
418  };
419  ConcurrencyState ConcurrencyCheckValue;
420
421public:
422  class ConcurrencyCheck {
423    ASTUnit &Self;
424
425  public:
426    explicit ConcurrencyCheck(ASTUnit &Self)
427      : Self(Self)
428    {
429      Self.ConcurrencyCheckValue.start();
430    }
431    ~ConcurrencyCheck() {
432      Self.ConcurrencyCheckValue.finish();
433    }
434  };
435  friend class ConcurrencyCheck;
436
437  ~ASTUnit();
438
439  bool isMainFileAST() const { return MainFileIsAST; }
440
441  bool isUnsafeToFree() const { return UnsafeToFree; }
442  void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
443
444  const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
445  DiagnosticsEngine &getDiagnostics()             { return *Diagnostics; }
446
447  const SourceManager &getSourceManager() const { return *SourceMgr; }
448        SourceManager &getSourceManager()       { return *SourceMgr; }
449
450  const Preprocessor &getPreprocessor() const { return *PP; }
451        Preprocessor &getPreprocessor()       { return *PP; }
452
453  const ASTContext &getASTContext() const { return *Ctx; }
454        ASTContext &getASTContext()       { return *Ctx; }
455
456  void setASTContext(ASTContext *ctx) { Ctx = ctx; }
457  void setPreprocessor(Preprocessor *pp);
458
459  bool hasSema() const { return TheSema; }
460  Sema &getSema() const {
461    assert(TheSema && "ASTUnit does not have a Sema object!");
462    return *TheSema;
463  }
464
465  const FileManager &getFileManager() const { return *FileMgr; }
466        FileManager &getFileManager()       { return *FileMgr; }
467
468  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
469
470  StringRef getOriginalSourceFileName() {
471    return OriginalSourceFile;
472  }
473
474  ASTDeserializationListener *getDeserializationListener();
475
476  /// \brief Add a temporary file that the ASTUnit depends on.
477  ///
478  /// This file will be erased when the ASTUnit is destroyed.
479  void addTemporaryFile(const llvm::sys::Path &TempFile);
480
481  bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
482
483  bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
484  void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
485
486  StringRef getMainFileName() const;
487
488  typedef std::vector<Decl *>::iterator top_level_iterator;
489
490  top_level_iterator top_level_begin() {
491    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
492    if (!TopLevelDeclsInPreamble.empty())
493      RealizeTopLevelDeclsFromPreamble();
494    return TopLevelDecls.begin();
495  }
496
497  top_level_iterator top_level_end() {
498    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
499    if (!TopLevelDeclsInPreamble.empty())
500      RealizeTopLevelDeclsFromPreamble();
501    return TopLevelDecls.end();
502  }
503
504  std::size_t top_level_size() const {
505    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
506    return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
507  }
508
509  bool top_level_empty() const {
510    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
511    return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
512  }
513
514  /// \brief Add a new top-level declaration.
515  void addTopLevelDecl(Decl *D) {
516    TopLevelDecls.push_back(D);
517  }
518
519  /// \brief Add a new local file-level declaration.
520  void addFileLevelDecl(Decl *D);
521
522  /// \brief Get the decls that are contained in a file in the Offset/Length
523  /// range. \p Length can be 0 to indicate a point at \p Offset instead of
524  /// a range.
525  void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
526                           SmallVectorImpl<Decl *> &Decls);
527
528  /// \brief Add a new top-level declaration, identified by its ID in
529  /// the precompiled preamble.
530  void addTopLevelDeclFromPreamble(serialization::DeclID D) {
531    TopLevelDeclsInPreamble.push_back(D);
532  }
533
534  /// \brief Retrieve a reference to the current top-level name hash value.
535  ///
536  /// Note: This is used internally by the top-level tracking action
537  unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
538
539  /// \brief Get the source location for the given file:line:col triplet.
540  ///
541  /// The difference with SourceManager::getLocation is that this method checks
542  /// whether the requested location points inside the precompiled preamble
543  /// in which case the returned source location will be a "loaded" one.
544  SourceLocation getLocation(const FileEntry *File,
545                             unsigned Line, unsigned Col) const;
546
547  /// \brief Get the source location for the given file:offset pair.
548  SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
549
550  /// \brief If \p Loc is a loaded location from the preamble, returns
551  /// the corresponding local location of the main file, otherwise it returns
552  /// \p Loc.
553  SourceLocation mapLocationFromPreamble(SourceLocation Loc);
554
555  /// \brief If \p Loc is a local location of the main file but inside the
556  /// preamble chunk, returns the corresponding loaded location from the
557  /// preamble, otherwise it returns \p Loc.
558  SourceLocation mapLocationToPreamble(SourceLocation Loc);
559
560  bool isInPreambleFileID(SourceLocation Loc);
561  bool isInMainFileID(SourceLocation Loc);
562  SourceLocation getStartOfMainFileID();
563  SourceLocation getEndOfPreambleFileID();
564
565  /// \see mapLocationFromPreamble.
566  SourceRange mapRangeFromPreamble(SourceRange R) {
567    return SourceRange(mapLocationFromPreamble(R.getBegin()),
568                       mapLocationFromPreamble(R.getEnd()));
569  }
570
571  /// \see mapLocationToPreamble.
572  SourceRange mapRangeToPreamble(SourceRange R) {
573    return SourceRange(mapLocationToPreamble(R.getBegin()),
574                       mapLocationToPreamble(R.getEnd()));
575  }
576
577  // Retrieve the diagnostics associated with this AST
578  typedef StoredDiagnostic *stored_diag_iterator;
579  typedef const StoredDiagnostic *stored_diag_const_iterator;
580  stored_diag_const_iterator stored_diag_begin() const {
581    return StoredDiagnostics.begin();
582  }
583  stored_diag_iterator stored_diag_begin() {
584    return StoredDiagnostics.begin();
585  }
586  stored_diag_const_iterator stored_diag_end() const {
587    return StoredDiagnostics.end();
588  }
589  stored_diag_iterator stored_diag_end() {
590    return StoredDiagnostics.end();
591  }
592  unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
593
594  stored_diag_iterator stored_diag_afterDriver_begin() {
595    if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
596      NumStoredDiagnosticsFromDriver = 0;
597    return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
598  }
599
600  typedef std::vector<CachedCodeCompletionResult>::iterator
601    cached_completion_iterator;
602
603  cached_completion_iterator cached_completion_begin() {
604    return CachedCompletionResults.begin();
605  }
606
607  cached_completion_iterator cached_completion_end() {
608    return CachedCompletionResults.end();
609  }
610
611  unsigned cached_completion_size() const {
612    return CachedCompletionResults.size();
613  }
614
615  /// \brief Returns an iterator range for the local preprocessing entities
616  /// of the local Preprocessor, if this is a parsed source file, or the loaded
617  /// preprocessing entities of the primary module if this is an AST file.
618  std::pair<PreprocessingRecord::iterator, PreprocessingRecord::iterator>
619    getLocalPreprocessingEntities() const;
620
621  /// \brief Type for a function iterating over a number of declarations.
622  /// \returns true to continue iteration and false to abort.
623  typedef bool (*DeclVisitorFn)(void *context, const Decl *D);
624
625  /// \brief Iterate over local declarations (locally parsed if this is a parsed
626  /// source file or the loaded declarations of the primary module if this is an
627  /// AST file).
628  /// \returns true if the iteration was complete or false if it was aborted.
629  bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
630
631  /// \brief Get the PCH file if one was included.
632  const FileEntry *getPCHFile();
633
634  /// \brief Returns true if the ASTUnit was constructed from a serialized
635  /// module file.
636  bool isModuleFile();
637
638  llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
639                                       std::string *ErrorStr = 0);
640
641  /// \brief Determine what kind of translation unit this AST represents.
642  TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
643
644  typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
645      FilenameOrMemBuf;
646  /// \brief A mapping from a file name to the memory buffer that stores the
647  /// remapped contents of that file.
648  typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
649
650  /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
651  static ASTUnit *create(CompilerInvocation *CI,
652                         IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
653                         bool CaptureDiagnostics,
654                         bool UserFilesAreVolatile);
655
656  /// \brief Create a ASTUnit from an AST file.
657  ///
658  /// \param Filename - The AST file to load.
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  /// \returns - The initialized ASTUnit or null if the AST failed to load.
664  static ASTUnit *LoadFromASTFile(const std::string &Filename,
665                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
666                                  const FileSystemOptions &FileSystemOpts,
667                                  bool OnlyLocalDecls = false,
668                                  RemappedFile *RemappedFiles = 0,
669                                  unsigned NumRemappedFiles = 0,
670                                  bool CaptureDiagnostics = false,
671                                  bool AllowPCHWithCompilerErrors = false,
672                                  bool UserFilesAreVolatile = false);
673
674private:
675  /// \brief Helper function for \c LoadFromCompilerInvocation() and
676  /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
677  ///
678  /// \param PrecompilePreamble Whether to precompile the preamble of this
679  /// translation unit, to improve the performance of reparsing.
680  ///
681  /// \returns \c true if a catastrophic failure occurred (which means that the
682  /// \c ASTUnit itself is invalid), or \c false otherwise.
683  bool LoadFromCompilerInvocation(bool PrecompilePreamble);
684
685public:
686
687  /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
688  /// object, by invoking the optionally provided ASTFrontendAction.
689  ///
690  /// \param CI - The compiler invocation to use; it must have exactly one input
691  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
692  ///
693  /// \param Diags - The diagnostics engine to use for reporting errors; its
694  /// lifetime is expected to extend past that of the returned ASTUnit.
695  ///
696  /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
697  /// transfered.
698  ///
699  /// \param Unit - optionally an already created ASTUnit. Its ownership is not
700  /// transfered.
701  ///
702  /// \param Persistent - if true the returned ASTUnit will be complete.
703  /// false means the caller is only interested in getting info through the
704  /// provided \see Action.
705  ///
706  /// \param ErrAST - If non-null and parsing failed without any AST to return
707  /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
708  /// mainly to allow the caller to see the diagnostics.
709  /// This will only receive an ASTUnit if a new one was created. If an already
710  /// created ASTUnit was passed in \p Unit then the caller can check that.
711  ///
712  static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
713                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
714                                             ASTFrontendAction *Action = 0,
715                                             ASTUnit *Unit = 0,
716                                             bool Persistent = true,
717                                      StringRef ResourceFilesPath = StringRef(),
718                                             bool OnlyLocalDecls = false,
719                                             bool CaptureDiagnostics = false,
720                                             bool PrecompilePreamble = false,
721                                       bool CacheCodeCompletionResults = false,
722                              bool IncludeBriefCommentsInCodeCompletion = false,
723                                       bool UserFilesAreVolatile = false,
724                                       OwningPtr<ASTUnit> *ErrAST = 0);
725
726  /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
727  /// CompilerInvocation object.
728  ///
729  /// \param CI - The compiler invocation to use; it must have exactly one input
730  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
731  ///
732  /// \param Diags - The diagnostics engine to use for reporting errors; its
733  /// lifetime is expected to extend past that of the returned ASTUnit.
734  //
735  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
736  // shouldn't need to specify them at construction time.
737  static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
738                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
739                                             bool OnlyLocalDecls = false,
740                                             bool CaptureDiagnostics = false,
741                                             bool PrecompilePreamble = false,
742                                      TranslationUnitKind TUKind = TU_Complete,
743                                       bool CacheCodeCompletionResults = false,
744                            bool IncludeBriefCommentsInCodeCompletion = false,
745                                             bool UserFilesAreVolatile = false);
746
747  /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
748  /// arguments, which must specify exactly one source file.
749  ///
750  /// \param ArgBegin - The beginning of the argument vector.
751  ///
752  /// \param ArgEnd - The end of the argument vector.
753  ///
754  /// \param Diags - The diagnostics engine to use for reporting errors; its
755  /// lifetime is expected to extend past that of the returned ASTUnit.
756  ///
757  /// \param ResourceFilesPath - The path to the compiler resource files.
758  ///
759  /// \param ErrAST - If non-null and parsing failed without any AST to return
760  /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
761  /// mainly to allow the caller to see the diagnostics.
762  ///
763  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
764  // shouldn't need to specify them at construction time.
765  static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
766                                      const char **ArgEnd,
767                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
768                                      StringRef ResourceFilesPath,
769                                      bool OnlyLocalDecls = false,
770                                      bool CaptureDiagnostics = false,
771                                      RemappedFile *RemappedFiles = 0,
772                                      unsigned NumRemappedFiles = 0,
773                                      bool RemappedFilesKeepOriginalName = true,
774                                      bool PrecompilePreamble = false,
775                                      TranslationUnitKind TUKind = TU_Complete,
776                                      bool CacheCodeCompletionResults = false,
777                            bool IncludeBriefCommentsInCodeCompletion = false,
778                                      bool AllowPCHWithCompilerErrors = false,
779                                      bool SkipFunctionBodies = false,
780                                      bool UserFilesAreVolatile = false,
781                                      bool ForSerialization = false,
782                                      OwningPtr<ASTUnit> *ErrAST = 0);
783
784  /// \brief Reparse the source files using the same command-line options that
785  /// were originally used to produce this translation unit.
786  ///
787  /// \returns True if a failure occurred that causes the ASTUnit not to
788  /// contain any translation-unit information, false otherwise.
789  bool Reparse(RemappedFile *RemappedFiles = 0,
790               unsigned NumRemappedFiles = 0);
791
792  /// \brief Perform code completion at the given file, line, and
793  /// column within this translation unit.
794  ///
795  /// \param File The file in which code completion will occur.
796  ///
797  /// \param Line The line at which code completion will occur.
798  ///
799  /// \param Column The column at which code completion will occur.
800  ///
801  /// \param IncludeMacros Whether to include macros in the code-completion
802  /// results.
803  ///
804  /// \param IncludeCodePatterns Whether to include code patterns (such as a
805  /// for loop) in the code-completion results.
806  ///
807  /// \param IncludeBriefComments Whether to include brief documentation within
808  /// the set of code completions returned.
809  ///
810  /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
811  /// OwnedBuffers parameters are all disgusting hacks. They will go away.
812  void CodeComplete(StringRef File, unsigned Line, unsigned Column,
813                    RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
814                    bool IncludeMacros, bool IncludeCodePatterns,
815                    bool IncludeBriefComments,
816                    CodeCompleteConsumer &Consumer,
817                    DiagnosticsEngine &Diag, LangOptions &LangOpts,
818                    SourceManager &SourceMgr, FileManager &FileMgr,
819                    SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
820              SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
821
822  /// \brief Save this translation unit to a file with the given name.
823  ///
824  /// \returns true if there was a file error or false if the save was
825  /// successful.
826  bool Save(StringRef File);
827
828  /// \brief Serialize this translation unit with the given output stream.
829  ///
830  /// \returns True if an error occurred, false otherwise.
831  bool serialize(raw_ostream &OS);
832
833  virtual ModuleLoadResult loadModule(SourceLocation ImportLoc,
834                                      ModuleIdPath Path,
835                                      Module::NameVisibilityKind Visibility,
836                                      bool IsInclusionDirective) {
837    // ASTUnit doesn't know how to load modules (not that this matters).
838    return ModuleLoadResult();
839  }
840
841  virtual void makeModuleVisible(Module *Mod,
842                                 Module::NameVisibilityKind Visibility,
843                                 SourceLocation ImportLoc) { }
844
845};
846
847} // namespace clang
848
849#endif
850