1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
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/.
10 #ifndef LO_CLANG_SHARED_PLUGINS
20 Check for places where we do
27 class EmptyIf
: public loplugin::FilteringRewritePlugin
<EmptyIf
>
30 explicit EmptyIf(loplugin::InstantiationData
const& data
)
31 : FilteringRewritePlugin(data
)
35 virtual void run() override
{ TraverseDecl(compiler
.getASTContext().getTranslationUnitDecl()); }
37 bool VisitIfStmt(IfStmt
const*);
40 bool ContainsComment(Stmt
const*);
43 static bool empty(Stmt
const* stmt
)
45 if (isa
<NullStmt
>(stmt
))
47 auto compoundStmt
= dyn_cast
<CompoundStmt
>(stmt
);
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
))
72 if (ifStmt
->getElse() && empty(ifStmt
->getElse()) && !ContainsComment(ifStmt
->getElse()))
74 report(DiagnosticsEngine::Warning
, "empty else body",
75 compat::getBeginLoc(ifStmt
->getElse()))
76 << ifStmt
->getElse()->getSourceRange();
80 if (!ifStmt
->getElse() && empty(ifStmt
->getThen()) && !ContainsComment(ifStmt
->getThen()))
82 report(DiagnosticsEngine::Warning
, "empty if body", compat::getBeginLoc(ifStmt
))
83 << ifStmt
->getSourceRange();
89 loplugin::Plugin::Registration
<EmptyIf
> emptyif("emptyif", true);
92 #endif // LO_CLANG_SHARED_PLUGINS
94 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */