1//===--- IntegerDivisionCheck.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 "IntegerDivisionCheck.h"
10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12
13using namespace clang::ast_matchers;
14
15namespace clang::tidy::bugprone {
16
17void IntegerDivisionCheck::registerMatchers(MatchFinder *Finder) {
18 const auto IntType = hasType(InnerMatcher: isInteger());
19
20 const auto BinaryOperators = binaryOperator(
21 hasAnyOperatorName("%", "<<", ">>", "<<", "^", "|", "&", "||", "&&", "<",
22 ">", "<=", ">=", "==", "!="));
23
24 const auto UnaryOperators = unaryOperator(hasAnyOperatorName("~", "!"));
25
26 const auto Exceptions =
27 anyOf(BinaryOperators, conditionalOperator(), binaryConditionalOperator(),
28 callExpr(IntType), explicitCastExpr(IntType), UnaryOperators);
29
30 Finder->addMatcher(
31 NodeMatch: traverse(TK: TK_AsIs,
32 InnerMatcher: binaryOperator(
33 hasOperatorName(Name: "/"), hasLHS(InnerMatcher: expr(IntType)),
34 hasRHS(InnerMatcher: expr(IntType)),
35 hasAncestor(castExpr(hasCastKind(Kind: CK_IntegralToFloating))
36 .bind(ID: "FloatCast")),
37 unless(hasAncestor(expr(
38 Exceptions,
39 hasAncestor(castExpr(equalsBoundNode(ID: "FloatCast")))))))
40 .bind(ID: "IntDiv")),
41 Action: this);
42}
43
44void IntegerDivisionCheck::check(const MatchFinder::MatchResult &Result) {
45 const auto *IntDiv = Result.Nodes.getNodeAs<BinaryOperator>(ID: "IntDiv");
46 diag(Loc: IntDiv->getBeginLoc(), Description: "result of integer division used in a floating "
47 "point context; possible loss of precision");
48}
49
50} // namespace clang::tidy::bugprone
51

source code of clang-tools-extra/clang-tidy/bugprone/IntegerDivisionCheck.cpp