You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
To extract all Java field names of type `String` is not as straightforward as one might think. A simple pattern like `String $F;` would only match fields declared without any modifiers or annotations. However, a pattern like `$MOD String $F;` cannot be correctly parsed by tree-sitter.
8
+
9
+
:::details Use playground pattern debugger to explore the AST
10
+
11
+
You can use the [playground](https://ast-grep.github.io/playground.html#eyJtb2RlIjoiUGF0Y2giLCJsYW5nIjoiamF2YSIsInF1ZXJ5IjoiY2xhc3MgQUJDe1xuICAgJE1PRCBTdHJpbmcgdGVzdDtcbn0iLCJyZXdyaXRlIjoiIiwic3RyaWN0bmVzcyI6ImFzdCIsInNlbGVjdG9yIjoiIiwiY29uZmlnIjoicnVsZTpcbiAga2luZDogZmllbGRfZGVjbGFyYXRpb25cbiAgaGFzOlxuICAgIGZpZWxkOiB0eXBlXG4gICAgcmVnZXg6IF5TdHJpbmckIiwic291cmNlIjoiQENvbXBvbmVudFxuY2xhc3MgQUJDIGV4dGVuZHMgT2JqZWN0e1xuICAgIEBSZXNvdXJjZVxuICAgIHByaXZhdGUgZmluYWwgU3RyaW5nIHdpdGhfYW5ubztcblxuICAgIHByaXZhdGUgZmluYWwgU3RyaW5nIHdpdGhfbXVsdGlfbW9kO1xuXG4gICAgcHVibGljIFN0cmluZyBzaW1wbGU7XG59In0=)'s pattern tab to visualize the AST of `class A { $MOD String $F; }`.
12
+
13
+
```
14
+
field_declaration
15
+
$MOD
16
+
variable_declarator
17
+
identifier: String
18
+
ERROR
19
+
identifier: $F
20
+
```
21
+
22
+
Tree-sitter does not think `$MOD` is a valid modifier, so it produces an `ERROR`.
23
+
24
+
While the valid AST for code like `private String field;` produces different AST structures:
25
+
26
+
```
27
+
field_declaration
28
+
modifiers
29
+
type_identifier
30
+
variable_declarator
31
+
identifier: field
32
+
```
33
+
34
+
:::
35
+
36
+
A more robust approach is to use a structural rule that targets `field_declaration` nodes and applies a `has` constraint on the `type` child node to match the type `String`. This method effectively captures fields regardless of their modifiers or annotations.
37
+
38
+
### YAML
39
+
40
+
```yaml
41
+
id: find-field-with-type
42
+
language: java
43
+
rule:
44
+
kind: field_declaration
45
+
has:
46
+
field: type
47
+
regex: ^String$
48
+
```
49
+
50
+
### Example
51
+
52
+
```java {3-4,6,8}
53
+
@Component
54
+
class ABC extends Object{
55
+
@Resource
56
+
private final String with_anno;
57
+
58
+
private final String with_multi_mod;
59
+
60
+
public String simple;
61
+
}
62
+
```
63
+
64
+
### Contributed by
65
+
Inspired by the post [discussion](https://github.com/ast-grep/ast-grep/discussions/2195)
0 commit comments