NichtHaskell/Source/abstractSyntaxTree/Statement/IfElseStatement.java
Jochen Seyfried 2527d15467 Added Bytecodegeneration to the missing classes
Also included some TODOs in areas where parameters and some connections are missing
2024-05-07 13:50:51 +02:00

59 lines
1.9 KiB
Java

package abstractSyntaxTree.Statement;
import TypeCheck.TypeCheckResult;
import TypeCheck.AbstractType;
import abstractSyntaxTree.Expression.IExpression;
import org.objectweb.asm.*;
public class IfElseStatement extends AbstractType implements IStatement{
IExpression condition;
IStatement ifStatement;
IStatement elseStatement;
public IfElseStatement(IExpression condition, IStatement ifStatement, IStatement elseStatement) {
this.condition = condition;
this.ifStatement = ifStatement;
this.elseStatement = elseStatement;
}
@Override
public TypeCheckResult typeCheck() throws Exception {
TypeCheckResult result = new TypeCheckResult();
TypeCheckResult conditionType = condition.typeCheck();
if (!conditionType.equals("bool")) {
throw new IllegalArgumentException("should be boolean");
}
TypeCheckResult ifStatementType = ifStatement.typeCheck();
TypeCheckResult elseStatementType = elseStatement.typeCheck();
if (!ifStatementType.equals(elseStatementType)) {
throw new IllegalArgumentException("if and else have different types");
}
result.type = elseStatementType.type;
return result;
}
@Override
public void CodeGen(MethodVisitor mv) throws Exception {
Label conditionFalse = new Label();
Label statementEnd = new Label();
condition.CodeGen(mv);
mv.visitJumpInsn(Opcodes.IFEQ, conditionFalse); //Checks if the condition is false (0)
ifStatement.CodeGen(mv); //If the condition is true, execute the ifBlock
mv.visitJumpInsn(Opcodes.GOTO, statementEnd); //Jump to the end of the if-else statement
mv.visitLabel(conditionFalse);
elseStatement.CodeGen(mv); //If the condition is false, execute the elseBlock
mv.visitLabel(statementEnd); //End of the if-else statement
}
}