0

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.