Skip to content

Commit

Permalink
GROOVY-8133, GROOVY-10476, GROOVY-10477
Browse files Browse the repository at this point in the history
  • Loading branch information
eric-milles committed Feb 9, 2022
1 parent 85fc2db commit 7abec84
Show file tree
Hide file tree
Showing 10 changed files with 1,016 additions and 41 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -2380,6 +2380,29 @@ public void testCompileStatic8051() {
runConformTest(sources, "1");
}

@Test
public void testCompileStatic8133() {
//@formatter:off
String[] sources = {
"Main.groovy",
"import groovy.transform.*\n" +
"import static org.codehaus.groovy.transform.stc.StaticTypesMarker.*\n" +
"\n" +
"@CompileStatic void test() {\n" +
" @ASTTest(phase=INSTRUCTION_SELECTION, value={\n" +
" def list_type = node.getNodeMetaData(INFERRED_TYPE)\n" +
" assert list_type?.toString(false) == 'java.util.List<java.lang.String>'\n" +
" })\n" +
" def list = ['foo','bar','baz'].stream()*.toUpperCase()\n" +
" print list\n" +
"}\n" +
"test()\n",
};
//@formatter:on

runConformTest(sources, "[FOO, BAR, BAZ]");
}

@Test
public void testCompileStatic8176() {
//@formatter:off
Expand Down Expand Up @@ -7278,4 +7301,24 @@ public void testCompileStatic10457() {

runConformTest(sources, "works");
}

@Test
public void testCompileStatic10476() {
//@formatter:off
String[] sources = {
"Main.groovy",
"@groovy.transform.CompileStatic\n" +
"void test() {\n" +
" def list = []\n" +
" for (e in ['foo','bar','baz'].stream()) {\n" +
" list.add(e.toUpperCase())\n" +
" }\n" +
" print list\n" +
"}\n" +
"test()\n",
};
//@formatter:on

runConformTest(sources, "[FOO, BAR, BAZ]");
}
}
2 changes: 1 addition & 1 deletion base/org.codehaus.groovy25/.checkstyle
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@
<file-match-pattern match-pattern="groovy/classgen/asm/(Optimizing)?StatementWriter.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/classgen/asm/sc/StaticInvocationWriter.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/classgen/asm/sc/StaticPropertyAccessHelper.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/classgen/asm/sc/StaticTypes(CallSite|Closure)Writer.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/classgen/asm/sc/StaticTypes(CallSite|Closure|Statement)Writer.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/classgen/asm/sc/StaticTypesTypeChooser.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/CompilationUnit.java" include-pattern="false" />
<file-match-pattern match-pattern="groovy/control/CompilerConfiguration.java" include-pattern="false" />
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,310 @@
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
package org.codehaus.groovy.classgen.asm.sc;

import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.ast.expr.MethodCallExpression;
import org.codehaus.groovy.ast.stmt.BlockStatement;
import org.codehaus.groovy.ast.stmt.ForStatement;
import org.codehaus.groovy.ast.tools.GeneralUtils;
import org.codehaus.groovy.classgen.AsmClassGenerator;
import org.codehaus.groovy.classgen.asm.BytecodeVariable;
import org.codehaus.groovy.classgen.asm.CompileStack;
import org.codehaus.groovy.classgen.asm.MethodCaller;
import org.codehaus.groovy.classgen.asm.OperandStack;
import org.codehaus.groovy.classgen.asm.StatementWriter;
import org.codehaus.groovy.classgen.asm.TypeChooser;
import org.codehaus.groovy.transform.stc.StaticTypeCheckingSupport;
import groovyjarjarasm.asm.Label;
import groovyjarjarasm.asm.MethodVisitor;

import java.util.Enumeration;
import java.util.Objects;

import static groovyjarjarasm.asm.Opcodes.AALOAD;
import static groovyjarjarasm.asm.Opcodes.ALOAD;
import static groovyjarjarasm.asm.Opcodes.ARRAYLENGTH;
import static groovyjarjarasm.asm.Opcodes.BALOAD;
import static groovyjarjarasm.asm.Opcodes.CALOAD;
import static groovyjarjarasm.asm.Opcodes.DALOAD;
import static groovyjarjarasm.asm.Opcodes.DUP;
import static groovyjarjarasm.asm.Opcodes.FALOAD;
import static groovyjarjarasm.asm.Opcodes.GOTO;
import static groovyjarjarasm.asm.Opcodes.IALOAD;
import static groovyjarjarasm.asm.Opcodes.ICONST_0;
import static groovyjarjarasm.asm.Opcodes.IFEQ;
import static groovyjarjarasm.asm.Opcodes.IFNULL;
import static groovyjarjarasm.asm.Opcodes.IF_ICMPGE;
import static groovyjarjarasm.asm.Opcodes.ILOAD;
import static groovyjarjarasm.asm.Opcodes.INVOKESTATIC;
import static groovyjarjarasm.asm.Opcodes.LALOAD;
import static groovyjarjarasm.asm.Opcodes.SALOAD;

/**
* A class to write out the optimized statements
*/
public class StaticTypesStatementWriter extends StatementWriter {

private static final ClassNode ENUMERATION_CLASSNODE = ClassHelper.make(Enumeration.class);
private static final MethodCaller ENUMERATION_NEXT_METHOD = MethodCaller.newInterface(Enumeration.class, "nextElement");
private static final MethodCaller ENUMERATION_HASMORE_METHOD = MethodCaller.newInterface(Enumeration.class, "hasMoreElements");

private final StaticTypesWriterController controller;

public StaticTypesStatementWriter(StaticTypesWriterController controller) {
super(controller);
this.controller = controller;
}

@Override
public void writeBlockStatement(BlockStatement statement) {
controller.switchToFastPath();
super.writeBlockStatement(statement);
controller.switchToSlowPath();
}

@Override
protected void writeForInLoop(final ForStatement loop) {
controller.getAcg().onLineNumber(loop,"visitForLoop");
writeStatementLabel(loop);

CompileStack compileStack = controller.getCompileStack();
MethodVisitor mv = controller.getMethodVisitor();
OperandStack operandStack = controller.getOperandStack();

compileStack.pushLoop(loop.getVariableScope(), loop.getStatementLabels());

// Identify type of collection
TypeChooser typeChooser = controller.getTypeChooser();
Expression collectionExpression = loop.getCollectionExpression();
ClassNode collectionType = typeChooser.resolveType(collectionExpression, controller.getClassNode());
Parameter loopVariable = loop.getVariable();
int size = operandStack.getStackLength();
if (collectionType.isArray() && loopVariable.getType().equals(collectionType.getComponentType())) { // GRECLIPSE edit
writeOptimizedForEachLoop(compileStack, operandStack, mv, loop, collectionExpression, collectionType, loopVariable);
} else if (ENUMERATION_CLASSNODE.equals(collectionType)) {
writeEnumerationBasedForEachLoop(compileStack, operandStack, mv, loop, collectionExpression, collectionType, loopVariable);
} else {
writeIteratorBasedForEachLoop(compileStack, operandStack, mv, loop, collectionExpression, collectionType, loopVariable);
}
operandStack.popDownTo(size);
compileStack.pop();
}

private void writeOptimizedForEachLoop(
CompileStack compileStack,
OperandStack operandStack,
MethodVisitor mv,
ForStatement loop,
Expression collectionExpression,
ClassNode collectionType,
Parameter loopVariable) {
BytecodeVariable variable = compileStack.defineVariable(loopVariable, false);

Label continueLabel = compileStack.getContinueLabel();
Label breakLabel = compileStack.getBreakLabel();

AsmClassGenerator acg = controller.getAcg();

// load array on stack
collectionExpression.visit(acg);
mv.visitInsn(DUP);
int array = compileStack.defineTemporaryVariable("$arr", collectionType, true);
mv.visitJumpInsn(IFNULL, breakLabel);

// $len = array.length
mv.visitVarInsn(ALOAD, array);
mv.visitInsn(ARRAYLENGTH);
operandStack.push(ClassHelper.int_TYPE);
int arrayLen = compileStack.defineTemporaryVariable("$len", ClassHelper.int_TYPE, true);

// $idx = 0
mv.visitInsn(ICONST_0);
operandStack.push(ClassHelper.int_TYPE);
int loopIdx = compileStack.defineTemporaryVariable("$idx", ClassHelper.int_TYPE, true);

mv.visitLabel(continueLabel);
// $idx<$len?
mv.visitVarInsn(ILOAD, loopIdx);
mv.visitVarInsn(ILOAD, arrayLen);
mv.visitJumpInsn(IF_ICMPGE, breakLabel);

// get array element
loadFromArray(mv, variable, array, loopIdx);

// $idx++
mv.visitIincInsn(loopIdx, 1);

// loop body
loop.getLoopBlock().visit(acg);

mv.visitJumpInsn(GOTO, continueLabel);

mv.visitLabel(breakLabel);

compileStack.removeVar(loopIdx);
compileStack.removeVar(arrayLen);
compileStack.removeVar(array);
}

private void loadFromArray(MethodVisitor mv, BytecodeVariable variable, int array, int iteratorIdx) {
OperandStack os = controller.getOperandStack();
mv.visitVarInsn(ALOAD, array);
mv.visitVarInsn(ILOAD, iteratorIdx);

ClassNode varType = variable.getType();
boolean primitiveType = ClassHelper.isPrimitiveType(varType);
boolean isByte = ClassHelper.byte_TYPE.equals(varType);
boolean isShort = ClassHelper.short_TYPE.equals(varType);
boolean isInt = ClassHelper.int_TYPE.equals(varType);
boolean isLong = ClassHelper.long_TYPE.equals(varType);
boolean isFloat = ClassHelper.float_TYPE.equals(varType);
boolean isDouble = ClassHelper.double_TYPE.equals(varType);
boolean isChar = ClassHelper.char_TYPE.equals(varType);
boolean isBoolean = ClassHelper.boolean_TYPE.equals(varType);

if (primitiveType) {
if (isByte) {
mv.visitInsn(BALOAD);
}
if (isShort) {
mv.visitInsn(SALOAD);
}
if (isInt || isChar || isBoolean) {
mv.visitInsn(isChar ? CALOAD : isBoolean ? BALOAD : IALOAD);
}
if (isLong) {
mv.visitInsn(LALOAD);
}
if (isFloat) {
mv.visitInsn(FALOAD);
}
if (isDouble) {
mv.visitInsn(DALOAD);
}
} else {
mv.visitInsn(AALOAD);
}
os.push(varType);
os.storeVar(variable);
}

private void writeIteratorBasedForEachLoop(
CompileStack compileStack,
OperandStack operandStack,
MethodVisitor mv,
ForStatement loop,
Expression collectionExpression,
ClassNode collectionType,
Parameter loopVariable) {
// Declare the loop counter.
BytecodeVariable variable = compileStack.defineVariable(loopVariable, false);
/* GRECLIPSE edit -- GROOVY-10476
if (StaticTypeCheckingSupport.implementsInterfaceOrIsSubclassOf(collectionType, ITERABLE_CLASSNODE)) {
MethodCallExpression iterator = new MethodCallExpression(collectionExpression, "iterator", new ArgumentListExpression());
iterator.setMethodTarget(collectionType.getMethod("iterator", Parameter.EMPTY_ARRAY));
iterator.setImplicitThis(false);
iterator.visit(controller.getAcg());
*/
MethodNode iterator = collectionType.getMethod("iterator", Parameter.EMPTY_ARRAY);
if (iterator == null) {
iterator = StaticTypeCheckingSupport.collectAllInterfaces(collectionType).stream()
.map(in -> in.getMethod("iterator", Parameter.EMPTY_ARRAY))
.filter(Objects::nonNull).findFirst().orElse(null);
}
if (iterator != null && iterator.getReturnType().equals(ClassHelper.Iterator_TYPE)) {
MethodCallExpression call = GeneralUtils.callX(collectionExpression, "iterator");
call.setImplicitThis(false);
call.setMethodTarget(iterator);
call.visit(controller.getAcg());
// GRECLIPSE end
} else {
collectionExpression.visit(controller.getAcg());
mv.visitMethodInsn(INVOKESTATIC, "org/codehaus/groovy/runtime/DefaultGroovyMethods", "iterator", "(Ljava/lang/Object;)Ljava/util/Iterator;", false);
operandStack.replace(ClassHelper.Iterator_TYPE);
}

// Then get the iterator and generate the loop control

int iteratorIdx = compileStack.defineTemporaryVariable("iterator", ClassHelper.Iterator_TYPE, true);

Label continueLabel = compileStack.getContinueLabel();
Label breakLabel = compileStack.getBreakLabel();

mv.visitLabel(continueLabel);
mv.visitVarInsn(ALOAD, iteratorIdx);
writeIteratorHasNext(mv);
// note: ifeq tests for ==0, a boolean is 0 if it is false
mv.visitJumpInsn(IFEQ, breakLabel);

mv.visitVarInsn(ALOAD, iteratorIdx);
writeIteratorNext(mv);
operandStack.push(ClassHelper.OBJECT_TYPE);
operandStack.storeVar(variable);

// Generate the loop body
loop.getLoopBlock().visit(controller.getAcg());

mv.visitJumpInsn(GOTO, continueLabel);
mv.visitLabel(breakLabel);
compileStack.removeVar(iteratorIdx);
}

private void writeEnumerationBasedForEachLoop(
CompileStack compileStack,
OperandStack operandStack,
MethodVisitor mv,
ForStatement loop,
Expression collectionExpression,
ClassNode collectionType,
Parameter loopVariable) {
// Declare the loop counter.
BytecodeVariable variable = compileStack.defineVariable(loopVariable, false);

collectionExpression.visit(controller.getAcg());

// Then get the iterator and generate the loop control

int enumIdx = compileStack.defineTemporaryVariable("$enum", ENUMERATION_CLASSNODE, true);

Label continueLabel = compileStack.getContinueLabel();
Label breakLabel = compileStack.getBreakLabel();

mv.visitLabel(continueLabel);
mv.visitVarInsn(ALOAD, enumIdx);
ENUMERATION_HASMORE_METHOD.call(mv);
// note: ifeq tests for ==0, a boolean is 0 if it is false
mv.visitJumpInsn(IFEQ, breakLabel);

mv.visitVarInsn(ALOAD, enumIdx);
ENUMERATION_NEXT_METHOD.call(mv);
operandStack.push(ClassHelper.OBJECT_TYPE);
operandStack.storeVar(variable);

// Generate the loop body
loop.getLoopBlock().visit(controller.getAcg());

mv.visitJumpInsn(GOTO, continueLabel);
mv.visitLabel(breakLabel);
}
}
Loading

0 comments on commit 7abec84

Please sign in to comment.