George
George

Reputation: 120

JavaScript: Parse Java source code, extract method

I'm trying to build a module that returns all methods of a given Java source code using nodeJs. So far I can get the AST tree built using "java-parser" module but I need to traverse it to filter out methods.

 code = ' public class CallingMethodsInSameClass
 {
    public static void main(String[] args) {
        printOne();
        printOne();
        printTwo();
 }
 public static void printOne() {
    System.out.println("Hello World");
 }

 public static void printTwo() {
    printOne();
    printOne();
} }';

var javaParser = require("java-parser");
var traverse = require("babel-traverse").default;
var methodsList = [];
traverse(ast, {
  enter(path){
  //do extraction
  }
}

I understand that babel-traverse is for Js but I wanted a way to traverse so I can filter the methods. I'm getting this error

throw new Error(messages.get("traverseNeedsParent", parent.type));
  ^

 Error: You must pass a scope and parentPath unless traversing a 
 Program/File. Instead of that you tried to traverse a undefined node 
 without passing scope and parentPath.

The AST if logged looks like

{ node: 'CompilationUnit',
  types: 
   [ { node: 'TypeDeclaration',
       name: [Object],
       superInterfaceTypes: [],
       superclassType: null,
       bodyDeclarations: [Array],
       typeParameters: [],
       interface: false,
       modifiers: [Array] } ],
  package: null,
  imports: [] }

where a method will be identified by "MethodDeclaration" within types. Any help is appreciated.

Upvotes: 0

Views: 1398

Answers (1)

xiaofeng.li
xiaofeng.li

Reputation: 8587

The AST is just another JSON object. Try jsonpath.

npm install jsonpath

To extract all methods, just filter on condition node=="MethodDeclaration":

var jp = require('jsonpath');
var methods = jp.query(ast, '$.types..[?(@.node=="MethodDeclaration")]');
console.log(methods);

See here for more JSON path syntax.

Upvotes: 3

Related Questions