aboutsummaryrefslogtreecommitdiffstats
path: root/src/QtUtils.cpp
blob: bba757d1543a694afeff62e85bf013df7b4707e0 (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
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
/*
   This file is part of the clazy static checker.

  Copyright (C) 2015-2016 Sergio Martins <smartins@kde.org>

  This library is free software; you can redistribute it and/or
  modify it under the terms of the GNU Library General Public
  License as published by the Free Software Foundation; either
  version 2 of the License, or (at your option) any later version.

  This library is distributed in the hope that it will be useful,
  but WITHOUT ANY WARRANTY; without even the implied warranty of
  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  Library General Public License for more details.

  You should have received a copy of the GNU Library General Public License
  along with this library; see the file COPYING.LIB.  If not, write to
  the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
  Boston, MA 02110-1301, USA.
*/

#include "clazy_stl.h"
#include "QtUtils.h"
#include "Utils.h"
#include "TypeUtils.h"
#include "StmtBodyRange.h"
#include "MacroUtils.h"
#include "HierarchyUtils.h"
#include "StringUtils.h"
#include "ContextUtils.h"

#include <clang/AST/AST.h>

using namespace std;
using namespace clang;

bool clazy::isQtIterableClass(clang::CXXRecordDecl *record)
{
    if (!record)
        return false;

    return isQtIterableClass(record->getQualifiedNameAsString());
}

const vector<StringRef> & clazy::qtContainers()
{
    static const vector<StringRef> classes = { "QListSpecialMethods", "QList", "QVector", "QVarLengthArray", "QMap",
                                               "QHash", "QMultiMap", "QMultiHash", "QSet", "QStack", "QQueue", "QString", "QStringRef",
                                               "QByteArray", "QSequentialIterable", "QAssociativeIterable", "QJsonArray", "QLinkedList" };
    return classes;
}

const vector<StringRef> & clazy::qtCOWContainers()
{
    static const vector<StringRef> classes = { "QListSpecialMethods", "QList", "QVector", "QMap", "QHash",
                                               "QMultiMap", "QMultiHash", "QSet", "QStack", "QQueue", "QString", "QStringRef",
                                               "QByteArray", "QJsonArray", "QLinkedList" };
    return classes;
}


std::unordered_map<string, std::vector<StringRef> > clazy::detachingMethods()
{
    static std::unordered_map<string, std::vector<StringRef> > map;
    if (map.empty()) {
        map = detachingMethodsWithConstCounterParts();
        map["QVector"].push_back("fill");
    }

    return map;
}

std::unordered_map<string, std::vector<StringRef> > clazy::detachingMethodsWithConstCounterParts()
{
    static std::unordered_map<string, std::vector<StringRef> > map;
    if (map.empty()) {
        map["QList"] = {"first", "last", "begin", "end", "front", "back", "operator[]"};
        map["QVector"] = {"first", "last", "begin", "end", "front", "back", "data", "operator[]" };
        map["QMap"] = {"begin", "end", "first", "find", "last", "operator[]", "lowerBound", "upperBound" };
        map["QHash"] = {"begin", "end", "find", "operator[]" };
        map["QLinkedList"] = {"first", "last", "begin", "end", "front", "back", "operator[]" };
        map["QSet"] = {"begin", "end", "find", "operator[]" };
        map["QStack"] = map["QVector"];
        map["QStack"].push_back({"top"});
        map["QQueue"] = map["QVector"];
        map["QQueue"].push_back({"head"});
        map["QMultiMap"] = map["QMap"];
        map["QMultiHash"] = map["QHash"];
        map["QString"] = {"begin", "end", "data", "operator[]"};
        map["QByteArray"] = {"data", "operator[]"};
        map["QImage"] = {"bits", "scanLine"};
    }

    return map;
}

bool clazy::isQtCOWIterableClass(clang::CXXRecordDecl *record)
{
    if (!record)
        return false;

    return isQtCOWIterableClass(record->getQualifiedNameAsString());
}

bool clazy::isQtCOWIterableClass(const string &className)
{
    const auto &classes = qtCOWContainers();
    return clazy::contains(classes, className);
}

bool clazy::isQtIterableClass(StringRef className)
{
    const auto &classes = qtContainers();
    return clazy::contains(classes, className);
}

bool clazy::isQtAssociativeContainer(clang::CXXRecordDecl *record)
{
    if (!record)
        return false;

    return isQtAssociativeContainer(record->getNameAsString());
}

bool clazy::isQtAssociativeContainer(StringRef className)
{
    static const vector<StringRef> classes = { "QSet", "QMap", "QHash" };
    return clazy::contains(classes, className);
}

bool clazy::isQObject(CXXRecordDecl *decl)
{
    return TypeUtils::derivesFrom(decl, "QObject");
}

bool clazy::isQObject(clang::QualType qt)
{
    qt = TypeUtils::pointeeQualType(qt);
    const auto t = qt.getTypePtrOrNull();
    return t ? isQObject(t->getAsCXXRecordDecl()) : false;
}

bool clazy::isConvertibleTo(const Type *source, const Type *target)
{
    if (!source || !target)
        return false;

    if (source->isPointerType() ^ target->isPointerType())
        return false;

    if (source == target)
        return true;

    if (source->getPointeeCXXRecordDecl() && source->getPointeeCXXRecordDecl() == target->getPointeeCXXRecordDecl())
        return true;

    if (source->isIntegerType() && target->isIntegerType())
        return true;

    if (source->isFloatingType() && target->isFloatingType())
        return true;

    // "QString" can convert to "const QString &" and vice versa
    if (TypeUtils::isConstRef(source) && source->getPointeeType().getTypePtrOrNull() == target)
        return true;
    if (TypeUtils::isConstRef(target) && target->getPointeeType().getTypePtrOrNull() == source)
        return true;

    return false;
}

bool clazy::isJavaIterator(CXXRecordDecl *record)
{
    if (!record)
        return false;

    static const vector<StringRef> names = { "QHashIterator", "QMapIterator", "QSetIterator", "QListIterator",
                                             "QVectorIterator", "QLinkedListIterator", "QStringListIterator" };

    return clazy::contains(names, clazy::name(record));
}

bool clazy::isJavaIterator(CXXMemberCallExpr *call)
{
    if (!call)
        return false;

    return isJavaIterator(call->getRecordDecl());
}

bool clazy::isQtContainer(QualType t)
{
    CXXRecordDecl *record = TypeUtils::typeAsRecord(t);
    if (!record)
        return false;

    return isQtContainer(record);
}

bool clazy::isQtContainer(const CXXRecordDecl *record)
{
    const StringRef typeName = clazy::name(record);
    return clazy::any_of(clazy::qtContainers(), [typeName] (StringRef container) {
        return container == typeName;
    });
}

bool clazy::containerNeverDetaches(const clang::VarDecl *valDecl, StmtBodyRange bodyRange) // clazy:exclude=function-args-by-value
{
    if (!valDecl)
        return false;

    const FunctionDecl *context = dyn_cast<FunctionDecl>(valDecl->getDeclContext());
    if (!context)
        return false;

    bodyRange.body = context->getBody();
    if (!bodyRange.body)
        return false;

    // TODO1: Being passed to a function as const should be OK
    if (Utils::isPassedToFunction(bodyRange, valDecl, false))
        return false;

    return true;
}

bool clazy::isAReserveClass(CXXRecordDecl *recordDecl)
{
    if (!recordDecl)
        return false;

    static const std::vector<std::string> classes = {"QVector", "std::vector", "QList", "QSet"};

    return clazy::any_of(classes, [recordDecl](const string &className) {
        return TypeUtils::derivesFrom(recordDecl, className);
    });
}

clang::CXXRecordDecl *clazy::getQObjectBaseClass(clang::CXXRecordDecl *recordDecl)
{
    if (!recordDecl)
        return nullptr;

    for (auto baseClass : recordDecl->bases()) {
        CXXRecordDecl *record = TypeUtils::recordFromBaseSpecifier(baseClass);
        if (isQObject(record))
            return record;
    }

    return nullptr;
}


bool clazy::isConnect(FunctionDecl *func)
{
    return func && func->getQualifiedNameAsString() == "QObject::connect";
}

bool clazy::connectHasPMFStyle(FunctionDecl *func)
{
    // Look for char* arguments
    for (auto parm : Utils::functionParameters(func)) {
        QualType qt = parm->getType();
        const Type *t = qt.getTypePtrOrNull();
        if (!t || !t->isPointerType())
            continue;

        const Type *ptt = t->getPointeeType().getTypePtrOrNull();
        if (ptt && ptt->isCharType())
            return false;
    }

    return true;
}

CXXMethodDecl *clazy::pmfFromConnect(CallExpr *funcCall, int argIndex)
{
    if (!funcCall)
        return nullptr;

    const int numArgs = funcCall->getNumArgs();
    if (numArgs < 3) {
        llvm::errs() << "error, connect call has less than 3 arguments\n";
        return nullptr;
    }

    if (argIndex >= numArgs)
        return nullptr;

    Expr *expr = funcCall->getArg(argIndex);
    return pmfFromUnary(expr);
}


CXXMethodDecl *clazy::pmfFromUnary(Expr *expr)
{
    if (auto uo = dyn_cast<UnaryOperator>(expr)) {
        return pmfFromUnary(uo);
    } else if (auto call = dyn_cast<CXXOperatorCallExpr>(expr)) {

        if (call->getNumArgs() <= 1)
            return nullptr;

        FunctionDecl *func = call->getDirectCallee();
        if (!func)
            return nullptr;

        auto context = func->getParent();
        if (!context)
            return nullptr;

        auto record = dyn_cast<CXXRecordDecl>(context);
        if (!record)
            return nullptr;

        const std::string className = record->getQualifiedNameAsString();
        if (className != "QNonConstOverload" && className != "QConstOverload")
            return nullptr;

        return pmfFromUnary(dyn_cast<UnaryOperator>(call->getArg(1)));
    } else if (auto staticCast = dyn_cast<CXXStaticCastExpr>(expr)) {
        return pmfFromUnary(staticCast->getSubExpr());
    } else if (auto callexpr = dyn_cast<CallExpr>(expr)) {
        // QOverload case, go deeper one level to get to the UnaryOperator
        if (callexpr->getNumArgs() == 1)
            return pmfFromUnary(callexpr->getArg(0));
    }

    return nullptr;
}

CXXMethodDecl *clazy::pmfFromUnary(UnaryOperator *uo)
{
    if (!uo)
        return nullptr;

    Expr *subExpr = uo->getSubExpr();
    if (!subExpr)
        return nullptr;

    auto declref = dyn_cast<DeclRefExpr>(subExpr);

    if (declref)
        return dyn_cast<CXXMethodDecl>(declref->getDecl());

    return nullptr;
}

bool clazy::recordHasCtorWithParam(clang::CXXRecordDecl *record, const std::string &paramType, bool &ok, int &numCtors)
{
    ok = true;
    numCtors = 0;
    if (!record || !record->hasDefinition() ||
        record->getDefinition() != record) { // Means fwd decl
        ok = false;
        return false;
    }

    for (auto ctor : record->ctors()) {
        if (ctor->isCopyOrMoveConstructor())
            continue;
        numCtors++;
        for (auto param : ctor->parameters()) {
            QualType qt = TypeUtils::pointeeQualType(param->getType());
            if (!qt.isConstQualified() && TypeUtils::derivesFrom(qt, paramType)) {
                return true;
            }
        }
    }

    return false;
}