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