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-parserVerified import paths — ran on the pinned version, not inferred.
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`.
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.
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.
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.
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.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.
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.