Search in sources :

Example 16 with ConfigCompileException

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

the class MethodScriptCompilerTest method testLex.

/**
 * Test of lex method, of class MethodScriptCompiler.
 */
@Test
public void testLex() throws Exception {
    String config = "/cmd = msg('string')";
    List<Token> e = new ArrayList<>();
    // This is the decomposed version of the above config
    e.add(new Token(Token.TType.COMMAND, "/cmd", Target.UNKNOWN));
    e.add(new Token(Token.TType.WHITESPACE, " ", Target.UNKNOWN));
    e.add(new Token(Token.TType.ALIAS_END, "=", Target.UNKNOWN));
    e.add(new Token(Token.TType.WHITESPACE, " ", Target.UNKNOWN));
    e.add(new Token(Token.TType.FUNC_NAME, "msg", Target.UNKNOWN));
    e.add(new Token(Token.TType.FUNC_START, "(", Target.UNKNOWN));
    e.add(new Token(Token.TType.STRING, "string", Target.UNKNOWN));
    e.add(new Token(Token.TType.FUNC_END, ")", Target.UNKNOWN));
    e.add(new Token(Token.TType.NEWLINE, "\n", Target.UNKNOWN));
    List<Token> result = MethodScriptCompiler.lex(config, null, false);
    assertEquals(e, result);
    String[] badConfigs = { // Bad escape sequences
    "'\\q'", "'\\m'" };
    for (String c : badConfigs) {
        try {
            MethodScriptCompiler.lex(c, null, false);
            // Shouldn't get here
            fail(c + " should not have lexed, but did.");
        } catch (ConfigCompileException ex) {
        // Success!
        }
    }
}
Also used : ArrayList(java.util.ArrayList) Token(com.laytonsmith.core.constructs.Token) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) Test(org.junit.Test) StaticTest(com.laytonsmith.testing.StaticTest)

Example 17 with ConfigCompileException

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

the class DocGen method functions.

/**
 * Returns the documentation for a single function.
 *
 * @param type The type of output to use. May be one of: html, wiki, text
 * @param platform The platform we're using
 * @param staged Is this for the staged wiki?
 * @return
 * @throws ConfigCompileException
 */
@SuppressWarnings("StringConcatenationInsideStringBufferAppend")
public static String functions(MarkupType type, api.Platforms platform, boolean staged) throws ConfigCompileException {
    Set<FunctionBase> functions = FunctionList.getFunctionList(platform);
    HashMap<Class, ArrayList<FunctionBase>> functionlist = new HashMap<Class, ArrayList<FunctionBase>>();
    StringBuilder out = new StringBuilder();
    for (FunctionBase f : functions) {
        // Sort the functions into classes
        Class apiClass = (f.getClass().getEnclosingClass() != null ? f.getClass().getEnclosingClass() : null);
        ArrayList<FunctionBase> fl = functionlist.get(apiClass);
        if (fl == null) {
            fl = new ArrayList<FunctionBase>();
            functionlist.put(apiClass, fl);
        }
        fl.add(f);
    }
    if (type == MarkupType.HTML) {
        out.append("Command Helper uses a language called MethodScript, which greatly extend the capabilities of the plugin, " + "and make the plugin a fully " + "<a href=\"http://en.wikipedia.org/wiki/Turing_Complete\">Turing Complete</a> language. " + "There are several functions defined, and they are grouped into \"classes\". \n");
    } else if (type == MarkupType.WIKI) {
        out.append("Command Helper uses a language called MethodScript, which greatly extend the capabilities of the plugin, " + "and make the plugin a fully " + "[http://en.wikipedia.org/wiki/Turing_Complete Turing Complete] language. " + "There are several functions defined, and they are grouped into \"classes\". \n");
        out.append("<p>Each function has its own page for documentation, where you can view examples for how to use a" + " particular function.\n");
    } else if (type == MarkupType.TEXT) {
        out.append("Command Helper uses a language called MethodScript, which greatly extend the capabilities of the plugin, " + "and make the plugin a fully " + "Turing Complete language [http://en.wikipedia.org/wiki/Turing_Complete].\n" + "There are several functions defined, and they are grouped into \"classes\".\n");
    }
    List<Map.Entry<Class, ArrayList<FunctionBase>>> entrySet = new ArrayList<Map.Entry<Class, ArrayList<FunctionBase>>>(functionlist.entrySet());
    Collections.sort(entrySet, new Comparator<Map.Entry<Class, ArrayList<FunctionBase>>>() {

        @Override
        public int compare(Map.Entry<Class, ArrayList<FunctionBase>> o1, Map.Entry<Class, ArrayList<FunctionBase>> o2) {
            return o1.getKey().getName().compareTo(o2.getKey().getName());
        }
    });
    int total = 0;
    int workingExamples = 0;
    for (Map.Entry<Class, ArrayList<FunctionBase>> entry : entrySet) {
        Class apiClass = entry.getKey();
        String className = apiClass.getName().split("\\.")[apiClass.getName().split("\\.").length - 1];
        if (className.equals("Sandbox")) {
            // Skip Sandbox functions
            continue;
        }
        String classDocs = null;
        try {
            Method m = apiClass.getMethod("docs", (Class[]) null);
            Object o = null;
            if ((m.getModifiers() & Modifier.STATIC) == 0) {
                try {
                    o = apiClass.newInstance();
                } catch (InstantiationException ex) {
                }
            }
            classDocs = (String) m.invoke(o, (Object[]) null);
        } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException | NoSuchMethodException ex) {
        } catch (Exception e) {
            e.printStackTrace(StreamUtils.GetSystemErr());
            StreamUtils.GetSystemErr().println("Continuing however.");
        }
        StringBuilder intro = new StringBuilder();
        if (type == MarkupType.HTML) {
            if (className != null) {
                intro.append("<h1>").append(className).append("</h1>" + "\n");
                intro.append(classDocs == null ? "" : classDocs).append("\n");
            } else {
                intro.append("<h1>Other Functions</h1>" + "\n");
            }
            intro.append("<table>" + "\n");
        } else if (type == MarkupType.WIKI) {
            if (className != null) {
                intro.append("===").append(className).append("===" + "\n");
                intro.append(classDocs == null ? "" : classDocs).append("\n");
            } else {
                intro.append("===Other Functions===" + "\n");
            }
            intro.append("{| width=\"100%\" cellspacing=\"1\" cellpadding=\"1\" border=\"1\" class=\"wikitable\"\n" + "|-\n" + "! scope=\"col\" width=\"6%\" | Function Name\n" + "! scope=\"col\" width=\"5%\" | Returns\n" + "! scope=\"col\" width=\"10%\" | Arguments\n" + "! scope=\"col\" width=\"10%\" | Throws\n" + "! scope=\"col\" width=\"61%\" | Description\n" + "! scope=\"col\" width=\"3%\" | Since\n" + "! scope=\"col\" width=\"5%\" | Restricted" + "\n");
        } else if (type == MarkupType.TEXT) {
            intro.append("\n").append(className).append("\n");
            intro.append("**********************************************************************************************" + "\n");
            if (className != null) {
                intro.append(classDocs == null ? "" : classDocs).append("\n");
            } else {
                intro.append("Other Functions" + "\n");
            }
            intro.append("**********************************************************************************************" + "\n");
        }
        List<FunctionBase> documentableFunctions = new ArrayList<FunctionBase>();
        for (FunctionBase f : entry.getValue()) {
            if (f.appearInDocumentation()) {
                documentableFunctions.add(f);
            }
        }
        if (!documentableFunctions.isEmpty()) {
            out.append(intro.toString() + "\n");
        }
        Collections.sort(documentableFunctions, new Comparator<FunctionBase>() {

            @Override
            public int compare(FunctionBase o1, FunctionBase o2) {
                return o1.getName().compareTo(o2.getName());
            }
        });
        for (FunctionBase f : documentableFunctions) {
            total++;
            String doc = f.docs();
            String restricted = (f instanceof Function && ((Function) f).isRestricted()) ? "<div style=\"background-color: red; font-weight: bold; text-align: center;\">Yes</div>" : "<div style=\"background-color: green; font-weight: bold; text-align: center;\">No</div>";
            StringBuilder thrown = new StringBuilder();
            if (f instanceof Function && ((Function) f).thrown() != null) {
                List<Class<? extends CREThrowable>> thrownList = Arrays.asList(((Function) f).thrown());
                for (int i = 0; i < thrownList.size(); i++) {
                    String t = ((Class<? extends CREThrowable>) thrownList.get(i)).getAnnotation(typeof.class).value();
                    if (type == MarkupType.HTML || type == MarkupType.TEXT) {
                        if (i != 0) {
                            thrown.append((type == MarkupType.HTML ? "<br />\n" : " | "));
                        }
                        thrown.append(t);
                    } else {
                        if (i != 0) {
                            thrown.append("<br />\n");
                        }
                        thrown.append("[[CommandHelper/Exceptions#").append(t).append("|").append(t).append("]]");
                    }
                }
            }
            String since = (f instanceof Documentation ? ((Documentation) f).since().toString() : "0.0.0");
            DocInfo di = new DocInfo(doc);
            boolean hasExample = false;
            if (f instanceof Function && ((Function) f).examples() != null && ((Function) f).examples().length > 0) {
                hasExample = true;
                workingExamples++;
            }
            if (di.ret == null || di.args == null || di.desc == null) {
                out.append(f.getName() + "'s documentation is not correctly formatted. Please check it and try again.\n");
            }
            if (type == MarkupType.HTML) {
                out.append("<tr><td>" + di.ret + "</td><td>" + di.args + "</td><td>" + thrown.toString() + "</td><td>" + di.desc + "</td><td>" + since + "</td><td>" + restricted + "</td></tr>\n");
            } else if (type == MarkupType.WIKI) {
                // Turn args into a prettified version
                out.append("|- id=\"" + f.getName() + "\"\n" + "! scope=\"row\" | [[CommandHelper/" + (staged ? "Staged/" : "") + "API/" + f.getName() + "|" + f.getName() + "]]()\n" + "| " + di.ret + "\n" + "| " + di.args + "\n" + "| " + thrown.toString() + "\n" + "| " + (di.topDesc != null ? di.topDesc + " [[CommandHelper/" + (staged ? "Staged/" : "") + "API/" + f.getName() + "#Description|See More...]]" : di.desc) + (hasExample ? "<br />([[CommandHelper/" + (staged ? "Staged/" : "") + "API/" + f.getName() + "#Examples|Examples...]])" : "") + "\n" + "| " + since + "\n" + "| " + restricted + "\n");
            } else if (type == MarkupType.TEXT) {
                out.append(di.ret + " " + f.getName() + "(" + di.args + ")" + " {" + thrown.toString() + "}\n\t" + di.desc + "\n\t" + since + ((f instanceof Function ? ((Function) f).isRestricted() : false) ? "\n\tThis function is restricted" : "\n\tThis function is not restricted\n"));
            }
        }
        if (!documentableFunctions.isEmpty()) {
            if (type == MarkupType.HTML) {
                out.append("</table>\n");
            } else if (type == MarkupType.WIKI) {
                out.append("|}\n{{Back to top}}\n");
            } else if (type == MarkupType.TEXT) {
                out.append("\n");
            }
        }
    }
    if (type == MarkupType.HTML) {
        out.append("" + "<h2>Errors in documentation</h2>\n" + "<em>Please note that this documentation is generated automatically," + " if you notice an error in the documentation, please file a bug report for the" + " plugin itself!</em>" + "<div style='text-size:small; text-decoration:italics; color:grey'>There are " + total + " functions in this API page</div>\n");
    } else if (type == MarkupType.WIKI) {
        out.append("" + "===Errors in documentation===\n" + "''Please note that this documentation is generated automatically," + " if you notice an error in the documentation, please file a bug report for the" + " plugin itself!'' For information on undocumented functions, see [[CommandHelper/Sandbox|this page]]" + "<div style='font-size:xx-small; font-style:italic; color:grey'>There are " + total + " functions in this API page, " + workingExamples + " of which" + " have examples.</div>\n\n{{Back to top}}\n{{LearningTrail}}\n");
    }
    return out.toString();
}
Also used : FunctionBase(com.laytonsmith.core.functions.FunctionBase) HashMap(java.util.HashMap) ArrayList(java.util.ArrayList) CREThrowable(com.laytonsmith.core.exceptions.CRE.CREThrowable) CFunction(com.laytonsmith.core.constructs.CFunction) Function(com.laytonsmith.core.functions.Function) com.laytonsmith.annotations.typeof(com.laytonsmith.annotations.typeof) Documentation(com.laytonsmith.core.Documentation) Method(java.lang.reflect.Method) InvocationTargetException(java.lang.reflect.InvocationTargetException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) InvocationTargetException(java.lang.reflect.InvocationTargetException) HashMap(java.util.HashMap) Map(java.util.Map)

Example 18 with ConfigCompileException

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

the class SingleFunctionDialog method uploadButtonActionPerformed.

// </editor-fold>//GEN-END:initComponents
private void uploadButtonActionPerformed(java.awt.event.ActionEvent evt) {
    // GEN-FIRST:event_uploadButtonActionPerformed
    Function f;
    try {
        f = (Function) FunctionList.getFunction(functionNameField.getText(), Target.UNKNOWN);
        if (!f.appearInDocumentation()) {
            statusLabel.setText("That function is not configured to have documentation.");
            return;
        }
        try {
            String docs = DocGen.examples(f.getName(), parent.handler.isStaged);
            parent.handler.doUpload(docs, "/API/" + f.getName(), true);
        } catch (Exception ex) {
            statusLabel.setText(ex.getMessage());
            ex.printStackTrace(StreamUtils.GetSystemErr());
        }
    } catch (ConfigCompileException ex) {
        statusLabel.setText("That function doesn't exist.");
        return;
    }
}
Also used : Function(com.laytonsmith.core.functions.Function) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException)

Example 19 with ConfigCompileException

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

the class Interpreter method doStartup.

private void doStartup() throws IOException, DataSourceException, URISyntaxException, Profiles.InvalidProfileException {
    Installer.Install(MethodScriptFileLocations.getDefault().getConfigDirectory());
    Installer.InstallCmdlineInterpreter();
    env = Static.GenerateStandaloneEnvironment(false);
    env.getEnv(GlobalEnv.class).SetCustom("cmdline", true);
    if (Prefs.UseColors()) {
        TermColors.EnableColors();
    } else {
        TermColors.DisableColors();
    }
    String auto_include = FileUtil.read(MethodScriptFileLocations.getDefault().getCmdlineInterpreterAutoIncludeFile());
    try {
        MethodScriptCompiler.execute(auto_include, MethodScriptFileLocations.getDefault().getCmdlineInterpreterAutoIncludeFile(), true, env, null, null, null);
    } catch (ConfigCompileException ex) {
        ConfigRuntimeException.HandleUncaughtException(ex, "Interpreter will continue to run, however.", null);
    } catch (ConfigCompileGroupException ex) {
        ConfigRuntimeException.HandleUncaughtException(ex, null);
    }
    // Install our signal handlers.
    SignalHandler.SignalCallback signalHandler = new SignalHandler.SignalCallback() {

        @Override
        public boolean handle(SignalType type) {
            if (isExecuting) {
                env.getEnv(GlobalEnv.class).SetInterrupt(true);
                if (scriptThread != null) {
                    scriptThread.interrupt();
                }
                for (Thread t : env.getEnv(GlobalEnv.class).GetDaemonManager().getActiveThreads()) {
                    t.interrupt();
                }
            } else {
                ctrlCcount++;
                if (ctrlCcount > MAX_CTRL_C_MASHES) {
                    // Ok, ok, we get the hint.
                    StreamUtils.GetSystemOut().println();
                    StreamUtils.GetSystemOut().flush();
                    // Standard Ctrl+C exit code
                    System.exit(130);
                }
                pl(YELLOW + "\nUse exit() to exit the shell." + reset());
                p(getPrompt());
            }
            return true;
        }
    };
    try {
        SignalHandler.addHandler(Signals.SIGTERM, signalHandler);
    } catch (IllegalArgumentException ex) {
    // Oh well.
    }
    try {
        SignalHandler.addHandler(Signals.SIGINT, signalHandler);
    } catch (IllegalArgumentException ex) {
    // Oh well again.
    }
}
Also used : SignalType(com.laytonsmith.PureUtilities.SignalType) SignalHandler(com.laytonsmith.PureUtilities.SignalHandler) GlobalEnv(com.laytonsmith.core.environments.GlobalEnv) CString(com.laytonsmith.core.constructs.CString) ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException)

Example 20 with ConfigCompileException

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

the class Interpreter method startWithTTY.

public static void startWithTTY(String file, List<String> args, boolean systemExitOnFailure) throws IOException, DataSourceException, URISyntaxException, Profiles.InvalidProfileException {
    File fromFile = new File(file).getCanonicalFile();
    Interpreter interpreter = new Interpreter(args, fromFile.getParentFile().getPath(), true);
    try {
        interpreter.execute(FileUtil.read(fromFile), args, fromFile);
    } catch (ConfigCompileException ex) {
        ConfigRuntimeException.HandleUncaughtException(ex, null, null);
        StreamUtils.GetSystemOut().println(TermColors.reset());
        if (systemExitOnFailure) {
            System.exit(1);
        }
    } catch (ConfigCompileGroupException ex) {
        ConfigRuntimeException.HandleUncaughtException(ex, null);
        StreamUtils.GetSystemOut().println(TermColors.reset());
        if (systemExitOnFailure) {
            System.exit(1);
        }
    }
}
Also used : ConfigCompileGroupException(com.laytonsmith.core.exceptions.ConfigCompileGroupException) File(java.io.File) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException)

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