Fix for loop overflowing the stack. Fixes #122

This commit is contained in:
Daniel Holle 2024-03-04 10:58:26 +01:00
parent 584690596e
commit f11d4b0716
6 changed files with 36 additions and 6 deletions

View File

@ -0,0 +1,12 @@
import java.lang.Integer;
import java.lang.Boolean;
class Bug122 {
void main() {
if (true) {
for (Integer i = 0; i < 10; i++) {
}
}
}
}

View File

@ -886,8 +886,12 @@ public class Codegen {
case TargetFor _for: {
state.enterScope();
var localCounter = state.localCounter;
if (_for.init() != null)
_for.init().forEach(e -> generate(state, e));
if (_for.init() != null) {
for (var e : _for.init()) {
generate(state, e);
if (e instanceof TargetAssign) mv.visitInsn(POP);
}
}
Label start = new Label();
Label end = new Label();

View File

@ -513,8 +513,9 @@ public class StatementGenerator {
} else {
return new ForStmt(
stmt.getStart(),
convert(control.forInit().localVariableDeclaration()),
convert(control.expression()), control.forUpdate.expression().stream().map(this::convert).toList(),
control.forInit() != null ? convert(control.forInit().localVariableDeclaration()) : List.of(),
control.expression() != null ? convert(control.expression()) : null,
control.forUpdate != null ? control.forUpdate.expression().stream().map(this::convert).toList() : List.of(),
convert(stmt.statement())
);
}

View File

@ -141,7 +141,12 @@ public class StatementToTargetExpression implements ASTVisitor {
@Override
public void visit(ForStmt forStmt) {
result = new TargetFor(forStmt.initializer.stream().map(converter::convert).toList(), converter.convert(forStmt.condition), forStmt.loopExpr.stream().map(converter::convert).toList(), converter.convert(forStmt.block));
result = new TargetFor(
forStmt.initializer.stream().map(converter::convert).toList(),
forStmt.condition != null ? converter.convert(forStmt.condition) : null,
forStmt.loopExpr.stream().map(converter::convert).toList(),
converter.convert(forStmt.block)
);
}
@Override

View File

@ -129,6 +129,7 @@ public class TYPEStmt implements StatementVisitor {
@Override
public void visit(ForStmt forStmt) {
forStmt.initializer.forEach(s -> s.accept(this));
if (forStmt.condition != null)
forStmt.condition.accept(this);
forStmt.loopExpr.forEach(e -> e.accept(this));
forStmt.block.accept(this);

View File

@ -841,4 +841,11 @@ public class TestComplete {
var clazz = classFiles.get("Op2");
var instance = clazz.getDeclaredConstructor().newInstance();
}
@Test
public void testBug122() throws Exception {
var classFiles = generateClassFiles(new ByteArrayClassLoader(), "Bug122.jav");
var clazz = classFiles.get("Bug122");
var instance = clazz.getDeclaredConstructor().newInstance();
}
}