use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.
the class MethodScriptCompiler method compile.
/**
* Compiles the token stream into a valid ParseTree. This also includes optimization and reduction.
*
* @param stream The token stream, as generated by {@link #lex(String, File, boolean) lex}
* @return A fully compiled, optimized, and reduced parse tree. If {@code stream} is null or empty, null is
* returned.
* @throws ConfigCompileException If the script contains syntax errors. Additionally, during optimization, certain
* methods may cause compile errors. Any function that can optimize static occurrences and throws a
* {@link ConfigRuntimeException} will have that exception converted to a ConfigCompileException.
*/
public static ParseTree compile(TokenStream stream) throws ConfigCompileException, ConfigCompileGroupException {
Set<ConfigCompileException> compilerErrors = new HashSet<>();
if (stream == null || stream.isEmpty()) {
return null;
}
Target unknown;
try {
// Instead of using Target.UNKNOWN, we can at least set the file.
unknown = new Target(0, stream.get(0).target.file(), 0);
} catch (Exception e) {
unknown = Target.UNKNOWN;
}
// Remove all newlines and whitespaces.
ListIterator<Token> it = stream.listIterator(0);
while (it.hasNext()) {
if (it.next().type.isWhitespace()) {
it.remove();
}
}
// Get the file options.
final FileOptions fileOptions = stream.getFileOptions();
ParseTree tree = new ParseTree(fileOptions);
tree.setData(CNull.NULL);
Stack<ParseTree> parents = new Stack<>();
/**
* constructCount is used to determine if we need to use autoconcat when reaching a FUNC_END. The previous
* constructs, if the count is greater than 1, will be moved down into an autoconcat.
*/
Stack<AtomicInteger> constructCount = new Stack<>();
constructCount.push(new AtomicInteger(0));
parents.push(tree);
tree.addChild(new ParseTree(new CFunction("__autoconcat__", unknown), fileOptions));
parents.push(tree.getChildAt(0));
tree = tree.getChildAt(0);
constructCount.push(new AtomicInteger(0));
/**
* The array stack is used to keep track of the number of square braces in use.
*/
Stack<AtomicInteger> arrayStack = new Stack<>();
arrayStack.add(new AtomicInteger(-1));
Stack<AtomicInteger> minusArrayStack = new Stack<>();
Stack<AtomicInteger> minusFuncStack = new Stack<>();
int parens = 0;
Token t = null;
int bracketCount = 0;
// Create a Token array to iterate over, rather than using the LinkedList's O(n) get() method.
Token[] tokenArray = stream.toArray(new Token[stream.size()]);
for (int i = 0; i < tokenArray.length; i++) {
t = tokenArray[i];
Token prev1 = i - 1 >= 0 ? tokenArray[i - 1] : new Token(TType.UNKNOWN, "", t.target);
Token next1 = i + 1 < stream.size() ? tokenArray[i + 1] : new Token(TType.UNKNOWN, "", t.target);
Token next2 = i + 2 < stream.size() ? tokenArray[i + 2] : new Token(TType.UNKNOWN, "", t.target);
Token next3 = i + 3 < stream.size() ? tokenArray[i + 3] : new Token(TType.UNKNOWN, "", t.target);
// Brace handling
if (t.type == TType.LCURLY_BRACKET) {
ParseTree b = new ParseTree(new CFunction("__cbrace__", t.getTarget()), fileOptions);
tree.addChild(b);
tree = b;
parents.push(b);
bracketCount++;
constructCount.push(new AtomicInteger(0));
continue;
}
if (t.type == TType.RCURLY_BRACKET) {
bracketCount--;
if (constructCount.peek().get() > 1) {
// We need to autoconcat some stuff
int stacks = constructCount.peek().get();
int replaceAt = tree.getChildren().size() - stacks;
ParseTree c = new ParseTree(new CFunction("__autoconcat__", tree.getTarget()), fileOptions);
List<ParseTree> subChildren = new ArrayList<>();
for (int b = replaceAt; b < tree.numberOfChildren(); b++) {
subChildren.add(tree.getChildAt(b));
}
c.setChildren(subChildren);
if (replaceAt > 0) {
List<ParseTree> firstChildren = new ArrayList<>();
for (int d = 0; d < replaceAt; d++) {
firstChildren.add(tree.getChildAt(d));
}
tree.setChildren(firstChildren);
} else {
tree.removeChildren();
}
tree.addChild(c);
}
parents.pop();
tree = parents.peek();
constructCount.pop();
try {
constructCount.peek().incrementAndGet();
} catch (EmptyStackException e) {
throw new ConfigCompileException("Unexpected end curly brace", t.target);
}
continue;
}
// Associative array/label handling
if (t.type == TType.LABEL && tree.getChildren().size() > 0) {
// If it's not an atomic identifier it's an error.
if (!prev1.type.isAtomicLit() && prev1.type != TType.IVARIABLE && prev1.type != TType.KEYWORD) {
ConfigCompileException error = new ConfigCompileException("Invalid label specified", t.getTarget());
if (prev1.type == TType.FUNC_END) {
// and stop compilation at this point.
throw error;
}
compilerErrors.add(error);
}
// Wrap previous construct in a CLabel
ParseTree cc = tree.getChildren().get(tree.getChildren().size() - 1);
tree.removeChildAt(tree.getChildren().size() - 1);
tree.addChild(new ParseTree(new CLabel(cc.getData()), fileOptions));
continue;
}
// Array notation handling
if (t.type.equals(TType.LSQUARE_BRACKET)) {
arrayStack.push(new AtomicInteger(tree.getChildren().size() - 1));
continue;
} else if (t.type.equals(TType.RSQUARE_BRACKET)) {
boolean emptyArray = false;
if (prev1.type.equals(TType.LSQUARE_BRACKET)) {
emptyArray = true;
}
if (arrayStack.size() == 1) {
throw new ConfigCompileException("Mismatched square bracket", t.target);
}
// array is the location of the array
int array = arrayStack.pop().get();
// index is the location of the first node with the index
int index = array + 1;
if (!tree.hasChildren() || array == -1) {
throw new ConfigCompileException("Brackets are illegal here", t.target);
}
ParseTree myArray = tree.getChildAt(array);
ParseTree myIndex;
if (!emptyArray) {
myIndex = new ParseTree(new CFunction("__autoconcat__", myArray.getTarget()), fileOptions);
for (int j = index; j < tree.numberOfChildren(); j++) {
myIndex.addChild(tree.getChildAt(j));
}
} else {
myIndex = new ParseTree(new CSlice("0..-1", t.target), fileOptions);
}
tree.setChildren(tree.getChildren().subList(0, array));
ParseTree arrayGet = new ParseTree(new CFunction("array_get", t.target), fileOptions);
arrayGet.addChild(myArray);
arrayGet.addChild(myIndex);
// Check if the @var[...] had a negating "-" in front. If so, add a neg().
if (!minusArrayStack.isEmpty() && arrayStack.size() + 1 == minusArrayStack.peek().get()) {
if (!next1.type.equals(TType.LSQUARE_BRACKET)) {
// Wait if there are more array_get's comming.
ParseTree negTree = new ParseTree(new CFunction("neg", unknown), fileOptions);
negTree.addChild(arrayGet);
tree.addChild(negTree);
minusArrayStack.pop();
} else {
// Negate the next array_get instead, so just add this one to the tree.
tree.addChild(arrayGet);
}
} else {
tree.addChild(arrayGet);
}
constructCount.peek().set(constructCount.peek().get() - myIndex.numberOfChildren());
continue;
}
// Smart strings
if (t.type == TType.SMART_STRING) {
if (t.val().contains("@")) {
ParseTree function = new ParseTree(fileOptions);
function.setData(new CFunction(new Compiler.smart_string().getName(), t.target));
ParseTree string = new ParseTree(fileOptions);
string.setData(new CString(t.value, t.target));
function.addChild(string);
tree.addChild(function);
} else {
tree.addChild(new ParseTree(new CString(t.val(), t.target), fileOptions));
}
constructCount.peek().incrementAndGet();
continue;
}
if (t.type == TType.DEREFERENCE) {
// Currently unimplemented, but going ahead and making it strict
compilerErrors.add(new ConfigCompileException("The '" + t.val() + "' symbol is not currently allowed in raw strings. You must quote all" + " symbols.", t.target));
}
if (t.type.equals(TType.FUNC_NAME)) {
CFunction func = new CFunction(t.val(), t.target);
ParseTree f = new ParseTree(func, fileOptions);
tree.addChild(f);
constructCount.push(new AtomicInteger(0));
tree = f;
parents.push(f);
} else if (t.type.equals(TType.FUNC_START)) {
if (!prev1.type.equals(TType.FUNC_NAME)) {
throw new ConfigCompileException("Unexpected parenthesis", t.target);
}
parens++;
} else if (t.type.equals(TType.FUNC_END)) {
if (parens <= 0) {
throw new ConfigCompileException("Unexpected parenthesis", t.target);
}
parens--;
// Pop function.
parents.pop();
if (constructCount.peek().get() > 1) {
// We need to autoconcat some stuff
int stacks = constructCount.peek().get();
int replaceAt = tree.getChildren().size() - stacks;
ParseTree c = new ParseTree(new CFunction("__autoconcat__", tree.getTarget()), fileOptions);
List<ParseTree> subChildren = new ArrayList<>();
for (int b = replaceAt; b < tree.numberOfChildren(); b++) {
subChildren.add(tree.getChildAt(b));
}
c.setChildren(subChildren);
if (replaceAt > 0) {
List<ParseTree> firstChildren = new ArrayList<>();
for (int d = 0; d < replaceAt; d++) {
firstChildren.add(tree.getChildAt(d));
}
tree.setChildren(firstChildren);
} else {
tree.removeChildren();
}
tree.addChild(c);
}
constructCount.pop();
try {
constructCount.peek().incrementAndGet();
} catch (EmptyStackException e) {
throw new ConfigCompileException("Unexpected end parenthesis", t.target);
}
try {
tree = parents.peek();
} catch (EmptyStackException e) {
throw new ConfigCompileException("Unexpected end parenthesis", t.target);
}
// Handle "-func(args)" and "-func(args)[index]".
if (!minusFuncStack.isEmpty() && minusFuncStack.peek().get() == parens + 1) {
if (next1.type.equals(TType.LSQUARE_BRACKET)) {
// Move the negation to the array_get which contains this function.
// +1 because the bracket isn't counted yet.
minusArrayStack.push(new AtomicInteger(arrayStack.size() + 1));
} else {
// Negate this function.
ParseTree negTree = new ParseTree(new CFunction("neg", unknown), fileOptions);
negTree.addChild(tree.getChildAt(tree.numberOfChildren() - 1));
tree.removeChildAt(tree.numberOfChildren() - 1);
tree.addChildAt(tree.numberOfChildren(), negTree);
}
minusFuncStack.pop();
}
} else if (t.type.equals(TType.COMMA)) {
if (constructCount.peek().get() > 1) {
int stacks = constructCount.peek().get();
int replaceAt = tree.getChildren().size() - stacks;
ParseTree c = new ParseTree(new CFunction("__autoconcat__", unknown), fileOptions);
List<ParseTree> subChildren = new ArrayList<>();
for (int b = replaceAt; b < tree.numberOfChildren(); b++) {
subChildren.add(tree.getChildAt(b));
}
c.setChildren(subChildren);
if (replaceAt > 0) {
List<ParseTree> firstChildren = new ArrayList<>();
for (int d = 0; d < replaceAt; d++) {
firstChildren.add(tree.getChildAt(d));
}
tree.setChildren(firstChildren);
} else {
tree.removeChildren();
}
tree.addChild(c);
}
constructCount.peek().set(0);
continue;
}
if (t.type == TType.SLICE) {
// "empty first" slice notation. Compare this to the code below.
try {
CSlice slice;
String value = next1.val();
if (next1.type == TType.MINUS || next1.type == TType.PLUS) {
value = next1.val() + next2.val();
i++;
}
slice = new CSlice(".." + value, t.getTarget());
i++;
tree.addChild(new ParseTree(slice, fileOptions));
constructCount.peek().incrementAndGet();
continue;
} catch (ConfigRuntimeException ex) {
// turn them into a CCE.
throw new ConfigCompileException(ex);
}
}
if (next1.type.equals(TType.SLICE)) {
// Slice notation handling
try {
CSlice slice;
if (t.type.isSeparator() || (t.type.isWhitespace() && prev1.type.isSeparator()) || t.type.isKeyword()) {
// empty first
String value = next2.val();
i++;
if (next2.type == TType.MINUS || next2.type == TType.PLUS) {
value = next2.val() + next3.val();
i++;
}
slice = new CSlice(".." + value, next1.getTarget());
if (t.type.isKeyword()) {
tree.addChild(new ParseTree(new CKeyword(t.val(), t.getTarget()), fileOptions));
constructCount.peek().incrementAndGet();
}
} else if (next2.type.isSeparator() || next2.type.isKeyword()) {
// empty last
String modifier = "";
if (prev1.type == TType.MINUS || prev1.type == TType.PLUS) {
// The negative would have already been inserted into the tree
modifier = prev1.val();
tree.removeChildAt(tree.getChildren().size() - 1);
}
slice = new CSlice(modifier + t.value + "..", t.target);
} else {
// both are provided
String modifier1 = "";
if (prev1.type == TType.MINUS || prev1.type == TType.PLUS) {
// It's a negative, incorporate that here, and remove the
// minus from the tree
modifier1 = prev1.val();
tree.removeChildAt(tree.getChildren().size() - 1);
}
Token first = t;
if (first.type.isWhitespace()) {
first = prev1;
}
Token second = next2;
i++;
String modifier2 = "";
if (next2.type == TType.MINUS || next2.type == TType.PLUS) {
modifier2 = next2.val();
second = next3;
i++;
}
slice = new CSlice(modifier1 + first.value + ".." + modifier2 + second.value, t.target);
}
i++;
tree.addChild(new ParseTree(slice, fileOptions));
constructCount.peek().incrementAndGet();
continue;
} catch (ConfigRuntimeException ex) {
// turn them into a CCE.
throw new ConfigCompileException(ex);
}
} else if (t.type == TType.LIT) {
Construct c = Static.resolveConstruct(t.val(), t.target);
if (c instanceof CString && fileOptions.isStrict()) {
compilerErrors.add(new ConfigCompileException("Bare strings are not allowed in strict mode", t.target));
} else if ((c instanceof CInt || c instanceof CDecimal) && next1.type == TType.DOT && next2.type == TType.LIT) {
// minus zero before decimals and leading zeroes after decimals
try {
if (t.value.startsWith("0m")) {
// CDecimal
String neg = "";
if (prev1.value.equals("-")) {
neg = "-";
}
c = new CDecimal(neg + t.value.substring(2) + '.' + next2.value, t.target);
} else {
// CDouble
c = new CDouble(Double.parseDouble(t.val() + '.' + next2.val()), t.target);
}
i += 2;
} catch (NumberFormatException e) {
// Not a double
}
}
tree.addChild(new ParseTree(c, fileOptions));
constructCount.peek().incrementAndGet();
} else if (t.type.equals(TType.STRING) || t.type.equals(TType.COMMAND)) {
tree.addChild(new ParseTree(new CString(t.val(), t.target), fileOptions));
constructCount.peek().incrementAndGet();
} else if (t.type.equals(TType.IDENTIFIER)) {
tree.addChild(new ParseTree(new CPreIdentifier(t.val(), t.target), fileOptions));
constructCount.peek().incrementAndGet();
} else if (t.type.isKeyword()) {
tree.addChild(new ParseTree(new CKeyword(t.val(), t.getTarget()), fileOptions));
constructCount.peek().incrementAndGet();
} else if (t.type.equals(TType.IVARIABLE)) {
tree.addChild(new ParseTree(new IVariable(t.val(), t.target), fileOptions));
constructCount.peek().incrementAndGet();
} else if (t.type.equals(TType.UNKNOWN)) {
tree.addChild(new ParseTree(Static.resolveConstruct(t.val(), t.target), fileOptions));
constructCount.peek().incrementAndGet();
} else if (t.type.isSymbol()) {
// Also handles "-function()" and "-@var[index]".
if (t.type.equals(TType.MINUS) && !prev1.type.isAtomicLit() && !prev1.type.equals(TType.IVARIABLE) && !prev1.type.equals(TType.VARIABLE) && !prev1.type.equals(TType.RCURLY_BRACKET) && !prev1.type.equals(TType.RSQUARE_BRACKET) && !prev1.type.equals(TType.FUNC_END) && (next1.type.equals(TType.IVARIABLE) || next1.type.equals(TType.VARIABLE) || next1.type.equals(TType.FUNC_NAME))) {
// Check if we are negating a value from an array, function or variable.
if (next2.type.equals(TType.LSQUARE_BRACKET)) {
// +1 because the bracket isn't counted yet.
minusArrayStack.push(new AtomicInteger(arrayStack.size() + 1));
} else if (next1.type.equals(TType.FUNC_NAME)) {
// +1 because the function isn't counted yet.
minusFuncStack.push(new AtomicInteger(parens + 1));
} else {
ParseTree negTree = new ParseTree(new CFunction("neg", unknown), fileOptions);
negTree.addChild(new ParseTree(new IVariable(next1.value, next1.target), fileOptions));
tree.addChild(negTree);
constructCount.peek().incrementAndGet();
// Skip the next variable as we've just handled it.
i++;
}
} else {
tree.addChild(new ParseTree(new CSymbol(t.val(), t.type, t.target), fileOptions));
constructCount.peek().incrementAndGet();
}
} else if (t.type == TType.DOT) {
// Check for doubles that start with a decimal, otherwise concat
Construct c = null;
if (next1.type == TType.LIT && prev1.type != TType.STRING && prev1.type != TType.SMART_STRING) {
try {
c = new CDouble(Double.parseDouble('.' + next1.val()), t.target);
i++;
} catch (NumberFormatException e) {
// Not a double
}
}
if (c == null) {
c = new CSymbol(".", TType.CONCAT, t.target);
}
tree.addChild(new ParseTree(c, fileOptions));
constructCount.peek().incrementAndGet();
} else if (t.type.equals(TType.VARIABLE) || t.type.equals(TType.FINAL_VAR)) {
tree.addChild(new ParseTree(new Variable(t.val(), null, false, t.type.equals(TType.FINAL_VAR), t.target), fileOptions));
constructCount.peek().incrementAndGet();
// right_vars.add(new Variable(t.val(), null, t.line_num));
}
}
assert t != null;
if (arrayStack.size() != 1) {
throw new ConfigCompileException("Mismatched square brackets", t.target);
}
if (parens != 0) {
throw new ConfigCompileException("Mismatched parenthesis", t.target);
}
if (bracketCount != 0) {
throw new ConfigCompileException("Mismatched curly braces", t.target);
}
Stack<List<Procedure>> procs = new Stack<>();
procs.add(new ArrayList<Procedure>());
processKeywords(tree);
optimizeAutoconcats(tree, compilerErrors);
optimize(tree, procs, compilerErrors);
link(tree, compilerErrors);
checkLabels(tree, compilerErrors);
checkBreaks(tree, compilerErrors);
if (!compilerErrors.isEmpty()) {
if (compilerErrors.size() == 1) {
// Just throw the one CCE
for (ConfigCompileException e : compilerErrors) {
throw e;
}
} else {
throw new ConfigCompileGroupException(compilerErrors);
}
}
parents.pop();
tree = parents.pop();
return tree;
}
use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.
the class BoundEvent method trigger.
/**
* When the event actually occurs, this should be run, after translating the original event object (of whatever type
* it may be) into a standard map, which contains the event object data. It is converted into a CArray here, and
* then the script is executed with the driver's execute function.
*
* @param activeEvent
*/
public void trigger(ActiveEvent activeEvent) throws EventException {
try {
// GenericTree<Construct> root = new GenericTree<Construct>();
// root.setRoot(tree);
Environment env = originalEnv.clone();
CArray ca = CArray.GetAssociativeArray(Target.UNKNOWN);
for (Map.Entry<String, Construct> entry : activeEvent.parsedEvent.entrySet()) {
ca.set(new CString(entry.getKey(), Target.UNKNOWN), entry.getValue(), Target.UNKNOWN);
}
env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, eventObjName, ca, Target.UNKNOWN));
env.getEnv(GlobalEnv.class).SetEvent(activeEvent);
activeEvent.addHistory("Triggering bound event: " + this);
try {
ProfilePoint p = env.getEnv(GlobalEnv.class).GetProfiler().start("Executing event handler for " + this.getEventName() + " defined at " + this.getTarget(), LogLevel.ERROR);
try {
this.execute(env, activeEvent);
} finally {
p.stop();
}
} catch (ConfigRuntimeException e) {
// We don't know how to handle this, but we need to set the env,
// then pass it up the chain
e.setEnv(env);
throw e;
}
} catch (CloneNotSupportedException ex) {
Logger.getLogger(BoundEvent.class.getName()).log(Level.SEVERE, null, ex);
}
}
use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.
the class ObjectGenerator method itemMeta.
public MCItemMeta itemMeta(Construct c, MCMaterial mat, Target t) throws ConfigRuntimeException {
MCItemFactory itemFactory = Static.getServer().getItemFactory();
if (itemFactory == null) {
throw new CRENotFoundException("Could not find the internal MCItemFactory object (are you running in cmdline mode?)", t);
}
MCItemMeta meta = itemFactory.getItemMeta(mat);
if (c instanceof CNull) {
return meta;
}
CArray ma;
if (c instanceof CArray) {
ma = (CArray) c;
try {
if (ma.containsKey("display")) {
Construct dni = ma.get("display", t);
if (!(dni instanceof CNull)) {
meta.setDisplayName(dni.val());
}
}
if (ma.containsKey("lore")) {
Construct li = ma.get("lore", t);
if (li instanceof CNull) {
// do nothing
} else if (li instanceof CString) {
List<String> ll = new ArrayList<>();
ll.add(li.val());
meta.setLore(ll);
} else if (li instanceof CArray) {
CArray la = (CArray) li;
List<String> ll = new ArrayList<>();
for (int j = 0; j < la.size(); j++) {
ll.add(la.get(j, t).val());
}
meta.setLore(ll);
} else {
throw new CREFormatException("Lore was expected to be an array or a string.", t);
}
}
if (ma.containsKey("enchants")) {
Construct enchants = ma.get("enchants", t);
if (enchants instanceof CArray) {
for (Map.Entry<MCEnchantment, Integer> ench : enchants((CArray) enchants, t).entrySet()) {
meta.addEnchant(ench.getKey(), ench.getValue(), true);
}
} else {
throw new CREFormatException("Enchants field was expected to be an array of Enchantment arrays", t);
}
}
if (ma.containsKey("repair") && !(ma.get("repair", t) instanceof CNull)) {
meta.setRepairCost(Static.getInt32(ma.get("repair", t), t));
}
// Version specific ItemMeta
if (Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_8)) {
if (ma.containsKey("flags")) {
Construct flags = ma.get("flags", t);
if (flags instanceof CArray) {
CArray flagArray = (CArray) flags;
for (int i = 0; i < flagArray.size(); i++) {
Construct flag = flagArray.get(i, t);
meta.addItemFlags(MCItemFlag.valueOf(flag.getValue().toUpperCase()));
}
} else {
throw new CREFormatException("Itemflags was expected to be an array of flags.", t);
}
}
if (Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_11)) {
if (ma.containsKey("unbreakable")) {
meta.setUnbreakable(Static.getBoolean(ma.get("unbreakable", t), t));
}
}
}
// Specific ItemMeta
if (meta instanceof MCBlockStateMeta) {
MCBlockStateMeta bsm = (MCBlockStateMeta) meta;
MCBlockState bs = bsm.getBlockState();
if (bs instanceof MCShulkerBox) {
if (ma.containsKey("inventory")) {
MCShulkerBox box = (MCShulkerBox) bs;
MCInventory inv = box.getInventory();
Construct csbm = ma.get("inventory", t);
if (csbm instanceof CArray) {
CArray cinv = (CArray) csbm;
for (String key : cinv.stringKeySet()) {
try {
int index = Integer.parseInt(key);
if (index < 0 || index >= inv.getSize()) {
ConfigRuntimeException.DoWarning("Out of range value (" + index + ") found" + " in ShulkerBox inventory array, so ignoring.");
}
MCItemStack is = ObjectGenerator.GetGenerator().item(cinv.get(key, t), t);
inv.setItem(index, is);
} catch (NumberFormatException ex) {
ConfigRuntimeException.DoWarning("Expecting integer value for key in ShulkerBox" + " inventory array, but \"" + key + "\" was found. Ignoring.");
}
}
bsm.setBlockState(bs);
} else if (!(csbm instanceof CNull)) {
throw new CREFormatException("ShulkerBox inventory expected to be an array or null.", t);
}
}
} else if (bs instanceof MCBanner) {
MCBanner banner = (MCBanner) bs;
if (ma.containsKey("basecolor")) {
banner.setBaseColor(MCDyeColor.valueOf(ma.get("basecolor", t).val().toUpperCase()));
}
if (ma.containsKey("patterns")) {
CArray array = ArgumentValidation.getArray(ma.get("patterns", t), t);
for (String key : array.stringKeySet()) {
CArray pattern = ArgumentValidation.getArray(array.get(key, t), t);
MCPatternShape shape = MCPatternShape.valueOf(pattern.get("shape", t).val().toUpperCase());
MCDyeColor color = MCDyeColor.valueOf(pattern.get("color", t).val().toUpperCase());
banner.addPattern(StaticLayer.GetConvertor().GetPattern(color, shape));
}
}
banner.update();
bsm.setBlockState(banner);
} else if (bs instanceof MCCreatureSpawner) {
if (ma.containsKey("spawntype")) {
MCCreatureSpawner mccs = (MCCreatureSpawner) bs;
MCEntityType type = MCEntityType.valueOf(ma.get("spawntype", t).val().toUpperCase());
mccs.setSpawnedType(type);
bsm.setBlockState(bs);
}
}
} else if (meta instanceof MCFireworkEffectMeta) {
MCFireworkEffectMeta femeta = (MCFireworkEffectMeta) meta;
if (ma.containsKey("effect")) {
Construct cfem = ma.get("effect", t);
if (cfem instanceof CArray) {
femeta.setEffect(fireworkEffect((CArray) cfem, t));
} else if (!(cfem instanceof CNull)) {
throw new CREFormatException("FireworkCharge effect was expected to be an array or null.", t);
}
}
} else if (meta instanceof MCFireworkMeta) {
MCFireworkMeta fmeta = (MCFireworkMeta) meta;
if (ma.containsKey("firework")) {
Construct construct = ma.get("firework", t);
if (construct instanceof CArray) {
CArray firework = (CArray) construct;
if (firework.containsKey("strength")) {
fmeta.setStrength(Static.getInt32(firework.get("strength", t), t));
}
if (firework.containsKey("effects")) {
// New style (supports multiple effects)
Construct effects = firework.get("effects", t);
if (effects instanceof CArray) {
for (Construct effect : ((CArray) effects).asList()) {
if (effect instanceof CArray) {
fmeta.addEffect(fireworkEffect((CArray) effect, t));
} else {
throw new CREFormatException("Firework effect was expected to be an array.", t);
}
}
} else {
throw new CREFormatException("Firework effects was expected to be an array.", t);
}
} else {
// Old style (supports only one effect)
fmeta.addEffect(fireworkEffect(firework, t));
}
} else {
throw new CREFormatException("Firework was expected to be an array.", t);
}
}
} else if (meta instanceof MCLeatherArmorMeta) {
if (ma.containsKey("color")) {
Construct ci = ma.get("color", t);
if (ci instanceof CNull) {
// nothing
} else if (ci instanceof CArray) {
((MCLeatherArmorMeta) meta).setColor(color((CArray) ci, t));
} else {
throw new CREFormatException("Color was expected to be an array.", t);
}
}
} else if (meta instanceof MCBookMeta) {
if (ma.containsKey("title")) {
Construct title = ma.get("title", t);
if (!(title instanceof CNull)) {
((MCBookMeta) meta).setTitle(title.val());
}
}
if (ma.containsKey("author")) {
Construct author = ma.get("author", t);
if (!(author instanceof CNull)) {
((MCBookMeta) meta).setAuthor(author.val());
}
}
if (ma.containsKey("pages")) {
Construct pages = ma.get("pages", t);
if (pages instanceof CNull) {
// nothing
} else if (pages instanceof CArray) {
CArray pa = (CArray) pages;
List<String> pl = new ArrayList<>();
for (int j = 0; j < pa.size(); j++) {
pl.add(pa.get(j, t).val());
}
((MCBookMeta) meta).setPages(pl);
} else {
throw new CREFormatException("Pages field was expected to be an array.", t);
}
}
} else if (meta instanceof MCSkullMeta) {
if (ma.containsKey("owneruuid")) {
Construct id = ma.get("owneruuid", t);
if (!(id instanceof CNull)) {
((MCSkullMeta) meta).setOwningPlayer(Static.getServer().getOfflinePlayer(Static.GetUUID(id, t)));
}
} else if (ma.containsKey("owner")) {
Construct owner = ma.get("owner", t);
if (!(owner instanceof CNull)) {
((MCSkullMeta) meta).setOwner(owner.val());
}
}
} else if (meta instanceof MCEnchantmentStorageMeta) {
if (ma.containsKey("stored")) {
Construct stored = ma.get("stored", t);
if (stored instanceof CNull) {
// Still doing nothing
} else if (stored instanceof CArray) {
for (Map.Entry<MCEnchantment, Integer> ench : enchants((CArray) stored, t).entrySet()) {
((MCEnchantmentStorageMeta) meta).addStoredEnchant(ench.getKey(), ench.getValue(), true);
}
} else {
throw new CREFormatException("Stored field was expected to be an array of Enchantment arrays", t);
}
}
} else if (meta instanceof MCPotionMeta) {
if (ma.containsKey("potions")) {
Construct effects = ma.get("potions", t);
if (effects instanceof CArray) {
for (MCLivingEntity.MCEffect e : potions((CArray) effects, t)) {
((MCPotionMeta) meta).addCustomEffect(e.getPotionID(), e.getStrength(), e.getTicksRemaining(), e.isAmbient(), true, t);
}
} else {
throw new CREFormatException("Effects was expected to be an array of potion arrays.", t);
}
}
if (Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_9)) {
if (ma.containsKey("base")) {
Construct potiondata = ma.get("base", t);
if (potiondata instanceof CArray) {
CArray pd = (CArray) potiondata;
((MCPotionMeta) meta).setBasePotionData(potionData((CArray) potiondata, t));
}
}
} else if (ma.containsKey("main")) {
((MCPotionMeta) meta).setMainEffect(Static.getInt32(ma.get("main", t), t));
}
} else if (meta instanceof MCBannerMeta) {
if (ma.containsKey("basecolor")) {
((MCBannerMeta) meta).setBaseColor(MCDyeColor.valueOf(ma.get("basecolor", t).val().toUpperCase()));
}
if (ma.containsKey("patterns")) {
CArray array = ArgumentValidation.getArray(ma.get("patterns", t), t);
for (String key : array.stringKeySet()) {
CArray pattern = ArgumentValidation.getArray(array.get(key, t), t);
MCPatternShape shape = MCPatternShape.valueOf(pattern.get("shape", t).val().toUpperCase());
MCDyeColor color = MCDyeColor.valueOf(pattern.get("color", t).val().toUpperCase());
((MCBannerMeta) meta).addPattern(StaticLayer.GetConvertor().GetPattern(color, shape));
}
}
} else if (meta instanceof MCSpawnEggMeta) {
if (ma.containsKey("spawntype")) {
Construct spawntype = ma.get("spawntype", t);
if (spawntype instanceof CString) {
((MCSpawnEggMeta) meta).setSpawnedType(MCEntityType.valueOf(spawntype.val().toUpperCase()));
}
}
} else if (meta instanceof MCMapMeta && Static.getServer().getMinecraftVersion().gte(MCVersion.MC1_11)) {
if (ma.containsKey("color")) {
Construct ci = ma.get("color", t);
if (ci instanceof CArray) {
((MCMapMeta) meta).setColor(color((CArray) ci, t));
} else if (!(ci instanceof CNull)) {
throw new CREFormatException("Color was expected to be an array.", t);
}
}
}
} catch (Exception ex) {
throw new CREFormatException(ex.getMessage(), t, ex);
}
} else {
throw new CREFormatException("An array was expected but recieved " + c + " instead.", t);
}
return meta;
}
use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.
the class CommandHelperInterpreterListener method execute.
public void execute(String script, final MCPlayer p) throws ConfigCompileException, ConfigCompileGroupException {
TokenStream stream = MethodScriptCompiler.lex(script, new File("Interpreter"), true);
ParseTree tree = MethodScriptCompiler.compile(stream);
interpreterMode.remove(p.getName());
GlobalEnv gEnv = new GlobalEnv(plugin.executionQueue, plugin.profiler, plugin.persistenceNetwork, CommandHelperFileLocations.getDefault().getConfigDirectory(), plugin.profiles, new TaskManager());
gEnv.SetDynamicScriptingMode(true);
CommandHelperEnvironment cEnv = new CommandHelperEnvironment();
cEnv.SetPlayer(p);
Environment env = Environment.createEnvironment(gEnv, cEnv);
try {
MethodScriptCompiler.registerAutoIncludes(env, null);
MethodScriptCompiler.execute(tree, env, new MethodScriptComplete() {
@Override
public void done(String output) {
output = output.trim();
if (output.isEmpty()) {
Static.SendMessage(p, ":");
} else {
if (output.startsWith("/")) {
// Run the command
Static.SendMessage(p, ":" + MCChatColor.YELLOW + output);
p.chat(output);
} else {
// output the results
Static.SendMessage(p, ":" + MCChatColor.GREEN + output);
}
}
interpreterMode.add(p.getName());
}
}, null);
} catch (CancelCommandException e) {
interpreterMode.add(p.getName());
} catch (ConfigRuntimeException e) {
ConfigRuntimeException.HandleUncaughtException(e, env);
Static.SendMessage(p, MCChatColor.RED + e.toString());
interpreterMode.add(p.getName());
} catch (Exception e) {
Static.SendMessage(p, MCChatColor.RED + e.toString());
Logger.getLogger(CommandHelperInterpreterListener.class.getName()).log(Level.SEVERE, null, e);
interpreterMode.add(p.getName());
}
}
use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.
the class AliasCore method alias.
/**
* This is the workhorse function. It takes a given command, then converts it into the actual command(s). If the
* command maps to a defined alias, it will run the specified alias. It will search through the global list of
* aliases, as well as the aliases defined for that specific player. This function doesn't handle the /alias command
* however.
*
* @param command
* @return
*/
public boolean alias(String command, final MCCommandSender player) {
if (scripts == null) {
throw ConfigRuntimeException.CreateUncatchableException("Cannot run alias commands, no config file is loaded", Target.UNKNOWN);
}
boolean match = false;
try {
// actually add the player to the array.
if (player != null && player instanceof MCPlayer && echoCommand.contains(((MCPlayer) player).getName())) {
// we are running one of the expanded commands, so exit with false
return false;
}
for (Script s : scripts) {
try {
if (s.match(command)) {
this.addPlayerReference(player);
if (Prefs.ConsoleLogCommands() && s.doLog()) {
StringBuilder b = new StringBuilder("CH: Running original command ");
if (player instanceof MCPlayer) {
b.append("on player ").append(((MCPlayer) player).getName());
} else {
b.append("from a MCCommandSender");
}
b.append(" ----> ").append(command);
Static.getLogger().log(Level.INFO, b.toString());
}
GlobalEnv gEnv = new GlobalEnv(parent.executionQueue, parent.profiler, parent.persistenceNetwork, MethodScriptFileLocations.getDefault().getConfigDirectory(), parent.profiles, new TaskManager());
CommandHelperEnvironment cEnv = new CommandHelperEnvironment();
cEnv.SetCommandSender(player);
Environment env = Environment.createEnvironment(gEnv, cEnv);
try {
env.getEnv(CommandHelperEnvironment.class).SetCommand(command);
ProfilePoint alias = env.getEnv(GlobalEnv.class).GetProfiler().start("Global Alias - \"" + command + "\"", LogLevel.ERROR);
try {
s.run(s.getVariables(command), env, new MethodScriptComplete() {
@Override
public void done(String output) {
try {
if (output != null) {
if (!output.trim().isEmpty() && output.trim().startsWith("/")) {
if (Prefs.DebugMode()) {
if (player instanceof MCPlayer) {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command on " + ((MCPlayer) player).getName() + ": " + output.trim());
} else {
Static.getLogger().log(Level.INFO, "[CommandHelper]: Executing command from console equivalent: " + output.trim());
}
}
if (player instanceof MCPlayer) {
((MCPlayer) player).chat(output.trim());
} else {
Static.getServer().dispatchCommand(player, output.trim().substring(1));
}
}
}
} catch (Throwable e) {
StreamUtils.GetSystemErr().println(e.getMessage());
player.sendMessage(MCChatColor.RED + e.getMessage());
} finally {
Static.getAliasCore().removePlayerReference(player);
}
}
});
} finally {
alias.stop();
}
} catch (ConfigRuntimeException ex) {
ex.setEnv(env);
ConfigRuntimeException.HandleUncaughtException(ex, env);
} catch (Throwable e) {
// This is not a simple user script error, this is a deeper problem, so we always handle this.
StreamUtils.GetSystemErr().println("An unexpected exception occured: " + e.getClass().getSimpleName());
player.sendMessage("An unexpected exception occured: " + MCChatColor.RED + e.getClass().getSimpleName());
e.printStackTrace();
} finally {
Static.getAliasCore().removePlayerReference(player);
}
match = true;
break;
}
} catch (Exception e) {
StreamUtils.GetSystemErr().println("An unexpected exception occured inside the command " + s.toString());
e.printStackTrace();
}
}
} catch (Throwable e) {
// Not only did an error happen, an error happened in our error handler
throw new InternalException(TermColors.RED + "An unexpected error occured in the CommandHelper plugin. " + "Further, this is likely an error with the error handler, so it may be caused by your script, " + "however, there is no more information at this point. Check your script, but also report this " + "as a bug in CommandHelper. Also, it's possible that some commands will no longer work. As a temporary " + "workaround, restart the server, and avoid doing whatever it is you did to make this happen.\nThe error is as follows: " + e.toString() + "\n" + TermColors.reset() + "Stack Trace:\n" + StringUtils.Join(Arrays.asList(e.getStackTrace()), "\n"));
}
return match;
}
Aggregations