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