java-parser
TypeScript icon, indicating that this package has built-in type declarations

2.3.3 • Public • Published

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

Versions

Current Tags

VersionDownloads (Last 7 Days)Tag
2.3.345,233latest

Version History

VersionDownloads (Last 7 Days)Published
2.3.345,233
2.3.238,442
2.3.13
2.3.04,505
2.2.076,744
2.1.0197
2.0.55,276
2.0.47,663
2.0.32,107
2.0.26,649
2.0.12,050
2.0.01,327
1.4.01,136
1.3.176
1.2.01,198
1.1.1123
1.1.0519
1.0.211,680
1.0.067
0.8.23,922
0.8.16
0.8.0186
0.7.1784
0.7.0605
0.6.053
0.5.17
0.5.06
0.4.023
0.3.216
0.3.19
0.2.05
0.1.35
0.1.25
0.0.2102
0.0.15

Package Sidebar

Install

npm i java-parser

Weekly Downloads

210,734

Version

2.3.3

License

Apache-2.0

Unpacked Size

261 kB

Total Files

20

Last publish

Collaborators

  • jdubois
  • deepu105
  • pascalgrimaud
  • cdessoude
  • jtkiesel