package io.gitlab.jfronny.muscript.data.dynamic; import io.gitlab.jfronny.commons.StringFormatter; import io.gitlab.jfronny.muscript.StandardLib; import io.gitlab.jfronny.muscript.compiler.ExprWriter; import io.gitlab.jfronny.muscript.compiler.Parser; import io.gitlab.jfronny.muscript.data.dynamic.additional.DContainer; import io.gitlab.jfronny.muscript.data.dynamic.additional.DFinal; import java.io.IOException; /** * Represents a value of an unknown type * Override toString(StringBuilder) to support custom serialization (note: the serialized form is ran with muScript to generate the tree) * @param the type represented */ public sealed interface Dynamic permits DBool, DNumber, DString, DObject, DList, DCallable, DNull, DContainer { static Dynamic deserialize(String source) { return Parser.parse(source).asDynamicExpr().get(StandardLib.createScope()); } static String serialize(Dynamic dynamic) { StringBuilder sb = new StringBuilder(); try (ExprWriter ew = new ExprWriter(sb)) { dynamic.serialize(ew); } catch (IOException e) { throw new RuntimeException("Could not stringify", e); } return sb.toString(); } void serialize(ExprWriter writer) throws IOException; T getValue(); default DBool asBool() { if (this instanceof DBool bool) return bool; else throw new DynamicTypeConversionException("bool"); } default DNumber asNumber() { if (this instanceof DNumber number) return number; else throw new DynamicTypeConversionException("number"); } default DString asString() { if (this instanceof DString string) return string; else return DFinal.of(StringFormatter.toString(getValue())); } default DObject asObject() { if (this instanceof DObject object) return object; else throw new DynamicTypeConversionException("object"); } default DList asList() { if (this instanceof DList list) return list; else throw new DynamicTypeConversionException("list"); } default DCallable asCallable() { if (this instanceof DCallable callable) return callable; else throw new DynamicTypeConversionException("callable"); } }