| 1 | //===--- FloatLoopCounter.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 "FloatLoopCounter.h" |
| 10 | #include "clang/AST/ASTContext.h" |
| 11 | #include "clang/ASTMatchers/ASTMatchFinder.h" |
| 12 | #include "clang/ASTMatchers/ASTMatchers.h" |
| 13 | |
| 14 | using namespace clang::ast_matchers; |
| 15 | |
| 16 | namespace clang::tidy::cert { |
| 17 | |
| 18 | void FloatLoopCounter::registerMatchers(MatchFinder *Finder) { |
| 19 | Finder->addMatcher( |
| 20 | NodeMatch: forStmt(hasIncrement(InnerMatcher: forEachDescendant( |
| 21 | declRefExpr(hasType(InnerMatcher: realFloatingPointType()), |
| 22 | to(InnerMatcher: varDecl().bind(ID: "var"))) |
| 23 | .bind(ID: "inc"))), |
| 24 | hasCondition(InnerMatcher: forEachDescendant( |
| 25 | declRefExpr(hasType(InnerMatcher: realFloatingPointType()), |
| 26 | to(InnerMatcher: varDecl(equalsBoundNode(ID: "var")))) |
| 27 | .bind(ID: "cond")))) |
| 28 | .bind(ID: "for"), |
| 29 | Action: this); |
| 30 | } |
| 31 | |
| 32 | void FloatLoopCounter::check(const MatchFinder::MatchResult &Result) { |
| 33 | const auto *FS = Result.Nodes.getNodeAs<ForStmt>(ID: "for"); |
| 34 | |
| 35 | diag(FS->getInc()->getBeginLoc(), "loop induction expression should not have " |
| 36 | "floating-point type") |
| 37 | << Result.Nodes.getNodeAs<DeclRefExpr>(ID: "inc")->getSourceRange() |
| 38 | << Result.Nodes.getNodeAs<DeclRefExpr>(ID: "cond")->getSourceRange(); |
| 39 | |
| 40 | if (!FS->getInc()->getType()->isRealFloatingType()) |
| 41 | if (const auto *V = Result.Nodes.getNodeAs<VarDecl>(ID: "var")) |
| 42 | diag(V->getBeginLoc(), "floating-point type loop induction variable", |
| 43 | DiagnosticIDs::Note); |
| 44 | } |
| 45 | |
| 46 | } // namespace clang::tidy::cert |
| 47 |
