56 lines
2.0 KiB
Java
56 lines
2.0 KiB
Java
package io.gitlab.jfronny.muscript.ast.conditional;
|
|
|
|
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.BoolExpr;
|
|
import io.gitlab.jfronny.muscript.ast.StringExpr;
|
|
import io.gitlab.jfronny.muscript.ast.literal.BoolLiteral;
|
|
|
|
import java.io.IOException;
|
|
|
|
public class StringConditional extends StringExpr {
|
|
public final BoolExpr condition;
|
|
public final StringExpr trueExpr;
|
|
public final StringExpr falseExpr;
|
|
|
|
public StringConditional(int chStart, int chEnd, BoolExpr condition, StringExpr trueExpr, StringExpr falseExpr) {
|
|
super(Order.Conditional, chStart, chEnd);
|
|
this.condition = condition;
|
|
this.trueExpr = trueExpr;
|
|
this.falseExpr = falseExpr;
|
|
}
|
|
|
|
@Override
|
|
public String get(Scope dataRoot) {
|
|
return condition.get(dataRoot) ? trueExpr.get(dataRoot) : falseExpr.get(dataRoot);
|
|
}
|
|
|
|
@Override
|
|
public StringExpr optimize() {
|
|
BoolExpr condition = this.condition.optimize();
|
|
StringExpr trueExpr = this.trueExpr.optimize();
|
|
StringExpr falseExpr = this.falseExpr.optimize();
|
|
if (condition instanceof BoolLiteral literal) return literal.value ? trueExpr : falseExpr;
|
|
if (trueExpr.equals(falseExpr)) return trueExpr;
|
|
return new StringConditional(chStart, chEnd, condition, trueExpr, falseExpr);
|
|
}
|
|
|
|
@Override
|
|
public void decompile(ExprWriter writer) throws IOException {
|
|
parenthesize(condition, writer, true);
|
|
writer.append(" ? ");
|
|
trueExpr.decompile(writer);
|
|
writer.append(" : ");
|
|
falseExpr.decompile(writer);
|
|
}
|
|
|
|
@Override
|
|
public boolean equals(Object obj) {
|
|
return obj instanceof StringConditional conditional
|
|
&& condition.equals(conditional.condition)
|
|
&& trueExpr.equals(conditional.trueExpr)
|
|
&& falseExpr.equals(conditional.falseExpr);
|
|
}
|
|
}
|