1 | //===--- DurationDivisionCheck.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 "DurationDivisionCheck.h" |
10 | #include "clang/AST/ASTContext.h" |
11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
12 | #include "clang/Lex/Lexer.h" |
13 | |
14 | namespace clang::tidy::abseil { |
15 | |
16 | using namespace clang::ast_matchers; |
17 | |
18 | void DurationDivisionCheck::registerMatchers(MatchFinder *Finder) { |
19 | const auto DurationExpr = |
20 | expr(hasType(InnerMatcher: cxxRecordDecl(hasName(Name: "::absl::Duration" )))); |
21 | Finder->addMatcher( |
22 | NodeMatch: traverse(TK: TK_AsIs, |
23 | InnerMatcher: implicitCastExpr( |
24 | hasSourceExpression(InnerMatcher: ignoringParenCasts( |
25 | InnerMatcher: cxxOperatorCallExpr(hasOverloadedOperatorName(Name: "/" ), |
26 | hasArgument(N: 0, InnerMatcher: DurationExpr), |
27 | hasArgument(N: 1, InnerMatcher: DurationExpr)) |
28 | .bind(ID: "OpCall" ))), |
29 | hasImplicitDestinationType(InnerMatcher: qualType(unless(isInteger()))), |
30 | unless(hasParent(cxxStaticCastExpr())), |
31 | unless(hasParent(cStyleCastExpr())), |
32 | unless(isInTemplateInstantiation()))), |
33 | Action: this); |
34 | } |
35 | |
36 | void DurationDivisionCheck::check(const MatchFinder::MatchResult &Result) { |
37 | const auto *OpCall = Result.Nodes.getNodeAs<CXXOperatorCallExpr>(ID: "OpCall" ); |
38 | diag(Loc: OpCall->getOperatorLoc(), |
39 | Description: "operator/ on absl::Duration objects performs integer division; " |
40 | "did you mean to use FDivDuration()?" ) |
41 | << FixItHint::CreateInsertion(InsertionLoc: OpCall->getBeginLoc(), |
42 | Code: "absl::FDivDuration(" ) |
43 | << FixItHint::CreateReplacement( |
44 | RemoveRange: SourceRange(OpCall->getOperatorLoc(), OpCall->getOperatorLoc()), |
45 | Code: ", " ) |
46 | << FixItHint::CreateInsertion( |
47 | InsertionLoc: Lexer::getLocForEndOfToken( |
48 | Loc: Result.SourceManager->getSpellingLoc(Loc: OpCall->getEndLoc()), Offset: 0, |
49 | SM: *Result.SourceManager, LangOpts: Result.Context->getLangOpts()), |
50 | Code: ")" ); |
51 | } |
52 | |
53 | } // namespace clang::tidy::abseil |
54 | |