You are viewing a plain text version of this content. The canonical link for it is here.
Posted to commits@groovy.apache.org by em...@apache.org on 2024/10/09 21:27:30 UTC
(groovy) branch master updated: GROOVY-11288: do not load assignment expression value for expr statement
This is an automated email from the ASF dual-hosted git repository.
emilles pushed a commit to branch master
in repository https://gitbox.apache.org/repos/asf/groovy.git
The following commit(s) were added to refs/heads/master by this push:
new cdb69c922e GROOVY-11288: do not load assignment expression value for expr statement
cdb69c922e is described below
commit cdb69c922e58d229540bcbb5b9585df061a3150f
Author: Eric Milles <er...@thomsonreuters.com>
AuthorDate: Wed Oct 9 16:26:27 2024 -0500
GROOVY-11288: do not load assignment expression value for expr statement
---
.../groovy/ast/expr/DeclarationExpression.java | 13 +-
.../classgen/asm/BinaryExpressionHelper.java | 91 ++--
.../asm/BinaryExpressionMultiTypeDispatcher.java | 26 +-
.../codehaus/groovy/classgen/asm/CompileStack.java | 24 +-
.../groovy/classgen/asm/StatementWriter.java | 14 +-
...icTypesBinaryExpressionMultiTypeDispatcher.java | 11 +-
.../transform/stc/StaticTypeCheckingVisitor.java | 1 +
.../classgen/asm/sc/StaticCompilationTest.groovy | 509 +++++++++++----------
8 files changed, 370 insertions(+), 319 deletions(-)
diff --git a/src/main/java/org/codehaus/groovy/ast/expr/DeclarationExpression.java b/src/main/java/org/codehaus/groovy/ast/expr/DeclarationExpression.java
index 987a7085b8..48e0cb6b6c 100644
--- a/src/main/java/org/codehaus/groovy/ast/expr/DeclarationExpression.java
+++ b/src/main/java/org/codehaus/groovy/ast/expr/DeclarationExpression.java
@@ -139,7 +139,7 @@ public class DeclarationExpression extends BinaryExpression {
if (v.isDynamicTyped()) {
text.append("def");
} else {
- text.append(formatTypeName(v.getType()));
+ text.append(formatTypeName(v.getOriginType()));
}
text.append(' ').append(v.getText());
} else {
@@ -149,7 +149,7 @@ public class DeclarationExpression extends BinaryExpression {
if (e instanceof VariableExpression) {
VariableExpression v = (VariableExpression) e;
if (!v.isDynamicTyped()) {
- text.append(formatTypeName(v.getType())).append(' ');
+ text.append(formatTypeName(v.getOriginType())).append(' ');
}
}
text.append(e.getText()).append(", ");
@@ -157,8 +157,13 @@ public class DeclarationExpression extends BinaryExpression {
text.setLength(text.length() - 2);
text.append(')');
}
- text.append(' ').append(getOperation().getText());
- text.append(' ').append(getRightExpression().getText());
+
+ if (getRightExpression() instanceof EmptyExpression) {
+ text.append(';');
+ } else {
+ text.append(' ').append(getOperation().getText());
+ text.append(' ').append(getRightExpression().getText());
+ }
return text.toString();
}
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
index dd45781aa6..15a0b03eb4 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionHelper.java
@@ -113,12 +113,16 @@ import static org.codehaus.groovy.syntax.Types.RIGHT_SHIFT_UNSIGNED;
import static org.codehaus.groovy.syntax.Types.RIGHT_SHIFT_UNSIGNED_EQUAL;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ALOAD;
+import static org.objectweb.asm.Opcodes.DCONST_0;
import static org.objectweb.asm.Opcodes.DUP;
+import static org.objectweb.asm.Opcodes.FCONST_0;
import static org.objectweb.asm.Opcodes.GOTO;
+import static org.objectweb.asm.Opcodes.ICONST_0;
import static org.objectweb.asm.Opcodes.IFEQ;
import static org.objectweb.asm.Opcodes.IFNE;
import static org.objectweb.asm.Opcodes.IF_ACMPEQ;
import static org.objectweb.asm.Opcodes.INSTANCEOF;
+import static org.objectweb.asm.Opcodes.LCONST_0;
import static org.objectweb.asm.Opcodes.POP;
public class BinaryExpressionHelper {
@@ -401,40 +405,41 @@ public class BinaryExpressionHelper {
Expression rightExpression = expression.getRightExpression();
boolean singleAssignment = !(leftExpression instanceof TupleExpression);
boolean directAssignment = defineVariable && singleAssignment; //def x=y
+ boolean returnRightValue = !Boolean.TRUE.equals(expression.getNodeMetaData("GROOVY-11288"));
- // TODO: LHS has not been visited, it could be a variable in a closure and type chooser is not aware.
+ // TODO: LHS has not been visited -- it could be a variable in a closure and type chooser is not aware.
ClassNode lhsType = controller.getTypeChooser().resolveType(leftExpression, controller.getClassNode());
if (directAssignment && rightExpression instanceof EmptyExpression) {
BytecodeVariable v = compileStack.defineVariable((Variable) leftExpression, lhsType, false);
- operandStack.loadOrStoreVariable(v, false);
+ if (returnRightValue) operandStack.loadOrStoreVariable(v, false);
return;
}
- // evaluate RHS and store the value
+ // evaluate RHS and store its value
- if (rightExpression instanceof ListExpression && lhsType.isArray()) {
+ if (lhsType.isArray() && rightExpression instanceof ListExpression) { // array = [ ... ]
Expression array = new ArrayExpression(lhsType.getComponentType(), ((ListExpression) rightExpression).getExpressions());
array.setSourcePosition(rightExpression);
array.visit(acg);
- } else if (rightExpression instanceof EmptyExpression) {
- loadInitValue(lhsType); // null or zero (or false)
+ } else if (rightExpression instanceof EmptyExpression) { // define field
+ /* */ if (ClassHelper.isPrimitiveDouble(lhsType)) {
+ mv.visitInsn(DCONST_0);
+ } else if (ClassHelper.isPrimitiveFloat(lhsType)) {
+ mv.visitInsn(FCONST_0);
+ } else if (ClassHelper.isPrimitiveLong(lhsType)) {
+ mv.visitInsn(LCONST_0);
+ } else if (ClassHelper.isPrimitiveType(lhsType)) {
+ mv.visitInsn(ICONST_0);
+ } else {
+ mv.visitInsn(ACONST_NULL);
+ }
+ operandStack.push(lhsType);
} else {
rightExpression.visit(acg);
}
- // GROOVY-10918: direct store to local variable or parameter (no temp)
- if (!defineVariable && leftExpression instanceof VariableExpression) {
- BytecodeVariable v = compileStack.getVariable(leftExpression.getText(), false);
- if (v != null) {
- operandStack.dup(); // return value of the assignment expression
- operandStack.storeVar(v);
- return;
- }
- }
-
ClassNode rhsType = operandStack.getTopOperand();
- int rhsValueId;
if (directAssignment) {
VariableExpression var = (VariableExpression) leftExpression;
@@ -460,17 +465,33 @@ public class BinaryExpressionHelper {
} else {
operandStack.doGroovyCast(lhsType);
}
- rhsType = lhsType;
- rhsValueId = compileStack.defineVariable(var, lhsType, true).getIndex();
- } else {
- rhsValueId = compileStack.defineTemporaryVariable("$rhs", rhsType, true);
+
+ // store value
+ BytecodeVariable v = compileStack.defineVariable(var, lhsType, true);
+ operandStack.remove(1);
+ if (returnRightValue) {
+ new VariableSlotLoader(lhsType, v.getIndex(), operandStack).visit(acg);
+ }
+ return;
+ }
+
+ // GROOVY-10918: direct store to local variable or parameter (no temp)
+ if (!defineVariable && leftExpression instanceof VariableExpression) {
+ BytecodeVariable v = compileStack.getVariable(leftExpression.getText(), false);
+ if (v != null) {
+ if (returnRightValue) operandStack.dup();
+ operandStack.storeVar(v);
+ return;
+ }
}
- // TODO: if RHS is VariableSlotLoader already, then skip creating a new one
+
+ int rhsValueId = compileStack.defineTemporaryVariable("$rhs", rhsType, true);
+ // TODO: if RHS is already a VariableSlotLoader, then skip creating a new one
Expression rhsValueLoader = new VariableSlotLoader(rhsType, rhsValueId, operandStack);
- // assignment for subscript
+ // subscript assignment
if (leftExpression instanceof BinaryExpression) {
- BinaryExpression leftBinExpr = (BinaryExpression) leftExpression;
+ var leftBinExpr = (BinaryExpression) leftExpression;
if (leftBinExpr.getOperation().getType() == LEFT_SQUARE_BRACKET) {
assignToArray(expression, leftBinExpr.getLeftExpression(), leftBinExpr.getRightExpression(), rhsValueLoader, leftBinExpr.isSafe());
}
@@ -480,13 +501,6 @@ public class BinaryExpressionHelper {
compileStack.pushLHS(true);
- if (directAssignment) {
- rhsValueLoader.visit(acg);
- operandStack.remove(1);
- compileStack.popLHS();
- return;
- }
-
if (singleAssignment) {
int mark = operandStack.getStackLength();
rhsValueLoader.visit(acg);
@@ -567,19 +581,10 @@ public class BinaryExpressionHelper {
compileStack.popLHS();
- // return value of assignment
- rhsValueLoader.visit(acg);
- compileStack.removeVar(rhsValueId);
- }
+ if (returnRightValue)
+ rhsValueLoader.visit(acg);
- private void loadInitValue(final ClassNode type) {
- MethodVisitor mv = controller.getMethodVisitor();
- if (ClassHelper.isPrimitiveType(type)) {
- mv.visitLdcInsn(0);
- } else {
- mv.visitInsn(ACONST_NULL);
- }
- controller.getOperandStack().push(type);
+ compileStack.removeVar(rhsValueId);
}
protected void evaluateCompareExpression(final MethodCaller compareMethod, final BinaryExpression expression) {
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.java b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.java
index 8b08f866e8..b3846494da 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/BinaryExpressionMultiTypeDispatcher.java
@@ -356,34 +356,32 @@ public class BinaryExpressionMultiTypeDispatcher extends BinaryExpressionHelper
@Override
protected void assignToArray(final Expression orig, final Expression receiver, final Expression index, final Expression rhsValueLoader, final boolean safe) {
- ClassNode current = controller.getClassNode();
- ClassNode arrayType = controller.getTypeChooser().resolveType(receiver, current);
- ClassNode arrayComponentType = arrayType.getComponentType();
- int operationType = getOperandType(arrayComponentType);
- BinaryExpressionWriter bew = binExpWriter[operationType];
- AsmClassGenerator acg = controller.getAcg();
-
+ ClassNode arrayType = controller.getTypeChooser().resolveType(receiver, controller.getClassNode());
+ BinaryExpressionWriter bew = binExpWriter[getOperandType(arrayType.getComponentType())];
if (bew.arraySet(true) && arrayType.isArray() && !safe) {
- OperandStack operandStack = controller.getOperandStack();
+ var asmGenerator = controller.getAcg();
+ var operandStack = controller.getOperandStack();
// load the array
- receiver.visit(acg);
+ receiver.visit(asmGenerator);
operandStack.doGroovyCast(arrayType);
// load index
- index.visit(acg);
+ index.visit(asmGenerator);
operandStack.doGroovyCast(int_TYPE);
// load rhs
- rhsValueLoader.visit(acg);
- operandStack.doGroovyCast(arrayComponentType);
+ rhsValueLoader.visit(asmGenerator);
+ operandStack.doGroovyCast(arrayType.getComponentType());
// store value in array
bew.arraySet(false);
- // load return value && correct operand stack
+ // update operand stack
operandStack.remove(3);
- rhsValueLoader.visit(acg);
+
+ if (!Boolean.TRUE.equals(orig.getNodeMetaData("GROOVY-11288")))
+ rhsValueLoader.visit(asmGenerator); // re-load result value
} else {
super.assignToArray(orig, receiver, index, rhsValueLoader, safe);
}
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/CompileStack.java b/src/main/java/org/codehaus/groovy/classgen/asm/CompileStack.java
index 8fbc48a7aa..e302b48cad 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/CompileStack.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/CompileStack.java
@@ -37,14 +37,12 @@ import java.util.LinkedList;
import java.util.List;
import java.util.Map;
-import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveDouble;
-import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveFloat;
-import static org.codehaus.groovy.ast.ClassHelper.isPrimitiveLong;
import static org.objectweb.asm.Opcodes.ACONST_NULL;
import static org.objectweb.asm.Opcodes.ASTORE;
import static org.objectweb.asm.Opcodes.DCONST_0;
import static org.objectweb.asm.Opcodes.DUP_X1;
import static org.objectweb.asm.Opcodes.FCONST_0;
+import static org.objectweb.asm.Opcodes.ICONST_0;
import static org.objectweb.asm.Opcodes.INVOKESPECIAL;
import static org.objectweb.asm.Opcodes.LCONST_0;
import static org.objectweb.asm.Opcodes.NEW;
@@ -641,16 +639,14 @@ public class CompileStack {
}
private static void pushInitValue(final ClassNode type, final MethodVisitor mv) {
- if (ClassHelper.isPrimitiveType(type)) {
- if (isPrimitiveLong(type)) {
- mv.visitInsn(LCONST_0);
- } else if (isPrimitiveDouble(type)) {
- mv.visitInsn(DCONST_0);
- } else if (isPrimitiveFloat(type)) {
- mv.visitInsn(FCONST_0);
- } else {
- mv.visitLdcInsn(0);
- }
+ /* */ if (ClassHelper.isPrimitiveDouble(type)) {
+ mv.visitInsn(DCONST_0);
+ } else if (ClassHelper.isPrimitiveFloat(type)) {
+ mv.visitInsn(FCONST_0);
+ } else if (ClassHelper.isPrimitiveLong(type)) {
+ mv.visitInsn(LCONST_0);
+ } else if (ClassHelper.isPrimitiveType(type)) {
+ mv.visitInsn(ICONST_0);
} else {
mv.visitInsn(ACONST_NULL);
}
@@ -718,7 +714,7 @@ public class CompileStack {
*/
private void makeNextVariableID(final ClassNode type, final boolean useReferenceDirectly) {
currentVariableIndex = nextVariableIndex;
- if ((isPrimitiveLong(type) || isPrimitiveDouble(type)) && !useReferenceDirectly) {
+ if (!useReferenceDirectly && (ClassHelper.isPrimitiveLong(type) || ClassHelper.isPrimitiveDouble(type))) {
nextVariableIndex += 1;
}
nextVariableIndex += 1;
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java b/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
index 1e41fc9ac8..0d94c9bf82 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/StatementWriter.java
@@ -20,6 +20,7 @@ package org.codehaus.groovy.classgen.asm;
import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
+import org.codehaus.groovy.ast.expr.BinaryExpression;
import org.codehaus.groovy.ast.expr.BooleanExpression;
import org.codehaus.groovy.ast.expr.ClosureListExpression;
import org.codehaus.groovy.ast.expr.ConstantExpression;
@@ -602,12 +603,17 @@ public class StatementWriter {
}
public void writeExpressionStatement(final ExpressionStatement statement) {
- controller.getAcg().onLineNumber(statement, "visitExpressionStatement: " + statement.getExpression().getClass().getName());
+ Expression expression = statement.getExpression();
+
+ controller.getAcg().onLineNumber(statement, "visitExpressionStatement: " + expression.getClass().getName());
writeStatementLabel(statement);
- int mark = controller.getOperandStack().getStackLength();
- Expression expression = statement.getExpression();
+ if (expression instanceof BinaryExpression)
+ expression.putNodeMetaData("GROOVY-11288", Boolean.TRUE);
+
+ var operandStack = controller.getOperandStack();
+ int mark = operandStack.getStackLength();
expression.visit(controller.getAcg());
- controller.getOperandStack().popDownTo(mark);
+ operandStack.popDownTo(mark);
}
}
diff --git a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java
index 45c89d41df..fa2b2178cf 100644
--- a/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java
+++ b/src/main/java/org/codehaus/groovy/classgen/asm/sc/StaticTypesBinaryExpressionMultiTypeDispatcher.java
@@ -326,10 +326,9 @@ public class StaticTypesBinaryExpressionMultiTypeDispatcher extends BinaryExpres
protected void assignToArray(final Expression enclosing, final Expression receiver, final Expression subscript, final Expression rhsValueLoader, final boolean safe) {
ClassNode receiverType = controller.getTypeChooser().resolveType(receiver, controller.getClassNode());
- if (receiverType.isArray() && !safe && binExpWriter[getOperandType(receiverType.getComponentType())].arraySet(true)) {
- super.assignToArray(enclosing, receiver, subscript, rhsValueLoader, safe);
-
- } else { // this code path is needed because ACG creates array access expressions
+ if (!safe && receiverType.isArray() && binExpWriter[getOperandType(receiverType.getComponentType())].arraySet(true)) {
+ super.assignToArray(enclosing, receiver, subscript, rhsValueLoader, false);
+ } else { // handle safe subscript and other cases by calling the "putAt" method
if (rhsValueLoader instanceof VariableSlotLoader && enclosing instanceof BinaryExpression) { // GROOVY-6061
rhsValueLoader.putNodeMetaData(INFERRED_TYPE, controller.getTypeChooser().resolveType(enclosing, controller.getClassNode()));
}
@@ -346,8 +345,8 @@ public class StaticTypesBinaryExpressionMultiTypeDispatcher extends BinaryExpres
operandStack.pop();
operandStack.remove(operandStack.getStackLength() - height);
- // return value of assignment
- rhsValueLoader.visit(controller.getAcg());
+ if (!Boolean.TRUE.equals(enclosing.getNodeMetaData("GROOVY-11288")))
+ rhsValueLoader.visit(controller.getAcg()); // re-load result value
}
}
}
diff --git a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
index cdc359e477..f91b21482c 100644
--- a/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
+++ b/src/main/java/org/codehaus/groovy/transform/stc/StaticTypeCheckingVisitor.java
@@ -891,6 +891,7 @@ public class StaticTypeCheckingVisitor extends ClassCodeVisitorSupport {
boolean isEmptyDeclaration = (expression instanceof DeclarationExpression
&& (rightExpression instanceof EmptyExpression || rType == UNKNOWN_PARAMETER_TYPE));
if (isEmptyDeclaration) {
+ expression.putNodeMetaData(INFERRED_TYPE, lType);
// GROOVY-11353: "def var = null" cannot be a primitive type
if (isDynamicTyped(lType) && rType == UNKNOWN_PARAMETER_TYPE)
lType.putNodeMetaData("non-primitive type", Boolean.TRUE);
diff --git a/src/test/org/codehaus/groovy/classgen/asm/sc/StaticCompilationTest.groovy b/src/test/org/codehaus/groovy/classgen/asm/sc/StaticCompilationTest.groovy
index 4e93b63a0e..e6c34e9202 100644
--- a/src/test/org/codehaus/groovy/classgen/asm/sc/StaticCompilationTest.groovy
+++ b/src/test/org/codehaus/groovy/classgen/asm/sc/StaticCompilationTest.groovy
@@ -21,255 +21,318 @@ package org.codehaus.groovy.classgen.asm.sc
import org.codehaus.groovy.classgen.asm.AbstractBytecodeTestCase
import org.codehaus.groovy.runtime.MethodClosure
-import static org.codehaus.groovy.control.CompilerConfiguration.DEFAULT as config
-
final class StaticCompilationTest extends AbstractBytecodeTestCase {
void testEmptyMethod() {
- def bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
- void m() {}
- ''')
- assert bytecode.hasStrictSequence(
- ['public m()V', 'L0', 'LINENUMBER 3 L0', 'RETURN']
- )
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ void m() { }
+ ''').hasStrictSequence([
+ 'L0',
+ 'LINENUMBER 2',
+ 'RETURN'
+ ])
}
void testPrimitiveReturn1() {
- def bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
int m() { 1 }
- ''')
- assert bytecode.hasStrictSequence(
- ['ICONST_1', 'IRETURN']
- )
+ ''').hasStrictSequence([
+ 'L0',
+ 'LINENUMBER 2 L0',
+ 'ICONST_1',
+ 'IRETURN'
+ ])
}
void testPrimitiveReturn2() {
- def bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
long m() { 1L }
- ''')
- assert bytecode.hasStrictSequence(
- ['LCONST_1', 'LRETURN']
- )
+ ''').hasStrictSequence([
+ 'L0',
+ 'LINENUMBER 2',
+ 'LCONST_1',
+ 'LRETURN'
+ ])
}
void testPrimitiveReturn3() {
- def bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
short m() { 1 }
- ''')
- assert bytecode.hasStrictSequence(
- ['ICONST_1', 'I2S', 'IRETURN']
- )
+ ''').hasStrictSequence([
+ 'L0',
+ 'LINENUMBER 2',
+ 'ICONST_1',
+ 'I2S',
+ 'IRETURN'
+ ])
}
void testPrimitiveReturn4() {
- def bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
byte m() { 1 }
- ''')
- assert bytecode.hasStrictSequence(
- ['ICONST_1', 'I2B', 'IRETURN']
- )
+ ''').hasStrictSequence([
+ 'L0',
+ 'LINENUMBER 2',
+ 'ICONST_1',
+ 'I2B',
+ 'IRETURN'
+ ])
}
void testIdentityReturns() {
- def bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
int m(int i) { i }
- ''')
- assert bytecode.hasStrictSequence(
- ['ILOAD', 'IRETURN']
- )
+ ''').hasStrictSequence(['ILOAD','IRETURN'])
- bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
long m(long l) { l }
- ''')
- assert bytecode.hasStrictSequence(
- ['LLOAD', 'LRETURN']
- )
+ ''').hasStrictSequence(['LLOAD','LRETURN'])
- bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
- short m(short l) { l }
- ''')
- assert bytecode.hasStrictSequence(
- ['ILOAD', 'IRETURN']
- )
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ short m(short s) { s }
+ ''').hasStrictSequence(['ILOAD','IRETURN'])
- bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
- float m(float l) { l }
- ''')
- assert bytecode.hasStrictSequence(
- ['FLOAD', 'FRETURN']
- )
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ float m(float f) { f }
+ ''').hasStrictSequence(['FLOAD','FRETURN'])
- bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
- double m(double l) { l }
- ''')
- assert bytecode.hasStrictSequence(
- ['DLOAD', 'DRETURN']
- )
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ double m(double d) { d }
+ ''').hasStrictSequence(['DLOAD','DRETURN'])
- bytecode = compile(method: 'm', '''
- @groovy.transform.CompileStatic
- Object m(Object l) { l }
- ''')
- assert bytecode.hasStrictSequence(
- ['ALOAD', 'ARETURN']
- )
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ Object m(Object o) { o }
+ ''').hasStrictSequence(['ALOAD','ARETURN'])
}
- void testSingleAssignment() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ // GROOVY-11288
+ void testEmptyDeclaration0() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m() {
- int a = 1
+ int i
}
- ''').hasSequence([
- "ICONST_1",
- "ISTORE",
- "RETURN"
- ])
+ ''').hasStrictSequence([
+ 'L0',
+ 'LINENUMBER 3',
+ 'ICONST_0',
+ 'ISTORE 1',
+ 'L1',
+ 'LINENUMBER 4',
+ 'RETURN'
+ ])
}
- void testReturnSingleAssignment() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ void testEmptyDeclaration1() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
int m() {
- int a = 1
+ int i
}
- ''').hasSequence([
- "ICONST_1",
- "ISTORE",
- "ILOAD",
- "IRETURN"
- ])
+ ''').hasStrictSequence([
+ 'L0',
+ 'LINENUMBER 3',
+ 'ICONST_0',
+ 'ISTORE 1',
+ 'L1',
+ 'ILOAD 1',
+ 'IRETURN'
+ ])
}
- void testIntLeftShift() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ // GROOVY-11288
+ void testSingleAssignment0() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m() {
- int a = 1
- int b = a << 32
+ int i = 1
}
''').hasStrictSequence([
- "ILOAD",
- "BIPUSH 32",
- "ISHL"
- ])
+ 'L0',
+ 'LINENUMBER 3',
+ 'ICONST_1',
+ 'ISTORE 1',
+ 'L1',
+ 'LINENUMBER 4',
+ 'RETURN'
+ ])
}
- void testLongLeftShift() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
- void m() {
- long a = 1L
- long b = a << 32
+ void testSingleAssignment1() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ int m() {
+ int i = 1
}
''').hasStrictSequence([
- "LLOAD",
- "BIPUSH 32",
- "LSHL"
- ])
+ 'L0',
+ 'LINENUMBER 3',
+ 'ICONST_1',
+ 'ISTORE 1',
+ 'L1',
+ 'ILOAD 1',
+ 'IRETURN'
+ ])
}
- void testArrayGet() {
- if (config.indyEnabled) return;
- // this test is done with indy in another tests case
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
- void m(int[] arr) {
- arr[0]
+ // GROOVY-11288
+ void testSimpleAssignment0() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ class C {
+ int i
+ void m() {
+ i = 1
+ }
}
''').hasStrictSequence([
- "ALOAD 1",
- "ICONST_0",
- "INVOKESTATIC org/codehaus/groovy/runtime/BytecodeInterface8.intArrayGet ([II)I"
- ])
+ 'L0',
+ 'LINENUMBER 5',
+ 'ICONST_1',
+ 'ISTORE 1',
+ 'ILOAD 1',
+ 'ALOAD 0',
+ 'SWAP',
+ 'PUTFIELD C.i',
+ 'L1',
+ 'LINENUMBER 6',
+ 'RETURN'
+ ])
}
- void testArraySet() {
- if (config.indyEnabled) return;
- // this test is done with indy in another tests case
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
- void m(int[] arr) {
- arr[0] = 0
+ // GROOVY-11288
+ void testSubscriptAssignment1() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ void m(int[] i) {
+ i[0] = 1
}
''').hasStrictSequence([
- "ICONST_0",
- "ISTORE 2",
- "ALOAD 1",
- "ICONST_0",
- "ILOAD 2",
- "INVOKESTATIC org/codehaus/groovy/runtime/BytecodeInterface8.intArraySet ([III)V"
- ])
+ 'L0',
+ 'LINENUMBER 3',
+ 'ICONST_1',
+ 'ISTORE 2',
+ 'ALOAD 1',
+ 'ICONST_0',
+ 'ILOAD 2',
+ 'INVOKEDYNAMIC set([III)V [',
+ '// handle kind 0x6 : INVOKESTATIC',
+ 'org/codehaus/groovy/vmplugin/v8/IndyInterface.staticArrayAccess',
+ '// arguments: none',
+ ']',
+ 'L1',
+ 'LINENUMBER 4',
+ 'RETURN'
+ ])
}
- void _testPlusPlus() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ // GROOVY-11288
+ void testSubscriptAssignment2() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ void m(int[] i) {
+ i?[0] = 1
+ }
+ ''').hasStrictSequence([
+ // ... for putAt
+ 'L2',
+ 'FRAME SAME1 java/lang/Object',
+ 'POP',
+ // load temp var 2 and pop gone
+ 'L3',
+ 'LINENUMBER 4',
+ 'RETURN'
+ ])
+ }
+
+ void testIntLeftShift() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m() {
- int i = 0
+ int a = 1
+ int b = a << 32
+ }
+ ''').hasStrictSequence([
+ 'ILOAD',
+ 'BIPUSH 32',
+ 'ISHL'
+ ])
+ }
+
+ void testLongLeftShift() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ void m() {
+ long a = 1L
+ long b = a << 32
+ }
+ ''').hasStrictSequence([
+ 'LLOAD',
+ 'BIPUSH 32',
+ 'LSHL'
+ ])
+ }
+
+ void _testPlusPlus() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ void m(int i) {
i++
}
''').hasStrictSequence([
- "IINC",
- ])
+ 'IINC'
+ ])
}
void _testMinusMinus() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
- void m() {
- int i = 0
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
+ void m(int i) {
i--
}
''').hasStrictSequence([
- "IINC",
- ])
+ 'IINC'
+ ])
}
- void _testPlusEquals() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ void testPlusEquals() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
int m() {
int i = 0
i += 13
return i
}
''').hasStrictSequence([
- "ILOAD",
- "ILOAD",
- "IADD",
- "ISTORE"
- ])
+ 'L0',
+ 'LINENUMBER 3',
+ 'ICONST_0',
+ 'ISTORE 1',
+ 'L1',
+ 'LINENUMBER 4',
+ 'ILOAD 1',
+ 'BIPUSH 13',
+ 'IADD',
+/*TODO*/ 'DUP',
+ 'ISTORE 1',
+/*TODO*/ 'POP',
+ 'L2',
+ 'LINENUMBER 5',
+ 'ILOAD 1',
+ 'IRETURN'
+ ])
}
- void _testPlusEqualsFromArgs() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ void testPlusEqualsFromArgs() {
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m(int i, int j) {
i += j
}
''').hasStrictSequence([
- "ILOAD",
- "ILOAD",
- "IADD",
- "ISTORE"
- ])
+ 'L0',
+ 'LINENUMBER 3',
+ 'ILOAD 1',
+ 'ILOAD 2',
+ 'IADD',
+/*TODO*/ 'DUP',
+ 'ISTORE 1',
+/*TODO*/ 'POP',
+ 'L1',
+ 'LINENUMBER 4',
+ 'RETURN'
+ ])
}
void testFlow() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
String m(String str) {
def obj = 1
obj = str
@@ -277,32 +340,26 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
}
m 'Cedric'
''').hasStrictSequence([
- 'LINENUMBER 4',
+ 'L0',
+ 'LINENUMBER 3',
'ICONST_1',
'INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;',
'ASTORE 2',
'L1',
- 'ALOAD 2',
- 'POP',
- 'L2',
- 'LINENUMBER 5',
+ 'LINENUMBER 4',
'ALOAD 1',
- 'DUP',
'ASTORE 2',
- 'POP',
- 'L3',
- 'LINENUMBER 6',
+ 'L2',
+ 'LINENUMBER 5',
'ALOAD 2',
'CHECKCAST java/lang/String',
'INVOKEVIRTUAL java/lang/String.toUpperCase ()Ljava/lang/String;',
- 'ARETURN',
- 'L4'
- ])
+ 'ARETURN'
+ ])
}
void testInstanceOf() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m(Object str) {
if (str instanceof String) {
str.toUpperCase()
@@ -310,15 +367,14 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
}
m 'Cedric'
''').hasStrictSequence([
- "ALOAD",
- "CHECKCAST java/lang/String",
- "INVOKEVIRTUAL java/lang/String.toUpperCase ()Ljava/lang/String;"
- ])
+ 'ALOAD',
+ 'CHECKCAST java/lang/String',
+ 'INVOKEVIRTUAL java/lang/String.toUpperCase ()Ljava/lang/String;'
+ ])
}
void testShouldGenerateDirectConstructorCall() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
class Foo {
String msg
Foo(int x, String y) { msg = y*x }
@@ -330,12 +386,11 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
'ICONST_2',
'LDC "Bar"',
'INVOKESPECIAL Foo.<init> (ILjava/lang/String;)V'
- ])
+ ])
}
void testShouldGenerateDirectArrayConstruct() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m() {
int[] arr = [123,456]
}
@@ -346,12 +401,11 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
'ICONST_0',
'BIPUSH 123',
'IASTORE'
- ])
+ ])
}
void testShouldGenerateDirectBooleanArrayConstruct() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m() {
boolean[] arr = [123,false]
}
@@ -364,7 +418,7 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
'INVOKESTATIC java/lang/Integer.valueOf (I)Ljava/lang/Integer;',
'INVOKESTATIC org/codehaus/groovy/runtime/typehandling/DefaultTypeTransformation.booleanUnbox (Ljava/lang/Object;)Z',
'BASTORE'
- ])
+ ])
}
void testShouldTriggerDirectCallToOuterClassGetter() {
@@ -399,20 +453,15 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
'ALOAD',
'ALOAD',
'INVOKEVIRTUAL Holder.setValue'
- ])
+ ])
}
void testShouldOptimizeBytecodeByAvoidingCreationOfMopMethods() {
- def shell = new GroovyShell()
- def clazz = shell.evaluate '''
- import groovy.transform.TypeCheckingMode
- import groovy.transform.CompileStatic
-
+ def clazz = new GroovyShell().evaluate '''import groovy.transform.*
@CompileStatic
class A {
def doSomething() { 'A' }
}
-
@CompileStatic
class B extends A {
def doSomething() { 'B' + super.doSomething() }
@@ -420,23 +469,17 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
B
'''
- assert clazz instanceof Class
assert clazz.name == 'B'
def mopMethods = clazz.declaredMethods.findAll { it.name =~ /(super|this)\$/ }
- assert mopMethods.empty
+ assert mopMethods.isEmpty()
}
void testShouldNotOptimizeBytecodeForMopMethodsBecauseOfSkip() {
- def shell = new GroovyShell()
- def clazz = shell.evaluate '''
- import groovy.transform.TypeCheckingMode
- import groovy.transform.CompileStatic
-
+ def clazz = new GroovyShell().evaluate '''import groovy.transform.*
@CompileStatic
class A {
def doSomething() { 'A' }
}
-
@CompileStatic
class B extends A {
@CompileStatic(TypeCheckingMode.SKIP)
@@ -445,16 +488,17 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
B
'''
- assert clazz instanceof Class
assert clazz.name == 'B'
def mopMethods = clazz.declaredMethods.findAll { it.name =~ /(super|this)\$/ }
- assert !mopMethods.empty
+ assert !mopMethods.isEmpty()
}
// GROOVY-7124
void testUseInvokeVirtualPreferredOverInvokeInterface() {
assert compile(method: 'foo', classNamePattern: 'B', '''
- interface A { void m() }
+ interface A {
+ void m()
+ }
class B implements A {
void m() {}
@groovy.transform.CompileStatic
@@ -482,28 +526,26 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
}
void testShouldOptimizeCharInit() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m() {
char c = 'x'
}
''').hasStrictSequence([
- 'LINENUMBER 4',
+ 'LINENUMBER 3',
'BIPUSH 120',
'ISTORE'
- ])
+ ])
}
void testShouldOptimizeCharComparison() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m() {
char c1 = 'x'
char c2 = 'x'
boolean b = c1==c2
}
''').hasSequence([
- 'LINENUMBER 4',
+ 'LINENUMBER 3',
'BIPUSH 120',
'ISTORE',
'BIPUSH 120',
@@ -511,12 +553,12 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
'ILOAD',
'ILOAD',
'IF_ICMPNE',
- ])
+ ])
// make sure the code passes
assertScript '''
@groovy.transform.CompileStatic
- void m() {
+ void test() {
char c1 = 'x'
char c2 = 'x'
boolean b = c1==c2
@@ -525,7 +567,7 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
b = c1==c3
assert !b
}
- m()
+ test()
'''
}
@@ -652,7 +694,7 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
assert compile(method:'m', anyExample).hasSequence([*loop_init,'AALOAD','ASTORE'])
// now check that everything runs fine
- [byteExample,shortExample, intExample, charExample, boolExample, longExample, floatExample, doubleExample, anyExample].each { script ->
+ [byteExample, shortExample, intExample, charExample, boolExample, longExample, floatExample, doubleExample, anyExample].each { script ->
assertScript(script)
}
}
@@ -682,18 +724,17 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
}
void testShouldRemoveUnnecessaryCast() {
- assert compile(method: 'm', '''
- @groovy.transform.CompileStatic
+ assert compile(method: 'm', '''@groovy.transform.CompileStatic
void m() {
char c = (char) 'x'
}
''').hasStrictSequence([
- 'LINENUMBER 4',
+ 'LINENUMBER 3',
'BIPUSH 120',
// No checkcast, but the idea is to check that further optimization was done
// because the RHS is no longer a CastExpression but a ConstantExpression
'ISTORE'
- ])
+ ])
}
void testInstanceMethodReference() {
@@ -712,11 +753,11 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
m()
'''
assert compile(method:'m', code).hasSequence([
- 'INVOKEDYNAMIC apply()Ljava/util/function/Function;',
- /* handle kind 0x6 : INVOKESTATIC */
- 'java/lang/invoke/LambdaMetafactory.metafactory',
- /* handle kind 0x5 : INVOKEVIRTUAL */
- 'java/lang/String.toUpperCase()Ljava/lang/String;'
+ 'INVOKEDYNAMIC apply()Ljava/util/function/Function;',
+ // handle kind 0x6 : INVOKESTATIC
+ 'java/lang/invoke/LambdaMetafactory.metafactory',
+ // handle kind 0x5 : INVOKEVIRTUAL
+ 'java/lang/String.toUpperCase()Ljava/lang/String;'
])
assertScript(code)
}
@@ -742,9 +783,9 @@ final class StaticCompilationTest extends AbstractBytecodeTestCase {
}
}
''').hasStrictSequence([
- 'ALOAD 0',
- 'INVOKEDYNAMIC invoke(LC;)Ljava/lang/Object;' // not INVOKEVIRTUAL
- ])
+ 'ALOAD 0',
+ 'INVOKEDYNAMIC invoke(LC;)Ljava/lang/Object;' // not INVOKEVIRTUAL
+ ])
def err = shouldFail '''
import groovy.transform.*