ASTUnit.h revision 6f3ce979a7748fd117e6473d6272b16d643b6262
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 llvm::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  llvm::IntrusiveRefCntPtr<LangOptions>       LangOpts;
74  llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
75  llvm::IntrusiveRefCntPtr<FileManager>       FileMgr;
76  llvm::IntrusiveRefCntPtr<SourceManager>     SourceMgr;
77  llvm::OwningPtr<HeaderSearch>               HeaderInfo;
78  llvm::IntrusiveRefCntPtr<TargetInfo>        Target;
79  llvm::IntrusiveRefCntPtr<Preprocessor>      PP;
80  llvm::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  llvm::OwningPtr<ASTConsumer> Consumer;
88
89  /// \brief The semantic analysis object used to type-check the translation
90  /// unit.
91  llvm::OwningPtr<Sema> TheSema;
92
93  /// Optional owned invocation, just used to make the invocation used in
94  /// LoadFromCommandLine available.
95  llvm::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 Whether we want to include nested macro expansions in the
263  /// detailed preprocessing record.
264  bool NestedMacroExpansions;
265
266  /// \brief The language options used when we load an AST file.
267  LangOptions ASTFileLangOpts;
268
269  static void ConfigureDiags(llvm::IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
270                             const char **ArgBegin, const char **ArgEnd,
271                             ASTUnit &AST, bool CaptureDiagnostics);
272
273  void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
274                                  SourceManager &SrcMan,
275                      const SmallVectorImpl<StoredDiagnostic> &Diags,
276                            SmallVectorImpl<StoredDiagnostic> &Out);
277
278  void clearFileLevelDecls();
279
280public:
281  /// \brief A cached code-completion result, which may be introduced in one of
282  /// many different contexts.
283  struct CachedCodeCompletionResult {
284    /// \brief The code-completion string corresponding to this completion
285    /// result.
286    CodeCompletionString *Completion;
287
288    /// \brief A bitmask that indicates which code-completion contexts should
289    /// contain this completion result.
290    ///
291    /// The bits in the bitmask correspond to the values of
292    /// CodeCompleteContext::Kind. To map from a completion context kind to a
293    /// bit, subtract one from the completion context kind and shift 1 by that
294    /// number of bits. Many completions can occur in several different
295    /// contexts.
296    unsigned ShowInContexts;
297
298    /// \brief The priority given to this code-completion result.
299    unsigned Priority;
300
301    /// \brief The libclang cursor kind corresponding to this code-completion
302    /// result.
303    CXCursorKind Kind;
304
305    /// \brief The availability of this code-completion result.
306    CXAvailabilityKind Availability;
307
308    /// \brief The simplified type class for a non-macro completion result.
309    SimplifiedTypeClass TypeClass;
310
311    /// \brief The type of a non-macro completion result, stored as a unique
312    /// integer used by the string map of cached completion types.
313    ///
314    /// This value will be zero if the type is not known, or a unique value
315    /// determined by the formatted type string. Se \c CachedCompletionTypes
316    /// for more information.
317    unsigned Type;
318  };
319
320  /// \brief Retrieve the mapping from formatted type names to unique type
321  /// identifiers.
322  llvm::StringMap<unsigned> &getCachedCompletionTypes() {
323    return CachedCompletionTypes;
324  }
325
326  /// \brief Retrieve the allocator used to cache global code completions.
327  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
328  getCachedCompletionAllocator() {
329    return CachedCompletionAllocator;
330  }
331
332  /// \brief Retrieve the allocator used to cache global code completions.
333  /// Creates the allocator if it doesn't already exist.
334  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
335  getCursorCompletionAllocator() {
336    if (!CursorCompletionAllocator.getPtr()) {
337      CursorCompletionAllocator = new GlobalCodeCompletionAllocator;
338    }
339    return CursorCompletionAllocator;
340  }
341
342private:
343  /// \brief Allocator used to store cached code completions.
344  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
345    CachedCompletionAllocator;
346
347  /// \brief Allocator used to store code completions for arbitrary cursors.
348  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
349    CursorCompletionAllocator;
350
351  /// \brief The set of cached code-completion results.
352  std::vector<CachedCodeCompletionResult> CachedCompletionResults;
353
354  /// \brief A mapping from the formatted type name to a unique number for that
355  /// type, which is used for type equality comparisons.
356  llvm::StringMap<unsigned> CachedCompletionTypes;
357
358  /// \brief A string hash of the top-level declaration and macro definition
359  /// names processed the last time that we reparsed the file.
360  ///
361  /// This hash value is used to determine when we need to refresh the
362  /// global code-completion cache.
363  unsigned CompletionCacheTopLevelHashValue;
364
365  /// \brief A string hash of the top-level declaration and macro definition
366  /// names processed the last time that we reparsed the precompiled preamble.
367  ///
368  /// This hash value is used to determine when we need to refresh the
369  /// global code-completion cache after a rebuild of the precompiled preamble.
370  unsigned PreambleTopLevelHashValue;
371
372  /// \brief The current hash value for the top-level declaration and macro
373  /// definition names
374  unsigned CurrentTopLevelHashValue;
375
376  /// \brief Bit used by CIndex to mark when a translation unit may be in an
377  /// inconsistent state, and is not safe to free.
378  unsigned UnsafeToFree : 1;
379
380  /// \brief Cache any "global" code-completion results, so that we can avoid
381  /// recomputing them with each completion.
382  void CacheCodeCompletionResults();
383
384  /// \brief Clear out and deallocate
385  void ClearCachedCompletionResults();
386
387  ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT
388  ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT
389
390  explicit ASTUnit(bool MainFileIsAST);
391
392  void CleanTemporaryFiles();
393  bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
394
395  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
396  ComputePreamble(CompilerInvocation &Invocation,
397                  unsigned MaxLines, bool &CreatedBuffer);
398
399  llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
400                               const CompilerInvocation &PreambleInvocationIn,
401                                                     bool AllowRebuild = true,
402                                                        unsigned MaxLines = 0);
403  void RealizeTopLevelDeclsFromPreamble();
404
405  /// \brief Allows us to assert that ASTUnit is not being used concurrently,
406  /// which is not supported.
407  ///
408  /// Clients should create instances of the ConcurrencyCheck class whenever
409  /// using the ASTUnit in a way that isn't intended to be concurrent, which is
410  /// just about any usage.
411  /// Becomes a noop in release mode; only useful for debug mode checking.
412  class ConcurrencyState {
413    void *Mutex; // a llvm::sys::MutexImpl in debug;
414
415  public:
416    ConcurrencyState();
417    ~ConcurrencyState();
418
419    void start();
420    void finish();
421  };
422  ConcurrencyState ConcurrencyCheckValue;
423
424public:
425  class ConcurrencyCheck {
426    ASTUnit &Self;
427
428  public:
429    explicit ConcurrencyCheck(ASTUnit &Self)
430      : Self(Self)
431    {
432      Self.ConcurrencyCheckValue.start();
433    }
434    ~ConcurrencyCheck() {
435      Self.ConcurrencyCheckValue.finish();
436    }
437  };
438  friend class ConcurrencyCheck;
439
440  ~ASTUnit();
441
442  bool isMainFileAST() const { return MainFileIsAST; }
443
444  bool isUnsafeToFree() const { return UnsafeToFree; }
445  void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
446
447  const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
448  DiagnosticsEngine &getDiagnostics()             { return *Diagnostics; }
449
450  const SourceManager &getSourceManager() const { return *SourceMgr; }
451        SourceManager &getSourceManager()       { return *SourceMgr; }
452
453  const Preprocessor &getPreprocessor() const { return *PP; }
454        Preprocessor &getPreprocessor()       { return *PP; }
455
456  const ASTContext &getASTContext() const { return *Ctx; }
457        ASTContext &getASTContext()       { return *Ctx; }
458
459  void setASTContext(ASTContext *ctx) { Ctx = ctx; }
460
461  bool hasSema() const { return TheSema; }
462  Sema &getSema() const {
463    assert(TheSema && "ASTUnit does not have a Sema object!");
464    return *TheSema;
465  }
466
467  const FileManager &getFileManager() const { return *FileMgr; }
468        FileManager &getFileManager()       { return *FileMgr; }
469
470  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
471
472  const std::string &getOriginalSourceFileName();
473
474  /// \brief Add a temporary file that the ASTUnit depends on.
475  ///
476  /// This file will be erased when the ASTUnit is destroyed.
477  void addTemporaryFile(const llvm::sys::Path &TempFile);
478
479  bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
480
481  bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
482  void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
483
484  void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; }
485  ASTLocation getLastASTLocation() const { return LastLoc; }
486
487
488  StringRef getMainFileName() const;
489
490  typedef std::vector<Decl *>::iterator top_level_iterator;
491
492  top_level_iterator top_level_begin() {
493    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
494    if (!TopLevelDeclsInPreamble.empty())
495      RealizeTopLevelDeclsFromPreamble();
496    return TopLevelDecls.begin();
497  }
498
499  top_level_iterator top_level_end() {
500    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
501    if (!TopLevelDeclsInPreamble.empty())
502      RealizeTopLevelDeclsFromPreamble();
503    return TopLevelDecls.end();
504  }
505
506  std::size_t top_level_size() const {
507    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
508    return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
509  }
510
511  bool top_level_empty() const {
512    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
513    return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
514  }
515
516  /// \brief Add a new top-level declaration.
517  void addTopLevelDecl(Decl *D) {
518    TopLevelDecls.push_back(D);
519  }
520
521  /// \brief Add a new local file-level declaration.
522  void addFileLevelDecl(Decl *D);
523
524  /// \brief Get the decls that are contained in a file in the Offset/Length
525  /// range. \arg Length can be 0 to indicate a point at \arg Offset instead of
526  /// a range.
527  void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
528                           SmallVectorImpl<Decl *> &Decls);
529
530  /// \brief Add a new top-level declaration, identified by its ID in
531  /// the precompiled preamble.
532  void addTopLevelDeclFromPreamble(serialization::DeclID D) {
533    TopLevelDeclsInPreamble.push_back(D);
534  }
535
536  /// \brief Retrieve a reference to the current top-level name hash value.
537  ///
538  /// Note: This is used internally by the top-level tracking action
539  unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
540
541  /// \brief Get the source location for the given file:line:col triplet.
542  ///
543  /// The difference with SourceManager::getLocation is that this method checks
544  /// whether the requested location points inside the precompiled preamble
545  /// in which case the returned source location will be a "loaded" one.
546  SourceLocation getLocation(const FileEntry *File,
547                             unsigned Line, unsigned Col) const;
548
549  /// \brief Get the source location for the given file:offset pair.
550  SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
551
552  /// \brief If \arg Loc is a loaded location from the preamble, returns
553  /// the corresponding local location of the main file, otherwise it returns
554  /// \arg Loc.
555  SourceLocation mapLocationFromPreamble(SourceLocation Loc);
556
557  /// \brief If \arg Loc is a local location of the main file but inside the
558  /// preamble chunk, returns the corresponding loaded location from the
559  /// preamble, otherwise it returns \arg Loc.
560  SourceLocation mapLocationToPreamble(SourceLocation Loc);
561
562  bool isInPreambleFileID(SourceLocation Loc);
563  bool isInMainFileID(SourceLocation Loc);
564  SourceLocation getStartOfMainFileID();
565  SourceLocation getEndOfPreambleFileID();
566
567  /// \brief \see mapLocationFromPreamble.
568  SourceRange mapRangeFromPreamble(SourceRange R) {
569    return SourceRange(mapLocationFromPreamble(R.getBegin()),
570                       mapLocationFromPreamble(R.getEnd()));
571  }
572
573  /// \brief \see mapLocationToPreamble.
574  SourceRange mapRangeToPreamble(SourceRange R) {
575    return SourceRange(mapLocationToPreamble(R.getBegin()),
576                       mapLocationToPreamble(R.getEnd()));
577  }
578
579  // Retrieve the diagnostics associated with this AST
580  typedef StoredDiagnostic *stored_diag_iterator;
581  typedef const StoredDiagnostic *stored_diag_const_iterator;
582  stored_diag_const_iterator stored_diag_begin() const {
583    return StoredDiagnostics.begin();
584  }
585  stored_diag_iterator stored_diag_begin() {
586    return StoredDiagnostics.begin();
587  }
588  stored_diag_const_iterator stored_diag_end() const {
589    return StoredDiagnostics.end();
590  }
591  stored_diag_iterator stored_diag_end() {
592    return StoredDiagnostics.end();
593  }
594  unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
595
596  stored_diag_iterator stored_diag_afterDriver_begin() {
597    if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
598      NumStoredDiagnosticsFromDriver = 0;
599    return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
600  }
601
602  typedef std::vector<CachedCodeCompletionResult>::iterator
603    cached_completion_iterator;
604
605  cached_completion_iterator cached_completion_begin() {
606    return CachedCompletionResults.begin();
607  }
608
609  cached_completion_iterator cached_completion_end() {
610    return CachedCompletionResults.end();
611  }
612
613  unsigned cached_completion_size() const {
614    return CachedCompletionResults.size();
615  }
616
617  llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
618                                       std::string *ErrorStr = 0);
619
620  /// \brief Determine what kind of translation unit this AST represents.
621  TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
622
623  typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
624      FilenameOrMemBuf;
625  /// \brief A mapping from a file name to the memory buffer that stores the
626  /// remapped contents of that file.
627  typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
628
629  /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
630  static ASTUnit *create(CompilerInvocation *CI,
631                         llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
632                         bool CaptureDiagnostics = false);
633
634  /// \brief Create a ASTUnit from an AST file.
635  ///
636  /// \param Filename - The AST file to load.
637  ///
638  /// \param Diags - The diagnostics engine to use for reporting errors; its
639  /// lifetime is expected to extend past that of the returned ASTUnit.
640  ///
641  /// \returns - The initialized ASTUnit or null if the AST failed to load.
642  static ASTUnit *LoadFromASTFile(const std::string &Filename,
643                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
644                                  const FileSystemOptions &FileSystemOpts,
645                                  bool OnlyLocalDecls = false,
646                                  RemappedFile *RemappedFiles = 0,
647                                  unsigned NumRemappedFiles = 0,
648                                  bool CaptureDiagnostics = false);
649
650private:
651  /// \brief Helper function for \c LoadFromCompilerInvocation() and
652  /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
653  ///
654  /// \param PrecompilePreamble Whether to precompile the preamble of this
655  /// translation unit, to improve the performance of reparsing.
656  ///
657  /// \returns \c true if a catastrophic failure occurred (which means that the
658  /// \c ASTUnit itself is invalid), or \c false otherwise.
659  bool LoadFromCompilerInvocation(bool PrecompilePreamble);
660
661public:
662
663  /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
664  /// object, by invoking the optionally provided ASTFrontendAction.
665  ///
666  /// \param CI - The compiler invocation to use; it must have exactly one input
667  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
668  ///
669  /// \param Diags - The diagnostics engine to use for reporting errors; its
670  /// lifetime is expected to extend past that of the returned ASTUnit.
671  ///
672  /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
673  /// transfered.
674  ///
675  /// \param Unit - optionally an already created ASTUnit. Its ownership is not
676  /// transfered.
677  ///
678  /// \param Persistent - if true the returned ASTUnit will be complete.
679  /// false means the caller is only interested in getting info through the
680  /// provided \see Action.
681  static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
682                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
683                                             ASTFrontendAction *Action = 0,
684                                             ASTUnit *Unit = 0,
685                                             bool Persistent = true,
686                                      StringRef ResourceFilesPath = StringRef(),
687                                             bool OnlyLocalDecls = false,
688                                             bool CaptureDiagnostics = false,
689                                             bool PrecompilePreamble = false,
690                                       bool CacheCodeCompletionResults = false);
691
692  /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
693  /// CompilerInvocation object.
694  ///
695  /// \param CI - The compiler invocation to use; it must have exactly one input
696  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
697  ///
698  /// \param Diags - The diagnostics engine to use for reporting errors; its
699  /// lifetime is expected to extend past that of the returned ASTUnit.
700  //
701  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
702  // shouldn't need to specify them at construction time.
703  static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
704                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
705                                             bool OnlyLocalDecls = false,
706                                             bool CaptureDiagnostics = false,
707                                             bool PrecompilePreamble = false,
708                                      TranslationUnitKind TUKind = TU_Complete,
709                                       bool CacheCodeCompletionResults = false,
710                                       bool NestedMacroExpansions = true);
711
712  /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
713  /// arguments, which must specify exactly one source file.
714  ///
715  /// \param ArgBegin - The beginning of the argument vector.
716  ///
717  /// \param ArgEnd - The end of the argument vector.
718  ///
719  /// \param Diags - The diagnostics engine to use for reporting errors; its
720  /// lifetime is expected to extend past that of the returned ASTUnit.
721  ///
722  /// \param ResourceFilesPath - The path to the compiler resource files.
723  //
724  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
725  // shouldn't need to specify them at construction time.
726  static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
727                                      const char **ArgEnd,
728                              llvm::IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
729                                      StringRef ResourceFilesPath,
730                                      bool OnlyLocalDecls = false,
731                                      bool CaptureDiagnostics = false,
732                                      RemappedFile *RemappedFiles = 0,
733                                      unsigned NumRemappedFiles = 0,
734                                      bool RemappedFilesKeepOriginalName = true,
735                                      bool PrecompilePreamble = false,
736                                      TranslationUnitKind TUKind = TU_Complete,
737                                      bool CacheCodeCompletionResults = false,
738                                      bool NestedMacroExpansions = true);
739
740  /// \brief Reparse the source files using the same command-line options that
741  /// were originally used to produce this translation unit.
742  ///
743  /// \returns True if a failure occurred that causes the ASTUnit not to
744  /// contain any translation-unit information, false otherwise.
745  bool Reparse(RemappedFile *RemappedFiles = 0,
746               unsigned NumRemappedFiles = 0);
747
748  /// \brief Perform code completion at the given file, line, and
749  /// column within this translation unit.
750  ///
751  /// \param File The file in which code completion will occur.
752  ///
753  /// \param Line The line at which code completion will occur.
754  ///
755  /// \param Column The column at which code completion will occur.
756  ///
757  /// \param IncludeMacros Whether to include macros in the code-completion
758  /// results.
759  ///
760  /// \param IncludeCodePatterns Whether to include code patterns (such as a
761  /// for loop) in the code-completion results.
762  ///
763  /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
764  /// OwnedBuffers parameters are all disgusting hacks. They will go away.
765  void CodeComplete(StringRef File, unsigned Line, unsigned Column,
766                    RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
767                    bool IncludeMacros, bool IncludeCodePatterns,
768                    CodeCompleteConsumer &Consumer,
769                    DiagnosticsEngine &Diag, LangOptions &LangOpts,
770                    SourceManager &SourceMgr, FileManager &FileMgr,
771                    SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
772              SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
773
774  /// \brief Save this translation unit to a file with the given name.
775  ///
776  /// \returns An indication of whether the save was successful or not.
777  CXSaveError Save(StringRef File);
778
779  /// \brief Serialize this translation unit with the given output stream.
780  ///
781  /// \returns True if an error occurred, false otherwise.
782  bool serialize(raw_ostream &OS);
783
784  virtual ModuleKey loadModule(SourceLocation ImportLoc,
785                               IdentifierInfo &ModuleName,
786                               SourceLocation ModuleNameLoc) {
787    // ASTUnit doesn't know how to load modules (not that this matters).
788    return 0;
789  }
790};
791
792} // namespace clang
793
794#endif
795