clang-tools  14.0.0git
SymbolCollector.h
Go to the documentation of this file.
1 //===--- SymbolCollector.h ---------------------------------------*- 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 #ifndef LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOLCOLLECTOR_H
9 #define LLVM_CLANG_TOOLS_EXTRA_CLANGD_INDEX_SYMBOLCOLLECTOR_H
10 
11 #include "CanonicalIncludes.h"
12 #include "CollectMacros.h"
13 #include "Index.h"
14 #include "SymbolOrigin.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Decl.h"
17 #include "clang/Basic/SourceLocation.h"
18 #include "clang/Basic/SourceManager.h"
19 #include "clang/Index/IndexDataConsumer.h"
20 #include "clang/Index/IndexSymbol.h"
21 #include "clang/Sema/CodeCompleteConsumer.h"
22 #include "llvm/ADT/DenseMap.h"
23 #include "llvm/Support/Regex.h"
24 #include <functional>
25 
26 namespace clang {
27 namespace clangd {
28 
29 /// Collect declarations (symbols) from an AST.
30 /// It collects most declarations except:
31 /// - Implicit declarations
32 /// - Anonymous declarations (anonymous enum/class/struct, etc)
33 /// - Declarations in anonymous namespaces in headers
34 /// - Local declarations (in function bodies, blocks, etc)
35 /// - Template specializations
36 /// - Library-specific private declarations (e.g. private declaration generated
37 /// by protobuf compiler)
38 ///
39 /// References to main-file symbols are not collected.
40 ///
41 /// See also shouldCollectSymbol(...).
42 ///
43 /// Clients (e.g. clangd) can use SymbolCollector together with
44 /// index::indexTopLevelDecls to retrieve all symbols when the source file is
45 /// changed.
46 class SymbolCollector : public index::IndexDataConsumer {
47 public:
48  struct Options {
49  /// When symbol paths cannot be resolved to absolute paths (e.g. files in
50  /// VFS that does not have absolute path), combine the fallback directory
51  /// with symbols' paths to get absolute paths. This must be an absolute
52  /// path.
53  std::string FallbackDir;
54  bool CollectIncludePath = false;
55  /// If set, this is used to map symbol #include path to a potentially
56  /// different #include path.
57  const CanonicalIncludes *Includes = nullptr;
58  // Populate the Symbol.References field.
59  bool CountReferences = false;
60  /// The symbol ref kinds that will be collected.
61  /// If not set, SymbolCollector will not collect refs.
62  /// Note that references of namespace decls are not collected, as they
63  /// contribute large part of the index, and they are less useful compared
64  /// with other decls.
66  /// If set to true, SymbolCollector will collect all refs (from main file
67  /// and included headers); otherwise, only refs from main file will be
68  /// collected.
69  /// This flag is only meaningful when RefFilter is set.
70  bool RefsInHeaders = false;
71  // Every symbol collected will be stamped with this origin.
73  /// Collect macros.
74  /// Note that SymbolCollector must be run with preprocessor in order to
75  /// collect macros. For example, `indexTopLevelDecls` will not index any
76  /// macro even if this is true.
77  bool CollectMacro = false;
78  /// Collect symbols local to main-files, such as static functions, symbols
79  /// inside an anonymous namespace, function-local classes and its member
80  /// functions.
82  /// Collect references to main-file symbols.
83  bool CollectMainFileRefs = false;
84  /// If set to true, SymbolCollector will collect doc for all symbols.
85  /// Note that documents of symbols being indexed for completion will always
86  /// be collected regardless of this option.
87  bool StoreAllDocumentation = false;
88  /// If this is set, only collect symbols/references from a file if
89  /// `FileFilter(SM, FID)` is true. If not set, all files are indexed.
90  std::function<bool(const SourceManager &, FileID)> FileFilter = nullptr;
91  };
92 
95 
96  /// Returns true is \p ND should be collected.
97  static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx,
98  const Options &Opts, bool IsMainFileSymbol);
99 
100  void initialize(ASTContext &Ctx) override;
101 
102  void setPreprocessor(std::shared_ptr<Preprocessor> PP) override {
103  this->PP = std::move(PP);
104  }
105 
106  bool
107  handleDeclOccurrence(const Decl *D, index::SymbolRoleSet Roles,
108  ArrayRef<index::SymbolRelation> Relations,
109  SourceLocation Loc,
110  index::IndexDataConsumer::ASTNodeInfo ASTNode) override;
111 
112  bool handleMacroOccurrence(const IdentifierInfo *Name, const MacroInfo *MI,
113  index::SymbolRoleSet Roles,
114  SourceLocation Loc) override;
115 
116  void handleMacros(const MainFileMacros &MacroRefsToIndex);
117 
118  SymbolSlab takeSymbols() { return std::move(Symbols).build(); }
119  RefSlab takeRefs() { return std::move(Refs).build(); }
120  RelationSlab takeRelations() { return std::move(Relations).build(); }
121 
122  /// Returns true if we are interested in references and declarations from \p
123  /// FID. If this function return false, bodies of functions inside those files
124  /// will be skipped to decrease indexing time.
125  bool shouldIndexFile(FileID FID);
126 
127  void finish() override;
128 
129 private:
130  const Symbol *addDeclaration(const NamedDecl &, SymbolID,
131  bool IsMainFileSymbol);
132  void addDefinition(const NamedDecl &, const Symbol &DeclSymbol);
133  void processRelations(const NamedDecl &ND, const SymbolID &ID,
134  ArrayRef<index::SymbolRelation> Relations);
135 
136  llvm::Optional<SymbolLocation> getTokenLocation(SourceLocation TokLoc);
137 
138  llvm::Optional<std::string> getIncludeHeader(const Symbol &S, FileID);
139 
140  // All Symbols collected from the AST.
141  SymbolSlab::Builder Symbols;
142  // File IDs for Symbol.IncludeHeaders.
143  // The final spelling is calculated in finish().
144  llvm::DenseMap<SymbolID, FileID> IncludeFiles;
145  void setIncludeLocation(const Symbol &S, SourceLocation);
146  // Indexed macros, to be erased if they turned out to be include guards.
147  llvm::DenseSet<const IdentifierInfo *> IndexedMacros;
148  // All refs collected from the AST. It includes:
149  // 1) symbols declared in the preamble and referenced from the main file (
150  // which is not a header), or
151  // 2) symbols declared and referenced from the main file (which is a header)
152  RefSlab::Builder Refs;
153  // All relations collected from the AST.
154  RelationSlab::Builder Relations;
155  ASTContext *ASTCtx;
156  std::shared_ptr<Preprocessor> PP;
157  std::shared_ptr<GlobalCodeCompletionAllocator> CompletionAllocator;
158  std::unique_ptr<CodeCompletionTUInfo> CompletionTUInfo;
159  Options Opts;
160  struct SymbolRef {
161  SourceLocation Loc;
162  index::SymbolRoleSet Roles;
163  const Decl *Container;
164  };
165  // Symbols referenced from the current TU, flushed on finish().
166  llvm::DenseSet<const NamedDecl *> ReferencedDecls;
167  llvm::DenseSet<const IdentifierInfo *> ReferencedMacros;
168  llvm::DenseMap<const NamedDecl *, std::vector<SymbolRef>> DeclRefs;
169  llvm::DenseMap<SymbolID, std::vector<SymbolRef>> MacroRefs;
170  // Maps canonical declaration provided by clang to canonical declaration for
171  // an index symbol, if clangd prefers a different declaration than that
172  // provided by clang. For example, friend declaration might be considered
173  // canonical by clang but should not be considered canonical in the index
174  // unless it's a definition.
175  llvm::DenseMap<const Decl *, const Decl *> CanonicalDecls;
176  // Cache whether to index a file or not.
177  llvm::DenseMap<FileID, bool> FilesToIndexCache;
178  // Encapsulates calculations and caches around header paths, which headers
179  // to insert for which symbol, etc.
180  class HeaderFileURICache;
181  std::unique_ptr<HeaderFileURICache> HeaderFileURIs;
182 };
183 
184 } // namespace clangd
185 } // namespace clang
186 
187 #endif
clang::clangd::SymbolCollector::setPreprocessor
void setPreprocessor(std::shared_ptr< Preprocessor > PP) override
Definition: SymbolCollector.h:102
Loc
SourceLocation Loc
Definition: KernelNameRestrictionCheck.cpp:45
SymbolOrigin.h
clang::clangd::SymbolCollector::Options::Origin
SymbolOrigin Origin
Definition: SymbolCollector.h:72
clang::clangd::SymbolCollector::Options::CollectMainFileSymbols
bool CollectMainFileSymbols
Collect symbols local to main-files, such as static functions, symbols inside an anonymous namespace,...
Definition: SymbolCollector.h:81
clang::clangd::RefKind::Unknown
@ Unknown
clang::clangd::SymbolCollector::handleMacros
void handleMacros(const MainFileMacros &MacroRefsToIndex)
Definition: SymbolCollector.cpp:488
clang::clangd::SymbolCollector::Options::CollectMainFileRefs
bool CollectMainFileRefs
Collect references to main-file symbols.
Definition: SymbolCollector.h:83
clang::clangd::SymbolCollector::Options::RefsInHeaders
bool RefsInHeaders
If set to true, SymbolCollector will collect all refs (from main file and included headers); otherwis...
Definition: SymbolCollector.h:70
clang::clangd::SymbolCollector::shouldCollectSymbol
static bool shouldCollectSymbol(const NamedDecl &ND, const ASTContext &ASTCtx, const Options &Opts, bool IsMainFileSymbol)
Returns true is ND should be collected.
Definition: SymbolCollector.cpp:313
clang::clangd::SymbolCollector::handleDeclOccurrence
bool handleDeclOccurrence(const Decl *D, index::SymbolRoleSet Roles, ArrayRef< index::SymbolRelation > Relations, SourceLocation Loc, index::IndexDataConsumer::ASTNodeInfo ASTNode) override
Definition: SymbolCollector.cpp:364
clang::clangd::RefKind
RefKind
Describes the kind of a cross-reference.
Definition: Ref.h:30
Index.h
clang::clangd::RefSlab::Builder
RefSlab::Builder is a mutable container that can 'freeze' to RefSlab.
Definition: Ref.h:134
clang::clangd::SymbolCollector::shouldIndexFile
bool shouldIndexFile(FileID FID)
Returns true if we are interested in references and declarations from FID.
Definition: SymbolCollector.cpp:862
clang::clangd::SymbolCollector::Options::FileFilter
std::function< bool(const SourceManager &, FileID)> FileFilter
If this is set, only collect symbols/references from a file if FileFilter(SM, FID) is true.
Definition: SymbolCollector.h:90
clang::clangd::SymbolCollector::takeRelations
RelationSlab takeRelations()
Definition: SymbolCollector.h:120
Ctx
Context Ctx
Definition: TUScheduler.cpp:460
clang::clangd::RelationSlab::Builder
RelationSlab::Builder is a mutable container that can 'freeze' to RelationSlab.
Definition: Relation.h:77
clang::clangd::SymbolCollector::finish
void finish() override
Definition: SymbolCollector.cpp:656
clang::clangd::RefSlab
An efficient structure of storing large set of symbol references in memory.
Definition: Ref.h:110
clang::clangd::SymbolCollector::Options::RefFilter
RefKind RefFilter
The symbol ref kinds that will be collected.
Definition: SymbolCollector.h:65
CanonicalIncludes.h
ns1::ns2::D
@ D
Definition: CategoricalFeature.h:3
Decl
const FunctionDecl * Decl
Definition: AvoidBindCheck.cpp:100
clang::clangd::CanonicalIncludes
Maps a definition location onto an #include file, based on a set of filename rules.
Definition: CanonicalIncludes.h:36
clang::clangd::RelationSlab
Definition: Relation.h:52
CollectMacros.h
clang::clangd::SymbolCollector::takeRefs
RefSlab takeRefs()
Definition: SymbolCollector.h:119
clang::clangd::MainFileMacros
Definition: CollectMacros.h:31
clang::clangd::SymbolCollector::Options::CollectMacro
bool CollectMacro
Collect macros.
Definition: SymbolCollector.h:77
clang::clangd::Symbol
The class presents a C++ symbol, e.g.
Definition: Symbol.h:36
Name
static constexpr llvm::StringLiteral Name
Definition: UppercaseLiteralSuffixCheck.cpp:28
clang::clangd::SymbolCollector::Options::Includes
const CanonicalIncludes * Includes
If set, this is used to map symbol #include path to a potentially different #include path.
Definition: SymbolCollector.h:57
clang::clangd::SymbolOrigin
SymbolOrigin
Definition: SymbolOrigin.h:21
clang::clangd::SymbolCollector::handleMacroOccurrence
bool handleMacroOccurrence(const IdentifierInfo *Name, const MacroInfo *MI, index::SymbolRoleSet Roles, SourceLocation Loc) override
Definition: SymbolCollector.cpp:532
clang::clangd::SymbolCollector::takeSymbols
SymbolSlab takeSymbols()
Definition: SymbolCollector.h:118
ID
static char ID
Definition: Logger.cpp:74
clang::clangd::SymbolCollector::initialize
void initialize(ASTContext &Ctx) override
Definition: SymbolCollector.cpp:304
clang::clangd::SymbolCollector
Collect declarations (symbols) from an AST.
Definition: SymbolCollector.h:46
clang
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//
Definition: ApplyReplacements.h:27
clang::clangd::SymbolCollector::Options::CountReferences
bool CountReferences
Definition: SymbolCollector.h:59
clang::clangd::SymbolCollector::Options
Definition: SymbolCollector.h:48
clang::clangd::SymbolOrigin::Unknown
@ Unknown
clang::clangd::SymbolCollector::Options::CollectIncludePath
bool CollectIncludePath
Definition: SymbolCollector.h:54
clang::clangd::SymbolSlab::Builder
SymbolSlab::Builder is a mutable container that can 'freeze' to SymbolSlab.
Definition: Symbol.h:200
clang::clangd::SymbolSlab
An immutable symbol container that stores a set of symbols.
Definition: Symbol.h:177
clang::clangd::SymbolCollector::Options::StoreAllDocumentation
bool StoreAllDocumentation
If set to true, SymbolCollector will collect doc for all symbols.
Definition: SymbolCollector.h:87
clang::clangd::SymbolID
Definition: SymbolID.h:32
clang::clangd::SymbolCollector::SymbolCollector
SymbolCollector(Options Opts)
Definition: SymbolCollector.cpp:301
clang::clangd::ASTNode
Simplified description of a clang AST node.
Definition: Protocol.h:1764
clang::clangd::SymbolCollector::Options::FallbackDir
std::string FallbackDir
When symbol paths cannot be resolved to absolute paths (e.g.
Definition: SymbolCollector.h:53
clang::clangd::SymbolCollector::~SymbolCollector
~SymbolCollector()