10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
12#include "clang/Lex/Lexer.h"
19 Finder->addMatcher(binaryOperator(unless(hasParent(binaryOperator())),
20 unless(isAssignmentOperator()),
21 unless(isComparisonOperator()),
22 unless(hasAnyOperatorName(
"&&",
"||")),
23 hasDescendant(binaryOperator()))
31 switch (BinOp->getOpcode()) {
50 const BinaryOperator *ParentBinOp,
52 const clang::SourceManager &SM,
53 const clang::LangOptions &LangOpts) {
60 if (ParentBinOp !=
nullptr && Precedence1 != Precedence2 && Precedence1 > 0 &&
62 const clang::SourceLocation StartLoc = BinOp->getBeginLoc();
63 const clang::SourceLocation EndLoc =
64 clang::Lexer::getLocForEndOfToken(BinOp->getEndLoc(), 0, SM, LangOpts);
68 "'%0' has higher precedence than '%1'; add parentheses to "
69 "explicitly specify the order of operations")
70 << (Precedence1 > Precedence2 ? BinOp->getOpcodeStr()
71 : ParentBinOp->getOpcodeStr())
72 << (Precedence1 > Precedence2 ? ParentBinOp->getOpcodeStr()
73 : BinOp->getOpcodeStr())
74 << SourceRange(StartLoc, EndLoc);
76 if (EndLoc.isValid()) {
77 Diag << FixItHint::CreateInsertion(StartLoc,
"(")
78 << FixItHint::CreateInsertion(EndLoc,
")");
82 addParantheses(dyn_cast<BinaryOperator>(BinOp->getLHS()->IgnoreImpCasts()),
83 BinOp, Check, SM, LangOpts);
84 addParantheses(dyn_cast<BinaryOperator>(BinOp->getRHS()->IgnoreImpCasts()),
85 BinOp, Check, SM, LangOpts);
89 const MatchFinder::MatchResult &Result) {
90 const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>(
"binOp");
92 std::pair<clang::SourceRange, std::pair<
const clang::BinaryOperator *,
93 const clang::BinaryOperator *>>>
95 const SourceManager &SM = *Result.SourceManager;
96 const clang::LangOptions &LO = Result.Context->getLangOpts();
Base class for all clang-tidy checks.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
ClangTidyChecks that register ASTMatchers should do the actual work in here.
void registerMatchers(ast_matchers::MatchFinder *Finder) override
Override this to register AST matchers with Finder.
static int getPrecedence(const BinaryOperator *BinOp)
static void addParantheses(const BinaryOperator *BinOp, const BinaryOperator *ParentBinOp, ClangTidyCheck *Check, const clang::SourceManager &SM, const clang::LangOptions &LangOpts)