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 if (
const auto *AS = dyn_cast<AttributedStmt>(S))
24 return AS->getSubStmt();
31 if (isa<CompoundStmt>(Then))
34 if (
const Stmt *Else = If->getElse()) {
36 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Else))
39 return isa<CompoundStmt>(Else);
47 ifStmt(hasElse(anything()),
48 unless(isConsteval()),
49 unless(hasParent(ifStmt())))
55 const MatchFinder::MatchResult &Result) {
56 const auto *MatchedIf = Result.Nodes.getNodeAs<IfStmt>(
"if_stmt");
59 checkIfStmt(Result, MatchedIf);
62void InconsistentIfElseBracesCheck::checkIfStmt(
63 const MatchFinder::MatchResult &Result,
const IfStmt *If) {
65 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Then)) {
68 emitDiagnostic(Result, If->getThen(), If->getRParenLoc(), If->getElseLoc());
71 checkIfStmt(Result, NestedIf);
72 }
else if (!isa<CompoundStmt>(Then)) {
73 emitDiagnostic(Result, If->getThen(), If->getRParenLoc(), If->getElseLoc());
76 if (
const Stmt *Else = If->getElse()) {
78 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Else))
79 checkIfStmt(Result, NestedIf);
80 else if (!isa<CompoundStmt>(Else))
81 emitDiagnostic(Result, If->getElse(), If->getElseLoc());
85void InconsistentIfElseBracesCheck::emitDiagnostic(
86 const MatchFinder::MatchResult &Result,
const Stmt *S,
87 SourceLocation StartLoc, SourceLocation EndLocHint) {
88 if (StartLoc.isMacroID()) {
89 diag(StartLoc,
"statement should have braces");
93 S, Result.Context->getLangOpts(), *Result.SourceManager, StartLoc,
95 assert(Hints && Hints.offersFixIts() &&
"Expected hints or fix-its");
96 diag(Hints.DiagnosticPos,
"statement should have braces")
97 << 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 const Stmt * ignoreAttributed(const Stmt *S)
Look through AttributedStmt wrappers to find the underlying statement.
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.