blob: 82993cb313ce88ff0fa2f128480c948502e90f08 [file] [log] [blame]
Gabor Horvath0b16c102017-08-10 13:30:30 +00001//===--- IntegerDivisionCheck.cpp - clang-tidy-----------------------------===//
2//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// 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
Gabor Horvath0b16c102017-08-10 13:30:30 +00006//
7//===----------------------------------------------------------------------===//
8
9#include "IntegerDivisionCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang {
16namespace tidy {
17namespace bugprone {
18
19void IntegerDivisionCheck::registerMatchers(MatchFinder *Finder) {
20 const auto IntType = hasType(isInteger());
21
Nathan James97572fa2020-03-10 00:42:21 +000022 const auto BinaryOperators = binaryOperator(
23 hasAnyOperatorName("%", "<<", ">>", "<<", "^", "|", "&", "||", "&&", "<",
24 ">", "<=", ">=", "==", "!="));
Gabor Horvath0b16c102017-08-10 13:30:30 +000025
Nathan James97572fa2020-03-10 00:42:21 +000026 const auto UnaryOperators = unaryOperator(hasAnyOperatorName("~", "!"));
Gabor Horvath0b16c102017-08-10 13:30:30 +000027
28 const auto Exceptions =
29 anyOf(BinaryOperators, conditionalOperator(), binaryConditionalOperator(),
30 callExpr(IntType), explicitCastExpr(IntType), UnaryOperators);
31
32 Finder->addMatcher(
33 binaryOperator(
34 hasOperatorName("/"), hasLHS(expr(IntType)), hasRHS(expr(IntType)),
35 hasAncestor(
36 castExpr(hasCastKind(CK_IntegralToFloating)).bind("FloatCast")),
37 unless(hasAncestor(
38 expr(Exceptions,
39 hasAncestor(castExpr(equalsBoundNode("FloatCast")))))))
40 .bind("IntDiv"),
41 this);
42}
43
44void IntegerDivisionCheck::check(const MatchFinder::MatchResult &Result) {
45 const auto *IntDiv = Result.Nodes.getNodeAs<BinaryOperator>("IntDiv");
Stephen Kelly43465bf2018-08-09 22:42:26 +000046 diag(IntDiv->getBeginLoc(), "result of integer division used in a floating "
Gabor Horvath0b16c102017-08-10 13:30:30 +000047 "point context; possible loss of precision");
48}
49
50} // namespace bugprone
51} // namespace tidy
52} // namespace clang