1 //===--- ASTMatchFinder.h - Structural query framework ----------*- 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 // Provides a way to construct an ASTConsumer that runs given matchers
11 // over the AST and invokes a given callback on every match.
13 // The general idea is to construct a matcher expression that describes a
14 // subtree match on the AST. Next, a callback that is executed every time the
15 // expression matches is registered, and the matcher is run over the AST of
16 // some code. Matched subexpressions can be bound to string IDs and easily
17 // be accessed from the registered callback. The callback can than use the
18 // AST nodes that the subexpressions matched on to output information about
19 // the match or construct changes that can be applied to the code.
22 // class HandleMatch : public MatchFinder::MatchCallback {
24 // virtual void Run(const MatchFinder::MatchResult &Result) {
25 // const CXXRecordDecl *Class =
26 // Result.Nodes.GetDeclAs<CXXRecordDecl>("id");
31 // int main(int argc, char **argv) {
32 // ClangTool Tool(argc, argv);
33 // MatchFinder finder;
34 // finder.AddMatcher(Id("id", record(hasName("::a_namespace::AClass"))),
36 // return Tool.Run(newFrontendActionFactory(&finder));
39 //===----------------------------------------------------------------------===//
41 #ifndef LLVM_CLANG_AST_MATCHERS_AST_MATCH_FINDER_H
42 #define LLVM_CLANG_AST_MATCHERS_AST_MATCH_FINDER_H
44 #include "clang/ASTMatchers/ASTMatchers.h"
48 namespace ast_matchers {
50 /// \brief A class to allow finding matches over the Clang AST.
52 /// After creation, you can add multiple matchers to the MatchFinder via
53 /// calls to addMatcher(...).
55 /// Once all matchers are added, newASTConsumer() returns an ASTConsumer
56 /// that will trigger the callbacks specified via addMatcher(...) when a match
59 /// The order of matches is guaranteed to be equivalent to doing a pre-order
60 /// traversal on the AST, and applying the matchers in the order in which they
61 /// were added to the MatchFinder.
63 /// See ASTMatchers.h for more information about how to create matchers.
65 /// Not intended to be subclassed.
68 /// \brief Contains all information for a given match.
70 /// Every time a match is found, the MatchFinder will invoke the registered
71 /// MatchCallback with a MatchResult containing information about the match.
73 MatchResult(const BoundNodes &Nodes, clang::ASTContext *Context);
75 /// \brief Contains the nodes bound on the current match.
77 /// This allows user code to easily extract matched AST nodes.
78 const BoundNodes Nodes;
80 /// \brief Utilities for interpreting the matched AST structures.
82 clang::ASTContext * const Context;
83 clang::SourceManager * const SourceManager;
87 /// \brief Called when the Match registered for it was successfully found
91 virtual ~MatchCallback();
93 /// \brief Called on every match by the \c MatchFinder.
94 virtual void run(const MatchResult &Result) = 0;
96 /// \brief Called at the start of each translation unit.
98 /// Optionally override to do per translation unit tasks.
99 virtual void onStartOfTranslationUnit() {}
102 /// \brief Called when parsing is finished. Intended for testing only.
103 class ParsingDoneTestCallback {
105 virtual ~ParsingDoneTestCallback();
106 virtual void run() = 0;
112 /// \brief Adds a matcher to execute when running over the AST.
114 /// Calls 'Action' with the BoundNodes on every match.
115 /// Adding more than one 'NodeMatch' allows finding different matches in a
116 /// single pass over the AST.
118 /// Does not take ownership of 'Action'.
120 void addMatcher(const DeclarationMatcher &NodeMatch,
121 MatchCallback *Action);
122 void addMatcher(const TypeMatcher &NodeMatch,
123 MatchCallback *Action);
124 void addMatcher(const StatementMatcher &NodeMatch,
125 MatchCallback *Action);
126 void addMatcher(const NestedNameSpecifierMatcher &NodeMatch,
127 MatchCallback *Action);
128 void addMatcher(const NestedNameSpecifierLocMatcher &NodeMatch,
129 MatchCallback *Action);
130 void addMatcher(const TypeLocMatcher &NodeMatch,
131 MatchCallback *Action);
134 /// \brief Creates a clang ASTConsumer that finds all matches.
135 clang::ASTConsumer *newASTConsumer();
137 /// \brief Calls the registered callbacks on all matches on the given \p Node.
139 /// Note that there can be multiple matches on a single node, for
140 /// example when using decl(forEachDescendant(stmt())).
143 template <typename T> void match(const T &Node, ASTContext &Context) {
144 match(clang::ast_type_traits::DynTypedNode::create(Node), Context);
146 void match(const clang::ast_type_traits::DynTypedNode &Node,
147 ASTContext &Context);
150 /// \brief Registers a callback to notify the end of parsing.
152 /// The provided closure is called after parsing is done, before the AST is
153 /// traversed. Useful for benchmarking.
154 /// Each call to FindAll(...) will call the closure once.
155 void registerTestCallbackAfterParsing(ParsingDoneTestCallback *ParsingDone);
158 /// \brief For each \c DynTypedMatcher a \c MatchCallback that will be called
160 std::vector<std::pair<const internal::DynTypedMatcher*, MatchCallback*> >
161 MatcherCallbackPairs;
163 /// \brief Called when parsing is done.
164 ParsingDoneTestCallback *ParsingDone;
167 /// \brief Returns the results of matching \p Matcher on \p Node.
169 /// Collects the \c BoundNodes of all callback invocations when matching
170 /// \p Matcher on \p Node and returns the collected results.
172 /// Multiple results occur when using matchers like \c forEachDescendant,
173 /// which generate a result for each sub-match.
177 template <typename MatcherT, typename NodeT>
178 SmallVector<BoundNodes, 1>
179 match(MatcherT Matcher, const NodeT &Node, ASTContext &Context);
181 template <typename MatcherT>
182 SmallVector<BoundNodes, 1>
183 match(MatcherT Matcher, const ast_type_traits::DynTypedNode &Node,
184 ASTContext &Context);
187 /// \brief Returns the first result of type \c NodeT bound to \p BoundTo.
189 /// Returns \c NULL if there is no match, or if the matching node cannot be
190 /// casted to \c NodeT.
192 /// This is useful in combanation with \c match():
194 /// Decl *D = selectFirst<Decl>("id", match(Matcher.bind("id"),
197 template <typename NodeT>
199 selectFirst(StringRef BoundTo, const SmallVectorImpl<BoundNodes> &Results) {
200 for (SmallVectorImpl<BoundNodes>::const_iterator I = Results.begin(),
203 if (NodeT *Node = I->getNodeAs<NodeT>(BoundTo))
210 class CollectMatchesCallback : public MatchFinder::MatchCallback {
212 virtual void run(const MatchFinder::MatchResult &Result) {
213 Nodes.push_back(Result.Nodes);
215 SmallVector<BoundNodes, 1> Nodes;
219 template <typename MatcherT>
220 SmallVector<BoundNodes, 1>
221 match(MatcherT Matcher, const ast_type_traits::DynTypedNode &Node,
222 ASTContext &Context) {
223 internal::CollectMatchesCallback Callback;
225 Finder.addMatcher(Matcher, &Callback);
226 Finder.match(Node, Context);
227 return Callback.Nodes;
230 template <typename MatcherT, typename NodeT>
231 SmallVector<BoundNodes, 1>
232 match(MatcherT Matcher, const NodeT &Node, ASTContext &Context) {
233 return match(Matcher, ast_type_traits::DynTypedNode::create(Node), Context);
236 } // end namespace ast_matchers
237 } // end namespace clang
239 #endif // LLVM_CLANG_AST_MATCHERS_AST_MATCH_FINDER_H