java-commons/muscript/src/main/java/io/gitlab/jfronny/muscript/data/dynamic/type/DType.java

44 lines
2.0 KiB
Java

package io.gitlab.jfronny.muscript.data.dynamic.type;
import org.jetbrains.annotations.Nullable;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;
public sealed interface DType permits DTypeCallable, DTypeGeneric, DTypeList, DTypeObject, DTypePrimitive, DTypeSum, DTypeAnd {
static String toString(@Nullable DType type) {
return toString(type, false);
}
default DType or(DType alternative) {
return new DTypeSum(Set.of(this, alternative));
}
default DType and(DType additional) {
return new DTypeAnd(Set.of(this, additional));
}
static String toString(@Nullable DType type, boolean wrapComplex) {
//TODO replace with switch pattern
if (type == null) return "any";
else if (type instanceof DTypePrimitive t) return switch (t) {
case BOOL -> "bool";
case NUMBER -> "number";
case STRING -> "string";
case NULL -> "null";
};
else if (type instanceof DTypeGeneric t) return "T" + t.index();
else if (type instanceof DTypeList t) return "[" + toString(t.entryType(), false) + "]";
else if (type instanceof DTypeObject t) return "{" + toString(t.entryType(), false) + "}";
else if (type instanceof DTypeCallable t) {
String args = t.from() == null
? "any"
: "(" + t.from().stream().map(Objects::toString).collect(Collectors.joining(", ")) + ")";
return args + " -> " + toString(t.to(), true);
} else if (type instanceof DTypeSum t) return (wrapComplex ? "<" : "") + t.elements().stream().map(s -> toString(s, true)).collect(Collectors.joining(" | ")) + (wrapComplex ? ">" : "");
else if (type instanceof DTypeAnd t) return (wrapComplex ? "<" : "") + t.elements().stream().map(s -> toString(s, true)).collect(Collectors.joining(" & ")) + (wrapComplex ? ">" : "");
else throw new IllegalArgumentException("Unexpected DType implementation: " + type.getClass());
}
}