77 lines
2.7 KiB
Java
77 lines
2.7 KiB
Java
package io.gitlab.jfronny.muscript.compiler.expr;
|
|
|
|
import io.gitlab.jfronny.muscript.compiler.*;
|
|
import io.gitlab.jfronny.muscript.dynamic.*;
|
|
|
|
public class Conditional extends Expr {
|
|
public final BoolExpr condition;
|
|
public final Expr<?> trueExpr;
|
|
public final Expr<?> falseExpr;
|
|
|
|
public Conditional(BoolExpr condition, Expr<?> trueExpr, Expr<?> falseExpr) {
|
|
this.condition = condition;
|
|
this.trueExpr = trueExpr;
|
|
this.falseExpr = falseExpr;
|
|
if (trueExpr.getResultType() != falseExpr.getResultType())
|
|
throw new IllegalArgumentException("Values used in conditional operator must be of the same type");
|
|
}
|
|
|
|
@Override
|
|
public Type getResultType() {
|
|
return trueExpr.getResultType();
|
|
}
|
|
|
|
@Override
|
|
public Object get(Dynamic branch, Dynamic dataRoot) {
|
|
return condition.get(branch, dataRoot) ? trueExpr.get(branch, dataRoot) : falseExpr.get(branch, dataRoot);
|
|
}
|
|
|
|
@Override
|
|
public BoolExpr asBoolExpr() {
|
|
BoolExpr trueExpr = this.trueExpr.asBoolExpr();
|
|
BoolExpr falseExpr = this.falseExpr.asBoolExpr();
|
|
return new BoolExpr() {
|
|
@Override
|
|
public Boolean get(Dynamic<?> branch, Dynamic<?> dataRoot) {
|
|
return condition.get(branch, dataRoot) ? trueExpr.get(branch, dataRoot) : falseExpr.get(branch, dataRoot);
|
|
}
|
|
};
|
|
}
|
|
|
|
@Override
|
|
public StringExpr asStringExpr() {
|
|
StringExpr trueExpr = this.trueExpr.asStringExpr();
|
|
StringExpr falseExpr = this.falseExpr.asStringExpr();
|
|
return new StringExpr() {
|
|
@Override
|
|
public String get(Dynamic<?> branch, Dynamic<?> dataRoot) {
|
|
return condition.get(branch, dataRoot) ? trueExpr.get(branch, dataRoot) : falseExpr.get(branch, dataRoot);
|
|
}
|
|
};
|
|
}
|
|
|
|
@Override
|
|
public NumberExpr asNumberExpr() {
|
|
NumberExpr trueExpr = this.trueExpr.asNumberExpr();
|
|
NumberExpr falseExpr = this.falseExpr.asNumberExpr();
|
|
return new NumberExpr() {
|
|
@Override
|
|
public Double get(Dynamic<?> branch, Dynamic<?> dataRoot) {
|
|
return condition.get(branch, dataRoot) ? trueExpr.get(branch, dataRoot) : falseExpr.get(branch, dataRoot);
|
|
}
|
|
};
|
|
}
|
|
|
|
@Override
|
|
public DynamicExpr asDynamicExpr() {
|
|
DynamicExpr trueExpr = this.trueExpr.asDynamicExpr();
|
|
DynamicExpr falseExpr = this.falseExpr.asDynamicExpr();
|
|
return new DynamicExpr() {
|
|
@Override
|
|
public Dynamic<?> get(Dynamic<?> branch, Dynamic<?> dataRoot) {
|
|
return condition.get(branch, dataRoot) ? trueExpr.get(branch, dataRoot) : falseExpr.get(branch, dataRoot);
|
|
}
|
|
};
|
|
}
|
|
}
|