tree-sitter-java icon indicating copy to clipboard operation
tree-sitter-java copied to clipboard

feat(grammar): Refactor modifiers for better querying

Open lightless233 opened this issue 8 months ago • 1 comments

Addresses #204.

Right now, modifiers like public or static are just anonymous keywords in the AST. This makes it a pain to write queries for them without matching on text.

This PR makes them actual nodes, similar to how tree-sitter-typescript handles it.

Changes:

  1. New (visibility) node:

    • public, protected, private are now grouped under this node.
    • Makes it easy to find declarations with specific visibility.
    ; e.g., find public methods
    (method_declaration (modifiers (visibility) @v) (#eq? @v "public"))
    
  2. New (modifier) node:

    • static, final, abstract, etc., now all produce a (modifier) node.
    • This provides a single node type for all these other keywords.
    ; e.g., find static fields
    (field_declaration (modifiers (modifier) @m) (#eq? @m "static"))
    

Resulting AST:

For public static class..., the AST is now much cleaner:

- (modifiers (KEYWORD) (KEYWORD))
+ (modifiers
+   (visibility)
+   (modifier)
+ )

Closes #204.

lightless233 avatar Jul 03 '25 09:07 lightless233

Not a maintainer, but thank you for your PR! I have integrated it in this fork (alongside other unreviewed PRs) and the change turned out to be very helpful in Mergiraf.

Since you seem to be using this grammar from Rust, maybe you're interested in switching to the fork (tree-sitter-java-orchard on crates.io).

wetneb avatar Jul 28 '25 14:07 wetneb