Object comparaison

Hello everyone,
I am trying to write a custom rule, but, I’m having trouble detecting if two methodInvocations are being called by the same object ?

object b;
b.doSomething();
b.go();

Any hint ?

Hello @kad,

What did you try already? Can you be a bit more explicit about the approach you are thinking of?

The main pain point I would see is that checking that it’s really the same object for both invocations is quite hard to achieve relying only on syntax and semantic. In order to drop most of the possible FPs, you need to rely on cfg and/or some sort of symbolic execution (SE).

Knowing these limitations, I would probably get the symbol of the IdentifierTree on which you are making the method invocation (b in your case), and then try to check that it’s the same symbol which is used with the next method invocation.

You are however going to be hit quite hard by reassignments or complex flows… And you will need to handle mountains of FPs, or willingly narrow the scope to simple cases (no reassignments, nothing outside current block scope).

  • Reassignment:
object o = get();  // object 1
o.doSomething();
o = getAgain();    // object 2
b.go();            // same symbol for 'o', but different objects
  • Complex flows:
object o = get();
if (test) {
  o.doSomething();
} else {
  o.go();   // same object, but go() is not called after doSomething(), they are exclusive
}

Final question: Is it a rule which would be exclusive to your company/project, or do you see some general bad practice/bug which would benefit everyone?

If it’s the second, we could specify a rule and implement it with our SE engine (which is far not mature enough to be exposed in custom rules for the time being).

Hope this helps,
Michael

1 Like

Hey @Michael,

The approach I’m thinking of is to check by object name, method name, which is not the best way to get it done. Cause it will generate a tons of FPs.

The rule itself will be used in internal in our company, for now.

Thanks for your response, as usual :slight_smile:
Kad