ASTUnit.h revision 478851c3ed6bd784e7377dffd8e57b200c1b9ba9
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/Serialization/ASTBitCodes.h"
18#include "clang/Sema/Sema.h"
19#include "clang/Sema/CodeCompleteConsumer.h"
20#include "clang/Lex/ModuleLoader.h"
21#include "clang/Lex/PreprocessingRecord.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/Basic/LangOptions.h"
24#include "clang/Basic/SourceManager.h"
25#include "clang/Basic/FileManager.h"
26#include "clang/Basic/FileSystemOptions.h"
27#include "clang-c/Index.h"
28#include "llvm/ADT/IntrusiveRefCntPtr.h"
29#include "llvm/ADT/OwningPtr.h"
30#include "llvm/ADT/SmallVector.h"
31#include "llvm/ADT/StringMap.h"
32#include "llvm/Support/Path.h"
33#include <map>
34#include <string>
35#include <vector>
36#include <cassert>
37#include <utility>
38#include <sys/types.h>
39
40namespace llvm {
41  class MemoryBuffer;
42}
43
44namespace clang {
45class ASTContext;
46class ASTReader;
47class CodeCompleteConsumer;
48class CompilerInvocation;
49class CompilerInstance;
50class Decl;
51class DiagnosticsEngine;
52class FileEntry;
53class FileManager;
54class HeaderSearch;
55class Preprocessor;
56class SourceManager;
57class TargetInfo;
58class ASTFrontendAction;
59
60/// \brief Utility class for loading a ASTContext from an AST file.
61///
62class ASTUnit : public ModuleLoader {
63private:
64  IntrusiveRefCntPtr<LangOptions>       LangOpts;
65  IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
66  IntrusiveRefCntPtr<FileManager>       FileMgr;
67  IntrusiveRefCntPtr<SourceManager>     SourceMgr;
68  OwningPtr<HeaderSearch>               HeaderInfo;
69  IntrusiveRefCntPtr<TargetInfo>        Target;
70  IntrusiveRefCntPtr<Preprocessor>      PP;
71  IntrusiveRefCntPtr<ASTContext>        Ctx;
72  ASTReader *Reader;
73
74  FileSystemOptions FileSystemOpts;
75
76  /// \brief The AST consumer that received information about the translation
77  /// unit as it was parsed or loaded.
78  OwningPtr<ASTConsumer> Consumer;
79
80  /// \brief The semantic analysis object used to type-check the translation
81  /// unit.
82  OwningPtr<Sema> TheSema;
83
84  /// Optional owned invocation, just used to make the invocation used in
85  /// LoadFromCommandLine available.
86  IntrusiveRefCntPtr<CompilerInvocation> Invocation;
87
88  /// \brief The set of target features.
89  ///
90  /// FIXME: each time we reparse, we need to restore the set of target
91  /// features from this vector, because TargetInfo::CreateTargetInfo()
92  /// mangles the target options in place. Yuck!
93  std::vector<std::string> TargetFeatures;
94
95  // OnlyLocalDecls - when true, walking this AST should only visit declarations
96  // that come from the AST itself, not from included precompiled headers.
97  // FIXME: This is temporary; eventually, CIndex will always do this.
98  bool                              OnlyLocalDecls;
99
100  /// \brief Whether to capture any diagnostics produced.
101  bool CaptureDiagnostics;
102
103  /// \brief Track whether the main file was loaded from an AST or not.
104  bool MainFileIsAST;
105
106  /// \brief What kind of translation unit this AST represents.
107  TranslationUnitKind TUKind;
108
109  /// \brief Whether we should time each operation.
110  bool WantTiming;
111
112  /// \brief Whether the ASTUnit should delete the remapped buffers.
113  bool OwnsRemappedFileBuffers;
114
115  /// Track the top-level decls which appeared in an ASTUnit which was loaded
116  /// from a source file.
117  //
118  // FIXME: This is just an optimization hack to avoid deserializing large parts
119  // of a PCH file when using the Index library on an ASTUnit loaded from
120  // source. In the long term we should make the Index library use efficient and
121  // more scalable search mechanisms.
122  std::vector<Decl*> TopLevelDecls;
123
124  /// \brief Sorted (by file offset) vector of pairs of file offset/Decl.
125  typedef SmallVector<std::pair<unsigned, Decl *>, 64> LocDeclsTy;
126  typedef llvm::DenseMap<FileID, LocDeclsTy *> FileDeclsTy;
127
128  /// \brief Map from FileID to the file-level declarations that it contains.
129  /// The files and decls are only local (and non-preamble) ones.
130  FileDeclsTy FileDecls;
131
132  /// The name of the original source file used to generate this ASTUnit.
133  std::string OriginalSourceFile;
134
135  /// \brief The set of diagnostics produced when creating the preamble.
136  SmallVector<StoredDiagnostic, 4> PreambleDiagnostics;
137
138  /// \brief The set of diagnostics produced when creating this
139  /// translation unit.
140  SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
141
142  /// \brief The set of diagnostics produced when failing to parse, e.g. due
143  /// to failure to load the PCH.
144  SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
145
146  /// \brief The number of stored diagnostics that come from the driver
147  /// itself.
148  ///
149  /// Diagnostics that come from the driver are retained from one parse to
150  /// the next.
151  unsigned NumStoredDiagnosticsFromDriver;
152
153  /// \brief Counter that determines when we want to try building a
154  /// precompiled preamble.
155  ///
156  /// If zero, we will never build a precompiled preamble. Otherwise,
157  /// it's treated as a counter that decrements each time we reparse
158  /// without the benefit of a precompiled preamble. When it hits 1,
159  /// we'll attempt to rebuild the precompiled header. This way, if
160  /// building the precompiled preamble fails, we won't try again for
161  /// some number of calls.
162  unsigned PreambleRebuildCounter;
163
164public:
165  class PreambleData {
166    const FileEntry *File;
167    std::vector<char> Buffer;
168    mutable unsigned NumLines;
169
170  public:
171    PreambleData() : File(0), NumLines(0) { }
172
173    void assign(const FileEntry *F, const char *begin, const char *end) {
174      File = F;
175      Buffer.assign(begin, end);
176      NumLines = 0;
177    }
178
179    void clear() { Buffer.clear(); File = 0; NumLines = 0; }
180
181    size_t size() const { return Buffer.size(); }
182    bool empty() const { return Buffer.empty(); }
183
184    const char *getBufferStart() const { return &Buffer[0]; }
185
186    unsigned getNumLines() const {
187      if (NumLines)
188        return NumLines;
189      countLines();
190      return NumLines;
191    }
192
193    SourceRange getSourceRange(const SourceManager &SM) const {
194      SourceLocation FileLoc = SM.getLocForStartOfFile(SM.getPreambleFileID());
195      return SourceRange(FileLoc, FileLoc.getLocWithOffset(size()-1));
196    }
197
198  private:
199    void countLines() const;
200  };
201
202  const PreambleData &getPreambleData() const {
203    return Preamble;
204  }
205
206private:
207
208  /// \brief The contents of the preamble that has been precompiled to
209  /// \c PreambleFile.
210  PreambleData Preamble;
211
212  /// \brief Whether the preamble ends at the start of a new line.
213  ///
214  /// Used to inform the lexer as to whether it's starting at the beginning of
215  /// a line after skipping the preamble.
216  bool PreambleEndsAtStartOfLine;
217
218  /// \brief The size of the source buffer that we've reserved for the main
219  /// file within the precompiled preamble.
220  unsigned PreambleReservedSize;
221
222  /// \brief Keeps track of the files that were used when computing the
223  /// preamble, with both their buffer size and their modification time.
224  ///
225  /// If any of the files have changed from one compile to the next,
226  /// the preamble must be thrown away.
227  llvm::StringMap<std::pair<off_t, time_t> > FilesInPreamble;
228
229  /// \brief When non-NULL, this is the buffer used to store the contents of
230  /// the main file when it has been padded for use with the precompiled
231  /// preamble.
232  llvm::MemoryBuffer *SavedMainFileBuffer;
233
234  /// \brief When non-NULL, this is the buffer used to store the
235  /// contents of the preamble when it has been padded to build the
236  /// precompiled preamble.
237  llvm::MemoryBuffer *PreambleBuffer;
238
239  /// \brief The number of warnings that occurred while parsing the preamble.
240  ///
241  /// This value will be used to restore the state of the \c DiagnosticsEngine
242  /// object when re-using the precompiled preamble. Note that only the
243  /// number of warnings matters, since we will not save the preamble
244  /// when any errors are present.
245  unsigned NumWarningsInPreamble;
246
247  /// \brief A list of the serialization ID numbers for each of the top-level
248  /// declarations parsed within the precompiled preamble.
249  std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
250
251  /// \brief Whether we should be caching code-completion results.
252  bool ShouldCacheCodeCompletionResults : 1;
253
254  /// \brief Whether to include brief documentation within the set of code
255  /// completions cached.
256  bool IncludeBriefCommentsInCodeCompletion : 1;
257
258  /// \brief The language options used when we load an AST file.
259  LangOptions ASTFileLangOpts;
260
261  static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> &Diags,
262                             const char **ArgBegin, const char **ArgEnd,
263                             ASTUnit &AST, bool CaptureDiagnostics);
264
265  void TranslateStoredDiagnostics(ASTReader *MMan, StringRef ModName,
266                                  SourceManager &SrcMan,
267                      const SmallVectorImpl<StoredDiagnostic> &Diags,
268                            SmallVectorImpl<StoredDiagnostic> &Out);
269
270  void clearFileLevelDecls();
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  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
320  getCachedCompletionAllocator() {
321    return CachedCompletionAllocator;
322  }
323
324  CodeCompletionTUInfo &getCodeCompletionTUInfo() {
325    if (!CCTUInfo)
326      CCTUInfo.reset(new CodeCompletionTUInfo(
327                                            new GlobalCodeCompletionAllocator));
328    return *CCTUInfo;
329  }
330
331private:
332  /// \brief Allocator used to store cached code completions.
333  IntrusiveRefCntPtr<GlobalCodeCompletionAllocator>
334    CachedCompletionAllocator;
335
336  OwningPtr<CodeCompletionTUInfo> CCTUInfo;
337
338  /// \brief The set of cached code-completion results.
339  std::vector<CachedCodeCompletionResult> CachedCompletionResults;
340
341  /// \brief A mapping from the formatted type name to a unique number for that
342  /// type, which is used for type equality comparisons.
343  llvm::StringMap<unsigned> CachedCompletionTypes;
344
345  /// \brief A string hash of the top-level declaration and macro definition
346  /// names processed the last time that we reparsed the file.
347  ///
348  /// This hash value is used to determine when we need to refresh the
349  /// global code-completion cache.
350  unsigned CompletionCacheTopLevelHashValue;
351
352  /// \brief A string hash of the top-level declaration and macro definition
353  /// names processed the last time that we reparsed the precompiled preamble.
354  ///
355  /// This hash value is used to determine when we need to refresh the
356  /// global code-completion cache after a rebuild of the precompiled preamble.
357  unsigned PreambleTopLevelHashValue;
358
359  /// \brief The current hash value for the top-level declaration and macro
360  /// definition names
361  unsigned CurrentTopLevelHashValue;
362
363  /// \brief Bit used by CIndex to mark when a translation unit may be in an
364  /// inconsistent state, and is not safe to free.
365  unsigned UnsafeToFree : 1;
366
367  /// \brief Cache any "global" code-completion results, so that we can avoid
368  /// recomputing them with each completion.
369  void CacheCodeCompletionResults();
370
371  /// \brief Clear out and deallocate
372  void ClearCachedCompletionResults();
373
374  ASTUnit(const ASTUnit&); // DO NOT IMPLEMENT
375  ASTUnit &operator=(const ASTUnit &); // DO NOT IMPLEMENT
376
377  explicit ASTUnit(bool MainFileIsAST);
378
379  void CleanTemporaryFiles();
380  bool Parse(llvm::MemoryBuffer *OverrideMainBuffer);
381
382  std::pair<llvm::MemoryBuffer *, std::pair<unsigned, bool> >
383  ComputePreamble(CompilerInvocation &Invocation,
384                  unsigned MaxLines, bool &CreatedBuffer);
385
386  llvm::MemoryBuffer *getMainBufferWithPrecompiledPreamble(
387                               const CompilerInvocation &PreambleInvocationIn,
388                                                     bool AllowRebuild = true,
389                                                        unsigned MaxLines = 0);
390  void RealizeTopLevelDeclsFromPreamble();
391
392  /// \brief Transfers ownership of the objects (like SourceManager) from
393  /// \param CI to this ASTUnit.
394  void transferASTDataFromCompilerInstance(CompilerInstance &CI);
395
396  /// \brief Allows us to assert that ASTUnit is not being used concurrently,
397  /// which is not supported.
398  ///
399  /// Clients should create instances of the ConcurrencyCheck class whenever
400  /// using the ASTUnit in a way that isn't intended to be concurrent, which is
401  /// just about any usage.
402  /// Becomes a noop in release mode; only useful for debug mode checking.
403  class ConcurrencyState {
404#ifndef NDEBUG
405    void *Mutex; // a llvm::sys::MutexImpl in debug;
406#endif
407
408  public:
409    ConcurrencyState();
410    ~ConcurrencyState();
411
412    void start();
413    void finish();
414  };
415  ConcurrencyState ConcurrencyCheckValue;
416
417public:
418  class ConcurrencyCheck {
419    ASTUnit &Self;
420
421  public:
422    explicit ConcurrencyCheck(ASTUnit &Self)
423      : Self(Self)
424    {
425      Self.ConcurrencyCheckValue.start();
426    }
427    ~ConcurrencyCheck() {
428      Self.ConcurrencyCheckValue.finish();
429    }
430  };
431  friend class ConcurrencyCheck;
432
433  ~ASTUnit();
434
435  bool isMainFileAST() const { return MainFileIsAST; }
436
437  bool isUnsafeToFree() const { return UnsafeToFree; }
438  void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
439
440  const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
441  DiagnosticsEngine &getDiagnostics()             { return *Diagnostics; }
442
443  const SourceManager &getSourceManager() const { return *SourceMgr; }
444        SourceManager &getSourceManager()       { return *SourceMgr; }
445
446  const Preprocessor &getPreprocessor() const { return *PP; }
447        Preprocessor &getPreprocessor()       { return *PP; }
448
449  const ASTContext &getASTContext() const { return *Ctx; }
450        ASTContext &getASTContext()       { return *Ctx; }
451
452  void setASTContext(ASTContext *ctx) { Ctx = ctx; }
453  void setPreprocessor(Preprocessor *pp);
454
455  bool hasSema() const { return TheSema; }
456  Sema &getSema() const {
457    assert(TheSema && "ASTUnit does not have a Sema object!");
458    return *TheSema;
459  }
460
461  const FileManager &getFileManager() const { return *FileMgr; }
462        FileManager &getFileManager()       { return *FileMgr; }
463
464  const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
465
466  const std::string &getOriginalSourceFileName();
467
468  /// \brief Add a temporary file that the ASTUnit depends on.
469  ///
470  /// This file will be erased when the ASTUnit is destroyed.
471  void addTemporaryFile(const llvm::sys::Path &TempFile);
472
473  bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
474
475  bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
476  void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
477
478  StringRef getMainFileName() const;
479
480  typedef std::vector<Decl *>::iterator top_level_iterator;
481
482  top_level_iterator top_level_begin() {
483    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
484    if (!TopLevelDeclsInPreamble.empty())
485      RealizeTopLevelDeclsFromPreamble();
486    return TopLevelDecls.begin();
487  }
488
489  top_level_iterator top_level_end() {
490    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
491    if (!TopLevelDeclsInPreamble.empty())
492      RealizeTopLevelDeclsFromPreamble();
493    return TopLevelDecls.end();
494  }
495
496  std::size_t top_level_size() const {
497    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
498    return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
499  }
500
501  bool top_level_empty() const {
502    assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
503    return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
504  }
505
506  /// \brief Add a new top-level declaration.
507  void addTopLevelDecl(Decl *D) {
508    TopLevelDecls.push_back(D);
509  }
510
511  /// \brief Add a new local file-level declaration.
512  void addFileLevelDecl(Decl *D);
513
514  /// \brief Get the decls that are contained in a file in the Offset/Length
515  /// range. \arg Length can be 0 to indicate a point at \arg Offset instead of
516  /// a range.
517  void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
518                           SmallVectorImpl<Decl *> &Decls);
519
520  /// \brief Add a new top-level declaration, identified by its ID in
521  /// the precompiled preamble.
522  void addTopLevelDeclFromPreamble(serialization::DeclID D) {
523    TopLevelDeclsInPreamble.push_back(D);
524  }
525
526  /// \brief Retrieve a reference to the current top-level name hash value.
527  ///
528  /// Note: This is used internally by the top-level tracking action
529  unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
530
531  /// \brief Get the source location for the given file:line:col triplet.
532  ///
533  /// The difference with SourceManager::getLocation is that this method checks
534  /// whether the requested location points inside the precompiled preamble
535  /// in which case the returned source location will be a "loaded" one.
536  SourceLocation getLocation(const FileEntry *File,
537                             unsigned Line, unsigned Col) const;
538
539  /// \brief Get the source location for the given file:offset pair.
540  SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
541
542  /// \brief If \arg Loc is a loaded location from the preamble, returns
543  /// the corresponding local location of the main file, otherwise it returns
544  /// \arg Loc.
545  SourceLocation mapLocationFromPreamble(SourceLocation Loc);
546
547  /// \brief If \arg Loc is a local location of the main file but inside the
548  /// preamble chunk, returns the corresponding loaded location from the
549  /// preamble, otherwise it returns \arg Loc.
550  SourceLocation mapLocationToPreamble(SourceLocation Loc);
551
552  bool isInPreambleFileID(SourceLocation Loc);
553  bool isInMainFileID(SourceLocation Loc);
554  SourceLocation getStartOfMainFileID();
555  SourceLocation getEndOfPreambleFileID();
556
557  /// \brief \see mapLocationFromPreamble.
558  SourceRange mapRangeFromPreamble(SourceRange R) {
559    return SourceRange(mapLocationFromPreamble(R.getBegin()),
560                       mapLocationFromPreamble(R.getEnd()));
561  }
562
563  /// \brief \see mapLocationToPreamble.
564  SourceRange mapRangeToPreamble(SourceRange R) {
565    return SourceRange(mapLocationToPreamble(R.getBegin()),
566                       mapLocationToPreamble(R.getEnd()));
567  }
568
569  // Retrieve the diagnostics associated with this AST
570  typedef StoredDiagnostic *stored_diag_iterator;
571  typedef const StoredDiagnostic *stored_diag_const_iterator;
572  stored_diag_const_iterator stored_diag_begin() const {
573    return StoredDiagnostics.begin();
574  }
575  stored_diag_iterator stored_diag_begin() {
576    return StoredDiagnostics.begin();
577  }
578  stored_diag_const_iterator stored_diag_end() const {
579    return StoredDiagnostics.end();
580  }
581  stored_diag_iterator stored_diag_end() {
582    return StoredDiagnostics.end();
583  }
584  unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
585
586  stored_diag_iterator stored_diag_afterDriver_begin() {
587    if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
588      NumStoredDiagnosticsFromDriver = 0;
589    return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
590  }
591
592  typedef std::vector<CachedCodeCompletionResult>::iterator
593    cached_completion_iterator;
594
595  cached_completion_iterator cached_completion_begin() {
596    return CachedCompletionResults.begin();
597  }
598
599  cached_completion_iterator cached_completion_end() {
600    return CachedCompletionResults.end();
601  }
602
603  unsigned cached_completion_size() const {
604    return CachedCompletionResults.size();
605  }
606
607  llvm::MemoryBuffer *getBufferForFile(StringRef Filename,
608                                       std::string *ErrorStr = 0);
609
610  /// \brief Determine what kind of translation unit this AST represents.
611  TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
612
613  typedef llvm::PointerUnion<const char *, const llvm::MemoryBuffer *>
614      FilenameOrMemBuf;
615  /// \brief A mapping from a file name to the memory buffer that stores the
616  /// remapped contents of that file.
617  typedef std::pair<std::string, FilenameOrMemBuf> RemappedFile;
618
619  /// \brief Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
620  static ASTUnit *create(CompilerInvocation *CI,
621                         IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
622                         bool CaptureDiagnostics = false);
623
624  /// \brief Create a ASTUnit from an AST file.
625  ///
626  /// \param Filename - The AST file to load.
627  ///
628  /// \param Diags - The diagnostics engine to use for reporting errors; its
629  /// lifetime is expected to extend past that of the returned ASTUnit.
630  ///
631  /// \returns - The initialized ASTUnit or null if the AST failed to load.
632  static ASTUnit *LoadFromASTFile(const std::string &Filename,
633                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
634                                  const FileSystemOptions &FileSystemOpts,
635                                  bool OnlyLocalDecls = false,
636                                  RemappedFile *RemappedFiles = 0,
637                                  unsigned NumRemappedFiles = 0,
638                                  bool CaptureDiagnostics = false,
639                                  bool AllowPCHWithCompilerErrors = false);
640
641private:
642  /// \brief Helper function for \c LoadFromCompilerInvocation() and
643  /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
644  ///
645  /// \param PrecompilePreamble Whether to precompile the preamble of this
646  /// translation unit, to improve the performance of reparsing.
647  ///
648  /// \returns \c true if a catastrophic failure occurred (which means that the
649  /// \c ASTUnit itself is invalid), or \c false otherwise.
650  bool LoadFromCompilerInvocation(bool PrecompilePreamble);
651
652public:
653
654  /// \brief Create an ASTUnit from a source file, via a CompilerInvocation
655  /// object, by invoking the optionally provided ASTFrontendAction.
656  ///
657  /// \param CI - The compiler invocation to use; it must have exactly one input
658  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
659  ///
660  /// \param Diags - The diagnostics engine to use for reporting errors; its
661  /// lifetime is expected to extend past that of the returned ASTUnit.
662  ///
663  /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
664  /// transfered.
665  ///
666  /// \param Unit - optionally an already created ASTUnit. Its ownership is not
667  /// transfered.
668  ///
669  /// \param Persistent - if true the returned ASTUnit will be complete.
670  /// false means the caller is only interested in getting info through the
671  /// provided \see Action.
672  ///
673  /// \param ErrAST - If non-null and parsing failed without any AST to return
674  /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
675  /// mainly to allow the caller to see the diagnostics.
676  /// This will only receive an ASTUnit if a new one was created. If an already
677  /// created ASTUnit was passed in \param Unit then the caller can check that.
678  ///
679  static ASTUnit *LoadFromCompilerInvocationAction(CompilerInvocation *CI,
680                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
681                                             ASTFrontendAction *Action = 0,
682                                             ASTUnit *Unit = 0,
683                                             bool Persistent = true,
684                                      StringRef ResourceFilesPath = StringRef(),
685                                             bool OnlyLocalDecls = false,
686                                             bool CaptureDiagnostics = false,
687                                             bool PrecompilePreamble = false,
688                                       bool CacheCodeCompletionResults = false,
689                              bool IncludeBriefCommentsInCodeCompletion = false,
690                                       OwningPtr<ASTUnit> *ErrAST = 0);
691
692  /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
693  /// CompilerInvocation object.
694  ///
695  /// \param CI - The compiler invocation to use; it must have exactly one input
696  /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
697  ///
698  /// \param Diags - The diagnostics engine to use for reporting errors; its
699  /// lifetime is expected to extend past that of the returned ASTUnit.
700  //
701  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
702  // shouldn't need to specify them at construction time.
703  static ASTUnit *LoadFromCompilerInvocation(CompilerInvocation *CI,
704                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
705                                             bool OnlyLocalDecls = false,
706                                             bool CaptureDiagnostics = false,
707                                             bool PrecompilePreamble = false,
708                                      TranslationUnitKind TUKind = TU_Complete,
709                                       bool CacheCodeCompletionResults = false,
710                            bool IncludeBriefCommentsInCodeCompletion = false);
711
712  /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
713  /// arguments, which must specify exactly one source file.
714  ///
715  /// \param ArgBegin - The beginning of the argument vector.
716  ///
717  /// \param ArgEnd - The end of the argument vector.
718  ///
719  /// \param Diags - The diagnostics engine to use for reporting errors; its
720  /// lifetime is expected to extend past that of the returned ASTUnit.
721  ///
722  /// \param ResourceFilesPath - The path to the compiler resource files.
723  ///
724  /// \param ErrAST - If non-null and parsing failed without any AST to return
725  /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
726  /// mainly to allow the caller to see the diagnostics.
727  ///
728  // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
729  // shouldn't need to specify them at construction time.
730  static ASTUnit *LoadFromCommandLine(const char **ArgBegin,
731                                      const char **ArgEnd,
732                              IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
733                                      StringRef ResourceFilesPath,
734                                      bool OnlyLocalDecls = false,
735                                      bool CaptureDiagnostics = false,
736                                      RemappedFile *RemappedFiles = 0,
737                                      unsigned NumRemappedFiles = 0,
738                                      bool RemappedFilesKeepOriginalName = true,
739                                      bool PrecompilePreamble = false,
740                                      TranslationUnitKind TUKind = TU_Complete,
741                                      bool CacheCodeCompletionResults = false,
742                            bool IncludeBriefCommentsInCodeCompletion = false,
743                                      bool AllowPCHWithCompilerErrors = false,
744                                      bool SkipFunctionBodies = false,
745                                      OwningPtr<ASTUnit> *ErrAST = 0);
746
747  /// \brief Reparse the source files using the same command-line options that
748  /// were originally used to produce this translation unit.
749  ///
750  /// \returns True if a failure occurred that causes the ASTUnit not to
751  /// contain any translation-unit information, false otherwise.
752  bool Reparse(RemappedFile *RemappedFiles = 0,
753               unsigned NumRemappedFiles = 0);
754
755  /// \brief Perform code completion at the given file, line, and
756  /// column within this translation unit.
757  ///
758  /// \param File The file in which code completion will occur.
759  ///
760  /// \param Line The line at which code completion will occur.
761  ///
762  /// \param Column The column at which code completion will occur.
763  ///
764  /// \param IncludeMacros Whether to include macros in the code-completion
765  /// results.
766  ///
767  /// \param IncludeCodePatterns Whether to include code patterns (such as a
768  /// for loop) in the code-completion results.
769  ///
770  /// \param IncludeBriefComments Whether to include brief documentation within
771  /// the set of code completions returned.
772  ///
773  /// FIXME: The Diag, LangOpts, SourceMgr, FileMgr, StoredDiagnostics, and
774  /// OwnedBuffers parameters are all disgusting hacks. They will go away.
775  void CodeComplete(StringRef File, unsigned Line, unsigned Column,
776                    RemappedFile *RemappedFiles, unsigned NumRemappedFiles,
777                    bool IncludeMacros, bool IncludeCodePatterns,
778                    bool IncludeBriefComments,
779                    CodeCompleteConsumer &Consumer,
780                    DiagnosticsEngine &Diag, LangOptions &LangOpts,
781                    SourceManager &SourceMgr, FileManager &FileMgr,
782                    SmallVectorImpl<StoredDiagnostic> &StoredDiagnostics,
783              SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
784
785  /// \brief Save this translation unit to a file with the given name.
786  ///
787  /// \returns An indication of whether the save was successful or not.
788  CXSaveError Save(StringRef File);
789
790  /// \brief Serialize this translation unit with the given output stream.
791  ///
792  /// \returns True if an error occurred, false otherwise.
793  bool serialize(raw_ostream &OS);
794
795  virtual Module *loadModule(SourceLocation ImportLoc, ModuleIdPath Path,
796                             Module::NameVisibilityKind Visibility,
797                             bool IsInclusionDirective) {
798    // ASTUnit doesn't know how to load modules (not that this matters).
799    return 0;
800  }
801};
802
803} // namespace clang
804
805#endif
806