muScript: more helpful dynamic type conversion exception
ci/woodpecker/push/woodpecker Pipeline was successful Details

This commit is contained in:
Johannes Frohnmeyer 2023-03-12 20:00:33 +01:00
parent 35130a9c7c
commit 5757e0055a
Signed by: Johannes
GPG Key ID: E76429612C2929F4
3 changed files with 13 additions and 10 deletions

View File

@ -35,7 +35,7 @@ public class Get extends DynamicExpr {
} else if (left instanceof DList l) {
return l.get(name.asNumberExpr().get(dataRoot).intValue());
}
throw new DynamicTypeConversionException("object or list").locational(chStart, chEnd);
throw new DynamicTypeConversionException("object or list", left).locational(chStart, chEnd);
}
@Override

View File

@ -40,12 +40,12 @@ public sealed interface Dynamic<T> permits DBool, DNumber, DString, DObject, DLi
default DBool asBool() {
if (this instanceof DBool bool) return bool;
else throw new DynamicTypeConversionException("bool");
else throw new DynamicTypeConversionException("bool", this);
}
default DNumber asNumber() {
if (this instanceof DNumber number) return number;
else throw new DynamicTypeConversionException("number");
else throw new DynamicTypeConversionException("number", this);
}
default DString asString() {
@ -55,16 +55,16 @@ public sealed interface Dynamic<T> permits DBool, DNumber, DString, DObject, DLi
default DObject asObject() {
if (this instanceof DObject object) return object;
else throw new DynamicTypeConversionException("object");
else throw new DynamicTypeConversionException("object", this);
}
default DList asList() {
if (this instanceof DList list) return list;
else throw new DynamicTypeConversionException("list");
else throw new DynamicTypeConversionException("list", this);
}
default DCallable asCallable() {
if (this instanceof DCallable callable) return callable;
else throw new DynamicTypeConversionException("callable");
else throw new DynamicTypeConversionException("callable", this);
}
}

View File

@ -3,15 +3,18 @@ package io.gitlab.jfronny.muscript.data.dynamic;
import io.gitlab.jfronny.muscript.error.LocationalException;
public class DynamicTypeConversionException extends RuntimeException {
private static final String MESSAGE = "Could not convert dynamic to ";
private static final String MESSAGE1 = "Could not convert dynamic of type ";
private static final String MESSAGE2 = " to ";
private final String target;
private final String actual;
public DynamicTypeConversionException(String target) {
super(MESSAGE + target);
public DynamicTypeConversionException(String target, Dynamic<?> dynamic) {
super(MESSAGE1 + dynamic.getClass().getSimpleName() + MESSAGE2 + target);
this.target = target;
this.actual = dynamic.getClass().getSimpleName();
}
public LocationalException locational(int start, int end) {
return new LocationalException(start, end, MESSAGE + target, this);
return new LocationalException(start, end, MESSAGE1 + actual + MESSAGE2 + target, this);
}
}