RewriteRule.cpp
15.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
//===--- Transformer.cpp - Transformer library implementation ---*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "clang/Tooling/Transformer/RewriteRule.h"
#include "clang/AST/ASTTypeTraits.h"
#include "clang/AST/Stmt.h"
#include "clang/ASTMatchers/ASTMatchFinder.h"
#include "clang/ASTMatchers/ASTMatchers.h"
#include "clang/Basic/SourceLocation.h"
#include "clang/Tooling/Transformer/SourceCode.h"
#include "llvm/ADT/Optional.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/Support/Errc.h"
#include "llvm/Support/Error.h"
#include <map>
#include <string>
#include <utility>
#include <vector>
using namespace clang;
using namespace transformer;
using ast_matchers::MatchFinder;
using ast_matchers::internal::DynTypedMatcher;
using MatchResult = MatchFinder::MatchResult;
const char transformer::RootID[] = "___root___";
static Expected<SmallVector<transformer::Edit, 1>>
translateEdits(const MatchResult &Result, ArrayRef<ASTEdit> ASTEdits) {
SmallVector<transformer::Edit, 1> Edits;
for (const auto &E : ASTEdits) {
Expected<CharSourceRange> Range = E.TargetRange(Result);
if (!Range)
return Range.takeError();
llvm::Optional<CharSourceRange> EditRange =
tooling::getRangeForEdit(*Range, *Result.Context);
// FIXME: let user specify whether to treat this case as an error or ignore
// it as is currently done.
if (!EditRange)
return SmallVector<Edit, 0>();
auto Replacement = E.Replacement->eval(Result);
if (!Replacement)
return Replacement.takeError();
auto Metadata = E.Metadata(Result);
if (!Metadata)
return Metadata.takeError();
transformer::Edit T;
T.Kind = E.Kind;
T.Range = *EditRange;
T.Replacement = std::move(*Replacement);
T.Metadata = std::move(*Metadata);
Edits.push_back(std::move(T));
}
return Edits;
}
EditGenerator transformer::editList(SmallVector<ASTEdit, 1> Edits) {
return [Edits = std::move(Edits)](const MatchResult &Result) {
return translateEdits(Result, Edits);
};
}
EditGenerator transformer::edit(ASTEdit Edit) {
return [Edit = std::move(Edit)](const MatchResult &Result) {
return translateEdits(Result, {Edit});
};
}
EditGenerator
transformer::flattenVector(SmallVector<EditGenerator, 2> Generators) {
if (Generators.size() == 1)
return std::move(Generators[0]);
return
[Gs = std::move(Generators)](
const MatchResult &Result) -> llvm::Expected<SmallVector<Edit, 1>> {
SmallVector<Edit, 1> AllEdits;
for (const auto &G : Gs) {
llvm::Expected<SmallVector<Edit, 1>> Edits = G(Result);
if (!Edits)
return Edits.takeError();
AllEdits.append(Edits->begin(), Edits->end());
}
return AllEdits;
};
}
ASTEdit transformer::changeTo(RangeSelector Target, TextGenerator Replacement) {
ASTEdit E;
E.TargetRange = std::move(Target);
E.Replacement = std::move(Replacement);
return E;
}
namespace {
/// A \c TextGenerator that always returns a fixed string.
class SimpleTextGenerator : public MatchComputation<std::string> {
std::string S;
public:
SimpleTextGenerator(std::string S) : S(std::move(S)) {}
llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &,
std::string *Result) const override {
Result->append(S);
return llvm::Error::success();
}
std::string toString() const override {
return (llvm::Twine("text(\"") + S + "\")").str();
}
};
} // namespace
static TextGenerator makeText(std::string S) {
return std::make_shared<SimpleTextGenerator>(std::move(S));
}
ASTEdit transformer::remove(RangeSelector S) {
return change(std::move(S), makeText(""));
}
static std::string formatHeaderPath(StringRef Header, IncludeFormat Format) {
switch (Format) {
case transformer::IncludeFormat::Quoted:
return Header.str();
case transformer::IncludeFormat::Angled:
return ("<" + Header + ">").str();
}
llvm_unreachable("Unknown transformer::IncludeFormat enum");
}
ASTEdit transformer::addInclude(RangeSelector Target, StringRef Header,
IncludeFormat Format) {
ASTEdit E;
E.Kind = EditKind::AddInclude;
E.TargetRange = Target;
E.Replacement = makeText(formatHeaderPath(Header, Format));
return E;
}
RewriteRule transformer::makeRule(DynTypedMatcher M, EditGenerator Edits,
TextGenerator Explanation) {
return RewriteRule{{RewriteRule::Case{std::move(M), std::move(Edits),
std::move(Explanation)}}};
}
namespace {
/// Unconditionally binds the given node set before trying `InnerMatcher` and
/// keeps the bound nodes on a successful match.
template <typename T>
class BindingsMatcher : public ast_matchers::internal::MatcherInterface<T> {
ast_matchers::BoundNodes Nodes;
const ast_matchers::internal::Matcher<T> InnerMatcher;
public:
explicit BindingsMatcher(ast_matchers::BoundNodes Nodes,
ast_matchers::internal::Matcher<T> InnerMatcher)
: Nodes(std::move(Nodes)), InnerMatcher(std::move(InnerMatcher)) {}
bool matches(
const T &Node, ast_matchers::internal::ASTMatchFinder *Finder,
ast_matchers::internal::BoundNodesTreeBuilder *Builder) const override {
ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
for (const auto &N : Nodes.getMap())
Result.setBinding(N.first, N.second);
if (InnerMatcher.matches(Node, Finder, &Result)) {
*Builder = std::move(Result);
return true;
}
return false;
}
};
/// Matches nodes of type T that have at least one descendant node for which the
/// given inner matcher matches. Will match for each descendant node that
/// matches. Based on ForEachDescendantMatcher, but takes a dynamic matcher,
/// instead of a static one, because it is used by RewriteRule, which carries
/// (only top-level) dynamic matchers.
template <typename T>
class DynamicForEachDescendantMatcher
: public ast_matchers::internal::MatcherInterface<T> {
const DynTypedMatcher DescendantMatcher;
public:
explicit DynamicForEachDescendantMatcher(DynTypedMatcher DescendantMatcher)
: DescendantMatcher(std::move(DescendantMatcher)) {}
bool matches(
const T &Node, ast_matchers::internal::ASTMatchFinder *Finder,
ast_matchers::internal::BoundNodesTreeBuilder *Builder) const override {
return Finder->matchesDescendantOf(
Node, this->DescendantMatcher, Builder,
ast_matchers::internal::ASTMatchFinder::BK_All);
}
};
template <typename T>
ast_matchers::internal::Matcher<T>
forEachDescendantDynamically(ast_matchers::BoundNodes Nodes,
DynTypedMatcher M) {
return ast_matchers::internal::makeMatcher(new BindingsMatcher<T>(
std::move(Nodes),
ast_matchers::internal::makeMatcher(
new DynamicForEachDescendantMatcher<T>(std::move(M)))));
}
class ApplyRuleCallback : public MatchFinder::MatchCallback {
public:
ApplyRuleCallback(RewriteRule Rule) : Rule(std::move(Rule)) {}
template <typename T>
void registerMatchers(const ast_matchers::BoundNodes &Nodes,
MatchFinder *MF) {
for (auto &Matcher : transformer::detail::buildMatchers(Rule))
MF->addMatcher(forEachDescendantDynamically<T>(Nodes, Matcher), this);
}
void run(const MatchFinder::MatchResult &Result) override {
if (!Edits)
return;
transformer::RewriteRule::Case Case =
transformer::detail::findSelectedCase(Result, Rule);
auto Transformations = Case.Edits(Result);
if (!Transformations) {
Edits = Transformations.takeError();
return;
}
Edits->append(Transformations->begin(), Transformations->end());
}
RewriteRule Rule;
// Initialize to a non-error state.
Expected<SmallVector<Edit, 1>> Edits = SmallVector<Edit, 1>();
};
} // namespace
template <typename T>
llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
rewriteDescendantsImpl(const T &Node, RewriteRule Rule,
const MatchResult &Result) {
ApplyRuleCallback Callback(std::move(Rule));
MatchFinder Finder;
Callback.registerMatchers<T>(Result.Nodes, &Finder);
Finder.match(Node, *Result.Context);
return std::move(Callback.Edits);
}
llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
transformer::detail::rewriteDescendants(const Decl &Node, RewriteRule Rule,
const MatchResult &Result) {
return rewriteDescendantsImpl(Node, std::move(Rule), Result);
}
llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
transformer::detail::rewriteDescendants(const Stmt &Node, RewriteRule Rule,
const MatchResult &Result) {
return rewriteDescendantsImpl(Node, std::move(Rule), Result);
}
llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
transformer::detail::rewriteDescendants(const TypeLoc &Node, RewriteRule Rule,
const MatchResult &Result) {
return rewriteDescendantsImpl(Node, std::move(Rule), Result);
}
llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
transformer::detail::rewriteDescendants(const DynTypedNode &DNode,
RewriteRule Rule,
const MatchResult &Result) {
if (const auto *Node = DNode.get<Decl>())
return rewriteDescendantsImpl(*Node, std::move(Rule), Result);
if (const auto *Node = DNode.get<Stmt>())
return rewriteDescendantsImpl(*Node, std::move(Rule), Result);
if (const auto *Node = DNode.get<TypeLoc>())
return rewriteDescendantsImpl(*Node, std::move(Rule), Result);
return llvm::make_error<llvm::StringError>(
llvm::errc::invalid_argument,
"type unsupported for recursive rewriting, Kind=" +
DNode.getNodeKind().asStringRef());
}
EditGenerator transformer::rewriteDescendants(std::string NodeId,
RewriteRule Rule) {
return [NodeId = std::move(NodeId),
Rule = std::move(Rule)](const MatchResult &Result)
-> llvm::Expected<SmallVector<clang::transformer::Edit, 1>> {
const ast_matchers::BoundNodes::IDToNodeMap &NodesMap =
Result.Nodes.getMap();
auto It = NodesMap.find(NodeId);
if (It == NodesMap.end())
return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument,
"ID not bound: " + NodeId);
return detail::rewriteDescendants(It->second, std::move(Rule), Result);
};
}
void transformer::addInclude(RewriteRule &Rule, StringRef Header,
IncludeFormat Format) {
for (auto &Case : Rule.Cases)
Case.Edits = flatten(std::move(Case.Edits), addInclude(Header, Format));
}
#ifndef NDEBUG
// Filters for supported matcher kinds. FIXME: Explicitly list the allowed kinds
// (all node matcher types except for `QualType` and `Type`), rather than just
// banning `QualType` and `Type`.
static bool hasValidKind(const DynTypedMatcher &M) {
return !M.canConvertTo<QualType>();
}
#endif
// Binds each rule's matcher to a unique (and deterministic) tag based on
// `TagBase` and the id paired with the case. All of the returned matchers have
// their traversal kind explicitly set, either based on a pre-set kind or to the
// provided `DefaultTraversalKind`.
static std::vector<DynTypedMatcher> taggedMatchers(
StringRef TagBase,
const SmallVectorImpl<std::pair<size_t, RewriteRule::Case>> &Cases,
ast_type_traits::TraversalKind DefaultTraversalKind) {
std::vector<DynTypedMatcher> Matchers;
Matchers.reserve(Cases.size());
for (const auto &Case : Cases) {
std::string Tag = (TagBase + Twine(Case.first)).str();
// HACK: Many matchers are not bindable, so ensure that tryBind will work.
DynTypedMatcher BoundMatcher(Case.second.Matcher);
BoundMatcher.setAllowBind(true);
auto M = *BoundMatcher.tryBind(Tag);
Matchers.push_back(!M.getTraversalKind()
? M.withTraversalKind(DefaultTraversalKind)
: std::move(M));
}
return Matchers;
}
// Simply gathers the contents of the various rules into a single rule. The
// actual work to combine these into an ordered choice is deferred to matcher
// registration.
RewriteRule transformer::applyFirst(ArrayRef<RewriteRule> Rules) {
RewriteRule R;
for (auto &Rule : Rules)
R.Cases.append(Rule.Cases.begin(), Rule.Cases.end());
return R;
}
std::vector<DynTypedMatcher>
transformer::detail::buildMatchers(const RewriteRule &Rule) {
// Map the cases into buckets of matchers -- one for each "root" AST kind,
// which guarantees that they can be combined in a single anyOf matcher. Each
// case is paired with an identifying number that is converted to a string id
// in `taggedMatchers`.
std::map<ASTNodeKind, SmallVector<std::pair<size_t, RewriteRule::Case>, 1>>
Buckets;
const SmallVectorImpl<RewriteRule::Case> &Cases = Rule.Cases;
for (int I = 0, N = Cases.size(); I < N; ++I) {
assert(hasValidKind(Cases[I].Matcher) &&
"Matcher must be non-(Qual)Type node matcher");
Buckets[Cases[I].Matcher.getSupportedKind()].emplace_back(I, Cases[I]);
}
// Each anyOf explicitly controls the traversal kind. The anyOf itself is set
// to `TK_AsIs` to ensure no nodes are skipped, thereby deferring to the kind
// of the branches. Then, each branch is either left as is, if the kind is
// already set, or explicitly set to `TK_AsIs`. We choose this setting because
// it is the default interpretation of matchers.
std::vector<DynTypedMatcher> Matchers;
for (const auto &Bucket : Buckets) {
DynTypedMatcher M = DynTypedMatcher::constructVariadic(
DynTypedMatcher::VO_AnyOf, Bucket.first,
taggedMatchers("Tag", Bucket.second, TK_AsIs));
M.setAllowBind(true);
// `tryBind` is guaranteed to succeed, because `AllowBind` was set to true.
Matchers.push_back(M.tryBind(RootID)->withTraversalKind(TK_AsIs));
}
return Matchers;
}
DynTypedMatcher transformer::detail::buildMatcher(const RewriteRule &Rule) {
std::vector<DynTypedMatcher> Ms = buildMatchers(Rule);
assert(Ms.size() == 1 && "Cases must have compatible matchers.");
return Ms[0];
}
SourceLocation transformer::detail::getRuleMatchLoc(const MatchResult &Result) {
auto &NodesMap = Result.Nodes.getMap();
auto Root = NodesMap.find(RootID);
assert(Root != NodesMap.end() && "Transformation failed: missing root node.");
llvm::Optional<CharSourceRange> RootRange = tooling::getRangeForEdit(
CharSourceRange::getTokenRange(Root->second.getSourceRange()),
*Result.Context);
if (RootRange)
return RootRange->getBegin();
// The match doesn't have a coherent range, so fall back to the expansion
// location as the "beginning" of the match.
return Result.SourceManager->getExpansionLoc(
Root->second.getSourceRange().getBegin());
}
// Finds the case that was "selected" -- that is, whose matcher triggered the
// `MatchResult`.
const RewriteRule::Case &
transformer::detail::findSelectedCase(const MatchResult &Result,
const RewriteRule &Rule) {
if (Rule.Cases.size() == 1)
return Rule.Cases[0];
auto &NodesMap = Result.Nodes.getMap();
for (size_t i = 0, N = Rule.Cases.size(); i < N; ++i) {
std::string Tag = ("Tag" + Twine(i)).str();
if (NodesMap.find(Tag) != NodesMap.end())
return Rule.Cases[i];
}
llvm_unreachable("No tag found for this rule.");
}
const llvm::StringRef RewriteRule::RootID = ::clang::transformer::RootID;
TextGenerator tooling::text(std::string M) {
return std::make_shared<SimpleTextGenerator>(std::move(M));
}