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