55 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 "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(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 also36 // want to handle the case of rewriting both sides. This is much simpler if37 // we unconditionally try and rewrite both, and let the rewriter determine38 // if nothing needs to be done.39 if (isInMacro(Result, Binop->getLHS()) || isInMacro(Result, Binop->getRHS()))40 return;41 const std::string LhsReplacement =42 rewriteExprFromNumberToDuration(Result, *Scale, Binop->getLHS());43 const 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::abseil55