Search in sources :

Example 1 with Documentation

use of com.laytonsmith.core.Documentation 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 2 with Documentation

use of com.laytonsmith.core.Documentation in project CommandHelper by EngineHub.

the class SyntaxHighlighters method GetEvents.

private static List<Documentation> GetEvents() {
    List<Documentation> l = new ArrayList<>();
    Set<Class<?>> classes = ClassDiscovery.getDefaultInstance().loadClassesWithAnnotation(api.class);
    for (Class<?> c : classes) {
        if (Event.class.isAssignableFrom(c) && Documentation.class.isAssignableFrom(c)) {
            try {
                Constructor<?> m = c.getConstructor();
                Documentation e = (Documentation) m.newInstance();
                l.add(e);
            } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
                StreamUtils.GetSystemErr().println(ex.getMessage());
            }
        }
    }
    return l;
}
Also used : Documentation(com.laytonsmith.core.Documentation) ArrayList(java.util.ArrayList) InvocationTargetException(java.lang.reflect.InvocationTargetException) Event(com.laytonsmith.core.events.Event)

Example 3 with Documentation

use of com.laytonsmith.core.Documentation in project CommandHelper by EngineHub.

the class SyntaxHighlighters method macro.

private static String macro(String macroName) {
    String[] split = macroName.split(":");
    String type = split[0];
    String datalist = split[1];
    List<String> params = new ArrayList<>();
    for (int i = 2; i < split.length; i++) {
        params.add(split[i].toLowerCase());
    }
    List<String> base = new ArrayList<>();
    if (datalist.equalsIgnoreCase("colors")) {
        for (MCChatColor c : MCChatColor.values()) {
            base.add(c.name());
        }
    } else if (datalist.equalsIgnoreCase("keywords")) {
        for (String keyword : SimpleSyntaxHighlighter.KEYWORDS) {
            base.add(keyword);
        }
    } else if (datalist.equalsIgnoreCase("functions")) {
        for (Function f : GetFunctions()) {
            if (SimpleSyntaxHighlighter.KEYWORDS.contains(f.getName())) {
                // Keywords override functions
                continue;
            }
            if (!f.appearInDocumentation()) {
                continue;
            }
            if (params.contains("restricted") || params.contains("unrestricted")) {
                if (params.contains("restricted") && f.isRestricted()) {
                    base.add(f.getName());
                } else if (params.contains("unrestricted") && !f.isRestricted()) {
                    base.add(f.getName());
                }
            } else {
                base.add(f.getName());
            }
        }
    } else if (datalist.equalsIgnoreCase("events")) {
        for (Documentation d : GetEvents()) {
            base.add(d.getName());
        }
    } else if (datalist.equalsIgnoreCase("exceptions")) {
        for (Class<? extends CREThrowable> c : ClassDiscovery.getDefaultInstance().loadClassesWithAnnotationThatExtend(typeof.class, CREThrowable.class)) {
            base.add(c.getAnnotation(typeof.class).value());
        }
    } else if (datalist.equalsIgnoreCase("types")) {
        base.addAll(NativeTypeList.getNativeTypeList());
        // Null is technically in the list, but it shouldn't be added.
        base.remove("null");
    } else if (datalist.equalsIgnoreCase("enums")) {
        Set<String> set = new HashSet<>();
        Set<Class<? extends Enum>> enums = ClassDiscovery.getDefaultInstance().loadClassesWithAnnotationThatExtend(MEnum.class, Enum.class);
        for (Class<? extends Enum> e : enums) {
            Enum[] es = e.getEnumConstants();
            for (Enum ee : es) {
                set.add(ee.name());
            }
        }
        base.addAll(set);
    } else if (datalist.equalsIgnoreCase("fileOptions")) {
        for (Field f : FileOptions.class.getDeclaredFields()) {
            base.add(f.getName());
        }
    }
    String header = "";
    String spliter = "IMPROPER FORMATTING";
    String footer = "";
    if (type.equalsIgnoreCase("space")) {
        if (params.contains("quoted")) {
            header = "'";
            spliter = "' '";
            footer = "'";
        } else {
            spliter = " ";
        }
    } else if (type.equalsIgnoreCase("comma")) {
        if (params.contains("quoted")) {
            header = "'";
            spliter = "', '";
            footer = "'";
        } else {
            spliter = ", ";
        }
    } else if (type.equalsIgnoreCase("pipe")) {
        if (params.contains("quoted")) {
            header = "'";
            spliter = "|";
            footer = "'";
        } else {
            spliter = "|";
        }
    } else if (type.equalsIgnoreCase("xml")) {
        String tag = "PLEASE INCLUDE THE TAG NAME USING tag=tagname AS A PARAMETER";
        for (String param : params) {
            // Find the tag name
            if (param.matches("tag=.*")) {
                tag = param.substring(4);
                break;
            }
        }
        if (params.contains("quoted")) {
            header = "<" + tag + ">'";
            spliter = "'</" + tag + "><" + tag + ">'";
            footer = "'</" + tag + ">";
        } else {
            header = "<" + tag + ">";
            spliter = "</" + tag + "><" + tag + ">";
            footer = "</" + tag + ">";
        }
    }
    return header + Join(base, spliter) + footer;
}
Also used : MEnum(com.laytonsmith.annotations.MEnum) Documentation(com.laytonsmith.core.Documentation) ArrayList(java.util.ArrayList) MCChatColor(com.laytonsmith.abstraction.enums.MCChatColor) Function(com.laytonsmith.core.functions.Function) Field(java.lang.reflect.Field) FileOptions(com.laytonsmith.core.compiler.FileOptions) HashSet(java.util.HashSet)

Example 4 with Documentation

use of com.laytonsmith.core.Documentation in project CommandHelper by EngineHub.

the class DocGen method events.

public static String events(MarkupType type) {
    Set<Class<?>> classes = ClassDiscovery.getDefaultInstance().loadClassesWithAnnotation(api.class);
    Set<Documentation> list = new TreeSet<Documentation>();
    for (Class<?> c : classes) {
        if (Event.class.isAssignableFrom(c) && Documentation.class.isAssignableFrom(c)) {
            try {
                // First, we have to instatiate the event.
                Constructor<Event> cons = (Constructor<Event>) c.getConstructor();
                Documentation docs = cons.newInstance();
                list.add(docs);
            } catch (Exception ex) {
                StreamUtils.GetSystemErr().println("Could not get documentation for " + c.getSimpleName());
            }
        }
    }
    StringBuilder doc = new StringBuilder();
    if (type == MarkupType.HTML) {
        doc.append("Events allow you to trigger scripts not just on commands, but also on other actions, such as" + " a player logging in, or a player breaking a block. See the documentation on events for" + " more information" + "<table><thead><tr><th>Name</th><th>Description</th><th>Prefilters</th>" + "<th>Event Data</th><th>Mutable Fields</th><th>Since</th></thead><tbody>");
    } else if (type == MarkupType.WIKI) {
        doc.append("Events allow you to trigger scripts not just on commands, but also on other actions, such as" + " a player logging in, or a player breaking a block. See the [[CommandHelper/Events|documentation on events]] for" + " more information<br />\n\n");
        doc.append("{| width=\"100%\" cellspacing=\"1\" cellpadding=\"1\" border=\"1\" class=\"wikitable\"\n" + "|-\n" + "! scope=\"col\" width=\"7%\" | Event Name\n" + "! scope=\"col\" width=\"36%\" | Description\n" + "! scope=\"col\" width=\"18%\" | Prefilters\n" + "! scope=\"col\" width=\"18%\" | Event Data\n" + "! scope=\"col\" width=\"18%\" | Mutable Fields\n" + "! scope=\"col\" width=\"3%\" | Since\n");
    } else if (type == MarkupType.TEXT) {
        doc.append("Events allow you to trigger scripts not just on commands, but also on other actions, such as" + " a player logging in, or a player breaking a block. See the documentation on events for" + " more information\n\n\n");
    }
    Pattern p = Pattern.compile("\\{(.*?)\\} *?(.*?) *?\\{(.*?)\\} *?\\{(.*?)\\}");
    for (Documentation d : list) {
        Matcher m = p.matcher(d.docs());
        if (m.find()) {
            String name = d.getName();
            String description = m.group(2).trim();
            String prefilter = PrefilterData.Get(m.group(1).split("\\|"), type);
            String eventData = EventData.Get(m.group(3).split("\\|"), type);
            String mutability = MutabilityData.Get(m.group(4).split("\\|"), type);
            // String manualTrigger = ManualTriggerData.Get(m.group(5).split("\\|"), type);
            String since = d.since().toString();
            if (type == MarkupType.HTML) {
                doc.append("<tr><td style=\"vertical-align:top\">").append(name).append("</td><td style=\"vertical-align:top\">").append(description).append("</td><td style=\"vertical-align:top\">").append(prefilter).append("</td><td style=\"vertical-align:top\">").append(eventData).append("</td><td style=\"vertical-align:top\">").append(mutability).append("</td><td style=\"vertical-align:top\">").append(since).append("</td></tr>\n");
            } else if (type == MarkupType.WIKI) {
                doc.append("|-\n" + "! scope=\"row\" | [[CommandHelper/Event API/").append(name).append("|").append(name).append("]]\n" + "| ").append(description).append("\n" + "| ").append(prefilter).append("\n" + "| ").append(eventData).append("\n" + "| ").append(mutability).append("\n" + "| ").append(since).append("\n");
            } else if (type == MarkupType.TEXT) {
                doc.append("Name: ").append(name).append("\nDescription: ").append(description).append("\nPrefilters:\n").append(prefilter).append("\nEvent Data:\n").append(eventData).append("\nMutable Fields:\n").append(mutability).append("\nSince: ").append(since).append("\n\n");
            }
        }
    }
    if (type == MarkupType.HTML) {
        doc.append("</tbody></table>\n");
    } else if (type == MarkupType.WIKI) {
        doc.append("|}\n");
    }
    if (type == MarkupType.HTML) {
        doc.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>\n");
    } else if (type == MarkupType.WIKI) {
        doc.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]]\n\n{{LearningTrail}}\n");
    }
    return doc.toString();
}
Also used : Pattern(java.util.regex.Pattern) Matcher(java.util.regex.Matcher) Constructor(java.lang.reflect.Constructor) Documentation(com.laytonsmith.core.Documentation) ConfigCompileException(com.laytonsmith.core.exceptions.ConfigCompileException) InvocationTargetException(java.lang.reflect.InvocationTargetException) TreeSet(java.util.TreeSet) Event(com.laytonsmith.core.events.Event)

Aggregations

Documentation (com.laytonsmith.core.Documentation)4 InvocationTargetException (java.lang.reflect.InvocationTargetException)3 ArrayList (java.util.ArrayList)3 Event (com.laytonsmith.core.events.Event)2 ConfigCompileException (com.laytonsmith.core.exceptions.ConfigCompileException)2 Function (com.laytonsmith.core.functions.Function)2 MCChatColor (com.laytonsmith.abstraction.enums.MCChatColor)1 MEnum (com.laytonsmith.annotations.MEnum)1 com.laytonsmith.annotations.typeof (com.laytonsmith.annotations.typeof)1 FileOptions (com.laytonsmith.core.compiler.FileOptions)1 CFunction (com.laytonsmith.core.constructs.CFunction)1 CREThrowable (com.laytonsmith.core.exceptions.CRE.CREThrowable)1 FunctionBase (com.laytonsmith.core.functions.FunctionBase)1 Constructor (java.lang.reflect.Constructor)1 Field (java.lang.reflect.Field)1 Method (java.lang.reflect.Method)1 HashMap (java.util.HashMap)1 HashSet (java.util.HashSet)1 Map (java.util.Map)1 TreeSet (java.util.TreeSet)1