Path: blob/main/contrib/llvm-project/clang/lib/Tooling/Transformer/RewriteRule.cpp
35269 views
//===--- Transformer.cpp - Transformer library implementation ---*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#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/StringRef.h"16#include "llvm/Support/Errc.h"17#include "llvm/Support/Error.h"18#include <map>19#include <string>20#include <utility>21#include <vector>2223using namespace clang;24using namespace transformer;2526using ast_matchers::MatchFinder;27using ast_matchers::internal::DynTypedMatcher;2829using MatchResult = MatchFinder::MatchResult;3031const char transformer::RootID[] = "___root___";3233static Expected<SmallVector<transformer::Edit, 1>>34translateEdits(const MatchResult &Result, ArrayRef<ASTEdit> ASTEdits) {35SmallVector<transformer::Edit, 1> Edits;36for (const auto &E : ASTEdits) {37Expected<CharSourceRange> Range = E.TargetRange(Result);38if (!Range)39return Range.takeError();40std::optional<CharSourceRange> EditRange =41tooling::getFileRangeForEdit(*Range, *Result.Context);42// FIXME: let user specify whether to treat this case as an error or ignore43// it as is currently done. This behavior is problematic in that it hides44// failures from bad ranges. Also, the behavior here differs from45// `flatten`. Here, we abort (without error), whereas flatten, if it hits an46// empty list, does not abort. As a result, `editList({A,B})` is not47// equivalent to `flatten(edit(A), edit(B))`. The former will abort if `A`48// produces a bad range, whereas the latter will simply ignore A.49if (!EditRange)50return SmallVector<Edit, 0>();51transformer::Edit T;52T.Kind = E.Kind;53T.Range = *EditRange;54if (E.Replacement) {55auto Replacement = E.Replacement->eval(Result);56if (!Replacement)57return Replacement.takeError();58T.Replacement = std::move(*Replacement);59}60if (E.Note) {61auto Note = E.Note->eval(Result);62if (!Note)63return Note.takeError();64T.Note = std::move(*Note);65}66if (E.Metadata) {67auto Metadata = E.Metadata(Result);68if (!Metadata)69return Metadata.takeError();70T.Metadata = std::move(*Metadata);71}72Edits.push_back(std::move(T));73}74return Edits;75}7677EditGenerator transformer::editList(SmallVector<ASTEdit, 1> Edits) {78return [Edits = std::move(Edits)](const MatchResult &Result) {79return translateEdits(Result, Edits);80};81}8283EditGenerator transformer::edit(ASTEdit Edit) {84return [Edit = std::move(Edit)](const MatchResult &Result) {85return translateEdits(Result, {Edit});86};87}8889EditGenerator transformer::noopEdit(RangeSelector Anchor) {90return [Anchor = std::move(Anchor)](const MatchResult &Result)91-> Expected<SmallVector<transformer::Edit, 1>> {92Expected<CharSourceRange> Range = Anchor(Result);93if (!Range)94return Range.takeError();95// In case the range is inside a macro expansion, map the location back to a96// "real" source location.97SourceLocation Begin =98Result.SourceManager->getSpellingLoc(Range->getBegin());99Edit E;100// Implicitly, leave `E.Replacement` as the empty string.101E.Kind = EditKind::Range;102E.Range = CharSourceRange::getCharRange(Begin, Begin);103return SmallVector<Edit, 1>{E};104};105}106107EditGenerator108transformer::flattenVector(SmallVector<EditGenerator, 2> Generators) {109if (Generators.size() == 1)110return std::move(Generators[0]);111return112[Gs = std::move(Generators)](113const MatchResult &Result) -> llvm::Expected<SmallVector<Edit, 1>> {114SmallVector<Edit, 1> AllEdits;115for (const auto &G : Gs) {116llvm::Expected<SmallVector<Edit, 1>> Edits = G(Result);117if (!Edits)118return Edits.takeError();119AllEdits.append(Edits->begin(), Edits->end());120}121return AllEdits;122};123}124125ASTEdit transformer::changeTo(RangeSelector Target, TextGenerator Replacement) {126ASTEdit E;127E.TargetRange = std::move(Target);128E.Replacement = std::move(Replacement);129return E;130}131132ASTEdit transformer::note(RangeSelector Anchor, TextGenerator Note) {133ASTEdit E;134E.TargetRange = transformer::before(Anchor);135E.Note = std::move(Note);136return E;137}138139namespace {140/// A \c TextGenerator that always returns a fixed string.141class SimpleTextGenerator : public MatchComputation<std::string> {142std::string S;143144public:145SimpleTextGenerator(std::string S) : S(std::move(S)) {}146llvm::Error eval(const ast_matchers::MatchFinder::MatchResult &,147std::string *Result) const override {148Result->append(S);149return llvm::Error::success();150}151std::string toString() const override {152return (llvm::Twine("text(\"") + S + "\")").str();153}154};155} // namespace156157static TextGenerator makeText(std::string S) {158return std::make_shared<SimpleTextGenerator>(std::move(S));159}160161ASTEdit transformer::remove(RangeSelector S) {162return change(std::move(S), makeText(""));163}164165static std::string formatHeaderPath(StringRef Header, IncludeFormat Format) {166switch (Format) {167case transformer::IncludeFormat::Quoted:168return Header.str();169case transformer::IncludeFormat::Angled:170return ("<" + Header + ">").str();171}172llvm_unreachable("Unknown transformer::IncludeFormat enum");173}174175ASTEdit transformer::addInclude(RangeSelector Target, StringRef Header,176IncludeFormat Format) {177ASTEdit E;178E.Kind = EditKind::AddInclude;179E.TargetRange = Target;180E.Replacement = makeText(formatHeaderPath(Header, Format));181return E;182}183184EditGenerator185transformer::detail::makeEditGenerator(llvm::SmallVector<ASTEdit, 1> Edits) {186return editList(std::move(Edits));187}188189EditGenerator transformer::detail::makeEditGenerator(ASTEdit Edit) {190return edit(std::move(Edit));191}192193RewriteRule transformer::detail::makeRule(DynTypedMatcher M,194EditGenerator Edits) {195RewriteRule R;196R.Cases = {{std::move(M), std::move(Edits)}};197return R;198}199200RewriteRule transformer::makeRule(ast_matchers::internal::DynTypedMatcher M,201std::initializer_list<ASTEdit> Edits) {202return detail::makeRule(std::move(M),203detail::makeEditGenerator(std::move(Edits)));204}205206namespace {207208/// Unconditionally binds the given node set before trying `InnerMatcher` and209/// keeps the bound nodes on a successful match.210template <typename T>211class BindingsMatcher : public ast_matchers::internal::MatcherInterface<T> {212ast_matchers::BoundNodes Nodes;213const ast_matchers::internal::Matcher<T> InnerMatcher;214215public:216explicit BindingsMatcher(ast_matchers::BoundNodes Nodes,217ast_matchers::internal::Matcher<T> InnerMatcher)218: Nodes(std::move(Nodes)), InnerMatcher(std::move(InnerMatcher)) {}219220bool matches(221const T &Node, ast_matchers::internal::ASTMatchFinder *Finder,222ast_matchers::internal::BoundNodesTreeBuilder *Builder) const override {223ast_matchers::internal::BoundNodesTreeBuilder Result(*Builder);224for (const auto &N : Nodes.getMap())225Result.setBinding(N.first, N.second);226if (InnerMatcher.matches(Node, Finder, &Result)) {227*Builder = std::move(Result);228return true;229}230return false;231}232};233234/// Matches nodes of type T that have at least one descendant node for which the235/// given inner matcher matches. Will match for each descendant node that236/// matches. Based on ForEachDescendantMatcher, but takes a dynamic matcher,237/// instead of a static one, because it is used by RewriteRule, which carries238/// (only top-level) dynamic matchers.239template <typename T>240class DynamicForEachDescendantMatcher241: public ast_matchers::internal::MatcherInterface<T> {242const DynTypedMatcher DescendantMatcher;243244public:245explicit DynamicForEachDescendantMatcher(DynTypedMatcher DescendantMatcher)246: DescendantMatcher(std::move(DescendantMatcher)) {}247248bool matches(249const T &Node, ast_matchers::internal::ASTMatchFinder *Finder,250ast_matchers::internal::BoundNodesTreeBuilder *Builder) const override {251return Finder->matchesDescendantOf(252Node, this->DescendantMatcher, Builder,253ast_matchers::internal::ASTMatchFinder::BK_All);254}255};256257template <typename T>258ast_matchers::internal::Matcher<T>259forEachDescendantDynamically(ast_matchers::BoundNodes Nodes,260DynTypedMatcher M) {261return ast_matchers::internal::makeMatcher(new BindingsMatcher<T>(262std::move(Nodes),263ast_matchers::internal::makeMatcher(264new DynamicForEachDescendantMatcher<T>(std::move(M)))));265}266267class ApplyRuleCallback : public MatchFinder::MatchCallback {268public:269ApplyRuleCallback(RewriteRule Rule) : Rule(std::move(Rule)) {}270271template <typename T>272void registerMatchers(const ast_matchers::BoundNodes &Nodes,273MatchFinder *MF) {274for (auto &Matcher : transformer::detail::buildMatchers(Rule))275MF->addMatcher(forEachDescendantDynamically<T>(Nodes, Matcher), this);276}277278void run(const MatchFinder::MatchResult &Result) override {279if (!Edits)280return;281size_t I = transformer::detail::findSelectedCase(Result, Rule);282auto Transformations = Rule.Cases[I].Edits(Result);283if (!Transformations) {284Edits = Transformations.takeError();285return;286}287Edits->append(Transformations->begin(), Transformations->end());288}289290RewriteRule Rule;291292// Initialize to a non-error state.293Expected<SmallVector<Edit, 1>> Edits = SmallVector<Edit, 1>();294};295} // namespace296297template <typename T>298llvm::Expected<SmallVector<clang::transformer::Edit, 1>>299rewriteDescendantsImpl(const T &Node, RewriteRule Rule,300const MatchResult &Result) {301ApplyRuleCallback Callback(std::move(Rule));302MatchFinder Finder;303Callback.registerMatchers<T>(Result.Nodes, &Finder);304Finder.match(Node, *Result.Context);305return std::move(Callback.Edits);306}307308llvm::Expected<SmallVector<clang::transformer::Edit, 1>>309transformer::detail::rewriteDescendants(const Decl &Node, RewriteRule Rule,310const MatchResult &Result) {311return rewriteDescendantsImpl(Node, std::move(Rule), Result);312}313314llvm::Expected<SmallVector<clang::transformer::Edit, 1>>315transformer::detail::rewriteDescendants(const Stmt &Node, RewriteRule Rule,316const MatchResult &Result) {317return rewriteDescendantsImpl(Node, std::move(Rule), Result);318}319320llvm::Expected<SmallVector<clang::transformer::Edit, 1>>321transformer::detail::rewriteDescendants(const TypeLoc &Node, RewriteRule Rule,322const MatchResult &Result) {323return rewriteDescendantsImpl(Node, std::move(Rule), Result);324}325326llvm::Expected<SmallVector<clang::transformer::Edit, 1>>327transformer::detail::rewriteDescendants(const DynTypedNode &DNode,328RewriteRule Rule,329const MatchResult &Result) {330if (const auto *Node = DNode.get<Decl>())331return rewriteDescendantsImpl(*Node, std::move(Rule), Result);332if (const auto *Node = DNode.get<Stmt>())333return rewriteDescendantsImpl(*Node, std::move(Rule), Result);334if (const auto *Node = DNode.get<TypeLoc>())335return rewriteDescendantsImpl(*Node, std::move(Rule), Result);336337return llvm::make_error<llvm::StringError>(338llvm::errc::invalid_argument,339"type unsupported for recursive rewriting, Kind=" +340DNode.getNodeKind().asStringRef());341}342343EditGenerator transformer::rewriteDescendants(std::string NodeId,344RewriteRule Rule) {345return [NodeId = std::move(NodeId),346Rule = std::move(Rule)](const MatchResult &Result)347-> llvm::Expected<SmallVector<clang::transformer::Edit, 1>> {348const ast_matchers::BoundNodes::IDToNodeMap &NodesMap =349Result.Nodes.getMap();350auto It = NodesMap.find(NodeId);351if (It == NodesMap.end())352return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument,353"ID not bound: " + NodeId);354return detail::rewriteDescendants(It->second, std::move(Rule), Result);355};356}357358void transformer::addInclude(RewriteRuleBase &Rule, StringRef Header,359IncludeFormat Format) {360for (auto &Case : Rule.Cases)361Case.Edits = flatten(std::move(Case.Edits), addInclude(Header, Format));362}363364#ifndef NDEBUG365// Filters for supported matcher kinds. FIXME: Explicitly list the allowed kinds366// (all node matcher types except for `QualType` and `Type`), rather than just367// banning `QualType` and `Type`.368static bool hasValidKind(const DynTypedMatcher &M) {369return !M.canConvertTo<QualType>();370}371#endif372373// Binds each rule's matcher to a unique (and deterministic) tag based on374// `TagBase` and the id paired with the case. All of the returned matchers have375// their traversal kind explicitly set, either based on a pre-set kind or to the376// provided `DefaultTraversalKind`.377static std::vector<DynTypedMatcher> taggedMatchers(378StringRef TagBase,379const SmallVectorImpl<std::pair<size_t, RewriteRule::Case>> &Cases,380TraversalKind DefaultTraversalKind) {381std::vector<DynTypedMatcher> Matchers;382Matchers.reserve(Cases.size());383for (const auto &Case : Cases) {384std::string Tag = (TagBase + Twine(Case.first)).str();385// HACK: Many matchers are not bindable, so ensure that tryBind will work.386DynTypedMatcher BoundMatcher(Case.second.Matcher);387BoundMatcher.setAllowBind(true);388auto M = *BoundMatcher.tryBind(Tag);389Matchers.push_back(!M.getTraversalKind()390? M.withTraversalKind(DefaultTraversalKind)391: std::move(M));392}393return Matchers;394}395396// Simply gathers the contents of the various rules into a single rule. The397// actual work to combine these into an ordered choice is deferred to matcher398// registration.399template <>400RewriteRuleWith<void>401transformer::applyFirst(ArrayRef<RewriteRuleWith<void>> Rules) {402RewriteRule R;403for (auto &Rule : Rules)404R.Cases.append(Rule.Cases.begin(), Rule.Cases.end());405return R;406}407408std::vector<DynTypedMatcher>409transformer::detail::buildMatchers(const RewriteRuleBase &Rule) {410// Map the cases into buckets of matchers -- one for each "root" AST kind,411// which guarantees that they can be combined in a single anyOf matcher. Each412// case is paired with an identifying number that is converted to a string id413// in `taggedMatchers`.414std::map<ASTNodeKind,415SmallVector<std::pair<size_t, RewriteRuleBase::Case>, 1>>416Buckets;417const SmallVectorImpl<RewriteRule::Case> &Cases = Rule.Cases;418for (int I = 0, N = Cases.size(); I < N; ++I) {419assert(hasValidKind(Cases[I].Matcher) &&420"Matcher must be non-(Qual)Type node matcher");421Buckets[Cases[I].Matcher.getSupportedKind()].emplace_back(I, Cases[I]);422}423424// Each anyOf explicitly controls the traversal kind. The anyOf itself is set425// to `TK_AsIs` to ensure no nodes are skipped, thereby deferring to the kind426// of the branches. Then, each branch is either left as is, if the kind is427// already set, or explicitly set to `TK_AsIs`. We choose this setting because428// it is the default interpretation of matchers.429std::vector<DynTypedMatcher> Matchers;430for (const auto &Bucket : Buckets) {431DynTypedMatcher M = DynTypedMatcher::constructVariadic(432DynTypedMatcher::VO_AnyOf, Bucket.first,433taggedMatchers("Tag", Bucket.second, TK_AsIs));434M.setAllowBind(true);435// `tryBind` is guaranteed to succeed, because `AllowBind` was set to true.436Matchers.push_back(M.tryBind(RootID)->withTraversalKind(TK_AsIs));437}438return Matchers;439}440441DynTypedMatcher transformer::detail::buildMatcher(const RewriteRuleBase &Rule) {442std::vector<DynTypedMatcher> Ms = buildMatchers(Rule);443assert(Ms.size() == 1 && "Cases must have compatible matchers.");444return Ms[0];445}446447SourceLocation transformer::detail::getRuleMatchLoc(const MatchResult &Result) {448auto &NodesMap = Result.Nodes.getMap();449auto Root = NodesMap.find(RootID);450assert(Root != NodesMap.end() && "Transformation failed: missing root node.");451std::optional<CharSourceRange> RootRange = tooling::getFileRangeForEdit(452CharSourceRange::getTokenRange(Root->second.getSourceRange()),453*Result.Context);454if (RootRange)455return RootRange->getBegin();456// The match doesn't have a coherent range, so fall back to the expansion457// location as the "beginning" of the match.458return Result.SourceManager->getExpansionLoc(459Root->second.getSourceRange().getBegin());460}461462// Finds the case that was "selected" -- that is, whose matcher triggered the463// `MatchResult`.464size_t transformer::detail::findSelectedCase(const MatchResult &Result,465const RewriteRuleBase &Rule) {466if (Rule.Cases.size() == 1)467return 0;468469auto &NodesMap = Result.Nodes.getMap();470for (size_t i = 0, N = Rule.Cases.size(); i < N; ++i) {471std::string Tag = ("Tag" + Twine(i)).str();472if (NodesMap.find(Tag) != NodesMap.end())473return i;474}475llvm_unreachable("No tag found for this rule.");476}477478479