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()->stripLabelLikeStatements();
24 if (isa<CompoundStmt>(Then))
27 if (
const Stmt *Else = If->getElse()) {
28 Else = Else->stripLabelLikeStatements();
29 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Else))
32 return isa<CompoundStmt>(Else);
40 ifStmt(hasElse(anything()),
41 unless(isConsteval()),
42 unless(hasParent(ifStmt())))
48 const MatchFinder::MatchResult &Result) {
49 const auto *MatchedIf = Result.Nodes.getNodeAs<IfStmt>(
"if_stmt");
52 checkIfStmt(Result, MatchedIf);
55void InconsistentIfElseBracesCheck::checkIfStmt(
56 const MatchFinder::MatchResult &Result,
const IfStmt *If) {
57 const Stmt *Then = If->getThen()->stripLabelLikeStatements();
58 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Then)) {
61 emitDiagnostic(Result, If->getThen(), If->getRParenLoc(), If->getElseLoc());
64 checkIfStmt(Result, NestedIf);
65 }
else if (!isa<CompoundStmt>(Then)) {
66 emitDiagnostic(Result, If->getThen(), If->getRParenLoc(), If->getElseLoc());
69 if (
const Stmt *Else = If->getElse()) {
70 Else = Else->stripLabelLikeStatements();
71 if (
const auto *NestedIf = dyn_cast<const IfStmt>(Else))
72 checkIfStmt(Result, NestedIf);
73 else if (!isa<CompoundStmt>(Else))
74 emitDiagnostic(Result, If->getElse(), If->getElseLoc());
78void InconsistentIfElseBracesCheck::emitDiagnostic(
79 const MatchFinder::MatchResult &Result,
const Stmt *S,
80 SourceLocation StartLoc, SourceLocation EndLocHint) {
81 if (StartLoc.isMacroID()) {
82 diag(StartLoc,
"statement should have braces");
86 S, Result.Context->getLangOpts(), *Result.SourceManager, StartLoc,
88 assert(Hints && Hints.offersFixIts() &&
"Expected hints or fix-its");
89 diag(Hints.DiagnosticPos,
"statement should have braces")
90 << 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.