java-parser

3.0.1 · active · verified Sun Apr 19

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

Warnings

Install

Imports

Quickstart

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}`));
    }
}

view raw JSON →