RewriteRule.cpp 17 KB

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