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"
64 class ASTDeserializationListener;
65 class ASTMutationListener;
67 class CompilerInstance;
68 class CompilerInvocation;
75 class MemoryBufferCache;
76 class PCHContainerOperations;
77 class PCHContainerReader;
79 class PreprocessorOptions;
83 /// \brief Enumerates the available scopes for skipping function bodies.
84 enum class SkipFunctionBodiesScope { None, Preamble, PreambleAndMainFile };
86 /// Utility class for loading a ASTContext from an AST file.
89 struct StandaloneFixIt {
90 std::pair<unsigned, unsigned> RemoveRange;
91 std::pair<unsigned, unsigned> InsertFromRange;
92 std::string CodeToInsert;
93 bool BeforePreviousInsertions;
96 struct StandaloneDiagnostic {
98 DiagnosticsEngine::Level Level;
100 std::string Filename;
102 std::vector<std::pair<unsigned, unsigned>> Ranges;
103 std::vector<StandaloneFixIt> FixIts;
107 std::shared_ptr<LangOptions> LangOpts;
108 IntrusiveRefCntPtr<DiagnosticsEngine> Diagnostics;
109 IntrusiveRefCntPtr<FileManager> FileMgr;
110 IntrusiveRefCntPtr<SourceManager> SourceMgr;
111 IntrusiveRefCntPtr<MemoryBufferCache> PCMCache;
112 std::unique_ptr<HeaderSearch> HeaderInfo;
113 IntrusiveRefCntPtr<TargetInfo> Target;
114 std::shared_ptr<Preprocessor> PP;
115 IntrusiveRefCntPtr<ASTContext> Ctx;
116 std::shared_ptr<TargetOptions> TargetOpts;
117 std::shared_ptr<HeaderSearchOptions> HSOpts;
118 std::shared_ptr<PreprocessorOptions> PPOpts;
119 IntrusiveRefCntPtr<ASTReader> Reader;
120 bool HadModuleLoaderFatalFailure = false;
122 struct ASTWriterData;
123 std::unique_ptr<ASTWriterData> WriterData;
125 FileSystemOptions FileSystemOpts;
127 /// The AST consumer that received information about the translation
128 /// unit as it was parsed or loaded.
129 std::unique_ptr<ASTConsumer> Consumer;
131 /// The semantic analysis object used to type-check the translation
133 std::unique_ptr<Sema> TheSema;
135 /// Optional owned invocation, just used to make the invocation used in
136 /// LoadFromCommandLine available.
137 std::shared_ptr<CompilerInvocation> Invocation;
139 /// Fake module loader: the AST unit doesn't need to load any modules.
140 TrivialModuleLoader ModuleLoader;
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;
147 /// Whether to capture any diagnostics produced.
148 bool CaptureDiagnostics = false;
150 /// Track whether the main file was loaded from an AST or not.
153 /// What kind of translation unit this AST represents.
154 TranslationUnitKind TUKind = TU_Complete;
156 /// Whether we should time each operation.
159 /// Whether the ASTUnit should delete the remapped buffers.
160 bool OwnsRemappedFileBuffers = true;
162 /// Track the top-level decls which appeared in an ASTUnit which was loaded
163 /// from a source file.
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;
171 /// Sorted (by file offset) vector of pairs of file offset/Decl.
172 using LocDeclsTy = SmallVector<std::pair<unsigned, Decl *>, 64>;
173 using FileDeclsTy = llvm::DenseMap<FileID, LocDeclsTy *>;
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;
179 /// The name of the original source file used to generate this ASTUnit.
180 std::string OriginalSourceFile;
182 /// The set of diagnostics produced when creating the preamble.
183 SmallVector<StandaloneDiagnostic, 4> PreambleDiagnostics;
185 /// The set of diagnostics produced when creating this
186 /// translation unit.
187 SmallVector<StoredDiagnostic, 4> StoredDiagnostics;
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;
193 /// The number of stored diagnostics that come from the driver
196 /// Diagnostics that come from the driver are retained from one parse to
198 unsigned NumStoredDiagnosticsFromDriver = 0;
200 /// Counter that determines when we want to try building a
201 /// precompiled preamble.
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;
211 /// Cache pairs "filename - source location"
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;
219 /// The contents of the preamble.
220 llvm::Optional<PrecompiledPreamble> Preamble;
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
225 std::unique_ptr<llvm::MemoryBuffer> SavedMainFileBuffer;
227 /// The number of warnings that occurred while parsing the preamble.
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;
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;
239 /// Whether we should be caching code-completion results.
240 bool ShouldCacheCodeCompletionResults : 1;
242 /// Whether to include brief documentation within the set of code
243 /// completions cached.
244 bool IncludeBriefCommentsInCodeCompletion : 1;
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;
250 static void ConfigureDiags(IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
251 ASTUnit &AST, bool CaptureDiagnostics);
253 void TranslateStoredDiagnostics(FileManager &FileMgr,
254 SourceManager &SrcMan,
255 const SmallVectorImpl<StandaloneDiagnostic> &Diags,
256 SmallVectorImpl<StoredDiagnostic> &Out);
258 void clearFileLevelDecls();
261 /// A cached code-completion result, which may be introduced in one of
262 /// many different contexts.
263 struct CachedCodeCompletionResult {
264 /// The code-completion string corresponding to this completion
266 CodeCompletionString *Completion;
268 /// A bitmask that indicates which code-completion contexts should
269 /// contain this completion result.
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;
277 /// The priority given to this code-completion result.
280 /// The libclang cursor kind corresponding to this code-completion
284 /// The availability of this code-completion result.
285 CXAvailabilityKind Availability;
287 /// The simplified type class for a non-macro completion result.
288 SimplifiedTypeClass TypeClass;
290 /// The type of a non-macro completion result, stored as a unique
291 /// integer used by the string map of cached completion types.
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.
299 /// Retrieve the mapping from formatted type names to unique type
301 llvm::StringMap<unsigned> &getCachedCompletionTypes() {
302 return CachedCompletionTypes;
305 /// Retrieve the allocator used to cache global code completions.
306 std::shared_ptr<GlobalCodeCompletionAllocator>
307 getCachedCompletionAllocator() {
308 return CachedCompletionAllocator;
311 CodeCompletionTUInfo &getCodeCompletionTUInfo() {
313 CCTUInfo = llvm::make_unique<CodeCompletionTUInfo>(
314 std::make_shared<GlobalCodeCompletionAllocator>());
319 /// Allocator used to store cached code completions.
320 std::shared_ptr<GlobalCodeCompletionAllocator> CachedCompletionAllocator;
322 std::unique_ptr<CodeCompletionTUInfo> CCTUInfo;
324 /// The set of cached code-completion results.
325 std::vector<CachedCodeCompletionResult> CachedCompletionResults;
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;
331 /// A string hash of the top-level declaration and macro definition
332 /// names processed the last time that we reparsed the file.
334 /// This hash value is used to determine when we need to refresh the
335 /// global code-completion cache.
336 unsigned CompletionCacheTopLevelHashValue = 0;
338 /// A string hash of the top-level declaration and macro definition
339 /// names processed the last time that we reparsed the precompiled preamble.
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;
345 /// The current hash value for the top-level declaration and macro
347 unsigned CurrentTopLevelHashValue = 0;
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;
353 /// \brief Enumerator specifying the scope for skipping function bodies.
354 SkipFunctionBodiesScope SkipFunctionBodies = SkipFunctionBodiesScope::None;
356 /// Cache any "global" code-completion results, so that we can avoid
357 /// recomputing them with each completion.
358 void CacheCodeCompletionResults();
360 /// Clear out and deallocate
361 void ClearCachedCompletionResults();
363 explicit ASTUnit(bool MainFileIsAST);
365 bool Parse(std::shared_ptr<PCHContainerOperations> PCHContainerOps,
366 std::unique_ptr<llvm::MemoryBuffer> OverrideMainBuffer,
367 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS);
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();
376 /// Transfers ownership of the objects (like SourceManager) from
377 /// \param CI to this ASTUnit.
378 void transferASTDataFromCompilerInstance(CompilerInstance &CI);
380 /// Allows us to assert that ASTUnit is not being used concurrently,
381 /// which is not supported.
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;
397 ConcurrencyState ConcurrencyCheckValue;
400 friend class ConcurrencyCheck;
402 class ConcurrencyCheck {
406 explicit ConcurrencyCheck(ASTUnit &Self) : Self(Self) {
407 Self.ConcurrencyCheckValue.start();
410 ~ConcurrencyCheck() {
411 Self.ConcurrencyCheckValue.finish();
415 ASTUnit(const ASTUnit &) = delete;
416 ASTUnit &operator=(const ASTUnit &) = delete;
419 bool isMainFileAST() const { return MainFileIsAST; }
421 bool isUnsafeToFree() const { return UnsafeToFree; }
422 void setUnsafeToFree(bool Value) { UnsafeToFree = Value; }
424 const DiagnosticsEngine &getDiagnostics() const { return *Diagnostics; }
425 DiagnosticsEngine &getDiagnostics() { return *Diagnostics; }
427 const SourceManager &getSourceManager() const { return *SourceMgr; }
428 SourceManager &getSourceManager() { return *SourceMgr; }
430 const Preprocessor &getPreprocessor() const { return *PP; }
431 Preprocessor &getPreprocessor() { return *PP; }
432 std::shared_ptr<Preprocessor> getPreprocessorPtr() const { return PP; }
434 const ASTContext &getASTContext() const { return *Ctx; }
435 ASTContext &getASTContext() { return *Ctx; }
437 void setASTContext(ASTContext *ctx) { Ctx = ctx; }
438 void setPreprocessor(std::shared_ptr<Preprocessor> pp);
440 /// Enable source-range based diagnostic messages.
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();
449 bool hasSema() const { return (bool)TheSema; }
451 Sema &getSema() const {
452 assert(TheSema && "ASTUnit does not have a Sema object!");
456 const LangOptions &getLangOpts() const {
457 assert(LangOpts && "ASTUnit does not have language options");
461 const HeaderSearchOptions &getHeaderSearchOpts() const {
462 assert(HSOpts && "ASTUnit does not have header search options");
466 const PreprocessorOptions &getPreprocessorOpts() const {
467 assert(PPOpts && "ASTUnit does not have preprocessor options");
471 const FileManager &getFileManager() const { return *FileMgr; }
472 FileManager &getFileManager() { return *FileMgr; }
474 const FileSystemOptions &getFileSystemOpts() const { return FileSystemOpts; }
476 IntrusiveRefCntPtr<ASTReader> getASTReader() const;
478 StringRef getOriginalSourceFileName() const {
479 return OriginalSourceFile;
482 ASTMutationListener *getASTMutationListener();
483 ASTDeserializationListener *getDeserializationListener();
485 bool getOnlyLocalDecls() const { return OnlyLocalDecls; }
487 bool getOwnsRemappedFileBuffers() const { return OwnsRemappedFileBuffers; }
488 void setOwnsRemappedFileBuffers(bool val) { OwnsRemappedFileBuffers = val; }
490 StringRef getMainFileName() const;
492 /// If this ASTUnit came from an AST file, returns the filename for it.
493 StringRef getASTFileName() const;
495 using top_level_iterator = std::vector<Decl *>::iterator;
497 top_level_iterator top_level_begin() {
498 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
499 if (!TopLevelDeclsInPreamble.empty())
500 RealizeTopLevelDeclsFromPreamble();
501 return TopLevelDecls.begin();
504 top_level_iterator top_level_end() {
505 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
506 if (!TopLevelDeclsInPreamble.empty())
507 RealizeTopLevelDeclsFromPreamble();
508 return TopLevelDecls.end();
511 std::size_t top_level_size() const {
512 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
513 return TopLevelDeclsInPreamble.size() + TopLevelDecls.size();
516 bool top_level_empty() const {
517 assert(!isMainFileAST() && "Invalid call for AST based ASTUnit!");
518 return TopLevelDeclsInPreamble.empty() && TopLevelDecls.empty();
521 /// Add a new top-level declaration.
522 void addTopLevelDecl(Decl *D) {
523 TopLevelDecls.push_back(D);
526 /// Add a new local file-level declaration.
527 void addFileLevelDecl(Decl *D);
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
532 void findFileRegionDecls(FileID File, unsigned Offset, unsigned Length,
533 SmallVectorImpl<Decl *> &Decls);
535 /// Retrieve a reference to the current top-level name hash value.
537 /// Note: This is used internally by the top-level tracking action
538 unsigned &getCurrentTopLevelHashValue() { return CurrentTopLevelHashValue; }
540 /// Get the source location for the given file:line:col triplet.
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;
548 /// Get the source location for the given file:offset pair.
549 SourceLocation getLocation(const FileEntry *File, unsigned Offset) const;
551 /// If \p Loc is a loaded location from the preamble, returns
552 /// the corresponding local location of the main file, otherwise it returns
554 SourceLocation mapLocationFromPreamble(SourceLocation Loc) const;
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;
561 bool isInPreambleFileID(SourceLocation Loc) const;
562 bool isInMainFileID(SourceLocation Loc) const;
563 SourceLocation getStartOfMainFileID() const;
564 SourceLocation getEndOfPreambleFileID() const;
566 /// \see mapLocationFromPreamble.
567 SourceRange mapRangeFromPreamble(SourceRange R) const {
568 return SourceRange(mapLocationFromPreamble(R.getBegin()),
569 mapLocationFromPreamble(R.getEnd()));
572 /// \see mapLocationToPreamble.
573 SourceRange mapRangeToPreamble(SourceRange R) const {
574 return SourceRange(mapLocationToPreamble(R.getBegin()),
575 mapLocationToPreamble(R.getEnd()));
578 // Retrieve the diagnostics associated with this AST
579 using stored_diag_iterator = StoredDiagnostic *;
580 using stored_diag_const_iterator = const StoredDiagnostic *;
582 stored_diag_const_iterator stored_diag_begin() const {
583 return StoredDiagnostics.begin();
586 stored_diag_iterator stored_diag_begin() {
587 return StoredDiagnostics.begin();
590 stored_diag_const_iterator stored_diag_end() const {
591 return StoredDiagnostics.end();
594 stored_diag_iterator stored_diag_end() {
595 return StoredDiagnostics.end();
598 unsigned stored_diag_size() const { return StoredDiagnostics.size(); }
600 stored_diag_iterator stored_diag_afterDriver_begin() {
601 if (NumStoredDiagnosticsFromDriver > StoredDiagnostics.size())
602 NumStoredDiagnosticsFromDriver = 0;
603 return StoredDiagnostics.begin() + NumStoredDiagnosticsFromDriver;
606 using cached_completion_iterator =
607 std::vector<CachedCodeCompletionResult>::iterator;
609 cached_completion_iterator cached_completion_begin() {
610 return CachedCompletionResults.begin();
613 cached_completion_iterator cached_completion_end() {
614 return CachedCompletionResults.end();
617 unsigned cached_completion_size() const {
618 return CachedCompletionResults.size();
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;
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);
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
634 /// \returns true if the iteration was complete or false if it was aborted.
635 bool visitLocalTopLevelDecls(void *context, DeclVisitorFn Fn);
637 /// Get the PCH file if one was included.
638 const FileEntry *getPCHFile();
640 /// Returns true if the ASTUnit was constructed from a serialized
642 bool isModuleFile() const;
644 std::unique_ptr<llvm::MemoryBuffer>
645 getBufferForFile(StringRef Filename, std::string *ErrorStr = nullptr);
647 /// Determine what kind of translation unit this AST represents.
648 TranslationUnitKind getTranslationUnitKind() const { return TUKind; }
650 /// Determine the input kind this AST unit represents.
651 InputKind getInputKind() const;
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 *>;
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);
664 /// Load options and the preprocessor state.
665 LoadPreprocessorOnly,
667 /// Load the AST, but do not restore Sema state.
670 /// Load everything, including Sema.
674 /// Create a ASTUnit from an AST file.
676 /// \param Filename - The AST file to load.
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.
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,
686 WhatToLoad ToLoad, IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
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);
693 /// Helper function for \c LoadFromCompilerInvocation() and
694 /// \c LoadFromCommandLine(), which loads an AST from a compiler invocation.
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.
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).
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,
710 IntrusiveRefCntPtr<llvm::vfs::FileSystem> VFS);
713 /// Create an ASTUnit from a source file, via a CompilerInvocation
714 /// object, by invoking the optionally provided ASTFrontendAction.
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.
719 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
720 /// creating modules.
722 /// \param Diags - The diagnostics engine to use for reporting errors; its
723 /// lifetime is expected to extend past that of the returned ASTUnit.
725 /// \param Action - The ASTFrontendAction to invoke. Its ownership is not
728 /// \param Unit - optionally an already created ASTUnit. Its ownership is not
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.
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.
741 static ASTUnit *LoadFromCompilerInvocationAction(
742 std::shared_ptr<CompilerInvocation> CI,
743 std::shared_ptr<PCHContainerOperations> PCHContainerOps,
744 IntrusiveRefCntPtr<DiagnosticsEngine> Diags,
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);
754 /// LoadFromCompilerInvocation - Create an ASTUnit from a source file, via a
755 /// CompilerInvocation object.
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.
760 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
761 /// creating modules.
763 /// \param Diags - The diagnostics engine to use for reporting errors; its
764 /// lifetime is expected to extend past that of the returned ASTUnit.
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,
771 IntrusiveRefCntPtr<DiagnosticsEngine> Diags, FileManager *FileMgr,
772 bool OnlyLocalDecls = false, bool CaptureDiagnostics = false,
773 unsigned PrecompilePreambleAfterNParses = 0,
774 TranslationUnitKind TUKind = TU_Complete,
775 bool CacheCodeCompletionResults = false,
776 bool IncludeBriefCommentsInCodeCompletion = false,
777 bool UserFilesAreVolatile = false);
779 /// LoadFromCommandLine - Create an ASTUnit from a vector of command line
780 /// arguments, which must specify exactly one source file.
782 /// \param ArgBegin - The beginning of the argument vector.
784 /// \param ArgEnd - The end of the argument vector.
786 /// \param PCHContainerOps - The PCHContainerOperations to use for loading and
787 /// creating modules.
789 /// \param Diags - The diagnostics engine to use for reporting errors; its
790 /// lifetime is expected to extend past that of the returned ASTUnit.
792 /// \param ResourceFilesPath - The path to the compiler resource files.
794 /// \param ModuleFormat - If provided, uses the specific module format.
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.
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.
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<llvm::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 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.
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<llvm::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