1 //===--- DurationFactoryFloatCheck.cpp - clang-tidy -----------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "DurationFactoryFloatCheck.h"
10 #include "DurationRewriter.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Lex/Lexer.h"
14 #include "clang/Tooling/FixIt.h"
17 using namespace clang::ast_matchers
;
19 namespace clang::tidy::abseil
{
21 // Returns `true` if `Range` is inside a macro definition.
22 static bool insideMacroDefinition(const MatchFinder::MatchResult
&Result
,
24 return !clang::Lexer::makeFileCharRange(
25 clang::CharSourceRange::getCharRange(Range
),
26 *Result
.SourceManager
, Result
.Context
->getLangOpts())
30 void DurationFactoryFloatCheck::registerMatchers(MatchFinder
*Finder
) {
32 callExpr(callee(functionDecl(DurationFactoryFunction())),
33 hasArgument(0, anyOf(cxxStaticCastExpr(hasDestinationType(
34 realFloatingPointType())),
35 cStyleCastExpr(hasDestinationType(
36 realFloatingPointType())),
37 cxxFunctionalCastExpr(hasDestinationType(
38 realFloatingPointType())),
44 void DurationFactoryFloatCheck::check(const MatchFinder::MatchResult
&Result
) {
45 const auto *MatchedCall
= Result
.Nodes
.getNodeAs
<CallExpr
>("call");
47 // Don't try and replace things inside of macro definitions.
48 if (insideMacroDefinition(Result
, MatchedCall
->getSourceRange()))
51 const Expr
*Arg
= MatchedCall
->getArg(0)->IgnoreImpCasts();
52 // Arguments which are macros are ignored.
53 if (Arg
->getBeginLoc().isMacroID())
56 std::optional
<std::string
> SimpleArg
= stripFloatCast(Result
, *Arg
);
58 SimpleArg
= stripFloatLiteralFraction(Result
, *Arg
);
61 diag(MatchedCall
->getBeginLoc(), "use the integer version of absl::%0")
62 << MatchedCall
->getDirectCallee()->getName()
63 << FixItHint::CreateReplacement(Arg
->getSourceRange(), *SimpleArg
);
67 } // namespace clang::tidy::abseil