1 //===--- UseBoolLiteralsCheck.cpp - clang-tidy-----------------------------===//
2 //
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
6 //
7 //===----------------------------------------------------------------------===//
8
9 #include "UseBoolLiteralsCheck.h"
10 #include "clang/AST/ASTContext.h"
11 #include "clang/ASTMatchers/ASTMatchFinder.h"
12 #include "clang/Lex/Lexer.h"
13
14 using namespace clang::ast_matchers;
15
16 namespace clang::tidy::modernize {
17
UseBoolLiteralsCheck(StringRef Name,ClangTidyContext * Context)18 UseBoolLiteralsCheck::UseBoolLiteralsCheck(StringRef Name,
19 ClangTidyContext *Context)
20 : ClangTidyCheck(Name, Context),
21 IgnoreMacros(Options.getLocalOrGlobal("IgnoreMacros", true)) {}
22
storeOptions(ClangTidyOptions::OptionMap & Opts)23 void UseBoolLiteralsCheck::storeOptions(ClangTidyOptions::OptionMap &Opts) {
24 Options.store(Opts, "IgnoreMacros", IgnoreMacros);
25 }
26
registerMatchers(MatchFinder * Finder)27 void UseBoolLiteralsCheck::registerMatchers(MatchFinder *Finder) {
28 Finder->addMatcher(
29 traverse(
30 TK_AsIs,
31 implicitCastExpr(
32 has(ignoringParenImpCasts(integerLiteral().bind("literal"))),
33 hasImplicitDestinationType(qualType(booleanType())),
34 unless(isInTemplateInstantiation()),
35 anyOf(hasParent(explicitCastExpr().bind("cast")), anything()))),
36 this);
37
38 Finder->addMatcher(
39 traverse(TK_AsIs,
40 conditionalOperator(
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")))))),
48 this);
49 }
50
check(const MatchFinder::MatchResult & Result)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();
55
56 if (Literal->isInstantiationDependent())
57 return;
58
59 const Expr *Expression = Cast ? Cast : Literal;
60
61 bool InMacro = Expression->getBeginLoc().isMacroID();
62
63 if (InMacro && IgnoreMacros)
64 return;
65
66 auto Diag =
67 diag(Expression->getExprLoc(),
68 "converting integer literal to bool, use bool literal instead");
69
70 if (!InMacro)
71 Diag << FixItHint::CreateReplacement(
72 Expression->getSourceRange(), LiteralBooleanValue ? "true" : "false");
73 }
74
75 } // namespace clang::tidy::modernize
76