[InstCombine] Drop range attributes in `foldBitCeil` (#116641)
[llvm-project.git] / clang-tools-extra / clang-tidy / modernize / UseBoolLiteralsCheck.cpp
blobc8e6bf47bb82fa66b7100baa5a02c0dbab25c105
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 //===----------------------------------------------------------------------===//
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) {
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);
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);
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())
57 return;
59 const Expr *Expression = Cast ? Cast : Literal;
61 bool InMacro = Expression->getBeginLoc().isMacroID();
63 if (InMacro && IgnoreMacros)
64 return;
66 auto Diag =
67 diag(Expression->getExprLoc(),
68 "converting integer literal to bool, use bool literal instead");
70 if (!InMacro)
71 Diag << FixItHint::CreateReplacement(
72 Expression->getSourceRange(), LiteralBooleanValue ? "true" : "false");
75 } // namespace clang::tidy::modernize