11 #include "clang/AST/ASTContext.h" 12 #include "clang/ASTMatchers/ASTMatchFinder.h" 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<SourceRange>;
46 ExpansionRanges getExpansionRanges(SourceLocation
Loc,
47 const MatchFinder::MatchResult &Result) {
49 while (Loc.isMacroID()) {
51 Result.SourceManager->getImmediateExpansionRange(Loc).getAsRange());
52 Loc = Locs.back().getBegin();
59 void MultipleStatementMacroCheck::registerMatchers(MatchFinder *Finder) {
60 const auto Inner = expr(isInMacro(), unless(compoundStmt())).bind(
"inner");
62 stmt(anyOf(ifStmt(hasThen(Inner)), ifStmt(hasElse(Inner)).bind(
"else"),
63 whileStmt(hasBody(Inner)), forStmt(hasBody(Inner))))
68 void MultipleStatementMacroCheck::check(
69 const MatchFinder::MatchResult &Result) {
70 const auto *Inner = Result.Nodes.getNodeAs<Expr>(
"inner");
71 const auto *Outer = Result.Nodes.getNodeAs<Stmt>(
"outer");
72 const auto *Next = nextStmt(Result, Outer);
76 SourceLocation OuterLoc = Outer->getLocStart();
77 if (Result.Nodes.getNodeAs<Stmt>(
"else"))
78 OuterLoc = cast<IfStmt>(Outer)->getElseLoc();
80 auto InnerRanges = getExpansionRanges(Inner->getLocStart(), Result);
81 auto OuterRanges = getExpansionRanges(OuterLoc, Result);
82 auto NextRanges = getExpansionRanges(Next->getLocStart(), Result);
86 while (!InnerRanges.empty() && !OuterRanges.empty() && !NextRanges.empty() &&
87 InnerRanges.back() == OuterRanges.back() &&
88 InnerRanges.back() == NextRanges.back()) {
89 InnerRanges.pop_back();
90 OuterRanges.pop_back();
91 NextRanges.pop_back();
96 if (InnerRanges.empty() || NextRanges.empty() ||
97 InnerRanges.back() != NextRanges.back())
100 diag(InnerRanges.back().getBegin(),
"multiple statement macro used without " 101 "braces; some statements will be " 102 "unconditionally executed");
SourceLocation Loc
'#' location in the include directive
AST_MATCHER(BinaryOperator, isAssignmentOperator)
===– Representation.cpp - ClangDoc Representation --------—*- C++ -*-===//