11 #include "clang/AST/DeclBase.h"
12 #include "clang/AST/Type.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/ASTMatchers/ASTMatchers.h"
15 #include "clang/Lex/Lexer.h"
17 using namespace clang::ast_matchers;
25 const auto &literal = Node.getValue();
26 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEsingle)
27 return literal.convertToFloat() == 0.5f;
28 if ((&Node.getSemantics()) == &llvm::APFloat::IEEEdouble)
29 return literal.convertToDouble() == 0.5;
35 void IncorrectRoundings::registerMatchers(MatchFinder *MatchFinder) {
37 auto FloatHalf = floatLiteral(floatHalf());
40 auto FloatType = expr(hasType(realFloatingPointType()));
44 auto FloatOrCastHalf =
46 implicitCastExpr(FloatType, has(ignoringParenImpCasts(FloatHalf))));
50 auto OneSideHalf = anyOf(allOf(hasLHS(FloatOrCastHalf), hasRHS(FloatType)),
51 allOf(hasRHS(FloatOrCastHalf), hasLHS(FloatType)));
55 MatchFinder->addMatcher(
57 hasImplicitDestinationType(isInteger()),
58 ignoringParenCasts(binaryOperator(hasOperatorName(
"+"), OneSideHalf)))
63 void IncorrectRoundings::check(
const MatchFinder::MatchResult &
Result) {
64 const auto *CastExpr = Result.Nodes.getStmtAs<ImplicitCastExpr>(
"CastExpr");
65 diag(CastExpr->getLocStart(),
66 "casting (double + 0.5) to integer leads to incorrect rounding; "
67 "consider using lround (#include <cmath>) instead");
AST_MATCHER(Type, isStrictlyInteger)