diff --git a/src/main/java/de/maishai/typedast/typedclass/TypedMethod.java b/src/main/java/de/maishai/typedast/typedclass/TypedMethod.java index 5f2ee7b..5754dac 100644 --- a/src/main/java/de/maishai/typedast/typedclass/TypedMethod.java +++ b/src/main/java/de/maishai/typedast/typedclass/TypedMethod.java @@ -73,38 +73,50 @@ public class TypedMethod implements TypedNode { return localVariables.stream().filter(localVariable -> localVariable.getName().equals(localVarName)).findFirst().get().getType(); } - private boolean hasEvenReturnsInIfElseBlocks() { - List typedIfElses = new ArrayList<>(); - for (var stmt : typedBlock.getStmts()) { - if (stmt instanceof TypedIfElse ifElse) { - for (var stmt2 : ifElse.getIfTypedBlock().getStmts()) { - if (stmt2 instanceof TypedReturn) { - typedIfElses.add(ifElse); - } - } - for (var stmt2 : ifElse.getElseTypedBlock().getStmts()) { - if (stmt2 instanceof TypedReturn) { - typedIfElses.add(ifElse); - } - } - } - } - if (typedIfElses.size() % 2 == 0) { - return true; - } else { + + private boolean checkReturn(List pStmt) { + if (pStmt.isEmpty()) { return false; } + for (int i = pStmt.size() - 1; i >= 0; i--) { + TypedStatement statement = pStmt.get(i); + + if (statement instanceof TypedReturn) { + return true; + } + if (statement instanceof TypedIfElse typedIfElse) { + boolean hasReturnInIfBlock = checkReturn(typedIfElse.getIfTypedBlock().getStmts()); + boolean hasReturnInElseBlock = typedIfElse.getElseTypedBlock() != null && checkReturn(typedIfElse.getElseTypedBlock().getStmts()); + if (hasReturnInIfBlock && hasReturnInElseBlock) { + return true; + } + } + if (statement instanceof TypedFor typedFor) { + if (checkReturn(typedFor.getTypedBlock().getStmts())) { + return true; + } + } + if (statement instanceof TypedWhile typedWhile) { + if (checkReturn(typedWhile.getTypedBlock().getStmts())) { + return true; + } + } + if (statement instanceof TypedDoWhile typedDoWhile) { + if (checkReturn(typedDoWhile.getTypedBlock().getStmts())) { + return true; + } + } + + } + return false; } + @Override public Type typeCheck(TypedProgram typedProgram) { - if (returnType != Type.VOID && !hasEvenReturnsInIfElseBlocks()) { + if (returnType != Type.VOID && !checkReturn(typedBlock.getStmts())) { if (typedBlock.typeCheck(typedProgram).getKind() != returnType.getKind()) { - if (hasEvenReturnsInIfElseBlocks()) { - throw new RuntimeException("Method " + name + " must have even returns in if else blocks"); - } else { - throw new RuntimeException("Method " + name + " must return " + returnType.getKind()); - } + throw new RuntimeException("please use ´return´ correctly in the method " + name); } } return returnType;