qproperty-type-mismatch.cpp 10 KB
Newer Older
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
/*
  This file is part of the clazy static checker.

    Copyright (C) 2019 Jean-Michaël Celerier <jeanmichael.celerier@gmail.com>

    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 "qproperty-type-mismatch.h"
#include "HierarchyUtils.h"
#include "TypeUtils.h"
#include "ClazyContext.h"
#include "AccessSpecifierManager.h"
#include "SourceCompatibilityHelpers.h"
#include "StringUtils.h"

#include <clang/AST/Decl.h>
#include <clang/AST/DeclCXX.h>
#include <clang/AST/Expr.h>
#include <clang/AST/ExprCXX.h>
#include <clang/AST/Stmt.h>
#include <clang/AST/Type.h>
#include <clang/Basic/IdentifierTable.h>
#include <clang/Basic/LLVM.h>
#include <clang/Basic/SourceManager.h>
#include <clang/Lex/Token.h>
#include <llvm/ADT/ArrayRef.h>
#include <llvm/ADT/StringRef.h>
#include <llvm/Support/Casting.h>
#include <algorithm>
#include <cctype>

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

using namespace clang;
using namespace std;


QPropertyTypeMismatch::QPropertyTypeMismatch(const std::string &name, ClazyContext *context)
    : CheckBase(name, context)
{
    enablePreProcessorCallbacks();
59
    context->enableVisitallTypeDefs();
60 61 62 63 64 65 66 67
}

void QPropertyTypeMismatch::VisitDecl(clang::Decl *decl)
{
    if (auto method = dyn_cast<CXXMethodDecl>(decl))
        VisitMethod(*method);
    else if (auto field = dyn_cast<FieldDecl>(decl))
        VisitField(*field);
68 69
    else if (auto typedefdecl = dyn_cast<TypedefNameDecl>(decl))
        VisitTypedef(typedefdecl);
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
}

void QPropertyTypeMismatch::VisitMethod(const clang::CXXMethodDecl & method)
{
    if (method.isThisDeclarationADefinition() && !method.hasInlineBody())
        return;

    const auto& theClass = method.getParent();
    const auto& classRange = theClass->getSourceRange();
    const auto& methodName = method.getNameInfo().getName().getAsString();

    for(const auto& prop : m_qproperties)
    {
        if(classRange.getBegin() < prop.loc && prop.loc < classRange.getEnd())
        {
            checkMethodAgainstProperty(prop, method, methodName);
        }
    }
}

void QPropertyTypeMismatch::VisitField(const FieldDecl & field)
{
    const auto& theClass = field.getParent();
    const auto& classRange = theClass->getSourceRange();
    const auto& methodName = field.getName().str();

    for(const auto& prop : m_qproperties)
    {
        if(classRange.getBegin() < prop.loc && prop.loc < classRange.getEnd())
        {
            checkFieldAgainstProperty(prop, field, methodName);
        }
    }
}

105
void QPropertyTypeMismatch::VisitTypedef(const clang::TypedefNameDecl *td)
106 107 108
{
    // Since when processing Q_PROPERTY we're at the pre-processor stage we don't have access
    // to the Qualtypes, so catch any typedefs here
109 110
    QualType underlyingType = td->getUnderlyingType();
    m_typedefMap[td->getQualifiedNameAsString()] = underlyingType;
111 112 113 114
    m_typedefMap[td->getNameAsString()] = underlyingType; // It might be written unqualified in the Q_PROPERTY

    // 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
    // Proper solution would be to process the .moc instead of doing text manipulation with the macros we receive
115 116 117
}

std::string QPropertyTypeMismatch::cleanupType(QualType type, bool unscoped) const
118
{
119 120
    type = type.getNonReferenceType().getCanonicalType().getUnqualifiedType();

121 122
    PrintingPolicy po(lo());
    po.SuppressTagKeyword = true;
123
    po.SuppressScope = unscoped;
124

125
    std::string str = type.getAsString(po);
126 127 128 129
    str.erase(std::remove_if(str.begin(), str.end(), [] (char c) {
        return std::isspace(c);
    }), str.end());

130 131 132 133 134 135 136
    return str;
}

void QPropertyTypeMismatch::checkMethodAgainstProperty (const Property& prop, const CXXMethodDecl& method, const std::string& methodName){

    auto error_begin = [&] { return "Q_PROPERTY '" + prop.name + "' of type '" + prop.type + "' is mismatched with "; };

137
    if (prop.read == methodName) {
138 139 140
        std::string retTypeStr;
        if (!typesMatch(prop.type, method.getReturnType(), retTypeStr)) {
            emitWarning(&method, error_begin() + "method '" + methodName + "' of return type '"+ retTypeStr +"'");
141 142 143 144 145 146 147 148 149 150 151
        }
    }
    else if(prop.write == methodName)
    {
        switch(method.getNumParams())
        {
        case 0:
            emitWarning(&method, error_begin() + "method '" + methodName + "' with no parameters");
            break;
        case 1:
        {
152 153
            std::string parmTypeStr;
            if (!typesMatch(prop.type, method.getParamDecl(0)->getType(), parmTypeStr))
154 155 156 157
                emitWarning(&method, error_begin() + "method '" + methodName + "' with parameter of type '"+ parmTypeStr +"'");
            break;
        }
        default:
158 159
            // Commented out: Too verbose and it's not a bug, maybe wrap with an option for the purists
            // emitWarning(&method, error_begin() + "method '" + methodName + "' with too many parameters");
160 161 162 163 164 165 166 167 168 169 170
            break;
        }
    }
    else if(prop.notify == methodName)
    {
        switch(method.getNumParams())
        {
        case 0:
            break;
        case 2:
        {
171 172
            /*
             // Commented out: Too verbose and it's not a bug, maybe wrap with an option for the purists
173 174 175 176 177 178 179 180
            auto param1TypeStr = cleanupType(method.getParamDecl(1)->getType());
            if(param1TypeStr.find("QPrivateSignal") == std::string::npos)
            {
                emitWarning(&method, error_begin() + "signal '" + methodName + "' with too many parameters" + param1TypeStr);
                break;
            }

            // We want to check the first parameter too :
181
            [[fallthrough]];*/
182 183 184
        }
        case 1:
        {
185
            std::string param0TypeStr;
186 187 188 189 190
            if (!typesMatch(prop.type, method.getParamDecl(0)->getType(), param0TypeStr)) {
                const bool isPrivateSignal = param0TypeStr.find("QPrivateSignal") != std::string::npos;
                if (!isPrivateSignal)
                    emitWarning(&method, error_begin() + "signal '" + methodName + "' with parameter of type '"+ param0TypeStr +"'");
            }
191 192 193 194 195 196 197 198 199 200 201 202
            break;
        }
        default:
        {
            break;
        }
        }
    }
}

void QPropertyTypeMismatch::checkFieldAgainstProperty (const Property& prop, const FieldDecl& field, const std::string& fieldName)
{
203 204 205
    if (prop.member && prop.name == fieldName) {
        std::string typeStr;
        if (!typesMatch(prop.type, field.getType(), typeStr))
206 207 208 209
            emitWarning(&field, "Q_PROPERTY '" + prop.name + "' of type '" + prop.type + "' is mismatched with member '" + fieldName + "' of type '"+ typeStr +"'");
    }
}

210
bool QPropertyTypeMismatch::typesMatch(const string &type1, QualType type2Qt, std::string &type2Cleaned) const
211
{
212 213
    type2Cleaned = cleanupType(type2Qt);
    if (type1 == type2Cleaned)
214 215
        return true;

216 217 218
    // Maybe it's a typedef
    auto it = m_typedefMap.find(type1);
    if (it != m_typedefMap.cend()) {
219
        return it->second == type2Qt || cleanupType(it->second) == type2Cleaned;
220 221
    }

222 223 224 225 226
    // Maybe the difference is just the scope, if yes then don't warn. We already have a check for complaining about lack of scope
    type2Cleaned = cleanupType(type2Qt, /*unscopped=*/ true);
    if (type1 == type2Cleaned)
        return true;

227 228 229
    return false;
}

230 231 232 233 234 235 236 237 238 239
void QPropertyTypeMismatch::VisitMacroExpands(const clang::Token &MacroNameTok, const clang::SourceRange &range, const MacroInfo *)
{
    IdentifierInfo *ii = MacroNameTok.getIdentifierInfo();
    if(!ii)
        return;
    if(ii->getName() != "Q_PROPERTY")
        return;

    CharSourceRange crange = Lexer::getAsCharRange(range, sm(), lo());

Egor Gabov's avatar
Egor Gabov committed
240
    string text = static_cast<string>(Lexer::getSourceText(crange, sm(), lo()));
241 242 243
    if (!text.empty() && text.back() == ')')
        text.pop_back();

244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260
    std::vector<std::string> split = clazy::splitString(text, ' ');
    if(split.size() < 2)
        return;

    Property p;
    p.loc = range.getBegin();

    // Handle type
    clazy::rtrim(split[0]);
    p.type = split[0];
    if(p.type.find("Q_PROPERTY(") == 0)
        p.type = p.type.substr(11);

    // Handle name
    clazy::rtrim(split[1]);
    p.name = split[1];

261
    // FIXME: This is getting hairy, better use regexps
262
    for (unsigned int i = 0; i < p.name.size(); ++i) {
263 264 265 266 267 268 269 270 271
        if (p.name[i] == '*') {
            p.type += '*';
        } else {
            break;
        }
    }

    p.name.erase(std::remove(p.name.begin(), p.name.end(), '*'), p.name.end());

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
    // Handle Q_PROPERTY functions
    enum {
        None, Read, Write, Notify
    } next = None;

    for (std::string &token : split) {
        clazy::rtrim(/*by-ref*/token);
        switch(next)
        {
        case None:
        {
            if (token == "READ") {
                next = Read;
                continue;
            }
            else if (token == "WRITE") {
                next = Write;
                continue;
            }
            else if (token == "NOTIFY") {
                next = Notify;
                continue;
            }
            else if (token == "MEMBER") {
                p.member = true;
                break;
            }
            break;
        }
        case Read:
            p.read = token;
            break;
        case Write:
            p.write = token;
            break;
        case Notify:
            p.notify = token;
            break;
        }

        next = None;
    }

    m_qproperties.push_back(std::move(p));
}