Skip to content

Instantly share code, notes, and snippets.

@aristotaloss
Created July 31, 2015 22:21
Show Gist options
  • Select an option

  • Save aristotaloss/293f49cb260536017b5e to your computer and use it in GitHub Desktop.

Select an option

Save aristotaloss/293f49cb260536017b5e to your computer and use it in GitHub Desktop.
package nl.bartpelle.adder.ast;
import nl.bartpelle.adder.AdderCtx;
import nl.bartpelle.adder.Instruction;
import nl.bartpelle.adder.enums.BinaryOperator;
import nl.bartpelle.adder.enums.Type;
import java.util.List;
/**
* Created by Bart on 8/16/2014.
*
*/
public class ArithmeticNode implements AstNode {
public AstNode left;
public AstNode right;
public BinaryOperator op;
public ArithmeticNode(AstNode left, AstNode right, BinaryOperator op) {
this.left = left;
this.right = right;
this.op = op;
}
@Override
public void dasm() {
left.dasm();
right.dasm();
System.out.println(op.toString().toLowerCase());
}
@Override public Type type() {
Type lefty = left.type();
Type righty = right.type();
if (lefty == Type.STRING || righty == Type.STRING) {
if (op != BinaryOperator.ADD)
throw new RuntimeException("cannot apply operator " + op.toString().toLowerCase() + " to string");
return Type.STRING; /* Concat */
}
if (lefty == Type.BOOL || righty == Type.BOOL) { /* Any boolean? */
//TODO boolean algebra (& and | etc)
throw new RuntimeException("operation " + op.toString().toLowerCase() + " is not valid for booleans");
}
if (lefty == Type.LONG || righty == Type.LONG)
return Type.LONG;
if (lefty == Type.INTEGER && righty == Type.INTEGER)
return Type.INTEGER;
throw new RuntimeException("unable to properly resolve arith type for " + lefty + " and " + righty);
}
@Override
public void encode(List<Instruction> out, AdderCtx ctx) {
left.encode(out, ctx);
right.encode(out, ctx);
if (left.type() == Type.STRING || right.type() == Type.STRING) {
out.add(Instruction.CAT);
} else {
switch (op) {
case ADD:
out.add(Instruction.ADD);
break;
case SUBTRACT:
out.add(Instruction.SUB);
break;
case MULTIPLY:
out.add(Instruction.MUL);
break;
case DIVIDE:
out.add(Instruction.DIV);
break;
case MODULO:
out.add(Instruction.MOD);
break;
case OR:
out.add(Instruction.OR);
break;
case XOR:
break;
case AND:
out.add(Instruction.OR);
break;
case SHIFTRIGHT:
break;
case SHIFTLEFT:
break;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment