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