clang-tools 22.0.0git
DurationComparisonCheck.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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
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
19 auto Matcher = expr(comparisonOperatorWithCallee(functionDecl(
20 functionDecl(DurationConversionFunction())
21 .bind("function_decl"))))
22 .bind("binop");
23
24 Finder->addMatcher(Matcher, this);
25}
26
27void DurationComparisonCheck::check(const MatchFinder::MatchResult &Result) {
28 const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
29
30 std::optional<DurationScale> Scale = getScaleForDurationInverse(
31 Result.Nodes.getNodeAs<FunctionDecl>("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, Binop->getLHS()) || isInMacro(Result, Binop->getRHS()))
40 return;
41 std::string LhsReplacement =
42 rewriteExprFromNumberToDuration(Result, *Scale, Binop->getLHS());
43 std::string RhsReplacement =
44 rewriteExprFromNumberToDuration(Result, *Scale, Binop->getRHS());
45
46 diag(Binop->getBeginLoc(), "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
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
std::optional< DurationScale > getScaleForDurationInverse(llvm::StringRef Name)
Given the name of an inverse Duration function (e.g., ToDoubleSeconds), return its DurationScale,...
bool isInMacro(const MatchFinder::MatchResult &Result, const Expr *E)
std::string rewriteExprFromNumberToDuration(const ast_matchers::MatchFinder::MatchResult &Result, DurationScale Scale, const Expr *Node)
Assuming Node has type double or int representing a time interval of Scale, return the expression to ...