java-parser
A Java Parser implemented in JavaScript using the Chevrotain Parsing ToolKit.
It outputs a Concrete Syntax Tree, rather than an Abstract Syntax Tree.
Currently the main focus of this project is to be used in implementing a prettier Java plugin.
But it could also be used as the basis for other Java related tools in the JavaScript ecosystem.
Installation
npm install java-parser --save-dev
or
yarn add java-parser --dev
Usage
Parsing
const { parse } = require("java-parser");
const javaText = `
public class HelloWorldExample{
public static void main(String args[]){
System.out.println("Hello World !");
}
}
`;
const cst = parse(javaText);
Traversing the CST
See relevant Chevrotain documentation on CST Traversal.
const {
BaseJavaCstVisitor,
BaseJavaCstVisitorWithDefaults
} = require("java-parser");
class LambdaArrowsPositionCollector extends BaseJavaCstVisitorWithDefaults {
constructor() {
super();
this.customResult = [];
this.validateVisitor();
}
lambdaExpression(ctx) {
if (ctx.lambdaParameters[0].children.Identifier) {
this.customResult.push(ctx.Arrow[0].startOffset);
}
}
}
const lambdaArrowsCollector = new LambdaArrowsPositionCollector();
lambdaArrowsCollector.visit(cst);
lambdaArrowsCollector.customResult.forEach(arrowOffset => {
console.log(arrowOffset);
});