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) {
61 const clang::SourceLocation StartLoc = BinOp->getBeginLoc();
62 const clang::SourceLocation EndLoc =
63 clang::Lexer::getLocForEndOfToken(BinOp->getEndLoc(), 0, SM, LangOpts);
67 "'%0' has higher precedence than '%1'; add parentheses to "
68 "explicitly specify the order of operations")
69 << (Precedence1 > Precedence2 ? BinOp->getOpcodeStr()
70 : ParentBinOp->getOpcodeStr())
71 << (Precedence1 > Precedence2 ? ParentBinOp->getOpcodeStr()
72 : BinOp->getOpcodeStr())
73 << SourceRange(StartLoc, EndLoc);
75 if (EndLoc.isValid()) {
76 Diag << FixItHint::CreateInsertion(StartLoc,
"(")
77 << FixItHint::CreateInsertion(EndLoc,
")");
81 addParantheses(dyn_cast<BinaryOperator>(BinOp->getLHS()->IgnoreImpCasts()),
82 BinOp, Check, SM, LangOpts);
83 addParantheses(dyn_cast<BinaryOperator>(BinOp->getRHS()->IgnoreImpCasts()),
84 BinOp, Check, SM, LangOpts);
88 const MatchFinder::MatchResult &Result) {
89 const auto *BinOp = Result.Nodes.getNodeAs<BinaryOperator>(
"binOp");
91 std::pair<clang::SourceRange, std::pair<
const clang::BinaryOperator *,
92 const clang::BinaryOperator *>>>
94 const SourceManager &SM = *Result.SourceManager;
95 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)