Search in sources :

Example 11 with ConfigRuntimeException

use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.

the class BukkitMCCommand method handleTabComplete.

// I may be able to move these to c.l.c.f.Commands.java
@Override
public List<String> handleTabComplete(MCCommandSender sender, String alias, String[] args) {
    if (Commands.onTabComplete.containsKey(cmd.getName().toLowerCase())) {
        Target t = Target.UNKNOWN;
        CArray cargs = new CArray(t);
        for (String arg : args) {
            cargs.push(new CString(arg, t), t);
        }
        CClosure closure = Commands.onTabComplete.get(cmd.getName().toLowerCase());
        try {
            closure.execute(new CString(alias, t), new CString(sender.getName(), t), cargs, // reserved for an obgen style command array
            new CArray(t));
        } catch (FunctionReturnException e) {
            Construct fret = e.getReturn();
            if (fret instanceof CArray) {
                List<String> ret = new ArrayList<>();
                if (((CArray) fret).inAssociativeMode()) {
                    for (Construct key : ((CArray) fret).keySet()) {
                        ret.add(((CArray) fret).get(key, Target.UNKNOWN).val());
                    }
                } else {
                    for (Construct value : ((CArray) fret).asList()) {
                        ret.add(value.val());
                    }
                }
                return ret;
            }
        } catch (ConfigRuntimeException cre) {
            ConfigRuntimeException.HandleUncaughtException(cre, closure.getEnv());
            return new ArrayList<>();
        }
    }
    BukkitMCCommandTabCompleteEvent event = new BukkitMCCommandTabCompleteEvent(sender, cmd, alias, args);
    EventUtils.TriggerListener(Driver.TAB_COMPLETE, "tab_complete_command", event);
    return event.getCompletions();
}
Also used : BukkitMCCommandTabCompleteEvent(com.laytonsmith.abstraction.bukkit.events.BukkitMiscEvents.BukkitMCCommandTabCompleteEvent) Target(com.laytonsmith.core.constructs.Target) CClosure(com.laytonsmith.core.constructs.CClosure) CArray(com.laytonsmith.core.constructs.CArray) Construct(com.laytonsmith.core.constructs.Construct) ArrayList(java.util.ArrayList) List(java.util.List) CString(com.laytonsmith.core.constructs.CString) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CString(com.laytonsmith.core.constructs.CString)

Example 12 with ConfigRuntimeException

use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.

the class Interpreter method execute.

/**
 * This executes an entire script. The cmdline_prompt_event is first triggered (if used) and if the event is
 * cancelled, nothing happens.
 *
 * @param script
 * @param args
 * @param fromFile
 * @throws ConfigCompileException
 * @throws IOException
 */
public void execute(String script, List<String> args, File fromFile) throws ConfigCompileException, IOException, ConfigCompileGroupException {
    CmdlineEvents.cmdline_prompt_input.CmdlinePromptInput input = new CmdlineEvents.cmdline_prompt_input.CmdlinePromptInput(script, inShellMode);
    EventUtils.TriggerListener(Driver.CMDLINE_PROMPT_INPUT, "cmdline_prompt_input", input);
    if (input.isCancelled()) {
        return;
    }
    ctrlCcount = 0;
    if ("exit".equals(script)) {
        if (inShellMode) {
            inShellMode = false;
            return;
        }
        pl(YELLOW + "Use exit() if you wish to exit.");
        return;
    }
    if ("help".equals(script)) {
        pl(getHelpMsg());
        return;
    }
    if (fromFile == null) {
        fromFile = new File("Interpreter");
    }
    boolean localShellMode = false;
    if (!inShellMode && script.startsWith("$$")) {
        localShellMode = true;
        script = script.substring(2);
    }
    if (inShellMode || localShellMode) {
        // Wrap this in shell_adv
        if (doBuiltin(script)) {
            return;
        }
        List<String> shellArgs = StringUtils.ArgParser(script);
        List<String> escapedArgs = new ArrayList<>();
        for (String arg : shellArgs) {
            escapedArgs.add(new CString(arg, Target.UNKNOWN).getQuote());
        }
        script = "shell_adv(" + "array(" + StringUtils.Join(escapedArgs, ",") + ")," + "array(" + "'stdout':closure(@l){sys_out(@l);}," + "'stderr':closure(@l){sys_err(@l);})" + ");";
    }
    isExecuting = true;
    ProfilePoint compile = env.getEnv(GlobalEnv.class).GetProfiler().start("Compilation", LogLevel.VERBOSE);
    final ParseTree tree;
    try {
        TokenStream stream = MethodScriptCompiler.lex(script, fromFile, true);
        tree = MethodScriptCompiler.compile(stream);
    } finally {
        compile.stop();
    }
    // Environment env = Environment.createEnvironment(this.env.getEnv(GlobalEnv.class));
    final List<Variable> vars = new ArrayList<>();
    if (args != null) {
        // Build the @arguments variable, the $ vars, and $ itself. Note that
        // we have special handling for $0, that is the script name, like bash.
        // However, it doesn't get added to either $ or @arguments, due to the
        // uncommon use of it.
        StringBuilder finalArgument = new StringBuilder();
        CArray arguments = new CArray(Target.UNKNOWN);
        {
            // Set the $0 argument
            Variable v = new Variable("$0", "", Target.UNKNOWN);
            v.setVal(fromFile.toString());
            v.setDefault(fromFile.toString());
            vars.add(v);
        }
        for (int i = 0; i < args.size(); i++) {
            String arg = args.get(i);
            if (i > 0) {
                finalArgument.append(" ");
            }
            Variable v = new Variable("$" + Integer.toString(i + 1), "", Target.UNKNOWN);
            v.setVal(new CString(arg, Target.UNKNOWN));
            v.setDefault(arg);
            vars.add(v);
            finalArgument.append(arg);
            arguments.push(new CString(arg, Target.UNKNOWN), Target.UNKNOWN);
        }
        Variable v = new Variable("$", "", false, true, Target.UNKNOWN);
        v.setVal(new CString(finalArgument.toString(), Target.UNKNOWN));
        v.setDefault(finalArgument.toString());
        vars.add(v);
        env.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, Target.UNKNOWN));
    }
    try {
        ProfilePoint p = this.env.getEnv(GlobalEnv.class).GetProfiler().start("Interpreter Script", LogLevel.ERROR);
        try {
            final MutableObject<Throwable> wasThrown = new MutableObject<>();
            scriptThread = new Thread(new Runnable() {

                @Override
                public void run() {
                    try {
                        MethodScriptCompiler.execute(tree, env, new MethodScriptComplete() {

                            @Override
                            public void done(String output) {
                                if (System.console() != null && !"".equals(output.trim())) {
                                    StreamUtils.GetSystemOut().println(output);
                                }
                            }
                        }, null, vars);
                    } catch (CancelCommandException e) {
                    // Nothing, though we could have been Ctrl+C cancelled, so we need to reset
                    // the interrupt flag. But we do that unconditionally below, in the finally,
                    // in the other thread.
                    } catch (ConfigRuntimeException e) {
                        ConfigRuntimeException.HandleUncaughtException(e, env);
                        // No need for the full stack trace
                        if (System.console() == null) {
                            System.exit(1);
                        }
                    } catch (NoClassDefFoundError e) {
                        StreamUtils.GetSystemErr().println(RED + Main.getNoClassDefFoundErrorMessage(e) + reset());
                        StreamUtils.GetSystemErr().println("Since you're running from standalone interpreter mode, this is not a fatal error, but one of the functions you just used required" + " an actual backing engine that isn't currently loaded. (It still might fail even if you load the engine though.) You simply won't be" + " able to use that function here.");
                        if (System.console() == null) {
                            System.exit(1);
                        }
                    } catch (InvalidEnvironmentException ex) {
                        StreamUtils.GetSystemErr().println(RED + ex.getMessage() + " " + ex.getData() + "() cannot be used in this context.");
                        if (System.console() == null) {
                            System.exit(1);
                        }
                    } catch (RuntimeException e) {
                        pl(RED + e.toString());
                        e.printStackTrace(StreamUtils.GetSystemErr());
                        if (System.console() == null) {
                            System.exit(1);
                        }
                    }
                }
            }, "MethodScript-Main");
            scriptThread.start();
            try {
                scriptThread.join();
            } catch (InterruptedException ex) {
            // 
            }
        } finally {
            p.stop();
        }
    } finally {
        env.getEnv(GlobalEnv.class).SetInterrupt(false);
        isExecuting = false;
    }
}
Also used : TokenStream(com.laytonsmith.core.compiler.TokenStream) InvalidEnvironmentException(com.laytonsmith.core.environments.InvalidEnvironmentException) IVariable(com.laytonsmith.core.constructs.IVariable) Variable(com.laytonsmith.core.constructs.Variable) IVariable(com.laytonsmith.core.constructs.IVariable) ArrayList(java.util.ArrayList) CArray(com.laytonsmith.core.constructs.CArray) CString(com.laytonsmith.core.constructs.CString) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CString(com.laytonsmith.core.constructs.CString) CmdlineEvents(com.laytonsmith.core.events.drivers.CmdlineEvents) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) MutableObject(com.laytonsmith.PureUtilities.Common.MutableObject) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) ProfilePoint(com.laytonsmith.core.profiler.ProfilePoint) MethodScriptComplete(com.laytonsmith.core.MethodScriptComplete) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) File(java.io.File) ParseTree(com.laytonsmith.core.ParseTree)

Example 13 with ConfigRuntimeException

use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.

the class CIClosure method execute.

@Override
public void execute(Construct... values) throws ConfigRuntimeException, ProgramFlowManipulationException, FunctionReturnException, CancelCommandException {
    if (node == null) {
        return;
    }
    StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
    stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("<<iclosure>>", getTarget()));
    try {
        Environment environment;
        synchronized (this) {
            boolean prev = env.getEnv(GlobalEnv.class).getCloneVars();
            env.getEnv(GlobalEnv.class).setCloneVars(false);
            environment = env.clone();
            env.getEnv(GlobalEnv.class).setCloneVars(prev);
        }
        environment.getEnv(GlobalEnv.class).setCloneVars(true);
        if (values != null) {
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                Construct value;
                try {
                    value = values[i];
                } catch (Exception e) {
                    value = defaults[i].clone();
                }
                environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(types[i], name, value, getTarget()));
            }
        }
        boolean hasArgumentsParam = false;
        for (String pName : this.names) {
            if (pName.equals("@arguments")) {
                hasArgumentsParam = true;
                break;
            }
        }
        if (!hasArgumentsParam) {
            CArray arguments = new CArray(node.getData().getTarget());
            if (values != null) {
                for (Construct value : values) {
                    arguments.push(value, node.getData().getTarget());
                }
            }
            environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, node.getData().getTarget()));
        }
        ParseTree newNode = new ParseTree(new CFunction("g", getTarget()), node.getFileOptions());
        List<ParseTree> children = new ArrayList<ParseTree>();
        children.add(node);
        newNode.setChildren(children);
        try {
            MethodScriptCompiler.execute(newNode, environment, null, environment.getEnv(GlobalEnv.class).GetScript());
        } catch (LoopManipulationException e) {
            // Not normal, but pop anyways
            stManager.popStackTraceElement();
            // This shouldn't ever happen.
            LoopManipulationException lme = ((LoopManipulationException) e);
            Target t = lme.getTarget();
            ConfigRuntimeException.HandleUncaughtException(ConfigRuntimeException.CreateUncatchableException("A " + lme.getName() + "() bubbled up to the top of" + " a closure, which is unexpected behavior.", t), environment);
        } catch (FunctionReturnException ex) {
            // Normal. Pop element
            stManager.popStackTraceElement();
            // Check the return type of the closure to see if it matches the defined type
            Construct ret = ex.getReturn();
            if (!InstanceofUtil.isInstanceof(ret, returnType)) {
                throw new CRECastException("Expected closure to return a value of type " + returnType.val() + " but a value of type " + ret.typeof() + " was returned instead", ret.getTarget());
            }
            // Now rethrow it
            throw ex;
        } catch (CancelCommandException e) {
            stManager.popStackTraceElement();
        // die()
        } catch (ConfigRuntimeException ex) {
            if (ex instanceof AbstractCREException) {
                ((AbstractCREException) ex).freezeStackTraceElements(stManager);
            }
            throw ex;
        } catch (Throwable t) {
            stManager.popStackTraceElement();
            throw t;
        }
        // If we got here, then there was no return type. This is fine, but only for returnType void or auto.
        if (!(returnType.equals(Auto.TYPE) || returnType.equals(CVoid.TYPE))) {
            throw new CRECastException("Expecting closure to return a value of type " + returnType.val() + "," + " but no value was returned.", node.getTarget());
        }
    } catch (CloneNotSupportedException ex) {
        Logger.getLogger(CClosure.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : ArrayList(java.util.ArrayList) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) StackTraceManager(com.laytonsmith.core.exceptions.StackTraceManager) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) LoopManipulationException(com.laytonsmith.core.exceptions.LoopManipulationException) ProgramFlowManipulationException(com.laytonsmith.core.exceptions.ProgramFlowManipulationException) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) Environment(com.laytonsmith.core.environments.Environment) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) LoopManipulationException(com.laytonsmith.core.exceptions.LoopManipulationException) ParseTree(com.laytonsmith.core.ParseTree)

Example 14 with ConfigRuntimeException

use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.

the class CClosure method execute.

/**
 * Executes the closure, giving it the supplied arguments. {@code values} may be null, which means that no arguments
 * are being sent.
 *
 * LoopManipulationExceptions will never bubble up past this point, because they are never allowed, so they are
 * handled automatically, but other ProgramFlowManipulationExceptions will, . ConfigRuntimeExceptions will also
 * bubble up past this, since an execution mechanism may need to do custom handling.
 *
 * A typical execution will include the following code:
 * <pre>
 * try {
 *	closure.execute();
 * } catch(ConfigRuntimeException e){
 *	ConfigRuntimeException.HandleUncaughtException(e);
 * } catch(ProgramFlowManipulationException e){
 *	// Ignored
 * }
 * </pre>
 *
 * @param values The values to be passed to the closure
 * @throws ConfigRuntimeException If any call inside the closure causes a CRE
 * @throws ProgramFlowManipulationException If any ProgramFlowManipulationException is thrown (other than a
 * LoopManipulationException) within the closure
 * @throws FunctionReturnException If the closure has a return() call in it.
 */
public void execute(Construct... values) throws ConfigRuntimeException, ProgramFlowManipulationException, FunctionReturnException, CancelCommandException {
    if (node == null) {
        return;
    }
    StackTraceManager stManager = env.getEnv(GlobalEnv.class).GetStackTraceManager();
    stManager.addStackTraceElement(new ConfigRuntimeException.StackTraceElement("<<closure>>", getTarget()));
    try {
        Environment environment;
        synchronized (this) {
            environment = env.clone();
        }
        if (values != null) {
            for (int i = 0; i < names.length; i++) {
                String name = names[i];
                Construct value;
                try {
                    value = values[i];
                } catch (Exception e) {
                    value = defaults[i].clone();
                }
                environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(types[i], name, value, getTarget()));
            }
        }
        boolean hasArgumentsParam = false;
        for (String pName : this.names) {
            if (pName.equals("@arguments")) {
                hasArgumentsParam = true;
                break;
            }
        }
        if (!hasArgumentsParam) {
            CArray arguments = new CArray(node.getData().getTarget());
            if (values != null) {
                for (Construct value : values) {
                    arguments.push(value, node.getData().getTarget());
                }
            }
            environment.getEnv(GlobalEnv.class).GetVarList().set(new IVariable(CArray.TYPE, "@arguments", arguments, node.getData().getTarget()));
        }
        ParseTree newNode = new ParseTree(new CFunction("g", getTarget()), node.getFileOptions());
        List<ParseTree> children = new ArrayList<ParseTree>();
        children.add(node);
        newNode.setChildren(children);
        try {
            MethodScriptCompiler.execute(newNode, environment, null, environment.getEnv(GlobalEnv.class).GetScript());
        } catch (LoopManipulationException e) {
            // This shouldn't ever happen.
            LoopManipulationException lme = ((LoopManipulationException) e);
            Target t = lme.getTarget();
            ConfigRuntimeException.HandleUncaughtException(ConfigRuntimeException.CreateUncatchableException("A " + lme.getName() + "() bubbled up to the top of" + " a closure, which is unexpected behavior.", t), environment);
        } catch (FunctionReturnException ex) {
            // Check the return type of the closure to see if it matches the defined type
            // Normal execution.
            Construct ret = ex.getReturn();
            if (!InstanceofUtil.isInstanceof(ret, returnType)) {
                throw new CRECastException("Expected closure to return a value of type " + returnType.val() + " but a value of type " + ret.typeof() + " was returned instead", ret.getTarget());
            }
            // Now rethrow it
            throw ex;
        } catch (CancelCommandException e) {
        // die()
        } catch (ConfigRuntimeException ex) {
            if (ex instanceof AbstractCREException) {
                ((AbstractCREException) ex).freezeStackTraceElements(stManager);
            }
            throw ex;
        } catch (Throwable t) {
            // Not sure. Pop and re-throw.
            throw t;
        } finally {
            stManager.popStackTraceElement();
        }
        // If we got here, then there was no return type. This is fine, but only for returnType void or auto.
        if (!(returnType.equals(Auto.TYPE) || returnType.equals(CVoid.TYPE))) {
            throw new CRECastException("Expecting closure to return a value of type " + returnType.val() + "," + " but no value was returned.", node.getTarget());
        }
    } catch (CloneNotSupportedException ex) {
        Logger.getLogger(CClosure.class.getName()).log(Level.SEVERE, null, ex);
    }
}
Also used : ArrayList(java.util.ArrayList) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) StackTraceManager(com.laytonsmith.core.exceptions.StackTraceManager) CRECastException(com.laytonsmith.core.exceptions.CRE.CRECastException) LoopManipulationException(com.laytonsmith.core.exceptions.LoopManipulationException) ProgramFlowManipulationException(com.laytonsmith.core.exceptions.ProgramFlowManipulationException) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) CancelCommandException(com.laytonsmith.core.exceptions.CancelCommandException) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) Environment(com.laytonsmith.core.environments.Environment) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) LoopManipulationException(com.laytonsmith.core.exceptions.LoopManipulationException) ParseTree(com.laytonsmith.core.ParseTree)

Example 15 with ConfigRuntimeException

use of com.laytonsmith.core.exceptions.ConfigRuntimeException in project CommandHelper by EngineHub.

the class EventUtils method FireListeners.

public static void FireListeners(SortedSet<BoundEvent> toRun, Event driver, BindableEvent e) {
    // Sort our event handlers by priorities
    BoundEvent.ActiveEvent activeEvent = new BoundEvent.ActiveEvent(e);
    for (BoundEvent b : toRun) {
        if (activeEvent.canReceive() || b.getPriority().equals(Priority.MONITOR)) {
            try {
                // We must re-set the active event's bound event and parsed event
                activeEvent.setBoundEvent(b);
                activeEvent.setParsedEvent(driver.evaluate(e));
                b.trigger(activeEvent);
            } catch (FunctionReturnException ex) {
            // We also know how to deal with this
            } catch (EventException ex) {
                throw new CREEventException(ex.getMessage(), Target.UNKNOWN, ex);
            } catch (ConfigRuntimeException ex) {
                // An exception has bubbled all the way up
                ConfigRuntimeException.HandleUncaughtException(ex, b.getEnvironment());
            }
        }
    }
    for (BoundEvent b : toRun) {
        activeEvent.setBoundEvent(b);
        if (activeEvent.isCancelled()) {
            activeEvent.executeCancelled();
        } else {
            activeEvent.executeTriggered();
        }
    }
}
Also used : EventException(com.laytonsmith.core.exceptions.EventException) CREEventException(com.laytonsmith.core.exceptions.CRE.CREEventException) CREEventException(com.laytonsmith.core.exceptions.CRE.CREEventException) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException)

Aggregations

ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)22 CString (com.laytonsmith.core.constructs.CString)11 GlobalEnv (com.laytonsmith.core.environments.GlobalEnv)10 FunctionReturnException (com.laytonsmith.core.exceptions.FunctionReturnException)10 Construct (com.laytonsmith.core.constructs.Construct)9 Environment (com.laytonsmith.core.environments.Environment)9 ArrayList (java.util.ArrayList)9 CancelCommandException (com.laytonsmith.core.exceptions.CancelCommandException)8 CArray (com.laytonsmith.core.constructs.CArray)7 CommandHelperEnvironment (com.laytonsmith.core.environments.CommandHelperEnvironment)7 IVariable (com.laytonsmith.core.constructs.IVariable)6 AbstractCREException (com.laytonsmith.core.exceptions.CRE.AbstractCREException)6 ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)6 Target (com.laytonsmith.core.constructs.Target)5 CRECastException (com.laytonsmith.core.exceptions.CRE.CRECastException)5 ProgramFlowManipulationException (com.laytonsmith.core.exceptions.ProgramFlowManipulationException)5 ParseTree (com.laytonsmith.core.ParseTree)4 ConfigCompileGroupException (com.laytonsmith.core.exceptions.ConfigCompileGroupException)4 StackTraceManager (com.laytonsmith.core.exceptions.StackTraceManager)4 ProfilePoint (com.laytonsmith.core.profiler.ProfilePoint)4