DurationAdditionCheck.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //===--- DurationAdditionCheck.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 "DurationAdditionCheck.h"
  9. #include "DurationRewriter.h"
  10. #include "clang/AST/ASTContext.h"
  11. #include "clang/ASTMatchers/ASTMatchFinder.h"
  12. #include "clang/Tooling/FixIt.h"
  13. #include <optional>
  14. using namespace clang::ast_matchers;
  15. namespace clang::tidy::abseil {
  16. void DurationAdditionCheck::registerMatchers(MatchFinder *Finder) {
  17. Finder->addMatcher(
  18. binaryOperator(hasOperatorName("+"),
  19. hasEitherOperand(expr(ignoringParenImpCasts(
  20. callExpr(callee(functionDecl(TimeConversionFunction())
  21. .bind("function_decl")))
  22. .bind("call")))))
  23. .bind("binop"),
  24. this);
  25. }
  26. void DurationAdditionCheck::check(const MatchFinder::MatchResult &Result) {
  27. const BinaryOperator *Binop =
  28. Result.Nodes.getNodeAs<clang::BinaryOperator>("binop");
  29. const CallExpr *Call = Result.Nodes.getNodeAs<clang::CallExpr>("call");
  30. // Don't try to replace things inside of macro definitions.
  31. if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
  32. return;
  33. std::optional<DurationScale> Scale = getScaleForTimeInverse(
  34. Result.Nodes.getNodeAs<clang::FunctionDecl>("function_decl")->getName());
  35. if (!Scale)
  36. return;
  37. llvm::StringRef TimeFactory = getTimeInverseForScale(*Scale);
  38. FixItHint Hint;
  39. if (Call == Binop->getLHS()->IgnoreParenImpCasts()) {
  40. Hint = FixItHint::CreateReplacement(
  41. Binop->getSourceRange(),
  42. (llvm::Twine(TimeFactory) + "(" +
  43. tooling::fixit::getText(*Call->getArg(0), *Result.Context) + " + " +
  44. rewriteExprFromNumberToDuration(Result, *Scale, Binop->getRHS()) + ")")
  45. .str());
  46. } else {
  47. assert(Call == Binop->getRHS()->IgnoreParenImpCasts() &&
  48. "Call should be found on the RHS");
  49. Hint = FixItHint::CreateReplacement(
  50. Binop->getSourceRange(),
  51. (llvm::Twine(TimeFactory) + "(" +
  52. rewriteExprFromNumberToDuration(Result, *Scale, Binop->getLHS()) +
  53. " + " + tooling::fixit::getText(*Call->getArg(0), *Result.Context) +
  54. ")")
  55. .str());
  56. }
  57. diag(Binop->getBeginLoc(), "perform addition in the duration domain") << Hint;
  58. }
  59. } // namespace clang::tidy::abseil