clang-tools 22.0.0git
TimeComparisonCheck.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
18void TimeComparisonCheck::registerMatchers(MatchFinder *Finder) {
19 auto Matcher =
20 expr(comparisonOperatorWithCallee(functionDecl(
21 functionDecl(TimeConversionFunction()).bind("function_decl"))))
22 .bind("binop");
23
24 Finder->addMatcher(Matcher, this);
25}
26
27void TimeComparisonCheck::check(const MatchFinder::MatchResult &Result) {
28 const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
29
30 std::optional<DurationScale> Scale = getScaleForTimeInverse(
31 Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
32 if (!Scale)
33 return;
34
35 if (isInMacro(Result, Binop->getLHS()) || isInMacro(Result, Binop->getRHS()))
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 std::string LhsReplacement =
43 rewriteExprFromNumberToTime(Result, *Scale, Binop->getLHS());
44 std::string RhsReplacement =
45 rewriteExprFromNumberToTime(Result, *Scale, Binop->getRHS());
46
47 diag(Binop->getBeginLoc(), "perform comparison in the time domain")
48 << FixItHint::CreateReplacement(Binop->getSourceRange(),
49 (llvm::Twine(LhsReplacement) + " " +
50 Binop->getOpcodeStr() + " " +
51 RhsReplacement)
52 .str());
53}
54
55} // namespace clang::tidy::abseil
void registerMatchers(ast_matchers::MatchFinder *Finder) override
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
std::optional< DurationScale > getScaleForTimeInverse(llvm::StringRef Name)
Given the name of an inverse Time function (e.g., ToUnixSeconds), return its DurationScale,...
std::string rewriteExprFromNumberToTime(const ast_matchers::MatchFinder::MatchResult &Result, DurationScale Scale, const Expr *Node)
Assuming Node has a type int representing a time instant of Scale since The Epoch,...
bool isInMacro(const MatchFinder::MatchResult &Result, const Expr *E)