2024-04-25 11:27:38 +00:00
|
|
|
package abstractSyntaxTree.Statement;
|
|
|
|
|
2024-05-02 11:12:39 +00:00
|
|
|
import TypeCheck.TypeCheckResult;
|
|
|
|
import TypeCheck.AbstractType;
|
2024-05-02 12:31:37 +00:00
|
|
|
import abstractSyntaxTree.Expression.IExpression;
|
2024-05-07 11:50:51 +00:00
|
|
|
import org.objectweb.asm.*;
|
2024-05-02 11:12:39 +00:00
|
|
|
|
|
|
|
public class IfElseStatement extends AbstractType implements IStatement{
|
2024-05-02 12:31:37 +00:00
|
|
|
IExpression condition;
|
|
|
|
IStatement ifStatement;
|
|
|
|
IStatement elseStatement;
|
|
|
|
|
|
|
|
public IfElseStatement(IExpression condition, IStatement ifStatement, IStatement elseStatement) {
|
|
|
|
this.condition = condition;
|
|
|
|
this.ifStatement = ifStatement;
|
|
|
|
this.elseStatement = elseStatement;
|
|
|
|
}
|
|
|
|
|
2024-05-02 11:12:39 +00:00
|
|
|
@Override
|
|
|
|
public TypeCheckResult typeCheck() throws Exception {
|
2024-05-02 12:31:37 +00:00
|
|
|
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;
|
2024-05-02 11:12:39 +00:00
|
|
|
}
|
2024-05-07 11:50:51 +00:00
|
|
|
|
|
|
|
@Override
|
2024-05-08 10:56:40 +00:00
|
|
|
public void codeGen(MethodVisitor mv) throws Exception {
|
2024-05-07 11:50:51 +00:00
|
|
|
|
|
|
|
Label conditionFalse = new Label();
|
|
|
|
Label statementEnd = new Label();
|
|
|
|
|
2024-05-08 11:51:20 +00:00
|
|
|
condition.codeGen(mv);
|
2024-05-07 11:50:51 +00:00
|
|
|
|
|
|
|
mv.visitJumpInsn(Opcodes.IFEQ, conditionFalse); //Checks if the condition is false (0)
|
2024-05-08 10:56:40 +00:00
|
|
|
ifStatement.codeGen(mv); //If the condition is true, execute the ifBlock
|
2024-05-07 11:50:51 +00:00
|
|
|
mv.visitJumpInsn(Opcodes.GOTO, statementEnd); //Jump to the end of the if-else statement
|
|
|
|
|
|
|
|
mv.visitLabel(conditionFalse);
|
2024-05-08 10:56:40 +00:00
|
|
|
elseStatement.codeGen(mv); //If the condition is false, execute the elseBlock
|
2024-05-07 11:50:51 +00:00
|
|
|
|
|
|
|
mv.visitLabel(statementEnd); //End of the if-else statement
|
|
|
|
|
|
|
|
}
|
2024-04-25 11:27:38 +00:00
|
|
|
}
|