1 //===--- Stencil.cpp - Stencil implementation -------------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
9 #include "clang/Tooling/Refactoring/Stencil.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/AST/ASTTypeTraits.h"
12 #include "clang/AST/Expr.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/ASTMatchers/ASTMatchers.h"
15 #include "clang/Lex/Lexer.h"
16 #include "clang/Tooling/Refactoring/SourceCode.h"
17 #include "llvm/Support/Errc.h"
22 using namespace clang;
23 using namespace tooling;
25 using ast_matchers::MatchFinder;
28 // A down_cast function to safely down cast a StencilPartInterface to a subclass
29 // D. Returns nullptr if P is not an instance of D.
30 template <typename D> const D *down_cast(const StencilPartInterface *P) {
31 if (P == nullptr || D::typeId() != P->typeId())
33 return static_cast<const D *>(P);
36 static llvm::Expected<ast_type_traits::DynTypedNode>
37 getNode(const ast_matchers::BoundNodes &Nodes, StringRef Id) {
38 auto &NodesMap = Nodes.getMap();
39 auto It = NodesMap.find(Id);
40 if (It == NodesMap.end())
41 return llvm::make_error<llvm::StringError>(llvm::errc::invalid_argument,
42 "Id not bound: " + Id);
47 // An arbitrary fragment of code within a stencil.
49 explicit RawTextData(std::string T) : Text(std::move(T)) {}
53 // A debugging operation to dump the AST for a particular (bound) AST node.
54 struct DebugPrintNodeOpData {
55 explicit DebugPrintNodeOpData(std::string S) : Id(std::move(S)) {}
59 // The fragment of code corresponding to the selected range.
60 struct SelectorOpData {
61 explicit SelectorOpData(RangeSelector S) : Selector(std::move(S)) {}
62 RangeSelector Selector;
66 bool isEqualData(const RawTextData &A, const RawTextData &B) {
67 return A.Text == B.Text;
70 bool isEqualData(const DebugPrintNodeOpData &A, const DebugPrintNodeOpData &B) {
74 // Equality is not (yet) defined for \c RangeSelector.
75 bool isEqualData(const SelectorOpData &, const SelectorOpData &) { return false; }
77 // The `evalData()` overloads evaluate the given stencil data to a string, given
78 // the match result, and append it to `Result`. We define an overload for each
79 // type of stencil data.
81 Error evalData(const RawTextData &Data, const MatchFinder::MatchResult &,
82 std::string *Result) {
83 Result->append(Data.Text);
84 return Error::success();
87 Error evalData(const DebugPrintNodeOpData &Data,
88 const MatchFinder::MatchResult &Match, std::string *Result) {
90 llvm::raw_string_ostream Os(Output);
91 auto NodeOrErr = getNode(Match.Nodes, Data.Id);
92 if (auto Err = NodeOrErr.takeError())
94 NodeOrErr->print(Os, PrintingPolicy(Match.Context->getLangOpts()));
96 return Error::success();
99 Error evalData(const SelectorOpData &Data, const MatchFinder::MatchResult &Match,
100 std::string *Result) {
101 auto Range = Data.Selector(Match);
103 return Range.takeError();
104 *Result += getText(*Range, *Match.Context);
105 return Error::success();
108 template <typename T>
109 class StencilPartImpl : public StencilPartInterface {
113 template <typename... Ps>
114 explicit StencilPartImpl(Ps &&... Args)
115 : StencilPartInterface(StencilPartImpl::typeId()),
116 Data(std::forward<Ps>(Args)...) {}
118 // Generates a unique identifier for this class (specifically, one per
119 // instantiation of the template).
120 static const void* typeId() {
125 Error eval(const MatchFinder::MatchResult &Match,
126 std::string *Result) const override {
127 return evalData(Data, Match, Result);
130 bool isEqual(const StencilPartInterface &Other) const override {
131 if (const auto *OtherPtr = down_cast<StencilPartImpl>(&Other))
132 return isEqualData(Data, OtherPtr->Data);
138 using RawText = StencilPartImpl<RawTextData>;
139 using DebugPrintNodeOp = StencilPartImpl<DebugPrintNodeOpData>;
140 using SelectorOp = StencilPartImpl<SelectorOpData>;
143 StencilPart Stencil::wrap(StringRef Text) {
144 return stencil::text(Text);
147 StencilPart Stencil::wrap(RangeSelector Selector) {
148 return stencil::selection(std::move(Selector));
151 void Stencil::append(Stencil OtherStencil) {
152 for (auto &Part : OtherStencil.Parts)
153 Parts.push_back(std::move(Part));
156 llvm::Expected<std::string>
157 Stencil::eval(const MatchFinder::MatchResult &Match) const {
159 for (const auto &Part : Parts)
160 if (auto Err = Part.eval(Match, &Result))
161 return std::move(Err);
165 StencilPart stencil::text(StringRef Text) {
166 return StencilPart(std::make_shared<RawText>(Text));
169 StencilPart stencil::selection(RangeSelector Selector) {
170 return StencilPart(std::make_shared<SelectorOp>(std::move(Selector)));
173 StencilPart stencil::dPrint(StringRef Id) {
174 return StencilPart(std::make_shared<DebugPrintNodeOp>(Id));