Use wildcard constraint in foreach, fixes #291 and hopefully doesn't break anything

This commit is contained in:
Daniel Holle 2024-03-14 10:23:19 +01:00
parent e17f08263e
commit e354838491
4 changed files with 20 additions and 3 deletions

View File

@ -1,8 +1,9 @@
import java.util.ArrayList; import java.util.ArrayList;
import java.lang.Integer; import java.lang.Integer;
import java.lang.Number;
public class ForEach { public class ForEach {
m() { public m() {
var list = new ArrayList<>(); var list = new ArrayList<>();
list.add(1); list.add(2); list.add(3); list.add(1); list.add(2); list.add(3);
@ -12,4 +13,11 @@ public class ForEach {
} }
return sum; return sum;
} }
public m2() {
var list = new ArrayList<? extends Number>();
for (Number n : list) {
}
}
} }

View File

@ -1073,6 +1073,7 @@ public class Codegen {
mv.visitJumpInsn(IFEQ, end); mv.visitJumpInsn(IFEQ, end);
mv.visitInsn(DUP); mv.visitInsn(DUP);
mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Iterator", "next", "()Ljava/lang/Object;", true); mv.visitMethodInsn(INVOKEINTERFACE, "java/util/Iterator", "next", "()Ljava/lang/Object;", true);
mv.visitTypeInsn(CHECKCAST, localVar.type().getInternalName());
mv.visitVarInsn(ASTORE, localVar.index); mv.visitVarInsn(ASTORE, localVar.index);
generate(state, forEach.body()); generate(state, forEach.body());

View File

@ -246,7 +246,15 @@ public class OutputGenerator implements ASTVisitor {
@Override @Override
public void visit(ForEachStmt forEachStmt) { public void visit(ForEachStmt forEachStmt) {
out.append("for(");
forEachStmt.statement.accept(this);
out.append(" : ");
forEachStmt.expression.accept(this);
out.append(")\n");
tab();
out.append(tabs);
forEachStmt.block.accept(this);
untab();
} }
@Override @Override

View File

@ -138,7 +138,7 @@ public class TYPEStmt implements StatementVisitor {
@Override @Override
public void visit(ForEachStmt forEachStmt) { public void visit(ForEachStmt forEachStmt) {
var iterableType = new RefType(ASTFactory.createClass(java.lang.Iterable.class).getClassName(), Arrays.asList(forEachStmt.statement.getType()), new NullToken()); var iterableType = new RefType(ASTFactory.createClass(java.lang.Iterable.class).getClassName(), Arrays.asList(new ExtendsWildcardType(forEachStmt.statement.getType(), new NullToken())), new NullToken());
constraintsSet.addUndConstraint(new Pair(forEachStmt.expression.getType(), iterableType, PairOperator.SMALLERDOT, loc(forEachStmt.getOffset()))); constraintsSet.addUndConstraint(new Pair(forEachStmt.expression.getType(), iterableType, PairOperator.SMALLERDOT, loc(forEachStmt.getOffset())));
forEachStmt.statement.accept(this); forEachStmt.statement.accept(this);
forEachStmt.expression.accept(this); forEachStmt.expression.accept(this);