65 lines
2.7 KiB
Java
65 lines
2.7 KiB
Java
package io.gitlab.jfronny.muscript.ast.compare;
|
|
|
|
import io.gitlab.jfronny.muscript.compiler.ExprWriter;
|
|
import io.gitlab.jfronny.muscript.compiler.Order;
|
|
import io.gitlab.jfronny.muscript.data.Scope;
|
|
import io.gitlab.jfronny.muscript.ast.*;
|
|
import io.gitlab.jfronny.muscript.ast.literal.NumberLiteral;
|
|
import io.gitlab.jfronny.muscript.ast.math.*;
|
|
|
|
import java.io.IOException;
|
|
|
|
public class Greater extends BoolExpr {
|
|
public final NumberExpr left;
|
|
public final NumberExpr right;
|
|
|
|
public Greater(int chStart, int chEnd, NumberExpr left, NumberExpr right) {
|
|
super(Order.Comparison, chStart, chEnd);
|
|
this.left = left;
|
|
this.right = right;
|
|
}
|
|
|
|
@Override
|
|
public Boolean get(Scope dataRoot) {
|
|
return left.get(dataRoot) > right.get(dataRoot);
|
|
}
|
|
|
|
@Override
|
|
public BoolExpr optimize() {
|
|
NumberExpr left = this.left.optimize();
|
|
NumberExpr right = this.right.optimize();
|
|
if (left instanceof NumberLiteral litL && right instanceof NumberLiteral litR)
|
|
return Expr.literal(chStart, chEnd, litL.value > litR.value);
|
|
if (left instanceof Divide divide)
|
|
return new Greater(chStart, chEnd, divide.dividend, new Multiply(divide.chStart, divide.chEnd, right, divide.divisor)).optimize();
|
|
if (left instanceof Invert invert)
|
|
return new Greater(chStart, chEnd, new Invert(right.chStart, right.chEnd, right), invert.inner).optimize();
|
|
if (left instanceof Minus minus)
|
|
return new Greater(chStart, chEnd, minus.minuend, new Plus(minus.chStart, minus.chEnd, minus.subtrahend, right)).optimize();
|
|
// Modulo is left out because it is too complicated for this naive impl
|
|
// Multiply is left out since it would transform into a division and may be 0
|
|
if (left instanceof Plus plus)
|
|
return new Greater(chStart, chEnd, plus.augend, new Minus(plus.chStart, plus.chEnd, plus.addend, right)).optimize();
|
|
// Power is left out because it can't be transformed cleanly either
|
|
return new Greater(chStart, chEnd, left, right);
|
|
}
|
|
|
|
@Override
|
|
public void decompile(ExprWriter writer) throws IOException {
|
|
if (left instanceof NumberLiteral && !(right instanceof NumberLiteral)) {
|
|
parenthesize(right, writer, false);
|
|
writer.append(" < ");
|
|
parenthesize(left, writer, true);
|
|
} else {
|
|
parenthesize(left, writer, false);
|
|
writer.append(" > ");
|
|
parenthesize(right, writer, true);
|
|
}
|
|
}
|
|
|
|
@Override
|
|
public boolean equals(Object obj) {
|
|
return obj instanceof Greater greater && left.equals(greater.left) && right.equals(greater.right);
|
|
}
|
|
}
|