ASTUnit.h revision c93dc7889644293e318e19d82830ea2acc45b678
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 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(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  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  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  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
345    CachedCompletionAllocator;
346
347  /// \brief Allocator used to store code completions for arbitrary cursors.
348  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  void setPreprocessor(Preprocessor *pp);
461
462  bool hasSema() const { return TheSema; }
463  Sema &getSema() const {
464    assert(TheSema && "ASTUnit does not have a Sema object!");
465    return *TheSema;
466  }
467
468  const FileManager &getFileManager() const { return *FileMgr; }
469        FileManager &getFileManager()       { return *FileMgr; }
470
471  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
472
473  const std::string &getOriginalSourceFileName();
474
475  /// \brief Add a temporary file that the ASTUnit depends on.
476  ///
477  /// This file will be erased when the ASTUnit is destroyed.
478  void addTemporaryFile(const llvm::sys::Path &TempFile);
479
480  bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
481
482  bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
483  void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
484
485  void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; }
486  ASTLocation getLastASTLocation() const { return LastLoc; }
487
488
489  StringRef getMainFileName() const;
490
491  typedef std::vector<Decl *>::iterator top_level_iterator;
492
493  top_level_iterator top_level_begin() {
494    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
495    if (!TopLevelDeclsInPreamble.empty())
496      RealizeTopLevelDeclsFromPreamble();
497    return TopLevelDecls.begin();
498  }
499
500  top_level_iterator top_level_end() {
501    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
502    if (!TopLevelDeclsInPreamble.empty())
503      RealizeTopLevelDeclsFromPreamble();
504    return TopLevelDecls.end();
505  }
506
507  std::size_t top_level_size() const {
508    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
509    return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
510  }
511
512  bool top_level_empty() const {
513    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
514    return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
515  }
516
517  /// \brief Add a new top-level declaration.
518  void addTopLevelDecl(Decl *D) {
519    TopLevelDecls.push_back(D);
520  }
521
522  /// \brief Add a new local file-level declaration.
523  void addFileLevelDecl(Decl *D);
524
525  /// \brief Get the decls that are contained in a file in the Offset/Length
526  /// range. \arg Length can be 0 to indicate a point at \arg Offset instead of
527  /// a range.
528  void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
529                           SmallVectorImpl<Decl *> &Decls);
530
531  /// \brief Add a new top-level declaration, identified by its ID in
532  /// the precompiled preamble.
533  void addTopLevelDeclFromPreamble(serialization::DeclID D) {
534    TopLevelDeclsInPreamble.push_back(D);
535  }
536
537  /// \brief Retrieve a reference to the current top-level name hash value.
538  ///
539  /// Note: This is used internally by the top-level tracking action
540  unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
541
542  /// \brief Get the source location for the given file:line:col triplet.
543  ///
544  /// The difference with SourceManager::getLocation is that this method checks
545  /// whether the requested location points inside the precompiled preamble
546  /// in which case the returned source location will be a "loaded" one.
547  SourceLocation getLocation(const FileEntry *File,
548                             unsigned Line, unsigned Col) const;
549
550  /// \brief Get the source location for the given file:offset pair.
551  SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
552
553  /// \brief If \arg Loc is a loaded location from the preamble, returns
554  /// the corresponding local location of the main file, otherwise it returns
555  /// \arg Loc.
556  SourceLocation mapLocationFromPreamble(SourceLocation Loc);
557
558  /// \brief If \arg Loc is a local location of the main file but inside the
559  /// preamble chunk, returns the corresponding loaded location from the
560  /// preamble, otherwise it returns \arg Loc.
561  SourceLocation mapLocationToPreamble(SourceLocation Loc);
562
563  bool isInPreambleFileID(SourceLocation Loc);
564  bool isInMainFileID(SourceLocation Loc);
565  SourceLocation getStartOfMainFileID();
566  SourceLocation getEndOfPreambleFileID();
567
568  /// \brief \see mapLocationFromPreamble.
569  SourceRange mapRangeFromPreamble(SourceRange R) {
570    return SourceRange(mapLocationFromPreamble(R.getBegin()),
571                       mapLocationFromPreamble(R.getEnd()));
572  }
573
574  /// \brief \see mapLocationToPreamble.
575  SourceRange mapRangeToPreamble(SourceRange R) {
576    return SourceRange(mapLocationToPreamble(R.getBegin()),
577                       mapLocationToPreamble(R.getEnd()));
578  }
579
580  // Retrieve the diagnostics associated with this AST
581  typedef StoredDiagnostic *stored_diag_iterator;
582  typedef const StoredDiagnostic *stored_diag_const_iterator;
583  stored_diag_const_iterator stored_diag_begin() const {
584    return StoredDiagnostics.begin();
585  }
586  stored_diag_iterator stored_diag_begin() {
587    return StoredDiagnostics.begin();
588  }
589  stored_diag_const_iterator stored_diag_end() const {
590    return StoredDiagnostics.end();
591  }
592  stored_diag_iterator stored_diag_end() {
593    return StoredDiagnostics.end();
594  }
595  unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
596
597  stored_diag_iterator stored_diag_afterDriver_begin() {
598    if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
599      NumStoredDiagnosticsFromDriver = 0;
600    return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
601  }
602
603  typedef std::vector<CachedCodeCompletionResult>::iterator
604    cached_completion_iterator;
605
606  cached_completion_iterator cached_completion_begin() {
607    return CachedCompletionResults.begin();
608  }
609
610  cached_completion_iterator cached_completion_end() {
611    return CachedCompletionResults.end();
612  }
613
614  unsigned cached_completion_size() const {
615    return CachedCompletionResults.size();
616  }
617
618  llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
619                                       std::string *ErrorStr = 0);
620
621  /// \brief Determine what kind of translation unit this AST represents.
622  TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
623
624  typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
625      FilenameOrMemBuf;
626  /// \brief A mapping from a file name to the memory buffer that stores the
627  /// remapped contents of that file.
628  typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
629
630  /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
631  static ASTUnit *create(CompilerInvocation *CI,
632                         IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
633                         bool CaptureDiagnostics = false);
634
635  /// \brief Create a ASTUnit from an AST file.
636  ///
637  /// \param Filename - The AST file to load.
638  ///
639  /// \param Diags - The diagnostics engine to use for reporting errors; its
640  /// lifetime is expected to extend past that of the returned ASTUnit.
641  ///
642  /// \returns - The initialized ASTUnit or null if the AST failed to load.
643  static ASTUnit *LoadFromASTFile(const std::string &Filename,
644                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
645                                  const FileSystemOptions &FileSystemOpts,
646                                  bool OnlyLocalDecls = false,
647                                  RemappedFile *RemappedFiles = 0,
648                                  unsigned NumRemappedFiles = 0,
649                                  bool CaptureDiagnostics = false);
650
651private:
652  /// \brief Helper function for \c LoadFromCompilerInvocation() and
653  /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
654  ///
655  /// \param PrecompilePreamble Whether to precompile the preamble of this
656  /// translation unit, to improve the performance of reparsing.
657  ///
658  /// \returns \c true if a catastrophic failure occurred (which means that the
659  /// \c ASTUnit itself is invalid), or \c false otherwise.
660  bool LoadFromCompilerInvocation(bool PrecompilePreamble);
661
662public:
663
664  /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
665  /// object, by invoking the optionally provided ASTFrontendAction.
666  ///
667  /// \param CI - The compiler invocation to use; it must have exactly one input
668  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
669  ///
670  /// \param Diags - The diagnostics engine to use for reporting errors; its
671  /// lifetime is expected to extend past that of the returned ASTUnit.
672  ///
673  /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
674  /// transfered.
675  ///
676  /// \param Unit - optionally an already created ASTUnit. Its ownership is not
677  /// transfered.
678  ///
679  /// \param Persistent - if true the returned ASTUnit will be complete.
680  /// false means the caller is only interested in getting info through the
681  /// provided \see Action.
682  static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
683                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
684                                             ASTFrontendAction *Action = 0,
685                                             ASTUnit *Unit = 0,
686                                             bool Persistent = true,
687                                      StringRef ResourceFilesPath = StringRef(),
688                                             bool OnlyLocalDecls = false,
689                                             bool CaptureDiagnostics = false,
690                                             bool PrecompilePreamble = false,
691                                       bool CacheCodeCompletionResults = false);
692
693  /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
694  /// CompilerInvocation object.
695  ///
696  /// \param CI - The compiler invocation to use; it must have exactly one input
697  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
698  ///
699  /// \param Diags - The diagnostics engine to use for reporting errors; its
700  /// lifetime is expected to extend past that of the returned ASTUnit.
701  //
702  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
703  // shouldn't need to specify them at construction time.
704  static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
705                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
706                                             bool OnlyLocalDecls = false,
707                                             bool CaptureDiagnostics = false,
708                                             bool PrecompilePreamble = false,
709                                      TranslationUnitKind TUKind = TU_Complete,
710                                       bool CacheCodeCompletionResults = false,
711                                       bool NestedMacroExpansions = true);
712
713  /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
714  /// arguments, which must specify exactly one source file.
715  ///
716  /// \param ArgBegin - The beginning of the argument vector.
717  ///
718  /// \param ArgEnd - The end of the argument vector.
719  ///
720  /// \param Diags - The diagnostics engine to use for reporting errors; its
721  /// lifetime is expected to extend past that of the returned ASTUnit.
722  ///
723  /// \param ResourceFilesPath - The path to the compiler resource files.
724  //
725  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
726  // shouldn't need to specify them at construction time.
727  static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
728                                      const char **ArgEnd,
729                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
730                                      StringRef ResourceFilesPath,
731                                      bool OnlyLocalDecls = false,
732                                      bool CaptureDiagnostics = false,
733                                      RemappedFile *RemappedFiles = 0,
734                                      unsigned NumRemappedFiles = 0,
735                                      bool RemappedFilesKeepOriginalName = true,
736                                      bool PrecompilePreamble = false,
737                                      TranslationUnitKind TUKind = TU_Complete,
738                                      bool CacheCodeCompletionResults = false,
739                                      bool NestedMacroExpansions = true);
740
741  /// \brief Reparse the source files using the same command-line options that
742  /// were originally used to produce this translation unit.
743  ///
744  /// \returns True if a failure occurred that causes the ASTUnit not to
745  /// contain any translation-unit information, false otherwise.
746  bool Reparse(RemappedFile *RemappedFiles = 0,
747               unsigned NumRemappedFiles = 0);
748
749  /// \brief Perform code completion at the given file, line, and
750  /// column within this translation unit.
751  ///
752  /// \param File The file in which code completion will occur.
753  ///
754  /// \param Line The line at which code completion will occur.
755  ///
756  /// \param Column The column at which code completion will occur.
757  ///
758  /// \param IncludeMacros Whether to include macros in the code-completion
759  /// results.
760  ///
761  /// \param IncludeCodePatterns Whether to include code patterns (such as a
762  /// for loop) in the code-completion results.
763  ///
764  /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
765  /// OwnedBuffers parameters are all disgusting hacks. They will go away.
766  void CodeComplete(StringRef File, unsigned Line, unsigned Column,
767                    RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
768                    bool IncludeMacros, bool IncludeCodePatterns,
769                    CodeCompleteConsumer &Consumer,
770                    DiagnosticsEngine &Diag, LangOptions &LangOpts,
771                    SourceManager &SourceMgr, FileManager &FileMgr,
772                    SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
773              SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
774
775  /// \brief Save this translation unit to a file with the given name.
776  ///
777  /// \returns An indication of whether the save was successful or not.
778  CXSaveError Save(StringRef File);
779
780  /// \brief Serialize this translation unit with the given output stream.
781  ///
782  /// \returns True if an error occurred, false otherwise.
783  bool serialize(raw_ostream &OS);
784
785  virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
786                             Module::NameVisibilityKind Visibility,
787                             bool IsInclusionDirective) {
788    // ASTUnit doesn't know how to load modules (not that this matters).
789    return 0;
790  }
791};
792
793} // namespace clang
794
795#endif
796