1 //===- ASTUnit.h - ASTUnit utility ------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // ASTUnit utility class.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_CLANG_FRONTEND_ASTUNIT_H
15 #define LLVM_CLANG_FRONTEND_ASTUNIT_H
17 #include "clang-c/Index.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/Basic/Diagnostic.h"
20 #include "clang/Basic/FileSystemOptions.h"
21 #include "clang/Basic/LLVM.h"
22 #include "clang/Basic/LangOptions.h"
23 #include "clang/Basic/SourceLocation.h"
24 #include "clang/Basic/SourceManager.h"
25 #include "clang/Basic/TargetOptions.h"
26 #include "clang/Lex/HeaderSearchOptions.h"
27 #include "clang/Lex/ModuleLoader.h"
28 #include "clang/Lex/PreprocessingRecord.h"
29 #include "clang/Sema/CodeCompleteConsumer.h"
30 #include "clang/Serialization/ASTBitCodes.h"
31 #include "clang/Frontend/PrecompiledPreamble.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"
59 class ASTDeserializationListener;
60 class ASTMutationListener;
62 class CompilerInstance;
63 class CompilerInvocation;
70 class MemoryBufferCache;
71 class PCHContainerOperations;
72 class PCHContainerReader;
74 class PreprocessorOptions;
84 /// \brief Enumerates the available scopes for skipping function bodies.
85 enum class SkipFunctionBodiesScope { None, Preamble, PreambleAndMainFile };
87 /// Utility class for loading a ASTContext from an AST file.
90 struct StandaloneFixIt {
91 std::pair<unsigned, unsigned> RemoveRange;
92 std::pair<unsigned, unsigned> InsertFromRange;
93 std::string CodeToInsert;
94 bool BeforePreviousInsertions;
97 struct StandaloneDiagnostic {
99 DiagnosticsEngine::Level Level;
101 std::string Filename;
103 std::vector<std::pair<unsigned, unsigned>> Ranges;
104 std::vector<StandaloneFixIt> FixIts;
108 std::shared_ptr<LangOptions> LangOpts;
109 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
110 IntrusiveRefCntPtr<FileManager> FileMgr;
111 IntrusiveRefCntPtr<SourceManager> SourceMgr;
112 IntrusiveRefCntPtr<MemoryBufferCache> PCMCache;
113 std::unique_ptr<HeaderSearch> HeaderInfo;
114 IntrusiveRefCntPtr<TargetInfo> Target;
115 std::shared_ptr<Preprocessor> PP;
116 IntrusiveRefCntPtr<ASTContext> Ctx;
117 std::shared_ptr<TargetOptions> TargetOpts;
118 std::shared_ptr<HeaderSearchOptions> HSOpts;
119 std::shared_ptr<PreprocessorOptions> PPOpts;
120 IntrusiveRefCntPtr<ASTReader> Reader;
121 bool HadModuleLoaderFatalFailure = false;
123 struct ASTWriterData;
124 std::unique_ptr<ASTWriterData> WriterData;
126 FileSystemOptions FileSystemOpts;
128 /// The AST consumer that received information about the translation
129 /// unit as it was parsed or loaded.
130 std::unique_ptr<ASTConsumer> Consumer;
132 /// The semantic analysis object used to type-check the translation
134 std::unique_ptr<Sema> TheSema;
136 /// Optional owned invocation, just used to make the invocation used in
137 /// LoadFromCommandLine available.
138 std::shared_ptr<CompilerInvocation> Invocation;
140 /// Fake module loader: the AST unit doesn't need to load any modules.
141 TrivialModuleLoader ModuleLoader;
143 // OnlyLocalDecls - when true, walking this AST should only visit declarations
144 // that come from the AST itself, not from included precompiled headers.
145 // FIXME: This is temporary; eventually, CIndex will always do this.
146 bool OnlyLocalDecls = false;
148 /// Whether to capture any diagnostics produced.
149 bool CaptureDiagnostics = false;
151 /// Track whether the main file was loaded from an AST or not.
154 /// What kind of translation unit this AST represents.
155 TranslationUnitKind TUKind = TU_Complete;
157 /// Whether we should time each operation.
160 /// Whether the ASTUnit should delete the remapped buffers.
161 bool OwnsRemappedFileBuffers = true;
163 /// Track the top-level decls which appeared in an ASTUnit which was loaded
164 /// from a source file.
166 // FIXME: This is just an optimization hack to avoid deserializing large parts
167 // of a PCH file when using the Index library on an ASTUnit loaded from
168 // source. In the long term we should make the Index library use efficient and
169 // more scalable search mechanisms.
170 std::vector<Decl*> TopLevelDecls;
172 /// Sorted (by file offset) vector of pairs of file offset/Decl.
173 using LocDeclsTy = SmallVector<std::pair<unsigned, Decl *>, 64>;
174 using FileDeclsTy = llvm::DenseMap<FileID, LocDeclsTy *>;
176 /// Map from FileID to the file-level declarations that it contains.
177 /// The files and decls are only local (and non-preamble) ones.
178 FileDeclsTy FileDecls;
180 /// The name of the original source file used to generate this ASTUnit.
181 std::string OriginalSourceFile;
183 /// The set of diagnostics produced when creating the preamble.
184 SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
186 /// The set of diagnostics produced when creating this
187 /// translation unit.
188 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
190 /// The set of diagnostics produced when failing to parse, e.g. due
191 /// to failure to load the PCH.
192 SmallVector<StoredDiagnostic, 4> FailedParseDiagnostics;
194 /// The number of stored diagnostics that come from the driver
197 /// Diagnostics that come from the driver are retained from one parse to
199 unsigned NumStoredDiagnosticsFromDriver = 0;
201 /// Counter that determines when we want to try building a
202 /// precompiled preamble.
204 /// If zero, we will never build a precompiled preamble. Otherwise,
205 /// it's treated as a counter that decrements each time we reparse
206 /// without the benefit of a precompiled preamble. When it hits 1,
207 /// we'll attempt to rebuild the precompiled header. This way, if
208 /// building the precompiled preamble fails, we won't try again for
209 /// some number of calls.
210 unsigned PreambleRebuildCounter = 0;
212 /// Cache pairs "filename - source location"
214 /// Cache contains only source locations from preamble so it is
215 /// guaranteed that they stay valid when the SourceManager is recreated.
216 /// This cache is used when loading preamble to increase performance
217 /// of that loading. It must be cleared when preamble is recreated.
218 llvm::StringMap<SourceLocation> PreambleSrcLocCache;
220 /// The contents of the preamble.
221 llvm::Optional<PrecompiledPreamble> Preamble;
223 /// When non-NULL, this is the buffer used to store the contents of
224 /// the main file when it has been padded for use with the precompiled
226 std::unique_ptr<llvm::MemoryBuffer> SavedMainFileBuffer;
228 /// The number of warnings that occurred while parsing the preamble.
230 /// This value will be used to restore the state of the \c DiagnosticsEngine
231 /// object when re-using the precompiled preamble. Note that only the
232 /// number of warnings matters, since we will not save the preamble
233 /// when any errors are present.
234 unsigned NumWarningsInPreamble = 0;
236 /// A list of the serialization ID numbers for each of the top-level
237 /// declarations parsed within the precompiled preamble.
238 std::vector<serialization::DeclID> TopLevelDeclsInPreamble;
240 /// Whether we should be caching code-completion results.
241 bool ShouldCacheCodeCompletionResults : 1;
243 /// Whether to include brief documentation within the set of code
244 /// completions cached.
245 bool IncludeBriefCommentsInCodeCompletion : 1;
247 /// True if non-system source files should be treated as volatile
248 /// (likely to change while trying to use them).
249 bool UserFilesAreVolatile : 1;
251 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
252 ASTUnit &AST, bool CaptureDiagnostics);
254 void TranslateStoredDiagnostics(FileManager &FileMgr,
255 SourceManager &SrcMan,
256 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
257 SmallVectorImpl<StoredDiagnostic> &Out);
259 void clearFileLevelDecls();
262 /// A cached code-completion result, which may be introduced in one of
263 /// many different contexts.
264 struct CachedCodeCompletionResult {
265 /// The code-completion string corresponding to this completion
267 CodeCompletionString *Completion;
269 /// A bitmask that indicates which code-completion contexts should
270 /// contain this completion result.
272 /// The bits in the bitmask correspond to the values of
273 /// CodeCompleteContext::Kind. To map from a completion context kind to a
274 /// bit, shift 1 by that number of bits. Many completions can occur in
275 /// several different contexts.
276 uint64_t ShowInContexts;
278 /// The priority given to this code-completion result.
281 /// The libclang cursor kind corresponding to this code-completion
285 /// The availability of this code-completion result.
286 CXAvailabilityKind Availability;
288 /// The simplified type class for a non-macro completion result.
289 SimplifiedTypeClass TypeClass;
291 /// The type of a non-macro completion result, stored as a unique
292 /// integer used by the string map of cached completion types.
294 /// This value will be zero if the type is not known, or a unique value
295 /// determined by the formatted type string. Se \c CachedCompletionTypes
296 /// for more information.
300 /// Retrieve the mapping from formatted type names to unique type
302 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
303 return CachedCompletionTypes;
306 /// Retrieve the allocator used to cache global code completions.
307 std::shared_ptr<GlobalCodeCompletionAllocator>
308 getCachedCompletionAllocator() {
309 return CachedCompletionAllocator;
312 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
314 CCTUInfo = llvm::make_unique<CodeCompletionTUInfo>(
315 std::make_shared<GlobalCodeCompletionAllocator>());
320 /// Allocator used to store cached code completions.
321 std::shared_ptr<GlobalCodeCompletionAllocator> CachedCompletionAllocator;
323 std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
325 /// The set of cached code-completion results.
326 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
328 /// A mapping from the formatted type name to a unique number for that
329 /// type, which is used for type equality comparisons.
330 llvm::StringMap<unsigned> CachedCompletionTypes;
332 /// A string hash of the top-level declaration and macro definition
333 /// names processed the last time that we reparsed the file.
335 /// This hash value is used to determine when we need to refresh the
336 /// global code-completion cache.
337 unsigned CompletionCacheTopLevelHashValue = 0;
339 /// A string hash of the top-level declaration and macro definition
340 /// names processed the last time that we reparsed the precompiled preamble.
342 /// This hash value is used to determine when we need to refresh the
343 /// global code-completion cache after a rebuild of the precompiled preamble.
344 unsigned PreambleTopLevelHashValue = 0;
346 /// The current hash value for the top-level declaration and macro
348 unsigned CurrentTopLevelHashValue = 0;
350 /// Bit used by CIndex to mark when a translation unit may be in an
351 /// inconsistent state, and is not safe to free.
352 unsigned UnsafeToFree : 1;
354 /// \brief Enumerator specifying the scope for skipping function bodies.
355 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
357 /// Cache any "global" code-completion results, so that we can avoid
358 /// recomputing them with each completion.
359 void CacheCodeCompletionResults();
361 /// Clear out and deallocate
362 void ClearCachedCompletionResults();
364 explicit ASTUnit(bool MainFileIsAST);
366 bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
367 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
368 IntrusiveRefCntPtr<vfs::FileSystem> VFS);
370 std::unique_ptr<llvm::MemoryBuffer> getMainBufferWithPrecompiledPreamble(
371 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
372 CompilerInvocation &PreambleInvocationIn,
373 IntrusiveRefCntPtr<vfs::FileSystem> VFS, bool AllowRebuild = true,
374 unsigned MaxLines = 0);
375 void RealizeTopLevelDeclsFromPreamble();
377 /// Transfers ownership of the objects (like SourceManager) from
378 /// \param CI to this ASTUnit.
379 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
381 /// Allows us to assert that ASTUnit is not being used concurrently,
382 /// which is not supported.
384 /// Clients should create instances of the ConcurrencyCheck class whenever
385 /// using the ASTUnit in a way that isn't intended to be concurrent, which is
386 /// just about any usage.
387 /// Becomes a noop in release mode; only useful for debug mode checking.
388 class ConcurrencyState {
389 void *Mutex; // a llvm::sys::MutexImpl in debug;
398 ConcurrencyState ConcurrencyCheckValue;
401 friend class ConcurrencyCheck;
403 class ConcurrencyCheck {
407 explicit ConcurrencyCheck(ASTUnit &Self) : Self(Self) {
408 Self.ConcurrencyCheckValue.start();
411 ~ConcurrencyCheck() {
412 Self.ConcurrencyCheckValue.finish();
416 ASTUnit(const ASTUnit &) = delete;
417 ASTUnit &operator=(const ASTUnit &) = delete;
420 bool isMainFileAST() const { return MainFileIsAST; }
422 bool isUnsafeToFree() const { return UnsafeToFree; }
423 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
425 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
426 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
428 const SourceManager &getSourceManager() const { return *SourceMgr; }
429 SourceManager &getSourceManager() { return *SourceMgr; }
431 const Preprocessor &getPreprocessor() const { return *PP; }
432 Preprocessor &getPreprocessor() { return *PP; }
433 std::shared_ptr<Preprocessor> getPreprocessorPtr() const { return PP; }
435 const ASTContext &getASTContext() const { return *Ctx; }
436 ASTContext &getASTContext() { return *Ctx; }
438 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
439 void setPreprocessor(std::shared_ptr<Preprocessor> pp);
441 /// Enable source-range based diagnostic messages.
443 /// If diagnostic messages with source-range information are to be expected
444 /// and AST comes not from file (e.g. after LoadFromCompilerInvocation) this
445 /// function has to be called.
446 /// The function is to be called only once and the AST should be associated
447 /// with the same source file afterwards.
448 void enableSourceFileDiagnostics();
450 bool hasSema() const { return (bool)TheSema; }
452 Sema &getSema() const {
453 assert(TheSema && "ASTUnit does not have a Sema object!");
457 const LangOptions &getLangOpts() const {
458 assert(LangOpts && "ASTUnit does not have language options");
462 const HeaderSearchOptions &getHeaderSearchOpts() const {
463 assert(HSOpts && "ASTUnit does not have header search options");
467 const PreprocessorOptions &getPreprocessorOpts() const {
468 assert(PPOpts && "ASTUnit does not have preprocessor options");
472 const FileManager &getFileManager() const { return *FileMgr; }
473 FileManager &getFileManager() { return *FileMgr; }
475 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
477 IntrusiveRefCntPtr<ASTReader> getASTReader() const;
479 StringRef getOriginalSourceFileName() const {
480 return OriginalSourceFile;
483 ASTMutationListener *getASTMutationListener();
484 ASTDeserializationListener *getDeserializationListener();
486 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
488 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
489 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
491 StringRef getMainFileName() const;
493 /// If this ASTUnit came from an AST file, returns the filename for it.
494 StringRef getASTFileName() const;
496 using top_level_iterator = std::vector<Decl *>::iterator;
498 top_level_iterator top_level_begin() {
499 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
500 if (!TopLevelDeclsInPreamble.empty())
501 RealizeTopLevelDeclsFromPreamble();
502 return TopLevelDecls.begin();
505 top_level_iterator top_level_end() {
506 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
507 if (!TopLevelDeclsInPreamble.empty())
508 RealizeTopLevelDeclsFromPreamble();
509 return TopLevelDecls.end();
512 std::size_t top_level_size() const {
513 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
514 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
517 bool top_level_empty() const {
518 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
519 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
522 /// Add a new top-level declaration.
523 void addTopLevelDecl(Decl *D) {
524 TopLevelDecls.push_back(D);
527 /// Add a new local file-level declaration.
528 void addFileLevelDecl(Decl *D);
530 /// Get the decls that are contained in a file in the Offset/Length
531 /// range. \p Length can be 0 to indicate a point at \p Offset instead of
533 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
534 SmallVectorImpl<Decl *> &Decls);
536 /// Retrieve a reference to the current top-level name hash value.
538 /// Note: This is used internally by the top-level tracking action
539 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
541 /// Get the source location for the given file:line:col triplet.
543 /// The difference with SourceManager::getLocation is that this method checks
544 /// whether the requested location points inside the precompiled preamble
545 /// in which case the returned source location will be a "loaded" one.
546 SourceLocation getLocation(const FileEntry *File,
547 unsigned Line, unsigned Col) const;
549 /// Get the source location for the given file:offset pair.
550 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
552 /// If \p Loc is a loaded location from the preamble, returns
553 /// the corresponding local location of the main file, otherwise it returns
555 SourceLocation mapLocationFromPreamble(SourceLocation Loc) const;
557 /// If \p Loc is a local location of the main file but inside the
558 /// preamble chunk, returns the corresponding loaded location from the
559 /// preamble, otherwise it returns \p Loc.
560 SourceLocation mapLocationToPreamble(SourceLocation Loc) const;
562 bool isInPreambleFileID(SourceLocation Loc) const;
563 bool isInMainFileID(SourceLocation Loc) const;
564 SourceLocation getStartOfMainFileID() const;
565 SourceLocation getEndOfPreambleFileID() const;
567 /// \see mapLocationFromPreamble.
568 SourceRange mapRangeFromPreamble(SourceRange R) const {
569 return SourceRange(mapLocationFromPreamble(R.getBegin()),
570 mapLocationFromPreamble(R.getEnd()));
573 /// \see mapLocationToPreamble.
574 SourceRange mapRangeToPreamble(SourceRange R) const {
575 return SourceRange(mapLocationToPreamble(R.getBegin()),
576 mapLocationToPreamble(R.getEnd()));
579 // Retrieve the diagnostics associated with this AST
580 using stored_diag_iterator = StoredDiagnostic *;
581 using stored_diag_const_iterator = const StoredDiagnostic *;
583 stored_diag_const_iterator stored_diag_begin() const {
584 return StoredDiagnostics.begin();
587 stored_diag_iterator stored_diag_begin() {
588 return StoredDiagnostics.begin();
591 stored_diag_const_iterator stored_diag_end() const {
592 return StoredDiagnostics.end();
595 stored_diag_iterator stored_diag_end() {
596 return StoredDiagnostics.end();
599 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
601 stored_diag_iterator stored_diag_afterDriver_begin() {
602 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
603 NumStoredDiagnosticsFromDriver = 0;
604 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
607 using cached_completion_iterator =
608 std::vector<CachedCodeCompletionResult>::iterator;
610 cached_completion_iterator cached_completion_begin() {
611 return CachedCompletionResults.begin();
614 cached_completion_iterator cached_completion_end() {
615 return CachedCompletionResults.end();
618 unsigned cached_completion_size() const {
619 return CachedCompletionResults.size();
622 /// Returns an iterator range for the local preprocessing entities
623 /// of the local Preprocessor, if this is a parsed source file, or the loaded
624 /// preprocessing entities of the primary module if this is an AST file.
625 llvm::iterator_range<PreprocessingRecord::iterator>
626 getLocalPreprocessingEntities() const;
628 /// Type for a function iterating over a number of declarations.
629 /// \returns true to continue iteration and false to abort.
630 using DeclVisitorFn = bool (*)(void *context, const Decl *D);
632 /// Iterate over local declarations (locally parsed if this is a parsed
633 /// source file or the loaded declarations of the primary module if this is an
635 /// \returns true if the iteration was complete or false if it was aborted.
636 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
638 /// Get the PCH file if one was included.
639 const FileEntry *getPCHFile();
641 /// Returns true if the ASTUnit was constructed from a serialized
643 bool isModuleFile() const;
645 std::unique_ptr<llvm::MemoryBuffer>
646 getBufferForFile(StringRef Filename, std::string *ErrorStr = nullptr);
648 /// Determine what kind of translation unit this AST represents.
649 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
651 /// Determine the input kind this AST unit represents.
652 InputKind getInputKind() const;
654 /// A mapping from a file name to the memory buffer that stores the
655 /// remapped contents of that file.
656 using RemappedFile = std::pair<std::string, llvm::MemoryBuffer *>;
658 /// Create a ASTUnit. Gets ownership of the passed CompilerInvocation.
659 static std::unique_ptr<ASTUnit>
660 create(std::shared_ptr<CompilerInvocation> CI,
661 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, bool CaptureDiagnostics,
662 bool UserFilesAreVolatile);
665 /// Load options and the preprocessor state.
666 LoadPreprocessorOnly,
668 /// Load the AST, but do not restore Sema state.
671 /// Load everything, including Sema.
675 /// Create a ASTUnit from an AST file.
677 /// \param Filename - The AST file to load.
679 /// \param PCHContainerRdr - The PCHContainerOperations to use for loading and
680 /// creating modules.
681 /// \param Diags - The diagnostics engine to use for reporting errors; its
682 /// lifetime is expected to extend past that of the returned ASTUnit.
684 /// \returns - The initialized ASTUnit or null if the AST failed to load.
685 static std::unique_ptr<ASTUnit> LoadFromASTFile(
686 const std::string &Filename, const PCHContainerReader &PCHContainerRdr,
687 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
688 const FileSystemOptions &FileSystemOpts, bool UseDebugInfo = false,
689 bool OnlyLocalDecls = false, ArrayRef<RemappedFile> RemappedFiles = None,
690 bool CaptureDiagnostics = false, bool AllowPCHWithCompilerErrors = false,
691 bool UserFilesAreVolatile = false);
694 /// Helper function for \c LoadFromCompilerInvocation() and
695 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
697 /// \param PrecompilePreambleAfterNParses After how many parses the preamble
698 /// of this translation unit should be precompiled, to improve the performance
699 /// of reparsing. Set to zero to disable preambles.
701 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
702 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
703 /// for it to be loaded correctly, VFS should have access to it(i.e., be an
704 /// overlay over RealFileSystem).
706 /// \returns \c true if a catastrophic failure occurred (which means that the
707 /// \c ASTUnit itself is invalid), or \c false otherwise.
708 bool LoadFromCompilerInvocation(
709 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
710 unsigned PrecompilePreambleAfterNParses,
711 IntrusiveRefCntPtr<vfs::FileSystem> VFS);
714 /// Create an ASTUnit from a source file, via a CompilerInvocation
715 /// object, by invoking the optionally provided ASTFrontendAction.
717 /// \param CI - The compiler invocation to use; it must have exactly one input
718 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
720 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
721 /// creating modules.
723 /// \param Diags - The diagnostics engine to use for reporting errors; its
724 /// lifetime is expected to extend past that of the returned ASTUnit.
726 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
729 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
732 /// \param Persistent - if true the returned ASTUnit will be complete.
733 /// false means the caller is only interested in getting info through the
734 /// provided \see Action.
736 /// \param ErrAST - If non-null and parsing failed without any AST to return
737 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
738 /// mainly to allow the caller to see the diagnostics.
739 /// This will only receive an ASTUnit if a new one was created. If an already
740 /// created ASTUnit was passed in \p Unit then the caller can check that.
742 static ASTUnit *LoadFromCompilerInvocationAction(
743 std::shared_ptr<CompilerInvocation> CI,
744 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
745 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
746 FrontendAction *Action = nullptr, ASTUnit *Unit = nullptr,
747 bool Persistent = true, StringRef ResourceFilesPath = StringRef(),
748 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
749 unsigned PrecompilePreambleAfterNParses = 0,
750 bool CacheCodeCompletionResults = false,
751 bool IncludeBriefCommentsInCodeCompletion = false,
752 bool UserFilesAreVolatile = false,
753 std::unique_ptr<ASTUnit> *ErrAST = nullptr);
755 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
756 /// CompilerInvocation object.
758 /// \param CI - The compiler invocation to use; it must have exactly one input
759 /// source file. The ASTUnit takes ownership of the CompilerInvocation object.
761 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
762 /// creating modules.
764 /// \param Diags - The diagnostics engine to use for reporting errors; its
765 /// lifetime is expected to extend past that of the returned ASTUnit.
767 // FIXME: Move OnlyLocalDecls, UseBumpAllocator to setters on the ASTUnit, we
768 // shouldn't need to specify them at construction time.
769 static std::unique_ptr<ASTUnit> LoadFromCompilerInvocation(
770 std::shared_ptr<CompilerInvocation> CI,
771 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
772 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
773 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
774 unsigned PrecompilePreambleAfterNParses = 0,
775 TranslationUnitKind TUKind = TU_Complete,
776 bool CacheCodeCompletionResults = false,
777 bool IncludeBriefCommentsInCodeCompletion = false,
778 bool UserFilesAreVolatile = false);
780 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
781 /// arguments, which must specify exactly one source file.
783 /// \param ArgBegin - The beginning of the argument vector.
785 /// \param ArgEnd - The end of the argument vector.
787 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
788 /// creating modules.
790 /// \param Diags - The diagnostics engine to use for reporting errors; its
791 /// lifetime is expected to extend past that of the returned ASTUnit.
793 /// \param ResourceFilesPath - The path to the compiler resource files.
795 /// \param ModuleFormat - If provided, uses the specific module format.
797 /// \param ErrAST - If non-null and parsing failed without any AST to return
798 /// (e.g. because the PCH could not be loaded), this accepts the ASTUnit
799 /// mainly to allow the caller to see the diagnostics.
801 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
802 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
803 /// for it to be loaded correctly, VFS should have access to it(i.e., be an
804 /// overlay over RealFileSystem). RealFileSystem will be used if \p VFS is nullptr.
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,
816 TranslationUnitKind TUKind = TU_Complete,
817 bool CacheCodeCompletionResults = false,
818 bool IncludeBriefCommentsInCodeCompletion = false,
819 bool AllowPCHWithCompilerErrors = false,
820 SkipFunctionBodiesScope SkipFunctionBodies =
821 SkipFunctionBodiesScope::None,
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,
826 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
828 /// Reparse the source files using the same command-line options that
829 /// were originally used to produce this translation unit.
831 /// \param VFS - A vfs::FileSystem to be used for all file accesses. Note that
832 /// preamble is saved to a temporary directory on a RealFileSystem, so in order
833 /// for it to be loaded correctly, VFS should give an access to this(i.e. be an
834 /// overlay over RealFileSystem). FileMgr->getVirtualFileSystem() will be used if
835 /// \p VFS is nullptr.
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,
841 IntrusiveRefCntPtr<vfs::FileSystem> VFS = nullptr);
843 /// Free data that will be re-generated on the next parse.
845 /// Preamble-related data is not affected.
846 void ResetForParse();
848 /// Perform code completion at the given file, line, and
849 /// column within this translation unit.
851 /// \param File The file in which code completion will occur.
853 /// \param Line The line at which code completion will occur.
855 /// \param Column The column at which code completion will occur.
857 /// \param IncludeMacros Whether to include macros in the code-completion
860 /// \param IncludeCodePatterns Whether to include code patterns (such as a
861 /// for loop) in the code-completion results.
863 /// \param IncludeBriefComments Whether to include brief documentation within
864 /// the set of code completions returned.
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,
876 SmallVectorImpl<const llvm::MemoryBuffer *> &OwnedBuffers);
878 /// Save this translation unit to a file with the given name.
880 /// \returns true if there was a file error or false if the save was
882 bool Save(StringRef File);
884 /// Serialize this translation unit with the given output stream.
886 /// \returns True if an error occurred, false otherwise.
887 bool serialize(raw_ostream &OS);
892 #endif // LLVM_CLANG_FRONTEND_ASTUNIT_H