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