xref: /freebsd-src/contrib/llvm-project/clang/lib/Tooling/Transformer/RewriteRule.cpp (revision bdd1243df58e60e85101c09001d9812a789b6bc4)
1a7dea167SDimitry Andric //===--- Transformer.cpp - Transformer library implementation ---*- C++ -*-===//
2a7dea167SDimitry Andric //
3a7dea167SDimitry Andric // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4a7dea167SDimitry Andric // See https://llvm.org/LICENSE.txt for license information.
5a7dea167SDimitry Andric // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6a7dea167SDimitry Andric //
7a7dea167SDimitry Andric //===----------------------------------------------------------------------===//
8a7dea167SDimitry Andric 
9a7dea167SDimitry Andric #include "clang/Tooling/Transformer/RewriteRule.h"
10e8d8bef9SDimitry Andric #include "clang/AST/ASTTypeTraits.h"
11e8d8bef9SDimitry Andric #include "clang/AST/Stmt.h"
12a7dea167SDimitry Andric #include "clang/ASTMatchers/ASTMatchFinder.h"
13a7dea167SDimitry Andric #include "clang/ASTMatchers/ASTMatchers.h"
14a7dea167SDimitry Andric #include "clang/Basic/SourceLocation.h"
15a7dea167SDimitry Andric #include "clang/Tooling/Transformer/SourceCode.h"
16a7dea167SDimitry Andric #include "llvm/ADT/StringRef.h"
17a7dea167SDimitry Andric #include "llvm/Support/Errc.h"
18a7dea167SDimitry Andric #include "llvm/Support/Error.h"
19a7dea167SDimitry Andric #include <map>
20a7dea167SDimitry Andric #include <string>
21a7dea167SDimitry Andric #include <utility>
22a7dea167SDimitry Andric #include <vector>
23a7dea167SDimitry Andric 
24a7dea167SDimitry Andric using namespace clang;
25a7dea167SDimitry Andric using namespace transformer;
26a7dea167SDimitry Andric 
27a7dea167SDimitry Andric using ast_matchers::MatchFinder;
28a7dea167SDimitry Andric using ast_matchers::internal::DynTypedMatcher;
29a7dea167SDimitry Andric 
30a7dea167SDimitry Andric using MatchResult = MatchFinder::MatchResult;
31a7dea167SDimitry Andric 
32e8d8bef9SDimitry Andric const char transformer::RootID[] = "___root___";
33e8d8bef9SDimitry Andric 
345ffd83dbSDimitry Andric static Expected<SmallVector<transformer::Edit, 1>>
translateEdits(const MatchResult & Result,ArrayRef<ASTEdit> ASTEdits)355ffd83dbSDimitry Andric translateEdits(const MatchResult &Result, ArrayRef<ASTEdit> ASTEdits) {
365ffd83dbSDimitry Andric   SmallVector<transformer::Edit, 1> Edits;
375ffd83dbSDimitry Andric   for (const auto &E : ASTEdits) {
385ffd83dbSDimitry Andric     Expected<CharSourceRange> Range = E.TargetRange(Result);
39a7dea167SDimitry Andric     if (!Range)
40a7dea167SDimitry Andric       return Range.takeError();
41*bdd1243dSDimitry Andric     std::optional<CharSourceRange> EditRange =
42*bdd1243dSDimitry Andric         tooling::getFileRangeForEdit(*Range, *Result.Context);
43a7dea167SDimitry Andric     // FIXME: let user specify whether to treat this case as an error or ignore
44e8d8bef9SDimitry Andric     // it as is currently done. This behavior is problematic in that it hides
45e8d8bef9SDimitry Andric     // failures from bad ranges. Also, the behavior here differs from
46e8d8bef9SDimitry Andric     // `flatten`. Here, we abort (without error), whereas flatten, if it hits an
47e8d8bef9SDimitry Andric     // empty list, does not abort. As a result, `editList({A,B})` is not
48e8d8bef9SDimitry Andric     // equivalent to `flatten(edit(A), edit(B))`. The former will abort if `A`
49e8d8bef9SDimitry Andric     // produces a bad range, whereas the latter will simply ignore A.
50a7dea167SDimitry Andric     if (!EditRange)
515ffd83dbSDimitry Andric       return SmallVector<Edit, 0>();
525ffd83dbSDimitry Andric     transformer::Edit T;
53e8d8bef9SDimitry Andric     T.Kind = E.Kind;
54a7dea167SDimitry Andric     T.Range = *EditRange;
55*bdd1243dSDimitry Andric     if (E.Replacement) {
56*bdd1243dSDimitry Andric       auto Replacement = E.Replacement->eval(Result);
57*bdd1243dSDimitry Andric       if (!Replacement)
58*bdd1243dSDimitry Andric         return Replacement.takeError();
59a7dea167SDimitry Andric       T.Replacement = std::move(*Replacement);
60*bdd1243dSDimitry Andric     }
61*bdd1243dSDimitry Andric     if (E.Note) {
62*bdd1243dSDimitry Andric       auto Note = E.Note->eval(Result);
63*bdd1243dSDimitry Andric       if (!Note)
64*bdd1243dSDimitry Andric         return Note.takeError();
65*bdd1243dSDimitry Andric       T.Note = std::move(*Note);
66*bdd1243dSDimitry Andric     }
67*bdd1243dSDimitry Andric     if (E.Metadata) {
68*bdd1243dSDimitry Andric       auto Metadata = E.Metadata(Result);
69*bdd1243dSDimitry Andric       if (!Metadata)
70*bdd1243dSDimitry Andric         return Metadata.takeError();
71e8d8bef9SDimitry Andric       T.Metadata = std::move(*Metadata);
72*bdd1243dSDimitry Andric     }
735ffd83dbSDimitry Andric     Edits.push_back(std::move(T));
74a7dea167SDimitry Andric   }
755ffd83dbSDimitry Andric   return Edits;
76a7dea167SDimitry Andric }
77a7dea167SDimitry Andric 
editList(SmallVector<ASTEdit,1> Edits)785ffd83dbSDimitry Andric EditGenerator transformer::editList(SmallVector<ASTEdit, 1> Edits) {
795ffd83dbSDimitry Andric   return [Edits = std::move(Edits)](const MatchResult &Result) {
805ffd83dbSDimitry Andric     return translateEdits(Result, Edits);
815ffd83dbSDimitry Andric   };
825ffd83dbSDimitry Andric }
835ffd83dbSDimitry Andric 
edit(ASTEdit Edit)845ffd83dbSDimitry Andric EditGenerator transformer::edit(ASTEdit Edit) {
855ffd83dbSDimitry Andric   return [Edit = std::move(Edit)](const MatchResult &Result) {
865ffd83dbSDimitry Andric     return translateEdits(Result, {Edit});
875ffd83dbSDimitry Andric   };
885ffd83dbSDimitry Andric }
895ffd83dbSDimitry Andric 
noopEdit(RangeSelector Anchor)90e8d8bef9SDimitry Andric EditGenerator transformer::noopEdit(RangeSelector Anchor) {
91e8d8bef9SDimitry Andric   return [Anchor = std::move(Anchor)](const MatchResult &Result)
92e8d8bef9SDimitry Andric              -> Expected<SmallVector<transformer::Edit, 1>> {
93e8d8bef9SDimitry Andric     Expected<CharSourceRange> Range = Anchor(Result);
94e8d8bef9SDimitry Andric     if (!Range)
95e8d8bef9SDimitry Andric       return Range.takeError();
96e8d8bef9SDimitry Andric     // In case the range is inside a macro expansion, map the location back to a
97e8d8bef9SDimitry Andric     // "real" source location.
98e8d8bef9SDimitry Andric     SourceLocation Begin =
99e8d8bef9SDimitry Andric         Result.SourceManager->getSpellingLoc(Range->getBegin());
100e8d8bef9SDimitry Andric     Edit E;
101e8d8bef9SDimitry Andric     // Implicitly, leave `E.Replacement` as the empty string.
102e8d8bef9SDimitry Andric     E.Kind = EditKind::Range;
103e8d8bef9SDimitry Andric     E.Range = CharSourceRange::getCharRange(Begin, Begin);
104e8d8bef9SDimitry Andric     return SmallVector<Edit, 1>{E};
105e8d8bef9SDimitry Andric   };
106e8d8bef9SDimitry Andric }
107e8d8bef9SDimitry Andric 
108e8d8bef9SDimitry Andric EditGenerator
flattenVector(SmallVector<EditGenerator,2> Generators)109e8d8bef9SDimitry Andric transformer::flattenVector(SmallVector<EditGenerator, 2> Generators) {
110e8d8bef9SDimitry Andric   if (Generators.size() == 1)
111e8d8bef9SDimitry Andric     return std::move(Generators[0]);
112e8d8bef9SDimitry Andric   return
113e8d8bef9SDimitry Andric       [Gs = std::move(Generators)](
114e8d8bef9SDimitry Andric           const MatchResult &Result) -> llvm::Expected<SmallVector<Edit, 1>> {
115e8d8bef9SDimitry Andric         SmallVector<Edit, 1> AllEdits;
116e8d8bef9SDimitry Andric         for (const auto &G : Gs) {
117e8d8bef9SDimitry Andric           llvm::Expected<SmallVector<Edit, 1>> Edits = G(Result);
118e8d8bef9SDimitry Andric           if (!Edits)
119e8d8bef9SDimitry Andric             return Edits.takeError();
120e8d8bef9SDimitry Andric           AllEdits.append(Edits->begin(), Edits->end());
121e8d8bef9SDimitry Andric         }
122e8d8bef9SDimitry Andric         return AllEdits;
123e8d8bef9SDimitry Andric       };
124e8d8bef9SDimitry Andric }
125e8d8bef9SDimitry Andric 
changeTo(RangeSelector Target,TextGenerator Replacement)1265ffd83dbSDimitry Andric ASTEdit transformer::changeTo(RangeSelector Target, TextGenerator Replacement) {
127a7dea167SDimitry Andric   ASTEdit E;
1285ffd83dbSDimitry Andric   E.TargetRange = std::move(Target);
129a7dea167SDimitry Andric   E.Replacement = std::move(Replacement);
130a7dea167SDimitry Andric   return E;
131a7dea167SDimitry Andric }
132a7dea167SDimitry Andric 
note(RangeSelector Anchor,TextGenerator Note)133*bdd1243dSDimitry Andric ASTEdit transformer::note(RangeSelector Anchor, TextGenerator Note) {
134*bdd1243dSDimitry Andric   ASTEdit E;
135*bdd1243dSDimitry Andric   E.TargetRange = transformer::before(Anchor);
136*bdd1243dSDimitry Andric   E.Note = std::move(Note);
137*bdd1243dSDimitry Andric   return E;
138*bdd1243dSDimitry Andric }
139*bdd1243dSDimitry Andric 
140480093f4SDimitry Andric namespace {
141480093f4SDimitry Andric /// A \c TextGenerator that always returns a fixed string.
142480093f4SDimitry Andric class SimpleTextGenerator : public MatchComputation<std::string> {
143480093f4SDimitry Andric   std::string S;
144480093f4SDimitry Andric 
145480093f4SDimitry Andric public:
SimpleTextGenerator(std::string S)146480093f4SDimitry Andric   SimpleTextGenerator(std::string S) : S(std::move(S)) {}
eval(const ast_matchers::MatchFinder::MatchResult &,std::string * Result) const147480093f4SDimitry Andric   llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &,
148480093f4SDimitry Andric                    std::string *Result) const override {
149480093f4SDimitry Andric     Result->append(S);
150480093f4SDimitry Andric     return llvm::Error::success();
151480093f4SDimitry Andric   }
toString() const152480093f4SDimitry Andric   std::string toString() const override {
153480093f4SDimitry Andric     return (llvm::Twine("text(\"") + S + "\")").str();
154480093f4SDimitry Andric   }
155480093f4SDimitry Andric };
156480093f4SDimitry Andric } // namespace
157480093f4SDimitry Andric 
makeText(std::string S)158e8d8bef9SDimitry Andric static TextGenerator makeText(std::string S) {
159e8d8bef9SDimitry Andric   return std::make_shared<SimpleTextGenerator>(std::move(S));
160480093f4SDimitry Andric }
161480093f4SDimitry Andric 
remove(RangeSelector S)162e8d8bef9SDimitry Andric ASTEdit transformer::remove(RangeSelector S) {
163e8d8bef9SDimitry Andric   return change(std::move(S), makeText(""));
164e8d8bef9SDimitry Andric }
165e8d8bef9SDimitry Andric 
formatHeaderPath(StringRef Header,IncludeFormat Format)166e8d8bef9SDimitry Andric static std::string formatHeaderPath(StringRef Header, IncludeFormat Format) {
167e8d8bef9SDimitry Andric   switch (Format) {
168e8d8bef9SDimitry Andric   case transformer::IncludeFormat::Quoted:
169e8d8bef9SDimitry Andric     return Header.str();
170e8d8bef9SDimitry Andric   case transformer::IncludeFormat::Angled:
171e8d8bef9SDimitry Andric     return ("<" + Header + ">").str();
172e8d8bef9SDimitry Andric   }
173e8d8bef9SDimitry Andric   llvm_unreachable("Unknown transformer::IncludeFormat enum");
174e8d8bef9SDimitry Andric }
175e8d8bef9SDimitry Andric 
addInclude(RangeSelector Target,StringRef Header,IncludeFormat Format)176e8d8bef9SDimitry Andric ASTEdit transformer::addInclude(RangeSelector Target, StringRef Header,
177e8d8bef9SDimitry Andric                                 IncludeFormat Format) {
178e8d8bef9SDimitry Andric   ASTEdit E;
179e8d8bef9SDimitry Andric   E.Kind = EditKind::AddInclude;
180e8d8bef9SDimitry Andric   E.TargetRange = Target;
181e8d8bef9SDimitry Andric   E.Replacement = makeText(formatHeaderPath(Header, Format));
182e8d8bef9SDimitry Andric   return E;
183e8d8bef9SDimitry Andric }
184e8d8bef9SDimitry Andric 
18581ad6265SDimitry Andric EditGenerator
makeEditGenerator(llvm::SmallVector<ASTEdit,1> Edits)18681ad6265SDimitry Andric transformer::detail::makeEditGenerator(llvm::SmallVector<ASTEdit, 1> Edits) {
18781ad6265SDimitry Andric   return editList(std::move(Edits));
18881ad6265SDimitry Andric }
18981ad6265SDimitry Andric 
makeEditGenerator(ASTEdit Edit)19081ad6265SDimitry Andric EditGenerator transformer::detail::makeEditGenerator(ASTEdit Edit) {
19181ad6265SDimitry Andric   return edit(std::move(Edit));
19281ad6265SDimitry Andric }
19381ad6265SDimitry Andric 
makeRule(DynTypedMatcher M,EditGenerator Edits)19481ad6265SDimitry Andric RewriteRule transformer::detail::makeRule(DynTypedMatcher M,
19581ad6265SDimitry Andric                                           EditGenerator Edits) {
19681ad6265SDimitry Andric   RewriteRule R;
19781ad6265SDimitry Andric   R.Cases = {{std::move(M), std::move(Edits)}};
19881ad6265SDimitry Andric   return R;
19981ad6265SDimitry Andric }
20081ad6265SDimitry Andric 
makeRule(ast_matchers::internal::DynTypedMatcher M,std::initializer_list<ASTEdit> Edits)20181ad6265SDimitry Andric RewriteRule transformer::makeRule(ast_matchers::internal::DynTypedMatcher M,
20281ad6265SDimitry Andric                                   std::initializer_list<ASTEdit> Edits) {
20381ad6265SDimitry Andric   return detail::makeRule(std::move(M),
20481ad6265SDimitry Andric                           detail::makeEditGenerator(std::move(Edits)));
205e8d8bef9SDimitry Andric }
206e8d8bef9SDimitry Andric 
207e8d8bef9SDimitry Andric namespace {
208e8d8bef9SDimitry Andric 
209e8d8bef9SDimitry Andric /// Unconditionally binds the given node set before trying `InnerMatcher` and
210e8d8bef9SDimitry Andric /// keeps the bound nodes on a successful match.
211e8d8bef9SDimitry Andric template <typename T>
212e8d8bef9SDimitry Andric class BindingsMatcher : public ast_matchers::internal::MatcherInterface<T> {
213e8d8bef9SDimitry Andric   ast_matchers::BoundNodes Nodes;
214e8d8bef9SDimitry Andric   const ast_matchers::internal::Matcher<T> InnerMatcher;
215e8d8bef9SDimitry Andric 
216e8d8bef9SDimitry Andric public:
BindingsMatcher(ast_matchers::BoundNodes Nodes,ast_matchers::internal::Matcher<T> InnerMatcher)217e8d8bef9SDimitry Andric   explicit BindingsMatcher(ast_matchers::BoundNodes Nodes,
218e8d8bef9SDimitry Andric                            ast_matchers::internal::Matcher<T> InnerMatcher)
219e8d8bef9SDimitry Andric       : Nodes(std::move(Nodes)), InnerMatcher(std::move(InnerMatcher)) {}
220e8d8bef9SDimitry Andric 
matches(const T & Node,ast_matchers::internal::ASTMatchFinder * Finder,ast_matchers::internal::BoundNodesTreeBuilder * Builder) const221e8d8bef9SDimitry Andric   bool matches(
222e8d8bef9SDimitry Andric       const T &Node, ast_matchers::internal::ASTMatchFinder *Finder,
223e8d8bef9SDimitry Andric       ast_matchers::internal::BoundNodesTreeBuilder *Builder) const override {
224e8d8bef9SDimitry Andric     ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);
225e8d8bef9SDimitry Andric     for (const auto &N : Nodes.getMap())
226e8d8bef9SDimitry Andric       Result.setBinding(N.first, N.second);
227e8d8bef9SDimitry Andric     if (InnerMatcher.matches(Node, Finder, &Result)) {
228e8d8bef9SDimitry Andric       *Builder = std::move(Result);
229e8d8bef9SDimitry Andric       return true;
230e8d8bef9SDimitry Andric     }
231e8d8bef9SDimitry Andric     return false;
232e8d8bef9SDimitry Andric   }
233e8d8bef9SDimitry Andric };
234e8d8bef9SDimitry Andric 
235e8d8bef9SDimitry Andric /// Matches nodes of type T that have at least one descendant node for which the
236e8d8bef9SDimitry Andric /// given inner matcher matches.  Will match for each descendant node that
237e8d8bef9SDimitry Andric /// matches.  Based on ForEachDescendantMatcher, but takes a dynamic matcher,
238e8d8bef9SDimitry Andric /// instead of a static one, because it is used by RewriteRule, which carries
239e8d8bef9SDimitry Andric /// (only top-level) dynamic matchers.
240e8d8bef9SDimitry Andric template <typename T>
241e8d8bef9SDimitry Andric class DynamicForEachDescendantMatcher
242e8d8bef9SDimitry Andric     : public ast_matchers::internal::MatcherInterface<T> {
243e8d8bef9SDimitry Andric   const DynTypedMatcher DescendantMatcher;
244e8d8bef9SDimitry Andric 
245e8d8bef9SDimitry Andric public:
DynamicForEachDescendantMatcher(DynTypedMatcher DescendantMatcher)246e8d8bef9SDimitry Andric   explicit DynamicForEachDescendantMatcher(DynTypedMatcher DescendantMatcher)
247e8d8bef9SDimitry Andric       : DescendantMatcher(std::move(DescendantMatcher)) {}
248e8d8bef9SDimitry Andric 
matches(const T & Node,ast_matchers::internal::ASTMatchFinder * Finder,ast_matchers::internal::BoundNodesTreeBuilder * Builder) const249e8d8bef9SDimitry Andric   bool matches(
250e8d8bef9SDimitry Andric       const T &Node, ast_matchers::internal::ASTMatchFinder *Finder,
251e8d8bef9SDimitry Andric       ast_matchers::internal::BoundNodesTreeBuilder *Builder) const override {
252e8d8bef9SDimitry Andric     return Finder->matchesDescendantOf(
253e8d8bef9SDimitry Andric         Node, this->DescendantMatcher, Builder,
254e8d8bef9SDimitry Andric         ast_matchers::internal::ASTMatchFinder::BK_All);
255e8d8bef9SDimitry Andric   }
256e8d8bef9SDimitry Andric };
257e8d8bef9SDimitry Andric 
258e8d8bef9SDimitry Andric template <typename T>
259e8d8bef9SDimitry Andric ast_matchers::internal::Matcher<T>
forEachDescendantDynamically(ast_matchers::BoundNodes Nodes,DynTypedMatcher M)260e8d8bef9SDimitry Andric forEachDescendantDynamically(ast_matchers::BoundNodes Nodes,
261e8d8bef9SDimitry Andric                              DynTypedMatcher M) {
262e8d8bef9SDimitry Andric   return ast_matchers::internal::makeMatcher(new BindingsMatcher<T>(
263e8d8bef9SDimitry Andric       std::move(Nodes),
264e8d8bef9SDimitry Andric       ast_matchers::internal::makeMatcher(
265e8d8bef9SDimitry Andric           new DynamicForEachDescendantMatcher<T>(std::move(M)))));
266e8d8bef9SDimitry Andric }
267e8d8bef9SDimitry Andric 
268e8d8bef9SDimitry Andric class ApplyRuleCallback : public MatchFinder::MatchCallback {
269e8d8bef9SDimitry Andric public:
ApplyRuleCallback(RewriteRule Rule)270e8d8bef9SDimitry Andric   ApplyRuleCallback(RewriteRule Rule) : Rule(std::move(Rule)) {}
271e8d8bef9SDimitry Andric 
272e8d8bef9SDimitry Andric   template <typename T>
registerMatchers(const ast_matchers::BoundNodes & Nodes,MatchFinder * MF)273e8d8bef9SDimitry Andric   void registerMatchers(const ast_matchers::BoundNodes &Nodes,
274e8d8bef9SDimitry Andric                         MatchFinder *MF) {
275e8d8bef9SDimitry Andric     for (auto &Matcher : transformer::detail::buildMatchers(Rule))
276e8d8bef9SDimitry Andric       MF->addMatcher(forEachDescendantDynamically<T>(Nodes, Matcher), this);
277e8d8bef9SDimitry Andric   }
278e8d8bef9SDimitry Andric 
run(const MatchFinder::MatchResult & Result)279e8d8bef9SDimitry Andric   void run(const MatchFinder::MatchResult &Result) override {
280e8d8bef9SDimitry Andric     if (!Edits)
281e8d8bef9SDimitry Andric       return;
28281ad6265SDimitry Andric     size_t I = transformer::detail::findSelectedCase(Result, Rule);
28381ad6265SDimitry Andric     auto Transformations = Rule.Cases[I].Edits(Result);
284e8d8bef9SDimitry Andric     if (!Transformations) {
285e8d8bef9SDimitry Andric       Edits = Transformations.takeError();
286e8d8bef9SDimitry Andric       return;
287e8d8bef9SDimitry Andric     }
288e8d8bef9SDimitry Andric     Edits->append(Transformations->begin(), Transformations->end());
289e8d8bef9SDimitry Andric   }
290e8d8bef9SDimitry Andric 
291e8d8bef9SDimitry Andric   RewriteRule Rule;
292e8d8bef9SDimitry Andric 
293e8d8bef9SDimitry Andric   // Initialize to a non-error state.
294e8d8bef9SDimitry Andric   Expected<SmallVector<Edit, 1>> Edits = SmallVector<Edit, 1>();
295e8d8bef9SDimitry Andric };
296e8d8bef9SDimitry Andric } // namespace
297e8d8bef9SDimitry Andric 
298e8d8bef9SDimitry Andric template <typename T>
299e8d8bef9SDimitry Andric llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
rewriteDescendantsImpl(const T & Node,RewriteRule Rule,const MatchResult & Result)300e8d8bef9SDimitry Andric rewriteDescendantsImpl(const T &Node, RewriteRule Rule,
301e8d8bef9SDimitry Andric                        const MatchResult &Result) {
302e8d8bef9SDimitry Andric   ApplyRuleCallback Callback(std::move(Rule));
303e8d8bef9SDimitry Andric   MatchFinder Finder;
304e8d8bef9SDimitry Andric   Callback.registerMatchers<T>(Result.Nodes, &Finder);
305e8d8bef9SDimitry Andric   Finder.match(Node, *Result.Context);
306e8d8bef9SDimitry Andric   return std::move(Callback.Edits);
307e8d8bef9SDimitry Andric }
308e8d8bef9SDimitry Andric 
309e8d8bef9SDimitry Andric llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
rewriteDescendants(const Decl & Node,RewriteRule Rule,const MatchResult & Result)310e8d8bef9SDimitry Andric transformer::detail::rewriteDescendants(const Decl &Node, RewriteRule Rule,
311e8d8bef9SDimitry Andric                                         const MatchResult &Result) {
312e8d8bef9SDimitry Andric   return rewriteDescendantsImpl(Node, std::move(Rule), Result);
313e8d8bef9SDimitry Andric }
314e8d8bef9SDimitry Andric 
315e8d8bef9SDimitry Andric llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
rewriteDescendants(const Stmt & Node,RewriteRule Rule,const MatchResult & Result)316e8d8bef9SDimitry Andric transformer::detail::rewriteDescendants(const Stmt &Node, RewriteRule Rule,
317e8d8bef9SDimitry Andric                                         const MatchResult &Result) {
318e8d8bef9SDimitry Andric   return rewriteDescendantsImpl(Node, std::move(Rule), Result);
319e8d8bef9SDimitry Andric }
320e8d8bef9SDimitry Andric 
321e8d8bef9SDimitry Andric llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
rewriteDescendants(const TypeLoc & Node,RewriteRule Rule,const MatchResult & Result)322e8d8bef9SDimitry Andric transformer::detail::rewriteDescendants(const TypeLoc &Node, RewriteRule Rule,
323e8d8bef9SDimitry Andric                                         const MatchResult &Result) {
324e8d8bef9SDimitry Andric   return rewriteDescendantsImpl(Node, std::move(Rule), Result);
325e8d8bef9SDimitry Andric }
326e8d8bef9SDimitry Andric 
327e8d8bef9SDimitry Andric llvm::Expected<SmallVector<clang::transformer::Edit, 1>>
rewriteDescendants(const DynTypedNode & DNode,RewriteRule Rule,const MatchResult & Result)328e8d8bef9SDimitry Andric transformer::detail::rewriteDescendants(const DynTypedNode &DNode,
329e8d8bef9SDimitry Andric                                         RewriteRule Rule,
330e8d8bef9SDimitry Andric                                         const MatchResult &Result) {
331e8d8bef9SDimitry Andric   if (const auto *Node = DNode.get<Decl>())
332e8d8bef9SDimitry Andric     return rewriteDescendantsImpl(*Node, std::move(Rule), Result);
333e8d8bef9SDimitry Andric   if (const auto *Node = DNode.get<Stmt>())
334e8d8bef9SDimitry Andric     return rewriteDescendantsImpl(*Node, std::move(Rule), Result);
335e8d8bef9SDimitry Andric   if (const auto *Node = DNode.get<TypeLoc>())
336e8d8bef9SDimitry Andric     return rewriteDescendantsImpl(*Node, std::move(Rule), Result);
337e8d8bef9SDimitry Andric 
338e8d8bef9SDimitry Andric   return llvm::make_error<llvm::StringError>(
339e8d8bef9SDimitry Andric       llvm::errc::invalid_argument,
340e8d8bef9SDimitry Andric       "type unsupported for recursive rewriting, Kind=" +
341e8d8bef9SDimitry Andric           DNode.getNodeKind().asStringRef());
342e8d8bef9SDimitry Andric }
343e8d8bef9SDimitry Andric 
rewriteDescendants(std::string NodeId,RewriteRule Rule)344e8d8bef9SDimitry Andric EditGenerator transformer::rewriteDescendants(std::string NodeId,
345e8d8bef9SDimitry Andric                                               RewriteRule Rule) {
346e8d8bef9SDimitry Andric   return [NodeId = std::move(NodeId),
347e8d8bef9SDimitry Andric           Rule = std::move(Rule)](const MatchResult &Result)
348e8d8bef9SDimitry Andric              -> llvm::Expected<SmallVector<clang::transformer::Edit, 1>> {
349e8d8bef9SDimitry Andric     const ast_matchers::BoundNodes::IDToNodeMap &NodesMap =
350e8d8bef9SDimitry Andric         Result.Nodes.getMap();
351e8d8bef9SDimitry Andric     auto It = NodesMap.find(NodeId);
352e8d8bef9SDimitry Andric     if (It == NodesMap.end())
353e8d8bef9SDimitry Andric       return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument,
354e8d8bef9SDimitry Andric                                                  "ID not bound: " + NodeId);
355e8d8bef9SDimitry Andric     return detail::rewriteDescendants(It->second, std::move(Rule), Result);
356e8d8bef9SDimitry Andric   };
357a7dea167SDimitry Andric }
358a7dea167SDimitry Andric 
addInclude(RewriteRuleBase & Rule,StringRef Header,IncludeFormat Format)35981ad6265SDimitry Andric void transformer::addInclude(RewriteRuleBase &Rule, StringRef Header,
360a7dea167SDimitry Andric                              IncludeFormat Format) {
361a7dea167SDimitry Andric   for (auto &Case : Rule.Cases)
362e8d8bef9SDimitry Andric     Case.Edits = flatten(std::move(Case.Edits), addInclude(Header, Format));
363a7dea167SDimitry Andric }
364a7dea167SDimitry Andric 
365a7dea167SDimitry Andric #ifndef NDEBUG
366a7dea167SDimitry Andric // Filters for supported matcher kinds. FIXME: Explicitly list the allowed kinds
367a7dea167SDimitry Andric // (all node matcher types except for `QualType` and `Type`), rather than just
368a7dea167SDimitry Andric // banning `QualType` and `Type`.
hasValidKind(const DynTypedMatcher & M)369a7dea167SDimitry Andric static bool hasValidKind(const DynTypedMatcher &M) {
370a7dea167SDimitry Andric   return !M.canConvertTo<QualType>();
371a7dea167SDimitry Andric }
372a7dea167SDimitry Andric #endif
373a7dea167SDimitry Andric 
374a7dea167SDimitry Andric // Binds each rule's matcher to a unique (and deterministic) tag based on
3755ffd83dbSDimitry Andric // `TagBase` and the id paired with the case. All of the returned matchers have
3765ffd83dbSDimitry Andric // their traversal kind explicitly set, either based on a pre-set kind or to the
3775ffd83dbSDimitry Andric // provided `DefaultTraversalKind`.
taggedMatchers(StringRef TagBase,const SmallVectorImpl<std::pair<size_t,RewriteRule::Case>> & Cases,TraversalKind DefaultTraversalKind)378a7dea167SDimitry Andric static std::vector<DynTypedMatcher> taggedMatchers(
379a7dea167SDimitry Andric     StringRef TagBase,
3805ffd83dbSDimitry Andric     const SmallVectorImpl<std::pair<size_t, RewriteRule::Case>> &Cases,
381e8d8bef9SDimitry Andric     TraversalKind DefaultTraversalKind) {
382a7dea167SDimitry Andric   std::vector<DynTypedMatcher> Matchers;
383a7dea167SDimitry Andric   Matchers.reserve(Cases.size());
384a7dea167SDimitry Andric   for (const auto &Case : Cases) {
385a7dea167SDimitry Andric     std::string Tag = (TagBase + Twine(Case.first)).str();
386a7dea167SDimitry Andric     // HACK: Many matchers are not bindable, so ensure that tryBind will work.
387a7dea167SDimitry Andric     DynTypedMatcher BoundMatcher(Case.second.Matcher);
388a7dea167SDimitry Andric     BoundMatcher.setAllowBind(true);
3895ffd83dbSDimitry Andric     auto M = *BoundMatcher.tryBind(Tag);
3905ffd83dbSDimitry Andric     Matchers.push_back(!M.getTraversalKind()
3915ffd83dbSDimitry Andric                            ? M.withTraversalKind(DefaultTraversalKind)
3925ffd83dbSDimitry Andric                            : std::move(M));
393a7dea167SDimitry Andric   }
394a7dea167SDimitry Andric   return Matchers;
395a7dea167SDimitry Andric }
396a7dea167SDimitry Andric 
397a7dea167SDimitry Andric // Simply gathers the contents of the various rules into a single rule. The
398a7dea167SDimitry Andric // actual work to combine these into an ordered choice is deferred to matcher
399a7dea167SDimitry Andric // registration.
40081ad6265SDimitry Andric template <>
40181ad6265SDimitry Andric RewriteRuleWith<void>
applyFirst(ArrayRef<RewriteRuleWith<void>> Rules)40281ad6265SDimitry Andric transformer::applyFirst(ArrayRef<RewriteRuleWith<void>> Rules) {
403a7dea167SDimitry Andric   RewriteRule R;
404a7dea167SDimitry Andric   for (auto &Rule : Rules)
405a7dea167SDimitry Andric     R.Cases.append(Rule.Cases.begin(), Rule.Cases.end());
406a7dea167SDimitry Andric   return R;
407a7dea167SDimitry Andric }
408a7dea167SDimitry Andric 
409a7dea167SDimitry Andric std::vector<DynTypedMatcher>
buildMatchers(const RewriteRuleBase & Rule)41081ad6265SDimitry Andric transformer::detail::buildMatchers(const RewriteRuleBase &Rule) {
411a7dea167SDimitry Andric   // Map the cases into buckets of matchers -- one for each "root" AST kind,
412a7dea167SDimitry Andric   // which guarantees that they can be combined in a single anyOf matcher. Each
413a7dea167SDimitry Andric   // case is paired with an identifying number that is converted to a string id
414a7dea167SDimitry Andric   // in `taggedMatchers`.
41581ad6265SDimitry Andric   std::map<ASTNodeKind,
41681ad6265SDimitry Andric            SmallVector<std::pair<size_t, RewriteRuleBase::Case>, 1>>
417a7dea167SDimitry Andric       Buckets;
418a7dea167SDimitry Andric   const SmallVectorImpl<RewriteRule::Case> &Cases = Rule.Cases;
419a7dea167SDimitry Andric   for (int I = 0, N = Cases.size(); I < N; ++I) {
420a7dea167SDimitry Andric     assert(hasValidKind(Cases[I].Matcher) &&
421a7dea167SDimitry Andric            "Matcher must be non-(Qual)Type node matcher");
422a7dea167SDimitry Andric     Buckets[Cases[I].Matcher.getSupportedKind()].emplace_back(I, Cases[I]);
423a7dea167SDimitry Andric   }
424a7dea167SDimitry Andric 
4255ffd83dbSDimitry Andric   // Each anyOf explicitly controls the traversal kind. The anyOf itself is set
4265ffd83dbSDimitry Andric   // to `TK_AsIs` to ensure no nodes are skipped, thereby deferring to the kind
4275ffd83dbSDimitry Andric   // of the branches. Then, each branch is either left as is, if the kind is
428e8d8bef9SDimitry Andric   // already set, or explicitly set to `TK_AsIs`. We choose this setting because
429e8d8bef9SDimitry Andric   // it is the default interpretation of matchers.
430a7dea167SDimitry Andric   std::vector<DynTypedMatcher> Matchers;
431a7dea167SDimitry Andric   for (const auto &Bucket : Buckets) {
432a7dea167SDimitry Andric     DynTypedMatcher M = DynTypedMatcher::constructVariadic(
433a7dea167SDimitry Andric         DynTypedMatcher::VO_AnyOf, Bucket.first,
434e8d8bef9SDimitry Andric         taggedMatchers("Tag", Bucket.second, TK_AsIs));
435a7dea167SDimitry Andric     M.setAllowBind(true);
436a7dea167SDimitry Andric     // `tryBind` is guaranteed to succeed, because `AllowBind` was set to true.
437e8d8bef9SDimitry Andric     Matchers.push_back(M.tryBind(RootID)->withTraversalKind(TK_AsIs));
438a7dea167SDimitry Andric   }
439a7dea167SDimitry Andric   return Matchers;
440a7dea167SDimitry Andric }
441a7dea167SDimitry Andric 
buildMatcher(const RewriteRuleBase & Rule)44281ad6265SDimitry Andric DynTypedMatcher transformer::detail::buildMatcher(const RewriteRuleBase &Rule) {
443a7dea167SDimitry Andric   std::vector<DynTypedMatcher> Ms = buildMatchers(Rule);
444a7dea167SDimitry Andric   assert(Ms.size() == 1 && "Cases must have compatible matchers.");
445a7dea167SDimitry Andric   return Ms[0];
446a7dea167SDimitry Andric }
447a7dea167SDimitry Andric 
getRuleMatchLoc(const MatchResult & Result)448a7dea167SDimitry Andric SourceLocation transformer::detail::getRuleMatchLoc(const MatchResult &Result) {
449a7dea167SDimitry Andric   auto &NodesMap = Result.Nodes.getMap();
450e8d8bef9SDimitry Andric   auto Root = NodesMap.find(RootID);
451a7dea167SDimitry Andric   assert(Root != NodesMap.end() && "Transformation failed: missing root node.");
452*bdd1243dSDimitry Andric   std::optional<CharSourceRange> RootRange = tooling::getFileRangeForEdit(
453a7dea167SDimitry Andric       CharSourceRange::getTokenRange(Root->second.getSourceRange()),
454a7dea167SDimitry Andric       *Result.Context);
455a7dea167SDimitry Andric   if (RootRange)
456a7dea167SDimitry Andric     return RootRange->getBegin();
457a7dea167SDimitry Andric   // The match doesn't have a coherent range, so fall back to the expansion
458a7dea167SDimitry Andric   // location as the "beginning" of the match.
459a7dea167SDimitry Andric   return Result.SourceManager->getExpansionLoc(
460a7dea167SDimitry Andric       Root->second.getSourceRange().getBegin());
461a7dea167SDimitry Andric }
462a7dea167SDimitry Andric 
463a7dea167SDimitry Andric // Finds the case that was "selected" -- that is, whose matcher triggered the
464a7dea167SDimitry Andric // `MatchResult`.
findSelectedCase(const MatchResult & Result,const RewriteRuleBase & Rule)46581ad6265SDimitry Andric size_t transformer::detail::findSelectedCase(const MatchResult &Result,
46681ad6265SDimitry Andric                                              const RewriteRuleBase &Rule) {
467a7dea167SDimitry Andric   if (Rule.Cases.size() == 1)
46881ad6265SDimitry Andric     return 0;
469a7dea167SDimitry Andric 
470a7dea167SDimitry Andric   auto &NodesMap = Result.Nodes.getMap();
471a7dea167SDimitry Andric   for (size_t i = 0, N = Rule.Cases.size(); i < N; ++i) {
472a7dea167SDimitry Andric     std::string Tag = ("Tag" + Twine(i)).str();
473a7dea167SDimitry Andric     if (NodesMap.find(Tag) != NodesMap.end())
47481ad6265SDimitry Andric       return i;
475a7dea167SDimitry Andric   }
476a7dea167SDimitry Andric   llvm_unreachable("No tag found for this rule.");
477a7dea167SDimitry Andric }
478