1 //===--- RewriteRule.h - RewriteRule class ----------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 /// Defines the RewriteRule class and related functions for creating,
11 /// modifying and interpreting RewriteRules.
13 //===----------------------------------------------------------------------===//
15 #ifndef LLVM_CLANG_TOOLING_TRANSFORMER_REWRITE_RULE_H_
16 #define LLVM_CLANG_TOOLING_TRANSFORMER_REWRITE_RULE_H_
18 #include "clang/ASTMatchers/ASTMatchFinder.h"
19 #include "clang/ASTMatchers/ASTMatchers.h"
20 #include "clang/ASTMatchers/ASTMatchersInternal.h"
21 #include "clang/Tooling/Refactoring/AtomicChange.h"
22 #include "clang/Tooling/Transformer/MatchConsumer.h"
23 #include "clang/Tooling/Transformer/RangeSelector.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Error.h"
32 namespace transformer {
33 using TextGenerator = MatchConsumer<std::string>;
35 // Description of a source-code edit, expressed in terms of an AST node.
36 // Includes: an ID for the (bound) node, a selector for source related to the
37 // node, a replacement and, optionally, an explanation for the edit.
39 // * Target: the source code impacted by the rule. This identifies an AST node,
40 // or part thereof (\c Part), whose source range indicates the extent of the
41 // replacement applied by the replacement term. By default, the extent is the
42 // node matched by the pattern term (\c NodePart::Node). Target's are typed
43 // (\c Kind), which guides the determination of the node extent.
45 // * Replacement: a function that produces a replacement string for the target,
46 // based on the match result.
48 // * Note: (optional) a note specifically for this edit, potentially referencing
49 // elements of the match. This will be displayed to the user, where possible;
50 // for example, in clang-tidy diagnostics. Use of notes should be rare --
51 // explanations of the entire rewrite should be set in the rule
52 // (`RewriteRule::Explanation`) instead. Notes serve the rare cases wherein
53 // edit-specific diagnostics are required.
55 // `ASTEdit` should be built using the `change` convenience functions. For
58 // change(name(fun), text("Frodo"))
60 // Or, if we use Stencil for the TextGenerator:
62 // using stencil::cat;
63 // change(statement(thenNode), cat("{", thenNode, "}"))
64 // change(callArgs(call), cat(x, ",", y))
66 // Or, if you are changing the node corresponding to the rule's matcher, you can
67 // use the single-argument override of \c change:
69 // change(cat("different_expr"))
72 RangeSelector TargetRange;
73 TextGenerator Replacement;
77 /// Format of the path in an include directive -- angle brackets or quotes.
78 enum class IncludeFormat {
83 /// Description of a source-code transformation.
85 // A *rewrite rule* describes a transformation of source code. A simple rule
86 // contains each of the following components:
88 // * Matcher: the pattern term, expressed as clang matchers (with Transformer
91 // * Edits: a set of Edits to the source code, described with ASTEdits.
93 // * Explanation: explanation of the rewrite. This will be displayed to the
94 // user, where possible; for example, in clang-tidy diagnostics.
96 // However, rules can also consist of (sub)rules, where the first that matches
97 // is applied and the rest are ignored. So, the above components are gathered
98 // as a `Case` and a rule is a list of cases.
100 // Rule cases have an additional, implicit, component: the parameters. These are
101 // portions of the pattern which are left unspecified, yet bound in the pattern
102 // so that we can reference them in the edits.
104 // The \c Transformer class can be used to apply the rewrite rule and obtain the
105 // corresponding replacements.
108 ast_matchers::internal::DynTypedMatcher Matcher;
109 SmallVector<ASTEdit, 1> Edits;
110 TextGenerator Explanation;
111 // Include paths to add to the file affected by this case. These are
112 // bundled with the `Case`, rather than the `RewriteRule`, because each case
113 // might have different associated changes to the includes.
114 std::vector<std::pair<std::string, IncludeFormat>> AddedIncludes;
116 // We expect RewriteRules will most commonly include only one case.
117 SmallVector<Case, 1> Cases;
119 // ID used as the default target of each match. The node described by the
120 // matcher is should always be bound to this id.
121 static constexpr llvm::StringLiteral RootID = "___root___";
124 /// Convenience function for constructing a simple \c RewriteRule.
125 RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
126 SmallVector<ASTEdit, 1> Edits,
127 TextGenerator Explanation = nullptr);
129 /// Convenience overload of \c makeRule for common case of only one edit.
130 inline RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
132 TextGenerator Explanation = nullptr) {
133 SmallVector<ASTEdit, 1> Edits;
134 Edits.emplace_back(std::move(Edit));
135 return makeRule(std::move(M), std::move(Edits), std::move(Explanation));
138 /// For every case in Rule, adds an include directive for the given header. The
139 /// common use is assumed to be a rule with only one case. For example, to
140 /// replace a function call and add headers corresponding to the new code, one
143 /// auto R = makeRule(callExpr(callee(functionDecl(hasName("foo")))),
144 /// change(text("bar()")));
145 /// AddInclude(R, "path/to/bar_header.h");
146 /// AddInclude(R, "vector", IncludeFormat::Angled);
148 void addInclude(RewriteRule &Rule, llvm::StringRef Header,
149 IncludeFormat Format = IncludeFormat::Quoted);
151 /// Applies the first rule whose pattern matches; other rules are ignored. If
152 /// the matchers are independent then order doesn't matter. In that case,
153 /// `applyFirst` is simply joining the set of rules into one.
155 // `applyFirst` is like an `anyOf` matcher with an edit action attached to each
156 // of its cases. Anywhere you'd use `anyOf(m1.bind("id1"), m2.bind("id2"))` and
157 // then dispatch on those ids in your code for control flow, `applyFirst` lifts
158 // that behavior to the rule level. So, you can write `applyFirst({makeRule(m1,
159 // action1), makeRule(m2, action2), ...});`
161 // For example, consider a type `T` with a deterministic serialization function,
162 // `serialize()`. For performance reasons, we would like to make it
163 // non-deterministic. Therefore, we want to drop the expectation that
164 // `a.serialize() = b.serialize() iff a = b` (although we'll maintain
165 // `deserialize(a.serialize()) = a`).
167 // We have three cases to consider (for some equality function, `eq`):
169 // eq(a.serialize(), b.serialize()) --> eq(a,b)
170 // eq(a, b.serialize()) --> eq(deserialize(a), b)
171 // eq(a.serialize(), b) --> eq(a, deserialize(b))
174 // `applyFirst` allows us to specify each independently:
176 // auto eq_fun = functionDecl(...);
177 // auto method_call = cxxMemberCallExpr(...);
179 // auto two_calls = callExpr(callee(eq_fun), hasArgument(0, method_call),
180 // hasArgument(1, method_call));
182 // callExpr(callee(eq_fun), callExpr(hasArgument(0, method_call)));
184 // callExpr(callee(eq_fun), callExpr(hasArgument(1, method_call)));
186 // RewriteRule R = applyFirst({makeRule(two_calls, two_calls_action),
187 // makeRule(left_call, left_call_action),
188 // makeRule(right_call, right_call_action)});
190 RewriteRule applyFirst(ArrayRef<RewriteRule> Rules);
192 /// Replaces a portion of the source text with \p Replacement.
193 ASTEdit change(RangeSelector Target, TextGenerator Replacement);
195 /// Replaces the entirety of a RewriteRule's match with \p Replacement. For
196 /// example, to replace a function call, one could write:
198 /// makeRule(callExpr(callee(functionDecl(hasName("foo")))),
199 /// change(text("bar()")))
201 inline ASTEdit change(TextGenerator Replacement) {
202 return change(node(RewriteRule::RootID), std::move(Replacement));
205 /// Inserts \p Replacement before \p S, leaving the source selected by \S
207 inline ASTEdit insertBefore(RangeSelector S, TextGenerator Replacement) {
208 return change(before(std::move(S)), std::move(Replacement));
211 /// Inserts \p Replacement after \p S, leaving the source selected by \S
213 inline ASTEdit insertAfter(RangeSelector S, TextGenerator Replacement) {
214 return change(after(std::move(S)), std::move(Replacement));
217 /// Removes the source selected by \p S.
218 inline ASTEdit remove(RangeSelector S) {
219 return change(std::move(S),
220 [](const ast_matchers::MatchFinder::MatchResult &)
221 -> Expected<std::string> { return ""; });
224 /// The following three functions are a low-level part of the RewriteRule
225 /// API. We expose them for use in implementing the fixtures that interpret
226 /// RewriteRule, like Transformer and TransfomerTidy, or for more advanced
229 // FIXME: These functions are really public, if advanced, elements of the
230 // RewriteRule API. Recast them as such. Or, just declare these functions
231 // public and well-supported and move them out of `detail`.
233 /// Builds a single matcher for the rule, covering all of the rule's cases.
234 /// Only supports Rules whose cases' matchers share the same base "kind"
235 /// (`Stmt`, `Decl`, etc.) Deprecated: use `buildMatchers` instead, which
236 /// supports mixing matchers of different kinds.
237 ast_matchers::internal::DynTypedMatcher buildMatcher(const RewriteRule &Rule);
239 /// Builds a set of matchers that cover the rule (one for each distinct node
240 /// matcher base kind: Stmt, Decl, etc.). Node-matchers for `QualType` and
241 /// `Type` are not permitted, since such nodes carry no source location
242 /// information and are therefore not relevant for rewriting. If any such
243 /// matchers are included, will return an empty vector.
244 std::vector<ast_matchers::internal::DynTypedMatcher>
245 buildMatchers(const RewriteRule &Rule);
247 /// Gets the beginning location of the source matched by a rewrite rule. If the
248 /// match occurs within a macro expansion, returns the beginning of the
249 /// expansion point. `Result` must come from the matching of a rewrite rule.
251 getRuleMatchLoc(const ast_matchers::MatchFinder::MatchResult &Result);
253 /// Returns the \c Case of \c Rule that was selected in the match result.
254 /// Assumes a matcher built with \c buildMatcher.
255 const RewriteRule::Case &
256 findSelectedCase(const ast_matchers::MatchFinder::MatchResult &Result,
257 const RewriteRule &Rule);
259 /// A source "transformation," represented by a character range in the source to
260 /// be replaced and a corresponding replacement string.
261 struct Transformation {
262 CharSourceRange Range;
263 std::string Replacement;
266 /// Attempts to translate `Edits`, which are in terms of AST nodes bound in the
267 /// match `Result`, into Transformations, which are in terms of the source code
270 /// Returns an empty vector if any of the edits apply to portions of the source
271 /// that are ineligible for rewriting (certain interactions with macros, for
272 /// example). Fails if any invariants are violated relating to bound nodes in
273 /// the match. However, it does not fail in the case of conflicting edits --
274 /// conflict handling is left to clients. We recommend use of the \c
275 /// AtomicChange or \c Replacements classes for assistance in detecting such
277 Expected<SmallVector<Transformation, 1>>
278 translateEdits(const ast_matchers::MatchFinder::MatchResult &Result,
279 llvm::ArrayRef<ASTEdit> Edits);
280 } // namespace detail
281 } // namespace transformer
284 // DEPRECATED: These are temporary aliases supporting client migration to the
285 // `transformer` namespace.
286 /// Wraps a string as a TextGenerator.
287 using TextGenerator = transformer::TextGenerator;
289 inline TextGenerator text(std::string M) {
290 return [M](const ast_matchers::MatchFinder::MatchResult &)
291 -> Expected<std::string> { return M; };
294 using transformer::addInclude;
295 using transformer::applyFirst;
296 using transformer::change;
297 using transformer::insertAfter;
298 using transformer::insertBefore;
299 using transformer::makeRule;
300 using transformer::remove;
301 using transformer::RewriteRule;
302 using transformer::IncludeFormat;
304 using namespace transformer::detail;
305 } // namespace detail
306 } // namespace tooling
309 #endif // LLVM_CLANG_TOOLING_TRANSFORMER_REWRITE_RULE_H_