Capture all return cases

This commit is contained in:
Ahmad 2024-05-14 06:55:18 +02:00
parent a4c3e931a0
commit ac23df965d

View File

@ -1,5 +1,6 @@
package de.maishai.typedast.typedclass; package de.maishai.typedast.typedclass;
import de.maishai.ast.records.IfElse;
import de.maishai.ast.records.Method; import de.maishai.ast.records.Method;
import de.maishai.ast.records.Node; import de.maishai.ast.records.Node;
import de.maishai.ast.records.Parameter; import de.maishai.ast.records.Parameter;
@ -63,13 +64,39 @@ public class TypedMethod implements TypedNode {
return localVariables.stream().filter(localVariable -> localVariable.getName().equals(localVarName)).findFirst().get().getType(); return localVariables.stream().filter(localVariable -> localVariable.getName().equals(localVarName)).findFirst().get().getType();
} }
private boolean hasEvenReturnsInIfElseBlocks() {
List<TypedIfElse> 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 {
return false;
}
}
@Override @Override
public Type typeCheck(TypedClass clas) { public Type typeCheck(TypedClass clas) {
if(returnType != Type.VOID){ if (returnType != Type.VOID && !hasEvenReturnsInIfElseBlocks()) {
if(typedBlock.typeCheck(clas).getKind() != returnType.getKind()){ if (typedBlock.typeCheck(clas).getKind() != returnType.getKind()) {
throw new RuntimeException("Method " + name + " must return " + returnType); 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());
}
}
} }
return returnType; return returnType;
} }