use of com.laytonsmith.core.exceptions.CRE.CRECastException in project CommandHelper by EngineHub.
the class ObjectGenerator method recipe.
public MCRecipe recipe(Construct c, Target t) {
if (!(c instanceof CArray)) {
throw new CRECastException("Expected array but recieved " + c.getCType().name(), t);
}
CArray recipe = (CArray) c;
String recipeKey = null;
if (recipe.containsKey("key")) {
recipeKey = recipe.get("key", t).val();
}
MCRecipeType recipeType;
try {
recipeType = MCRecipeType.valueOf(recipe.get("type", t).val());
} catch (IllegalArgumentException e) {
throw new CREFormatException("Invalid recipe type.", t);
}
MCItemStack result = item(recipe.get("result", t), t);
MCRecipe ret;
try {
ret = StaticLayer.GetNewRecipe(recipeKey, recipeType, result);
} catch (IllegalArgumentException ex) {
throw new CREFormatException(ex.getMessage(), t);
}
switch(recipeType) {
case SHAPED:
CArray shaped = Static.getArray(recipe.get("shape", t), t);
;
String[] shape = new String[(int) shaped.size()];
if (shaped.size() < 1 || shaped.size() > 3 || shaped.inAssociativeMode()) {
throw new CREFormatException("Shape array is invalid.", t);
}
int i = 0;
for (Construct row : shaped.asList()) {
if (row instanceof CString && row.val().length() >= 1 && row.val().length() <= 3) {
shape[i] = row.val();
i++;
} else {
throw new CREFormatException("Shape array is invalid.", t);
}
}
((MCShapedRecipe) ret).setShape(shape);
CArray shapedIngredients = Static.getArray(recipe.get("ingredients", t), t);
if (!shapedIngredients.inAssociativeMode()) {
throw new CREFormatException("Ingredients array is invalid.", t);
}
for (String key : shapedIngredients.stringKeySet()) {
MCItemStack is;
Construct ingredient = shapedIngredients.get(key, t);
if (ingredient instanceof CString) {
CString item = (CString) ingredient;
if (item.val().contains(":")) {
String[] split = item.val().split(":");
is = StaticLayer.GetItemStack(Integer.valueOf(split[0]), Integer.valueOf(split[1]), 1);
} else {
is = StaticLayer.GetItemStack(Integer.valueOf(item.val()), 1);
}
} else if (ingredient instanceof CInt) {
is = StaticLayer.GetItemStack(Static.getInt32(ingredient, t), 1);
} else if (ingredient instanceof CArray) {
is = item(ingredient, t);
} else if (ingredient instanceof CNull) {
is = StaticLayer.GetItemStack(0, 0);
} else {
throw new CREFormatException("Item was not found", t);
}
((MCShapedRecipe) ret).setIngredient(key.charAt(0), is);
}
return ret;
case SHAPELESS:
CArray ingredients = Static.getArray(recipe.get("ingredients", t), t);
if (ingredients.inAssociativeMode()) {
throw new CREFormatException("Ingredients array is invalid.", t);
}
for (Construct ingredient : ingredients.asList()) {
MCItemStack is;
if (ingredient instanceof CString) {
if (ingredient.val().contains(":")) {
String[] split = ingredient.val().split(":");
is = StaticLayer.GetItemStack(Integer.valueOf(split[0]), Integer.valueOf(split[1]), 1);
} else {
is = StaticLayer.GetItemStack(Integer.valueOf(ingredient.val()), 1);
}
} else if (ingredient instanceof CArray) {
is = item(ingredient, t);
} else {
throw new CREFormatException("Item was not found", t);
}
((MCShapelessRecipe) ret).addIngredient(is);
}
return ret;
case FURNACE:
CArray is = Static.getArray(recipe.get("input", t), t);
((MCFurnaceRecipe) ret).setInput(item(is, t));
return ret;
default:
throw new CREFormatException("Could not find valid recipe type.", t);
}
}
use of com.laytonsmith.core.exceptions.CRE.CRECastException in project CommandHelper by EngineHub.
the class CIClosure method execute.
@Override
public void execute(Construct... values) throws ConfigRuntimeException, ProgramFlowManipulationException, FunctionReturnException, CancelCommandException {
if (node == null) {
return;
}
StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("<<iclosure>>", getTarget()));
try {
Environment environment;
synchronized (this) {
boolean prev = env.getEnv(GlobalEnv.class).getCloneVars();
env.getEnv(GlobalEnv.class).setCloneVars(false);
environment = env.clone();
env.getEnv(GlobalEnv.class).setCloneVars(prev);
}
environment.getEnv(GlobalEnv.class).setCloneVars(true);
if (values != null) {
for (int i = 0; i < names.length; i++) {
String name = names[i];
Construct value;
try {
value = values[i];
} catch (Exception e) {
value = defaults[i].clone();
}
environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(types[i], name, value, getTarget()));
}
}
boolean hasArgumentsParam = false;
for (String pName : this.names) {
if (pName.equals("@arguments")) {
hasArgumentsParam = true;
break;
}
}
if (!hasArgumentsParam) {
CArray arguments = new CArray(node.getData().getTarget());
if (values != null) {
for (Construct value : values) {
arguments.push(value, node.getData().getTarget());
}
}
environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, node.getData().getTarget()));
}
ParseTree newNode = new ParseTree(new CFunction("g", getTarget()), node.getFileOptions());
List<ParseTree> children = new ArrayList<ParseTree>();
children.add(node);
newNode.setChildren(children);
try {
MethodScriptCompiler.execute(newNode, environment, null, environment.getEnv(GlobalEnv.class).GetScript());
} catch (LoopManipulationException e) {
// Not normal, but pop anyways
stManager.popStackTraceElement();
// This shouldn't ever happen.
LoopManipulationException lme = ((LoopManipulationException) e);
Target t = lme.getTarget();
ConfigRuntimeException.HandleUncaughtException(ConfigRuntimeException.CreateUncatchableException("A " + lme.getName() + "() bubbled up to the top of" + " a closure, which is unexpected behavior.", t), environment);
} catch (FunctionReturnException ex) {
// Normal. Pop element
stManager.popStackTraceElement();
// Check the return type of the closure to see if it matches the defined type
Construct ret = ex.getReturn();
if (!InstanceofUtil.isInstanceof(ret, returnType)) {
throw new CRECastException("Expected closure to return a value of type " + returnType.val() + " but a value of type " + ret.typeof() + " was returned instead", ret.getTarget());
}
// Now rethrow it
throw ex;
} catch (CancelCommandException e) {
stManager.popStackTraceElement();
// die()
} catch (ConfigRuntimeException ex) {
if (ex instanceof AbstractCREException) {
((AbstractCREException) ex).freezeStackTraceElements(stManager);
}
throw ex;
} catch (Throwable t) {
stManager.popStackTraceElement();
throw t;
}
// If we got here, then there was no return type. This is fine, but only for returnType void or auto.
if (!(returnType.equals(Auto.TYPE) || returnType.equals(CVoid.TYPE))) {
throw new CRECastException("Expecting closure to return a value of type " + returnType.val() + "," + " but no value was returned.", node.getTarget());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CClosure.class.getName()).log(Level.SEVERE, null, ex);
}
}
use of com.laytonsmith.core.exceptions.CRE.CRECastException in project CommandHelper by EngineHub.
the class CArray method sort.
public void sort(final SortType sort) {
if (this.associative_mode) {
array = new ArrayList(associative_array.values());
this.associative_array.clear();
this.associative_array = null;
this.associative_mode = false;
CHLog.GetLogger().Log(CHLog.Tags.GENERAL, LogLevel.VERBOSE, "Attempting to sort an associative array; key values will be lost.", this.getTarget());
}
array.sort(new Comparator<Construct>() {
@Override
public int compare(Construct o1, Construct o2) {
// o1 > o2 -> 1
for (int i = 0; i < 2; i++) {
Construct c;
if (i == 0) {
c = o1;
} else {
c = o2;
}
if (c instanceof CArray) {
throw new CRECastException("Cannot sort an array of arrays.", CArray.this.getTarget());
}
if (!(c instanceof CBoolean || c instanceof CString || c instanceof CInt || c instanceof CDouble || c instanceof CNull)) {
throw new CREFormatException("Unsupported type being sorted: " + c.getCType(), CArray.this.getTarget());
}
}
if (o1 instanceof CNull || o2 instanceof CNull) {
if (o1 instanceof CNull && o2 instanceof CNull) {
return 0;
} else if (o1 instanceof CNull) {
return "".compareTo(o2.getValue());
} else {
return o1.val().compareTo("");
}
}
if (o1 instanceof CBoolean || o2 instanceof CBoolean) {
if (Static.getBoolean(o1, Target.UNKNOWN) == Static.getBoolean(o2, Target.UNKNOWN)) {
return 0;
} else {
int oo1 = Static.getBoolean(o1, Target.UNKNOWN) ? 1 : 0;
int oo2 = Static.getBoolean(o2, Target.UNKNOWN) ? 1 : 0;
return (oo1 < oo2) ? -1 : 1;
}
}
// At this point, things will either be numbers or strings
switch(sort) {
case REGULAR:
return compareRegular(o1, o2);
case NUMERIC:
return compareNumeric(o1, o2);
case STRING:
return compareString(o1.val(), o2.val());
case STRING_IC:
return compareString(o1.val().toLowerCase(), o2.val().toLowerCase());
}
throw ConfigRuntimeException.CreateUncatchableException("Missing implementation for " + sort.name(), Target.UNKNOWN);
}
public int compareRegular(Construct o1, Construct o2) {
if (Static.getBoolean(new DataHandling.is_numeric().exec(Target.UNKNOWN, null, o1), Target.UNKNOWN) && Static.getBoolean(new DataHandling.is_numeric().exec(Target.UNKNOWN, null, o2), Target.UNKNOWN)) {
return compareNumeric(o1, o2);
} else if (Static.getBoolean(new DataHandling.is_numeric().exec(Target.UNKNOWN, null, o1), Target.UNKNOWN)) {
// The first is a number, the second is a string
return -1;
} else if (Static.getBoolean(new DataHandling.is_numeric().exec(Target.UNKNOWN, null, o2), Target.UNKNOWN)) {
// The second is a number, the first is a string
return 1;
} else {
// They are both strings
return compareString(o1.val(), o2.val());
}
}
public int compareNumeric(Construct o1, Construct o2) {
double d1 = Static.getNumber(o1, o1.getTarget());
double d2 = Static.getNumber(o2, o2.getTarget());
return Double.compare(d1, d2);
}
public int compareString(String o1, String o2) {
return o1.compareTo(o2);
}
});
this.setDirty();
}
use of com.laytonsmith.core.exceptions.CRE.CRECastException in project CommandHelper by EngineHub.
the class CClosure method execute.
/**
* Executes the closure, giving it the supplied arguments. {@code values} may be null, which means that no arguments
* are being sent.
*
* LoopManipulationExceptions will never bubble up past this point, because they are never allowed, so they are
* handled automatically, but other ProgramFlowManipulationExceptions will, . ConfigRuntimeExceptions will also
* bubble up past this, since an execution mechanism may need to do custom handling.
*
* A typical execution will include the following code:
* <pre>
* try {
* closure.execute();
* } catch(ConfigRuntimeException e){
* ConfigRuntimeException.HandleUncaughtException(e);
* } catch(ProgramFlowManipulationException e){
* // Ignored
* }
* </pre>
*
* @param values The values to be passed to the closure
* @throws ConfigRuntimeException If any call inside the closure causes a CRE
* @throws ProgramFlowManipulationException If any ProgramFlowManipulationException is thrown (other than a
* LoopManipulationException) within the closure
* @throws FunctionReturnException If the closure has a return() call in it.
*/
public void execute(Construct... values) throws ConfigRuntimeException, ProgramFlowManipulationException, FunctionReturnException, CancelCommandException {
if (node == null) {
return;
}
StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("<<closure>>", getTarget()));
try {
Environment environment;
synchronized (this) {
environment = env.clone();
}
if (values != null) {
for (int i = 0; i < names.length; i++) {
String name = names[i];
Construct value;
try {
value = values[i];
} catch (Exception e) {
value = defaults[i].clone();
}
environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(types[i], name, value, getTarget()));
}
}
boolean hasArgumentsParam = false;
for (String pName : this.names) {
if (pName.equals("@arguments")) {
hasArgumentsParam = true;
break;
}
}
if (!hasArgumentsParam) {
CArray arguments = new CArray(node.getData().getTarget());
if (values != null) {
for (Construct value : values) {
arguments.push(value, node.getData().getTarget());
}
}
environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, node.getData().getTarget()));
}
ParseTree newNode = new ParseTree(new CFunction("g", getTarget()), node.getFileOptions());
List<ParseTree> children = new ArrayList<ParseTree>();
children.add(node);
newNode.setChildren(children);
try {
MethodScriptCompiler.execute(newNode, environment, null, environment.getEnv(GlobalEnv.class).GetScript());
} catch (LoopManipulationException e) {
// This shouldn't ever happen.
LoopManipulationException lme = ((LoopManipulationException) e);
Target t = lme.getTarget();
ConfigRuntimeException.HandleUncaughtException(ConfigRuntimeException.CreateUncatchableException("A " + lme.getName() + "() bubbled up to the top of" + " a closure, which is unexpected behavior.", t), environment);
} catch (FunctionReturnException ex) {
// Check the return type of the closure to see if it matches the defined type
// Normal execution.
Construct ret = ex.getReturn();
if (!InstanceofUtil.isInstanceof(ret, returnType)) {
throw new CRECastException("Expected closure to return a value of type " + returnType.val() + " but a value of type " + ret.typeof() + " was returned instead", ret.getTarget());
}
// Now rethrow it
throw ex;
} catch (CancelCommandException e) {
// die()
} catch (ConfigRuntimeException ex) {
if (ex instanceof AbstractCREException) {
((AbstractCREException) ex).freezeStackTraceElements(stManager);
}
throw ex;
} catch (Throwable t) {
// Not sure. Pop and re-throw.
throw t;
} finally {
stManager.popStackTraceElement();
}
// If we got here, then there was no return type. This is fine, but only for returnType void or auto.
if (!(returnType.equals(Auto.TYPE) || returnType.equals(CVoid.TYPE))) {
throw new CRECastException("Expecting closure to return a value of type " + returnType.val() + "," + " but no value was returned.", node.getTarget());
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(CClosure.class.getName()).log(Level.SEVERE, null, ex);
}
}
use of com.laytonsmith.core.exceptions.CRE.CRECastException in project CommandHelper by EngineHub.
the class MObject method set.
/**
* Sets the field to the given parameter. If the field is a non-dynamic property, it is actually set in the object
* (and converted properly), otherwise it is simply added to the dynamic field list.
*
* @param field
* @param value
* @param t
*/
public final void set(String field, Construct value, Target t) {
String alias = alias(field);
if (alias != null) {
field = alias;
}
for (Field f : this.getClass().getFields()) {
if (f.isAnnotationPresent(nofield.class)) {
// Skip this one
continue;
}
if (f.getName().equals(field)) {
// This is it, so let's set it, (converting if necessary) then break
Object val;
Class fType = f.getType();
if (value instanceof CNull) {
// TODO
// Easy case
val = null;
} else {
if (fType == byte.class) {
val = Static.getInt8(value, t);
} else if (fType == short.class) {
val = Static.getInt16(value, t);
} else if (fType == int.class) {
val = Static.getInt32(value, t);
} else if (fType == long.class) {
val = Static.getInt(value, t);
} else if (fType == char.class) {
if (value.val().length() == 0) {
val = null;
} else {
val = value.val().charAt(0);
}
} else if (fType == boolean.class) {
val = Static.getBoolean(value, t);
} else if (fType == float.class) {
val = Static.getDouble32(value, t);
} else if (fType == double.class) {
val = Static.getDouble(value, t);
} else if (fType == MMap.class) {
CArray ca = Static.getArray(value, t);
MMap m = new MMap();
for (String key : ca.stringKeySet()) {
m.put(key, ca.get(key, t));
}
val = m;
} else if (fType == MList.class) {
CArray ca = Static.getArray(value, t);
MList m = new MList();
if (ca.inAssociativeMode()) {
throw new CRECastException("Expected non-associative array, but an associative array was found instead.", t);
}
for (int i = 0; i < ca.size(); i++) {
m.add(ca.get(i, t));
}
val = m;
} else if (Construct.class.isAssignableFrom(fType)) {
val = value;
} else if (MObject.class.isAssignableFrom(fType)) {
CArray ca = Static.getArray(value, t);
val = MObject.Construct(fType, ca);
} else {
// Programming error.
throw new Error(this.getClass().getName() + " contained the public field " + f.getName() + " of type " + fType.getName() + ", which is an unsupported field type.");
}
}
try {
// val is now set correctly, guaranteed.
f.set(this, val);
// These exceptions cannot happen.
} catch (IllegalArgumentException | IllegalAccessException ex) {
throw new Error(ex);
}
}
}
// Always put the dynamic parameter, regardless
fields.put(field, value);
}
Aggregations