56 lines · cpp
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-exception6//7//===----------------------------------------------------------------------===//8 9#include "TimeComparisonCheck.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 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 also39 // want to handle the case of rewriting both sides. This is much simpler if40 // we unconditionally try and rewrite both, and let the rewriter determine41 // if nothing needs to be done.42 const std::string LhsReplacement =43 rewriteExprFromNumberToTime(Result, *Scale, Binop->getLHS());44 const 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::abseil56