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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
/* -*- 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/.
 */

#include <cassert>
#include <string>
#include <iostream>
#include <fstream>
#include <set>
#include "plugin.hxx"

/**
  Check for places where we do
   if (xxx) ;
  or
   if (xxx) {}
 */
namespace
{
class EmptyIf : public loplugin::FilteringRewritePlugin<EmptyIf>
{
public:
    explicit EmptyIf(loplugin::InstantiationData const& data)
        : FilteringRewritePlugin(data)
    {
    }

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

    bool VisitIfStmt(IfStmt const*);

private:
    bool ContainsComment(Stmt const*);
};

static bool empty(Stmt const* stmt)
{
    if (isa<NullStmt>(stmt))
        return true;
    auto compoundStmt = dyn_cast<CompoundStmt>(stmt);
    if (!compoundStmt)
        return false;
    return compoundStmt->size() == 0;
}

bool EmptyIf::ContainsComment(Stmt const* stmt)
{
    auto range = stmt->getSourceRange();
    SourceManager& SM = compiler.getSourceManager();
    SourceLocation startLoc = range.getBegin();
    SourceLocation endLoc = range.getEnd();
    char const* p1 = SM.getCharacterData(startLoc);
    char const* p2 = SM.getCharacterData(endLoc);
    p2 += Lexer::MeasureTokenLength(endLoc, SM, compiler.getLangOpts());
    auto s = llvm::StringRef(p1, p2 - p1);
    return s.find("//") != llvm::StringRef::npos || s.find("/*") != llvm::StringRef::npos
           || s.find("#if") != llvm::StringRef::npos;
}

bool EmptyIf::VisitIfStmt(IfStmt const* ifStmt)<--- The function 'VisitIfStmt' is never used.
{
    if (ignoreLocation(ifStmt))
        return true;

    if (ifStmt->getElse() && empty(ifStmt->getElse()) && !ContainsComment(ifStmt->getElse()))
    {
        report(DiagnosticsEngine::Warning, "empty else body",
               compat::getBeginLoc(ifStmt->getElse()))
            << ifStmt->getElse()->getSourceRange();
        return true;
    }

    if (!ifStmt->getElse() && empty(ifStmt->getThen()) && !ContainsComment(ifStmt->getThen()))
    {
        report(DiagnosticsEngine::Warning, "empty if body", compat::getBeginLoc(ifStmt))
            << ifStmt->getSourceRange();
    }

    return true;
}

loplugin::Plugin::Registration<EmptyIf> X("emptyif", true);
}

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