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