[Spoon-discuss] Exception inserting code when if-statement body has no curly braces
Renaud Pawlak
renaud.pawlak at gmail.com
Sun Jan 4 16:56:10 CET 2009
Hi Alex,
The only way is to add the block (curly brackets) when it is not
there. Iterate on the CtReturn list returned by the filter, then for
each CtReturn, check that the parent (CtElement.getParent) is a
CtBlock. If it is, proceed like you did before. If it not, create a
new empty CtBlock with the factory and add the return and the
endMethod statements. Then call the CtElement.replace(CtElement)
method on the return statement with your new block as a parameter.
Note that the insertBefore method could do this operation
transparently but it could be a little bit too invasive to modify the
AST that much... insertBefore assumes that the target statement is
within a block...
Cheers,
/Renaud
On Sun, Jan 4, 2009 at 12:28 AM, Alex Epshteyn
<alexander.epshteyn at gmail.com> wrote:
> I'm trying to insert some code before every return statement in each
> method. There is a problem when a return statement occurs inside a
> block with no curly braces like this:
>
>
> /** Spoon throws an exception when trying to instrument a block with
> no curlies around it */
> public void foo(int x) {
> if (x < 0)
> return; // will fail here
> if (x == 0) {
> return; // this is OK because curly braces present
> }
> else
> positive(xStr);
> }
>
> Spoon throws:
>
> java.lang.ClassCastException: spoon.support.reflect.code.CtIfImpl
> cannot be cast to spoon.reflect.code.CtBlock
> at spoon.support.reflect.code.CtStatementImpl.insertBefore(CtStatementImpl.java:78)
>
>
> Here is my Processor code:
>
> public void process(CtMethod method) {
> ...
> // instrument all return statements
> // TODO: if statements without curly braces will throw an
> exception: java.lang.ClassCastException:
> spoon.support.reflect.code.CtIfImpl cannot be cast to
> spoon.reflect.code.CtBlock
>
> method.getBody().insertBefore(
> new TypeFilter<CtReturn>(CtReturn.class),
> Substitution.substituteMethodBody(
> (CtClass) method.getDeclaringType(),
> createTemplate(methodId, paramNames), "endMethod"));
> }
>
>
> I'm using Spoon 1.4. Would appreciate your assistance in finding a
> workaround to this problem.
>
> Thanks,
> Alex
>
> _______________________________________________
> Spoon-discuss mailing list
> Spoon-discuss at lists.gforge.inria.fr
> http://lists.gforge.inria.fr/cgi-bin/mailman/listinfo/spoon-discuss
>
--
Renaud Pawlak, Professor
ISEP - 21 rue d'Assas 75006 Paris, France
Head of the Computer Engineering Department
Head of ISEP Research and Consulting for Computer Engineering
Phone: +33 149 54 52 78
Cell #1: +33 6 37 29 12 15
Cell #2: +33 6 36 47 06 01
Fax: +33 1 49 54 52 51
http://renaudpawlak.wikidot.com
More information about the Spoon-discuss
mailing list