clang 24.0.0git
IndexingAction.cpp
Go to the documentation of this file.
1//===- IndexingAction.cpp - Frontend index action -------------------------===//
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
10#include "IndexingContext.h"
11#include "clang/AST/DeclGroup.h"
19#include <memory>
20
21using namespace clang;
22using namespace clang::index;
23
24namespace {
25
26class IndexPPCallbacks final : public PPCallbacks {
27 std::shared_ptr<IndexingContext> IndexCtx;
28
29public:
30 IndexPPCallbacks(std::shared_ptr<IndexingContext> IndexCtx)
31 : IndexCtx(std::move(IndexCtx)) {}
32
33 void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
34 SourceRange Range, const MacroArgs *Args) override {
35 IndexCtx->handleMacroReference(*MacroNameTok.getIdentifierInfo(),
36 Range.getBegin(), *MD.getMacroInfo());
37 }
38
39 void MacroDefined(const Token &MacroNameTok,
40 const MacroDirective *MD) override {
41 IndexCtx->handleMacroDefined(*MacroNameTok.getIdentifierInfo(),
42 MacroNameTok.getLocation(),
43 *MD->getMacroInfo());
44 }
45
46 void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD,
47 const MacroDirective *Undef) override {
48 if (!MD.getMacroInfo()) // Ignore noop #undef.
49 return;
50 IndexCtx->handleMacroUndefined(*MacroNameTok.getIdentifierInfo(),
51 MacroNameTok.getLocation(),
52 *MD.getMacroInfo());
53 }
54
55 void Defined(const Token &MacroNameTok, const MacroDefinition &MD,
56 SourceRange Range) override {
57 if (!MD.getMacroInfo()) // Ignore nonexistent macro.
58 return;
59 // Note: this is defined(M), not #define M
60 IndexCtx->handleMacroReference(*MacroNameTok.getIdentifierInfo(),
61 MacroNameTok.getLocation(),
62 *MD.getMacroInfo());
63 }
64 void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
65 const MacroDefinition &MD) override {
66 if (!MD.getMacroInfo()) // Ignore non-existent macro.
67 return;
68 IndexCtx->handleMacroReference(*MacroNameTok.getIdentifierInfo(),
69 MacroNameTok.getLocation(),
70 *MD.getMacroInfo());
71 }
72 void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
73 const MacroDefinition &MD) override {
74 if (!MD.getMacroInfo()) // Ignore nonexistent macro.
75 return;
76 IndexCtx->handleMacroReference(*MacroNameTok.getIdentifierInfo(),
77 MacroNameTok.getLocation(),
78 *MD.getMacroInfo());
79 }
80
83 void Elifdef(SourceLocation Loc, const Token &MacroNameTok,
84 const MacroDefinition &MD) override {
85 if (!MD.getMacroInfo()) // Ignore non-existent macro.
86 return;
87 IndexCtx->handleMacroReference(*MacroNameTok.getIdentifierInfo(),
88 MacroNameTok.getLocation(),
89 *MD.getMacroInfo());
90 }
91 void Elifndef(SourceLocation Loc, const Token &MacroNameTok,
92 const MacroDefinition &MD) override {
93 if (!MD.getMacroInfo()) // Ignore non-existent macro.
94 return;
95 IndexCtx->handleMacroReference(*MacroNameTok.getIdentifierInfo(),
96 MacroNameTok.getLocation(),
97 *MD.getMacroInfo());
98 }
99};
100
101class IndexASTConsumer final : public ASTConsumer {
102 std::shared_ptr<IndexDataConsumer> DataConsumer;
103 std::shared_ptr<IndexingContext> IndexCtx;
104 std::shared_ptr<Preprocessor> PP;
105 std::function<bool(const Decl *)> ShouldSkipFunctionBody;
106 bool DeferIndexingToEndOfTranslationUnit;
107
108public:
109 IndexASTConsumer(std::shared_ptr<IndexDataConsumer> DataConsumer,
110 const IndexingOptions &Opts,
111 std::shared_ptr<Preprocessor> PP,
112 std::function<bool(const Decl *)> ShouldSkipFunctionBody)
113 : DataConsumer(std::move(DataConsumer)),
114 IndexCtx(new IndexingContext(Opts, *this->DataConsumer)),
115 PP(std::move(PP)),
116 ShouldSkipFunctionBody(std::move(ShouldSkipFunctionBody)),
117 DeferIndexingToEndOfTranslationUnit(
118 Opts.DeferIndexingToEndOfTranslationUnit) {
119 assert(this->DataConsumer != nullptr);
120 assert(this->PP != nullptr);
121 }
122
123protected:
124 void Initialize(ASTContext &Context) override {
125 IndexCtx->setASTContext(Context);
126 IndexCtx->getDataConsumer().initialize(Context);
127 IndexCtx->getDataConsumer().setPreprocessor(PP);
128 PP->addPPCallbacks(std::make_unique<IndexPPCallbacks>(IndexCtx));
129 }
130
131 bool HandleTopLevelDecl(DeclGroupRef DG) override {
132 if (!DeferIndexingToEndOfTranslationUnit)
133 return IndexCtx->indexDeclGroupRef(DG);
134 return true;
135 }
136
137 void HandleInterestingDecl(DeclGroupRef DG) override {
138 // Ignore deserialized decls.
139 }
140
141 void HandleTopLevelDeclInObjCContainer(DeclGroupRef DG) override {
142 if (!DeferIndexingToEndOfTranslationUnit)
143 IndexCtx->indexDeclGroupRef(DG);
144 }
145
146 void HandleTranslationUnit(ASTContext &Ctx) override {
147 if (DeferIndexingToEndOfTranslationUnit)
148 for (auto *DG : Ctx.getTranslationUnitDecl()->decls())
149 IndexCtx->indexTopLevelDecl(DG);
150 DataConsumer->finish();
151 }
152
153 bool shouldSkipFunctionBody(Decl *D) override {
154 return ShouldSkipFunctionBody(D);
155 }
156};
157
158class IndexAction final : public ASTFrontendAction {
159 std::shared_ptr<IndexDataConsumer> DataConsumer;
160 IndexingOptions Opts;
161
162public:
163 IndexAction(std::shared_ptr<IndexDataConsumer> DataConsumer,
164 const IndexingOptions &Opts)
165 : DataConsumer(std::move(DataConsumer)), Opts(Opts) {
166 assert(this->DataConsumer != nullptr);
167 }
168
169protected:
170 std::unique_ptr<ASTConsumer> CreateASTConsumer(CompilerInstance &CI,
171 StringRef InFile) override {
172 return std::make_unique<IndexASTConsumer>(
173 DataConsumer, Opts, CI.getPreprocessorPtr(),
174 /*ShouldSkipFunctionBody=*/[](const Decl *) { return false; });
175 }
176};
177
178} // anonymous namespace
179
180std::unique_ptr<ASTConsumer> index::createIndexingASTConsumer(
181 std::shared_ptr<IndexDataConsumer> DataConsumer,
182 const IndexingOptions &Opts, std::shared_ptr<Preprocessor> PP,
183 std::function<bool(const Decl *)> ShouldSkipFunctionBody) {
184 return std::make_unique<IndexASTConsumer>(DataConsumer, Opts, PP,
185 ShouldSkipFunctionBody);
186}
187
188std::unique_ptr<ASTConsumer> clang::index::createIndexingASTConsumer(
189 std::shared_ptr<IndexDataConsumer> DataConsumer,
190 const IndexingOptions &Opts, std::shared_ptr<Preprocessor> PP) {
191 std::function<bool(const Decl *)> ShouldSkipFunctionBody = [](const Decl *) {
192 return false;
193 };
194 if (Opts.ShouldTraverseDecl)
195 ShouldSkipFunctionBody =
196 [ShouldTraverseDecl(Opts.ShouldTraverseDecl)](const Decl *D) {
197 return !ShouldTraverseDecl(D);
198 };
199 return createIndexingASTConsumer(std::move(DataConsumer), Opts, std::move(PP),
200 std::move(ShouldSkipFunctionBody));
201}
202
203std::unique_ptr<FrontendAction>
204index::createIndexingAction(std::shared_ptr<IndexDataConsumer> DataConsumer,
205 const IndexingOptions &Opts) {
206 assert(DataConsumer != nullptr);
207 return std::make_unique<IndexAction>(std::move(DataConsumer), Opts);
208}
209
210static bool topLevelDeclVisitor(void *context, const Decl *D) {
211 IndexingContext &IndexCtx = *static_cast<IndexingContext *>(context);
212 return IndexCtx.indexTopLevelDecl(D);
213}
214
215static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IndexCtx) {
217}
218
220 const MacroInfo *MI,
221 MacroDirective::Kind DirectiveKind,
222 SourceLocation Loc,
223 IndexDataConsumer &DataConsumer) {
224 // When using modules, it may happen that we find #undef of a macro that
225 // was defined in another module. In such case, MI may be nullptr, since
226 // we only look for macro definitions in the current TU. In that case,
227 // there is nothing to index.
228 if (!MI)
229 return;
230
231 // Skip implicit visibility change.
232 if (DirectiveKind == MacroDirective::MD_Visibility)
233 return;
234
235 auto Role = DirectiveKind == MacroDirective::MD_Define
238 DataConsumer.handleMacroOccurrence(II, MI, static_cast<unsigned>(Role), Loc);
239}
240
242 IndexDataConsumer &DataConsumer) {
243 for (const auto &M : PP.macros()) {
244 for (auto *MD = M.second.getLatest(); MD; MD = MD->getPrevious()) {
245 indexPreprocessorMacro(M.first, MD->getMacroInfo(), MD->getKind(),
246 MD->getLocation(), DataConsumer);
247 }
248 }
249}
250
253 IndexDataConsumer &DataConsumer) {
254 for (const auto &M : PP.macros()) {
255 if (M.second.getLatest() == nullptr) {
256 for (auto *MM : PP.getLeafModuleMacros(M.first)) {
257 auto *OwningMod = MM->getOwningModule();
258 if (OwningMod && OwningMod->getASTFileKey() &&
259 *OwningMod->getASTFileKey() == Mod.FileKey) {
260 if (auto *MI = MM->getMacroInfo()) {
262 MI->getDefinitionLoc(), DataConsumer);
263 }
264 }
265 }
266 }
267 }
268}
269
271 IndexingOptions Opts) {
272 IndexingContext IndexCtx(Opts, DataConsumer);
273 IndexCtx.setASTContext(Unit.getASTContext());
274 DataConsumer.initialize(Unit.getASTContext());
275 DataConsumer.setPreprocessor(Unit.getPreprocessorPtr());
276
278 indexPreprocessorMacros(Unit.getPreprocessor(), DataConsumer);
279 indexTranslationUnit(Unit, IndexCtx);
280 DataConsumer.finish();
281}
282
285 IndexDataConsumer &DataConsumer,
286 IndexingOptions Opts) {
287 IndexingContext IndexCtx(Opts, DataConsumer);
288 IndexCtx.setASTContext(Ctx);
289
290 DataConsumer.initialize(Ctx);
291
293 indexPreprocessorMacros(PP, DataConsumer);
294
295 for (const Decl *D : Decls)
296 IndexCtx.indexTopLevelDecl(D);
297 DataConsumer.finish();
298}
299
300std::unique_ptr<PPCallbacks>
302 return std::make_unique<IndexPPCallbacks>(
303 std::make_shared<IndexingContext>(Opts, Consumer));
304}
305
307 IndexDataConsumer &DataConsumer,
308 IndexingOptions Opts) {
309 ASTContext &Ctx = Reader.getContext();
310 IndexingContext IndexCtx(Opts, DataConsumer);
311 IndexCtx.setASTContext(Ctx);
312 DataConsumer.initialize(Ctx);
313
314 if (Opts.IndexMacrosInPreprocessor) {
315 indexPreprocessorModuleMacros(Reader.getPreprocessor(), Mod, DataConsumer);
316 }
317
318 for (const Decl *D : Reader.getModuleFileLevelDecls(Mod)) {
319 IndexCtx.indexTopLevelDecl(D);
320 }
321 DataConsumer.finish();
322}
std::shared_ptr< TokenRole > Role
A token can have a special role that can carry extra information about the token's formatting.
Defines the clang::FrontendAction interface and various convenience abstract classes (clang::ASTFront...
static void indexPreprocessorModuleMacros(Preprocessor &PP, serialization::ModuleFile &Mod, IndexDataConsumer &DataConsumer)
static void indexPreprocessorMacros(Preprocessor &PP, IndexDataConsumer &DataConsumer)
static void indexTranslationUnit(ASTUnit &Unit, IndexingContext &IndexCtx)
static void indexPreprocessorMacro(const IdentifierInfo *II, const MacroInfo *MI, MacroDirective::Kind DirectiveKind, SourceLocation Loc, IndexDataConsumer &DataConsumer)
static bool topLevelDeclVisitor(void *context, const Decl *D)
Defines the PPCallbacks interface.
Defines the clang::Preprocessor interface.
ASTConsumer - This is an abstract interface that should be implemented by clients that read ASTs.
Definition ASTConsumer.h:35
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
TranslationUnitDecl * getTranslationUnitDecl() const
Abstract base class to use for AST consumer-based frontend actions.
Reads an AST files chain containing the contents of a translation unit.
Definition ASTReader.h:427
ASTContext & getContext()
Retrieve the AST context that this AST reader supplements.
Definition ASTReader.h:2593
llvm::iterator_range< ModuleDeclIterator > getModuleFileLevelDecls(ModuleFile &Mod)
Preprocessor & getPreprocessor() const
Retrieve the preprocessor.
Definition ASTReader.h:1977
Utility class for loading a ASTContext from an AST file.
Definition ASTUnit.h:94
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:2425
std::shared_ptr< Preprocessor > getPreprocessorPtr() const
Definition ASTUnit.h:450
const Preprocessor & getPreprocessor() const
Definition ASTUnit.h:448
const ASTContext & getASTContext() const
Definition ASTUnit.h:452
std::shared_ptr< Preprocessor > getPreprocessorPtr()
decl_range decls() const
decls_begin/decls_end - Iterate over the declarations stored in this context.
Definition DeclBase.h:2403
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
One of these records is kept for each identifier that is lexed.
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
Definition MacroInfo.h:612
const MacroInfo * getMacroInfo() const
Definition MacroInfo.h:417
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:40
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
virtual void Elifndef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD)
Hook called whenever an #elifndef branch is taken.
virtual void Elifdef(SourceLocation Loc, const Token &MacroNameTok, const MacroDefinition &MD)
Hook called whenever an #elifdef branch is taken.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
ArrayRef< ModuleMacro * > getLeafModuleMacros(const IdentifierInfo *II) const
Get the list of leaf (non-overridden) module macros for a name.
llvm::iterator_range< macro_iterator > macros(bool IncludeExternalMacros=true) const
Encodes a location in the source.
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:197
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:142
virtual void setPreprocessor(std::shared_ptr< Preprocessor > PP)
virtual bool handleMacroOccurrence(const IdentifierInfo *Name, const MacroInfo *MI, SymbolRoleSet Roles, SourceLocation Loc)
virtual void initialize(ASTContext &Ctx)
void setASTContext(ASTContext &ctx)
bool indexTopLevelDecl(const Decl *D)
Information about a module that has been loaded by the ASTReader.
Definition ModuleFile.h:158
ModuleFileKey FileKey
The key ModuleManager used for the module file.
Definition ModuleFile.h:180
std::unique_ptr< PPCallbacks > indexMacrosCallback(IndexDataConsumer &Consumer, IndexingOptions Opts)
Creates a PPCallbacks that indexes macros and feeds macros to Consumer.
void indexTopLevelDecls(ASTContext &Ctx, Preprocessor &PP, ArrayRef< const Decl * > Decls, IndexDataConsumer &DataConsumer, IndexingOptions Opts)
Recursively indexes Decls.
void indexModuleFile(serialization::ModuleFile &Mod, ASTReader &Reader, IndexDataConsumer &DataConsumer, IndexingOptions Opts)
Recursively indexes all top-level decls in the module.
std::unique_ptr< ASTConsumer > createIndexingASTConsumer(std::shared_ptr< IndexDataConsumer > DataConsumer, const IndexingOptions &Opts, std::shared_ptr< Preprocessor > PP)
Creates an ASTConsumer that indexes all symbols (macros and AST decls).
std::unique_ptr< FrontendAction > createIndexingAction(std::shared_ptr< IndexDataConsumer > DataConsumer, const IndexingOptions &Opts)
Creates a frontend action that indexes all symbols (macros and AST decls).
void indexASTUnit(ASTUnit &Unit, IndexDataConsumer &DataConsumer, IndexingOptions Opts)
Recursively indexes all decls in the AST.
Top level wrappers for InstallAPI frontend operations.
int const char * function
Definition c++config.h:31
std::function< bool(const Decl *)> ShouldTraverseDecl