Skip to content

[clang-query] Allow for trailing comma in matchers #148018

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 15, 2025

Conversation

one-d-wide
Copy link
Contributor

Allow AST matches in clang-query to have a trailing comma at the end of matcher arguments. Makes it nicer to work with queries that span multiple lines.

So, for example, the following is possible:

match namedDecl(
  isExpansionInMainFile(),
  anyOf(
    varDecl().bind("var"),
    functionDecl().bind("func"),
    # enumDecl().bind("enum"),
  ),
)

CC: @AaronBallman

Copy link

Thank you for submitting a Pull Request (PR) to the LLVM Project!

This PR will be automatically labeled and the relevant teams will be notified.

If you wish to, you can add reviewers by using the "Reviewers" section on this page.

If this is not working for you, it is probably because you do not have write permissions for the repository. In which case you can instead tag reviewers by name in a comment by using @ followed by their GitHub username.

If you have received no comments on your PR for a week, you can request a review by "ping"ing the PR by adding a comment “Ping”. The common courtesy "ping" rate is once a week. Please remember that you are asking for valuable time from other developers.

If you have further questions, they may be answered by the LLVM GitHub User Guide.

You can also ask questions in a comment on this PR, on the LLVM Discord or on the forums.

@llvmbot llvmbot added clang Clang issues not falling into any other category clang-tools-extra labels Jul 10, 2025
@llvmbot
Copy link
Member

llvmbot commented Jul 10, 2025

@llvm/pr-subscribers-clang-tools-extra

@llvm/pr-subscribers-clang

Author: Remy Farley (one-d-wide)

Changes

Allow AST matches in clang-query to have a trailing comma at the end of matcher arguments. Makes it nicer to work with queries that span multiple lines.

So, for example, the following is possible:

match namedDecl(
  isExpansionInMainFile(),
  anyOf(
    varDecl().bind("var"),
    functionDecl().bind("func"),
    # enumDecl().bind("enum"),
  ),
)

CC: @AaronBallman


Full diff: https://github.com/llvm/llvm-project/pull/148018.diff

2 Files Affected:

  • (added) clang-tools-extra/test/clang-query/trailing-comma.c (+10)
  • (modified) clang/lib/ASTMatchers/Dynamic/Parser.cpp (+10)
diff --git a/clang-tools-extra/test/clang-query/trailing-comma.c b/clang-tools-extra/test/clang-query/trailing-comma.c
new file mode 100644
index 0000000000000..ecdfd3b8ab6fd
--- /dev/null
+++ b/clang-tools-extra/test/clang-query/trailing-comma.c
@@ -0,0 +1,10 @@
+// RUN: clang-query -c "match \
+// RUN:   functionDecl( \
+// RUN:       hasName( \
+// RUN:           \"foo\", \
+// RUN:       ), \
+// RUN:   ) \
+// RUN: " %s -- | FileCheck %s
+
+// CHECK: trailing-comma.c:10:1: note: "root" binds here
+void foo(void) {}
diff --git a/clang/lib/ASTMatchers/Dynamic/Parser.cpp b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
index 8a5ac4d0f9d0c..baac797f09ec3 100644
--- a/clang/lib/ASTMatchers/Dynamic/Parser.cpp
+++ b/clang/lib/ASTMatchers/Dynamic/Parser.cpp
@@ -490,6 +490,11 @@ bool Parser::parseMatcherBuilder(MatcherCtor Ctor, const TokenInfo &NameToken,
               << CommaToken.Text;
           return false;
         }
+        // Allow for a trailing , token and possibly a new line.
+        Tokenizer->SkipNewlines();
+        if (Tokenizer->nextTokenKind() == TokenInfo::TK_CloseParen) {
+          continue;
+        }
       }
 
       Diagnostics::Context Ctx(Diagnostics::Context::MatcherArg, Error,
@@ -658,6 +663,11 @@ bool Parser::parseMatcherExpressionImpl(const TokenInfo &NameToken,
               << CommaToken.Text;
           return false;
         }
+        // Allow for a trailing , token and possibly a new line.
+        Tokenizer->SkipNewlines();
+        if (Tokenizer->nextTokenKind() == TokenInfo::TK_CloseParen) {
+          continue;
+        }
       }
 
       Diagnostics::Context Ctx(Diagnostics::Context::MatcherArg, Error,

@AaronBallman AaronBallman self-requested a review July 11, 2025 17:40
Copy link
Collaborator

@AaronBallman AaronBallman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the PR! I think we need to think about this a little bit; my concern is that folks often use clang-query to write queries they'll eventually be using in clang-tidy checks. However, the tidy checks are using the C++ DSL which won't support trailing commas (and I don't think could be made to support them). So while it might make things easier in some cases, it may be a surprising difference between the tools. WDYT?

If we go forward with this, we should add a release note to clang-tools-extra/docs/ReleaseNotes.rst. We don't currently have any docs for clang-query, but if we had those docs, we should probably note the difference between the C++ DSL and clang-query in them. (That's not something you have to worry about for your patch though.)

@one-d-wide one-d-wide force-pushed the clang-query-trailing-comma branch from 5992431 to b35f9eb Compare July 12, 2025 12:01
@one-d-wide
Copy link
Contributor Author

I don't think this is much of an issue. Once you attempt to interpret a query with trailing comma in it as C++ code, a compiler (or even an LSP) will usually emit a (mostly) unambiguous error, which should be trivial to correct. And that's it. Existing queries, including ones ported back from C++, are unaffected.

I see this feature as only helpful during the development of a query, smoothing the experience by, for example, allowing to conveniently comment query arguments out (which also done in a way incompatible with C++ btw).

In which case getting an error is rather annoying, since matcher arguments act more like parameters in a C++ initializer list (where trailing comma is actually allowed), rather than positional arguments in a function.

Updated release notes.

Copy link
Collaborator

@AaronBallman AaronBallman left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, I think I'm okay with this. It's a bit different from C++, but the difference seems sufficiently useful and the amount of pain with switching between the two DSLs seems pretty minimal.

I did have a request for some additional test coverage though.

@one-d-wide one-d-wide force-pushed the clang-query-trailing-comma branch from b35f9eb to 7e8d7da Compare July 15, 2025 10:44
@AaronBallman
Copy link
Collaborator

AaronBallman commented Jul 15, 2025

It looks like precommit CI found a relevant failure on Windows:

******************** TEST 'Clang Tools :: clang-query/trailing-comma.c' FAILED ********************
  Exit Code: 1
  
  Command Output (stdout):
  --
  # shell parser error on RUN: at line 14: clang-query -c "$(echo "match functionDecl( hasName( \"foo\" , ) , )" | sed "s/ /\n/g")" C:\_work\llvm-project\llvm-project\clang-tools-extra\test\clang-query\trailing-comma.c    | FileCheck --check-prefix=CHECK-OK C:\_work\llvm-project\llvm-project\clang-tools-extra\test\clang-query\trailing-comma.c
  
  --
  
  ********************

I think the use of sed is fine, Maybe it's tripping up on $() ?

@one-d-wide one-d-wide force-pushed the clang-query-trailing-comma branch from 7e8d7da to 22e6282 Compare July 15, 2025 14:52
@one-d-wide
Copy link
Contributor Author

Duh, apparently lit's internal cli interpreter, enabled due to this (setting LIT_USE_INTERNAL_SHELL=1 reproduces the error), doesn't even attempt to parse $... and $(...) substitutions.

Not sure if /dev/stdin trick would work on win32, so fixed it by first piping into %t.

@AaronBallman AaronBallman merged commit 041a8a9 into llvm:main Jul 15, 2025
10 checks passed
Copy link

@one-d-wide Congratulations on having your first Pull Request (PR) merged into the LLVM Project!

Your changes will be combined with recent changes from other authors, then tested by our build bots. If there is a problem with a build, you may receive a report in an email or a comment on this PR.

Please check whether problems have been caused by your change specifically, as the builds can include changes from many authors. It is not uncommon for your change to be included in a build that fails due to someone else's changes, or infrastructure issues.

How to do this, and the rest of the post-merge process, is covered in detail here.

If your change does cause a problem, it may be reverted, or you can revert it yourself. This is a normal part of LLVM development. You can fix your changes and open a new PR to merge them again.

If you don't get any reports, no action is required from you. Your changes are working as expected, well done!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
clang Clang issues not falling into any other category clang-tools-extra
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants