Debian Codegraph @

src/checks/manuallevel/qproperty-type-mismatch.cpp

raw
1 /*
2 SPDX-FileCopyrightText: 2019 Jean-Michaël Celerier <[email protected]>
3
4 SPDX-License-Identifier: LGPL-2.0-or-later
5 */
6
7 #include "qproperty-type-mismatch.h"
8 #include "AccessSpecifierManager.h"
9 #include "ClazyContext.h"
10 #include "TypeUtils.h"
11
12 #include <clang/AST/Decl.h>
13 #include <clang/AST/DeclCXX.h>
14 #include <clang/AST/Expr.h>
15 #include <clang/AST/ExprCXX.h>
16 #include <clang/AST/Stmt.h>
17 #include <clang/AST/Type.h>
18 #include <clang/Basic/IdentifierTable.h>
19 #include <clang/Basic/LLVM.h>
20 #include <clang/Basic/SourceManager.h>
21 #include <clang/Lex/Token.h>
22 #include <llvm/ADT/ArrayRef.h>
23 #include <llvm/ADT/StringRef.h>
24 #include <llvm/Support/Casting.h>
25
26 #include <algorithm>
27 #include <cctype>
28 #include <string_view>
29
30 using namespace clang;
31
32 void QPropertyTypeMismatch::VisitDecl(clang::Decl *decl)
33 {
34 if (auto *method = dyn_cast<CXXMethodDecl>(decl)) {
35 VisitMethod(*method);
36 } else if (auto *field = dyn_cast<FieldDecl>(decl)) {
37 VisitField(*field);
38 } else if (auto *typedefdecl = dyn_cast<TypedefNameDecl>(decl)) {
39 VisitTypedef(typedefdecl);
40 }
41 }
42
43 void QPropertyTypeMismatch::VisitMethod(const clang::CXXMethodDecl &method)
44 {
45 if (method.isThisDeclarationADefinition() && !method.hasInlineBody()) {
46 return;
47 }
48
49 const auto &theClass = method.getParent();
50 const auto &classRange = theClass->getSourceRange();
51 const auto &methodName = method.getNameInfo().getName().getAsString();
52
53 for (const auto &prop : m_qproperties) {
54 if (classRange.getBegin() < prop.loc && prop.loc < classRange.getEnd()) {
55 checkMethodAgainstProperty(prop, method, methodName);
56 }
57 }
58 }
59
60 void QPropertyTypeMismatch::VisitField(const FieldDecl &field)
61 {
62 const auto &theClass = field.getParent();
63 const auto &classRange = theClass->getSourceRange();
64 const auto &methodName = field.getName().str();
65
66 for (const auto &prop : m_qproperties) {
67 if (classRange.getBegin() < prop.loc && prop.loc < classRange.getEnd()) {
68 checkFieldAgainstProperty(prop, field, methodName);
69 }
70 }
71 }
72
73 void QPropertyTypeMismatch::VisitTypedef(const clang::TypedefNameDecl *td)
74 {
75 // Since when processing Q_PROPERTY we're at the pre-processor stage we don't have access
76 // to the Qualtypes, so catch any typedefs here
77 QualType underlyingType = td->getUnderlyingType();
78 m_typedefMap[td->getQualifiedNameAsString()] = underlyingType;
79 if (!m_context->qtNamespace().empty()) {
80 m_typedefMap[trimQtNamespace(td->getQualifiedNameAsString())] = underlyingType;
81 }
82 m_typedefMap[td->getNameAsString()] = underlyingType; // It might be written unqualified in the Q_PROPERTY
83
84 // FIXME: All the above is a bit flaky, as we don't know the actual namespace when the type is written without namespace in Q_PROPERTY
85 // Proper solution would be to process the .moc instead of doing text manipulation with the macros we receive
86 }
87
88 std::string QPropertyTypeMismatch::cleanupType(QualType type, bool unscoped) const
89 {
90 type = type.getNonReferenceType().getCanonicalType().getUnqualifiedType();
91
92 PrintingPolicy po(lo());
93 po.SuppressTagKeyword = true;
94 po.SuppressScope = unscoped;
95
96 std::string str = type.getAsString(po);
97 str.erase(std::remove_if(str.begin(),
98 str.end(),
99 [](char c) {
100 return std::isspace(c);
101 }),
102 str.end());
103
104 return str;
105 }
106
107 void QPropertyTypeMismatch::checkMethodAgainstProperty(const Property &prop, const CXXMethodDecl &method, const std::string &methodName)
108 {
109 auto error_begin = [&] {
110 return "Q_PROPERTY '" + prop.name + "' of type '" + prop.type + "' is mismatched with ";
111 };
112
113 if (prop.read == methodName) {
114 std::string retTypeStr;
115 if (!typesMatch(prop.type, method.getReturnType(), retTypeStr)) {
116 emitWarning(&method, error_begin() + "method '" + methodName + "' of return type '" + retTypeStr + "'");
117 }
118 } else if (prop.write == methodName) {
119 switch (method.getNumParams()) {
120 case 0:
121 emitWarning(&method, error_begin() + "method '" + methodName + "' with no parameters");
122 break;
123 case 1: {
124 std::string parmTypeStr;
125 if (!typesMatch(prop.type, method.getParamDecl(0)->getType(), parmTypeStr)) {
126 emitWarning(&method, error_begin() + "method '" + methodName + "' with parameter of type '" + parmTypeStr + "'");
127 }
128 break;
129 }
130 default:
131 // Commented out: Too verbose and it's not a bug, maybe wrap with an option for the purists
132 // emitWarning(&method, error_begin() + "method '" + methodName + "' with too many parameters");
133 break;
134 }
135 } else if (prop.notify == methodName) {
136 switch (method.getNumParams()) {
137 case 0:
138 break;
139 case 2: {
140 /*
141 // Commented out: Too verbose and it's not a bug, maybe wrap with an option for the purists
142 auto param1TypeStr = cleanupType(method.getParamDecl(1)->getType());
143 if(param1TypeStr.find("QPrivateSignal") == std::string::npos)
144 {
145 emitWarning(&method, error_begin() + "signal '" + methodName + "' with too many parameters" + param1TypeStr);
146 break;
147 }
148
149 // We want to check the first parameter too :
150 [[fallthrough]];*/
151 }
152 case 1: {
153 std::string param0TypeStr;
154 if (!typesMatch(prop.type, method.getParamDecl(0)->getType(), param0TypeStr)) {
155 const bool isPrivateSignal = param0TypeStr.find("QPrivateSignal") != std::string::npos;
156 if (!isPrivateSignal) {
157 emitWarning(&method, error_begin() + "signal '" + methodName + "' with parameter of type '" + param0TypeStr + "'");
158 }
159 }
160 break;
161 }
162 default: {
163 break;
164 }
165 }
166 }
167 }
168
169 void QPropertyTypeMismatch::checkFieldAgainstProperty(const Property &prop, const FieldDecl &field, const std::string &fieldName)
170 {
171 if (prop.member && prop.name == fieldName) {
172 std::string typeStr;
173 if (!typesMatch(prop.type, field.getType(), typeStr)) {
174 emitWarning(&field,
175 "Q_PROPERTY '" + prop.name + "' of type '" + prop.type + "' is mismatched with member '" + fieldName + "' of type '" + typeStr + "'");
176 }
177 }
178 }
179
180 bool QPropertyTypeMismatch::typesMatch(const std::string &type1, QualType type2Qt, std::string &type2Cleaned) const
181 {
182 type2Cleaned = cleanupType(type2Qt);
183 if (type1 == type2Cleaned) {
184 return true;
185 }
186
187 // Maybe it's a typedef
188 auto it = m_typedefMap.find(type1);
189 if (it != m_typedefMap.cend()) {
190 return it->second == type2Qt || cleanupType(it->second) == type2Cleaned;
191 }
192
193 // Maybe the difference is just the scope, if yes then don't warn. We already have a check for complaining about lack of scope
194 type2Cleaned = cleanupType(type2Qt, /*unscopped=*/true);
195 return type1 == type2Cleaned;
196 }
197
198 void QPropertyTypeMismatch::VisitMacroExpands(const clang::Token &MacroNameTok, const clang::SourceRange &range, const MacroInfo *)
199 {
200 IdentifierInfo *ii = MacroNameTok.getIdentifierInfo();
201 if (!ii) {
202 return;
203 }
204
205 constexpr llvm::StringLiteral q_property{"Q_PROPERTY"};
206
207 if (ii->getName() != q_property) {
208 return;
209 }
210
211 const CharSourceRange crange = Lexer::getAsCharRange(range, sm(), lo());
212
213 llvm::StringRef text = Lexer::getSourceText(crange, sm(), lo());
214
215 const auto openingLParen = std::find_if_not(text.begin() + q_property.size(), text.end(), [](char c) {
216 return std::isspace(c);
217 });
218 if (*openingLParen != '(') {
219 emitWarning(range.getBegin(), "Could not parse argument of the Q_PROPERTY macro");
220 return;
221 }
222
223 const std::size_t contentBegin = openingLParen - text.begin() + 1;
224 std::size_t contentLength = text.size() - contentBegin;
225 if (!text.empty() && text.back() == ')') {
226 --contentLength;
227 }
228 text = text.substr(contentBegin, contentLength);
229
230 std::vector<std::string_view> split = clazy::splitStringBySpaces(text);
231 if (split.size() < 2) {
232 return;
233 }
234
235 Property p;
236 p.loc = range.getBegin();
237
238 std::size_t splitIndex = 0;
239 using namespace std::string_view_literals;
240
241 // Handle type (type string and any following modifiers)
242 const auto isModifier = [](std::string_view str) {
243 return str == "*"sv || str == "&"sv;
244 };
245
246 for (; isModifier(split[splitIndex]) || p.type.empty(); ++splitIndex) {
247 p.type += split[splitIndex];
248 }
249
250 // Handle name
251 p.name = split[splitIndex];
252
253 std::size_t actualNameStartPos = 0;
254 // FIXME: This is getting hairy, better use regexps
255 for (unsigned int i = 0; i < p.name.size(); ++i) {
256 if (p.name[i] == '*' || p.name[i] == '&') {
257 p.type += p.name[i];
258 ++actualNameStartPos;
259 } else {
260 break;
261 }
262 }
263
264 if (actualNameStartPos) {
265 p.name.erase(0, actualNameStartPos);
266 }
267
268 // Handle Q_PROPERTY functions
269 enum { None, Read, Write, Notify } next = None;
270
271 for (const std::string_view &token : split) {
272 switch (next) {
273 case None: {
274 if (token == "READ"sv) {
275 next = Read;
276 continue;
277 } else if (token == "WRITE"sv) {
278 next = Write;
279 continue;
280 } else if (token == "NOTIFY"sv) {
281 next = Notify;
282 continue;
283 } else if (token == "MEMBER"sv) {
284 p.member = true;
285 break;
286 }
287 break;
288 }
289 case Read:
290 p.read = token;
291 break;
292 case Write:
293 p.write = token;
294 break;
295 case Notify:
296 p.notify = token;
297 break;
298 }
299
300 next = None;
301 }
302
303 m_qproperties.push_back(std::move(p));
304 }