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

source code of clang-tools-extra/clang-tidy/abseil/DurationComparisonCheck.cpp