Debian Codegraph @

src/checks/manuallevel/use-arrow-operator-instead-of-data.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2021 Klarälvdalens Datakonsult AB a KDAB Group company [email protected]
3 SPDX-FileContributor: Waqar Ahmed <[email protected]>
4
5 SPDX-FileCopyrightText: 2021 Waqar Ahmed <[email protected]>
6
7 SPDX-License-Identifier: LGPL-2.0-or-later
8 */
9
10 #include "use-arrow-operator-instead-of-data.h"
11 #include "StringUtils.h"
12 #include "Utils.h"
13 #include "clazy_stl.h"
14
15 #include <clang/AST/ExprCXX.h>
16
17 using namespace clang;
18
19 void UseArrowOperatorInsteadOfData::VisitStmt(clang::Stmt *stmt)
20 {
21 auto *ce = dyn_cast<CXXMemberCallExpr>(stmt);
22 if (!ce) {
23 return;
24 }
25
26 auto vec = Utils::callListForChain(ce);
27 if (vec.size() < 2) {
28 return;
29 }
30
31 CallExpr *callExpr = vec.at(vec.size() - 1);
32
33 FunctionDecl *funcDecl = callExpr->getDirectCallee();
34 if (!funcDecl) {
35 return;
36 }
37 const std::string func = clazy::qualifiedMethodName(funcDecl);
38 static const std::vector<std::string> whiteList{"QScopedPointer::data", "QPointer::data", "QSharedPointer::data", "QSharedDataPointer::data"};
39 if (!clazy::contains(whiteList, func)) {
40 return;
41 }
42
43 for (const auto &chain : vec) {
44 if (auto a = dyn_cast<CXXMemberCallExpr>(chain)) {
45 if (auto callee = dyn_cast<MemberExpr>(a->getCallee()); callee && dyn_cast<CXXStaticCastExpr>(callee->getBase()->IgnoreImpCasts())) {
46 return; // We have some kind of cast going on here. This means we can not use the arrow operator directly
47 }
48 }
49 }
50
51 std::vector<FixItHint> fixits;
52
53 constexpr int MinPossibleColonPos = sizeof("QPointer") - 1;
54 const std::string ClassName = func.substr(0, func.find(':', MinPossibleColonPos));
55
56 auto begin = callExpr->getExprLoc();
57 const auto end = callExpr->getEndLoc();
58
59 // find '.' in ptr.data()
60 int dotOffset = 0;
61 const char *d = sm().getCharacterData(begin);
62 while (*d != '.') {
63 dotOffset--;
64 d--;
65 }
66 begin = begin.getLocWithOffset(dotOffset);
67
68 fixits.push_back(FixItHint::CreateRemoval(SourceRange{begin, end}));
69
70 emitWarning(callExpr->getBeginLoc(), "Use operator -> directly instead of " + ClassName + "::data()->", fixits);
71 }