Debian Codegraph @

llvm-project/clang-tools-extra/clang-tidy/abseil/DurationAdditionCheck.cpp

raw
1 //===--- DurationAdditionCheck.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 //===----------------------------------------------------------------------===//
8
9 #include "DurationAdditionCheck.h"
10 #include "DurationRewriter.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
13 #include "clang/Tooling/FixIt.h"
14 #include <optional>
15
16 using namespace clang::ast_matchers;
17
18 namespace clang::tidy::abseil {
19
20 void DurationAdditionCheck::registerMatchers(MatchFinder *Finder) {
21 Finder->addMatcher(
22 binaryOperator(hasOperatorName("+"),
23 hasEitherOperand(expr(ignoringParenImpCasts(
24 callExpr(callee(functionDecl(TimeConversionFunction())
25 .bind("function_decl")))
26 .bind("call")))))
27 .bind("binop"),
28 this);
29 }
30
31 void DurationAdditionCheck::check(const MatchFinder::MatchResult &Result) {
32 const BinaryOperator *Binop =
33 Result.Nodes.getNodeAs<clang::BinaryOperator>("binop");
34 const CallExpr *Call = Result.Nodes.getNodeAs<clang::CallExpr>("call");
35
36 // Don't try to replace things inside of macro definitions.
37 if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
38 return;
39
40 std::optional<DurationScale> Scale = getScaleForTimeInverse(
41 Result.Nodes.getNodeAs<clang::FunctionDecl>("function_decl")->getName());
42 if (!Scale)
43 return;
44
45 llvm::StringRef TimeFactory = getTimeInverseForScale(*Scale);
46
47 FixItHint Hint;
48 if (Call == Binop->getLHS()->IgnoreParenImpCasts()) {
49 Hint = FixItHint::CreateReplacement(
50 Binop->getSourceRange(),
51 (llvm::Twine(TimeFactory) + "(" +
52 tooling::fixit::getText(*Call->getArg(0), *Result.Context) + " + " +
53 rewriteExprFromNumberToDuration(Result, *Scale, Binop->getRHS()) + ")")
54 .str());
55 } else {
56 assert(Call == Binop->getRHS()->IgnoreParenImpCasts() &&
57 "Call should be found on the RHS");
58 Hint = FixItHint::CreateReplacement(
59 Binop->getSourceRange(),
60 (llvm::Twine(TimeFactory) + "(" +
61 rewriteExprFromNumberToDuration(Result, *Scale, Binop->getLHS()) +
62 " + " + tooling::fixit::getText(*Call->getArg(0), *Result.Context) +
63 ")")
64 .str());
65 }
66
67 diag(Binop->getBeginLoc(), "perform addition in the duration domain") << Hint;
68 }
69
70 } // namespace clang::tidy::abseil