[PATCH] D116328: [ast-matchers] Add hasSubstatement() traversal matcher for caseStmt(), defaultStmt(), labelStmt()

Aaron Ballman via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Wed Jan 5 04:53:48 PST 2022


aaron.ballman added a comment.

> Previously if you wanted to match the statement associated with a case, default, or labelled statement, you had to use hasDescendant.

This isn't true. You can use `has()` to do direct substatemematching, and I'm wondering whether we need this new matcher at all. e.g., https://godbolt.org/z/K5sYP757r



================
Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:2432
     dependentCoawaitExpr;
+
 /// Matches co_yield expressions.
----------------
Spurious newline?


================
Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:7720
 
+/// Matches the substatement associated with a case, default or label statement.
+///
----------------
May need to reformat as well, but the intent is to make it clear that this does not behave like `hasAnySubstatement()`.


================
Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:7727
+///   foo: return;
+///   bar: break;
+/// \endcode
----------------
This is invalid code (there's nothing to break out of), so you may want to tweak the example a bit.


================
Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:7730-7734
+/// caseStmt(hasSubstmt(returnStmt()))
+///   matches "case 2: return;"
+/// defaultStmt(hasSubstmt(returnStmt()))
+///   matches "default: return;"
+/// labelStmt(hasSubstmt(breakStmt()))
----------------



================
Comment at: clang/include/clang/ASTMatchers/ASTMatchers.h:7737-7738
+AST_POLYMORPHIC_MATCHER_P(hasSubstatement,
+                          AST_POLYMORPHIC_SUPPORTED_TYPES(CaseStmt, DefaultStmt,
+                                                          LabelStmt),
+                          internal::Matcher<Stmt>, InnerMatcher) {
----------------
Pretty sure you can use the base class here as a simplification.


================
Comment at: clang/lib/ASTMatchers/Dynamic/Registry.cpp:69
   registerMatcher(#name, internal::makeMatcherAutoMarshall(                    \
-                             ::clang::ast_matchers::name, #name));
+                             ::clang::ast_matchers::name, #name))
 
----------------
Good catch; feel free to land this and related changes as an NFC commit.


================
Comment at: clang/unittests/ASTMatchers/ASTMatchersTraversalTest.cpp:161
+TEST_P(ASTMatchersTest, HasLabelSubstmt) {
+  EXPECT_TRUE(matches("void f() { while (1) { bar: break; foo: return; } }",
+                      traverse(TK_AsIs, labelStmt(hasSubstatement(breakStmt())))));
----------------
Should fix the formatting.


CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D116328/new/

https://reviews.llvm.org/D116328



More information about the cfe-commits mailing list