63 lines
2.3 KiB
Java
63 lines
2.3 KiB
Java
package io.gitlab.jfronny.muscript.ast.math;
|
|
|
|
import io.gitlab.jfronny.muscript.compiler.*;
|
|
import io.gitlab.jfronny.muscript.data.Scope;
|
|
import io.gitlab.jfronny.muscript.ast.Expr;
|
|
import io.gitlab.jfronny.muscript.ast.NumberExpr;
|
|
import io.gitlab.jfronny.muscript.ast.literal.NumberLiteral;
|
|
|
|
import java.io.IOException;
|
|
import java.util.stream.Stream;
|
|
|
|
public class Power extends NumberExpr {
|
|
private final NumberExpr base;
|
|
private final NumberExpr exponent;
|
|
|
|
public Power(CodeLocation location, NumberExpr base, NumberExpr exponent) {
|
|
super(Order.Exp, location);
|
|
this.base = base;
|
|
this.exponent = exponent;
|
|
}
|
|
|
|
@Override
|
|
public Double get(Scope dataRoot) {
|
|
return Math.pow(base.get(dataRoot), exponent.get(dataRoot));
|
|
}
|
|
|
|
@Override
|
|
public NumberExpr optimize() {
|
|
NumberExpr base = this.base.optimize();
|
|
NumberExpr exponent = this.exponent.optimize();
|
|
if (base instanceof NumberLiteral litB && exponent instanceof NumberLiteral litE)
|
|
return literal(location, Math.pow(litB.value, litE.value));
|
|
if (exponent instanceof NumberLiteral exp && base instanceof Multiply multiply) {
|
|
if (multiply.multiplier instanceof NumberLiteral literal)
|
|
return new Multiply(multiply.location,
|
|
literal(location, Math.pow(literal.value, exp.value)),
|
|
new Power(location, multiply.multiplicand, exp));
|
|
if (multiply.multiplicand instanceof NumberLiteral literal)
|
|
return new Multiply(multiply.location,
|
|
literal(location, Math.pow(literal.value, exp.value)),
|
|
new Power(location, multiply.multiplier, exp));
|
|
}
|
|
return new Power(location, base, exponent);
|
|
}
|
|
|
|
@Override
|
|
public Stream<Expr<?>> extractSideEffects() {
|
|
return Stream.concat(base.extractSideEffects(), exponent.extractSideEffects());
|
|
}
|
|
|
|
@Override
|
|
public void decompile(ExprWriter writer) throws IOException {
|
|
parenthesize(base, writer, false);
|
|
writer.append(" ^ ");
|
|
parenthesize(exponent, writer, true);
|
|
}
|
|
|
|
@Override
|
|
public boolean equals(Object obj) {
|
|
return obj instanceof Power power && base.equals(power.base) && exponent.equals(power.exponent);
|
|
}
|
|
}
|