jboss-javassist / javassist

Java bytecode engineering toolkit
www.javassist.org
Other
4.11k stars 699 forks source link

Defer kind of thing future request #290

Open clankill3r opened 5 years ago

clankill3r commented 5 years ago

We have insertBefore insertAfter and insertAt.

Some programming languages have a defer keyword. Which is added to the method stack to be executed next.

This is used when memory is allocated for example, but the memory has to be freed after the method or a memory leak is there. With the defer, it does not matter if the method returns early, at the end or in the middle with a exception that is thrown for example. It will always execute the code of the defer line.

Some kind of behaviour like this would be really welcome. Cause right now I have no idea how to add something with javassist that is always executed as the last thing in the method.

Raymond-Naseef commented 5 years ago

Java has try { } finally and finally always occurs even if errors are being thrown from inside the try. Does this do what you need?

clankill3r commented 5 years ago

Thank you, I never thought of that. Normally i'm not a big fan of try catch but in this case it will serve it's purpose fine!

clankill3r commented 4 years ago

@Raymond-Naseef Do you have any idea how to do this for a method? I can't do it with insertBefore and insertAfter cause it will already fail at insertBefore: Sadly it is evaluated directly :(

cm.insertBefore("{");
cm.insertAfter("}");

I want avoid making a copy of the method and calling that cause i'm working on a profiler.

chibash commented 4 years ago

Can you take a look at CtBehavior#addCatch?

clankill3r commented 4 years ago

I will have a look, thanks for the pointer.

Op ma 18 nov. 2019 om 02:00 schreef Shigeru Chiba <notifications@github.com

:

Can you take a look at CtBehavior#addCatch?

— You are receiving this because you modified the open/close state. Reply to this email directly, view it on GitHub https://github.com/jboss-javassist/javassist/issues/290?email_source=notifications&email_token=AAFUKWXSDN35JXNSXI2GQG3QUHSL3A5CNFSM4JL3JAX2YY3PNVWWK3TUL52HS4DFVREXG43VMVBW63LNMVXHJKTDN5WW2ZLOORPWSZGOEEI3RUI#issuecomment-554809553, or unsubscribe https://github.com/notifications/unsubscribe-auth/AAFUKWUJSP6UPERHBIONJ4LQUHSL3ANCNFSM4JL3JAXQ .

clankill3r commented 1 year ago

I don't see how this would be possible, let's say I have:

public void setup() {
    defer("A");
    defer("B");
    println("hello");
    defer("C");
}

@Defer
void defer(String what) {
    System.out.println(what);
}

Then the order should become:

    println("hello");
    defer("C");
    defer("B");
    defer("A");

The thing is that the ExprEditor does not allow for such things. And there is no method.insertAfter(MethodCall) for example. If that was the case, that could have been done and then the original calls could have been replaced by "{}".