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