Search in sources :

Example 6 with Variable

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

the class RandomTests method testClone.

@Test
public void testClone() throws CloneNotSupportedException {
    CArray c1 = C.Array(C.Void(), C.Void()).clone();
    CBoolean c2 = C.Boolean(true).clone();
    CDouble c4 = C.Double(1).clone();
    CFunction c5 = new CFunction("", Target.UNKNOWN).clone();
    CInt c6 = C.Int(1).clone();
    CNull c7 = C.Null().clone();
    CString c8 = C.String("").clone();
    Construct c9 = C.Void().clone();
    Command c10 = new Command("/c", Target.UNKNOWN).clone();
    IVariable c12 = new IVariable(Auto.TYPE, "@name", C.Null(), Target.UNKNOWN).clone();
    Variable c13 = new Variable("$name", "", false, false, Target.UNKNOWN);
}
Also used : CInt(com.laytonsmith.core.constructs.CInt) IVariable(com.laytonsmith.core.constructs.IVariable) Variable(com.laytonsmith.core.constructs.Variable) Command(com.laytonsmith.core.constructs.Command) CBoolean(com.laytonsmith.core.constructs.CBoolean) IVariable(com.laytonsmith.core.constructs.IVariable) CArray(com.laytonsmith.core.constructs.CArray) CDouble(com.laytonsmith.core.constructs.CDouble) CFunction(com.laytonsmith.core.constructs.CFunction) Construct(com.laytonsmith.core.constructs.Construct) CNull(com.laytonsmith.core.constructs.CNull) CString(com.laytonsmith.core.constructs.CString) Test(org.junit.Test)

Example 7 with Variable

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

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

the class OptimizationUtilities method optimize0.

private static String optimize0(ParseTree node) {
    if (node.getData() instanceof CFunction) {
        StringBuilder b = new StringBuilder();
        boolean first = true;
        b.append(((CFunction) node.getData()).val()).append("(");
        for (ParseTree child : node.getChildren()) {
            if (!first) {
                b.append(",");
            }
            first = false;
            b.append(optimize0(child));
        }
        b.append(")");
        return b.toString();
    } else if (node.getData() instanceof CString) {
        // strings
        return new StringBuilder().append("'").append(node.getData().val().replaceAll("\t", "\\t").replaceAll("\n", "\\n").replace("\\", "\\\\").replace("'", "\\'")).append("'").toString();
    } else if (node.getData() instanceof IVariable) {
        return ((IVariable) node.getData()).getVariableName();
    } else if (node.getData() instanceof Variable) {
        return ((Variable) node.getData()).getVariableName();
    } else if (node.getData() instanceof CSlice) {
        return node.getData().val();
    } else if (node.getData() instanceof CArray) {
        // It's a hardcoded array. This only happens in the course of optimization, if
        // the optimizer adds a new array. We still need to handle it appropriately though.
        // The values in the array will be constant, guaranteed.
        StringBuilder b = new StringBuilder();
        b.append("array(");
        boolean first = true;
        CArray n = (CArray) node.getData();
        for (String key : n.stringKeySet()) {
            if (!first) {
                b.append(",");
            }
            first = false;
            b.append(optimize0(new ParseTree(n.get(key, Target.UNKNOWN), node.getFileOptions())));
        }
        b.append(")");
        return b.toString();
    } else {
        // static
        return node.getData().toString();
    }
}
Also used : Variable(com.laytonsmith.core.constructs.Variable) IVariable(com.laytonsmith.core.constructs.IVariable) IVariable(com.laytonsmith.core.constructs.IVariable) CSlice(com.laytonsmith.core.constructs.CSlice) CArray(com.laytonsmith.core.constructs.CArray) CFunction(com.laytonsmith.core.constructs.CFunction) CString(com.laytonsmith.core.constructs.CString) ParseTree(com.laytonsmith.core.ParseTree) CString(com.laytonsmith.core.constructs.CString)

Example 9 with Variable

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

the class NewScript method toString.

@Override
public String toString() {
    StringBuilder b = new StringBuilder(label != null ? label + ":" : "");
    boolean first = true;
    for (Construct c : signature) {
        if (!first) {
            b.append(" ");
        }
        first = false;
        if (c instanceof Variable) {
            Variable var = (Variable) c;
            if (var.isOptional() && !var.getDefault().trim().isEmpty()) {
                b.append("[").append(var.getVariableName()).append("='").append(var.getDefault()).append("']");
            } else if (var.isOptional()) {
                b.append("[").append(var.getVariableName()).append("]");
            } else {
                b.append(var.getVariableName());
            }
        } else {
            b.append(c.val());
        }
    }
    return b.toString();
}
Also used : Variable(com.laytonsmith.core.constructs.Variable) Construct(com.laytonsmith.core.constructs.Construct)

Example 10 with Variable

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

the class ExampleScript method getOutput.

public String getOutput() throws IOException, DataSourceException, URISyntaxException {
    if (output != null) {
        return output;
    }
    Script s = Script.GenerateScript(script, Static.GLOBAL_PERMISSION);
    Environment env;
    try {
        env = Static.GenerateStandaloneEnvironment();
    } catch (Profiles.InvalidProfileException ex) {
        throw new RuntimeException(ex);
    }
    Class[] interfaces = new Class[] { MCPlayer.class };
    MCPlayer p = (MCPlayer) Proxy.newProxyInstance(ExampleScript.class.getClassLoader(), interfaces, new InvocationHandler() {

        @Override
        public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
            if (method.getName().equals("getName") || method.getName().equals("getDisplayName")) {
                return "Player";
            }
            if (method.getName().equals("sendMessage")) {
                playerOutput.append(args[0].toString()).append("\n");
            }
            if (method.getName().equals("isOnline")) {
                return true;
            }
            return genericReturn(method.getReturnType());
        }
    });
    // TODO: Remove this dependency. Make MCPlayer implement a generic "User" and make that
    // part of the GlobalEnv.
    env.getEnv(CommandHelperEnvironment.class).SetPlayer(p);
    final StringBuilder finalOutput = new StringBuilder();
    String thrown = null;
    try {
        List<Variable> vars = new ArrayList<>();
        try {
            MethodScriptCompiler.execute(originalScript, new File("/" + functionName + ".ms"), true, env, new MethodScriptComplete() {

                @Override
                public void done(String output) {
                    if (output != null) {
                        finalOutput.append(output);
                    }
                }
            }, null, vars);
        } catch (ConfigCompileException | ConfigCompileGroupException ex) {
        // We already checked for compile errors, so this won't happen
        }
    } catch (ConfigRuntimeException e) {
        String name = e.getClass().getName();
        if (e instanceof AbstractCREException) {
            name = ((AbstractCREException) e).getName();
        }
        thrown = "\n(Throws " + name + ": " + e.getMessage() + ")";
    }
    String playerOut = playerOutput.toString().trim();
    String finalOut = finalOutput.toString().trim();
    String out = (playerOut.isEmpty() ? "" : playerOut) + (finalOut.isEmpty() || !playerOut.trim().isEmpty() ? "" : ":" + finalOut);
    if (thrown != null) {
        out += thrown;
    }
    return out;
}
Also used : Variable(com.laytonsmith.core.constructs.Variable) MCPlayer(com.laytonsmith.abstraction.MCPlayer) ArrayList(java.util.ArrayList) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) ConfigRuntimeException(com.laytonsmith.core.exceptions.ConfigRuntimeException) Profiles(com.laytonsmith.core.Profiles) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) Script(com.laytonsmith.core.Script) AbstractCREException(com.laytonsmith.core.exceptions.CRE.AbstractCREException) Method(java.lang.reflect.Method) InvocationHandler(java.lang.reflect.InvocationHandler) MethodScriptComplete(com.laytonsmith.core.MethodScriptComplete) Environment(com.laytonsmith.core.environments.Environment) CommandHelperEnvironment(com.laytonsmith.core.environments.CommandHelperEnvironment) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) File(java.io.File)

Aggregations

Variable (com.laytonsmith.core.constructs.Variable)14 CString (com.laytonsmith.core.constructs.CString)12 IVariable (com.laytonsmith.core.constructs.IVariable)11 Construct (com.laytonsmith.core.constructs.Construct)8 ArrayList (java.util.ArrayList)7 ProfilePoint (com.laytonsmith.core.profiler.ProfilePoint)6 ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)5 Token (com.laytonsmith.core.constructs.Token)4 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)4 ParseTree (com.laytonsmith.core.ParseTree)3 CArray (com.laytonsmith.core.constructs.CArray)3 CFunction (com.laytonsmith.core.constructs.CFunction)3 GlobalEnv (com.laytonsmith.core.environments.GlobalEnv)3 MethodScriptComplete (com.laytonsmith.core.MethodScriptComplete)2 FileOptions (com.laytonsmith.core.compiler.FileOptions)2 CDouble (com.laytonsmith.core.constructs.CDouble)2 CInt (com.laytonsmith.core.constructs.CInt)2 CNull (com.laytonsmith.core.constructs.CNull)2 CSlice (com.laytonsmith.core.constructs.CSlice)2 Command (com.laytonsmith.core.constructs.Command)2