3

I've generated a call graph from java bytecode, and need to find closest parent of a class that generates a method. I've got a solution, I'd just want to verify it cannot be made any simpler.

The graph has following relationships and labels:

+---------[ :Class ] -[hasMethod]-> [ :Method ] --+
|            ^                        ^           |
+-[inherits]-+                        +-[invokes]-+

Now consider following code as input:

class Parent {
   protected void hello() {
   }
}

class Foo extends Parent {
   @Override
   protected void hello() {
   }
}

class Bar extends Foo {
   public void test() {
      hello();
   }
}

By parsing the bytecode I get following nodes and relationships (just the relevant ones are shown here:

(Parent:Class)-[:hasMethod]-(:Method{name:"Parent#hello()V", 
   simpleName:"hello", signature:"()V"})
(Foo:Class)-[:inherits]->Parent
Foo-[:hasMethod]->(:Method{name: "Foo#hello()V", 
   simpleName:"hello", signature:"()V"})
(Bar:Class)-[:inherits]->Foo
Bar->[:hasMethod]->(test:Method{simpleName: "test"})
test->[:invokes]->(:Method{name: "Bar#hello()V",
  simpleName:"hello", signature: "()V"

I want to find the declared method of the closest parent that will be invoked in such case. My solution looks like this:

match (m:Method) where not m<-[:hasMethod]-()
// method.name is Class#name(signature) 
with m, split(m.name,'#')[0] as className

// find a method with same name and signature
match (superMethod:Method{methodName:m.methodName, signature:m.signature}),

// which is declared in a superclass
p=(c:Class{name:className})-[:inherits*]->(super)-[:hasMethod]->superMethod

// and group them in a collection
with m, collect(p) as allPossibleSuperMethods

// and now keep the closest method (with the shortest path to it)
with m, reduce(path = null, p in allPossibleSuperMethods |
  case
    // the candidate is either better than nothing or shorter than previous
    when path is null or length(p) < length(path) then p
   // or we've got our winner already 
   else path
end) as superMethodPath

// and the last on the path is the closest declared method
with m,last(superMethodPath) as superMethod

// so we mark the replacement
create m-[:implementedBy]->superMethod

As you see the task is to create link between non-declared method (one that doesn't have hasMethod relationship), and exactly one declared method of a parent class. The question is: can it be made any simpler? As far as I understand shortestPath function cannot have constraints on target nodes, if we omit the fact, that we need to traverse two distinct relationship types.

The example is available also in interactive version at http://console.neo4j.org/?id=9cmwaf

The task for the query is to return just single row - Foo#hello()

1

0

Your Answer

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

Browse other questions tagged or ask your own question.