DurationDivisionCheck.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. //===--- DurationDivisionCheck.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 "DurationDivisionCheck.h"
  9. #include "clang/AST/ASTContext.h"
  10. #include "clang/ASTMatchers/ASTMatchFinder.h"
  11. #include "clang/Lex/Lexer.h"
  12. namespace clang::tidy::abseil {
  13. using namespace clang::ast_matchers;
  14. void DurationDivisionCheck::registerMatchers(MatchFinder *Finder) {
  15. const auto DurationExpr =
  16. expr(hasType(cxxRecordDecl(hasName("::absl::Duration"))));
  17. Finder->addMatcher(
  18. traverse(TK_AsIs,
  19. implicitCastExpr(
  20. hasSourceExpression(ignoringParenCasts(
  21. cxxOperatorCallExpr(hasOverloadedOperatorName("/"),
  22. hasArgument(0, DurationExpr),
  23. hasArgument(1, DurationExpr))
  24. .bind("OpCall"))),
  25. hasImplicitDestinationType(qualType(unless(isInteger()))),
  26. unless(hasParent(cxxStaticCastExpr())),
  27. unless(hasParent(cStyleCastExpr())),
  28. unless(isInTemplateInstantiation()))),
  29. this);
  30. }
  31. void DurationDivisionCheck::check(const MatchFinder::MatchResult &Result) {
  32. const auto *OpCall = Result.Nodes.getNodeAs<CXXOperatorCallExpr>("OpCall");
  33. diag(OpCall->getOperatorLoc(),
  34. "operator/ on absl::Duration objects performs integer division; "
  35. "did you mean to use FDivDuration()?")
  36. << FixItHint::CreateInsertion(OpCall->getBeginLoc(),
  37. "absl::FDivDuration(")
  38. << FixItHint::CreateReplacement(
  39. SourceRange(OpCall->getOperatorLoc(), OpCall->getOperatorLoc()),
  40. ", ")
  41. << FixItHint::CreateInsertion(
  42. Lexer::getLocForEndOfToken(
  43. Result.SourceManager->getSpellingLoc(OpCall->getEndLoc()), 0,
  44. *Result.SourceManager, Result.Context->getLangOpts()),
  45. ")");
  46. }
  47. } // namespace clang::tidy::abseil