blob: e747cd7bdc046185d03ec0c60bdd846c219eae26 [file] [log] [blame]
Daniel Jasperfe7beeb2012-07-16 09:18:17 +00001//===--- RefactoringCallbacks.cpp - Structural query framework ------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10//
11//===----------------------------------------------------------------------===//
12#include "clang/Lex/Lexer.h"
13#include "clang/ASTMatchers/RefactoringCallbacks.h"
14
15namespace clang {
16namespace ast_matchers {
17
18RefactoringCallback::RefactoringCallback() {}
19tooling::Replacements &RefactoringCallback::getReplacements() {
20 return Replace;
21}
22
23static tooling::Replacement replaceStmtWithText(SourceManager &Sources,
24 const Stmt &From,
25 StringRef Text) {
26 return tooling::Replacement(Sources, CharSourceRange::getTokenRange(
27 From.getSourceRange()), Text);
28}
29static tooling::Replacement replaceStmtWithStmt(SourceManager &Sources,
30 const Stmt &From,
31 const Stmt &To) {
32 return replaceStmtWithText(Sources, From, Lexer::getSourceText(
33 CharSourceRange::getTokenRange(To.getSourceRange()),
34 Sources, LangOptions()));
35}
36
37ReplaceStmtWithText::ReplaceStmtWithText(StringRef FromId, StringRef ToText)
38 : FromId(FromId), ToText(ToText) {}
39
40void ReplaceStmtWithText::run(const MatchFinder::MatchResult &Result) {
41 if (const Stmt *FromMatch = Result.Nodes.getStmtAs<Stmt>(FromId)) {
42 Replace.insert(tooling::Replacement(
43 *Result.SourceManager,
44 CharSourceRange::getTokenRange(FromMatch->getSourceRange()),
45 ToText));
46 }
47}
48
49ReplaceStmtWithStmt::ReplaceStmtWithStmt(StringRef FromId, StringRef ToId)
50 : FromId(FromId), ToId(ToId) {}
51
52void ReplaceStmtWithStmt::run(const MatchFinder::MatchResult &Result) {
53 const Stmt *FromMatch = Result.Nodes.getStmtAs<Stmt>(FromId);
54 const Stmt *ToMatch = Result.Nodes.getStmtAs<Stmt>(ToId);
55 if (FromMatch && ToMatch)
56 Replace.insert(replaceStmtWithStmt(
57 *Result.SourceManager, *FromMatch, *ToMatch));
58}
59
60ReplaceIfStmtWithItsBody::ReplaceIfStmtWithItsBody(StringRef Id,
61 bool PickTrueBranch)
62 : Id(Id), PickTrueBranch(PickTrueBranch) {}
63
64void ReplaceIfStmtWithItsBody::run(const MatchFinder::MatchResult &Result) {
65 if (const IfStmt *Node = Result.Nodes.getStmtAs<IfStmt>(Id)) {
66 const Stmt *Body = PickTrueBranch ? Node->getThen() : Node->getElse();
67 if (Body) {
68 Replace.insert(replaceStmtWithStmt(*Result.SourceManager, *Node, *Body));
69 } else if (!PickTrueBranch) {
70 // If we want to use the 'else'-branch, but it doesn't exist, delete
71 // the whole 'if'.
72 Replace.insert(replaceStmtWithText(*Result.SourceManager, *Node, ""));
73 }
74 }
75}
76
77} // end namespace ast_matchers
78} // end namespace clang