Search in sources :

Example 26 with ConfigCompileException

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

the class IClosureKeyword method process.

@Override
public int process(List<ParseTree> list, int keywordPosition) throws ConfigCompileException {
    try {
        if (list.get(keywordPosition).getData() instanceof CFunction) {
            // It's a function, so do the old processing
            SimpleBlockKeywordFunction.doProcess(this.getKeywordName(), null, true, list, keywordPosition);
            // easiest if we do the conversion here.
            try {
                if (list.get(keywordPosition - 1).getData() instanceof CClassType) {
                    ParseTree type = list.remove(keywordPosition - 1);
                    List<ParseTree> children = list.get(keywordPosition - 1).getChildren();
                    children.add(0, type);
                    list.get(keywordPosition - 1).setChildren(children);
                    return keywordPosition - 1;
                }
            } catch (IndexOutOfBoundsException ex) {
            // Ignore, it's not a typed closure
            }
            return keywordPosition;
        } else {
            // Else it's standalone, so this should be treated as the closure ClassType
            list.set(keywordPosition, new ParseTree(CIClosure.TYPE, list.get(keywordPosition).getFileOptions()));
            return keywordPosition;
        }
    } catch (IndexOutOfBoundsException ex) {
        throw new ConfigCompileException("Unexpected \"iclosure\" reference", list.get(keywordPosition).getTarget());
    }
}
Also used : CFunction(com.laytonsmith.core.constructs.CFunction) CClassType(com.laytonsmith.core.constructs.CClassType) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) ParseTree(com.laytonsmith.core.ParseTree)

Example 27 with ConfigCompileException

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

the class CompositeFunction method exec.

@Override
public Construct exec(Target t, Environment environment, Construct... args) throws ConfigRuntimeException {
    ParseTree tree;
    if (!cachedScripts.containsKey(this.getClass())) {
        try {
            String script = script();
            tree = MethodScriptCompiler.compile(MethodScriptCompiler.lex(script, null, true)).getChildAt(0);
        } catch (ConfigCompileException | ConfigCompileGroupException ex) {
            // This is really bad.
            throw new Error(ex);
        }
        if (cacheCompile()) {
            cachedScripts.put(this.getClass(), tree);
        }
    } else {
        tree = cachedScripts.get(this.getClass());
    }
    GlobalEnv env = environment.getEnv(GlobalEnv.class);
    IVariableList oldVariables = env.GetVarList();
    IVariableList newVariables = new IVariableList();
    newVariables.set(new IVariable(CClassType.get("array"), "@arguments", new CArray(t, args.length, args), t));
    env.SetVarList(newVariables);
    Construct ret = CVoid.VOID;
    try {
        env.GetScript().eval(tree, environment);
    } catch (FunctionReturnException ex) {
        ret = ex.getReturn();
    }
    env.SetVarList(oldVariables);
    return ret;
}
Also used : IVariable(com.laytonsmith.core.constructs.IVariable) IVariableList(com.laytonsmith.core.constructs.IVariableList) CArray(com.laytonsmith.core.constructs.CArray) Construct(com.laytonsmith.core.constructs.Construct) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) FunctionReturnException(com.laytonsmith.core.exceptions.FunctionReturnException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) ParseTree(com.laytonsmith.core.ParseTree)

Example 28 with ConfigCompileException

use of com.laytonsmith.core.exceptions.ConfigCompileException 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)

Example 29 with ConfigCompileException

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

the class IncludeCache method get.

public static ParseTree get(File file, Target t) {
    CHLog.GetLogger().Log(TAG, LogLevel.DEBUG, "Loading " + file, t);
    if (cache.containsKey(file)) {
        CHLog.GetLogger().Log(TAG, LogLevel.INFO, "Returning " + file + " from cache", t);
        return cache.get(file);
    }
    CHLog.GetLogger().Log(TAG, LogLevel.VERBOSE, "Cache does not already contain file. Compiling and caching.", t);
    // We have to pull the file from the FS, and compile it.
    if (!Security.CheckSecurity(file)) {
        throw new CRESecurityException("The script cannot access " + file + " due to restrictions imposed by the base-dir setting.", t);
    }
    CHLog.GetLogger().Log(TAG, LogLevel.VERBOSE, "Security check passed", t);
    try {
        String s = new ZipReader(file).getFileContents();
        ParseTree tree = MethodScriptCompiler.compile(MethodScriptCompiler.lex(s, file, true));
        CHLog.GetLogger().Log(TAG, LogLevel.VERBOSE, "Compilation succeeded, adding to cache.", t);
        IncludeCache.add(file, tree);
        return tree;
    } catch (ConfigCompileException ex) {
        throw new CREIncludeException("There was a compile error when trying to include the script at " + file + "\n" + ex.getMessage() + " :: " + file.getName() + ":" + ex.getLineNum(), t);
    } catch (ConfigCompileGroupException ex) {
        StringBuilder b = new StringBuilder();
        b.append("There were compile errors when trying to include the script at ").append(file).append("\n");
        for (ConfigCompileException e : ex.getList()) {
            b.append(e.getMessage()).append(" :: ").append(e.getFile().getName()).append(":").append(e.getLineNum());
        }
        throw new CREIncludeException(b.toString(), t);
    } catch (IOException ex) {
        throw new CREIOException("The script at " + file + " could not be found or read in.", t);
    }
}
Also used : CREIncludeException(com.laytonsmith.core.exceptions.CRE.CREIncludeException) ZipReader(com.laytonsmith.PureUtilities.ZipReader) IOException(java.io.IOException) CREIOException(com.laytonsmith.core.exceptions.CRE.CREIOException) CREIOException(com.laytonsmith.core.exceptions.CRE.CREIOException) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) ParseTree(com.laytonsmith.core.ParseTree) CRESecurityException(com.laytonsmith.core.exceptions.CRE.CRESecurityException)

Example 30 with ConfigCompileException

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

the class SiteDeploy method generateFunctionDocs.

private void generateFunctionDocs(Function f, DocGen.DocInfo docs) {
    StringBuilder page = new StringBuilder();
    page.append("== ").append(f.getName()).append(" ==\n");
    page.append("<div>").append(docs.desc).append("</div>\n");
    page.append("=== Vital Info ===\n");
    page.append("{| style=\"width: 40%;\" cellspacing=\"1\" cellpadding=\"1\" border=\"1\" class=\"wikitable\"\n");
    page.append("|-\n" + "! scope=\"col\" width=\"20%\" | \n" + "! scope=\"col\" width=\"80%\" | \n" + "|-\n" + "! scope=\"row\" | Name\n" + "| ").append(f.getName()).append("\n" + "|-\n" + "! scope=\"row\" | Returns\n" + "| ").append(docs.ret).append("\n" + "|-\n" + "! scope=\"row\" | Usages\n" + "| ").append(docs.args).append("\n" + "|-\n" + "! scope=\"row\" | Throws\n" + "| ");
    List<String> exceptions = new ArrayList<>();
    for (Class<? extends CREThrowable> c : f.thrown()) {
        String t = c.getAnnotation(typeof.class).value();
        exceptions.add("[[../objects/" + t + "|" + t + "]]");
    }
    page.append(StringUtils.Join(exceptions, "<br>"));
    page.append("\n" + "|-\n" + "! scope=\"row\" | Since\n" + "| ").append(f.since()).append("\n" + "|-\n" + "! scope=\"row\" | Restricted\n");
    page.append("| <div style=\"background-color: ");
    page.append(f.isRestricted() ? "red" : "green");
    page.append("; font-weight: bold; text-align: center;\">").append(f.isRestricted() ? "Yes" : "No").append("</div>\n" + "|-\n" + "! scope=\"row\" | Optimizations\n" + "| ");
    String optimizationMessage = "None";
    if (f instanceof Optimizable) {
        Set<Optimizable.OptimizationOption> options = ((Optimizable) f).optimizationOptions();
        List<String> list = new ArrayList<>();
        for (Optimizable.OptimizationOption option : options) {
            list.add("[[../../Optimizer#" + option.name() + "|" + option.name() + "]]");
        }
        optimizationMessage = StringUtils.Join(list, " <br /> ");
    }
    page.append(optimizationMessage);
    page.append("\n|}");
    if (docs.extendedDesc != null) {
        page.append("<div>").append(docs.extendedDesc).append("</div>");
    }
    String[] usages = docs.originalArgs.split("\\|");
    StringBuilder usageBuilder = new StringBuilder();
    for (String usage : usages) {
        usageBuilder.append("<pre>\n").append(f.getName()).append("(").append(usage.trim()).append(")\n</pre>");
    }
    page.append("\n=== Usages ===\n");
    page.append(usageBuilder.toString());
    StringBuilder exampleBuilder = new StringBuilder();
    try {
        if (f.examples() != null && f.examples().length > 0) {
            int count = 1;
            // If the output was automatically generated, change the color of the pre
            for (ExampleScript es : f.examples()) {
                exampleBuilder.append("====Example ").append(count).append("====\n").append(HTMLUtils.escapeHTML(es.getDescription())).append("\n\n" + "Given the following code:\n");
                exampleBuilder.append(SimpleSyntaxHighlighter.Highlight(es.getScript(), true)).append("\n");
                String style = "";
                exampleBuilder.append("\n\nThe output ");
                if (es.isAutomatic()) {
                    style = " background-color: #BDC7E9;";
                    exampleBuilder.append("would");
                } else {
                    exampleBuilder.append("might");
                }
                exampleBuilder.append(" be:\n<pre class=\"pre\" style=\"border-top: 1px solid blue; border-bottom: 1px solid blue;").append(style).append("\"");
                exampleBuilder.append(">%%NOWIKI|").append(es.getOutput()).append("%%").append("</pre>\n");
                count++;
            }
        } else {
            exampleBuilder.append("Sorry, there are no examples for this function! :(\n");
        }
    } catch (ConfigCompileException | IOException | DataSourceException | URISyntaxException ex) {
        exampleBuilder.append("Error while compiling the examples for ").append(f.getName());
    }
    page.append("\n=== Examples ===\n");
    page.append(exampleBuilder.toString());
    Class<?>[] seeAlso = f.seeAlso();
    String seeAlsoText = "";
    if (seeAlso != null && seeAlso.length > 0) {
        seeAlsoText += "===See Also===\n";
        boolean first = true;
        for (Class<?> c : seeAlso) {
            if (!first) {
                seeAlsoText += ", ";
            }
            first = false;
            if (Function.class.isAssignableFrom(c)) {
                Function f2 = (Function) ReflectionUtils.newInstance(c);
                seeAlsoText += "<code>[[" + f2.getName() + "|" + f2.getName() + "]]</code>";
            } else if (Template.class.isAssignableFrom(c)) {
                Template t = (Template) ReflectionUtils.newInstance(c);
                seeAlsoText += "[[" + t.getName() + "|Learning Trail: " + t.getDisplayName() + "]]";
            } else {
                throw new Error("Unsupported class found in @seealso annotation: " + c.getName());
            }
        }
    }
    page.append(seeAlsoText);
    Class<?> container = f.getClass();
    while (container.getEnclosingClass() != null) {
        container = container.getEnclosingClass();
    }
    String bW = "<p id=\"edit_this_page\">" + EDIT_THIS_PAGE_PREAMBLE + String.format(githubBaseUrl, "java/" + container.getName().replace(".", "/")) + ".java" + EDIT_THIS_PAGE_POSTAMBLE + " (Note this page is automatically generated from the documentation in the source code.)</p>";
    page.append(bW);
    String description = "";
    writePage(f.getName(), page.toString(), "API/functions/" + f.getName(), Arrays.asList(new String[] { f.getName(), f.getName() + " api", f.getName() + " example", f.getName() + " description" }), description);
}
Also used : ArrayList(java.util.ArrayList) URISyntaxException(java.net.URISyntaxException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) Template(com.laytonsmith.tools.docgen.templates.Template) Function(com.laytonsmith.core.functions.Function) com.laytonsmith.annotations.typeof(com.laytonsmith.annotations.typeof) ExampleScript(com.laytonsmith.core.functions.ExampleScript) Optimizable(com.laytonsmith.core.Optimizable) IOException(java.io.IOException) DataSourceException(com.laytonsmith.persistence.DataSourceException)

Aggregations

ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)37 ParseTree (com.laytonsmith.core.ParseTree)16 CFunction (com.laytonsmith.core.constructs.CFunction)14 ArrayList (java.util.ArrayList)13 ConfigCompileGroupException (com.laytonsmith.core.exceptions.ConfigCompileGroupException)12 CString (com.laytonsmith.core.constructs.CString)11 Construct (com.laytonsmith.core.constructs.Construct)8 Token (com.laytonsmith.core.constructs.Token)8 IVariable (com.laytonsmith.core.constructs.IVariable)7 Target (com.laytonsmith.core.constructs.Target)6 GlobalEnv (com.laytonsmith.core.environments.GlobalEnv)6 Function (com.laytonsmith.core.functions.Function)6 Variable (com.laytonsmith.core.constructs.Variable)5 CommandHelperEnvironment (com.laytonsmith.core.environments.CommandHelperEnvironment)5 Environment (com.laytonsmith.core.environments.Environment)5 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)5 FunctionBase (com.laytonsmith.core.functions.FunctionBase)5 File (java.io.File)5 List (java.util.List)5 FunctionList (com.laytonsmith.core.functions.FunctionList)4