diff options
Diffstat (limited to 'RGens/src')
16 files changed, 384 insertions, 412 deletions
diff --git a/RGens/src/main/java/bjc/rgens/.DS_Store b/RGens/src/main/java/bjc/rgens/.DS_Store Binary files differdeleted file mode 100644 index 918453d..0000000 --- a/RGens/src/main/java/bjc/rgens/.DS_Store +++ /dev/null diff --git a/RGens/src/main/java/bjc/rgens/ZadronsPouch.java b/RGens/src/main/java/bjc/rgens/ZadronsPouch.java index 5634385..827d022 100644 --- a/RGens/src/main/java/bjc/rgens/ZadronsPouch.java +++ b/RGens/src/main/java/bjc/rgens/ZadronsPouch.java @@ -9,14 +9,13 @@ import bjc.utils.gen.RandomGrammar; * Example showing code manipulate of random grammars * * @author ben - * */ public class ZadronsPouch { /** * Main method for running application * * @param args - * Unused CLI args + * Unused CLI args */ public static void main(String[] args) { ZadronsPouch zp = new ZadronsPouch(); @@ -34,16 +33,18 @@ public class ZadronsPouch { private RandomGrammar<String> grammar; - /** - * Create a new instance with a grammar - */ + /** Create a new instance with a grammar */ public ZadronsPouch() { grammar = new RandomGrammar<>(); + /* + * @NOTE + * Should there be some sort of builder sort of interface? + */ addRule("[item]", - "[egg]", "[glove]", "[crys-sphere]", "[rock]", - "[figurine]", "[vial]", "[mini-weapon]", "[bag]", - "[card]", "[rope]", "[box]", "[wand]"); + "[egg]", "[glove]", "[crys-sphere]", "[rock]", + "[figurine]", "[vial]", "[mini-weapon]", "[bag]", + "[card]", "[rope]", "[box]", "[wand]"); addEggRules(); addGloveRules(); @@ -65,7 +66,7 @@ public class ZadronsPouch { addRule("[bag]", "bag of [bag-type]", "[sack-type] sack", "[purse-type] purse"); addRule("[bag-type]", - "holding", "tricks", "useful items", + "holding", "tricks", "useful items", "devouring", "dwarf-kind", "invisible cloth", "monster summoning"); addRule("[sack-type]", @@ -78,22 +79,22 @@ public class ZadronsPouch { addRule("[box]", "[box-type] box", "cube of [box-type]"); addRule("[box-type]", - "limited-force", "frost-resisting", "morphing", - "self-destructing", "pandora", "panicking"); + "limited-force", "frost-resisting", "morphing", + "self-destructing", "pandora", "panicking"); } private void addCardRules() { addRule("[card]", "card of [card-type]", "[card-type] card"); addRule("[card-type]", - "fate", "teleporting", "elusive treasure", "spell-storing", - "many-things", "imprisoning", "messaging", "bounty"); + "fate", "teleporting", "elusive treasure", "spell-storing", + "many-things", "imprisoning", "messaging", "bounty"); } private void addCrysSphereRules() { addRule("[crys-sphere]", - "[sphere-type] spheres", "[sphere-type] sphere", - "lens of [lens-type]", "[crystal-type] crystal", + "[sphere-type] spheres", "[sphere-type] sphere", + "lens of [lens-type]", "[crystal-type] crystal", "crystal of [crystal-type]", "crystal ball", "crystal ball of [crys-suffix]"); addRule("[sphere-type]", @@ -110,18 +111,18 @@ public class ZadronsPouch { addRule("[egg]", "[egg-type] egg"); addRule("[egg-type]", - "copper", "stone", "golden", - "white", "white/pink", "glass"); + "copper", "stone", "golden", + "white", "white/pink", "glass"); } private void addFigurineRules() { addRule("[figurine]", "[fig-material] [fig-animal]"); addRule("[fig-material]", - "golden", "onyx", "serpentine", "ivory", - "marble", "bronze", "jade", "limestone"); + "golden", "onyx", "serpentine", "ivory", + "marble", "bronze", "jade", "limestone"); addRule("[fig-animal]", - "lion", "dog", "owl", "goat", + "lion", "dog", "owl", "goat", "elephant", "warrior", "palace", "leprechaun"); } @@ -139,11 +140,11 @@ public class ZadronsPouch { private void addMiniWeaponRules() { addRule("[mini-weapon]", "minature [weapon-type]", "small [weapon-type]", - "tiny [weapon-type]", "[sling-type] sling", + "tiny [weapon-type]", "[sling-type] sling", "[weapon-type]"); addRule("[weapon-type]", - "boomerang", "arrow", "net", - "catapult", "hammer", "sword", "club"); + "boomerang", "arrow", "net", + "catapult", "hammer", "sword", "club"); addRule("[sling-type]", "seeking"); } @@ -151,12 +152,12 @@ public class ZadronsPouch { private void addRockRules() { addRule("[rock]", "[pebble-type] pebble", "stone of [stone-type]", - "[stone-type] stone", "brick of [brick-type]", + "[stone-type] stone", "brick of [brick-type]", "[geode-type] geode"); addRule("[pebble-type]", "inscribed", "elemental control"); addRule("[stone-type]", - "good-luck", "weight", + "good-luck", "weight", "blind-defense", "metal-clinging"); addRule("[brick-type]", "flying"); @@ -169,8 +170,8 @@ public class ZadronsPouch { "[rope-type] rope", "rope of [rope-type]", "ball of [string-type] [string-kind]"); addRule("[rope-type]", - "trick", "entangling", "climbing", "dancing", - "tripping", "snaring", "levitating", "self-entangling"); + "trick", "entangling", "climbing", "dancing", + "tripping", "snaring", "levitating", "self-entangling"); addRule("[string-type]", "endless"); addRule("[string-kind]", @@ -189,10 +190,10 @@ public class ZadronsPouch { private void addVialRules() { addRule("[vial]", - "vial of [vial-type]", "[vial-type] vial", + "vial of [vial-type]", "[vial-type] vial", "[bottle-type] bottle", "[flask-type] flask"); addRule("[vial-type]", - "holding", "trapping", + "holding", "trapping", "experience", "unnatural regeneration"); addRule("[bottle-type]", "ever-smoking", "wheezing", @@ -206,10 +207,10 @@ public class ZadronsPouch { "[wand-type] wand", "wand of [wand-type]", "canceling [wand-type] wand"); addRule("[wand-type]", - "magic missile", "[spell-1]", "[spell-2]", - "gusting", "life-detecting", "zadron"); + "magic missile", "[spell-1]", "[spell-2]", + "gusting", "life-detecting", "zadron"); addRule("[spell-1]", - "frost", "fire", "lightning", "fear", + "frost", "fire", "lightning", "fear", "illumination", "polymorphing", "conjuration", "paralyzing"); addRule("[spell-2]", "[spell2-type] detecting"); diff --git a/RGens/src/main/java/bjc/rgens/newparser/CaseElement.java b/RGens/src/main/java/bjc/rgens/newparser/CaseElement.java index 210686e..30b0172 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/CaseElement.java +++ b/RGens/src/main/java/bjc/rgens/newparser/CaseElement.java @@ -2,6 +2,10 @@ package bjc.rgens.newparser; import static bjc.rgens.newparser.CaseElement.ElementType.*; +/* + * @TODO 10/11/17 Ben Culkin :CaseElementSplit + * Split this into multiple subclasses based off of a value of ElementType. + */ /** * A element in a rule case. * @@ -12,24 +16,15 @@ public class CaseElement { * The possible types of an element. * * @author EVE - * */ public static enum ElementType { - /** - * An element that represents a literal string. - */ + /** An element that represents a literal string. */ LITERAL, - /** - * An element that represents a rule reference. - */ + /** An element that represents a rule reference. */ RULEREF, - /** - * An element that represents a random range. - */ + /** An element that represents a random range. */ RANGE, - /** - * An element that represents a variable that stores a string. - */ + /** An element that represents a variable that stores a string. */ VARDEF, /** * An element that represents a variable that stores the result @@ -38,16 +33,12 @@ public class CaseElement { EXPVARDEF; } - /* - * Regexps for marking rule types. - */ - private static final String SPECIAL_CASELEM = "\\{[^}]+\\}"; - private static final String REFER_CASELEM = "\\[[^\\]]+\\]"; - private static final String RANGE_CASELM = "\\[\\d+\\.\\.\\d+\\]"; + /* Regexps for marking rule types. */ + private static final String SPECIAL_CASELEM = "\\{[^}]+\\}"; + private static final String REFER_CASELEM = "\\[[^\\]]+\\]"; + private static final String RANGE_CASELM = "\\[\\d+\\.\\.\\d+\\]"; - /** - * The type of this element. - */ + /** The type of this element. */ public final ElementType type; /** @@ -118,24 +109,21 @@ public class CaseElement { * Create a new case element. * * @param typ - * The type of this element. + * The type of this element. * * @throws IllegalArgumentException - * If the specified type needs parameters. + * If the specified type needs parameters. */ public CaseElement(ElementType typ) { switch (typ) { case LITERAL: case RULEREF: throw new IllegalArgumentException("This type requires a string parameter"); - case RANGE: throw new IllegalArgumentException("This type requires two integer parameters"); - case VARDEF: case EXPVARDEF: throw new IllegalArgumentException("This type requires two string parameters"); - default: break; } @@ -147,28 +135,24 @@ public class CaseElement { * Create a new case element that has a single string value. * * @param typ - * The type of this element. + * The type of this element. * * @param val - * The string value of this element. + * The string value of this element. * * @throws IllegalArgumentException - * If the specified type doesn't take a single string - * parameter. + * If the specified type doesn't take a single string parameter. */ public CaseElement(ElementType typ, String val) { switch (typ) { case LITERAL: case RULEREF: break; - case RANGE: throw new IllegalArgumentException("This type requires two integer parameters"); - case VARDEF: case EXPVARDEF: throw new IllegalArgumentException("This type requires two string parameters"); - default: throw new IllegalArgumentException("This type doesn't have a string parameter"); } @@ -182,29 +166,27 @@ public class CaseElement { * Create a new case element that has two integer values. * * @param typ - * The type of this element. + * The type of this element. + * * @param first - * The first integer value for this element. + * The first integer value for this element. + * * @param second - * The second integer value for this element. + * The second integer value for this element. * * @throws IllegalArgumentException - * If the specified type doesn't take two integer - * parameters. + * If the specified type doesn't take two integer parameters. */ public CaseElement(ElementType typ, int first, int second) { switch (typ) { case LITERAL: case RULEREF: throw new IllegalArgumentException("This type requires a string parameter"); - case RANGE: break; - case VARDEF: case EXPVARDEF: throw new IllegalArgumentException("This type requires two string parameters"); - default: throw new IllegalArgumentException("This type doesn't have two integer parameters"); } @@ -219,29 +201,27 @@ public class CaseElement { * Create a new case element that has two string values. * * @param typ - * The type of this element. + * The type of this element. + * * @param name - * The first string value for this element. + * The first string value for this element. + * * @param def - * The second string value for this element. + * The second string value for this element. * * @throws IllegalArgumentException - * If the specified type doesn't take two string - * parameters. + * If the specified type doesn't take two string parameters. */ public CaseElement(ElementType typ, String name, String def) { switch (typ) { case LITERAL: case RULEREF: throw new IllegalArgumentException("This type requires a string parameter"); - case RANGE: throw new IllegalArgumentException("This type requires two integer parameters"); - case VARDEF: case EXPVARDEF: break; - default: throw new IllegalArgumentException("This type doesn't have two string parameters"); } @@ -255,17 +235,17 @@ public class CaseElement { /** * Get the literal string value for this element. * - * @return The literal string value for this element. + * @return + * The literal string value for this element. * * @throws IllegalStateException - * If this type doesn't have a literal string value. + * If this type doesn't have a literal string value. */ public String getLiteral() { switch (type) { case LITERAL: case RULEREF: break; - default: throw new IllegalStateException( String.format("Type '%s' doesn't have a literal string value")); @@ -277,20 +257,19 @@ public class CaseElement { /** * Get the starting integer value for this element. * - * @return The starting integer value for this element. + * @return + * The starting integer value for this element. * * @throws IllegalStateException - * If this type doesn't have a starting integer value. + * If this type doesn't have a starting integer value. */ public int getStart() { switch (type) { case RANGE: break; - default: throw new IllegalStateException( String.format("Type '%s' doesn't have a starting integer value", type)); - } return start; @@ -299,16 +278,16 @@ public class CaseElement { /** * Get the ending integer value for this element. * - * @return The ending integer value for this element. + * @return + * The ending integer value for this element. * * @throws IllegalStateException - * If this type doesn't have a ending integer value. + * If this type doesn't have a ending integer value. */ public int getEnd() { switch (type) { case RANGE: break; - default: throw new IllegalStateException( String.format("Type '%s' doesn't have a ending integer value", type)); @@ -320,17 +299,17 @@ public class CaseElement { /** * Get the variable name for this element. * - * @return The variable name of this element. + * @return + * The variable name of this element. * * @throws IllegalStateException - * If the type doesn't have a variable name. + * If the type doesn't have a variable name. */ public String getName() { switch (type) { case VARDEF: case EXPVARDEF: break; - default: throw new IllegalStateException(String.format("Type '%s' doesn't have a name", type)); } @@ -341,17 +320,17 @@ public class CaseElement { /** * Get the variable definition for this element. * - * @return The variable definition of this element. + * @return + * The variable definition of this element. * * @throws IllegalStateException - * If the type doesn't have a variable definition. + * If the type doesn't have a variable definition. */ public String getDefn() { switch (type) { case VARDEF: case EXPVARDEF: break; - default: throw new IllegalStateException(String.format("Type '%s' doesn't have a name", type)); } @@ -365,16 +344,12 @@ public class CaseElement { case LITERAL: case RULEREF: return literalVal; - case RANGE: return String.format("[%d..%d]", start, end); - case VARDEF: return String.format("{%s:=%s}", varName, varDef); - case EXPVARDEF: return String.format("{%s=%s}", varName, varDef); - default: return String.format("Unknown type '%s'", type); } @@ -384,9 +359,10 @@ public class CaseElement { * Create a case element from a string. * * @param csepart - * The string to convert. + * The string to convert. * - * @return A case element representing the string. + * @return + * A case element representing the string. */ public static CaseElement createElement(String csepart) { if (csepart == null) { @@ -394,42 +370,33 @@ public class CaseElement { } if (csepart.matches(SPECIAL_CASELEM)) { - /* - * Handle special cases. - */ + /* Handle special cases. */ String specialBody = csepart.substring(1, csepart.length() - 1); if (specialBody.matches("\\S+:=\\S+")) { - /* - * Handle expanding variable definitions. - */ + /* Handle expanding variable definitions. */ String[] parts = specialBody.split(":="); if (parts.length != 2) { - throw new GrammarException("Expanded variables must be a name and a definition," - + " seperated by :="); + String msg = "Expanded variables must be a name and a definition, seperated by :="; + + throw new GrammarException(msg); } return new CaseElement(EXPVARDEF, parts[0], parts[1]); } else if (specialBody.matches("\\S+=\\S+")) { - /* - * Handle regular variable definitions. - */ - /* - * Handle expanding variable definitions. - */ + /* Handle regular variable definitions. */ String[] parts = specialBody.split("="); if (parts.length != 2) { - throw new GrammarException("Variables must be a name and a definition," - + " seperated by ="); + String msg = "Variables must be a name and a definition, seperated by ="; + + throw new GrammarException(msg); } return new CaseElement(VARDEF, parts[0], parts[1]); } else if (specialBody.matches("{empty}")) { - /* - * Literal blank, for empty cases. - */ + /* Literal blank, for empty cases. */ return new CaseElement(LITERAL, ""); } else { throw new IllegalArgumentException( @@ -437,12 +404,10 @@ public class CaseElement { } } else if (csepart.matches(REFER_CASELEM)) { if (csepart.matches(RANGE_CASELM)) { - /* - * Handle ranges - */ + /* Handle ranges */ String rawRange = csepart.substring(1, csepart.length() - 1); - int firstNum = Integer.parseInt(rawRange.substring(0, rawRange.indexOf('.'))); + int firstNum = Integer.parseInt(rawRange.substring(0, rawRange.indexOf('.'))); int secondNum = Integer.parseInt(rawRange.substring(rawRange.lastIndexOf('.') + 1)); return new CaseElement(RANGE, firstNum, secondNum); diff --git a/RGens/src/main/java/bjc/rgens/newparser/GrammarException.java b/RGens/src/main/java/bjc/rgens/newparser/GrammarException.java index ac37f7a..8e66f90 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/GrammarException.java +++ b/RGens/src/main/java/bjc/rgens/newparser/GrammarException.java @@ -5,19 +5,16 @@ package bjc.rgens.newparser; * grammar. * * @author student - * */ public class GrammarException extends RuntimeException { - /* - * Serialization ID. - */ + /* Serialization ID. */ private static final long serialVersionUID = -7287427479316953668L; /** * Create a new grammar exception with the specified message. * * @param msg - * The message for this exception. + * The message for this exception. */ public GrammarException(String msg) { super(msg); @@ -28,12 +25,12 @@ public class GrammarException extends RuntimeException { * cause. * * @param msg - * The message for this exception. + * The message for this exception. * * @param cause - * The cause of this exception. + * The cause of this exception. */ public GrammarException(String msg, Exception cause) { super(msg, cause); } -}
\ No newline at end of file +} diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammar.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammar.java index ada1a57..2dfec39 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammar.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammar.java @@ -21,11 +21,12 @@ import edu.gatech.gtri.bktree.MutableBkTree; * Represents a randomized grammar. * * @author EVE - * */ public class RGrammar { + /* The max distance between possible alternate rules. */ private static final int MAX_DISTANCE = 6; + /* The metric for the levenshtein distance. */ private static final class LevenshteinMetric implements Metric<String> { private static LevenshteinDistance DIST; @@ -42,12 +43,28 @@ public class RGrammar { } } + /* The current state during generation. */ private static class GenerationState { - public StringBuilder contents; - public Random rnd; - + /* The current string. */ + public StringBuilder contents; + /* The RNG. */ + public Random rnd; + + /* The current set of variables. */ public Map<String, String> vars; + /** + * Create a new generation state. + * + * @param cont + * The string being generated. + * + * @param rand + * The RNG to use. + * + * @param vs + * The variables to use. + */ public GenerationState(StringBuilder cont, Random rand, Map<String, String> vs) { contents = cont; rnd = rand; @@ -55,20 +72,26 @@ public class RGrammar { } } + /* The pattern for matching the name of a variable. */ private static Pattern NAMEVAR_PATTERN = Pattern.compile("\\$(\\w+)"); + /* The rules of the grammar. */ private Map<String, Rule> rules; + /* The rules imported from other grammars. */ private Map<String, RGrammar> importRules; + /* The rules exported from this grammar. */ private Set<String> exportRules; + /* The initial rule of this grammar. */ private String initialRule; - + + /* The tree to use for finding rule suggestions. */ private BkTreeSearcher<String> ruleSearcher; /** * Create a new randomized grammar using the specified set of rules. * * @param ruls - * The rules to use. + * The rules to use. */ public RGrammar(Map<String, Rule> ruls) { rules = ruls; @@ -81,7 +104,7 @@ public class RGrammar { * definitions are checked. * * @param importedRules - * The set of imported rules to use. + * The set of imported rules to use. */ public void setImportedRules(Map<String, RGrammar> importedRules) { importRules = importedRules; @@ -105,10 +128,11 @@ public class RGrammar { * rule. * * @param startRule - * The rule to start generating at, or null to use the - * initial rule for this grammar. + * The rule to start generating at, or null to use the initial rule + * for this grammar. * - * @return A possible string from the grammar. + * @return + * A possible string from the grammar. */ public String generate(String startRule) { return generate(startRule, new Random(), new HashMap<>()); @@ -119,16 +143,17 @@ public class RGrammar { * rule. * * @param startRule - * The rule to start generating at, or null to use the - * initial rule for this grammar. + * The rule to start generating at, or null to use the initial rule + * for this grammar. * * @param rnd - * The random number generator to use. + * The random number generator to use. * * @param vars - * The set of variables to use. + * The set of variables to use. * - * @return A possible string from the grammar. + * @return + * A possible string from the grammar. */ public String generate(String startRule, Random rnd, Map<String, String> vars) { String fromRule = startRule; @@ -155,9 +180,7 @@ public class RGrammar { return contents.toString(); } - /* - * Generate a rule case. - */ + /* Generate a rule case. */ private void generateCase(RuleCase start, GenerationState state) { try { switch (start.type) { @@ -165,9 +188,7 @@ public class RGrammar { for (CaseElement elm : start.getElements()) { generateElement(elm, state); } - break; - default: String msg = String.format("Unknown case type '%s'", start.type); throw new GrammarException(msg); @@ -178,9 +199,7 @@ public class RGrammar { } } - /* - * Generate a case element. - */ + /* Generate a case element. */ private void generateElement(CaseElement elm, GenerationState state) { try { switch (elm.type) { @@ -188,14 +207,12 @@ public class RGrammar { state.contents.append(elm.getLiteral()); state.contents.append(" "); break; - case RULEREF: generateRuleReference(elm, state); break; - case RANGE: int start = elm.getStart(); - int end = elm.getEnd(); + int end = elm.getEnd(); int val = state.rnd.nextInt(end - start); val += start; @@ -203,15 +220,12 @@ public class RGrammar { state.contents.append(val); state.contents.append(" "); break; - case VARDEF: generateVarDef(elm.getName(), elm.getDefn(), state); break; - case EXPVARDEF: generateExpVarDef(elm.getName(), elm.getDefn(), state); break; - default: String msg = String.format("Unknown element type '%s'", elm.type); throw new GrammarException(msg); @@ -222,12 +236,10 @@ public class RGrammar { } } - /* - * Generate a expanding variable definition. - */ + /* Generate a expanding variable definition. */ private void generateExpVarDef(String name, String defn, GenerationState state) { - GenerationState newState = new GenerationState(new StringBuilder(), state.rnd, - state.vars); + GenerationState newState = new GenerationState( + new StringBuilder(), state.rnd, state.vars); if (rules.containsKey(defn)) { RuleCase destCase = rules.get(defn).getCase(); @@ -235,7 +247,7 @@ public class RGrammar { generateCase(destCase, newState); } else if (importRules.containsKey(defn)) { RGrammar destGrammar = importRules.get(defn); - String res = destGrammar.generate(defn, state.rnd, state.vars); + String res = destGrammar.generate(defn, state.rnd, state.vars); newState.contents.append(res); } else { @@ -246,32 +258,24 @@ public class RGrammar { state.vars.put(name, newState.contents.toString()); } - /* - * Generate a variable definition. - */ + /* Generate a variable definition. */ private static void generateVarDef(String name, String defn, GenerationState state) { state.vars.put(name, defn); } - /* - * Generate a rule reference. - */ + /* Generate a rule reference. */ private void generateRuleReference(CaseElement elm, GenerationState state) { String refersTo = elm.getLiteral(); - GenerationState newState = new GenerationState(new StringBuilder(), state.rnd, - state.vars); + GenerationState newState = new GenerationState( + new StringBuilder(), state.rnd, state.vars); if (refersTo.contains("$")) { - /* - * Parse variables - */ + /* Parse variables */ String refBody = refersTo.substring(1, refersTo.length() - 1); if (refBody.contains("-")) { - /* - * Handle dependent rule names. - */ + /* Handle dependent rule names. */ StringBuffer nameBuffer = new StringBuffer(); Matcher nameMatcher = NAMEVAR_PATTERN.matcher(refBody); @@ -301,9 +305,7 @@ public class RGrammar { refersTo = "[" + nameBuffer.toString() + "]"; } else { - /* - * Handle string references. - */ + /* Handle string references. */ if (refBody.equals("$")) { throw new GrammarException("Cannot refer to unnamed variables"); } @@ -333,11 +335,11 @@ public class RGrammar { if (ruleSearcher != null) { Set<Match<? extends String>> results = ruleSearcher.search(refersTo, MAX_DISTANCE); - String[] resArray = results.stream().map((mat) -> mat.getMatch()) - .toArray((i) -> new String[i]); + String[] resArray = results.stream() + .map(Match::getMatch).toArray((i) -> new String[i]); String msg = String.format("No rule '%s' defined (perhaps you meant %s?)", - refersTo, StringUtils.toEnglishList(resArray, false)); + refersTo, StringUtils.toEnglishList(resArray, false)); throw new GrammarException(msg); } @@ -347,10 +349,9 @@ public class RGrammar { } if (refersTo.contains("+")) { - /* - * Rule names with pluses in them get space-flattened - */ + /* Rule names with pluses in them get space-flattened */ state.contents.append(newState.contents.toString().replaceAll("\\s+", "")); + state.contents.append(" "); } else { state.contents.append(newState.contents.toString()); } @@ -359,7 +360,8 @@ public class RGrammar { /** * Get the initial rule of this grammar. * - * @return The initial rule of this grammar. + * @return + * The initial rule of this grammar. */ public String getInitialRule() { return initialRule; @@ -369,13 +371,11 @@ public class RGrammar { * Set the initial rule of this grammar. * * @param initRule - * The initial rule of this grammar, or null to say there - * is no initial rule. + * The initial rule of this grammar, or null to say there is no + * initial rule. */ public void setInitialRule(String initRule) { - /* - * Passing null nulls our initial rule. - */ + /* Passing null, nulls our initial rule. */ if (initRule == null) { this.initialRule = null; return; @@ -385,6 +385,7 @@ public class RGrammar { throw new GrammarException("The empty string is not a valid rule name"); } else if (!rules.containsKey(initRule)) { String msg = String.format("No rule '%s' local to this grammar defined.", initRule); + throw new GrammarException(msg); } @@ -396,7 +397,8 @@ public class RGrammar { * * The initial rule is exported by default if specified. * - * @return The rules exported by this grammar. + * @return + * The rules exported by this grammar. */ public Set<Rule> getExportedRules() { Set<Rule> res = new HashSet<>(); @@ -405,6 +407,7 @@ public class RGrammar { if (!rules.containsKey(rname)) { String msg = String.format("No rule '%s' local to this grammar defined", initialRule); + throw new GrammarException(msg); } @@ -422,7 +425,7 @@ public class RGrammar { * Set the rules exported by this grammar. * * @param exportedRules - * The rules exported by this grammar. + * The rules exported by this grammar. */ public void setExportedRules(Set<String> exportedRules) { exportRules = exportedRules; @@ -431,7 +434,8 @@ public class RGrammar { /** * Get all the rules in this grammar. * - * @return All the rules in this grammar. + * @return + * All the rules in this grammar. */ public Map<String, Rule> getRules() { return rules; diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarBuilder.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarBuilder.java index bd8ba84..4e9f9e1 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarBuilder.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarBuilder.java @@ -14,24 +14,31 @@ import static bjc.rgens.newparser.RuleCase.CaseType.*; * Construct randomized grammars piece by piece. * * @author EVE - * */ public class RGrammarBuilder { + /* The rules being built. */ private Map<String, Rule> rules; - + /* The current set of exported rules. */ private Set<String> exportedRules; - + /* The current initial rule. */ private String initialRule; - /** - * Create a new randomized grammar builder. - */ + /** Create a new randomized grammar builder. */ public RGrammarBuilder() { rules = new HashMap<>(); exportedRules = new HashSet<>(); } + /** + * Get or create a rule by the given name. + * + * @param rName + * The name of the rule. + * + * @return + * The rule by that name, or a new one if none existed. + */ public Rule getOrCreateRule(String rName) { if(rName == null) throw new NullPointerException("Rule name must not be null"); @@ -52,7 +59,8 @@ public class RGrammarBuilder { /** * Convert this builder into a grammar. * - * @return The grammar built by this builder + * @return + * The grammar built by this builder */ public RGrammar toRGrammar() { RGrammar grammar = new RGrammar(rules); @@ -68,11 +76,10 @@ public class RGrammarBuilder { * Set the initial rule of the grammar. * * @param init - * The initial rule of the grammar. + * The initial rule of the grammar. * * @throws IllegalArgumentException - * If the rule is either not valid or not defined in the - * grammar. + * If the rule is either not valid or not defined in the grammar. */ public void setInitialRule(String init) { if (init == null) { @@ -88,11 +95,10 @@ public class RGrammarBuilder { * Add an exported rule to this grammar. * * @param export - * The name of the rule to export. + * The name of the rule to export. * * @throws IllegalArgumentException - * If the rule is either not valid or not defined in the - * grammar. + * If the rule is either not valid or not defined in the grammar. */ public void addExport(String export) { if (export == null) { @@ -108,14 +114,14 @@ public class RGrammarBuilder { * Suffix a given case element to every case of a specific rule. * * @param ruleName - * The rule to suffix. + * The rule to suffix. * * @param suffix - * The suffix to add. + * The suffix to add. * * @throws IllegalArgumentException - * If the rule name is either invalid or not defined by - * this grammar, or if the suffix is invalid. + * If the rule name is either invalid or not defined by this + * grammar, or if the suffix is invalid. */ public void suffixWith(String ruleName, String suffix) { if (ruleName == null) { @@ -135,14 +141,14 @@ public class RGrammarBuilder { * Prefix a given case element to every case of a specific rule. * * @param ruleName - * The rule to prefix. + * The rule to prefix. * * @param prefix - * The prefix to add. + * The prefix to add. * * @throws IllegalArgumentException - * If the rule name is either invalid or not defined by - * this grammar, or if the prefix is invalid. + * If the rule name is either invalid or not defined by this + * grammar, or if the prefix is invalid. */ public void prefixWith(String ruleName, String prefix) { if (ruleName == null) { diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarFormatter.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarFormatter.java index 168fb7b..acb2c07 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarFormatter.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarFormatter.java @@ -10,16 +10,16 @@ import java.util.Set; * Format randomized grammars to strings properly. * * @author EVE - * */ public class RGrammarFormatter { /** * Format a grammar into a file that represents that grammar. * * @param gram - * The grammar to format. + * The grammar to format. * - * @return The formatted grammar. + * @return + * The formatted grammar. */ public static String formatGrammar(RGrammar gram) { StringBuilder sb = new StringBuilder(); @@ -49,6 +49,7 @@ public class RGrammarFormatter { return sb.toString().trim(); } + /* Format a rule. */ private static void processRule(Rule rule, StringBuilder sb) { IList<RuleCase> cases = rule.getCases(); @@ -81,18 +82,15 @@ public class RGrammarFormatter { } + /* Format a case. */ private static void processCase(RuleCase cse, StringBuilder sb) { - /* - * Process each element, adding a space. - */ + /* Process each element, adding a space. */ for (CaseElement element : cse.getElements()) { sb.append(element.toString()); sb.append(" "); } - /* - * Remove the trailing space. - */ + /* Remove the trailing space. */ sb.deleteCharAt(sb.length() - 1); } } diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarParser.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarParser.java index cb9f686..e253cc3 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarParser.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarParser.java @@ -16,27 +16,27 @@ import java.util.Map; * Reads {@link RGrammar} from a input stream. * * @author student - * */ public class RGrammarParser { + /* Whether we are in debug mode or not. */ public static final boolean DEBUG = false; /* * Templates for level-dependent delimiters. */ + /* Pragma block delimiter. */ private static final String TMPL_PRAGMA_BLOCK_DELIM = "\\R\\t{%d}(?!\\t)"; + /* Rule declaration block delimiter. */ private static final String TMPL_RULEDECL_BLOCK_DELIM = "\\R\\t\\t{%d}"; + /* Where block delimiter. */ private static final String TMPL_WHERE_BLOCK_DELIM = "\\R\\t{%d}(?:in|end)\\R"; + /* Top-level block delimiter. */ private static final String TMPL_TOPLEVEL_BLOCK_DELIM = "\\R\\t{%d}\\.?\\R"; - /* - * Pragma impls. - */ + /* Pragma impls. */ private static Map<String, TriConsumer<String, RGrammarBuilder, Integer>> pragmas; - /* - * Initialize pragmas. - */ + /* Initialize pragmas. */ static { pragmas = new HashMap<>(); @@ -64,6 +64,7 @@ public class RGrammarParser { if (parts.length != 2) { String msg = "Suffix-with pragma takes two arguments, the name of the rule to suffix, then what to suffix it with"; + throw new GrammarException(msg); } @@ -75,6 +76,7 @@ public class RGrammarParser { if (parts.length != 2) { String msg = "Prefix-with pragma takes two arguments, the name of the rule to prefix, then what to prefix it with"; + throw new GrammarException(msg); } @@ -86,12 +88,13 @@ public class RGrammarParser { * Read a {@link RGrammar} from an input stream. * * @param is - * The input stream to read from. + * The input stream to read from. * - * @return The grammar represented by the stream. + * @return + * The grammar represented by the stream. * * @throws GrammarException - * Thrown if the grammar has a syntax error. + * Thrown if the grammar has a syntax error. */ public static RGrammar readGrammar(Reader is) throws GrammarException { String dlm = String.format(TMPL_TOPLEVEL_BLOCK_DELIM, 0); @@ -121,18 +124,12 @@ public class RGrammarParser { } } - /* - * Throughout these, level indicates the nesting level of that construct. - */ + /* Throughout these, level indicates the nesting level of that construct. */ - /* - * Handles an arbitrary block. - */ - private static void handleBlock(RGrammarBuilder build, String block, - int level) throws GrammarException { - /* - * Discard empty blocks. - */ + /* Handles an arbitrary block. */ + private static void handleBlock(RGrammarBuilder build, String block, + int level) throws GrammarException { + /* Discard empty blocks. */ if (block.equals("") || block.matches("\\R")) return; @@ -157,8 +154,9 @@ public class RGrammarParser { /* * Comment block. * - * @Incomplete Attach these to the grammar builder so - * that they can be re-output during formatting. + * @TODO 10/11/17 Ben Culkin :GrammarComment + * Attach these to the grammar somehow so that they + * can be re-output during formatting. */ return; } else { @@ -167,9 +165,7 @@ public class RGrammarParser { } } - /* - * Handle reading a block of pragmas. - */ + /* Handle reading a block of pragmas. */ private static void handlePragmaBlock(String block, RGrammarBuilder build, int level) throws GrammarException { String dlm = String.format(TMPL_PRAGMA_BLOCK_DELIM, level); @@ -185,14 +181,16 @@ public class RGrammarParser { if (pragmaSep == -1) { String msg = "A pragma invocation must consist of the word pragma, followed by a space, then the body of the pragma"; + throw new GrammarException(msg); } String pragmaLeader = pragmaContents.substring(0, pragmaSep); - String pragmaBody = pragmaContents.substring(pragmaSep + 1); + String pragmaBody = pragmaContents.substring(pragmaSep + 1); if (!pragmaLeader.equalsIgnoreCase("pragma")) { String msg = String.format("Illegal line leader in pragma block: '%s'", pragmaLeader); + throw new GrammarException(msg); } @@ -200,8 +198,8 @@ public class RGrammarParser { }); } catch (GrammarException gex) { Block pragma = pragmaReader.getBlock(); + String msg = String.format("Error in pragma: (%s)", pragma); - String msg = String.format("Error in pragma: (%s)", pragma); throw new GrammarException(msg, gex); } } catch (Exception ex) { @@ -209,9 +207,7 @@ public class RGrammarParser { } } - /* - * Handle an individual pragma in a block. - */ + /* Handle an individual pragma in a block. */ private static void handlePragma(String pragma, RGrammarBuilder build, int level) throws GrammarException { int bodySep = pragma.indexOf(' '); @@ -230,26 +226,24 @@ public class RGrammarParser { pragmas.get(pragmaName).accept(pragmaBody, build, level); } catch (GrammarException gex) { String msg = String.format("Error in pragma '%s'", pragmaName); + throw new GrammarException(msg, gex); } } else { String msg = String.format("Unknown pragma '%s'", pragmaName); + throw new GrammarException(msg); } } - /* - * Handle a block of a rule declaration and one or more cases. - */ + /* Handle a block of a rule declaration and one or more cases. */ private static void handleRuleBlock(String ruleBlock, RGrammarBuilder build, int level) throws GrammarException { String dlm = String.format(TMPL_RULEDECL_BLOCK_DELIM, level); try (BlockReader ruleReader = new SimpleBlockReader(dlm, new StringReader(ruleBlock))) { try { if (ruleReader.hasNextBlock()) { - /* - * Rule with a declaration followed by multiple cases. - */ + /* Rule with a declaration followed by multiple cases. */ ruleReader.nextBlock(); Block declBlock = ruleReader.getBlock(); @@ -257,16 +251,18 @@ public class RGrammarParser { Rule rl = handleRuleDecl(build, declContents); ruleReader.forEachBlock((block) -> { + /* Ignore comment lines. */ + if(block.contents.trim().startsWith("#")) return; + handleRuleCase(block.contents, build, rl); }); } else { - /* - * Rule with a declaration followed by a single case. - */ + /* Rule with a declaration followed by a single case. */ handleRuleDecl(build, ruleBlock); } } catch (GrammarException gex) { String msg = String.format("Error in rule case (%s)", ruleReader.getBlock()); + throw new GrammarException(msg, gex); } } catch (Exception ex) { @@ -274,31 +270,25 @@ public class RGrammarParser { } } - /* - * Handle a rule declaration and its initial case. - */ + /* Handle a rule declaration and its initial case. */ private static Rule handleRuleDecl(RGrammarBuilder build, String declContents) { int declSep = declContents.indexOf("\u2192"); if (declSep == -1) { /* - * TODO remove support for the old syntax when all of the files are - * converted. + * @NOTE + * We should maybe remove support for the old + * syntax at some point. However, maybe we don't + * want to do so so as to make inputting grammars + * easier. */ declSep = declContents.indexOf(' '); if (declSep == -1) { - throw new GrammarException("A rule must be given at least one case in its declaration, and" - + "seperated from that case by \u2192"); + String msg = "A rule must be given at least one case in its declaration, and seperated from that case by \u2192"; + + throw new GrammarException(msg); } - - /* - * @NOTE - * - * This is true, but I don't care that much anyways. - * System.out.println( - * "WARNING: Empty space separating a declaration and its case is deprecated. Use \u2192 instead"); - */ } String ruleName = declContents.substring(0, declSep).trim(); @@ -315,18 +305,14 @@ public class RGrammarParser { return rul; } - /* - * Handle a single case of a rule. - */ + /* Handle a single case of a rule. */ private static void handleRuleCase(String cse, RGrammarBuilder build, Rule rul) { IList<CaseElement> caseParts = new FunctionalList<>(); for (String csepart : cse.split(" ")) { String partToAdd = csepart.trim(); - /* - * Ignore empty parts - */ + /* Ignore empty parts */ if (partToAdd.equals("")) continue; @@ -336,9 +322,7 @@ public class RGrammarParser { rul.addCase(new RuleCase(RuleCase.CaseType.NORMAL, caseParts)); } - /* - * Handle a where block (a block with local rules). - */ + /* Handle a where block (a block with local rules). */ private static void handleWhereBlock(String block, RGrammarBuilder build, int level) throws GrammarException { int nlIndex = block.indexOf("\\n"); @@ -366,10 +350,12 @@ public class RGrammarParser { Block whereBody = whereReader.next(); /** - * TODO implement where blocks. + * @TODO 10/11/17 Ben Culkin :WhereBlocks + * Implement where blocks. * - * A where block has the context evaluated in a new context, and - * the body executed in that context. + * A where block has the context evaluated + * in a new context, and the body executed + * in that context. */ } catch (GrammarException gex) { throw new GrammarException(String.format("Error in where block (%s)", diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarSet.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarSet.java index eb2ba56..bb67039 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarSet.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarSet.java @@ -14,7 +14,6 @@ import java.util.Set; * Represents a set of grammars that can share rules via exports. * * @author EVE - * */ public class RGrammarSet { /* Contains all the grammars in this set. */ @@ -29,9 +28,7 @@ public class RGrammarSet { /* Contains which file a grammar was loaded from. */ private Map<String, String> loadedFrom; - /** - * Create a new set of randomized grammars. - */ + /** Create a new set of randomized grammars. */ public RGrammarSet() { grammars = new HashMap<>(); @@ -45,13 +42,13 @@ public class RGrammarSet { * Add a grammar to this grammar set. * * @param grammarName - * The name of the grammar to add. + * The name of the grammar to add. * * @param gram - * The grammar to add. + * The grammar to add. * * @throws IllegalArgumentException - * If the grammar name is invalid. + * If the grammar name is invalid. */ public void addGrammar(String grammarName, RGrammar gram) { /* Make sure a grammar is valid. */ @@ -68,6 +65,7 @@ public class RGrammarSet { /* Process exports from the grammar. */ for (Rule export : gram.getExportedRules()) { exportedRules.put(export.name, gram); + exportFrom.put(export.name, grammarName); } @@ -79,13 +77,13 @@ public class RGrammarSet { * Get a grammar from this grammar set. * * @param grammarName - * The name of the grammar to get. + * The name of the grammar to get. * - * @return The grammar with that name. + * @return + * The grammar with that name. * * @throws IllegalArgumentException - * If the grammar name is invalid or not present in this - * set. + * If the grammar name is invalid or not present in this set. */ public RGrammar getGrammar(String grammarName) { /* Check arguments. */ @@ -106,13 +104,13 @@ public class RGrammarSet { * Get the grammar a rule was exported from. * * @param exportName - * The name of the exported rule. + * The name of the exported rule. * - * @return The grammar the exported rule came from. + * @return + * The grammar the exported rule came from. * * @throws IllegalArgumentException - * If the export name is invalid or not present in this - * set. + * If the export name is invalid or not present in this set. */ public RGrammar getExportSource(String exportName) { /* Check arguments. */ @@ -134,13 +132,13 @@ public class RGrammarSet { * This will often be a grammar name, but is not required to be one. * * @param exportName - * The name of the exported rule. + * The name of the exported rule. * - * @return The source of an exported rule. + * @return + * The source of an exported rule. * * @throws IllegalArgumentException - * If the exported rule is invalid or not present in - * this set. + * If the exported rule is invalid or not present in this set. */ public String exportedFrom(String exportName) { /* Check arguments. */ @@ -150,6 +148,7 @@ public class RGrammarSet { throw new IllegalArgumentException("The empty string is not a valid rule name"); } else if (!exportedRules.containsKey(exportName)) { String msg = String.format("No export with name '%s' defined", exportName); + throw new IllegalArgumentException(msg); } @@ -162,13 +161,13 @@ public class RGrammarSet { * This will often be a file name, but is not required to be one. * * @param grammarName - * The name of the exported grammar. + * The name of the exported grammar. * - * @return The source of an exported grammar. + * @return + * The source of an exported grammar. * * @throws IllegalArgumentException - * If the exported grammar is invalid or not present in - * this set. + * If the exported grammar is invalid or not present in this set. */ public String loadedFrom(String grammarName) { /* Check arguments. */ @@ -189,7 +188,8 @@ public class RGrammarSet { /** * Get the names of all the grammars in this set. * - * @return The names of all the grammars in this set. + * @return + * The names of all the grammars in this set. */ public Set<String> getGrammars() { return grammars.keySet(); @@ -198,7 +198,8 @@ public class RGrammarSet { /** * Get the names of all the exported rules in this set. * - * @return The names of all the exported rules in this set. + * @return + * The names of all the exported rules in this set. */ public Set<String> getExportedRules() { return exportedRules.keySet(); @@ -208,12 +209,13 @@ public class RGrammarSet { * Load a grammar set from a configuration file. * * @param cfgFile - * The configuration file to load from. + * The configuration file to load from. * - * @return The grammar set created by the configuration file. + * @return + * The grammar set created by the configuration file. * * @throws IOException - * If something goes wrong during configuration loading. + * If something goes wrong during configuration loading. */ public static RGrammarSet fromConfigFile(Path cfgFile) throws IOException { /* The grammar set to hand back. */ @@ -246,14 +248,14 @@ public class RGrammarSet { /* Name and path of grammar. */ String name = ln.substring(0, nameIdx); - Path path = Paths.get(ln.substring(nameIdx).trim()); + Path path = Paths.get(ln.substring(nameIdx).trim()); /* * Convert from configuration relative path to * absolute path. */ Path convPath = cfgParent.resolve(path); - File fle = convPath.toFile(); + File fle = convPath.toFile(); if (fle.isDirectory()) { /* @TODO implement subset grammars */ diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarTest.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarTest.java index 97440f6..cdbba09 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarTest.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarTest.java @@ -10,21 +10,20 @@ import java.nio.file.Paths; * Test for new grammar syntax. * * @author EVE - * */ public class RGrammarTest { /** * Main method. * * @param args - * Unused CLI args. + * Unused CLI args. */ public static void main(String[] args) { URL rsc = RGrammarTest.class.getResource("/server-config-sample.cfg"); try { /* Load a grammar set. */ - Path cfgPath = Paths.get(rsc.toURI()); + Path cfgPath = Paths.get(rsc.toURI()); RGrammarSet gramSet = RGrammarSet.fromConfigFile(cfgPath); /* Generate rule suggestions for all the grammars in the set. */ @@ -34,24 +33,25 @@ public class RGrammarTest { /* Generate for each exported rule. */ for (String exportName : gramSet.getExportedRules()) { - RGrammar grammar = gramSet.getExportSource(exportName); + /* Where we loaded the rule from. */ + String loadSrc = gramSet.loadedFrom(gramSet.exportedFrom(exportName)); - for (int i = 0; i < 10; i++) { + System.out.println(); + System.out.printf("Generating for exported rule '%s' from file '%s'\n", exportName, loadSrc); + + RGrammar grammar = gramSet.getExportSource(exportName); + for (int i = 0; i < 100; i++) { try { - System.out.printf("Generating for exported rule '%s'\n", exportName); String res = grammar.generate(exportName); + if(exportName.contains("+")) res = res.replaceAll("\\s+", ""); + System.out.printf("\tContents: %s\n", res); } catch (GrammarException gex) { - /* - * Print out errors with generation. - */ + /* Print out errors with generation. */ String fmt = "Error in exported rule '%s' (loaded from '%s')\n"; - String loadSrc = gramSet.loadedFrom(gramSet.exportedFrom(exportName)); System.out.printf(fmt, exportName, loadSrc); - System.out.println(); - gex.printStackTrace(); System.out.println(); @@ -59,7 +59,6 @@ public class RGrammarTest { } } } - } catch (IOException ioex) { ioex.printStackTrace(); } catch (URISyntaxException urisex) { diff --git a/RGens/src/main/java/bjc/rgens/newparser/Rule.java b/RGens/src/main/java/bjc/rgens/newparser/Rule.java index aee1a89..612d603 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/Rule.java +++ b/RGens/src/main/java/bjc/rgens/newparser/Rule.java @@ -9,24 +9,22 @@ import java.util.Random; * A rule in a randomized grammar. * * @author EVE - * */ public class Rule { - /** - * The name of this grammar rule. - */ + /** The name of this grammar rule. */ public final String name; + /* The cases for this rule. */ private IList<RuleCase> cases; /** * Create a new grammar rule. * * @param ruleName - * The name of the grammar rule. + * The name of the grammar rule. * * @throws IllegalArgumentException - * If the rule name is invalid. + * If the rule name is invalid. */ public Rule(String ruleName) { if (ruleName == null) { @@ -44,7 +42,7 @@ public class Rule { * Adds a case to the rule. * * @param cse - * The case to add. + * The case to add. */ public void addCase(RuleCase cse) { if (cse == null) { @@ -57,7 +55,8 @@ public class Rule { /** * Get a random case from this rule. * - * @return A random case from this rule. + * @return + * A random case from this rule. */ public RuleCase getCase() { return cases.randItem(); @@ -67,9 +66,10 @@ public class Rule { * Get a random case from this rule. * * @param rnd - * The random number generator to use. + * The random number generator to use. * - * @return A random case from this rule. + * @return + * A random case from this rule. */ public RuleCase getCase(Random rnd) { return cases.randItem(rnd::nextInt); @@ -78,7 +78,8 @@ public class Rule { /** * Get all the cases of this rule. * - * @return All the cases in this rule. + * @return + * All the cases in this rule. */ public IList<RuleCase> getCases() { return cases; @@ -120,4 +121,4 @@ public class Rule { public String toString() { return String.format("Rule [ruleName='%s', ruleCases=%s]", name, cases); } -}
\ No newline at end of file +} diff --git a/RGens/src/main/java/bjc/rgens/newparser/RuleCase.java b/RGens/src/main/java/bjc/rgens/newparser/RuleCase.java index c22aa98..4ec0d2d 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RuleCase.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RuleCase.java @@ -2,6 +2,11 @@ package bjc.rgens.newparser; import bjc.utils.funcdata.IList; +/* + * @NOTE + * If at some point we add new case types, they should go into subclasses, + * not into this class. + */ /** * A case in a rule in a randomized grammar. * @@ -12,18 +17,13 @@ public class RuleCase { * The possible types of a case. * * @author EVE - * */ public static enum CaseType { - /** - * A normal case, composed from a list of elementList. - */ + /** A normal case, composed from a list of elementList. */ NORMAL, } - /** - * The type of this case. - */ + /** The type of this case. */ public final CaseType type; /** @@ -41,16 +41,15 @@ public class RuleCase { * Create a new case of the specified type. * * @param typ - * The type of case to create. + * The type of case to create. * * @throws IllegalArgumentException - * If the type requires parameters. + * If the type requires parameters. */ public RuleCase(CaseType typ) { switch (typ) { case NORMAL: throw new IllegalArgumentException("This type requires an element list parameter"); - default: break; } @@ -63,19 +62,18 @@ public class RuleCase { * parameter. * * @param typ - * The type of case to create. + * The type of case to create. * * @param elements - * The element list parameter of the case. + * The element list parameter of the case. * * @throws IllegalArgumentException - * If this type doesn't take a element list parameter. + * If this type doesn't take a element list parameter. */ public RuleCase(CaseType typ, IList<CaseElement> elements) { switch (typ) { case NORMAL: break; - default: throw new IllegalArgumentException("This type doesn't have a element list parameter"); } @@ -88,8 +86,9 @@ public class RuleCase { /** * Get the element list value of this type. * - * @return The element list value of this case, or null if this type - * doesn't have one. + * @return + * The element list value of this case, or null if this type + * doesn't have one. */ public IList<CaseElement> getElements() { return elementList; diff --git a/RGens/src/main/java/bjc/rgens/text/markov/Markov.java b/RGens/src/main/java/bjc/rgens/text/markov/Markov.java index b4564c4..e21d60f 100644 --- a/RGens/src/main/java/bjc/rgens/text/markov/Markov.java +++ b/RGens/src/main/java/bjc/rgens/text/markov/Markov.java @@ -9,7 +9,6 @@ import java.util.*; * Can give a pseudo-random suffix character based on probability. * * @author Daniel Friedman (Fall 2011) - * */ public class Markov { String substring; @@ -21,7 +20,7 @@ public class Markov { * Constructs a Markov object from a given substring. * * @param substr - * the given substring. + * The given substring. */ public Markov(String substr) { this.substring = substr; @@ -38,9 +37,10 @@ public class Markov { * Suffix characters are stored in a TreeMap. * * @param substr - * the specified substring. + * The specified substring. + * * @param suffix - * the specified suffix. + * The specified suffix. */ public Markov(String substr, Character suffix) { this.substring = substr; @@ -62,7 +62,7 @@ public class Markov { * Adds a suffix character to the TreeMap. * * @param c - * the suffix character to be added. + * The suffix character to be added. */ public void add(char c) { add(); @@ -70,7 +70,9 @@ public class Markov { if (map.containsKey(c)) { int frequency = map.get(c); map.put(c, frequency + 1); - } else map.put(c, 1); + } else { + map.put(c, 1); + } } /** @@ -78,8 +80,10 @@ public class Markov { * of times the specified suffix follows the substring in a text. * * @param c - * the specified suffix. - * @return the frequency count. + * The specified suffix. + * + * @return + * The frequency count. */ public int getFrequencyCount(char c) { if (!map.containsKey(c)) { @@ -93,8 +97,11 @@ public class Markov { * Gives a percentage of frequency count / number of total suffixes. * * @param c - * @return the ratio of frequency count of a single character to the - * total number of suffixes + * The character to look for the frequency for. + * + * @return + * The ratio of frequency count of a single character to the total + * number of suffixes. */ public double getCharFrequency(char c) { if (getFrequencyCount(c) == -1) { @@ -108,8 +115,10 @@ public class Markov { * Finds whether or not the given suffix is in the TreeMap. * * @param c - * the given suffix. - * @return True if the suffix exists in the TreeMap, false otherwise. + * The given suffix. + * + * @return + * True if the suffix exists in the TreeMap, false otherwise. */ public boolean containsChar(char c) { if (!map.containsKey(c)) { @@ -122,7 +131,8 @@ public class Markov { /** * Gives the number of times this substring occurs in a text. * - * @return said number of times. + * @return + * Said number of times. */ public int count() { return count; @@ -131,7 +141,8 @@ public class Markov { /** * Gives the TreeMap. * - * @return the TreeMap. + * @return + * The TreeMap. */ public TreeMap<Character, Integer> getMap() { return map; @@ -141,14 +152,14 @@ public class Markov { * Using probability, returns a pseudo-random character to follow the * substring. * - * Character possibilities are added to an ArrayList - * (duplicates allowed), and a random number from 0 to the last index in - * the ArrayList is picked. Since more common suffixes occupy more - * indices in the ArrayList, the probability of getting a more common - * suffix is greater than the probability of getting a less common - * suffix. + * Character possibilities are added to an ArrayList (duplicates + * allowed), and a random number from 0 to the last index in the + * ArrayList is picked. Since more common suffixes occupy more indices + * in the ArrayList, the probability of getting a more common suffix is + * greater than the probability of getting a less common suffix. * - * @return the pseudo-random suffix. + * @return + * The pseudo-random suffix. */ public char random() { Character ret = null; @@ -178,7 +189,8 @@ public class Markov { /** * Gives a String representation of the Markov object. * - * @return said String representation. + * @return + * Said String representation. */ @Override public String toString() { diff --git a/RGens/src/main/java/bjc/rgens/text/markov/StandaloneMarkov.java b/RGens/src/main/java/bjc/rgens/text/markov/StandaloneMarkov.java index 29f8446..cebf2bc 100644 --- a/RGens/src/main/java/bjc/rgens/text/markov/StandaloneMarkov.java +++ b/RGens/src/main/java/bjc/rgens/text/markov/StandaloneMarkov.java @@ -6,25 +6,27 @@ import java.util.Map; * A standalone Markov generator. * * @author bjculkin - * */ public class StandaloneMarkov { + /* The order of the generator. */ private int ord; + /* The generators to use. */ private Map<String, Markov> hash; + /* The initial string. */ private String first; /** * Create a new standalone Markov generator. * * @param order - * The order of this generator. + * The order of this generator. * * @param markovHash - * The generators to use. + * The generators to use. * * @param firstSub - * The string to start out with. + * The string to start out with. */ public StandaloneMarkov(int order, Map<String, Markov> markovHash, String firstSub) { ord = order; @@ -36,9 +38,10 @@ public class StandaloneMarkov { * Generate random text from the markov generator. * * @param charsToGenerate - * The number of characters of text to generate. + * The number of characters of text to generate. * - * @return The randomly generate text. + * @return + * The randomly generate text. */ public String generateTextFromMarkov(int charsToGenerate) { StringBuilder text = new StringBuilder(); diff --git a/RGens/src/main/java/bjc/rgens/text/markov/StandaloneTextGenerator.java b/RGens/src/main/java/bjc/rgens/text/markov/StandaloneTextGenerator.java index c6eea0d..339e8d5 100644 --- a/RGens/src/main/java/bjc/rgens/text/markov/StandaloneTextGenerator.java +++ b/RGens/src/main/java/bjc/rgens/text/markov/StandaloneTextGenerator.java @@ -9,19 +9,19 @@ import java.util.Map; * Create a Markov generate from a provided source. * * @author bjculkin - * */ public class StandaloneTextGenerator { /** * Build a markov generator from a provided source. * * @param order - * The markov order to use. + * The markov order to use. * * @param reader - * The source to seed the generator from. + * The source to seed the generator from. * - * @return The markov generator for the provided text. + * @return + * The markov generator for the provided text. */ public static StandaloneMarkov generateMarkovMap(int order, Reader reader) { Map<String, Markov> hash = new HashMap<>(); diff --git a/RGens/src/main/java/bjc/rgens/text/markov/TextGenerator.java b/RGens/src/main/java/bjc/rgens/text/markov/TextGenerator.java index 0ec40df..f629d49 100644 --- a/RGens/src/main/java/bjc/rgens/text/markov/TextGenerator.java +++ b/RGens/src/main/java/bjc/rgens/text/markov/TextGenerator.java @@ -13,16 +13,15 @@ public class TextGenerator { * Main method. * * @param args - * when used with three arguments, the first represents - * the k-order of the Markov objects. The second - * represents the number of characters to print out. The - * third represents the file to be read. + * When used with three arguments, the first represents the k-order + * of the Markov objects. The second represents the number of + * characters to print out. The third represents the file to be + * read. * - * When used with two arguments, the first represents the - * k-order of the Markov objects, and the second - * represents the file to be read. The generated text - * will be the same number of characters as the original - * file. + * When used with two arguments, the first represents the k-order + * of the Markov objects, and the second represents the file to be + * read. The generated text will be the same number of characters + * as the original file. */ public static void main(String[] args) { int k = 0; @@ -71,4 +70,4 @@ public class TextGenerator { System.exit(1); } } -}
\ No newline at end of file +} |
