2 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
4 * This file is part of the LibreOffice project.
6 * This Source Code Form is subject to the terms of the Mozilla Public
7 * License, v. 2.0. If a copy of the MPL was not distributed with this
8 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
13 #include <unordered_set>
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/StmtVisitor.h"
21 Mike Kaganski found a bug where the code was looping over a block and
22 not using the index var, and the loop was unnecessary.
23 So he wanted to have a look for other places like that.
27 class UnusedIndex
: public loplugin::FilteringPlugin
<UnusedIndex
>
30 explicit UnusedIndex(loplugin::InstantiationData
const& data
)
31 : FilteringPlugin(data
)
35 virtual void run() override
{ TraverseDecl(compiler
.getASTContext().getTranslationUnitDecl()); }
37 bool TraverseForStmt(ForStmt
* stmt
);
38 bool VisitDeclRefExpr(DeclRefExpr
const* stmt
);
41 std::vector
<VarDecl
const*> mLoopVarDecls
;
42 std::unordered_set
<VarDecl
const*> mFoundSet
;
45 bool UnusedIndex::TraverseForStmt(ForStmt
* stmt
)
47 if (ignoreLocation(stmt
))
50 VarDecl
const* loopVarDecl
= nullptr;
53 auto declStmt
= dyn_cast
<DeclStmt
>(stmt
->getInit());
54 if (declStmt
&& declStmt
->isSingleDecl())
56 loopVarDecl
= dyn_cast
<VarDecl
>(declStmt
->getSingleDecl());
60 mLoopVarDecls
.push_back(loopVarDecl
);
62 // deliberately ignore the other parts of the for stmt, except for the body
63 auto ret
= RecursiveASTVisitor::TraverseStmt(stmt
->getBody());
65 if (loopVarDecl
&& mFoundSet
.erase(loopVarDecl
) == 0)
66 report(DiagnosticsEngine::Warning
, "loop variable not used",
67 compat::getBeginLoc(loopVarDecl
))
68 << loopVarDecl
->getSourceRange();
71 mLoopVarDecls
.pop_back();
75 bool UnusedIndex::VisitDeclRefExpr(DeclRefExpr
const* stmt
)
77 auto varDecl
= dyn_cast
<VarDecl
>(stmt
->getDecl());
80 if (std::find(mLoopVarDecls
.begin(), mLoopVarDecls
.end(), varDecl
) != mLoopVarDecls
.end())
81 mFoundSet
.insert(varDecl
);
85 loplugin::Plugin::Registration
<UnusedIndex
> X("unusedindex", false);
88 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */