summaryrefslogtreecommitdiff
path: root/compilerplugins/clang/changerectanglegetref.cxx
blob: f687693ee8cbbfbf80963a2bf9a4e2b20c2ec7ea (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * Based on LLVM/Clang.
 *
 * This file is distributed under the University of Illinois Open Source
 * License. See LICENSE.TXT for details.
 *
 */

#include "plugin.hxx"
#include "check.hxx"
#include <regex>

/**
 * Changes calls to tools::Rectangle methods that return a ref to instead call the setter methods.
 *
 * run as:
 *   make COMPILER_PLUGIN_TOOL=changerectanglegetref UPDATE_FILES=all FORCE_COMPILE_ALL=1
 * or
 *   make <module> COMPILER_PLUGIN_TOOL=changerectanglegetref FORCE_COMPILE_ALL=1
 */

namespace
{
class ChangeRectangleGetRef : public RecursiveASTVisitor<ChangeRectangleGetRef>,
                              public loplugin::RewritePlugin
{
public:
    explicit ChangeRectangleGetRef(loplugin::InstantiationData const& data)
        : RewritePlugin(data)
    {
    }
    virtual void run() override;
    bool VisitCXXMemberCallExpr(CXXMemberCallExpr const* call);

private:
    bool ChangeAssignment(Stmt const* parent, std::string const& methodName,
                          std::string const& setPrefix);
    bool ChangeBinaryOperator(BinaryOperator const* parent, CXXMemberCallExpr const* call,
                              std::string const& methodName, std::string const& setPrefix);
    bool ChangeUnaryOperator(UnaryOperator const* parent, CXXMemberCallExpr const* call,
                             std::string const& methodName, std::string const& setPrefix);
    std::string extractCode(SourceLocation startLoc, SourceLocation endLoc);
};

void ChangeRectangleGetRef::run()
{
    TraverseDecl(compiler.getASTContext().getTranslationUnitDecl());
}

bool ChangeRectangleGetRef::VisitCXXMemberCallExpr(CXXMemberCallExpr const* call)
{
    if (ignoreLocation(call))
        return true;
    const CXXMethodDecl* func = call->getMethodDecl();
    if (!func)
        return true;
    if (func->isConst())
        return true;
    auto dc = loplugin::DeclCheck(func);
    std::string methodName;
    std::string setPrefix;
    if (dc.Function("Top").Class("Rectangle").Namespace("tools").GlobalNamespace())
    {
        methodName = "Top";
        setPrefix = "Set";
    }
    else if (dc.Function("Bottom").Class("Rectangle").Namespace("tools").GlobalNamespace())
    {
        methodName = "Bottom";
        setPrefix = "Set";
    }
    else if (dc.Function("Left").Class("Rectangle").Namespace("tools").GlobalNamespace())
    {
        methodName = "Left";
        setPrefix = "Set";
    }
    else if (dc.Function("Right").Class("Rectangle").Namespace("tools").GlobalNamespace())
    {
        methodName = "Right";
        setPrefix = "Set";
    }
    else if (dc.Function("X").Class("Point").GlobalNamespace())
    {
        methodName = "X";
        setPrefix = "set";
    }
    else if (dc.Function("Y").Class("Point").GlobalNamespace())
    {
        methodName = "Y";
        setPrefix = "set";
    }
    else if (dc.Function("Width").Class("Size").GlobalNamespace())
    {
        methodName = "Width";
        setPrefix = "set";
    }
    else if (dc.Function("Height").Class("Size").GlobalNamespace())
    {
        methodName = "Height";
        setPrefix = "set";
    }
    else
        return true;
    if (!loplugin::TypeCheck(func->getReturnType()).LvalueReference())
        return true;

    auto parent = getParentStmt(call);
    if (!parent)
        return true;
    if (auto unaryOp = dyn_cast<UnaryOperator>(parent))
    {
        if (!ChangeUnaryOperator(unaryOp, call, methodName, setPrefix))
            report(DiagnosticsEngine::Warning, "Could not fix this one1", call->getLocStart());
        return true;
    }
    auto binaryOp = dyn_cast<BinaryOperator>(parent);
    if (!binaryOp)
    {
        //        parent->dump();
        //        report(DiagnosticsEngine::Warning, "Could not fix this one3", call->getLocStart());
        return true;
    }
    auto opcode = binaryOp->getOpcode();
    if (opcode == BO_Assign)
    {
        if (!ChangeAssignment(parent, methodName, setPrefix))
            report(DiagnosticsEngine::Warning, "Could not fix this one4", call->getLocStart());
        return true;
    }
    if (opcode == BO_RemAssign || opcode == BO_AddAssign || opcode == BO_SubAssign
        || opcode == BO_MulAssign || opcode == BO_DivAssign)
    {
        if (!ChangeBinaryOperator(binaryOp, call, methodName, setPrefix))
            report(DiagnosticsEngine::Warning, "Could not fix this one5", call->getLocStart());
        return true;
    }
    return true;
}

bool ChangeRectangleGetRef::ChangeAssignment(Stmt const* parent, std::string const& methodName,
                                             std::string const& setPrefix)
{
    // Look for expressions like
    //    aRect.Left() = ...;
    // and replace with
    //    aRect.SetLeft( ... );
    SourceManager& SM = compiler.getSourceManager();
    SourceLocation startLoc = parent->getLocStart();
    SourceLocation endLoc = parent->getLocEnd();
    const char* p1 = SM.getCharacterData(startLoc);
    const char* p2 = SM.getCharacterData(endLoc);
    unsigned n = Lexer::MeasureTokenLength(endLoc, SM, compiler.getLangOpts());
    if (p2 < p1) // clang is misbehaving, appears to be macro constant related
        return false;
    std::string callText(p1, p2 - p1 + n);
    auto originalLength = callText.size();

    auto newText = std::regex_replace(callText, std::regex(methodName + "\\(\\) *="),
                                      setPrefix + methodName + "(");
    if (newText == callText)
        return false;
    newText += " )";

    return replaceText(startLoc, originalLength, newText);
}

bool ChangeRectangleGetRef::ChangeBinaryOperator(BinaryOperator const* binaryOp,
                                                 CXXMemberCallExpr const* call,
                                                 std::string const& methodName,
                                                 std::string const& setPrefix)
{
    // Look for expressions like
    //    aRect.Left() += ...;
    // and replace with
    //    aRect.SetLeft( aRect.GetLeft() + ... );
    SourceManager& SM = compiler.getSourceManager();
    SourceLocation startLoc = binaryOp->getLocStart();
    SourceLocation endLoc = binaryOp->getLocEnd();
    const char* p1 = SM.getCharacterData(startLoc);
    const char* p2 = SM.getCharacterData(endLoc);
    if (p2 < p1) // clang is misbehaving, appears to be macro constant related
        return false;
    unsigned n = Lexer::MeasureTokenLength(endLoc, SM, compiler.getLangOpts());
    std::string callText(p1, p2 - p1 + n);
    auto originalLength = callText.size();

    std::string regexOpname;
    std::string replaceOpname;
    switch (binaryOp->getOpcode())
    {
        case BO_RemAssign:
            regexOpname = "\\%=";
            replaceOpname = "%";
            break;
        case BO_AddAssign:
            regexOpname = "\\+=";
            replaceOpname = "+";
            break;
        case BO_SubAssign:
            regexOpname = "\\-=";
            replaceOpname = "-";
            break;
        case BO_MulAssign:
            regexOpname = "\\*=";
            replaceOpname = "*";
            break;
        case BO_DivAssign:
            regexOpname = "\\/=";
            replaceOpname = "/";
            break;
        default:
            assert(false);
    }

    auto implicitObjectText = extractCode(call->getImplicitObjectArgument()->getExprLoc(),
                                          call->getImplicitObjectArgument()->getExprLoc());
    auto newText = std::regex_replace(callText, std::regex(methodName + "\\(\\) *" + regexOpname),
                                      setPrefix + methodName + "( " + implicitObjectText + "."
                                          + methodName + "() " + replaceOpname + " ");
    if (newText == callText)
        return false;
    // sometimes we end up with duplicate spaces after the opname
    newText
        = std::regex_replace(newText, std::regex(methodName + "\\(\\) \\" + replaceOpname + "  "),
                             methodName + "() " + replaceOpname + " ");
    newText += " )";

    return replaceText(startLoc, originalLength, newText);
}

bool ChangeRectangleGetRef::ChangeUnaryOperator(UnaryOperator const* unaryOp,
                                                CXXMemberCallExpr const* call,
                                                std::string const& methodName,
                                                std::string const& setPrefix)
{
    // Look for expressions like
    //    aRect.Left()++;
    // and replace with
    //    aRect.SetLeft( ++aRect.GetLeft() );
    SourceManager& SM = compiler.getSourceManager();
    SourceLocation startLoc = unaryOp->getLocStart();
    SourceLocation endLoc = unaryOp->getLocEnd();
    const char* p1 = SM.getCharacterData(startLoc);
    const char* p2 = SM.getCharacterData(endLoc);
    if (p2 < p1) // clang is misbehaving, appears to be macro constant related
        return false;
    unsigned n = Lexer::MeasureTokenLength(endLoc, SM, compiler.getLangOpts());
    std::string callText(p1, p2 - p1 + n);
    auto originalLength = callText.size();

    auto implicitObjectText = extractCode(call->getImplicitObjectArgument()->getExprLoc(),
                                          call->getImplicitObjectArgument()->getExprLoc());
    auto op = unaryOp->getOpcode();
    std::string regexOpname;
    std::string replaceOpname;
    switch (op)
    {
        case UO_PostInc:
        case UO_PreInc:
            replaceOpname = "++";
            regexOpname = "\\+\\+";
            break;
        case UO_PostDec:
        case UO_PreDec:
            replaceOpname = "--";
            regexOpname = "\\-\\-";
            break;
        default:
            assert(false);
    }
    if (op == UO_PostInc || op == UO_PostDec)
    {
        auto newText
            = std::regex_replace(callText, std::regex(methodName + "\\(\\) *" + regexOpname),
                                 setPrefix + methodName + "( " + replaceOpname + implicitObjectText
                                     + "." + methodName + "()");
        return replaceText(startLoc, originalLength, newText);
    }
    else
    {
        auto newText
            = std::regex_replace(callText, std::regex(regexOpname + " *" + methodName + "\\(\\)"),
                                 setPrefix + methodName + "( " + replaceOpname + implicitObjectText
                                     + "." + methodName + "()");
        return replaceText(startLoc, originalLength, newText);
    }
}

std::string ChangeRectangleGetRef::extractCode(SourceLocation startLoc, SourceLocation endLoc)
{
    SourceManager& SM = compiler.getSourceManager();
    const char* p1 = SM.getCharacterData(startLoc);
    const char* p2 = SM.getCharacterData(endLoc);
    unsigned n = Lexer::MeasureTokenLength(endLoc, SM, compiler.getLangOpts());
    return std::string(p1, p2 - p1 + n);
}

static loplugin::Plugin::Registration<ChangeRectangleGetRef> X("changerectanglegetref", false);

} // namespace

/* vim:set shiftwidth=4 softtabstop=4 expandtab: */