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

85 lines
2.6 KiB
Java

package io.gitlab.jfronny.muscript.ast;
import io.gitlab.jfronny.muscript.annotations.CanThrow;
import io.gitlab.jfronny.muscript.ast.literal.*;
import io.gitlab.jfronny.muscript.ast.string.StringCoerce;
import io.gitlab.jfronny.muscript.compiler.*;
import io.gitlab.jfronny.muscript.data.Scope;
import io.gitlab.jfronny.muscript.data.dynamic.DObject;
import io.gitlab.jfronny.muscript.data.dynamic.Dynamic;
import io.gitlab.jfronny.muscript.error.TypeMismatchException;
import java.util.stream.Stream;
@CanThrow
public abstract sealed class Expr<T> extends Decompilable
permits BoolExpr, DynamicExpr, NullLiteral, NumberExpr, StringExpr {
public final CodeLocation location;
protected Expr(Order order, CodeLocation location) {
super(order);
this.location = location;
}
public abstract Type getResultType();
public abstract T get(Scope dataRoot);
public T get(DObject dataRoot) {
return get(dataRoot instanceof Scope scope ? scope : new Scope(dataRoot));
}
public abstract Expr<T> optimize();
public BoolExpr asBoolExpr() {
if (this instanceof BoolExpr e) return e;
throw new TypeMismatchException(location, Type.Boolean, getResultType());
}
public StringExpr asStringExpr() {
if (this instanceof StringExpr e) return e;
return new StringCoerce(location, this);
}
public NumberExpr asNumberExpr() {
if (this instanceof NumberExpr e) return e;
throw new TypeMismatchException(location, Type.Number, getResultType());
}
public abstract DynamicExpr asDynamicExpr();
public abstract Stream<Expr<?>> extractSideEffects();
public boolean isNull() {
return this instanceof NullLiteral;
}
public static BoolExpr literal(boolean bool) {
return literal(CodeLocation.NONE, bool);
}
public static StringExpr literal(String string) {
return literal(CodeLocation.NONE, string);
}
public static NumberExpr literal(double number) {
return literal(CodeLocation.NONE, number);
}
public static NullLiteral literalNull() {
return literalNull(CodeLocation.NONE);
}
public static BoolExpr literal(CodeLocation location, boolean bool) {
return new BoolLiteral(location, bool);
}
public static StringExpr literal(CodeLocation location, String string) {
return new StringLiteral(location, string);
}
public static NumberExpr literal(CodeLocation location, double number) {
return new NumberLiteral(location, number);
}
public static NullLiteral literalNull(CodeLocation location) {
return new NullLiteral(location);
}
}