Refactored TypedAST and added a new exception type

This commit is contained in:
ahmad 2024-07-05 09:40:19 +02:00
parent 976f9c2ba6
commit 92c08ac3de
4 changed files with 19 additions and 10 deletions

View File

@ -0,0 +1,7 @@
package de.maishai.typedast.ExceptionHandler;
public class InvalidWhileConditionException extends RuntimeException{
public InvalidWhileConditionException() {
super("Invalid while condition");
}
}

View File

@ -19,11 +19,11 @@ public final class TypedDeclaration implements TypedNode {
private Type type;
public TypedDeclaration(TypedProgram typedProgram, Declaration declaration) {
convertToTypedDeclaration(typedProgram, declaration);
convertToTypedDeclaration(declaration);
typeCheck(typedProgram);
}
private void convertToTypedDeclaration(TypedProgram typedProgram, Declaration declaration) {
private void convertToTypedDeclaration(Declaration declaration) {
name = declaration.name();
type = declaration.type();
}

View File

@ -35,15 +35,17 @@ public class TypedIfElse implements TypedStatement {
@Override
public Type typeCheck(TypedProgram typedProgram) {
Type ifType = ifTypedBlock.typeCheck(typedProgram);
Type elseType = elseTypedBlock.typeCheck(typedProgram);
if (ifTypedBlock.typeCheck(typedProgram) == elseTypedBlock.typeCheck(typedProgram)) {
type = ifTypedBlock.typeCheck(typedProgram);
if (ifType == elseType) {
type = ifType;
}
if (elseTypedBlock.typeCheck(typedProgram) == Type.VOID) {
type = ifTypedBlock.typeCheck(typedProgram);
if (elseType == Type.VOID) {
type = ifType;
}
if (ifTypedBlock.typeCheck(typedProgram) == Type.VOID) {
type = elseTypedBlock.typeCheck(typedProgram);
if (ifType == Type.VOID) {
type = elseType;
}
return type;

View File

@ -1,6 +1,7 @@
package de.maishai.typedast.typedclass;
import de.maishai.ast.records.While;
import de.maishai.typedast.ExceptionHandler.InvalidWhileConditionException;
import de.maishai.typedast.MethodContext;
import de.maishai.typedast.Type;
import de.maishai.typedast.TypedExpression;
@ -28,11 +29,10 @@ public class TypedWhile implements TypedStatement {
cond = convertExpression(typedProgram, unTypedWhile.cond());
typedBlock = new TypedBlock(typedProgram, unTypedWhile.block());
}
@Override
public Type typeCheck(TypedProgram typedProgram) {
if (cond.typeCheck(typedProgram) != Type.BOOL) {
throw new RuntimeException("While condition must be a boolean");
throw new InvalidWhileConditionException();
}
type = typedBlock.typeCheck(typedProgram);
return type;