clang-tools  8.0.0
DurationSubtractionCheck.cpp
Go to the documentation of this file.
1 //===--- DurationSubtractionCheck.cpp - clang-tidy ------------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
11 #include "DurationRewriter.h"
12 #include "clang/AST/ASTContext.h"
13 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 #include "clang/Tooling/FixIt.h"
15 
16 using namespace clang::ast_matchers;
17 
18 namespace clang {
19 namespace tidy {
20 namespace abseil {
21 
22 void DurationSubtractionCheck::registerMatchers(MatchFinder *Finder) {
23  Finder->addMatcher(
24  binaryOperator(
25  hasOperatorName("-"),
26  hasLHS(callExpr(callee(functionDecl(DurationConversionFunction())
27  .bind("function_decl")),
28  hasArgument(0, expr().bind("lhs_arg")))))
29  .bind("binop"),
30  this);
31 }
32 
33 void DurationSubtractionCheck::check(const MatchFinder::MatchResult &Result) {
34  const auto *Binop = Result.Nodes.getNodeAs<BinaryOperator>("binop");
35  const auto *FuncDecl = Result.Nodes.getNodeAs<FunctionDecl>("function_decl");
36 
37  // Don't try to replace things inside of macro definitions.
38  if (Binop->getExprLoc().isMacroID() || Binop->getExprLoc().isInvalid())
39  return;
40 
41  llvm::Optional<DurationScale> Scale = getScaleForInverse(FuncDecl->getName());
42  if (!Scale)
43  return;
44 
45  std::string RhsReplacement =
46  rewriteExprFromNumberToDuration(Result, *Scale, Binop->getRHS());
47 
48  const Expr *LhsArg = Result.Nodes.getNodeAs<Expr>("lhs_arg");
49 
50  diag(Binop->getBeginLoc(), "perform subtraction in the duration domain")
51  << FixItHint::CreateReplacement(
52  Binop->getSourceRange(),
53  (llvm::Twine("absl::") + FuncDecl->getName() + "(" +
54  tooling::fixit::getText(*LhsArg, *Result.Context) + " - " +
55  RhsReplacement + ")")
56  .str());
57 }
58 
59 } // namespace abseil
60 } // namespace tidy
61 } // namespace clang
std::string rewriteExprFromNumberToDuration(const ast_matchers::MatchFinder::MatchResult &Result, DurationScale Scale, const Expr *Node)
Assuming Node has type double or int representing a time interval of Scale, return the expression to ...
llvm::Optional< llvm::Expected< tooling::AtomicChanges > > Result
llvm::Optional< DurationScale > getScaleForInverse(llvm::StringRef Name)
Given the name of an inverse Duration function (e.g., ToDoubleSeconds), return its DurationScale...
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//