1 //===--- UseBoolLiteralsCheck.cpp - clang-tidy-----------------------------===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "UseBoolLiteralsCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Lex/Lexer.h"
14 using namespace clang::ast_matchers
;
16 namespace clang::tidy::modernize
{
18 UseBoolLiteralsCheck::UseBoolLiteralsCheck(StringRef Name
,
19 ClangTidyContext
*Context
)
20 : ClangTidyCheck(Name
, Context
),
21 IgnoreMacros(Options
.getLocalOrGlobal("IgnoreMacros", true)) {}
23 void UseBoolLiteralsCheck::storeOptions(ClangTidyOptions::OptionMap
&Opts
) {
24 Options
.store(Opts
, "IgnoreMacros", IgnoreMacros
);
27 void UseBoolLiteralsCheck::registerMatchers(MatchFinder
*Finder
) {
32 has(ignoringParenImpCasts(integerLiteral().bind("literal"))),
33 hasImplicitDestinationType(qualType(booleanType())),
34 unless(isInTemplateInstantiation()),
35 anyOf(hasParent(explicitCastExpr().bind("cast")), anything()))),
41 hasParent(implicitCastExpr(
42 hasImplicitDestinationType(qualType(booleanType())),
43 unless(isInTemplateInstantiation()))),
44 eachOf(hasTrueExpression(ignoringParenImpCasts(
45 integerLiteral().bind("literal"))),
46 hasFalseExpression(ignoringParenImpCasts(
47 integerLiteral().bind("literal")))))),
51 void UseBoolLiteralsCheck::check(const MatchFinder::MatchResult
&Result
) {
52 const auto *Literal
= Result
.Nodes
.getNodeAs
<IntegerLiteral
>("literal");
53 const auto *Cast
= Result
.Nodes
.getNodeAs
<Expr
>("cast");
54 bool LiteralBooleanValue
= Literal
->getValue().getBoolValue();
56 if (Literal
->isInstantiationDependent())
59 const Expr
*Expression
= Cast
? Cast
: Literal
;
61 bool InMacro
= Expression
->getBeginLoc().isMacroID();
63 if (InMacro
&& IgnoreMacros
)
67 diag(Expression
->getExprLoc(),
68 "converting integer literal to bool, use bool literal instead");
71 Diag
<< FixItHint::CreateReplacement(
72 Expression
->getSourceRange(), LiteralBooleanValue
? "true" : "false");
75 } // namespace clang::tidy::modernize