cid#1555694 COPY_INSTEAD_OF_MOVE
[LibreOffice.git] / compilerplugins / clang / emptyif.cxx
blob5412188f8d523c14f96e6bdaeafcbb8217993382
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
8 */
10 #ifndef LO_CLANG_SHARED_PLUGINS
12 #include <cassert>
13 #include <string>
14 #include <iostream>
15 #include <fstream>
16 #include <set>
17 #include "plugin.hxx"
19 /**
20 Check for places where we do
21 if (xxx) ;
23 if (xxx) {}
25 namespace
27 class EmptyIf : public loplugin::FilteringRewritePlugin<EmptyIf>
29 public:
30 explicit EmptyIf(loplugin::InstantiationData const& data)
31 : FilteringRewritePlugin(data)
35 virtual void run() override { TraverseDecl(compiler.getASTContext().getTranslationUnitDecl()); }
37 bool VisitIfStmt(IfStmt const*);
39 private:
40 bool ContainsComment(Stmt const*);
43 static bool empty(Stmt const* stmt)
45 if (isa<NullStmt>(stmt))
46 return true;
47 auto compoundStmt = dyn_cast<CompoundStmt>(stmt);
48 if (!compoundStmt)
49 return false;
50 return compoundStmt->size() == 0;
53 bool EmptyIf::ContainsComment(Stmt const* stmt)
55 auto range = stmt->getSourceRange();
56 SourceManager& SM = compiler.getSourceManager();
57 SourceLocation startLoc = range.getBegin();
58 SourceLocation endLoc = range.getEnd();
59 char const* p1 = SM.getCharacterData(startLoc);
60 char const* p2 = SM.getCharacterData(endLoc);
61 p2 += Lexer::MeasureTokenLength(endLoc, SM, compiler.getLangOpts());
62 auto s = llvm::StringRef(p1, p2 - p1);
63 return s.find("//") != llvm::StringRef::npos || s.find("/*") != llvm::StringRef::npos
64 || s.find("#if") != llvm::StringRef::npos;
67 bool EmptyIf::VisitIfStmt(IfStmt const* ifStmt)
69 if (ignoreLocation(ifStmt))
70 return true;
72 if (ifStmt->getElse() && empty(ifStmt->getElse()) && !ContainsComment(ifStmt->getElse()))
74 report(DiagnosticsEngine::Warning, "empty else body", ifStmt->getElse()->getBeginLoc())
75 << ifStmt->getElse()->getSourceRange();
76 return true;
79 if (!ifStmt->getElse() && empty(ifStmt->getThen()) && !ContainsComment(ifStmt->getThen()))
81 report(DiagnosticsEngine::Warning, "empty if body", ifStmt->getBeginLoc())
82 << ifStmt->getSourceRange();
85 return true;
88 loplugin::Plugin::Registration<EmptyIf> emptyif("emptyif", true);
91 #endif // LO_CLANG_SHARED_PLUGINS
93 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */