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