Search in sources :

Example 6 with CArray

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

the class AbstractCREException method getCausedBy.

private static Construct getCausedBy(Throwable causedBy) {
    if (causedBy == null || !(causedBy instanceof CRECausedByWrapper)) {
        return CNull.NULL;
    }
    CRECausedByWrapper cre = (CRECausedByWrapper) causedBy;
    CArray ret = cre.getException();
    return ret;
}
Also used : CArray(com.laytonsmith.core.constructs.CArray)

Example 7 with CArray

use of com.laytonsmith.core.constructs.CArray 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 8 with CArray

use of com.laytonsmith.core.constructs.CArray 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 9 with CArray

use of com.laytonsmith.core.constructs.CArray 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);
    }
}
Also used : IVariable(com.laytonsmith.core.constructs.IVariable) CArray(com.laytonsmith.core.constructs.CArray) CString(com.laytonsmith.core.constructs.CString) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CString(com.laytonsmith.core.constructs.CString) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) Environment(com.laytonsmith.core.environments.Environment) Construct(com.laytonsmith.core.constructs.Construct) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) HashMap(java.util.HashMap) Map(java.util.Map)

Example 10 with CArray

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

the class ObjectGenerator method enchants.

public CArray enchants(Map<MCEnchantment, Integer> map, Target t) {
    CArray ret = new CArray(t);
    for (Map.Entry<MCEnchantment, Integer> entry : map.entrySet()) {
        CArray eObj = CArray.GetAssociativeArray(t);
        eObj.set("etype", new CString(entry.getKey().getName(), t), t);
        eObj.set("elevel", new CInt(entry.getValue(), t), t);
        ret.push(eObj, t);
    }
    return ret;
}
Also used : MCEnchantment(com.laytonsmith.abstraction.MCEnchantment) CInt(com.laytonsmith.core.constructs.CInt) CArray(com.laytonsmith.core.constructs.CArray) Map(java.util.Map) HashMap(java.util.HashMap) CString(com.laytonsmith.core.constructs.CString)

Aggregations

CArray (com.laytonsmith.core.constructs.CArray)50 CString (com.laytonsmith.core.constructs.CString)27 Construct (com.laytonsmith.core.constructs.Construct)23 CInt (com.laytonsmith.core.constructs.CInt)17 CNull (com.laytonsmith.core.constructs.CNull)12 CREFormatException (com.laytonsmith.core.exceptions.CRE.CREFormatException)12 HashMap (java.util.HashMap)9 CDouble (com.laytonsmith.core.constructs.CDouble)8 IVariable (com.laytonsmith.core.constructs.IVariable)8 GlobalEnv (com.laytonsmith.core.environments.GlobalEnv)6 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)6 ArrayList (java.util.ArrayList)6 Map (java.util.Map)6 CBoolean (com.laytonsmith.core.constructs.CBoolean)5 Target (com.laytonsmith.core.constructs.Target)5 CRECastException (com.laytonsmith.core.exceptions.CRE.CRECastException)5 FunctionReturnException (com.laytonsmith.core.exceptions.FunctionReturnException)5 MCEnchantment (com.laytonsmith.abstraction.MCEnchantment)4 MCItemMeta (com.laytonsmith.abstraction.MCItemMeta)4 MCItemStack (com.laytonsmith.abstraction.MCItemStack)4