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