summaryrefslogtreecommitdiff
path: root/Homework/cs5300/compiler/p5-compiler/submit/ast/UnaryOperator.java
diff options
context:
space:
mode:
Diffstat (limited to 'Homework/cs5300/compiler/p5-compiler/submit/ast/UnaryOperator.java')
-rw-r--r--Homework/cs5300/compiler/p5-compiler/submit/ast/UnaryOperator.java54
1 files changed, 54 insertions, 0 deletions
diff --git a/Homework/cs5300/compiler/p5-compiler/submit/ast/UnaryOperator.java b/Homework/cs5300/compiler/p5-compiler/submit/ast/UnaryOperator.java
new file mode 100644
index 0000000..799a0be
--- /dev/null
+++ b/Homework/cs5300/compiler/p5-compiler/submit/ast/UnaryOperator.java
@@ -0,0 +1,54 @@
+/*
+ * Code formatter project
+ * CS 4481
+ */
+package submit.ast;
+
+import submit.MIPSResult;
+import submit.RegisterAllocator;
+import submit.SymbolTable;
+
+/**
+ *
+ * @author edwajohn
+ */
+public class UnaryOperator extends AbstractNode implements Expression {
+
+ private final UnaryOperatorType type;
+ private final Expression expression;
+
+ public UnaryOperator(String type, Expression expression) {
+ this.type = UnaryOperatorType.fromString(type);
+ this.expression = expression;
+ }
+
+ @Override
+ public void toCminus(StringBuilder builder, String prefix) {
+ builder.append(type);
+ expression.toCminus(builder, prefix);
+ }
+ @Override
+ public MIPSResult toMIPS(StringBuilder code, StringBuilder data,
+ SymbolTable symbolTable,
+ RegisterAllocator regAllocator) {
+ MIPSResult result =
+ expression.toMIPS(code, data, symbolTable, regAllocator);
+
+ if (type == UnaryOperatorType.NEG) {
+ code.append("# Negation\n");
+ if (result.getAddress() != null) {
+ String reg = regAllocator.getRegisterOrLoadIntoRegister(result, code);
+
+ code.append(String.format("sub %s, $zero, %s\n", reg, reg))
+ .append(String.format("sw %s 0(%s)\n", reg, result.getAddress()));
+
+ regAllocator.clear(reg);
+ } else {
+ code.append(String.format("sub %s, $zero, %s\n", result.getRegister(),
+ result.getRegister()));
+ }
+ }
+
+ return result;
+ }
+}