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