simplifyconstruct.cxx 2.67 KB
Newer Older
1 2 3 4 5 6 7 8 9
/* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
/*
 * This file is part of the LibreOffice project.
 *
 * This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
 */

10 11
#ifndef LO_CLANG_SHARED_PLUGINS

12 13 14 15 16 17 18 19 20 21 22
#include <memory>
#include <cassert>
#include <string>
#include <iostream>
#include <fstream>
#include <set>
#include "plugin.hxx"
#include "check.hxx"

namespace
{
23
class SimplifyConstruct : public loplugin::FilteringPlugin<SimplifyConstruct>
24 25 26
{
public:
    explicit SimplifyConstruct(loplugin::InstantiationData const& data)
27
        : FilteringPlugin(data)
28 29 30 31 32 33 34 35 36 37 38
    {
    }

    virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }

    bool VisitCXXConstructExpr(CXXConstructExpr const*);

    // ignore some contexts within which nullptr is fine
    bool TraverseReturnStmt(ReturnStmt*) { return true; }
    bool TraverseInitListExpr(InitListExpr*) { return true; }
    bool TraverseCXXBindTemporaryExpr(CXXBindTemporaryExpr*) { return true; }
39 40 41 42
    // ignore them for the shared visitor too
    bool PreTraverseReturnStmt(ReturnStmt*) { return false; }
    bool PreTraverseInitListExpr(InitListExpr*) { return false; }
    bool PreTraverseCXXBindTemporaryExpr(CXXBindTemporaryExpr*) { return false; }
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59
};

bool SimplifyConstruct::VisitCXXConstructExpr(CXXConstructExpr const* constructExpr)
{
    if (ignoreLocation(constructExpr))
        return true;
    auto tc = loplugin::TypeCheck(constructExpr->getType());
    if (!tc.Class("unique_ptr").StdNamespace() && !tc.Class("shared_ptr").StdNamespace()
        && !tc.Class("SvRef").Namespace("tools").GlobalNamespace()
        && !tc.Class("Reference").Namespace("rtl").GlobalNamespace()
        && !tc.Class("Reference")
                .Namespace("uno")
                .Namespace("star")
                .Namespace("sun")
                .Namespace("com")
                .GlobalNamespace())
        return true;
60
    if (constructExpr->getNumArgs() == 1
61 62 63
        && isa<CXXNullPtrLiteralExpr>(constructExpr->getArg(0)->IgnoreParenImpCasts()))
    {
        report(DiagnosticsEngine::Warning,
64 65
               "no need to explicitly init an instance of %0 with nullptr, just use default "
               "constructor",
66
               constructExpr->getSourceRange().getBegin())
67
            << constructExpr->getType() << constructExpr->getSourceRange();
68 69 70 71
    }
    return true;
}

72
loplugin::Plugin::Registration<SimplifyConstruct> simplifyconstruct("simplifyconstruct", true);
73 74
}

75 76
#endif // LO_CLANG_SHARED_PLUGINS

77
/* vim:set shiftwidth=4 softtabstop=4 expandtab: */