/* * Code formatter project * CS 4481 */ package submit.ast; import submit.MIPSResult; import submit.RegisterAllocator; import submit.SymbolTable; /** * * @author edwajohn */ public class BinaryOperator extends AbstractNode implements Expression { private final Expression lhs, rhs; private final BinaryOperatorType type; public BinaryOperator(Expression lhs, BinaryOperatorType type, Expression rhs) { this.lhs = lhs; this.type = type; this.rhs = rhs; } public BinaryOperator(Expression lhs, String type, Expression rhs) { this.lhs = lhs; this.type = BinaryOperatorType.fromString(type); this.rhs = rhs; } @Override public void toCminus(StringBuilder builder, String prefix) { lhs.toCminus(builder, prefix); builder.append(" ").append(type).append(" "); rhs.toCminus(builder, prefix); } @Override public MIPSResult toMIPS(StringBuilder code, StringBuilder data, SymbolTable symbolTable, RegisterAllocator registerAllocator) { switch (type) { case PLUS: case MINUS: case TIMES: case DIVIDE: MIPSResult left = lhs.toMIPS(code, data, symbolTable, registerAllocator); String leftRegister = registerAllocator.getRegisterOrLoadIntoRegister(left, code); MIPSResult right = rhs.toMIPS(code, data, symbolTable, registerAllocator); String rightRegister = registerAllocator.getRegisterOrLoadIntoRegister(right, code); String resultRegister = registerAllocator.getAny(); switch (type) { case PLUS: code.append(String.format("add %s %s %s\n", resultRegister, leftRegister, rightRegister)); break; case MINUS: code.append(String.format("sub %s %s %s\n", resultRegister, leftRegister, rightRegister)); break; case TIMES: code.append(String.format("mult %s %s\n", leftRegister, rightRegister)); code.append(String.format("mflo %s\n", resultRegister)); break; case DIVIDE: code.append(String.format("div %s %s\n", leftRegister, rightRegister)); code.append(String.format("mflo %s\n", resultRegister)); break; default: break; } registerAllocator.clear(leftRegister); registerAllocator.clear(rightRegister); return MIPSResult.createRegisterResult(resultRegister, VarType.INT); default: break; } return MIPSResult.createVoidResult(); } }