1.0.1 • Published 2 years ago

parser-java v1.0.1

Weekly downloads
-
License
MIT
Repository
-
Last release
2 years ago

parser-java: A Java parser for JavaScript/TypeScript

Example

The following code parses a Java program stored in the variable program and prints the result.

import { exit } from 'process';
import { parse, traverseNonterminals } from 'parser-java';

const program = `
class Foo {
  public static int main(String[] args) {
    return (1+2-3)*4/5;
  }
}
`;

const parseTree = parse(program);
if (parseTree instanceof Error) {
  console.log(parseTree.message);
  exit(1);
}

traverseNonterminals(parseTree, (node) => {
  const start = node.range.start;
  const end = node.range.end;
  console.log(node.symbol, (node.childNodes[0] as Object).constructor.name, {
    start: `(${start.line}, ${start.column})`,
    end: `(${end.line}, ${end.column})`,
  });
});

The above code prints the following output.

Spacing NodeZeroOrMore { start: '(1, 1)', end: '(2, 1)' }
CompilationUnit NodeSequence { start: '(2, 1)', end: '(7, 1)' }
TypeDeclaration NodeOrderedChoice { start: '(2, 1)', end: '(7, 1)' }
ClassDeclaration NodeOrderedChoice { start: '(2, 1)', end: '(7, 1)' }
NormalClassDeclaration NodeSequence { start: '(2, 1)', end: '(7, 1)' }
CLASS NodeSequence { start: '(2, 1)', end: '(2, 7)' }
Spacing NodeZeroOrMore { start: '(2, 6)', end: '(2, 7)' }
Identifier NodeSequence { start: '(2, 7)', end: '(2, 11)' }
Letter NodeOrderedChoice { start: '(2, 7)', end: '(2, 8)' }
LetterOrDigit NodeOrderedChoice { start: '(2, 8)', end: '(2, 9)' }
LetterOrDigit NodeOrderedChoice { start: '(2, 9)', end: '(2, 10)' }
Spacing NodeZeroOrMore { start: '(2, 10)', end: '(2, 11)' }
ClassBody NodeSequence { start: '(2, 11)', end: '(7, 1)' }
LWING NodeSequence { start: '(2, 11)', end: '(3, 3)' }
...
RWING NodeSequence { start: '(5, 3)', end: '(6, 1)' }
Spacing NodeZeroOrMore { start: '(5, 4)', end: '(6, 1)' }
RWING NodeSequence { start: '(6, 1)', end: '(7, 1)' }
Spacing NodeZeroOrMore { start: '(6, 2)', end: '(7, 1)' }
EOT NodeNot { start: '(7, 1)', end: '(7, 1)' }

Installation

To install, run:

$ npm install parser-java

Contributing

License

parser-java is available as open-source under the terms of the MIT License.