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