### Java Method References Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Provides examples of different Java method reference syntaxes. ```java action = bar::method; foo.bar::method; String[]::new; Foo::apply; super::something; ``` -------------------------------- ### Java Marker Annotation Example Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates the use of marker annotations in Java. Marker annotations do not have any arguments. ```java @Override class Quack { @bar public void foo() { } } ``` -------------------------------- ### Tree-sitter CLI Development Commands Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Common commands for developing and testing the tree-sitter-java grammar using the tree-sitter CLI. Includes installation, generation, testing, and building. ```bash # Install dependencies npm install # Regenerate src/parser.c from grammar.js npx tree-sitter generate # Run the Node.js binding test npm test # > node --test bindings/node/*_test.js # ✔ can load grammar (4.123ms) # Build the WASM binary for the browser playground npm run prestart # tree-sitter build --wasm # Launch the interactive playground npm start # tree-sitter playground # Run all corpus tests (tests/corpus/*.txt) npx tree-sitter test # Run a single corpus test file npx tree-sitter test --filter declarations # Lint grammar.js npm run lint # Build native prebuilds for distribution npx prebuildify --napi --strip # Python: install and run tests pip install -e ".[core]" python -m pytest bindings/python/tests/ # Rust: run tests cargo test # Go: run tests go test ./bindings/go/... ``` -------------------------------- ### Java While Statement Example Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates a basic while loop in Java. Ensure the loop condition eventually becomes false to avoid infinite loops. ```java class WhileDemo { public static void main(String[] args){ int count = 1; while (count < 11) { System.out.println("Count is: " + count); count++; } } } ``` -------------------------------- ### Standard for loop with block Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates a traditional for loop used for iteration with initialization, condition, and update expressions, followed by a block of code to execute. This example includes printing a counter. ```java for(int i = 1; i < 11; i++) { System.out.println("Count is: " + i); } ``` ```tree-sitter-grammar (program (for_statement init: (local_variable_declaration type: (integral_type) declarator: (variable_declarator name: (identifier) value: (decimal_integer_literal))) condition: (binary_expression left: (identifier) right: (decimal_integer_literal)) update: (update_expression (identifier)) body: (block (expression_statement (method_invocation object: (field_access object: (identifier) field: (identifier)) name: (identifier) arguments: (argument_list (binary_expression left: (string_literal (string_fragment)) right: (identifier))))))) ``` -------------------------------- ### Java Return Switch Expression with Pattern Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Example of a Java return statement containing a switch expression with pattern matching. ```java return switch (s) { case rectangle r -> 2; }; ``` -------------------------------- ### Java Operator Precedence Example Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/precedence.txt Illustrates Java's operator precedence with arithmetic and boolean expressions. Note the order of operations for multiplication, addition, and comparison. ```java class A { public void b() { int a = 1; int b = 2; bool c = (1*1) + a > 5; bool d = a+b == a+b; } } ``` -------------------------------- ### Parse and Query Java Code with Python Binding Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Utilize the Python binding for tree-sitter-java to parse and query Java source code. This example shows how to build a parser, parse byte strings, and use bundled highlight and tag queries for syntax highlighting and symbol indexing. It also includes a function to check for parse errors. ```python import tree_sitter import tree_sitter_java # Build a parser JAVA_LANGUAGE = tree_sitter.Language(tree_sitter_java.language()) parser = tree_sitter.Parser(JAVA_LANGUAGE) source = b""" public record Point(int x, int y) { public double distance() { return Math.sqrt(x * x + y * y); } } public sealed interface Shape permits Circle, Rectangle {} public class Circle implements Shape { private final double radius; public Circle(double radius) { this.radius = radius; } public double area() { return Math.PI * radius * radius; } } """ tree = parser.parse(source) root = tree.root_node # Use the bundled highlights query for syntax highlighting highlights_query = tree_sitter.Query(JAVA_LANGUAGE, tree_sitter_java.HIGHLIGHTS_QUERY) captures = highlights_query.captures(root) for node, capture_name in captures.items(): print(f"{capture_name}: '{node.text.decode()}'") # Use the bundled tags query for symbol indexing tags_query = tree_sitter.Query(JAVA_LANGUAGE, tree_sitter_java.TAGS_QUERY) matches = tags_query.matches(root) for _, match in matches: for capture_name, nodes in match.items(): for node in nodes: print(f"{capture_name}: {node.text.decode()}") # Check for parse errors def check_errors(node, src): if node.has_error: print(f"Error at {node.start_point}: {src[node.start_byte:node.end_byte]}") for child in node.children: check_errors(child, src) check_errors(root, source) ``` -------------------------------- ### Java Annotation with Arguments Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Example of Java annotations with named arguments. Annotations can be used to provide metadata to the compiler or runtime. ```java @SuppressWarnings(value = "unchecked") @GwtCompatible(module = "foo", emulated = true) class Duck { } ``` -------------------------------- ### Nested if-then-else statements Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Shows how if statements can be nested within each other. This example highlights a common pattern where an inner if-else is part of the consequence of an outer if statement. ```java if (a) if (b) c(); else d(); ``` ```tree-sitter-grammar (program (if_statement (parenthesized_expression (identifier)) (if_statement (parenthesized_expression (identifier)) (expression_statement (method_invocation (identifier) (argument_list))) (expression_statement (method_invocation (identifier) (argument_list)))))) ``` -------------------------------- ### Java Octal Escape Sequence Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/literals.txt Shows an example of an octal escape sequence within a Java character literal. This is used to represent characters using their octal values. ```java '\7'; ``` -------------------------------- ### Class Declaration with Generic Type Parameters in Java Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Example of a Java class declaration that includes generic type parameters. This syntax is common for creating flexible data structures. ```java class Pair { A first; B second; } ``` -------------------------------- ### Go: Load and Use Tree-sitter Java Grammar Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Demonstrates loading the Java grammar using CGo and performing an initial parse of a Java source file. It also shows how to inspect the root node's properties and traverse its children. ```go package main import ( "fmt" tree_sitter "github.com/tree-sitter/go-tree-sitter" tree_sitter_java "github.com/tree-sitter/tree-sitter-java/bindings/go" ) func main() { // Load the Java grammar language := tree_sitter.NewLanguage(tree_sitter_java.Language()) if language == nil { panic("Error loading Java grammar") } parser := tree_sitter.NewParser() defer parser.Close() parser.SetLanguage(language) source := []byte(` package com.example; import java.util.ArrayList; import java.util.List; public class Main { public static void main(String[] args) { List items = new ArrayList<>(); items.add("Hello"); items.add("World"); for (String item : items) { System.out.println(item); } } `) tree := parser.Parse(source, nil) defer tree.Close() root := tree.RootNode() fmt.Println("Root type:", root.Kind()) // program fmt.Println("Has errors:", root.HasError()) // false fmt.Println("Child count:", root.ChildCount()) // 2 (package + class) // Traverse top-level children for i := 0; i < uint(root.ChildCount()); i++ { child := root.Child(i) fmt.Printf(" [%d] %s\n", i, child.Kind()) } } ``` -------------------------------- ### Object Instantiation in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Demonstrates object creation using the 'new' keyword. Note the two different syntaxes for calling constructors. ```java class Point { public double Foo() { new BufferedWriter(); Foo.new BufferedWriter(); } } ``` -------------------------------- ### Load and Use Highlights Query (Node.js) Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Loads the tree-sitter-java.wasm, parses a Java file, and queries for highlights using queries/highlights.scm. Requires web-tree-sitter and Node.js. ```javascript const Parser = require("web-tree-sitter"); await Parser.init(); const parser = new Parser(); const Java = await Parser.Language.load("tree-sitter-java.wasm"); parser.setLanguage(Java); const fs = require("fs"); const source = fs.readFileSync("Main.java", "utf8"); const tree = parser.parse(source); // Query highlights const highlightsQuery = Java.query(fs.readFileSync("queries/highlights.scm", "utf8")); const captures = highlightsQuery.captures(tree.rootNode); for (const { name, node } of captures) { console.log(`@${name}: "${node.text}" [${node.startPosition.row}:${node.startPosition.column}]`); } // @keyword: "public" [0:0] // @type: "Main" [0:13] // @function.method: "greet" [1:18] // @string: "\"Hello\"" [2:15] // @comment: "// inline comment" [3:4] // ... ``` -------------------------------- ### Rust: Incremental Parsing with Tree-sitter Java Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Shows how to perform an initial parse and an incremental re-parse by applying an edit to the previous tree. It also demonstrates accessing embedded node types and query strings. ```rust use tree_sitter::Parser; use tree_sitter_java; fn main() { let mut parser = Parser::new(); parser .set_language(&tree_sitter_java::LANGUAGE.into()) .expect("Error loading Java parser"); // Initial parse let source = r#" public class Counter { private int count = 0; public void increment() { count++; } public void decrement() { count--; } public int get() { return count; } } "#; let tree = parser.parse(source, None).unwrap(); assert!(!tree.root_node().has_error()); // Incremental re-parse: rename method "get" -> "getCount" let new_source = source.replace("int get()", "int getCount()"); let edit_byte_offset = source.find("int get()").unwrap(); let mut tree2 = tree.clone(); tree2.edit(&tree_sitter::InputEdit { start_byte: edit_byte_offset, old_end_byte: edit_byte_offset + "int get()".len(), new_end_byte: edit_byte_offset + "int getCount()".len(), start_position: tree_sitter::Point::new(0, 0), old_end_position: tree_sitter::Point::new(0, 0), new_end_position: tree_sitter::Point::new(0, 0), }); let updated_tree = parser.parse(&new_source, Some(&tree2)).unwrap(); assert!(!updated_tree.root_node().has_error()); // Inspect node types from embedded node-types.json let node_types: serde_json::Value = serde_json::from_str(tree_sitter_java::NODE_TYPES).unwrap(); println!("Node type count: {}", node_types.as_array().unwrap().len()); // Use highlight queries println!("Highlights query length: {}", tree_sitter_java::HIGHLIGHTS_QUERY.len()); println!("Tags query length: {}", tree_sitter_java::TAGS_QUERY.len()); } ``` -------------------------------- ### Basic Java Comment Syntax Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/comments.txt Illustrates the basic syntax for single-line and multi-line comments in Java. ```java // This is a comment /* This is also a comment */ /* this comment /* // /** ends here: */ /**/ a /* dkjfhsdf + */ + b; /* ***** */ ``` -------------------------------- ### Java Record Pattern Matching Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates the structure of record pattern matching within instanceof expressions in Java. ```java if (bbs instanceof Box(Box(var s))) { } ``` -------------------------------- ### Swift: Tree-sitter Java Integration Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Shows how to integrate the TreeSitterJava Swift package with SwiftTreeSitter for parsing Java code. It demonstrates setting up the parser, parsing source code, and navigating the resulting syntax tree. ```swift import XCTest import SwiftTreeSitter import TreeSitterJava // Set up parser let parser = Parser() let language = Language(language: tree_sitter_java()) try! parser.setLanguage(language) let source = """ public class Fibonacci { public static int fib(int n) { if (n <= 1) return n; return fib(n - 1) + fib(n - 2); } } """ // Parse source let tree = parser.parse(source)! let root = tree.rootNode! print(root.nodeType!) // program print(root.hasError) // false // Navigate to the method declaration let classDecl = root.child(at: 0)! let classBody = classDecl.child(named: "body")! let methodDecl = classBody.child(at: 1)! print(methodDecl.nodeType!) // method_declaration // Convert source range to Swift String range let methodRange = methodDecl.range print("Method source range:", methodRange) ``` -------------------------------- ### Single Element Annotation in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates a class with single-element annotations. Ensure the annotation processor is configured correctly. ```java @Duck(waddle.swim) @SuppressWarnings("unchecked") class Quack { } ``` -------------------------------- ### Lambda Expressions in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates basic lambda expressions. These are concise ways to represent anonymous functions. ```java version -> create; (record, b) -> record + b; ``` -------------------------------- ### Java Switch Statement with Pattern Matching Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates a Java switch statement utilizing pattern matching with a record pattern. ```java switch (s) { case Rectangle r: return 2; } ``` -------------------------------- ### Switch Expressions in Binary Expressions Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates the use of switch expressions within a binary expression. Ensure the switch expressions are correctly formed and return values compatible with the binary operation. ```java class Test { int i; static void foo(int i, int j) { // switch expressions inside of a binary expression int x = switch (i) { default -> 1; } + switch (j) { default -> 2; }; } } ``` -------------------------------- ### Local Variable Declarations in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Demonstrates local variable declarations with integral and boolean types, including initialization with a decimal integer literal and a boolean literal. ```tree-sitter-java (block (local_variable_declaration (integral_type) (variable_declarator (identifier) (decimal_integer_literal))) (local_variable_declaration (type_identifier) (variable_declarator (identifier) (false)))) ``` -------------------------------- ### Sealed classes and interfaces Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Shows the syntax for sealed interfaces and classes, defining permitted subclasses or implementations. ```java sealed interface A permits B, C { } final class B implements A {} non-sealed interface C extends A {} ``` ```tree-sitter-grammar (program (interface_declaration (modifiers) (identifier) (permits (type_list (type_identifier) (type_identifier))) (interface_body)) (class_declaration (modifiers) (identifier) (super_interfaces (type_list (type_identifier))) (class_body)) (interface_declaration (modifiers) (identifier) (extends_interfaces (type_list (type_identifier))) (interface_body))) ``` -------------------------------- ### Switch Statement and Pre-increment Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates a basic switch statement with a default case and a pre-increment operation. Note that the switch statement here does not return a value, unlike switch expressions. ```java class Test { int i; static void foo(boolean bar) { int ddsd; switch(bar) { default: i = 3; } ++ddsd; } } ``` -------------------------------- ### Method Reference Expressions in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates different forms of method references in Java, such as those referencing instance methods, static methods, or constructors. These are parsed into specific Tree-sitter node structures. ```tree-sitter (identifier) (method_reference (identifier) (identifier)))) (expression_statement (method_reference (field_access (identifier) (identifier)) (identifier))) (expression_statement (method_reference (array_type (type_identifier) (dimensions)))) (expression_statement (method_reference (generic_type (type_identifier) (type_arguments (type_identifier))) (identifier))) (expression_statement (method_reference (super) (identifier)))) ``` -------------------------------- ### Java Class with Annotation and Method Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Illustrates a Java class declaration containing a method with an assignment expression involving an object creation with a marker annotation. ```java public class Anno { public void anno() { this.ABCâ = new @Anno Point(); } } ``` ```tree-sitter-java (program (class_declaration (modifiers) (identifier) (class_body (method_declaration (modifiers) (void_type) (identifier) (formal_parameters) (block (expression_statement (assignment_expression (field_access (this) (identifier)) (object_creation_expression (marker_annotation (identifier)) (type_identifier) (argument_list)))))))) ``` -------------------------------- ### Local Array Variable Declarations in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Illustrates declarations for local array variables, including initializing from method calls and creating arrays with specified dimensions. The grammar captures array types and creation expressions. ```java String[] nodeNames = internalCluster().getNodeNames(); Integer[][] inputArrays = new Integer[0x100][]; ``` ```tree-sitter-grammar (program (local_variable_declaration type: (array_type element: (type_identifier) dimensions: (dimensions)) declarator: (variable_declarator name: (identifier) value: (method_invocation object: (method_invocation name: (identifier) arguments: (argument_list)) name: (identifier) arguments: (argument_list)))) (local_variable_declaration type: (array_type element: (type_identifier) dimensions: (dimensions)) declarator: (variable_declarator name: (identifier) value: (array_creation_expression type: (type_identifier) dimensions: (dimensions_expr (hex_integer_literal)) dimensions: (dimensions))))) ``` -------------------------------- ### Run Symbol Tagging Query (Python) Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Parses Java source code using tree-sitter and extracts symbol definitions and references using the tags query. Requires tree-sitter and tree-sitter-java Python packages. ```python import tree_sitter import tree_sitter_java JAVA_LANGUAGE = tree_sitter.Language(tree_sitter_java.language()) parser = tree_sitter.Parser(JAVA_LANGUAGE) source = b""" public interface Printable { void print(); } public class Document implements Printable { private String content; public Document(String content) { this.content = content; } @Override public void print() { System.out.println(content); } } public class Main { public static void main(String[] args) { Document doc = new Document("Hello"); doc.print(); } } """ tree = parser.parse(source) # Run the tags query to extract symbol definitions and references tags_query = tree_sitter.Query(JAVA_LANGUAGE, tree_sitter_java.TAGS_QUERY) matches = tags_query.matches(tree.root_node) for _, match in matches: for capture_name, nodes in match.items(): for node in (nodes if isinstance(nodes, list) else [nodes]): print(f"{capture_name:30s} {node.text.decode()!r:25s} line {node.start_point[0]+1}") # definition.interface 'Printable' line 2 # definition.class 'Document' line 6 # definition.method 'print' line 14 # reference.implementation 'Printable' line 6 # reference.call '(content)' line 22 ``` -------------------------------- ### Java Spread Parameter with Annotation Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates a Java method signature with a spread parameter annotated with '@Foo'. This syntax is used for varargs with annotations. ```java void foo(int... @Foo x) { } ``` ```tree-sitter-grammar (program (method_declaration (void_type) (identifier) (formal_parameters (spread_parameter (integral_type) (marker_annotation (identifier)) (variable_declarator (identifier)))) (block))) ) ``` -------------------------------- ### Binary Expression Parsing in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates the parsing of a binary expression involving parentheses and nested operations. This highlights how Tree-sitter represents operator precedence and grouping. ```java (a & b) + c; ``` ```tree-sitter (program (expression_statement (binary_expression (parenthesized_expression (binary_expression (identifier) (identifier))) (identifier)))) ``` -------------------------------- ### Java Module with Normal Annotation Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Demonstrates a Java module declaration with a normal annotation, including various element-value pairs. The grammar parses annotations with identifiers and argument lists. ```java @RequestForEnhancement( id = 2868724, synopsis = "Provide time-travel functionality", engineer = "Mr. Peabody", date = "4/1/2004" ) module com.foo { } ``` ```tree-sitter-grammar (program (module_declaration (annotation (identifier) (annotation_argument_list (element_value_pair (identifier) (decimal_integer_literal)) (element_value_pair (identifier) (string_literal (string_fragment))) (element_value_pair (identifier) (string_literal (string_fragment))) (element_value_pair (identifier) (string_literal (string_fragment))))) ``` -------------------------------- ### Annotation Following Type Arguments in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Shows a Java constructor declaration with annotations applied to type arguments and generic type parameters, including a null literal in the argument list. ```java public class A { public B() { return new <@BG Inner> @BH Inner<@BI Inner>(null); } } ``` ```tree-sitter-java (program (class_declaration (modifiers) (identifier) (class_body (constructor_declaration (modifiers) (identifier) (formal_parameters) (constructor_body (return_statement (object_creation_expression (type_arguments (annotated_type (marker_annotation (identifier)) (type_identifier))) (marker_annotation (identifier)) (generic_type (type_identifier) (type_arguments (annotated_type (marker_annotation (identifier)) (type_identifier)))) (argument_list (null_literal))))))))) ``` -------------------------------- ### For loop with method calls Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Presents a for loop where initialization, condition, and update are all method invocations. The loop body also contains a method invocation with an argument. ```java for (j.init(i); j.check(); j.update()) { System.out.println(j); } ``` ```tree-sitter-grammar (program (for_statement init: (method_invocation object: (identifier) name: (identifier) arguments: (argument_list (identifier))) condition: (method_invocation object: (identifier) name: (identifier) arguments: (argument_list)) update: (method_invocation object: (identifier) name: (identifier) arguments: (argument_list)) body: (block (expression_statement (method_invocation object: (field_access object: (identifier) field: (identifier)) name: (identifier) arguments: (argument_list (identifier))))))) ``` -------------------------------- ### Java Switch Statement Parsing Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates the tree-sitter grammar for parsing Java switch statements with arrow syntax. ```java class Test { int i; int f(int i) { return 0; } void main() { switch (f(i)) { case 0, 1 -> System.out.println(6); case 2 -> System.out.println(7); } } } ``` -------------------------------- ### Enhanced for loop (for-each) Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates the enhanced for loop syntax for iterating over collections or arrays. It simplifies iteration by abstracting away index management. ```java for (A b : c) { d(b); } ``` ```tree-sitter-grammar (program (enhanced_for_statement (type_identifier) (identifier) (identifier) (block (expression_statement ``` -------------------------------- ### Java Class with Type Arguments Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates a Java class declaration with a generic type parameter. ```java class Box { private T theObject; public Box( T arg) { theObject = arg; } // more code } ``` -------------------------------- ### Java Try-with-Resources Statement Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates the try-with-resources statement for automatic resource management. Resources declared in the try statement are automatically closed. ```java try (FileInputStream input = new FileInputStream("file.txt")) { int data = input.read(); } ``` -------------------------------- ### Record declaration implementing an interface Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Illustrates a Java record declaration that explicitly implements an interface. ```java record R() implements I {} ``` ```tree-sitter-grammar (program (record_declaration (identifier) (formal_parameters) (super_interfaces (type_list (type_identifier))) (class_body))) ``` -------------------------------- ### Record declaration with compact constructor Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Shows a Java record with a compact constructor that includes validation logic. ```java record Person(int age) { public Person { if (age < 0) throw new IllegalArgumentException("invalid age"); } } ``` ```tree-sitter-grammar (program (record_declaration (identifier) (formal_parameters (formal_parameter (integral_type) (identifier))) (class_body (compact_constructor_declaration (modifiers) (identifier) (block (if_statement (parenthesized_expression (binary_expression (identifier) (decimal_integer_literal))) (throw_statement (object_creation_expression (type_identifier) (argument_list (string_literal (string_fragment))))))))))) ``` -------------------------------- ### Method Invocation with Arguments in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Represents a method invocation with a list of arguments, including decimal integer literals. ```tree-sitter-java (expression_statement (method_invocation (identifier) (argument_list (decimal_integer_literal) (decimal_integer_literal)))) ``` -------------------------------- ### Instanceof Expressions Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates the parsing of 'instanceof' checks, including variations with scoped types, generic types, array types, and inline type declarations. ```java a instanceof C.D; ``` ```java a instanceof List; ``` ```java c instanceof C[]; ``` ```java c instanceof C foo; ``` ```java d instanceof final D bar; ``` ```tree-sitter-grammar (program (expression_statement (instanceof_expression (identifier) (scoped_type_identifier (type_identifier) (type_identifier))))) (expression_statement (instanceof_expression (identifier) (generic_type (type_identifier) (type_arguments (type_identifier))))) (expression_statement (instanceof_expression (identifier) (array_type (type_identifier) (dimensions))))) (expression_statement (instanceof_expression (identifier) (type_identifier) (identifier))) (expression_statement (instanceof_expression (identifier) (type_identifier) (identifier)))) ``` -------------------------------- ### Module Directive Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Defines a Java module and its dependencies. ```java module com.example.foo { requires com.example.foo.http; } ``` ```java (program (module_declaration name: (scoped_identifier scope: (scoped_identifier scope: (identifier) name: (identifier)) name: (identifier)) body: (module_body (requires_module_directive module: (scoped_identifier scope: (scoped_identifier scope: (scoped_identifier scope: (identifier) name: (identifier)) name: (identifier)) name: (identifier)))))) ``` -------------------------------- ### If-then-else statement with blocks Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates a standard if-then-else structure with both the consequence and alternative enclosed in blocks. This is the recommended way to write conditional logic in Java. ```java if (x = 3) { y = 9; } else { y = 0; } ``` ```tree-sitter-grammar (program (if_statement condition: (parenthesized_expression (assignment_expression left: (identifier) right: (decimal_integer_literal))) consequence: (block (expression_statement (assignment_expression left: (identifier) right: (decimal_integer_literal)))) alternative: (block (expression_statement (assignment_expression left: (identifier) right: (decimal_integer_literal)))))) ``` -------------------------------- ### Class Declaration with Modifiers and Superclass Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Demonstrates class declarations with access modifiers (public, private, abstract) and extending a superclass. Use `extends` keyword for inheritance. ```java public class Point { } ``` ```java private class Point { } ``` ```java abstract class ColoredPoint extends Point { } ``` ```tree-sitter-java (program (class_declaration (modifiers) (identifier) (class_body)) (class_declaration (modifiers) (identifier) (class_body)) (class_declaration (modifiers) (identifier) (superclass (type_identifier)) (class_body))) ``` -------------------------------- ### Parse Java Integer Literal Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/comments.txt Demonstrates the parsing of a decimal integer literal in Java. ```java 123; // comment ``` -------------------------------- ### Java Module Declarations Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Shows basic Java module declarations, including standard and 'open' modules. The grammar represents module declarations with scoped identifiers and module bodies. ```java module com.foo { } open module com.foo { } ``` ```tree-sitter-grammar (program (module_declaration name: (scoped_identifier scope: (identifier) name: (identifier)) body: (module_body)) (module_declaration name: (scoped_identifier scope: (identifier) name: (identifier)) body: (module_body))) ``` -------------------------------- ### Pattern Matching with instanceof Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Shows various forms of pattern matching using the `instanceof` operator in Java. This includes matching against record patterns and extracting variables. ```java public class Patterns { static void patterns() { Rectangle r = new Rectangle(new ColoredPoint(c1), new ColoredPoint(c2)); if (obj instanceof Point(int x)) { } if (r instanceof Rectangle(ColoredPoint ul)) { } if (r instanceof Rectangle(ColoredPoint(Point p, Color c), ColoredPoint lr)) { } if (r instanceof Rectangle(ColoredPoint(Point(var x, var y), var c), var lr)) { } } } ``` -------------------------------- ### Package Declaration Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Represents a Java package declaration. ```java (package_declaration (identifier))) ``` -------------------------------- ### Module Directive with Exports, Opens, Uses, and Provides Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt A comprehensive Java module declaration including requires, exports, opens, uses, and provides directives. ```java module com.example.foo { requires com.example.http; requires java.logging; requires transitive com.example.network; exports com.example.bar; exports com.example.internal to com.example.probe; opens com.example.quux; opens com.example.internal to com.example.network, com.example.probe; uses com.example.Intf; provides com.example.Intf with com.example.Impl; } ``` ```java (program (module_declaration (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier)) (module_body (requires_module_directive (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier))) (requires_module_directive (scoped_identifier (identifier) (identifier))) (requires_module_directive (requires_modifier) (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier))) (exports_module_directive (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier))) (exports_module_directive (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier)) (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier))) (opens_module_directive (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier))) (opens_module_directive (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier)) (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier)) (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier))) (uses_module_directive (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier))) (provides_module_directive (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier)) (scoped_identifier (scoped_identifier (identifier) (identifier)) (identifier)))))) ``` -------------------------------- ### Parse Java Source Code with Node.js Binding Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt Use the Node.js binding to parse Java source code into a concrete syntax tree. This snippet demonstrates setting up the parser, parsing a Java string, and traversing the resulting tree to extract information like node types and field values. It also shows how to recursively find method declarations. ```javascript const Parser = require("tree-sitter"); const Java = require("tree-sitter-java"); const parser = new Parser(); parser.setLanguage(Java); const sourceCode = "` import java.util.List; public class Greeter { private final String name; public Greeter(String name) { this.name = name; } public String greet() { return \"Hello, " + name + "!\"; } public static void main(String[] args) { Greeter g = new Greeter(\"World\"); System.out.println(g.greet()); // Hello, World! } } `; const tree = parser.parse(sourceCode); const root = tree.rootNode; console.log(root.type); // "program" console.log(root.hasError()); // false console.log(root.child(0).type); // "import_declaration" console.log(root.child(1).type); // "class_declaration" console.log(root.child(1).childForFieldName("name").text); // "Greeter" // Walk all method declarations function findMethods(node) { if (node.type === "method_declaration") { const nameNode = node.childForFieldName("name"); console.log("Method:", nameNode.text, "at line", node.startPosition.row + 1); } for (const child of node.children) findMethods(child); } findMethods(root); // Method: greet at line 9 // Method: main at line 13 ``` -------------------------------- ### Record Declaration Inside a Class Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Demonstrates nesting a record declaration within a class. The nested record 'Commande' has a constructor and a method. ```java public class Usecase { public static record Commande(@NotNull String param) { public Commande foo() { return new Commande(""); } } } ``` -------------------------------- ### Tree-sitter Grammar for Java Method References Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Represents the Tree-sitter node structure for various Java method reference syntaxes. ```tree-sitter-grammar (program (expression_statement (assignment_expression ``` -------------------------------- ### Annotation in Array Creation Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Shows how to use annotations within an array creation expression. This is useful for marking array elements or types. ```java String[] allMyStrings = new @Nullable String[5]; ``` -------------------------------- ### Method Declaration with Parameters Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Declares a method within a class, including its return type, name, and parameters. Parameters are defined by type and name within parentheses. ```java class Beyonce { void calculateAnswer(double wingSpan, int numberOfEngines, double length, double grossTons) { //do the calculation here } } ``` ```tree-sitter-java (program (class_declaration (identifier) (class_body (method_declaration (void_type) (identifier) (formal_parameters (formal_parameter (floating_point_type) (identifier)) (formal_parameter (integral_type) (identifier)) (formal_parameter (floating_point_type) (identifier)) (formal_parameter (floating_point_type) ``` -------------------------------- ### Java Constructor Declaration Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Demonstrates parsing of constructor declarations, including overloaded constructors and explicit constructor invocations using 'this'. ```java class Point { int x, y; Point(int x, int y) { this.x = x; this.y = y; } Point() { this(0, 0); } } ``` ```tree-sitter-java (program (class_declaration name: (identifier) body: (class_body (field_declaration type: (integral_type) declarator: (variable_declarator name: (identifier))) (field_declaration type: (integral_type) declarator: (variable_declarator name: (identifier))) (constructor_declaration name: (identifier) parameters: (formal_parameters (formal_parameter type: (integral_type) name: (identifier)) (formal_parameter type: (integral_type) name: (identifier))) body: (constructor_body (expression_statement (assignment_expression left: (field_access object: (this) field: (identifier)) right: (identifier))) (expression_statement (assignment_expression left: (field_access object: (this) field: (identifier)) right: (identifier))))) (constructor_declaration name: (identifier) parameters: (formal_parameters) body: (constructor_body (explicit_constructor_invocation constructor: (this) arguments: (argument_list (decimal_integer_literal) (decimal_integer_literal)))))))) ``` -------------------------------- ### Basic Class Declaration Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Declares a simple class with no members. Use `class` keyword followed by the class name and an empty body. ```java class Point { } ``` ```tree-sitter-java (program (class_declaration (identifier) (class_body))) ``` -------------------------------- ### Java Traditional Switch Expression Parsing Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates the tree-sitter grammar for traditional Java switch expressions with yield statements. ```java class Test { int d = 3; static final int NUM = 2; void main() { int result = switch (d) { case 5 + 6: yield 1; case NUM: yield 2; default: System.out.println("hmmm..."); yield 0; }; } } ``` -------------------------------- ### Record declaration inside an interface Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Demonstrates the syntax for declaring a record type within a Java interface. ```java interface I { record R(int a) {} } ``` ```tree-sitter-grammar (program (interface_declaration (identifier) (interface_body (record_declaration (identifier) (formal_parameters (formal_parameter (integral_type) (identifier))) (class_body))))) ``` -------------------------------- ### Nested Receiver Parameter in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Illustrates parsing of a nested class constructor with a receiver parameter that includes nested types. ```java public class Inner1 { public class Inner2 { public class Inner3 { public Inner3(GetAnnotatedReceiverType.Inner1.Inner2 GetAnnotatedReceiverType.Inner1.Inner2.this) {} } } } ``` ```tree-sitter-java (program (class_declaration (modifiers) (identifier) (type_parameters (type_parameter (type_identifier))) (class_body (class_declaration (modifiers) (identifier) (class_body (class_declaration (modifiers) (identifier) (class_body (constructor_declaration (modifiers) (identifier) (formal_parameters (receiver_parameter (scoped_type_identifier (generic_type (scoped_type_identifier (type_identifier) (type_identifier)) (type_arguments (type_identifier))) (type_identifier)) (identifier) (identifier) (identifier) (this))) (constructor_body))))))))) ``` -------------------------------- ### Parse Java Literals and Comments Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/comments.txt Shows how Tree-sitter parses a simple Java program containing a literal and a comment. ```tree-sitter grammar (program (expression_statement (decimal_integer_literal)) (line_comment)) ``` -------------------------------- ### Local Variable Declaration in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Demonstrates a simple local variable declaration within a Java method. The grammar shows the structure for integral types and variable declarators. ```java class A { public int b() { int c = 5; } } ``` ```tree-sitter-grammar (program (class_declaration name: (identifier) body: (class_body (method_declaration (modifiers) type: (integral_type) name: (identifier) parameters: (formal_parameters) body: (block (local_variable_declaration type: (integral_type) declarator: (variable_declarator name: (identifier) value: (decimal_integer_literal)))))))) ``` -------------------------------- ### Java Class with Wildcard Type Argument Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Illustrates a Java field declaration using a wildcard type argument. ```java class WildcardDemo { List a; } ``` -------------------------------- ### Java Module with Marker Annotation Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Shows Java module declarations using marker annotations, which do not have arguments. The grammar distinguishes marker annotations from regular annotations. ```java @Preliminary module com.foo { } @Preliminary open module com.foo { } ``` ```tree-sitter-grammar (program (module_declaration (marker_annotation (identifier)) (scoped_identifier (identifier) (identifier)) (module_body)) (module_declaration (marker_annotation (identifier)) (scoped_identifier (identifier) (identifier)) (module_body))) ``` -------------------------------- ### Switch with Qualified Enum Constant in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Demonstrates a Java switch statement using qualified enum constants (e.g., Coin.HEADS). This shows how Tree-sitter parses enum references within switch cases. ```java switch (c) { case Coin.HEADS -> { } case Coin.TAILS -> { } } ``` -------------------------------- ### Tree Sitter Query for Java Class Declaration Source: https://context7.com/tree-sitter/tree-sitter-java/llms.txt A Tree Sitter query demonstrating the structure of a Java class declaration with generic type parameters. This query can be used for parsing and analysis. ```tree-sitter-query (program (class_declaration name: (identifier) type_parameters: (type_parameters (type_parameter (type_identifier)) (type_parameter (type_identifier))) body: (class_body (field_declaration type: (type_identifier) declarator: (variable_declarator name: (identifier))) (field_declaration type: (type_identifier) declarator: (variable_declarator name: (identifier)))))) ``` -------------------------------- ### Type Import on Declaration (Wildcard) Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/declarations.txt Imports all classes from a specific package using a wildcard. ```java import java.util.*; ``` ```java (program (import_declaration (scoped_identifier (identifier) (identifier)) (asterisk))) ``` -------------------------------- ### String Interpolation in Java Source: https://github.com/tree-sitter/tree-sitter-java/blob/master/test/corpus/expressions.txt Covers various forms of string interpolation in Java, including simple template expressions, expressions with embedded code, and multiline string templates. This shows how different interpolation syntaxes are parsed. ```java STR."Hello There"; STR."Hello \{x + y}"; STR."We can have \{many(of)} \{them.in} a \{row}"; compPass(""" StringTemplate result = RAW.\"\"\" \\{} \""""; """); ``` ```tree-sitter (program (expression_statement (template_expression (identifier) (string_literal (string_fragment)))) (expression_statement (template_expression (identifier) (string_literal (string_fragment) (string_interpolation (binary_expression (identifier) (identifier)))))) (expression_statement (template_expression (identifier) (string_literal (string_fragment) (string_interpolation (method_invocation (identifier) (argument_list (identifier)))) (string_fragment) (string_interpolation (field_access (identifier) (identifier))) (string_fragment) (string_interpolation (identifier))))) (expression_statement (method_invocation (identifier) (argument_list (string_literal (multiline_string_fragment) (escape_sequence) (multiline_string_fragment) (multiline_string_fragment) (escape_sequence) (multiline_string_fragment) (escape_sequence) (multiline_string_fragment) (multiline_string_fragment)))))) ```