[docs] Add LICENSE.txt to the root of the mono-repo
[llvm-project.git] / clang-tools-extra / clang-tidy / abseil / DurationComparisonCheck.cpp
bloba6e12dd8966b851b06c019371d34f741e9d37d3c
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 //===----------------------------------------------------------------------===//
9 #include "DurationComparisonCheck.h"
10 #include "DurationRewriter.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Tooling/FixIt.h"
15 using namespace clang::ast_matchers;
17 namespace clang {
18 namespace tidy {
19 namespace abseil {
21 void DurationComparisonCheck::registerMatchers(MatchFinder *Finder) {
22 auto Matcher = expr(comparisonOperatorWithCallee(functionDecl(
23 functionDecl(DurationConversionFunction())
24 .bind("function_decl"))))
25 .bind("binop");
27 Finder->addMatcher(Matcher, this);
30 void DurationComparisonCheck::check(const MatchFinder::MatchResult &Result) {
31 const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
33 llvm::Optional<DurationScale> Scale = getScaleForDurationInverse(
34 Result.Nodes.getNodeAs<FunctionDecl>("function_decl")->getName());
35 if (!Scale)
36 return;
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 if (isInMacro(Result, Binop->getLHS()) || isInMacro(Result, Binop->getRHS()))
43 return;
44 std::string LhsReplacement =
45 rewriteExprFromNumberToDuration(Result, *Scale, Binop->getLHS());
46 std::string RhsReplacement =
47 rewriteExprFromNumberToDuration(Result, *Scale, Binop->getRHS());
49 diag(Binop->getBeginLoc(), "perform comparison in the duration domain")
50 << FixItHint::CreateReplacement(Binop->getSourceRange(),
51 (llvm::Twine(LhsReplacement) + " " +
52 Binop->getOpcodeStr() + " " +
53 RhsReplacement)
54 .str());
57 } // namespace abseil
58 } // namespace tidy
59 } // namespace clang