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