DurationFactoryFloatCheck.cpp 2.5 KB

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