[ 
https://issues.apache.org/jira/browse/GROOVY-11287?page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel&focusedCommentId=17946514#comment-17946514
 ] 

Eric Milles commented on GROOVY-11287:
--------------------------------------

Adding something like this to 
[{{BinaryExpressionTransformer}}|https://github.com/apache/groovy/blob/d77d909df28896a21fe4958a201f98c891d5cb51/src/main/java/org/codehaus/groovy/transform/sc/transformers/BinaryExpressionTransformer.java#L83]
 is straightforward enough:
{code:java}
    public Expression transformBinaryExpression(final BinaryExpression bin) {
        Expression leftExpression = bin.getLeftExpression();
        Expression rightExpression = bin.getRightExpression();

        if (Types.isAssignment(bin.getOperation().getType())) { // 
GROOVY-11287: inline simple maths
            Expression value = transformInlineConstants(rightExpression, 
findType(rightExpression));
            if (value instanceof ConstantExpression) {
                bin.setRightExpression(value);
                rightExpression = value;
            }
        }
{code}

The real question is when should this be done?  Under what conditions is it 
safe to replace the source expression with an inlined, compile-time result?  
The above example is only for assignment, but the same could be applied to a 
method call argument or a return value as well.

> Perform constant folding for basic math calculations in CS
> ----------------------------------------------------------
>
>                 Key: GROOVY-11287
>                 URL: https://issues.apache.org/jira/browse/GROOVY-11287
>             Project: Groovy
>          Issue Type: New Feature
>          Components: performance, Static compilation
>            Reporter: Oscar N
>            Priority: Major
>
> I have the following Groovy code and its Java equivalent:
> {code:groovy}
> @CompileStatic
> final class Main {
>     private static final int ONE = 1
>     static void main(String[] args) {
>         int two = ONE + 1
>         println two
>     }
> }
> {code}
> {code:java}
> public final class JavaMain {
>     private static final int ONE = 1;
>     public static void main(String[] args) {
>         int two = ONE + 1;
>         System.out.println(two);
>     }
> }
> {code}
> In Groovy, it currently compiles to:
> {code}int two = ONE + 1{code}
> In Java, the calculation is done at compile-time and inlined:
> {code}int two = 2{code}
> It would be great if Groovy also did this.



--
This message was sent by Atlassian Jira
(v8.20.10#820010)

Reply via email to