Search in sources :

Example 11 with CFunction

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

the class ForeachKeyword method process.

@Override
public int process(List<ParseTree> list, int keywordPosition) throws ConfigCompileException {
    ParseTree foreach = list.get(keywordPosition);
    Target t = foreach.getTarget();
    if (list.size() > keywordPosition + 1) {
        // This portion handles the initial code block, i.e. foreach(...){ }
        ParseTree codeBlock = list.get(keywordPosition + 1);
        if (isCodeBlock(codeBlock)) {
            validateCodeBlock(codeBlock, "");
            foreach.addChild(getArgumentOrNull(codeBlock));
            list.remove(keywordPosition + 1);
        }
    }
    if (list.size() > keywordPosition + 1) {
        // This part handles the else keyword, i.e. foreach(...){ } else { }
        ParseTree elseKeyword = list.get(keywordPosition + 1);
        // If it's not an else keyword, then we'll leave it alone, and be done.
        if (elseKeyword.getData() instanceof CKeyword && elseKeyword.getData().val().equals("else")) {
            list.remove(keywordPosition + 1);
            ParseTree codeBlock = list.get(keywordPosition + 1);
            if (isCodeBlock(codeBlock)) {
                validateCodeBlock(codeBlock, "");
                foreach.addChild(getArgumentOrNull(codeBlock));
            }
            // We also have to refactor this into a foreachelse, instead of a foreach.
            list.get(keywordPosition).setData(new CFunction(FOREACHELSE, t));
            list.remove(keywordPosition + 1);
        }
    }
    return keywordPosition;
}
Also used : Target(com.laytonsmith.core.constructs.Target) CFunction(com.laytonsmith.core.constructs.CFunction) CKeyword(com.laytonsmith.core.constructs.CKeyword) ParseTree(com.laytonsmith.core.ParseTree)

Example 12 with CFunction

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

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

the class DocGen method examples.

public static String examples(String function, boolean staged) throws Exception {
    FunctionBase fb = FunctionList.getFunction(new CFunction(function, Target.UNKNOWN));
    if (fb instanceof Function) {
        Function f = (Function) fb;
        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>";
        String optimizationMessage = "None";
        if (f instanceof Optimizable) {
            Set<Optimizable.OptimizationOption> options = ((Optimizable) f).optimizationOptions();
            List<String> list = new ArrayList<String>();
            for (Optimizable.OptimizationOption option : options) {
                list.add("[[CommandHelper/" + (staged ? "Staged/" : "") + "Optimizer#" + option.name() + "|" + option.name() + "]]");
            }
            optimizationMessage = StringUtils.Join(list, "<br />");
        }
        DocInfo di = new DocInfo(f.docs());
        StringBuilder thrown = new StringBuilder();
        if (f instanceof Function && ((Function) f).thrown() != null) {
            List 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 (i != 0) {
                    thrown.append("<br />\n");
                }
                thrown.append("[[CommandHelper/Exceptions#").append(t).append("|").append(t).append("]]");
            }
        }
        String tableUsages = di.originalArgs.replace("|", "<hr />");
        String[] usages = di.originalArgs.split("\\|");
        StringBuilder usageBuilder = new StringBuilder();
        for (String usage : usages) {
            usageBuilder.append("<pre>\n").append(f.getName()).append("(").append(usage.trim()).append(")\n</pre>");
        }
        StringBuilder exampleBuilder = new StringBuilder();
        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(es.getDescription()).append("\n\n" + "Given the following code:\n");
                exampleBuilder.append(SimpleSyntaxHighlighter.Highlight(es.getScript(), true)).append("\n");
                String style = "";
                if (es.isAutomatic()) {
                    style = " style=\"background-color: #BDC7E9\"";
                    exampleBuilder.append("\n\nThe output would be:\n<pre");
                } else {
                    exampleBuilder.append("\n\nThe output might be:\n<pre");
                }
                exampleBuilder.append(style).append(">").append(es.getOutput()).append("</pre>\n");
                count++;
            }
        } else {
            exampleBuilder.append("Sorry, there are no examples for this function! :(");
        }
        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) c.newInstance();
                    seeAlsoText += "<code>[[CommandHelper/" + (staged ? "Staged/" : "") + "API/" + f2.getName() + "|" + f2.getName() + "]]</code>";
                } else if (Template.class.isAssignableFrom(c)) {
                    Template t = (Template) c.newInstance();
                    seeAlsoText += "[[CommandHelper/" + (staged ? "Staged/" : "") + t.getName() + "|Learning Trail: " + t.getDisplayName() + "]]";
                } else {
                    throw new Error("Unsupported class found in @seealso annotation: " + c.getName());
                }
            }
        }
        Map<String, String> templateFields = new HashMap<>();
        templateFields.put("function_name", f.getName());
        templateFields.put("returns", di.ret);
        templateFields.put("tableUsages", tableUsages);
        templateFields.put("throws", thrown.toString());
        templateFields.put("since", f.since().toString());
        templateFields.put("restricted", restricted);
        templateFields.put("optimizationMessage", optimizationMessage);
        templateFields.put("description", di.extendedDesc == null ? di.desc : di.topDesc + "\n\n" + di.extendedDesc);
        templateFields.put("usages", usageBuilder.toString());
        templateFields.put("examples", exampleBuilder.toString());
        templateFields.put("staged", staged ? "Staged/" : "");
        templateFields.put("seeAlso", seeAlsoText);
        String template = StreamUtils.GetString(DocGenTemplates.class.getResourceAsStream("/templates/example_templates"));
        // Find all the %%templates%% in the template
        Matcher m = Pattern.compile("%%(.*?)%%").matcher(template);
        try {
            while (m.find()) {
                String name = m.group(1);
                String templateValue = templateFields.get(name);
                template = template.replaceAll("%%" + Pattern.quote(name) + "%%", templateValue.replace("$", "\\$").replaceAll("\\'", "\\\\'"));
            }
            return template;
        } catch (RuntimeException e) {
            throw new RuntimeException("Caught a runtime exception while generating template for " + function, e);
        }
    } else {
        throw new RuntimeException(function + " does not implement Function");
    }
}
Also used : FunctionBase(com.laytonsmith.core.functions.FunctionBase) HashMap(java.util.HashMap) Matcher(java.util.regex.Matcher) ArrayList(java.util.ArrayList) Template(com.laytonsmith.tools.docgen.templates.Template) CFunction(com.laytonsmith.core.constructs.CFunction) Function(com.laytonsmith.core.functions.Function) ArrayList(java.util.ArrayList) FunctionList(com.laytonsmith.core.functions.FunctionList) List(java.util.List) com.laytonsmith.annotations.typeof(com.laytonsmith.annotations.typeof) ExampleScript(com.laytonsmith.core.functions.ExampleScript) CFunction(com.laytonsmith.core.constructs.CFunction) Optimizable(com.laytonsmith.core.Optimizable)

Example 14 with CFunction

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

the class NewMethodScriptCompiler method compile.

/**
 * TODO: Need a platform resolver here?
 *
 * @param tokenStream
 * @param compilerEnvironment
 * @return
 * @throws ConfigCompileException
 */
public static ParseTree compile(TokenStream tokenStream, Environment compilerEnvironment) throws ConfigCompileException {
    ParseTree root = new ParseTree(new CFunction("__autoconcat__", Target.UNKNOWN), tokenStream.getFileOptions());
    new CompilerObject(tokenStream).compile(root, compilerEnvironment);
    link(root, compilerEnvironment);
    return root;
}
Also used : CFunction(com.laytonsmith.core.constructs.CFunction) ParseTree(com.laytonsmith.core.ParseTree)

Example 15 with CFunction

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

the class NewMethodScriptCompiler method link.

private static void link(ParseTree root, Environment compilerEnvirontment) throws ConfigCompileException {
    // Before we actually link, we need to optimize our branch functions, that is,
    // currently just if. However, at this point, we also need to optimize __autoconcat__.
    // so we know what the tree actually looks like. Also, we want to first group all our auto includes
    // together, along with our actual tree.
    ParseTree master = new ParseTree(new CFunction("__autoconcat__", Target.UNKNOWN), root.getFileOptions());
    for (ParseTree include : compilerEnvirontment.getEnv(CompilerEnvironment.class).getIncludes()) {
        master.addChild(include);
    }
    master.addChild(root);
    OptimizerObject optimizer = new OptimizerObject(root, compilerEnvirontment);
    optimizer.optimize();
// root is now optimized
}
Also used : CFunction(com.laytonsmith.core.constructs.CFunction) ParseTree(com.laytonsmith.core.ParseTree)

Aggregations

CFunction (com.laytonsmith.core.constructs.CFunction)22 ParseTree (com.laytonsmith.core.ParseTree)16 ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)13 CString (com.laytonsmith.core.constructs.CString)6 Construct (com.laytonsmith.core.constructs.Construct)6 IVariable (com.laytonsmith.core.constructs.IVariable)6 Target (com.laytonsmith.core.constructs.Target)5 CArray (com.laytonsmith.core.constructs.CArray)4 CKeyword (com.laytonsmith.core.constructs.CKeyword)4 CDouble (com.laytonsmith.core.constructs.CDouble)3 CInt (com.laytonsmith.core.constructs.CInt)3 Variable (com.laytonsmith.core.constructs.Variable)3 ConfigRuntimeException (com.laytonsmith.core.exceptions.ConfigRuntimeException)3 FunctionList (com.laytonsmith.core.functions.FunctionList)3 ArrayList (java.util.ArrayList)3 List (java.util.List)3 KeywordList (com.laytonsmith.core.compiler.KeywordList)2 CClassType (com.laytonsmith.core.constructs.CClassType)2 CLabel (com.laytonsmith.core.constructs.CLabel)2 CNull (com.laytonsmith.core.constructs.CNull)2