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