Debian Codegraph @

src/checks/level0/qcolor-from-literal.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2017 Sergio Martins <[email protected]>
3 SPDX-FileCopyrightText: 2023 Alexander Lohnau <[email protected]>
4
5 SPDX-License-Identifier: LGPL-2.0-or-later
6 */
7
8 #include "qcolor-from-literal.h"
9 #include "HierarchyUtils.h"
10 #include "StringUtils.h"
11
12 #include <cctype>
13 #include <clang/AST/Expr.h>
14 #include <clang/AST/ExprCXX.h>
15 #include <clang/AST/Stmt.h>
16 #include <clang/ASTMatchers/ASTMatchFinder.h>
17 #include <clang/ASTMatchers/ASTMatchers.h>
18 #include <clang/ASTMatchers/ASTMatchersInternal.h>
19 #include <clang/Basic/LLVM.h>
20 #include <llvm/ADT/StringRef.h>
21 #include <llvm/Support/Casting.h>
22
23 using namespace clang;
24 using namespace clang::ast_matchers;
25
26 static bool isSingleDigitRgb(llvm::StringRef ref)
27 {
28 return ref.size() == 4;
29 }
30 static bool isDoubleDigitRgb(llvm::StringRef ref)
31 {
32 return ref.size() == 7;
33 }
34 static bool isDoubleDigitRgba(llvm::StringRef ref)
35 {
36 return ref.size() == 9;
37 }
38 static bool isTripleDigitRgb(llvm::StringRef ref)
39 {
40 return ref.size() == 10;
41 }
42 static bool isQuadrupleDigitRgb(llvm::StringRef ref)
43 {
44 return ref.size() == 13;
45 }
46
47 static bool isStringColorLiteralPattern(StringRef str)
48 {
49 if (!clazy::startsWith(str, "#")) {
50 return false;
51 }
52 return isSingleDigitRgb(str) || isDoubleDigitRgb(str) || isDoubleDigitRgba(str) || isTripleDigitRgb(str) || isQuadrupleDigitRgb(str);
53 }
54
55 class QColorFromLiteral_Callback : public ClazyAstMatcherCallback
56 {
57 public:
58 using ClazyAstMatcherCallback::ClazyAstMatcherCallback;
59
60 void run(const MatchFinder::MatchResult &result) override
61 {
62 auto *lt = result.Nodes.getNodeAs<StringLiteral>("myLiteral");
63 const Expr *replaceExpr = lt; // When QColor::fromString is used, we want to wrap the QColor constructor around it
64 bool isStaticFromString = false;
65 if (auto res = result.Nodes.getNodeAs<CallExpr>("methodCall"); res && res->getNumArgs() == 1) {
66 if (Expr *argExpr = const_cast<Expr *>(res->getArg(0))) {
67 lt = clazy::getFirstChildOfType<StringLiteral>(argExpr);
68 replaceExpr = res;
69 isStaticFromString = true;
70 }
71 }
72 if (!lt) {
73 return;
74 }
75
76 llvm::StringRef str = lt->getString();
77 if (!clazy::startsWith(str, "#")) {
78 return;
79 }
80
81 const bool singleDigit = isSingleDigitRgb(str);
82 const bool doubleDigit = isDoubleDigitRgb(str);
83 const bool doubleDigitA = isDoubleDigitRgba(str);
84 if (bool isAnyValidPattern = singleDigit || doubleDigit || doubleDigitA || isTripleDigitRgb(str) || isQuadrupleDigitRgb(str); !isAnyValidPattern) {
85 m_check->emitWarning(replaceExpr->getBeginLoc(), "Pattern length does not match any supported one by QColor, check the documentation");
86 return;
87 }
88
89 for (unsigned int i = 1; i < str.size(); ++i) {
90 if (!isxdigit(str[i])) {
91 m_check->emitWarning(replaceExpr->getBeginLoc(), "QColor pattern may only contain hexadecimal digits");
92 return;
93 }
94 }
95
96 if (singleDigit || doubleDigit || doubleDigitA) {
97 const int increment = singleDigit ? 1 : 2;
98 int endPos = 1;
99 int startPos = 1;
100
101 std::string aColor = doubleDigitA ? getHexValue(str, startPos, endPos, increment) : "";
102 std::string rColor = getHexValue(str, startPos, endPos, increment);
103 std::string gColor = getHexValue(str, startPos, endPos, increment);
104 std::string bColor = getHexValue(str, startPos, endPos, increment);
105
106 std::string fixit;
107 std::string message;
108 if (doubleDigitA) {
109 const static std::string sep = ", ";
110 fixit = prefixHex(rColor) + sep + prefixHex(gColor) + sep + prefixHex(bColor) + sep + prefixHex(aColor);
111 message = "The QColor ctor taking ints is cheaper than one taking string literals";
112 } else {
113 fixit = "0x" + twoDigit(rColor) + twoDigit(gColor) + twoDigit(bColor);
114 message = "The QColor ctor taking RGB int value is cheaper than one taking string literals";
115 }
116 if (isStaticFromString) {
117 fixit = "QColor(" + fixit + ")";
118 }
119 m_check->emitWarning(replaceExpr->getBeginLoc(), message, {clang::FixItHint::CreateReplacement(replaceExpr->getSourceRange(), fixit)});
120 } else {
121 // triple or quadruple digit RGBA
122 m_check->emitWarning(replaceExpr->getBeginLoc(), "The QColor ctor taking QRgba64 is cheaper than one taking string literals");
123 }
124 }
125 inline std::string twoDigit(const std::string &in)
126 {
127 return in.length() == 1 ? in + in : in;
128 }
129 inline std::string prefixHex(const std::string &in)
130 {
131 const static std::string hex = "0x";
132 return in == "0" ? in : hex + in;
133 }
134 inline std::string getHexValue(StringRef fullStr, int &startPos, int &endPos, int increment) const
135 {
136 endPos += increment;
137 clang::StringRef color = fullStr.slice(startPos, endPos);
138 startPos = endPos;
139
140 int result = 0;
141 color.getAsInteger(16, result);
142 if (result == 0) {
143 return "0";
144 } else {
145 return color.str();
146 }
147 }
148 };
149
150 QColorFromLiteral::~QColorFromLiteral() = default;
151
152 void QColorFromLiteral::VisitStmt(Stmt *stmt)
153 {
154 auto *call = dyn_cast<CXXMemberCallExpr>(stmt);
155 if (!call || call->getNumArgs() != 1) {
156 return;
157 }
158
159 std::string name = clazy::qualifiedMethodName(call);
160 if (name != "QColor::setNamedColor") {
161 return;
162 }
163
164 auto *lt = clazy::getFirstChildOfType2<StringLiteral>(call->getArg(0));
165 if (lt && isStringColorLiteralPattern(lt->getString())) {
166 emitWarning(lt, "The ctor taking ints is cheaper than QColor::setNamedColor(QString)");
167 }
168 }
169
170 void QColorFromLiteral::registerASTMatchers(MatchFinder &finder)
171 {
172 m_astMatcherCallBack = std::make_unique<QColorFromLiteral_Callback>(this);
173 finder.addMatcher(cxxConstructExpr(hasDeclaration(namedDecl(hasName("QColor"))), hasArgument(0, stringLiteral().bind("myLiteral"))),
174 m_astMatcherCallBack.get());
175 finder.addMatcher(callExpr(hasDeclaration(cxxMethodDecl(hasName("fromString"), hasParent(cxxRecordDecl(hasName("QColor")))))).bind("methodCall"),
176 m_astMatcherCallBack.get());
177 }