Search in sources :

Example 1 with CNull

use of com.laytonsmith.core.constructs.CNull in project CommandHelper by EngineHub.

the class Procedure method execute.

/**
 * Executes this procedure, with the arguments that were passed in
 *
 * @param args
 * @param env
 * @param t
 * @return
 */
public Construct execute(List<Construct> args, Environment env, Target t) {
    env.getEnv(GlobalEnv.class).SetVarList(new IVariableList());
    // This is what will become our @arguments var
    CArray arguments = new CArray(Target.UNKNOWN);
    for (String key : originals.keySet()) {
        Construct c = originals.get(key);
        env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(Auto.TYPE, key, c, Target.UNKNOWN));
        arguments.push(c, t);
    }
    // new Script(null, null);
    Script fakeScript = Script.GenerateScript(tree, env.getEnv(GlobalEnv.class).GetLabel());
    for (int i = 0; i < args.size(); i++) {
        Construct c = args.get(i);
        arguments.set(i, c, t);
        if (varIndex.size() > i) {
            String varname = varIndex.get(i).getVariableName();
            if (c instanceof CNull || InstanceofUtil.isInstanceof(c, varIndex.get(i).getDefinedType()) || varIndex.get(i).getDefinedType().equals(Auto.TYPE)) {
                env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(varIndex.get(i).getDefinedType(), varname, c, c.getTarget()));
            } else {
                throw new CRECastException("Procedure \"" + name + "\" expects a value of type " + varIndex.get(i).getDefinedType().val() + " in argument " + (i + 1) + ", but" + " a value of type " + c.typeof() + " was found instead.", c.getTarget());
            }
        }
    }
    env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, Target.UNKNOWN));
    StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
    stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("proc " + name, getTarget()));
    try {
        if (tree.getData() instanceof CFunction && "sconcat".equals(tree.getData().val())) {
            // compiler proper.
            for (ParseTree child : tree.getChildren()) {
                fakeScript.eval(child, env);
            }
        } else {
            fakeScript.eval(tree, env);
        }
    } catch (FunctionReturnException e) {
        // Normal exit
        stManager.popStackTraceElement();
        Construct ret = e.getReturn();
        if (!InstanceofUtil.isInstanceof(ret, returnType)) {
            throw new CRECastException("Expected procedure \"" + name + "\" to return a value of type " + returnType.val() + " but a value of type " + ret.typeof() + " was returned instead", ret.getTarget());
        }
        return ret;
    } catch (LoopManipulationException ex) {
        // Not exactly normal, but pop anyways
        stManager.popStackTraceElement();
        // a compile error.
        throw ConfigRuntimeException.CreateUncatchableException("Loop manipulation operations (e.g. break() or continue()) cannot" + " bubble up past procedures.", t);
    } catch (ConfigRuntimeException e) {
        if (e instanceof AbstractCREException) {
            ((AbstractCREException) e).freezeStackTraceElements(stManager);
        }
        stManager.popStackTraceElement();
        throw e;
    } catch (Throwable th) {
        // Not sure. Pop, but rethrow
        stManager.popStackTraceElement();
        throw th;
    }
    // Normal exit, but no return.
    stManager.popStackTraceElement();
    // If we got here, then there was no return value. This is fine, but only for returnType void or auto.
    if (!(returnType.equals(Auto.TYPE) || returnType.equals(CVoid.TYPE))) {
        throw new CRECastException("Expecting procedure \"" + name + "\" to return a value of type " + returnType.val() + "," + " but no value was returned.", tree.getTarget());
    }
    return CVoid.VOID;
}
Also used : AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) IVariable(com.laytonsmith.core.constructs.IVariable) IVariableList(com.laytonsmith.core.constructs.IVariableList) CArray(com.laytonsmith.core.constructs.CArray) CFunction(com.laytonsmith.core.constructs.CFunction) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) StackTraceManager(com.laytonsmith.core.exceptions.StackTraceManager) Construct(com.laytonsmith.core.constructs.Construct) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) LoopManipulationException(com.laytonsmith.core.exceptions.LoopManipulationException) CNull(com.laytonsmith.core.constructs.CNull)

Example 2 with CNull

use of com.laytonsmith.core.constructs.CNull in project CommandHelper by EngineHub.

the class Script method eval.

/**
 * Given the parse tree and environment, executes the tree.
 *
 * @param c
 * @param env
 * @return
 * @throws CancelCommandException
 */
public Construct eval(ParseTree c, final Environment env) throws CancelCommandException {
    if (env.getEnv(GlobalEnv.class).IsInterrupted()) {
        // unconditionally.
        throw new CancelCommandException("", Target.UNKNOWN);
    }
    final Construct m = c.getData();
    CurrentEnv = env;
    if (m.getCType() != ConstructType.FUNCTION) {
        if (m.getCType() == ConstructType.VARIABLE) {
            return new CString(m.val(), m.getTarget());
        } else {
            return m;
        }
    }
    StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
    boolean addedRootStackElement = false;
    try {
        // If it's an unknown target, this is not user generated code, and we want to skip adding the element here.
        if (stManager.isStackEmpty() && !m.getTarget().equals(Target.UNKNOWN)) {
            stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("<<main code>>", m.getTarget()));
            addedRootStackElement = true;
        }
        stManager.setCurrentTarget(c.getTarget());
        env.getEnv(GlobalEnv.class).SetScript(this);
        if (m.val().charAt(0) == '_' && m.val().charAt(1) != '_') {
            // Not really a function, so we can't put it in Function.
            Procedure p = getProc(m.val());
            if (p == null) {
                throw new CREInvalidProcedureException("Unknown procedure \"" + m.val() + "\"", m.getTarget());
            }
            Environment newEnv = env;
            try {
                newEnv = env.clone();
            } catch (CloneNotSupportedException e) {
            }
            ProfilePoint pp = env.getEnv(GlobalEnv.class).GetProfiler().start(m.val() + " execution", LogLevel.INFO);
            Construct ret;
            try {
                ret = p.cexecute(c.getChildren(), newEnv, m.getTarget());
            } finally {
                pp.stop();
            }
            return ret;
        }
        final Function f;
        try {
            f = (Function) FunctionList.getFunction(m);
        } catch (ConfigCompileException e) {
            // Turn it into a config runtime exception. This shouldn't ever happen though.
            throw ConfigRuntimeException.CreateUncatchableException("Unable to find function " + m.val(), m.getTarget());
        }
        ArrayList<Construct> args = new ArrayList<>();
        try {
            if (f.isRestricted() && !Static.hasCHPermission(f.getName(), env)) {
                throw new CREInsufficientPermissionException("You do not have permission to use the " + f.getName() + " function.", m.getTarget());
            }
            if (f.useSpecialExec()) {
                ProfilePoint p = null;
                if (f.shouldProfile() && env.getEnv(GlobalEnv.class).GetProfiler() != null && env.getEnv(GlobalEnv.class).GetProfiler().isLoggable(f.profileAt())) {
                    p = env.getEnv(GlobalEnv.class).GetProfiler().start(f.profileMessageS(c.getChildren()), f.profileAt());
                }
                Construct ret;
                try {
                    ret = f.execs(m.getTarget(), env, this, c.getChildren().toArray(new ParseTree[] {}));
                } finally {
                    if (p != null) {
                        p.stop();
                    }
                }
                return ret;
            }
            for (ParseTree c2 : c.getChildren()) {
                args.add(eval(c2, env));
            }
            Object[] a = args.toArray();
            Construct[] ca = new Construct[a.length];
            for (int i = 0; i < a.length; i++) {
                ca[i] = (Construct) a[i];
                // CArray, CBoolean, CDouble, CInt, CNull, CString, CVoid, CEntry, CLabel (only to sconcat).
                if (!(ca[i] instanceof CArray || ca[i] instanceof CBoolean || ca[i] instanceof CDouble || ca[i] instanceof CInt || ca[i] instanceof CNull || ca[i] instanceof CString || ca[i] instanceof CVoid || ca[i] instanceof IVariable || ca[i] instanceof CEntry || ca[i] instanceof CLabel) && (!f.getName().equals("__autoconcat__") && (ca[i] instanceof CLabel))) {
                    throw new CRECastException("Invalid Construct (" + ca[i].getClass() + ") being passed as an argument to a function (" + f.getName() + ")", m.getTarget());
                }
                while (f.preResolveVariables() && ca[i] instanceof IVariable) {
                    IVariable cur = (IVariable) ca[i];
                    ca[i] = env.getEnv(GlobalEnv.class).GetVarList().get(cur.getVariableName(), cur.getTarget()).ival();
                }
            }
            {
                // It takes a moment to generate the toString of some things, so lets not do it
                // if we actually aren't going to profile
                ProfilePoint p = null;
                if (f.shouldProfile() && env.getEnv(GlobalEnv.class).GetProfiler() != null && env.getEnv(GlobalEnv.class).GetProfiler().isLoggable(f.profileAt())) {
                    p = env.getEnv(GlobalEnv.class).GetProfiler().start(f.profileMessage(ca), f.profileAt());
                }
                Construct ret;
                try {
                    ret = f.exec(m.getTarget(), env, ca);
                } finally {
                    if (p != null) {
                        p.stop();
                    }
                }
                return ret;
            }
        // We want to catch and rethrow the ones we know how to catch, and then
        // catch and report anything else.
        } catch (ConfigRuntimeException | ProgramFlowManipulationException e) {
            if (e instanceof AbstractCREException) {
                ((AbstractCREException) e).freezeStackTraceElements(stManager);
            }
            throw e;
        } catch (InvalidEnvironmentException e) {
            if (!e.isDataSet()) {
                e.setData(f.getName());
            }
            throw e;
        } catch (Exception e) {
            String brand = Implementation.GetServerType().getBranding();
            SimpleVersion version = Static.getVersion();
            String culprit = brand;
            outer: for (ExtensionTracker tracker : ExtensionManager.getTrackers().values()) {
                for (FunctionBase b : tracker.getFunctions()) {
                    if (b.getName().equals(f.getName())) {
                        // name instead of the core plugin's name.
                        for (Extension extension : tracker.getExtensions()) {
                            culprit = extension.getName();
                            break outer;
                        }
                    }
                }
            }
            String emsg = TermColors.RED + "Uh oh! You've found an error in " + TermColors.CYAN + culprit + TermColors.RED + ".\n" + "This happened while running your code, so you may be able to find a workaround," + " but is ultimately an issue in " + culprit + ".\n" + "The following code caused the error:\n" + TermColors.WHITE;
            List<String> args2 = new ArrayList<>();
            Map<String, String> vars = new HashMap<>();
            for (Construct cc : args) {
                if (cc instanceof IVariable) {
                    Construct ccc = env.getEnv(GlobalEnv.class).GetVarList().get(((IVariable) cc).getVariableName(), cc.getTarget()).ival();
                    String vval = ccc.val();
                    if (ccc instanceof CString) {
                        vval = ccc.asString().getQuote();
                    }
                    vars.put(((IVariable) cc).getVariableName(), vval);
                }
                if (cc == null) {
                    args2.add("java-null");
                } else if (cc instanceof CString) {
                    args2.add(cc.asString().getQuote());
                } else if (cc instanceof IVariable) {
                    args2.add(((IVariable) cc).getVariableName());
                } else {
                    args2.add(cc.val());
                }
            }
            if (!vars.isEmpty()) {
                emsg += StringUtils.Join(vars, " = ", "\n") + "\n";
            }
            emsg += f.getName() + "(";
            emsg += StringUtils.Join(args2, ", ");
            emsg += ")\n";
            emsg += TermColors.RED + "on or around " + TermColors.YELLOW + m.getTarget().file() + TermColors.WHITE + ":" + TermColors.CYAN + m.getTarget().line() + TermColors.RED + ".\n";
            // Server might not be available in this platform, so let's be sure to ignore those exceptions
            String modVersion;
            try {
                modVersion = StaticLayer.GetConvertor().GetServer().getAPIVersion();
            } catch (Exception ex) {
                modVersion = Implementation.GetServerType().name();
            }
            String extensionData = "";
            for (ExtensionTracker tracker : ExtensionManager.getTrackers().values()) {
                for (Extension extension : tracker.getExtensions()) {
                    try {
                        extensionData += TermColors.CYAN + extension.getName() + TermColors.RED + " (" + TermColors.RESET + extension.getVersion() + TermColors.RED + ")\n";
                    } catch (AbstractMethodError ex) {
                        // This happens with an old style extensions. Just skip it.
                        extensionData += TermColors.CYAN + "Unknown Extension" + TermColors.RED + "\n";
                    }
                }
            }
            if (extensionData.isEmpty()) {
                extensionData = "NONE\n";
            }
            emsg += "Please report this to the developers, and be sure to include the version numbers:\n" + TermColors.CYAN + "Server" + TermColors.RED + " version: " + TermColors.RESET + modVersion + TermColors.RED + ";\n" + TermColors.CYAN + brand + TermColors.RED + " version: " + TermColors.RESET + version + TermColors.RED + ";\n" + "Loaded extensions and versions:\n" + extensionData + "Here's the stacktrace:\n" + TermColors.RESET + Static.GetStacktraceString(e);
            Static.getLogger().log(Level.SEVERE, emsg);
            throw new CancelCommandException(null, Target.UNKNOWN);
        }
    } finally {
        if (addedRootStackElement && stManager.isStackSingle()) {
            stManager.popStackTraceElement();
        }
    }
}
Also used : CLabel(com.laytonsmith.core.constructs.CLabel) InvalidEnvironmentException(com.laytonsmith.core.environments.InvalidEnvironmentException) FunctionBase(com.laytonsmith.core.functions.FunctionBase) IVariable(com.laytonsmith.core.constructs.IVariable) ArrayList(java.util.ArrayList) CArray(com.laytonsmith.core.constructs.CArray) CREInvalidProcedureException(com.laytonsmith.core.exceptions.CRE.CREInvalidProcedureException) ExtensionTracker(com.laytonsmith.core.extensions.ExtensionTracker) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CString(com.laytonsmith.core.constructs.CString) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) CString(com.laytonsmith.core.constructs.CString) Function(com.laytonsmith.core.functions.Function) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) SimpleVersion(com.laytonsmith.PureUtilities.SimpleVersion) FunctionList(com.laytonsmith.core.functions.FunctionList) List(java.util.List) ArrayList(java.util.ArrayList) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) CREInsufficientPermissionException(com.laytonsmith.core.exceptions.CRE.CREInsufficientPermissionException) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) CBoolean(com.laytonsmith.core.constructs.CBoolean) CDouble(com.laytonsmith.core.constructs.CDouble) ProgramFlowManipulationException(com.laytonsmith.core.exceptions.ProgramFlowManipulationException) StackTraceManager(com.laytonsmith.core.exceptions.StackTraceManager) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) ProgramFlowManipulationException(com.laytonsmith.core.exceptions.ProgramFlowManipulationException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) InvalidEnvironmentException(com.laytonsmith.core.environments.InvalidEnvironmentException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) CREInsufficientPermissionException(com.laytonsmith.core.exceptions.CRE.CREInsufficientPermissionException) LoopBreakException(com.laytonsmith.core.exceptions.LoopBreakException) CREInvalidProcedureException(com.laytonsmith.core.exceptions.CRE.CREInvalidProcedureException) LoopContinueException(com.laytonsmith.core.exceptions.LoopContinueException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) CVoid(com.laytonsmith.core.constructs.CVoid) Extension(com.laytonsmith.core.extensions.Extension) CInt(com.laytonsmith.core.constructs.CInt) Construct(com.laytonsmith.core.constructs.Construct) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Environment(com.laytonsmith.core.environments.Environment) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) CEntry(com.laytonsmith.core.constructs.CEntry) Map(java.util.Map) HashMap(java.util.HashMap) CNull(com.laytonsmith.core.constructs.CNull)

Example 3 with CNull

use of com.laytonsmith.core.constructs.CNull in project CommandHelper by EngineHub.

the class ObjectGenerator method item.

/**
 * Gets an MCItemStack from a given item "object". Supports both the old and new formats currently
 *
 * @param i
 * @param t
 * @return An abstract item stack
 */
public MCItemStack item(Construct i, Target t) {
    if (i instanceof CNull) {
        return EmptyItem();
    }
    if (!(i instanceof CArray)) {
        throw new CREFormatException("Expected an array!", t);
    }
    CArray item = (CArray) i;
    MCMaterial mat;
    int data = 0;
    int qty = 1;
    if (item.containsKey("qty")) {
        qty = Static.getInt32(item.get("qty", t), t);
        if (qty <= 0) {
            return EmptyItem();
        }
    }
    if (item.containsKey("name")) {
        mat = StaticLayer.GetConvertor().GetMaterial(item.get("name", t).val());
    } else if (item.containsKey("type")) {
        Construct type = item.get("type", t);
        if (type instanceof CString) {
            int seperatorIndex = type.val().indexOf(':');
            if (seperatorIndex != -1) {
                try {
                    data = Integer.parseInt(type.val().substring(seperatorIndex + 1));
                } catch (NumberFormatException e) {
                    throw new CRERangeException("The item data \"" + type.val().substring(seperatorIndex + 1) + "\" is not a valid integer.", t);
                }
                type = new CString(type.val().substring(0, seperatorIndex), t);
            }
        }
        mat = StaticLayer.GetConvertor().getMaterial(Static.getInt32(type, t));
    } else {
        throw new CREFormatException("Could not find item name!", t);
    }
    if (mat == null) {
        throw new CRENotFoundException("A material could not be found based on the given name.", t);
    }
    if (mat.getType() == 0) {
        return EmptyItem();
    }
    if (item.containsKey("data")) {
        data = Static.getInt32(item.get("data", t), t);
    }
    MCItemMeta meta = null;
    if (item.containsKey("meta")) {
        meta = itemMeta(item.get("meta", t), mat, t);
    }
    // Create itemstack
    MCItemStack ret = StaticLayer.GetItemStack(mat, data, qty);
    if (meta != null) {
        ret.setItemMeta(meta);
    }
    // Fallback to enchants in item array if not in meta
    if (item.containsKey("enchants")) {
        try {
            Map<MCEnchantment, Integer> enchants = enchants((CArray) item.get("enchants", t), t);
            for (Map.Entry<MCEnchantment, Integer> entry : enchants.entrySet()) {
                ret.addUnsafeEnchantment(entry.getKey(), entry.getValue());
            }
        } catch (ClassCastException ex) {
            throw new CREFormatException("Enchants must be an array of enchantment arrays.", t);
        }
    }
    return ret;
}
Also used : CRENotFoundException(com.laytonsmith.core.exceptions.CRE.CRENotFoundException) CArray(com.laytonsmith.core.constructs.CArray) MCItemMeta(com.laytonsmith.abstraction.MCItemMeta) CString(com.laytonsmith.core.constructs.CString) MCMaterial(com.laytonsmith.abstraction.blocks.MCMaterial) MCEnchantment(com.laytonsmith.abstraction.MCEnchantment) MCItemStack(com.laytonsmith.abstraction.MCItemStack) Construct(com.laytonsmith.core.constructs.Construct) CREFormatException(com.laytonsmith.core.exceptions.CRE.CREFormatException) Map(java.util.Map) HashMap(java.util.HashMap) CRERangeException(com.laytonsmith.core.exceptions.CRE.CRERangeException) CNull(com.laytonsmith.core.constructs.CNull)

Example 4 with CNull

use of com.laytonsmith.core.constructs.CNull 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;
}
Also used : CRENotFoundException(com.laytonsmith.core.exceptions.CRE.CRENotFoundException) MCBanner(com.laytonsmith.abstraction.blocks.MCBanner) MCEntityType(com.laytonsmith.abstraction.enums.MCEntityType) MCFireworkMeta(com.laytonsmith.abstraction.MCFireworkMeta) CArray(com.laytonsmith.core.constructs.CArray) ArrayList(java.util.ArrayList) MCLeatherArmorMeta(com.laytonsmith.abstraction.MCLeatherArmorMeta) MCSpawnEggMeta(com.laytonsmith.abstraction.MCSpawnEggMeta) CString(com.laytonsmith.core.constructs.CString) CString(com.laytonsmith.core.constructs.CString) MCPotionMeta(com.laytonsmith.abstraction.MCPotionMeta) MCEnchantment(com.laytonsmith.abstraction.MCEnchantment) MCMapMeta(com.laytonsmith.abstraction.MCMapMeta) MCItemStack(com.laytonsmith.abstraction.MCItemStack) MCDyeColor(com.laytonsmith.abstraction.enums.MCDyeColor) MCBookMeta(com.laytonsmith.abstraction.MCBookMeta) MCBlockStateMeta(com.laytonsmith.abstraction.MCBlockStateMeta) List(java.util.List) ArrayList(java.util.ArrayList) MCFireworkEffectMeta(com.laytonsmith.abstraction.MCFireworkEffectMeta) MCBlockState(com.laytonsmith.abstraction.blocks.MCBlockState) MCBannerMeta(com.laytonsmith.abstraction.MCBannerMeta) MCInventory(com.laytonsmith.abstraction.MCInventory) MCSkullMeta(com.laytonsmith.abstraction.MCSkullMeta) MCItemFactory(com.laytonsmith.abstraction.MCItemFactory) MCItemMeta(com.laytonsmith.abstraction.MCItemMeta) MCPatternShape(com.laytonsmith.abstraction.enums.MCPatternShape) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) CRERangeException(com.laytonsmith.core.exceptions.CRE.CRERangeException) CREEnchantmentException(com.laytonsmith.core.exceptions.CRE.CREEnchantmentException) CREFormatException(com.laytonsmith.core.exceptions.CRE.CREFormatException) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) CREInvalidWorldException(com.laytonsmith.core.exceptions.CRE.CREInvalidWorldException) CRENotFoundException(com.laytonsmith.core.exceptions.CRE.CRENotFoundException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) MCEnchantmentStorageMeta(com.laytonsmith.abstraction.MCEnchantmentStorageMeta) MCCreatureSpawner(com.laytonsmith.abstraction.MCCreatureSpawner) Construct(com.laytonsmith.core.constructs.Construct) CREFormatException(com.laytonsmith.core.exceptions.CRE.CREFormatException) Map(java.util.Map) HashMap(java.util.HashMap) MCShulkerBox(com.laytonsmith.abstraction.blocks.MCShulkerBox) CNull(com.laytonsmith.core.constructs.CNull)

Example 5 with CNull

use of com.laytonsmith.core.constructs.CNull 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);
    }
}
Also used : MCRecipe(com.laytonsmith.abstraction.MCRecipe) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) MCShapelessRecipe(com.laytonsmith.abstraction.MCShapelessRecipe) CArray(com.laytonsmith.core.constructs.CArray) MCFurnaceRecipe(com.laytonsmith.abstraction.MCFurnaceRecipe) CString(com.laytonsmith.core.constructs.CString) CString(com.laytonsmith.core.constructs.CString) MCShapedRecipe(com.laytonsmith.abstraction.MCShapedRecipe) CInt(com.laytonsmith.core.constructs.CInt) MCItemStack(com.laytonsmith.abstraction.MCItemStack) MCRecipeType(com.laytonsmith.abstraction.enums.MCRecipeType) Construct(com.laytonsmith.core.constructs.Construct) CREFormatException(com.laytonsmith.core.exceptions.CRE.CREFormatException) CNull(com.laytonsmith.core.constructs.CNull)

Aggregations

CNull (com.laytonsmith.core.constructs.CNull)13 CArray (com.laytonsmith.core.constructs.CArray)12 Construct (com.laytonsmith.core.constructs.Construct)11 CString (com.laytonsmith.core.constructs.CString)8 CInt (com.laytonsmith.core.constructs.CInt)5 HashMap (java.util.HashMap)5 MCItemMeta (com.laytonsmith.abstraction.MCItemMeta)4 GlobalEnv (com.laytonsmith.core.environments.GlobalEnv)4 CRECastException (com.laytonsmith.core.exceptions.CRE.CRECastException)4 MCItemStack (com.laytonsmith.abstraction.MCItemStack)3 CBoolean (com.laytonsmith.core.constructs.CBoolean)3 CDouble (com.laytonsmith.core.constructs.CDouble)3 IVariable (com.laytonsmith.core.constructs.IVariable)3 AbstractCREException (com.laytonsmith.core.exceptions.CRE.AbstractCREException)3 CREFormatException (com.laytonsmith.core.exceptions.CRE.CREFormatException)3 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)3 Map (java.util.Map)3 MCBannerMeta (com.laytonsmith.abstraction.MCBannerMeta)2 MCBlockStateMeta (com.laytonsmith.abstraction.MCBlockStateMeta)2 MCBookMeta (com.laytonsmith.abstraction.MCBookMeta)2