Registry / serialization / java-parser

java-parser

JSON →
library3.0.1jsnpmunverified

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.

npm install java-parser
INSTALL
IMPORT
SIG · JAVA-PARSER
J
java-parser
serializationjavascriptv3.0.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

parse
import { parse } from 'java-parser';
const { parse } = require('java-parser');
The `java-parser` package is ESM-only since version 3.0.0, so CommonJS `require` statements will fail unless transpiled or run in an environment configured for ESM interoperability.
toAST
import { toAST } from 'java-parser';
import toAST from 'java-parser/toAST';
`toAST` is a named export from the main package, not a default export from a subpath. It transforms the CST produced by `parse` into an AST.
LexingError
import { LexingError } from 'java-parser';
LexingError is useful for catching and handling errors that occur during the tokenization phase of parsing.

Demonstrates how to parse a simple Java class into a Concrete Syntax Tree (CST) and then transform it into an Abstract Syntax Tree (AST) using `java-parser`.

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}`)); } }
Debug
Known issues
breakingVersion 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.
fix
Migrate your project to use ES Modules with `import` statements, or configure your build system (e.g., Webpack, Rollup) or Node.js environment to handle ESM. For Node.js, ensure your `package.json` includes `"type": "module"` or use `.mjs` file extensions.
affects: >=3.0.0
breakingThe 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.
fix
Review the `@prettier/java-ast` documentation or source code for the exact AST structure in version 3.x.x. Update any code that traverses or manipulates the AST to match the new structure. Comprehensive testing of AST consumers is recommended.
affects: >=3.0.0
gotchaThe 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.
fix
If you are extending the parser or creating custom Chevrotain visitors, review the Chevrotain v10 migration guide. Thoroughly test parsing edge cases and error scenarios after updating to `java-parser` v3.
affects: >=3.0.0
Errors
Common errors & fixes
ReferenceError: require is not defined
`java-parser` is an ES Module (ESM) only package since v3, and `require()` is a CommonJS (CJS) construct.
fix
Change `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>.
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.
fix
Inspect 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
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`.
fix
Log 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.
Upgrade
Version history
3.0.1latest on npm
Audit
Dependencies
chevrotainrequiredCore parsing engine for generating the Concrete Syntax Tree (CST).
@prettier/java-astrequiredProvides the Abstract Syntax Tree (AST) definition and transformation utilities, tightly coupled within the Prettier Java ecosystem.
Agent activity
8 hits · last 30 days
node
8
Resources
java-parser — npm install java-parser · libregistry