clang  10.0.0svn
RewriteRule.h
Go to the documentation of this file.
1 //===--- RewriteRule.h - RewriteRule class ----------------------*- 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 /// \file
10 /// Defines the RewriteRule class and related functions for creating,
11 /// modifying and interpreting RewriteRules.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CLANG_TOOLING_TRANSFORMER_REWRITE_RULE_H_
16 #define LLVM_CLANG_TOOLING_TRANSFORMER_REWRITE_RULE_H_
17 
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include "llvm/Support/Error.h"
27 #include <functional>
28 #include <string>
29 #include <utility>
30 
31 namespace clang {
32 namespace transformer {
34 
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.
38 //
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.
44 //
45 // * Replacement: a function that produces a replacement string for the target,
46 // based on the match result.
47 //
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.
54 //
55 // `ASTEdit` should be built using the `change` convenience functions. For
56 // example,
57 // \code
58 // change(name(fun), text("Frodo"))
59 // \endcode
60 // Or, if we use Stencil for the TextGenerator:
61 // \code
62 // using stencil::cat;
63 // change(statement(thenNode), cat("{", thenNode, "}"))
64 // change(callArgs(call), cat(x, ",", y))
65 // \endcode
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:
68 // \code
69 // change(cat("different_expr"))
70 // \endcode
71 struct ASTEdit {
75 };
76 
77 /// Format of the path in an include directive -- angle brackets or quotes.
78 enum class IncludeFormat {
79  Quoted,
80  Angled,
81 };
82 
83 /// Description of a source-code transformation.
84 //
85 // A *rewrite rule* describes a transformation of source code. A simple rule
86 // contains each of the following components:
87 //
88 // * Matcher: the pattern term, expressed as clang matchers (with Transformer
89 // extensions).
90 //
91 // * Edits: a set of Edits to the source code, described with ASTEdits.
92 //
93 // * Explanation: explanation of the rewrite. This will be displayed to the
94 // user, where possible; for example, in clang-tidy diagnostics.
95 //
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.
99 //
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.
103 //
104 // The \c Transformer class can be used to apply the rewrite rule and obtain the
105 // corresponding replacements.
106 struct RewriteRule {
107  struct Case {
108  ast_matchers::internal::DynTypedMatcher Matcher;
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;
115  };
116  // We expect RewriteRules will most commonly include only one case.
118 
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___";
122 };
123 
124 /// Convenience function for constructing a simple \c RewriteRule.
125 RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
127  TextGenerator Explanation = nullptr);
128 
129 /// Convenience overload of \c makeRule for common case of only one edit.
130 inline RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M,
131  ASTEdit Edit,
132  TextGenerator Explanation = nullptr) {
134  Edits.emplace_back(std::move(Edit));
135  return makeRule(std::move(M), std::move(Edits), std::move(Explanation));
136 }
137 
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
141 /// could write:
142 /// \code
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);
147 /// \endcode
148 void addInclude(RewriteRule &Rule, llvm::StringRef Header,
150 
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.
154 //
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), ...});`
160 //
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`).
166 //
167 // We have three cases to consider (for some equality function, `eq`):
168 // ```
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))
172 // ```
173 //
174 // `applyFirst` allows us to specify each independently:
175 // ```
176 // auto eq_fun = functionDecl(...);
177 // auto method_call = cxxMemberCallExpr(...);
178 //
179 // auto two_calls = callExpr(callee(eq_fun), hasArgument(0, method_call),
180 // hasArgument(1, method_call));
181 // auto left_call =
182 // callExpr(callee(eq_fun), callExpr(hasArgument(0, method_call)));
183 // auto right_call =
184 // callExpr(callee(eq_fun), callExpr(hasArgument(1, method_call)));
185 //
186 // RewriteRule R = applyFirst({makeRule(two_calls, two_calls_action),
187 // makeRule(left_call, left_call_action),
188 // makeRule(right_call, right_call_action)});
189 // ```
191 
192 /// Replaces a portion of the source text with \p Replacement.
194 
195 /// Replaces the entirety of a RewriteRule's match with \p Replacement. For
196 /// example, to replace a function call, one could write:
197 /// \code
198 /// makeRule(callExpr(callee(functionDecl(hasName("foo")))),
199 /// change(text("bar()")))
200 /// \endcode
201 inline ASTEdit change(TextGenerator Replacement) {
202  return change(node(RewriteRule::RootID), std::move(Replacement));
203 }
204 
205 /// Inserts \p Replacement before \p S, leaving the source selected by \S
206 /// unchanged.
208  return change(before(std::move(S)), std::move(Replacement));
209 }
210 
211 /// Inserts \p Replacement after \p S, leaving the source selected by \S
212 /// unchanged.
214  return change(after(std::move(S)), std::move(Replacement));
215 }
216 
217 /// Removes the source selected by \p S.
218 inline ASTEdit remove(RangeSelector S) {
219  return change(std::move(S),
221  -> Expected<std::string> { return ""; });
222 }
223 
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
227 /// users.
228 //
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`.
232 namespace 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);
238 
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);
246 
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.
252 
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 &
257  const RewriteRule &Rule);
258 
259 /// A source "transformation," represented by a character range in the source to
260 /// be replaced and a corresponding replacement string.
263  std::string Replacement;
264 };
265 
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
268 /// text.
269 ///
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
276 /// conflicts.
280 } // namespace detail
281 } // namespace transformer
282 
283 namespace tooling {
284 // DEPRECATED: These are temporary aliases supporting client migration to the
285 // `transformer` namespace.
286 /// Wraps a string as a TextGenerator.
288 
289 inline TextGenerator text(std::string M) {
290  return [M](const ast_matchers::MatchFinder::MatchResult &)
291  -> Expected<std::string> { return M; };
292 }
293 
296 using transformer::change;
300 using transformer::remove;
303 namespace detail {
304 using namespace transformer::detail;
305 } // namespace detail
306 } // namespace tooling
307 } // namespace clang
308 
309 #endif // LLVM_CLANG_TOOLING_TRANSFORMER_REWRITE_RULE_H_
Expected< SmallVector< Transformation, 1 > > translateEdits(const ast_matchers::MatchFinder::MatchResult &Result, llvm::ArrayRef< ASTEdit > Edits)
Attempts to translate Edits, which are in terms of AST nodes bound in the match Result, into Transformations, which are in terms of the source code text.
Definition: RewriteRule.cpp:33
void addInclude(RewriteRule &Rule, llvm::StringRef Header, IncludeFormat Format=IncludeFormat::Quoted)
For every case in Rule, adds an include directive for the given header.
ast_matchers::internal::DynTypedMatcher buildMatcher(const RewriteRule &Rule)
Builds a single matcher for the rule, covering all of the rule&#39;s cases.
Description of a source-code transformation.
Definition: RewriteRule.h:106
IncludeFormat
Format of the path in an include directive – angle brackets or quotes.
Definition: RewriteRule.h:78
RangeSelector before(RangeSelector Selector)
Selects the (empty) range [B,B) when Selector selects the range [B,E).
std::vector< std::pair< std::string, IncludeFormat > > AddedIncludes
Definition: RewriteRule.h:114
static constexpr llvm::StringLiteral RootID
Definition: RewriteRule.h:121
SmallVector< Case, 1 > Cases
Definition: RewriteRule.h:117
Represents a character-granular source range.
const RewriteRule::Case & findSelectedCase(const ast_matchers::MatchFinder::MatchResult &Result, const RewriteRule &Rule)
Returns the Case of Rule that was selected in the match result.
Contains all information for a given match.
ASTEdit remove(RangeSelector S)
Removes the source selected by S.
Definition: RewriteRule.h:218
std::vector< ast_matchers::internal::DynTypedMatcher > buildMatchers(const RewriteRule &Rule)
Builds a set of matchers that cover the rule (one for each distinct node matcher base kind: Stmt...
SmallVector< ASTEdit, 1 > Edits
Definition: RewriteRule.h:109
MatchConsumer< CharSourceRange > RangeSelector
Definition: RangeSelector.h:27
ASTEdit insertAfter(RangeSelector S, TextGenerator Replacement)
Inserts Replacement after S, leaving the source selected by unchanged.
Definition: RewriteRule.h:213
ASTEdit change(RangeSelector Target, TextGenerator Replacement)
Replaces a portion of the source text with Replacement.
Definition: RewriteRule.cpp:57
Encodes a location in the source.
ASTEdit insertBefore(RangeSelector S, TextGenerator Replacement)
Inserts Replacement before S, leaving the source selected by unchanged.
Definition: RewriteRule.h:207
std::function< Expected< T >(const ast_matchers::MatchFinder::MatchResult &)> MatchConsumer
A failable computation over nodes bound by AST matchers.
Definition: MatchConsumer.h:35
ast_matchers::internal::DynTypedMatcher Matcher
Definition: RewriteRule.h:108
RangeSelector after(RangeSelector Selector)
Selects the the point immediately following Selector.
RewriteRule applyFirst(ArrayRef< RewriteRule > Rules)
Applies the first rule whose pattern matches; other rules are ignored.
RewriteRule makeRule(ast_matchers::internal::DynTypedMatcher M, SmallVector< ASTEdit, 1 > Edits, TextGenerator Explanation=nullptr)
Convenience function for constructing a simple RewriteRule.
Dataflow Directional Tag Classes.
MatchConsumer< std::string > TextGenerator
Definition: RewriteRule.h:33
StencilPart text(llvm::StringRef Text)
A source "transformation," represented by a character range in the source to be replaced and a corres...
Definition: RewriteRule.h:261
SourceLocation getRuleMatchLoc(const ast_matchers::MatchFinder::MatchResult &Result)
Gets the beginning location of the source matched by a rewrite rule.
transformer::TextGenerator TextGenerator
Wraps a string as a TextGenerator.
Definition: RewriteRule.h:287
Defines a combinator library supporting the definition of selectors, which select source ranges based...
RangeSelector node(std::string ID)
Selects a node, including trailing semicolon (for non-expression statements).