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