11#include "clang/AST/ASTContext.h"
12#include "clang/ASTMatchers/ASTMatchFinder.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Lex/Lexer.h"
15#include "clang/Tooling/FixIt.h"
25 const SourceManager &SM = Finder->getASTContext().getSourceManager();
26 const SourceLocation Loc = Node.getBeginLoc();
27 return SM.isMacroBodyExpansion(Loc) || SM.isMacroArgExpansion(Loc);
30AST_MATCHER(Stmt, isC23) {
return Finder->getASTContext().getLangOpts().C23; }
34bool isNULLMacroExpansion(
const Stmt *Statement, ASTContext &Context) {
35 const SourceManager &SM = Context.getSourceManager();
36 const LangOptions &LO = Context.getLangOpts();
37 const SourceLocation Loc = Statement->getBeginLoc();
38 return SM.isMacroBodyExpansion(Loc) &&
39 Lexer::getImmediateMacroName(Loc, SM, LO) ==
"NULL";
43 return isNULLMacroExpansion(&Node, Finder->getASTContext());
50 ASTContext &Context) {
51 switch (CastExprKind) {
52 case CK_IntegralToBoolean:
53 return Type->isUnsignedIntegerType() ?
"0u" :
"0";
55 case CK_FloatingToBoolean:
56 return ASTContext::hasSameType(Type, Context.FloatTy) ?
"0.0f" :
"0.0";
58 case CK_PointerToBoolean:
59 case CK_MemberPointerToBoolean:
60 return (Context.getLangOpts().CPlusPlus11 || Context.getLangOpts().C23)
65 llvm_unreachable(
"Unexpected cast kind");
70 const auto *UnaryOperatorExpr = dyn_cast<UnaryOperator>(Statement);
71 return UnaryOperatorExpr && UnaryOperatorExpr->getOpcode() == UO_LNot;
75 const ImplicitCastExpr *Cast,
76 const Stmt *Parent, ASTContext &Context,
77 bool UseUpperCaseLiteralSuffix) {
80 const bool InvertComparison =
82 if (InvertComparison) {
83 const SourceLocation ParentStartLoc = Parent->getBeginLoc();
84 const SourceLocation ParentEndLoc =
85 cast<UnaryOperator>(Parent)->getSubExpr()->getBeginLoc();
86 Diag << FixItHint::CreateRemoval(
87 CharSourceRange::getCharRange(ParentStartLoc, ParentEndLoc));
89 Parent = Context.getParents(*Parent)[0].get<Stmt>();
92 const Expr *SubExpr = Cast->getSubExpr();
94 const bool NeedInnerParens =
96 const bool NeedOuterParens =
99 std::string StartLocInsertion;
101 if (NeedOuterParens) {
102 StartLocInsertion +=
"(";
104 if (NeedInnerParens) {
105 StartLocInsertion +=
"(";
108 if (!StartLocInsertion.empty()) {
109 Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(), StartLocInsertion);
112 std::string EndLocInsertion;
114 if (NeedInnerParens) {
115 EndLocInsertion +=
")";
118 if (InvertComparison) {
119 EndLocInsertion +=
" == ";
121 EndLocInsertion +=
" != ";
125 Cast->getCastKind(), SubExpr->getType(), Context);
127 if (UseUpperCaseLiteralSuffix)
128 EndLocInsertion += ZeroLiteral.upper();
130 EndLocInsertion += ZeroLiteral;
132 if (NeedOuterParens) {
133 EndLocInsertion +=
")";
136 const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
137 Cast->getEndLoc(), 0, Context.getSourceManager(), Context.getLangOpts());
138 Diag << FixItHint::CreateInsertion(EndLoc, EndLocInsertion);
142 ASTContext &Context) {
143 if (isNULLMacroExpansion(Expression, Context)) {
147 if (
const auto *IntLit =
148 dyn_cast<IntegerLiteral>(Expression->IgnoreParens())) {
149 return (IntLit->getValue() == 0) ?
"false" :
"true";
152 if (
const auto *FloatLit = dyn_cast<FloatingLiteral>(Expression)) {
153 llvm::APFloat FloatLitAbsValue = FloatLit->getValue();
154 FloatLitAbsValue.clearSign();
155 return (FloatLitAbsValue.bitcastToAPInt() == 0) ?
"false" :
"true";
158 if (
const auto *CharLit = dyn_cast<CharacterLiteral>(Expression)) {
159 return (CharLit->getValue() == 0) ?
"false" :
"true";
162 if (isa<StringLiteral>(Expression->IgnoreCasts())) {
170 const SourceRange PrefixRange(Loc.getLocWithOffset(-1), Loc);
171 const StringRef SpaceBeforeStmtStr = Lexer::getSourceText(
172 CharSourceRange::getCharRange(PrefixRange), Context.getSourceManager(),
173 Context.getLangOpts(),
nullptr);
174 if (SpaceBeforeStmtStr.empty())
177 const StringRef AllowedCharacters(
" \t\n\v\f\r(){}[]<>;,+=-|&~!^*/");
178 return !AllowedCharacters.contains(SpaceBeforeStmtStr.back());
182 const ImplicitCastExpr *Cast,
184 StringRef OtherType) {
185 if (!Context.getLangOpts().CPlusPlus) {
186 Diag << FixItHint::CreateInsertion(Cast->getBeginLoc(),
187 (Twine(
"(") + OtherType +
")").str());
191 const Expr *SubExpr = Cast->getSubExpr();
192 const bool NeedParens = !isa<ParenExpr>(SubExpr->IgnoreImplicit());
195 Diag << FixItHint::CreateInsertion(
196 Cast->getBeginLoc(), (Twine() + (NeedSpace ?
" " :
"") +
"static_cast<" +
197 OtherType +
">" + (NeedParens ?
"(" :
""))
201 const SourceLocation EndLoc = Lexer::getLocForEndOfToken(
202 Cast->getEndLoc(), 0, Context.getSourceManager(),
203 Context.getLangOpts());
205 Diag << FixItHint::CreateInsertion(EndLoc,
")");
211 QualType DestType, ASTContext &Context) {
213 if (!Context.getLangOpts().CPlusPlus11 &&
214 (DestType->isPointerType() || DestType->isMemberPointerType()) &&
215 BoolLiteral->getValue() ==
false) {
219 if (DestType->isFloatingType()) {
220 if (ASTContext::hasSameType(DestType, Context.FloatTy)) {
221 return BoolLiteral->getValue() ?
"1.0f" :
"0.0f";
223 return BoolLiteral->getValue() ?
"1.0" :
"0.0";
226 if (DestType->isUnsignedIntegerType()) {
227 return BoolLiteral->getValue() ?
"1u" :
"0u";
229 return BoolLiteral->getValue() ?
"1" :
"0";
233 ASTContext &Context) {
234 std::queue<const Stmt *> Q;
237 const TraversalKindScope RAII(Context, TK_AsIs);
240 for (
const auto &N : Context.getParents(*Q.front())) {
241 const Stmt *S = N.get<Stmt>();
244 if (isa<IfStmt>(S) || isa<ConditionalOperator>(S) || isa<ForStmt>(S) ||
245 isa<WhileStmt>(S) || isa<DoStmt>(S) ||
246 isa<BinaryConditionalOperator>(S))
248 if (isa<ParenExpr>(S) || isa<ImplicitCastExpr>(S) ||
250 (isa<BinaryOperator>(S) && cast<BinaryOperator>(S)->isLogicalOp())) {
264 AllowIntegerConditions(Options.get(
"AllowIntegerConditions", false)),
265 AllowPointerConditions(Options.get(
"AllowPointerConditions", false)),
266 UseUpperCaseLiteralSuffix(
267 Options.get(
"UseUpperCaseLiteralSuffix", false)) {}
271 Options.store(Opts,
"AllowIntegerConditions", AllowIntegerConditions);
272 Options.store(Opts,
"AllowPointerConditions", AllowPointerConditions);
273 Options.store(Opts,
"UseUpperCaseLiteralSuffix", UseUpperCaseLiteralSuffix);
277 auto ExceptionCases =
278 expr(anyOf(allOf(isMacroExpansion(), unless(isNULLMacroExpansion())),
279 has(ignoringImplicit(
280 memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1)))))),
281 hasParent(explicitCastExpr()),
282 expr(hasType(qualType().bind(
"type")),
283 hasParent(initListExpr(hasParent(explicitCastExpr(
284 hasType(qualType(equalsBoundNode(
"type"))))))))));
285 auto ImplicitCastFromBool = implicitCastExpr(
286 anyOf(hasCastKind(CK_IntegralCast), hasCastKind(CK_IntegralToFloating),
288 allOf(anyOf(hasCastKind(CK_NullToPointer),
289 hasCastKind(CK_NullToMemberPointer)),
290 hasSourceExpression(cxxBoolLiteral()))),
291 hasSourceExpression(expr(hasType(booleanType()))));
293 binaryOperator(hasOperatorName(
"^"), hasLHS(ImplicitCastFromBool),
294 hasRHS(ImplicitCastFromBool));
295 auto ComparisonInCall = allOf(
296 hasParent(callExpr()),
297 hasSourceExpression(binaryOperator(hasAnyOperatorName(
"==",
"!="))));
299 auto IsInCompilerGeneratedFunction = hasAncestor(namedDecl(anyOf(
300 isImplicit(), functionDecl(isDefaulted()), functionTemplateDecl())));
305 anyOf(hasCastKind(CK_IntegralToBoolean),
306 hasCastKind(CK_FloatingToBoolean),
307 hasCastKind(CK_PointerToBoolean),
308 hasCastKind(CK_MemberPointerToBoolean)),
310 unless(allOf(isC23(),
311 hasSourceExpression(ignoringParens(
312 binaryOperator(hasAnyOperatorName(
313 ">",
">=",
"==",
"!=",
"<",
"<=")))))),
318 stmt(anyOf(ifStmt(), whileStmt()), has(declStmt())))),
320 unless(ExceptionCases), unless(has(BoolXor)),
322 unless(ComparisonInCall),
325 optionally(hasParent(stmt().bind(
"parentStmt"))),
326 unless(isInTemplateInstantiation()),
327 unless(IsInCompilerGeneratedFunction))
328 .bind(
"implicitCastToBool")),
331 auto BoolComparison = binaryOperator(hasAnyOperatorName(
"==",
"!="),
332 hasLHS(ImplicitCastFromBool),
333 hasRHS(ImplicitCastFromBool));
334 auto BoolOpAssignment = binaryOperator(hasAnyOperatorName(
"|=",
"&="),
335 hasLHS(expr(hasType(booleanType()))));
336 auto BitfieldAssignment = binaryOperator(
337 hasLHS(memberExpr(hasDeclaration(fieldDecl(hasBitWidth(1))))));
338 auto BitfieldConstruct = cxxConstructorDecl(hasDescendant(cxxCtorInitializer(
339 withInitializer(equalsBoundNode(
"implicitCastFromBool")),
340 forField(hasBitWidth(1)))));
345 ImplicitCastFromBool, unless(ExceptionCases),
351 binaryOperator(anyOf(BoolComparison, BoolXor,
352 BoolOpAssignment, BitfieldAssignment)))),
353 implicitCastExpr().bind(
"implicitCastFromBool"),
354 unless(hasParent(BitfieldConstruct)),
357 hasParent(implicitCastExpr().bind(
"furtherImplicitCast"))),
358 unless(isInTemplateInstantiation()),
359 unless(IsInCompilerGeneratedFunction))),
364 const MatchFinder::MatchResult &Result) {
366 if (
const auto *CastToBool =
367 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"implicitCastToBool")) {
368 const auto *Parent = Result.Nodes.getNodeAs<Stmt>(
"parentStmt");
369 handleCastToBool(CastToBool, Parent, *Result.Context);
373 if (
const auto *CastFromBool =
374 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"implicitCastFromBool")) {
375 const auto *NextImplicitCast =
376 Result.Nodes.getNodeAs<ImplicitCastExpr>(
"furtherImplicitCast");
377 handleCastFromBool(CastFromBool, NextImplicitCast, *Result.Context);
381void ImplicitBoolConversionCheck::handleCastToBool(
const ImplicitCastExpr *Cast,
383 ASTContext &Context) {
384 if (AllowPointerConditions &&
385 (Cast->getCastKind() == CK_PointerToBoolean ||
386 Cast->getCastKind() == CK_MemberPointerToBoolean) &&
391 if (AllowIntegerConditions && Cast->getCastKind() == CK_IntegralToBoolean &&
396 auto Diag = diag(Cast->getBeginLoc(),
"implicit conversion %0 -> 'bool'")
397 << Cast->getSubExpr()->getType();
399 const StringRef EquivalentLiteral =
401 if (!EquivalentLiteral.empty()) {
402 Diag << tooling::fixit::createReplacement(*Cast, EquivalentLiteral);
405 UseUpperCaseLiteralSuffix);
409void ImplicitBoolConversionCheck::handleCastFromBool(
410 const ImplicitCastExpr *Cast,
const ImplicitCastExpr *NextImplicitCast,
411 ASTContext &Context) {
412 const QualType DestType =
413 NextImplicitCast ? NextImplicitCast->getType() : Cast->getType();
414 auto Diag = diag(Cast->getBeginLoc(),
"implicit conversion 'bool' -> %0")
417 if (
const auto *BoolLiteral =
418 dyn_cast<CXXBoolLiteralExpr>(Cast->getSubExpr()->IgnoreParens())) {
420 const auto EquivalentForBoolLiteral =
422 if (UseUpperCaseLiteralSuffix)
423 Diag << tooling::fixit::createReplacement(
424 *Cast, EquivalentForBoolLiteral.upper());
426 Diag << tooling::fixit::createReplacement(*Cast,
427 EquivalentForBoolLiteral);
Every ClangTidyCheck reports errors through a DiagnosticsEngine provided by this context.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void storeOptions(ClangTidyOptions::OptionMap &Opts) override
ImplicitBoolConversionCheck(StringRef Name, ClangTidyContext *Context)
void registerMatchers(ast_matchers::MatchFinder *Finder) override
AST_MATCHER(BinaryOperator, isRelationalOperator)
static bool isCastAllowedInCondition(const ImplicitCastExpr *Cast, ASTContext &Context)
static bool isUnaryLogicalNotOperator(const Stmt *Statement)
static void fixGenericExprCastToBool(DiagnosticBuilder &Diag, const ImplicitCastExpr *Cast, const Stmt *Parent, ASTContext &Context, bool UseUpperCaseLiteralSuffix)
static StringRef getZeroLiteralToCompareWithForType(CastKind CastExprKind, QualType Type, ASTContext &Context)
static void fixGenericExprCastFromBool(DiagnosticBuilder &Diag, const ImplicitCastExpr *Cast, ASTContext &Context, StringRef OtherType)
static StringRef getEquivalentBoolLiteralForExpr(const Expr *Expression, ASTContext &Context)
static bool needsSpacePrefix(SourceLocation Loc, ASTContext &Context)
static StringRef getEquivalentForBoolLiteral(const CXXBoolLiteralExpr *BoolLiteral, QualType DestType, ASTContext &Context)
bool areParensNeededForStatement(const Stmt &Node)
llvm::StringMap< ClangTidyValue > OptionMap