[en_US] Added 13 autocorrect words
[LibreOffice.git] / compilerplugins / clang / unusedindex.cxx
bloba47d55b0fd0a2f3960c082d0c379a56c4f8d9ae8
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 loplugin::FilteringPlugin<UnusedIndex>
29 public:
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);
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",
67 compat::getBeginLoc(loopVarDecl))
68 << loopVarDecl->getSourceRange();
70 if (loopVarDecl)
71 mLoopVarDecls.pop_back();
72 return ret;
75 bool UnusedIndex::VisitDeclRefExpr(DeclRefExpr const* stmt)
77 auto varDecl = dyn_cast<VarDecl>(stmt->getDecl());
78 if (!varDecl)
79 return true;
80 if (std::find(mLoopVarDecls.begin(), mLoopVarDecls.end(), varDecl) != mLoopVarDecls.end())
81 mFoundSet.insert(varDecl);
82 return true;
85 loplugin::Plugin::Registration<UnusedIndex> X("unusedindex", false);
88 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */