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