Expand description
ยง๐ ๏ธ Java Parser Developer Guide
This guide is designed to help you quickly get started with developing and integrating oak-java.
ยง๐ฆ Quick Start
ยงBasic Parsing Example
The following is a standard workflow for parsing a Java class with modern features like Records and Annotations:
use oak_java::{JavaParser, SourceText, JavaLanguage};
fn main() {
// 1. Prepare source code
let code = r#"
package com.example;
import java.util.List;
/**
* Represents a user in the system.
*/
@Entity
public record User(String name, int age) {
public void greet() {
System.out.println("Hello, " + name);
}
}
"#;
let source = SourceText::new(code);
// 2. Initialize parser
let config = JavaLanguage::new();
let parser = JavaParser::new(&config);
// 3. Execute parsing
let result = parser.parse(&source);
// 4. Handle results
if result.is_success() {
println!("Parsing successful! AST node count: {}", result.node_count());
} else {
eprintln!("Errors found during parsing.");
}
}ยง๐ Core API Usage
ยง1. Syntax Tree Traversal
After a successful parse, you can use the built-in visitor pattern or manually traverse the Green/Red Tree to extract Java-specific constructs like class/record definitions, annotations, or complex method bodies.
ยง2. Incremental Parsing
No need to re-parse the entire source file when small changes occur:
// Assuming you have an old parse result 'old_result' and new source text 'new_source'
let new_result = parser.reparse(&new_source, &old_result);ยง3. Diagnostics
oak-java provides rich error contexts specifically tailored for Java developers, handling complex scenarios like missing semicolons or malformed annotations:
for diag in result.diagnostics() {
println!("[{}:{}] {}", diag.line, diag.column, diag.message);
}ยง๐๏ธ Architecture Overview
- Lexer: Tokenizes Java source text into a stream of tokens, handling keywords, operators, literals, and support for Unicode identifiers.
- Parser: Syntax analyzer based on the Pratt parsing algorithm to handle Javaโs expression precedence, structural declarations, and modern language features.
- AST: A strongly-typed syntax abstraction layer designed for high-performance Java analysis tools, IDEs, and refactoring engines.
ยง๐ Advanced Resources
Re-exportsยง
pub use crate::ast::JavaRoot;pub use crate::builder::JavaBuilder;pub use crate::language::JavaLanguage;pub use crate::lexer::JavaLexer;pub use crate::parser::JavaParser;pub use crate::lsp::highlighter::JavaHighlighter;pub use crate::lsp::JavaLanguageService;pub use crate::mcp::serve_java_mcp;pub use lexer::token_type::JavaTokenType;pub use parser::element_type::JavaElementType;