• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--- DurationComparisonCheck.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 
9 #include "DurationComparisonCheck.h"
10 #include "DurationRewriter.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Tooling/FixIt.h"
14 
15 using namespace clang::ast_matchers;
16 
17 namespace clang {
18 namespace tidy {
19 namespace abseil {
20 
registerMatchers(MatchFinder * Finder)21 void DurationComparisonCheck::registerMatchers(MatchFinder *Finder) {
22   auto Matcher = expr(comparisonOperatorWithCallee(functionDecl(
23                           functionDecl(DurationConversionFunction())
24                               .bind("function_decl"))))
25                      .bind("binop");
26 
27   Finder->addMatcher(Matcher, this);
28 }
29 
check(const MatchFinder::MatchResult & Result)30 void DurationComparisonCheck::check(const MatchFinder::MatchResult &Result) {
31   const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
32 
33   llvm::Optional<DurationScale> Scale = getScaleForDurationInverse(
34       Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
35   if (!Scale)
36     return;
37 
38   // In most cases, we'll only need to rewrite one of the sides, but we also
39   // want to handle the case of rewriting both sides. This is much simpler if
40   // we unconditionally try and rewrite both, and let the rewriter determine
41   // if nothing needs to be done.
42   if (isInMacro(Result, Binop->getLHS()) || isInMacro(Result, Binop->getRHS()))
43     return;
44   std::string LhsReplacement =
45       rewriteExprFromNumberToDuration(Result, *Scale, Binop->getLHS());
46   std::string RhsReplacement =
47       rewriteExprFromNumberToDuration(Result, *Scale, Binop->getRHS());
48 
49   diag(Binop->getBeginLoc(), "perform comparison in the duration domain")
50       << FixItHint::CreateReplacement(Binop->getSourceRange(),
51                                       (llvm::Twine(LhsReplacement) + " " +
52                                        Binop->getOpcodeStr() + " " +
53                                        RhsReplacement)
54                                           .str());
55 }
56 
57 } // namespace abseil
58 } // namespace tidy
59 } // namespace clang
60