Version 6.1.0.2, tag libreoffice-6.1.0.2
[LibreOffice.git] / compilerplugins / clang / unusedindex.cxx
blob1235e32b3a28ccc74b66100296c8d4b38984fc20
2 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
3 /*
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/.
9 */
11 #include <string>
12 #include <iostream>
13 #include <unordered_set>
15 #include "plugin.hxx"
16 #include "check.hxx"
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.
25 namespace
27 class UnusedIndex : public RecursiveASTVisitor<UnusedIndex>, public loplugin::Plugin
29 public:
30 explicit UnusedIndex(loplugin::InstantiationData const& data)
31 : Plugin(data)
35 virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
37 bool TraverseForStmt(ForStmt* stmt);
38 bool VisitDeclRefExpr(DeclRefExpr const* stmt);
40 private:
41 std::vector<VarDecl const*> mLoopVarDecls;
42 std::unordered_set<VarDecl const*> mFoundSet;
45 bool UnusedIndex::TraverseForStmt(ForStmt* stmt)
47 if (ignoreLocation(stmt))
48 return true;
50 VarDecl const* loopVarDecl = nullptr;
51 if (stmt->getInit())
53 auto declStmt = dyn_cast<DeclStmt>(stmt->getInit());
54 if (declStmt && declStmt->isSingleDecl())
56 loopVarDecl = dyn_cast<VarDecl>(declStmt->getSingleDecl());
59 if (loopVarDecl)
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", loopVarDecl->getLocStart())
67 << loopVarDecl->getSourceRange();
69 if (loopVarDecl)
70 mLoopVarDecls.pop_back();
71 return ret;
74 bool UnusedIndex::VisitDeclRefExpr(DeclRefExpr const* stmt)
76 auto varDecl = dyn_cast<VarDecl>(stmt->getDecl());
77 if (!varDecl)
78 return true;
79 if (std::find(mLoopVarDecls.begin(), mLoopVarDecls.end(), varDecl) != mLoopVarDecls.end())
80 mFoundSet.insert(varDecl);
81 return true;
84 loplugin::Plugin::Registration<UnusedIndex> X("unusedindex", false);
87 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */