70 lines
2.7 KiB
Java
70 lines
2.7 KiB
Java
package io.gitlab.jfronny.muscript.ast.compare;
|
|
|
|
import io.gitlab.jfronny.muscript.compiler.*;
|
|
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;
|
|
import java.util.stream.Stream;
|
|
|
|
public class Greater extends BoolExpr {
|
|
public final NumberExpr left;
|
|
public final NumberExpr right;
|
|
|
|
public Greater(CodeLocation location, NumberExpr left, NumberExpr right) {
|
|
super(Order.Comparison, location);
|
|
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 literal(location, litL.value > litR.value);
|
|
if (left instanceof Divide divide)
|
|
return new Greater(location, divide.dividend, new Multiply(divide.location, right, divide.divisor)).optimize();
|
|
if (left instanceof Invert invert)
|
|
return new Greater(location, new Invert(right.location, right), invert.inner).optimize();
|
|
if (left instanceof Minus minus)
|
|
return new Greater(location, minus.minuend, new Plus(minus.location, 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(location, plus.augend, new Minus(plus.location, plus.addend, right)).optimize();
|
|
// Power is left out because it can't be transformed cleanly either
|
|
return new Greater(location, left, right);
|
|
}
|
|
|
|
@Override
|
|
public Stream<Expr<?>> extractSideEffects() {
|
|
return Stream.concat(left.extractSideEffects(), right.extractSideEffects());
|
|
}
|
|
|
|
@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);
|
|
}
|
|
}
|