java-commons/muscript/src/main/java/io/gitlab/jfronny/muscript/ast/math/Plus.java

57 lines
2.0 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 Plus extends NumberExpr {
public final NumberExpr augend;
public final NumberExpr addend;
public Plus(CodeLocation location, NumberExpr augend, NumberExpr addend) {
super(Order.Term, location);
this.augend = augend;
this.addend = addend;
}
@Override
public Double get(Scope dataRoot) {
return augend.get(dataRoot) + addend.get(dataRoot);
}
@Override
public NumberExpr optimize() {
NumberExpr augend = this.augend.optimize();
NumberExpr addend = this.addend.optimize();
if (augend instanceof NumberLiteral litU && addend instanceof NumberLiteral litD)
return literal(location, litU.value + litD.value);
if (augend instanceof Invert invU && addend instanceof Invert invD)
return new Invert(location, new Plus(location, invU.inner, invD.inner)).optimize();
if (augend instanceof Invert inv) return new Minus(location, addend, inv.inner).optimize();
if (addend instanceof Invert inv) return new Minus(location, augend, inv.inner).optimize();
return new Plus(location, augend, addend);
}
@Override
public Stream<Expr<?>> extractSideEffects() {
return Stream.concat(augend.extractSideEffects(), addend.extractSideEffects());
}
@Override
public void decompile(ExprWriter writer) throws IOException {
parenthesize(augend, writer, false);
writer.append(" + ");
parenthesize(addend, writer, true);
}
@Override
public boolean equals(Object obj) {
return obj instanceof Plus plus && augend.equals(plus.augend) && addend.equals(plus.addend);
}
}