1 //===--- RefactoringCallbacks.cpp - Structural query framework ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
11 //===----------------------------------------------------------------------===//
12 #include "clang/Tooling/RefactoringCallbacks.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Basic/SourceLocation.h"
15 #include "clang/Lex/Lexer.h"
17 using llvm::StringError;
18 using llvm::make_error;
23 RefactoringCallback::RefactoringCallback() {}
24 tooling::Replacements &RefactoringCallback::getReplacements() {
28 ASTMatchRefactorer::ASTMatchRefactorer(
29 std::map<std::string, Replacements> &FileToReplaces)
30 : FileToReplaces(FileToReplaces) {}
32 void ASTMatchRefactorer::addDynamicMatcher(
33 const ast_matchers::internal::DynTypedMatcher &Matcher,
34 RefactoringCallback *Callback) {
35 MatchFinder.addDynamicMatcher(Matcher, Callback);
36 Callbacks.push_back(Callback);
39 class RefactoringASTConsumer : public ASTConsumer {
41 explicit RefactoringASTConsumer(ASTMatchRefactorer &Refactoring)
42 : Refactoring(Refactoring) {}
44 void HandleTranslationUnit(ASTContext &Context) override {
45 // The ASTMatchRefactorer is re-used between translation units.
46 // Clear the matchers so that each Replacement is only emitted once.
47 for (const auto &Callback : Refactoring.Callbacks) {
48 Callback->getReplacements().clear();
50 Refactoring.MatchFinder.matchAST(Context);
51 for (const auto &Callback : Refactoring.Callbacks) {
52 for (const auto &Replacement : Callback->getReplacements()) {
54 Refactoring.FileToReplaces[Replacement.getFilePath()].add(
57 llvm::errs() << "Skipping replacement " << Replacement.toString()
58 << " due to this error:\n"
59 << toString(std::move(Err)) << "\n";
66 ASTMatchRefactorer &Refactoring;
69 std::unique_ptr<ASTConsumer> ASTMatchRefactorer::newASTConsumer() {
70 return llvm::make_unique<RefactoringASTConsumer>(*this);
73 static Replacement replaceStmtWithText(SourceManager &Sources, const Stmt &From,
75 return tooling::Replacement(
76 Sources, CharSourceRange::getTokenRange(From.getSourceRange()), Text);
78 static Replacement replaceStmtWithStmt(SourceManager &Sources, const Stmt &From,
80 return replaceStmtWithText(
82 Lexer::getSourceText(CharSourceRange::getTokenRange(To.getSourceRange()),
83 Sources, LangOptions()));
86 ReplaceStmtWithText::ReplaceStmtWithText(StringRef FromId, StringRef ToText)
87 : FromId(FromId), ToText(ToText) {}
89 void ReplaceStmtWithText::run(
90 const ast_matchers::MatchFinder::MatchResult &Result) {
91 if (const Stmt *FromMatch = Result.Nodes.getNodeAs<Stmt>(FromId)) {
92 auto Err = Replace.add(tooling::Replacement(
93 *Result.SourceManager,
94 CharSourceRange::getTokenRange(FromMatch->getSourceRange()), ToText));
95 // FIXME: better error handling. For now, just print error message in the
98 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
104 ReplaceStmtWithStmt::ReplaceStmtWithStmt(StringRef FromId, StringRef ToId)
105 : FromId(FromId), ToId(ToId) {}
107 void ReplaceStmtWithStmt::run(
108 const ast_matchers::MatchFinder::MatchResult &Result) {
109 const Stmt *FromMatch = Result.Nodes.getNodeAs<Stmt>(FromId);
110 const Stmt *ToMatch = Result.Nodes.getNodeAs<Stmt>(ToId);
111 if (FromMatch && ToMatch) {
112 auto Err = Replace.add(
113 replaceStmtWithStmt(*Result.SourceManager, *FromMatch, *ToMatch));
114 // FIXME: better error handling. For now, just print error message in the
117 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
123 ReplaceIfStmtWithItsBody::ReplaceIfStmtWithItsBody(StringRef Id,
125 : Id(Id), PickTrueBranch(PickTrueBranch) {}
127 void ReplaceIfStmtWithItsBody::run(
128 const ast_matchers::MatchFinder::MatchResult &Result) {
129 if (const IfStmt *Node = Result.Nodes.getNodeAs<IfStmt>(Id)) {
130 const Stmt *Body = PickTrueBranch ? Node->getThen() : Node->getElse();
133 Replace.add(replaceStmtWithStmt(*Result.SourceManager, *Node, *Body));
134 // FIXME: better error handling. For now, just print error message in the
137 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
140 } else if (!PickTrueBranch) {
141 // If we want to use the 'else'-branch, but it doesn't exist, delete
144 Replace.add(replaceStmtWithText(*Result.SourceManager, *Node, ""));
145 // FIXME: better error handling. For now, just print error message in the
148 llvm::errs() << llvm::toString(std::move(Err)) << "\n";
155 ReplaceNodeWithTemplate::ReplaceNodeWithTemplate(
156 llvm::StringRef FromId, std::vector<TemplateElement> Template)
157 : FromId(FromId), Template(std::move(Template)) {}
159 llvm::Expected<std::unique_ptr<ReplaceNodeWithTemplate>>
160 ReplaceNodeWithTemplate::create(StringRef FromId, StringRef ToTemplate) {
161 std::vector<TemplateElement> ParsedTemplate;
162 for (size_t Index = 0; Index < ToTemplate.size();) {
163 if (ToTemplate[Index] == '$') {
164 if (ToTemplate.substr(Index, 2) == "$$") {
166 ParsedTemplate.push_back(
167 TemplateElement{TemplateElement::Literal, "$"});
168 } else if (ToTemplate.substr(Index, 2) == "${") {
169 size_t EndOfIdentifier = ToTemplate.find("}", Index);
170 if (EndOfIdentifier == std::string::npos) {
171 return make_error<StringError>(
172 "Unterminated ${...} in replacement template near " +
173 ToTemplate.substr(Index),
174 llvm::inconvertibleErrorCode());
176 std::string SourceNodeName =
177 ToTemplate.substr(Index + 2, EndOfIdentifier - Index - 2);
178 ParsedTemplate.push_back(
179 TemplateElement{TemplateElement::Identifier, SourceNodeName});
180 Index = EndOfIdentifier + 1;
182 return make_error<StringError>(
183 "Invalid $ in replacement template near " +
184 ToTemplate.substr(Index),
185 llvm::inconvertibleErrorCode());
188 size_t NextIndex = ToTemplate.find('$', Index + 1);
189 ParsedTemplate.push_back(
190 TemplateElement{TemplateElement::Literal,
191 ToTemplate.substr(Index, NextIndex - Index)});
195 return std::unique_ptr<ReplaceNodeWithTemplate>(
196 new ReplaceNodeWithTemplate(FromId, std::move(ParsedTemplate)));
199 void ReplaceNodeWithTemplate::run(
200 const ast_matchers::MatchFinder::MatchResult &Result) {
201 const auto &NodeMap = Result.Nodes.getMap();
204 for (const auto &Element : Template) {
205 switch (Element.Type) {
206 case TemplateElement::Literal:
207 ToText += Element.Value;
209 case TemplateElement::Identifier: {
210 auto NodeIter = NodeMap.find(Element.Value);
211 if (NodeIter == NodeMap.end()) {
212 llvm::errs() << "Node " << Element.Value
213 << " used in replacement template not bound in Matcher \n";
214 llvm::report_fatal_error("Unbound node in replacement template.");
216 CharSourceRange Source =
217 CharSourceRange::getTokenRange(NodeIter->second.getSourceRange());
218 ToText += Lexer::getSourceText(Source, *Result.SourceManager,
219 Result.Context->getLangOpts());
224 if (NodeMap.count(FromId) == 0) {
225 llvm::errs() << "Node to be replaced " << FromId
226 << " not bound in query.\n";
227 llvm::report_fatal_error("FromId node not bound in MatchResult");
230 tooling::Replacement(*Result.SourceManager, &NodeMap.at(FromId), ToText,
231 Result.Context->getLangOpts());
232 llvm::Error Err = Replace.add(Replacement);
234 llvm::errs() << "Query and replace failed in " << Replacement.getFilePath()
235 << "! " << llvm::toString(std::move(Err)) << "\n";
236 llvm::report_fatal_error("Replacement failed");
240 } // end namespace tooling
241 } // end namespace clang