aboutsummaryrefslogtreecommitdiffstats
path: root/src/checks/level0/qstring-ref.cpp
blob: 92d703e43d3883e1003b643b018c8b98d7ce3738 (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
/*
    SPDX-FileCopyrightText: 2015 Sergio Martins <smartins@kde.org>

    SPDX-License-Identifier: LGPL-2.0-or-later
*/

#include "qstring-ref.h"
#include "ClazyContext.h"
#include "FixItUtils.h"
#include "HierarchyUtils.h"
#include "SourceCompatibilityHelpers.h"
#include "StringUtils.h"
#include "Utils.h"
#include "clazy_stl.h"

#include <clang/AST/DeclCXX.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ExprCXX.h>
#include <clang/AST/Stmt.h>
#include <clang/Basic/Diagnostic.h>
#include <clang/Basic/IdentifierTable.h>
#include <clang/Basic/LLVM.h>
#include <clang/Basic/SourceLocation.h>
#include <clang/Lex/Lexer.h>
#include <llvm/ADT/SmallVector.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/Casting.h>

#include <array>
#include <vector>

namespace clang
{
class Decl;
class LangOptions;
} // namespace clang

using namespace clang;

StringRefCandidates::StringRefCandidates(const std::string &name, ClazyContext *context)
    : CheckBase(name, context, Option_CanIgnoreIncludes)
{
}

static bool isInterestingFirstMethod(CXXMethodDecl *method)
{
    if (!method || clazy::name(method->getParent()) != "QString") {
        return false;
    }

    static const llvm::SmallVector<StringRef, 3> list = {{"left", "mid", "right"}};
    return clazy::contains(list, clazy::name(method));
}

static bool isInterestingSecondMethod(CXXMethodDecl *method, const clang::LangOptions &lo)
{
    if (!method || clazy::name(method->getParent()) != "QString") {
        return false;
    }

    static const std::array<StringRef, 19> list = {{"compare",
                                                    "contains",
                                                    "count",
                                                    "startsWith",
                                                    "endsWith",
                                                    "indexOf",
                                                    "isEmpty",
                                                    "isNull",
                                                    "lastIndexOf",
                                                    "length",
                                                    "size",
                                                    "toDouble",
                                                    "toFloat",
                                                    "toInt",
                                                    "toUInt",
                                                    "toULong",
                                                    "toULongLong",
                                                    "toUShort",
                                                    "toUcs4"}};

    if (!clazy::contains(list, clazy::name(method))) {
        return false;
    }

    return !clazy::anyArgIsOfAnySimpleType(method, {"QRegExp", "QRegularExpression"}, lo);
}

static bool isMethodReceivingQStringRef(CXXMethodDecl *method)
{
    if (!method || clazy::name(method->getParent()) != "QString") {
        return false;
    }

    static const std::array<StringRef, 8> list = {{"append", "compare", "count", "indexOf", "endsWith", "lastIndexOf", "localAwareCompare", "startsWidth"}};

    if (clazy::contains(list, clazy::name(method))) {
        return true;
    }

    if (method->getOverloadedOperator() == OO_PlusEqual) { // operator+=
        return true;
    }

    return false;
}

void StringRefCandidates::VisitStmt(clang::Stmt *stmt)
{
    // Here we look for code like str.firstMethod().secondMethod(), where firstMethod() is for example mid() and secondMethod is for example, toInt()

    auto *call = dyn_cast<CallExpr>(stmt);
    if (!call || processCase1(dyn_cast<CXXMemberCallExpr>(call))) {
        return;
    }

    processCase2(call);
}

static bool containsChild(Stmt *s, Stmt *target)
{
    if (!s) {
        return false;
    }

    if (s == target) {
        return true;
    }

    if (auto *mte = dyn_cast<MaterializeTemporaryExpr>(s)) {
#if LLVM_VERSION_MAJOR >= 10
        return containsChild(mte->getSubExpr(), target);
#else
        return containsChild(mte->getTemporary(), target);
#endif
    } else if (auto *ice = dyn_cast<ImplicitCastExpr>(s)) {
        return containsChild(ice->getSubExpr(), target);
    } else if (auto *bte = dyn_cast<CXXBindTemporaryExpr>(s)) {
        return containsChild(bte->getSubExpr(), target);
    }

    return false;
}

bool StringRefCandidates::isConvertedToSomethingElse(clang::Stmt *s) const
{
    // While passing a QString to the QVariant ctor works fine, passing QStringRef doesn't
    // So let's not warn when QStrings are cast to something else.
    if (!s) {
        return false;
    }

    auto *constr = clazy::getFirstParentOfType<CXXConstructExpr>(m_context->parentMap, s);
    if (!constr || constr->getNumArgs() == 0) {
        return false;
    }

    if (containsChild(constr->getArg(0), s)) {
        CXXConstructorDecl *ctor = constr->getConstructor();
        CXXRecordDecl *record = ctor ? ctor->getParent() : nullptr;
        return record ? record->getQualifiedNameAsString() != "QString" : false;
    }

    return false;
}

// Catches cases like: int i = s.mid(1, 1).toInt()
bool StringRefCandidates::processCase1(CXXMemberCallExpr *memberCall)
{
    if (!memberCall) {
        return false;
    }

    // In the AST secondMethod() is parent of firstMethod() call, and will be visited first (because at runtime firstMethod() is resolved first().
    // So check for interesting second method first
    CXXMethodDecl *method = memberCall->getMethodDecl();
    if (!isInterestingSecondMethod(method, lo())) {
        return false;
    }

    std::vector<CallExpr *> callExprs = Utils::callListForChain(memberCall);
    if (callExprs.size() < 2) {
        return false;
    }

    // The list now contains {secondMethod(), firstMethod() }
    auto *firstMemberCall = dyn_cast<CXXMemberCallExpr>(callExprs.at(1));

    if (!firstMemberCall || !isInterestingFirstMethod(firstMemberCall->getMethodDecl())) {
        return false;
    }

    if (isConvertedToSomethingElse(memberCall)) {
        return false;
    }

    const std::string firstMethodName = firstMemberCall->getMethodDecl()->getNameAsString();
    const std::vector<FixItHint> fixits = fixit(firstMemberCall);

    emitWarning(firstMemberCall->getEndLoc(), "Use " + firstMethodName + "Ref() instead", fixits);
    return true;
}

// Catches cases like: s.append(s2.mid(1, 1));
bool StringRefCandidates::processCase2(CallExpr *call)
{
    auto *memberCall = dyn_cast<CXXMemberCallExpr>(call);
    auto *operatorCall = memberCall ? nullptr : dyn_cast<CXXOperatorCallExpr>(call);

    CXXMethodDecl *method = nullptr;
    if (memberCall) {
        method = memberCall->getMethodDecl();
    } else if (operatorCall && operatorCall->getCalleeDecl()) {
        Decl *decl = operatorCall->getCalleeDecl();
        method = dyn_cast<CXXMethodDecl>(decl);
    }

    if (!isMethodReceivingQStringRef(method)) {
        return false;
    }

    Expr *firstArgument = call->getNumArgs() > 0 ? call->getArg(0) : nullptr;
    MaterializeTemporaryExpr *temp = firstArgument ? dyn_cast<MaterializeTemporaryExpr>(firstArgument) : nullptr;
    if (!temp) {
        Expr *secondArgument = call->getNumArgs() > 1 ? call->getArg(1) : nullptr;
        temp = secondArgument ? dyn_cast<MaterializeTemporaryExpr>(secondArgument) : nullptr;
        if (!temp) { // For the CXXOperatorCallExpr it's in the second argument
            return false;
        }
    }

    auto *innerCall = clazy::getFirstChildOfType2<CallExpr>(temp);
    auto *innerMemberCall = innerCall ? dyn_cast<CXXMemberCallExpr>(innerCall) : nullptr;
    if (!innerMemberCall) {
        return false;
    }

    CXXMethodDecl *innerMethod = innerMemberCall->getMethodDecl();
    if (!isInterestingFirstMethod(innerMethod)) {
        return false;
    }

    const std::vector<FixItHint> fixits = fixit(innerMemberCall);

    emitWarning(call->getBeginLoc(), "Use " + innerMethod->getNameAsString() + "Ref() instead", fixits);
    return true;
}

std::vector<FixItHint> StringRefCandidates::fixit(CXXMemberCallExpr *call)
{
    auto *memberExpr = clazy::getFirstChildOfType<MemberExpr>(call);
    if (!memberExpr) {
        queueManualFixitWarning(call->getBeginLoc(), "Internal error 1");
        return {};
    }

    auto insertionLoc = Lexer::getLocForEndOfToken(memberExpr->getEndLoc(), 0, sm(), lo());
    // llvm::errs() << insertionLoc.printToString(sm()) << "\n";
    if (!insertionLoc.isValid()) {
        queueManualFixitWarning(call->getBeginLoc(), "Internal error 2");
        return {};
    }

    std::vector<FixItHint> fixits;
    fixits.push_back(clazy::createInsertion(insertionLoc, "Ref"));
    return fixits;
}