From ac23df965d33ddbb92248fc1937785609da0d632 Mon Sep 17 00:00:00 2001 From: Ahmad Date: Tue, 14 May 2024 06:55:18 +0200 Subject: [PATCH] Capture all return cases --- .../typedast/typedclass/TypedMethod.java | 35 ++++++++++++++++--- 1 file changed, 31 insertions(+), 4 deletions(-) diff --git a/src/main/java/de/maishai/typedast/typedclass/TypedMethod.java b/src/main/java/de/maishai/typedast/typedclass/TypedMethod.java index 219d41e..cd701eb 100644 --- a/src/main/java/de/maishai/typedast/typedclass/TypedMethod.java +++ b/src/main/java/de/maishai/typedast/typedclass/TypedMethod.java @@ -1,5 +1,6 @@ package de.maishai.typedast.typedclass; +import de.maishai.ast.records.IfElse; import de.maishai.ast.records.Method; import de.maishai.ast.records.Node; 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(); } + 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 { + return false; + } + } @Override public Type typeCheck(TypedClass clas) { - if(returnType != Type.VOID){ - if(typedBlock.typeCheck(clas).getKind() != returnType.getKind()){ - throw new RuntimeException("Method " + name + " must return " + returnType); - } + if (returnType != Type.VOID && !hasEvenReturnsInIfElseBlocks()) { + if (typedBlock.typeCheck(clas).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()); + } + } } return returnType; }