ASTUnit.h revision 8cc488fefb2fb04bc8d5398da29f0182f97934cf
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/PreprocessingRecord.h"
22#include "clang/Basic/SourceManager.h"
23#include "clang/Basic/FileManager.h"
24#include "clang/Basic/FileSystemOptions.h"
25#include "clang-c/Index.h"
26#include "llvm/ADT/IntrusiveRefCntPtr.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallVector.h"
29#include "llvm/ADT/StringMap.h"
30#include "llvm/Support/Path.h"
31#include <map>
32#include <string>
33#include <vector>
34#include <cassert>
35#include <utility>
36#include <sys/types.h>
37
38namespace llvm {
39  class MemoryBuffer;
40}
41
42namespace clang {
43class ASTContext;
44class ASTReader;
45class CodeCompleteConsumer;
46class CompilerInvocation;
47class Decl;
48class Diagnostic;
49class FileEntry;
50class FileManager;
51class HeaderSearch;
52class Preprocessor;
53class SourceManager;
54class TargetInfo;
55class ASTFrontendAction;
56
57using namespace idx;
58
59/// \brief Allocator for a cached set of global code completions.
60class GlobalCodeCompletionAllocator
61  : public CodeCompletionAllocator,
62    public llvm::RefCountedBase<GlobalCodeCompletionAllocator>
63{
64
65};
66
67/// \brief Utility class for loading a ASTContext from an AST file.
68///
69class ASTUnit {
70public:
71  typedef std::map<FileID, std::vector<PreprocessedEntity *> >
72    PreprocessedEntitiesByFileMap;
73
74private:
75  llvm::IntrusiveRefCntPtr<Diagnostic> Diagnostics;
76  llvm::IntrusiveRefCntPtr<FileManager>      FileMgr;
77  llvm::IntrusiveRefCntPtr<SourceManager>    SourceMgr;
78  llvm::OwningPtr<HeaderSearch>     HeaderInfo;
79  llvm::IntrusiveRefCntPtr<TargetInfo>       Target;
80  llvm::IntrusiveRefCntPtr<Preprocessor>     PP;
81  llvm::IntrusiveRefCntPtr<ASTContext>       Ctx;
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 Whether this AST represents a complete translation unit.
116  bool CompleteTranslationUnit;
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 The list of preprocessed entities which appeared when the ASTUnit
134  /// was loaded.
135  ///
136  /// FIXME: This is just an optimization hack to avoid deserializing large
137  /// parts of a PCH file while performing a walk or search. In the long term,
138  /// we should provide more scalable search mechanisms.
139  std::vector<PreprocessedEntity *> PreprocessedEntities;
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 Temporary files that should be removed when the ASTUnit is
162  /// destroyed.
163  SmallVector<llvm::sys::Path, 4> TemporaryFiles;
164
165  /// \brief A mapping from file IDs to the set of preprocessed entities
166  /// stored in that file.
167  ///
168  /// FIXME: This is just an optimization hack to avoid searching through
169  /// many preprocessed entities during cursor traversal in the CIndex library.
170  /// Ideally, we would just be able to perform a binary search within the
171  /// list of preprocessed entities.
172  PreprocessedEntitiesByFileMap PreprocessedEntitiesByFile;
173
174  /// \brief Simple hack to allow us to assert that ASTUnit is not being
175  /// used concurrently, which is not supported.
176  ///
177  /// Clients should create instances of the ConcurrencyCheck class whenever
178  /// using the ASTUnit in a way that isn't intended to be concurrent, which is
179  /// just about any usage.
180  unsigned int ConcurrencyCheckValue;
181  static const unsigned int CheckLocked = 28573289;
182  static const unsigned int CheckUnlocked = 9803453;
183
184  /// \brief Counter that determines when we want to try building a
185  /// precompiled preamble.
186  ///
187  /// If zero, we will never build a precompiled preamble. Otherwise,
188  /// it's treated as a counter that decrements each time we reparse
189  /// without the benefit of a precompiled preamble. When it hits 1,
190  /// we'll attempt to rebuild the precompiled header. This way, if
191  /// building the precompiled preamble fails, we won't try again for
192  /// some number of calls.
193  unsigned PreambleRebuildCounter;
194
195  /// \brief The file in which the precompiled preamble is stored.
196  std::string PreambleFile;
197
198  /// \brief The contents of the preamble that has been precompiled to
199  /// \c PreambleFile.
200  std::vector<char> Preamble;
201
202  /// \brief Whether the preamble ends at the start of a new line.
203  ///
204  /// Used to inform the lexer as to whether it's starting at the beginning of
205  /// a line after skipping the preamble.
206  bool PreambleEndsAtStartOfLine;
207
208  /// \brief The size of the source buffer that we've reserved for the main
209  /// file within the precompiled preamble.
210  unsigned PreambleReservedSize;
211
212  /// \brief Keeps track of the files that were used when computing the
213  /// preamble, with both their buffer size and their modification time.
214  ///
215  /// If any of the files have changed from one compile to the next,
216  /// the preamble must be thrown away.
217  llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble;
218
219  /// \brief When non-NULL, this is the buffer used to store the contents of
220  /// the main file when it has been padded for use with the precompiled
221  /// preamble.
222  llvm::MemoryBuffer *SavedMainFileBuffer;
223
224  /// \brief When non-NULL, this is the buffer used to store the
225  /// contents of the preamble when it has been padded to build the
226  /// precompiled preamble.
227  llvm::MemoryBuffer *PreambleBuffer;
228
229  /// \brief The number of warnings that occurred while parsing the preamble.
230  ///
231  /// This value will be used to restore the state of the \c Diagnostic object
232  /// when re-using the precompiled preamble. Note that only the
233  /// number of warnings matters, since we will not save the preamble
234  /// when any errors are present.
235  unsigned NumWarningsInPreamble;
236
237  /// \brief A list of the serialization ID numbers for each of the top-level
238  /// declarations parsed within the precompiled preamble.
239  std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
240
241  /// \brief A list of the offsets into the precompiled preamble which
242  /// correspond to preprocessed entities.
243  std::vector<uint64_t> PreprocessedEntitiesInPreamble;
244
245  /// \brief Whether we should be caching code-completion results.
246  bool ShouldCacheCodeCompletionResults;
247
248  /// \brief Whether we want to include nested macro expansions in the
249  /// detailed preprocessing record.
250  bool NestedMacroExpansions;
251
252  static void ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
253                             const char **ArgBegin, const char **ArgEnd,
254                             ASTUnit &AST, bool CaptureDiagnostics);
255
256  void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
257                                  SourceManager &SrcMan,
258                      const SmallVectorImpl<StoredDiagnostic> &Diags,
259                            SmallVectorImpl<StoredDiagnostic> &Out);
260
261public:
262  /// \brief A cached code-completion result, which may be introduced in one of
263  /// many different contexts.
264  struct CachedCodeCompletionResult {
265    /// \brief The code-completion string corresponding to this completion
266    /// result.
267    CodeCompletionString *Completion;
268
269    /// \brief A bitmask that indicates which code-completion contexts should
270    /// contain this completion result.
271    ///
272    /// The bits in the bitmask correspond to the values of
273    /// CodeCompleteContext::Kind. To map from a completion context kind to a
274    /// bit, subtract one from the completion context kind and shift 1 by that
275    /// number of bits. Many completions can occur in several different
276    /// contexts.
277    unsigned ShowInContexts;
278
279    /// \brief The priority given to this code-completion result.
280    unsigned Priority;
281
282    /// \brief The libclang cursor kind corresponding to this code-completion
283    /// result.
284    CXCursorKind Kind;
285
286    /// \brief The availability of this code-completion result.
287    CXAvailabilityKind Availability;
288
289    /// \brief The simplified type class for a non-macro completion result.
290    SimplifiedTypeClass TypeClass;
291
292    /// \brief The type of a non-macro completion result, stored as a unique
293    /// integer used by the string map of cached completion types.
294    ///
295    /// This value will be zero if the type is not known, or a unique value
296    /// determined by the formatted type string. Se \c CachedCompletionTypes
297    /// for more information.
298    unsigned Type;
299  };
300
301  /// \brief Retrieve the mapping from formatted type names to unique type
302  /// identifiers.
303  llvm::StringMap<unsigned> &getCachedCompletionTypes() {
304    return CachedCompletionTypes;
305  }
306
307  /// \brief Retrieve the allocator used to cache global code completions.
308  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
309  getCachedCompletionAllocator() {
310    return CachedCompletionAllocator;
311  }
312
313private:
314  /// \brief Allocator used to store cached code completions.
315  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
316    CachedCompletionAllocator;
317
318  /// \brief The set of cached code-completion results.
319  std::vector<CachedCodeCompletionResult> CachedCompletionResults;
320
321  /// \brief A mapping from the formatted type name to a unique number for that
322  /// type, which is used for type equality comparisons.
323  llvm::StringMap<unsigned> CachedCompletionTypes;
324
325  /// \brief A string hash of the top-level declaration and macro definition
326  /// names processed the last time that we reparsed the file.
327  ///
328  /// This hash value is used to determine when we need to refresh the
329  /// global code-completion cache.
330  unsigned CompletionCacheTopLevelHashValue;
331
332  /// \brief A string hash of the top-level declaration and macro definition
333  /// names processed the last time that we reparsed the precompiled preamble.
334  ///
335  /// This hash value is used to determine when we need to refresh the
336  /// global code-completion cache after a rebuild of the precompiled preamble.
337  unsigned PreambleTopLevelHashValue;
338
339  /// \brief The current hash value for the top-level declaration and macro
340  /// definition names
341  unsigned CurrentTopLevelHashValue;
342
343  /// \brief Bit used by CIndex to mark when a translation unit may be in an
344  /// inconsistent state, and is not safe to free.
345  unsigned UnsafeToFree : 1;
346
347  /// \brief Cache any "global" code-completion results, so that we can avoid
348  /// recomputing them with each completion.
349  void CacheCodeCompletionResults();
350
351  /// \brief Clear out and deallocate
352  void ClearCachedCompletionResults();
353
354  ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT
355  ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT
356
357  explicit ASTUnit(bool MainFileIsAST);
358
359  void CleanTemporaryFiles();
360  bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
361
362  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
363  ComputePreamble(CompilerInvocation &Invocation,
364                  unsigned MaxLines, bool &CreatedBuffer);
365
366  llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
367                               const CompilerInvocation &PreambleInvocationIn,
368                                                     bool AllowRebuild = true,
369                                                        unsigned MaxLines = 0);
370  void RealizeTopLevelDeclsFromPreamble();
371  void RealizePreprocessedEntitiesFromPreamble();
372
373public:
374  class ConcurrencyCheck {
375    volatile ASTUnit &Self;
376
377  public:
378    explicit ConcurrencyCheck(ASTUnit &Self)
379      : Self(Self)
380    {
381      assert(Self.ConcurrencyCheckValue == CheckUnlocked &&
382             "Concurrent access to ASTUnit!");
383      Self.ConcurrencyCheckValue = CheckLocked;
384    }
385
386    ~ConcurrencyCheck() {
387      Self.ConcurrencyCheckValue = CheckUnlocked;
388    }
389  };
390  friend class ConcurrencyCheck;
391
392  ~ASTUnit();
393
394  bool isMainFileAST() const { return MainFileIsAST; }
395
396  bool isUnsafeToFree() const { return UnsafeToFree; }
397  void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
398
399  const Diagnostic &getDiagnostics() const { return *Diagnostics; }
400  Diagnostic &getDiagnostics()             { return *Diagnostics; }
401
402  const SourceManager &getSourceManager() const { return *SourceMgr; }
403        SourceManager &getSourceManager()       { return *SourceMgr; }
404
405  const Preprocessor &getPreprocessor() const { return *PP; }
406        Preprocessor &getPreprocessor()       { return *PP; }
407
408  const ASTContext &getASTContext() const { return *Ctx; }
409        ASTContext &getASTContext()       { return *Ctx; }
410
411  bool hasSema() const { return TheSema; }
412  Sema &getSema() const {
413    assert(TheSema && "ASTUnit does not have a Sema object!");
414    return *TheSema;
415  }
416
417  const FileManager &getFileManager() const { return *FileMgr; }
418        FileManager &getFileManager()       { return *FileMgr; }
419
420  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
421
422  const std::string &getOriginalSourceFileName();
423  const std::string &getASTFileName();
424
425  /// \brief Add a temporary file that the ASTUnit depends on.
426  ///
427  /// This file will be erased when the ASTUnit is destroyed.
428  void addTemporaryFile(const llvm::sys::Path &TempFile) {
429    TemporaryFiles.push_back(TempFile);
430  }
431
432  bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
433
434  bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
435  void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
436
437  /// \brief Retrieve the maximum PCH level of declarations that a
438  /// traversal of the translation unit should consider.
439  unsigned getMaxPCHLevel() const;
440
441  void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; }
442  ASTLocation getLastASTLocation() const { return LastLoc; }
443
444
445  StringRef getMainFileName() const;
446
447  typedef std::vector<Decl *>::iterator top_level_iterator;
448
449  top_level_iterator top_level_begin() {
450    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
451    if (!TopLevelDeclsInPreamble.empty())
452      RealizeTopLevelDeclsFromPreamble();
453    return TopLevelDecls.begin();
454  }
455
456  top_level_iterator top_level_end() {
457    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
458    if (!TopLevelDeclsInPreamble.empty())
459      RealizeTopLevelDeclsFromPreamble();
460    return TopLevelDecls.end();
461  }
462
463  std::size_t top_level_size() const {
464    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
465    return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
466  }
467
468  bool top_level_empty() const {
469    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
470    return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
471  }
472
473  /// \brief Add a new top-level declaration.
474  void addTopLevelDecl(Decl *D) {
475    TopLevelDecls.push_back(D);
476  }
477
478  /// \brief Add a new top-level declaration, identified by its ID in
479  /// the precompiled preamble.
480  void addTopLevelDeclFromPreamble(serialization::DeclID D) {
481    TopLevelDeclsInPreamble.push_back(D);
482  }
483
484  /// \brief Retrieve a reference to the current top-level name hash value.
485  ///
486  /// Note: This is used internally by the top-level tracking action
487  unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
488
489  typedef std::vector<PreprocessedEntity *>::iterator pp_entity_iterator;
490
491  pp_entity_iterator pp_entity_begin();
492  pp_entity_iterator pp_entity_end();
493
494  /// \brief Add a new preprocessed entity that's stored at the given offset
495  /// in the precompiled preamble.
496  void addPreprocessedEntityFromPreamble(uint64_t Offset) {
497    PreprocessedEntitiesInPreamble.push_back(Offset);
498  }
499
500  /// \brief Retrieve the mapping from File IDs to the preprocessed entities
501  /// within that file.
502  PreprocessedEntitiesByFileMap &getPreprocessedEntitiesByFile() {
503    return PreprocessedEntitiesByFile;
504  }
505
506  // Retrieve the diagnostics associated with this AST
507  typedef const StoredDiagnostic *stored_diag_iterator;
508  stored_diag_iterator stored_diag_begin() const {
509    return StoredDiagnostics.begin();
510  }
511  stored_diag_iterator stored_diag_end() const {
512    return StoredDiagnostics.end();
513  }
514  unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
515
516  SmallVector<StoredDiagnostic, 4> &getStoredDiagnostics() {
517    return StoredDiagnostics;
518  }
519
520  typedef std::vector<CachedCodeCompletionResult>::iterator
521    cached_completion_iterator;
522
523  cached_completion_iterator cached_completion_begin() {
524    return CachedCompletionResults.begin();
525  }
526
527  cached_completion_iterator cached_completion_end() {
528    return CachedCompletionResults.end();
529  }
530
531  unsigned cached_completion_size() const {
532    return CachedCompletionResults.size();
533  }
534
535  llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
536                                       std::string *ErrorStr = 0);
537
538  /// \brief Whether this AST represents a complete translation unit.
539  ///
540  /// If false, this AST is only a partial translation unit, e.g., one
541  /// that might still be used as a precompiled header or preamble.
542  bool isCompleteTranslationUnit() const { return CompleteTranslationUnit; }
543
544  typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
545      FilenameOrMemBuf;
546  /// \brief A mapping from a file name to the memory buffer that stores the
547  /// remapped contents of that file.
548  typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
549
550  /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
551  static ASTUnit *create(CompilerInvocation *CI,
552                         llvm::IntrusiveRefCntPtr<Diagnostic> Diags);
553
554  /// \brief Create a ASTUnit from an AST file.
555  ///
556  /// \param Filename - The AST file to load.
557  ///
558  /// \param Diags - The diagnostics engine to use for reporting errors; its
559  /// lifetime is expected to extend past that of the returned ASTUnit.
560  ///
561  /// \returns - The initialized ASTUnit or null if the AST failed to load.
562  static ASTUnit *LoadFromASTFile(const std::string &Filename,
563                                  llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
564                                  const FileSystemOptions &FileSystemOpts,
565                                  bool OnlyLocalDecls = false,
566                                  RemappedFile *RemappedFiles = 0,
567                                  unsigned NumRemappedFiles = 0,
568                                  bool CaptureDiagnostics = false);
569
570private:
571  /// \brief Helper function for \c LoadFromCompilerInvocation() and
572  /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
573  ///
574  /// \param PrecompilePreamble Whether to precompile the preamble of this
575  /// translation unit, to improve the performance of reparsing.
576  ///
577  /// \returns \c true if a catastrophic failure occurred (which means that the
578  /// \c ASTUnit itself is invalid), or \c false otherwise.
579  bool LoadFromCompilerInvocation(bool PrecompilePreamble);
580
581public:
582
583  /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
584  /// object, by invoking the optionally provided ASTFrontendAction.
585  ///
586  /// \param CI - The compiler invocation to use; it must have exactly one input
587  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
588  ///
589  /// \param Diags - The diagnostics engine to use for reporting errors; its
590  /// lifetime is expected to extend past that of the returned ASTUnit.
591  ///
592  /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
593  /// transfered.
594  static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
595                                     llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
596                                             ASTFrontendAction *Action = 0);
597
598  /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
599  /// CompilerInvocation object.
600  ///
601  /// \param CI - The compiler invocation to use; it must have exactly one input
602  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
603  ///
604  /// \param Diags - The diagnostics engine to use for reporting errors; its
605  /// lifetime is expected to extend past that of the returned ASTUnit.
606  //
607  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
608  // shouldn't need to specify them at construction time.
609  static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
610                                     llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
611                                             bool OnlyLocalDecls = false,
612                                             bool CaptureDiagnostics = false,
613                                             bool PrecompilePreamble = false,
614                                          bool CompleteTranslationUnit = true,
615                                       bool CacheCodeCompletionResults = false,
616                                       bool NestedMacroExpansions = true);
617
618  /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
619  /// arguments, which must specify exactly one source file.
620  ///
621  /// \param ArgBegin - The beginning of the argument vector.
622  ///
623  /// \param ArgEnd - The end of the argument vector.
624  ///
625  /// \param Diags - The diagnostics engine to use for reporting errors; its
626  /// lifetime is expected to extend past that of the returned ASTUnit.
627  ///
628  /// \param ResourceFilesPath - The path to the compiler resource files.
629  //
630  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
631  // shouldn't need to specify them at construction time.
632  static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
633                                      const char **ArgEnd,
634                                    llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
635                                      StringRef ResourceFilesPath,
636                                      bool OnlyLocalDecls = false,
637                                      bool CaptureDiagnostics = false,
638                                      RemappedFile *RemappedFiles = 0,
639                                      unsigned NumRemappedFiles = 0,
640                                      bool RemappedFilesKeepOriginalName = true,
641                                      bool PrecompilePreamble = false,
642                                      bool CompleteTranslationUnit = true,
643                                      bool CacheCodeCompletionResults = false,
644                                      bool CXXPrecompilePreamble = false,
645                                      bool CXXChainedPCH = false,
646                                      bool NestedMacroExpansions = true);
647
648  /// \brief Reparse the source files using the same command-line options that
649  /// were originally used to produce this translation unit.
650  ///
651  /// \returns True if a failure occurred that causes the ASTUnit not to
652  /// contain any translation-unit information, false otherwise.
653  bool Reparse(RemappedFile *RemappedFiles = 0,
654               unsigned NumRemappedFiles = 0);
655
656  /// \brief Perform code completion at the given file, line, and
657  /// column within this translation unit.
658  ///
659  /// \param File The file in which code completion will occur.
660  ///
661  /// \param Line The line at which code completion will occur.
662  ///
663  /// \param Column The column at which code completion will occur.
664  ///
665  /// \param IncludeMacros Whether to include macros in the code-completion
666  /// results.
667  ///
668  /// \param IncludeCodePatterns Whether to include code patterns (such as a
669  /// for loop) in the code-completion results.
670  ///
671  /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
672  /// OwnedBuffers parameters are all disgusting hacks. They will go away.
673  void CodeComplete(StringRef File, unsigned Line, unsigned Column,
674                    RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
675                    bool IncludeMacros, bool IncludeCodePatterns,
676                    CodeCompleteConsumer &Consumer,
677                    Diagnostic &Diag, LangOptions &LangOpts,
678                    SourceManager &SourceMgr, FileManager &FileMgr,
679                    SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
680              SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
681
682  /// \brief Save this translation unit to a file with the given name.
683  ///
684  /// \returns An indication of whether the save was successful or not.
685  CXSaveError Save(StringRef File);
686
687  /// \brief Serialize this translation unit with the given output stream.
688  ///
689  /// \returns True if an error occurred, false otherwise.
690  bool serialize(raw_ostream &OS);
691};
692
693} // namespace clang
694
695#endif
696