java-parser
java-parser is a JavaScript-based parser for Java source code, designed to operate without a JVM. It takes Java code as input and produces a Concrete Syntax Tree (CST) using the Chevrotain parsing toolkit. The current stable version is 3.0.1. While it is a foundational, internal component of the `prettier-plugin-java` project for formatting, it can be used independently to programmatically analyze Java code. The library offers functionality to parse raw code into a CST and then transform that CST into a more abstract AST representation. This capability makes it suitable for static analysis, code transformations, or custom tooling within JavaScript environments where JVM-based parsers are not practical or desired. Releases often align with its parent `prettier-java` monorepo updates, typically focusing on parser correctness and AST generation improvements.
Common errors
-
ReferenceError: require is not defined
cause `java-parser` is an ES Module (ESM) only package since v3, and `require()` is a CommonJS (CJS) construct.fixChange `const { parse } = require('java-parser');` to `import { parse } from 'java-parser';`. Ensure your environment (e.g., Node.js project) is configured for ESM, typically by adding `"type": "module"` to `package.json` or using `.mjs` file extensions. -
Parsing failed: Expected token of type --> 'X' <-- but found --> 'Y' <-- at line <num>, column <num>.
cause The input Java code contains a syntax error that the parser cannot resolve, or the `java-parser` library does not support the specific Java language feature or syntax used.fixInspect the specified line and column in your Java code for syntax errors. Ensure the Java code conforms to a standard Java grammar supported by the parser. If the code is valid Java, check `java-parser`'s capabilities and reported Java language level support. -
TypeError: Cannot read properties of undefined (reading 'children') or similar AST traversal errors
cause Your code is attempting to access properties of the Abstract Syntax Tree (AST) that do not exist or have changed their structure, often due to an update to `java-parser` or `@prettier/java-ast`.fixLog the generated AST (`console.log(JSON.stringify(ast, null, 2));`) to understand its current structure. Adjust your AST traversal and manipulation logic to match the actual shape of the AST generated by `java-parser` version 3.x.x.
Warnings
- breaking Version 3.0.0 of `java-parser` transitioned to being an ES Module (ESM) only package, dropping CommonJS (CJS) support. Projects using `require()` will encounter errors unless they are configured for ESM interoperability or transpiled.
- breaking The Abstract Syntax Tree (AST) structure generated by `toAST` may have changed significantly in version 3.0.0 due to updates in the `@prettier/java-ast` dependency and internal parser logic improvements. Code relying on specific AST node shapes or properties will likely break.
- gotcha The underlying Chevrotain parsing toolkit was updated to v10 in `java-parser` v3. This major update in a core dependency could introduce subtle changes in parsing behavior, error reporting, or performance characteristics, especially for advanced users interacting directly with the Chevrotain API or AST visitors.
Install
-
npm install java-parser -
yarn add java-parser -
pnpm add java-parser
Imports
- parse
const { parse } = require('java-parser');import { parse } from 'java-parser'; - toAST
import toAST from 'java-parser/toAST';
import { toAST } from 'java-parser'; - LexingError
import { LexingError } from 'java-parser';
Quickstart
import { parse, toAST } from 'java-parser';
const javaCode = `
package com.example;
public class MyClass {
// This is a single-line comment
private String name; /* This is a multi-line comment */
public MyClass(String name) {
this.name = name;
}
public void greet() {
System.out.println("Hello, " + name + "!");
}
}
`;
try {
// Parse the Java code into a Concrete Syntax Tree (CST)
const cst = parse(javaCode);
console.log("CST Root: ", cst.name);
// console.log(JSON.stringify(cst, null, 2)); // Uncomment for full CST
// Convert the CST to an Abstract Syntax Tree (AST)
const ast = toAST(cst);
console.log("AST Root Type: ", ast.type);
// Access package name example (assuming standard AST structure)
// The exact path may vary based on AST definition.
console.log("AST Package Name: ", ast.packageDeclaration?.name?.children?.Identifier?.[0]?.image || 'N/A');
// console.log(JSON.stringify(ast, null, 2)); // Uncomment for full AST
console.log("\nSuccessfully parsed Java code and converted to AST.");
} catch (e: any) {
console.error("Parsing failed:", e.message);
if (e.errors) {
e.errors.forEach((err: any) => console.error(` - Line ${err.line}, Column ${err.column}: ${err.message}`));
}
}