2.3.0 • Published 2 months ago

java-parser v2.3.0

Weekly downloads
39,894
License
Apache-2.0
Repository
github
Last release
2 months ago

npm

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);
// explore the CST

Traversing the CST

See relevant Chevrotain documentation on CST Traversal.

const {
  BaseJavaCstVisitor,
  BaseJavaCstVisitorWithDefaults
} = require("java-parser");

// Use "BaseJavaCstVisitor" if you need to implement all the visitor methods yourself.
class LambdaArrowsPositionCollector extends BaseJavaCstVisitorWithDefaults {
  constructor() {
    super();
    this.customResult = [];
    this.validateVisitor();
  }

  lambdaExpression(ctx) {
    // Collects all the starting offsets of lambda arrows in lambdas with short (no parenthesis)
    // single argument lists: e.g:
    // - n -> n*n (will be collected)
    // - (n) -> n*n (not collected)
    if (ctx.lambdaParameters[0].children.Identifier) {
      this.customResult.push(ctx.Arrow[0].startOffset);
    }
  }
}

const lambdaArrowsCollector = new LambdaArrowsPositionCollector();
// The CST result from the previous code snippet
lambdaArrowsCollector.visit(cst);
lambdaArrowsCollector.customResult.forEach(arrowOffset => {
  console.log(arrowOffset);
});
2.3.0

2 months ago

2.2.0

5 months ago

2.1.0

6 months ago

2.0.5

8 months ago

2.0.4

1 year ago

2.0.3

1 year ago

2.0.2

2 years ago

2.0.1

2 years ago

2.0.0

3 years ago

1.4.0

3 years ago

1.3.1

3 years ago

1.2.0

3 years ago

1.1.1

3 years ago

1.1.0

3 years ago

1.0.2

3 years ago

1.0.0

3 years ago

0.8.1

4 years ago

0.8.2

4 years ago

0.8.0

4 years ago

0.7.1

4 years ago

0.7.0

4 years ago

0.6.0

4 years ago

0.5.1

4 years ago

0.5.0

4 years ago

0.4.0

5 years ago

0.3.2

5 years ago

0.3.1

5 years ago

0.2.0

5 years ago

0.1.3

5 years ago

0.1.2

5 years ago

0.0.2

8 years ago

0.0.1

8 years ago