Demonstration of a Visitor and an Editor.

It is sometimes desireable to rewrite a body of the form

if (condition) {
    return a;
} else {
    return b;
}

into a series of statements without intermediate returns, like this:

value ret;
if (condition) {
    ret = a;
} else {
    ret = b;
}

However, this is not possible for every block:

if (condition) {
    return a;
}
return b;

If we replace returns with ret assignments here, the second return would still be reached.

hasEarlyReturns() detects if a body contains such an early return by visiting the body; RewriteReturnsEditor rewrites a body as shown above.

This could be used for some compiler optimizations.

Functions
hasEarlyReturnsSource Codeshared Boolean hasEarlyReturns(Body body)

Determines if a body contains an early return.

In a body without early returns, removing a return statement does not cause execution of additional statements, because no statements occurred behind the return in the original body.

For example, this body contains an early return:

if (condition) {
    return a;
}
return b;

On the other hand, this one has no early returns:

if (condition) {
    return a;
} else {
    return b;
}
Classes
RewriteReturnsEditorSource Codeshared RewriteReturnsEditor

Rewrites all returns in a block to specifications of the named value.

For example,

if (condition) {
    return a;
} else {
    return b;
}

is rewritten to

if (condition) {
    returnValue = a;
} else {
    returnValue = b;
}

You should only use this if the block has no early returns, otherwise this changes the semantics of the block.

Usage:

rewrittenBlock= someBlock.transform(RewriteReturnsEditor(returnValueName));