10#include "clang/AST/ASTContext.h"
11#include "clang/ASTMatchers/ASTMatchFinder.h"
22const Stmt *nextStmt(
const MatchFinder::MatchResult &Result,
const Stmt *S) {
23 auto Parents = Result.Context->getParents(*S);
29 const Stmt *Prev =
nullptr;
30 for (
const Stmt *Child :
Parent->children()) {
35 return nextStmt(Result,
Parent);
38using ExpansionRanges = std::vector<SourceRange>;
43ExpansionRanges getExpansionRanges(SourceLocation
Loc,
44 const MatchFinder::MatchResult &Result) {
46 while (
Loc.isMacroID()) {
48 Result.SourceManager->getImmediateExpansionRange(
Loc).getAsRange());
49 Loc = Locs.back().getBegin();
57 const auto Inner = expr(isInMacro(), unless(compoundStmt())).bind(
"inner");
59 stmt(anyOf(ifStmt(hasThen(
Inner)), ifStmt(hasElse(
Inner)).bind(
"else"),
60 whileStmt(hasBody(
Inner)), forStmt(hasBody(
Inner))))
66 const MatchFinder::MatchResult &Result) {
67 const auto *
Inner = Result.Nodes.getNodeAs<Expr>(
"inner");
68 const auto *Outer = Result.Nodes.getNodeAs<Stmt>(
"outer");
69 const auto *Next = nextStmt(Result, Outer);
73 SourceLocation OuterLoc = Outer->getBeginLoc();
74 if (Result.Nodes.getNodeAs<Stmt>(
"else"))
75 OuterLoc = cast<IfStmt>(Outer)->getElseLoc();
77 auto InnerRanges = getExpansionRanges(
Inner->getBeginLoc(), Result);
78 auto OuterRanges = getExpansionRanges(OuterLoc, Result);
79 auto NextRanges = getExpansionRanges(Next->getBeginLoc(), Result);
83 while (!InnerRanges.empty() && !OuterRanges.empty() && !NextRanges.empty() &&
84 InnerRanges.back() == OuterRanges.back() &&
85 InnerRanges.back() == NextRanges.back()) {
86 InnerRanges.pop_back();
87 OuterRanges.pop_back();
88 NextRanges.pop_back();
93 if (InnerRanges.empty() || NextRanges.empty() ||
94 InnerRanges.back() != NextRanges.back())
97 diag(InnerRanges.back().getBegin(),
"multiple statement macro used without "
98 "braces; some statements will be "
99 "unconditionally executed");
std::pair< Context, Canceler > Inner
::clang::DynTypedNode Node
DiagnosticBuilder diag(SourceLocation Loc, StringRef Description, DiagnosticIDs::Level Level=DiagnosticIDs::Warning)
Add a diagnostic with the check's name.
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.
AST_MATCHER(clang::VarDecl, hasConstantDeclaration)