ASTUnit.h revision d808bd2978bd4ac95a92b309b038452b533fd7a0
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  static void ConfigureDiags(llvm::IntrusiveRefCntPtr<Diagnostic> &Diags,
253                             const char **ArgBegin, const char **ArgEnd,
254                             ASTUnit &AST, bool CaptureDiagnostics);
255
256public:
257  /// \brief A cached code-completion result, which may be introduced in one of
258  /// many different contexts.
259  struct CachedCodeCompletionResult {
260    /// \brief The code-completion string corresponding to this completion
261    /// result.
262    CodeCompletionString *Completion;
263
264    /// \brief A bitmask that indicates which code-completion contexts should
265    /// contain this completion result.
266    ///
267    /// The bits in the bitmask correspond to the values of
268    /// CodeCompleteContext::Kind. To map from a completion context kind to a
269    /// bit, subtract one from the completion context kind and shift 1 by that
270    /// number of bits. Many completions can occur in several different
271    /// contexts.
272    unsigned ShowInContexts;
273
274    /// \brief The priority given to this code-completion result.
275    unsigned Priority;
276
277    /// \brief The libclang cursor kind corresponding to this code-completion
278    /// result.
279    CXCursorKind Kind;
280
281    /// \brief The availability of this code-completion result.
282    CXAvailabilityKind Availability;
283
284    /// \brief The simplified type class for a non-macro completion result.
285    SimplifiedTypeClass TypeClass;
286
287    /// \brief The type of a non-macro completion result, stored as a unique
288    /// integer used by the string map of cached completion types.
289    ///
290    /// This value will be zero if the type is not known, or a unique value
291    /// determined by the formatted type string. Se \c CachedCompletionTypes
292    /// for more information.
293    unsigned Type;
294  };
295
296  /// \brief Retrieve the mapping from formatted type names to unique type
297  /// identifiers.
298  llvm::StringMap<unsigned> &getCachedCompletionTypes() {
299    return CachedCompletionTypes;
300  }
301
302  /// \brief Retrieve the allocator used to cache global code completions.
303  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
304  getCachedCompletionAllocator() {
305    return CachedCompletionAllocator;
306  }
307
308private:
309  /// \brief Allocator used to store cached code completions.
310  llvm::IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
311    CachedCompletionAllocator;
312
313  /// \brief The set of cached code-completion results.
314  std::vector<CachedCodeCompletionResult> CachedCompletionResults;
315
316  /// \brief A mapping from the formatted type name to a unique number for that
317  /// type, which is used for type equality comparisons.
318  llvm::StringMap<unsigned> CachedCompletionTypes;
319
320  /// \brief A string hash of the top-level declaration and macro definition
321  /// names processed the last time that we reparsed the file.
322  ///
323  /// This hash value is used to determine when we need to refresh the
324  /// global code-completion cache.
325  unsigned CompletionCacheTopLevelHashValue;
326
327  /// \brief A string hash of the top-level declaration and macro definition
328  /// names processed the last time that we reparsed the precompiled preamble.
329  ///
330  /// This hash value is used to determine when we need to refresh the
331  /// global code-completion cache after a rebuild of the precompiled preamble.
332  unsigned PreambleTopLevelHashValue;
333
334  /// \brief The current hash value for the top-level declaration and macro
335  /// definition names
336  unsigned CurrentTopLevelHashValue;
337
338  /// \brief Bit used by CIndex to mark when a translation unit may be in an
339  /// inconsistent state, and is not safe to free.
340  unsigned UnsafeToFree : 1;
341
342  /// \brief Cache any "global" code-completion results, so that we can avoid
343  /// recomputing them with each completion.
344  void CacheCodeCompletionResults();
345
346  /// \brief Clear out and deallocate
347  void ClearCachedCompletionResults();
348
349  ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT
350  ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT
351
352  explicit ASTUnit(bool MainFileIsAST);
353
354  void CleanTemporaryFiles();
355  bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
356
357  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
358  ComputePreamble(CompilerInvocation &Invocation,
359                  unsigned MaxLines, bool &CreatedBuffer);
360
361  llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
362                                         CompilerInvocation PreambleInvocation,
363                                                     bool AllowRebuild = true,
364                                                        unsigned MaxLines = 0);
365  void RealizeTopLevelDeclsFromPreamble();
366  void RealizePreprocessedEntitiesFromPreamble();
367
368public:
369  class ConcurrencyCheck {
370    volatile ASTUnit &Self;
371
372  public:
373    explicit ConcurrencyCheck(ASTUnit &Self)
374      : Self(Self)
375    {
376      assert(Self.ConcurrencyCheckValue == CheckUnlocked &&
377             "Concurrent access to ASTUnit!");
378      Self.ConcurrencyCheckValue = CheckLocked;
379    }
380
381    ~ConcurrencyCheck() {
382      Self.ConcurrencyCheckValue = CheckUnlocked;
383    }
384  };
385  friend class ConcurrencyCheck;
386
387  ~ASTUnit();
388
389  bool isMainFileAST() const { return MainFileIsAST; }
390
391  bool isUnsafeToFree() const { return UnsafeToFree; }
392  void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
393
394  const Diagnostic &getDiagnostics() const { return *Diagnostics; }
395  Diagnostic &getDiagnostics()             { return *Diagnostics; }
396
397  const SourceManager &getSourceManager() const { return *SourceMgr; }
398        SourceManager &getSourceManager()       { return *SourceMgr; }
399
400  const Preprocessor &getPreprocessor() const { return *PP; }
401        Preprocessor &getPreprocessor()       { return *PP; }
402
403  const ASTContext &getASTContext() const { return *Ctx; }
404        ASTContext &getASTContext()       { return *Ctx; }
405
406  bool hasSema() const { return TheSema; }
407  Sema &getSema() const {
408    assert(TheSema && "ASTUnit does not have a Sema object!");
409    return *TheSema;
410  }
411
412  const FileManager &getFileManager() const { return *FileMgr; }
413        FileManager &getFileManager()       { return *FileMgr; }
414
415  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
416
417  const std::string &getOriginalSourceFileName();
418  const std::string &getASTFileName();
419
420  /// \brief Add a temporary file that the ASTUnit depends on.
421  ///
422  /// This file will be erased when the ASTUnit is destroyed.
423  void addTemporaryFile(const llvm::sys::Path &TempFile) {
424    TemporaryFiles.push_back(TempFile);
425  }
426
427  bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
428
429  bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
430  void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
431
432  /// \brief Retrieve the maximum PCH level of declarations that a
433  /// traversal of the translation unit should consider.
434  unsigned getMaxPCHLevel() const;
435
436  void setLastASTLocation(ASTLocation ALoc) { LastLoc = ALoc; }
437  ASTLocation getLastASTLocation() const { return LastLoc; }
438
439
440  llvm::StringRef getMainFileName() const;
441
442  typedef std::vector<Decl *>::iterator top_level_iterator;
443
444  top_level_iterator top_level_begin() {
445    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
446    if (!TopLevelDeclsInPreamble.empty())
447      RealizeTopLevelDeclsFromPreamble();
448    return TopLevelDecls.begin();
449  }
450
451  top_level_iterator top_level_end() {
452    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
453    if (!TopLevelDeclsInPreamble.empty())
454      RealizeTopLevelDeclsFromPreamble();
455    return TopLevelDecls.end();
456  }
457
458  std::size_t top_level_size() const {
459    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
460    return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
461  }
462
463  bool top_level_empty() const {
464    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
465    return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
466  }
467
468  /// \brief Add a new top-level declaration.
469  void addTopLevelDecl(Decl *D) {
470    TopLevelDecls.push_back(D);
471  }
472
473  /// \brief Add a new top-level declaration, identified by its ID in
474  /// the precompiled preamble.
475  void addTopLevelDeclFromPreamble(serialization::DeclID D) {
476    TopLevelDeclsInPreamble.push_back(D);
477  }
478
479  /// \brief Retrieve a reference to the current top-level name hash value.
480  ///
481  /// Note: This is used internally by the top-level tracking action
482  unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
483
484  typedef std::vector<PreprocessedEntity *>::iterator pp_entity_iterator;
485
486  pp_entity_iterator pp_entity_begin();
487  pp_entity_iterator pp_entity_end();
488
489  /// \brief Add a new preprocessed entity that's stored at the given offset
490  /// in the precompiled preamble.
491  void addPreprocessedEntityFromPreamble(uint64_t Offset) {
492    PreprocessedEntitiesInPreamble.push_back(Offset);
493  }
494
495  /// \brief Retrieve the mapping from File IDs to the preprocessed entities
496  /// within that file.
497  PreprocessedEntitiesByFileMap &getPreprocessedEntitiesByFile() {
498    return PreprocessedEntitiesByFile;
499  }
500
501  // Retrieve the diagnostics associated with this AST
502  typedef const StoredDiagnostic *stored_diag_iterator;
503  stored_diag_iterator stored_diag_begin() const {
504    return StoredDiagnostics.begin();
505  }
506  stored_diag_iterator stored_diag_end() const {
507    return StoredDiagnostics.end();
508  }
509  unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
510
511  llvm::SmallVector<StoredDiagnostic, 4> &getStoredDiagnostics() {
512    return StoredDiagnostics;
513  }
514
515  typedef std::vector<CachedCodeCompletionResult>::iterator
516    cached_completion_iterator;
517
518  cached_completion_iterator cached_completion_begin() {
519    return CachedCompletionResults.begin();
520  }
521
522  cached_completion_iterator cached_completion_end() {
523    return CachedCompletionResults.end();
524  }
525
526  unsigned cached_completion_size() const {
527    return CachedCompletionResults.size();
528  }
529
530  llvm::MemoryBuffer *getBufferForFile(llvm::StringRef Filename,
531                                       std::string *ErrorStr = 0);
532
533  /// \brief Whether this AST represents a complete translation unit.
534  ///
535  /// If false, this AST is only a partial translation unit, e.g., one
536  /// that might still be used as a precompiled header or preamble.
537  bool isCompleteTranslationUnit() const { return CompleteTranslationUnit; }
538
539  typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
540      FilenameOrMemBuf;
541  /// \brief A mapping from a file name to the memory buffer that stores the
542  /// remapped contents of that file.
543  typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
544
545  /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
546  static ASTUnit *create(CompilerInvocation *CI,
547                         llvm::IntrusiveRefCntPtr<Diagnostic> Diags);
548
549  /// \brief Create a ASTUnit from an AST file.
550  ///
551  /// \param Filename - The AST file to load.
552  ///
553  /// \param Diags - The diagnostics engine to use for reporting errors; its
554  /// lifetime is expected to extend past that of the returned ASTUnit.
555  ///
556  /// \returns - The initialized ASTUnit or null if the AST failed to load.
557  static ASTUnit *LoadFromASTFile(const std::string &Filename,
558                                  llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
559                                  const FileSystemOptions &FileSystemOpts,
560                                  bool OnlyLocalDecls = false,
561                                  RemappedFile *RemappedFiles = 0,
562                                  unsigned NumRemappedFiles = 0,
563                                  bool CaptureDiagnostics = false);
564
565private:
566  /// \brief Helper function for \c LoadFromCompilerInvocation() and
567  /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
568  ///
569  /// \param PrecompilePreamble Whether to precompile the preamble of this
570  /// translation unit, to improve the performance of reparsing.
571  ///
572  /// \returns \c true if a catastrophic failure occurred (which means that the
573  /// \c ASTUnit itself is invalid), or \c false otherwise.
574  bool LoadFromCompilerInvocation(bool PrecompilePreamble);
575
576public:
577
578  /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
579  /// object, by invoking the optionally provided ASTFrontendAction.
580  ///
581  /// \param CI - The compiler invocation to use; it must have exactly one input
582  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
583  ///
584  /// \param Diags - The diagnostics engine to use for reporting errors; its
585  /// lifetime is expected to extend past that of the returned ASTUnit.
586  ///
587  /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
588  /// transfered.
589  static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
590                                     llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
591                                             ASTFrontendAction *Action = 0);
592
593  /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
594  /// CompilerInvocation object.
595  ///
596  /// \param CI - The compiler invocation to use; it must have exactly one input
597  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
598  ///
599  /// \param Diags - The diagnostics engine to use for reporting errors; its
600  /// lifetime is expected to extend past that of the returned ASTUnit.
601  //
602  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
603  // shouldn't need to specify them at construction time.
604  static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
605                                     llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
606                                             bool OnlyLocalDecls = false,
607                                             bool CaptureDiagnostics = false,
608                                             bool PrecompilePreamble = false,
609                                          bool CompleteTranslationUnit = true,
610                                       bool CacheCodeCompletionResults = false);
611
612  /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
613  /// arguments, which must specify exactly one source file.
614  ///
615  /// \param ArgBegin - The beginning of the argument vector.
616  ///
617  /// \param ArgEnd - The end of the argument vector.
618  ///
619  /// \param Diags - The diagnostics engine to use for reporting errors; its
620  /// lifetime is expected to extend past that of the returned ASTUnit.
621  ///
622  /// \param ResourceFilesPath - The path to the compiler resource files.
623  //
624  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
625  // shouldn't need to specify them at construction time.
626  static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
627                                      const char **ArgEnd,
628                                    llvm::IntrusiveRefCntPtr<Diagnostic> Diags,
629                                      llvm::StringRef ResourceFilesPath,
630                                      bool OnlyLocalDecls = false,
631                                      bool CaptureDiagnostics = false,
632                                      RemappedFile *RemappedFiles = 0,
633                                      unsigned NumRemappedFiles = 0,
634                                      bool RemappedFilesKeepOriginalName = true,
635                                      bool PrecompilePreamble = false,
636                                      bool CompleteTranslationUnit = true,
637                                      bool CacheCodeCompletionResults = false,
638                                      bool CXXPrecompilePreamble = false,
639                                      bool CXXChainedPCH = false);
640
641  /// \brief Reparse the source files using the same command-line options that
642  /// were originally used to produce this translation unit.
643  ///
644  /// \returns True if a failure occurred that causes the ASTUnit not to
645  /// contain any translation-unit information, false otherwise.
646  bool Reparse(RemappedFile *RemappedFiles = 0,
647               unsigned NumRemappedFiles = 0);
648
649  /// \brief Perform code completion at the given file, line, and
650  /// column within this translation unit.
651  ///
652  /// \param File The file in which code completion will occur.
653  ///
654  /// \param Line The line at which code completion will occur.
655  ///
656  /// \param Column The column at which code completion will occur.
657  ///
658  /// \param IncludeMacros Whether to include macros in the code-completion
659  /// results.
660  ///
661  /// \param IncludeCodePatterns Whether to include code patterns (such as a
662  /// for loop) in the code-completion results.
663  ///
664  /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
665  /// OwnedBuffers parameters are all disgusting hacks. They will go away.
666  void CodeComplete(llvm::StringRef File, unsigned Line, unsigned Column,
667                    RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
668                    bool IncludeMacros, bool IncludeCodePatterns,
669                    CodeCompleteConsumer &Consumer,
670                    Diagnostic &Diag, LangOptions &LangOpts,
671                    SourceManager &SourceMgr, FileManager &FileMgr,
672                    llvm::SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
673              llvm::SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
674
675  /// \brief Save this translation unit to a file with the given name.
676  ///
677  /// \returns True if an error occurred, false otherwise.
678  bool Save(llvm::StringRef File);
679
680  /// \brief Serialize this translation unit with the given output stream.
681  ///
682  /// \returns True if an error occurred, false otherwise.
683  bool serialize(llvm::raw_ostream &OS);
684};
685
686} // namespace clang
687
688#endif
689