Implemented checkReturn

This commit is contained in:
Ahmad 2024-06-26 21:20:07 +02:00
parent 4532d220d3
commit 50b6a821bb

View File

@ -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<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 {
private boolean checkReturn(List<TypedStatement> 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;