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