11#include "clang/AST/ASTContext.h"
12#include "clang/AST/Stmt.h"
13#include "clang/ASTMatchers/ASTMatchers.h"
14#include "clang/Basic/SourceLocation.h"
15#include "clang/Lex/Lexer.h"
23 const Stmt *
const Then = If->getThen();
24 if (isa<CompoundStmt>(Then))
27 if (
const Stmt *
const Else = If->getElse()) {
28 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Else))
31 return isa<CompoundStmt>(Else);
39 ifStmt(hasElse(anything()),
40 unless(isConsteval()),
41 unless(hasParent(ifStmt())))
47 const MatchFinder::MatchResult &Result) {
48 const auto *MatchedIf = Result.Nodes.getNodeAs<IfStmt>(
"if_stmt");
51 checkIfStmt(Result, MatchedIf);
54void InconsistentIfElseBracesCheck::checkIfStmt(
55 const MatchFinder::MatchResult &Result,
const IfStmt *If) {
56 const Stmt *Then = If->getThen();
57 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Then)) {
60 emitDiagnostic(Result, If->getThen(), If->getRParenLoc(), If->getElseLoc());
63 checkIfStmt(Result, NestedIf);
64 }
else if (!isa<CompoundStmt>(Then)) {
65 emitDiagnostic(Result, Then, If->getRParenLoc(), If->getElseLoc());
68 if (
const Stmt *
const Else = If->getElse()) {
69 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Else))
70 checkIfStmt(Result, NestedIf);
71 else if (!isa<CompoundStmt>(Else))
72 emitDiagnostic(Result, If->getElse(), If->getElseLoc());
76void InconsistentIfElseBracesCheck::emitDiagnostic(
77 const MatchFinder::MatchResult &Result,
const Stmt *S,
78 SourceLocation StartLoc, SourceLocation EndLocHint) {
79 if (StartLoc.isMacroID()) {
80 diag(StartLoc,
"statement should have braces");
84 S, Result.Context->getLangOpts(), *Result.SourceManager, StartLoc,
86 assert(Hints && Hints.offersFixIts() &&
"Expected hints or fix-its");
87 diag(Hints.DiagnosticPos,
"statement should have braces")
88 << Hints.openingBraceFixIt() << Hints.closingBraceFixIt();
This file provides utilities to put braces around a statement.
void check(const ast_matchers::MatchFinder::MatchResult &Result) override
void registerMatchers(ast_matchers::MatchFinder *Finder) override
static bool shouldHaveBraces(const IfStmt *If)
Check that at least one branch of the If statement is a CompoundStmt.
BraceInsertionHints getBraceInsertionsHints(const Stmt *const S, const LangOptions &LangOpts, const SourceManager &SM, SourceLocation StartLoc, SourceLocation EndLocHint)
Create fix-it hints for braces that wrap the given statement when applied.