11 #include "clang/AST/ASTContext.h"
12 #include "clang/ASTMatchers/ASTMatchFinder.h"
14 using namespace clang::ast_matchers;
22 AST_MATCHER(Expr, isInMacro) {
return Node.getLocStart().isMacroID(); }
25 const Stmt *nextStmt(
const MatchFinder::MatchResult &Result,
const Stmt *S) {
26 auto Parents = Result.Context->getParents(*S);
29 const auto *Parent = Parents[0].get<Stmt>();
32 const Stmt *Prev =
nullptr;
33 for (
const Stmt *Child : Parent->children()) {
38 return nextStmt(Result, Parent);
41 using ExpansionRanges = std::vector<std::pair<SourceLocation, SourceLocation>>;
46 ExpansionRanges getExpansionRanges(SourceLocation
Loc,
47 const MatchFinder::MatchResult &Result) {
49 while (Loc.isMacroID()) {
50 Locs.push_back(Result.SourceManager->getImmediateExpansionRange(Loc));
51 Loc = Locs.back().first;
58 void MultipleStatementMacroCheck::registerMatchers(MatchFinder *
Finder) {
59 const auto Inner = expr(isInMacro(), unless(compoundStmt())).bind(
"inner");
61 stmt(anyOf(ifStmt(hasThen(Inner)), ifStmt(hasElse(Inner)).bind(
"else"),
62 whileStmt(hasBody(Inner)), forStmt(hasBody(Inner))))
67 void MultipleStatementMacroCheck::check(
68 const MatchFinder::MatchResult &Result) {
69 const auto *Inner = Result.Nodes.getNodeAs<Expr>(
"inner");
70 const auto *Outer = Result.Nodes.getNodeAs<Stmt>(
"outer");
71 const auto *Next = nextStmt(Result, Outer);
75 SourceLocation OuterLoc = Outer->getLocStart();
76 if (Result.Nodes.getNodeAs<Stmt>(
"else"))
77 OuterLoc = cast<IfStmt>(Outer)->getElseLoc();
79 auto InnerRanges = getExpansionRanges(Inner->getLocStart(), Result);
80 auto OuterRanges = getExpansionRanges(OuterLoc, Result);
81 auto NextRanges = getExpansionRanges(Next->getLocStart(), Result);
85 while (!InnerRanges.empty() && !OuterRanges.empty() && !NextRanges.empty() &&
86 InnerRanges.back() == OuterRanges.back() &&
87 InnerRanges.back() == NextRanges.back()) {
88 InnerRanges.pop_back();
89 OuterRanges.pop_back();
90 NextRanges.pop_back();
95 if (InnerRanges.empty() || NextRanges.empty() ||
96 InnerRanges.back() != NextRanges.back())
99 diag(InnerRanges.back().first,
"multiple statement macro used without "
100 "braces; some statements will be "
101 "unconditionally executed");
SourceLocation Loc
'#' location in the include directive
std::unique_ptr< ast_matchers::MatchFinder > Finder
AST_MATCHER(VarDecl, isAsm)