diff options
| author | Benjamin J. Culkin <bjculkin@mix.wvu.edu> | 2017-07-23 16:27:29 -0300 |
|---|---|---|
| committer | Benjamin J. Culkin <bjculkin@mix.wvu.edu> | 2017-07-23 16:27:29 -0300 |
| commit | 985c3e8e9eeff790a138d74aeea30bc069cb97f9 (patch) | |
| tree | 610482757b04c338715af176aad680254c1fef8e /RGens | |
| parent | 37caa6e5d2108778e7ee0c7940bd2b7d2b13095c (diff) | |
Formatting
Diffstat (limited to 'RGens')
17 files changed, 435 insertions, 380 deletions
diff --git a/RGens/src/main/java/bjc/rgens/ZadronsPouch.java b/RGens/src/main/java/bjc/rgens/ZadronsPouch.java index 7160bdd..5634385 100644 --- a/RGens/src/main/java/bjc/rgens/ZadronsPouch.java +++ b/RGens/src/main/java/bjc/rgens/ZadronsPouch.java @@ -7,14 +7,14 @@ 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 */ @@ -41,9 +41,9 @@ public class ZadronsPouch { grammar = new RandomGrammar<>(); 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(); @@ -63,118 +63,118 @@ public class ZadronsPouch { private void addBagRules() { addRule("[bag]", - "bag of [bag-type]", "[sack-type] sack", "[purse-type] purse"); + "bag of [bag-type]", "[sack-type] sack", "[purse-type] purse"); addRule("[bag-type]", - "holding", "tricks", "useful items", - "devouring", "dwarf-kind", "invisible cloth", - "monster summoning"); + "holding", "tricks", "useful items", + "devouring", "dwarf-kind", "invisible cloth", + "monster summoning"); addRule("[sack-type]", - "lunch", "recursive"); + "lunch", "recursive"); addRule("[purse-type]", - "everfull"); + "everfull"); } private void addBoxRules() { addRule("[box]", - "[box-type] box", "cube of [box-type]"); + "[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"); + "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", - "crystal of [crystal-type]", "crystal ball", - "crystal ball of [crys-suffix]"); + "[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]", - "microphonic", "seeing-eye"); + "microphonic", "seeing-eye"); addRule("[lens-type]", - "detection"); + "detection"); addRule("[crystal-type]", - "prison", "radar"); + "prison", "radar"); addRule("[crys-suffix]", - "jumping"); + "jumping"); } private void addEggRules() { addRule("[egg]", - "[egg-type] 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]"); + "[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", - "elephant", "warrior", "palace", "leprechaun"); + "lion", "dog", "owl", "goat", + "elephant", "warrior", "palace", "leprechaun"); } private void addGloveRules() { - addRule("[glove]", - "gauntlets of [gauntlet-type]", - "gloves of [glove-type]", - "[glove-type] gloves"); + addRule("[glove]", + "gauntlets of [gauntlet-type]", + "gloves of [glove-type]", + "[glove-type] gloves"); addRule("[gauntlet-type]", - "dexterity", "power"); + "dexterity", "power"); addRule("[glove-type]", - "pushing", "choking", "bigby", "stunning"); + "pushing", "choking", "bigby", "stunning"); } private void addMiniWeaponRules() { addRule("[mini-weapon]", - "minature [weapon-type]", "small [weapon-type]", - "tiny [weapon-type]", "[sling-type] sling", - "[weapon-type]"); + "minature [weapon-type]", "small [weapon-type]", + "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"); + "seeking"); } private void addRockRules() { addRule("[rock]", - "[pebble-type] pebble", "stone of [stone-type]", - "[stone-type] stone", "brick of [brick-type]", - "[geode-type] geode"); + "[pebble-type] pebble", "stone of [stone-type]", + "[stone-type] stone", "brick of [brick-type]", + "[geode-type] geode"); addRule("[pebble-type]", - "inscribed", "elemental control"); + "inscribed", "elemental control"); addRule("[stone-type]", - "good-luck", "weight", - "blind-defense", "metal-clinging"); + "good-luck", "weight", + "blind-defense", "metal-clinging"); addRule("[brick-type]", - "flying"); + "flying"); addRule("[geode-type]", - "ioun"); + "ioun"); } private void addRopeRules() { addRule("[rope]", - "[rope-type] rope", "rope of [rope-type]", - "ball of [string-type] [string-kind]"); + "[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"); - addRule("[string-type]", - "endless"); + "trick", "entangling", "climbing", "dancing", + "tripping", "snaring", "levitating", "self-entangling"); + addRule("[string-type]", + "endless"); addRule("[string-kind]", - "string", "yarn"); + "string", "yarn"); } private void addRule(String rule, String... cases) { @@ -189,31 +189,31 @@ public class ZadronsPouch { private void addVialRules() { addRule("[vial]", - "vial of [vial-type]", "[vial-type] vial", - "[bottle-type] bottle", "[flask-type] flask"); + "vial of [vial-type]", "[vial-type] vial", + "[bottle-type] bottle", "[flask-type] flask"); addRule("[vial-type]", - "holding", "trapping", - "experience", "unnatural regeneration"); + "holding", "trapping", + "experience", "unnatural regeneration"); addRule("[bottle-type]", - "ever-smoking", "wheezing", - "blank potion"); + "ever-smoking", "wheezing", + "blank potion"); addRule("[flask-type]", - "iron"); + "iron"); } private void addWandRules() { addRule("[wand]", - "[wand-type] wand", "wand of [wand-type]", - "canceling [wand-type] wand"); + "[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", - "illumination", "polymorphing", "conjuration", "paralyzing"); + "frost", "fire", "lightning", "fear", + "illumination", "polymorphing", "conjuration", "paralyzing"); addRule("[spell-2]", - "[spell2-type] detecting"); + "[spell2-type] detecting"); addRule("[spell2-type]", - "magic", "enemy", "secret door/trap"); + "magic", "enemy", "secret door/trap"); } } diff --git a/RGens/src/main/java/bjc/rgens/newparser/CaseElement.java b/RGens/src/main/java/bjc/rgens/newparser/CaseElement.java index 5f798aa..8a5454b 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/CaseElement.java +++ b/RGens/src/main/java/bjc/rgens/newparser/CaseElement.java @@ -4,13 +4,13 @@ import static bjc.rgens.newparser.CaseElement.ElementType.*; /** * A element in a rule case. - * + * * @author EVE */ public class CaseElement { /** * The possible types of an element. - * + * * @author EVE * */ @@ -38,9 +38,9 @@ public class CaseElement { EXPVARDEF; } - private static final String SPECIAL_CASELEM = "\\{[^}]+\\}"; - private static final String REFER_CASELEM = "\\[[^\\]]+\\]"; - private static final String RANGE_CASELM = "\\[\\d+\\.\\.\\d+\\]"; + 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. @@ -49,10 +49,10 @@ public class CaseElement { /** * The literal string value of this element. - * + * * This means that it is a string whose value should always mean the * same thing. - * + * * <h2>Used For</h2> * <dl> * <dt>LITERAL</dt> @@ -65,7 +65,7 @@ public class CaseElement { /** * The starting integer value of this element. - * + * * <h2>Used For</h2> * <dl> * <dt>RANGE</dt> @@ -76,7 +76,7 @@ public class CaseElement { /** * The starting integer value of this element. - * + * * <h2>Used For</h2> * <dl> * <dt>RANGE</dt> @@ -87,7 +87,7 @@ public class CaseElement { /** * The name of the variable this element defines. - * + * * <h2>Used For</h2> * <dl> * <dt>VARDEF</dt> @@ -100,7 +100,7 @@ public class CaseElement { /** * The definition of the variable this element defines. - * + * * <h2>Used For</h2> * <dl> * <dt>VARDEF</dt> @@ -113,23 +113,26 @@ public class CaseElement { /** * Create a new case element. - * + * * @param typ * The type of this element. - * + * * @throws IllegalArgumentException * If the specified type needs parameters. */ public CaseElement(ElementType typ) { - switch(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; } @@ -139,27 +142,30 @@ public class CaseElement { /** * Create a new case element that has a single string value. - * + * * @param typ * The type of this element. - * + * * @param val * The string value of this element. - * + * * @throws IllegalArgumentException * If the specified type doesn't take a single string * parameter. */ public CaseElement(ElementType typ, String val) { - switch(typ) { + 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"); } @@ -171,28 +177,31 @@ public class CaseElement { /** * Create a new case element that has two integer values. - * + * * @param typ * The type of this element. * @param first * The first integer value for this element. * @param second * The second integer value for this element. - * + * * @throws IllegalArgumentException * If the specified type doesn't take two integer * parameters. */ public CaseElement(ElementType typ, int first, int second) { - switch(typ) { + 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"); } @@ -205,28 +214,31 @@ public class CaseElement { /** * Create a new case element that has two string values. - * + * * @param typ * The type of this element. * @param name * The first string value for this element. * @param def * The second string value for this element. - * + * * @throws IllegalArgumentException * If the specified type doesn't take two string * parameters. */ public CaseElement(ElementType typ, String name, String def) { - switch(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: break; + default: throw new IllegalArgumentException("This type doesn't have two string parameters"); } @@ -239,19 +251,21 @@ public class CaseElement { /** * Get 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. */ public String getLiteral() { - switch(type) { + switch (type) { case LITERAL: case RULEREF: break; + default: - throw new IllegalStateException(String.format("Type '%s' doesn't have a literal string value")); + throw new IllegalStateException( + String.format("Type '%s' doesn't have a literal string value")); } return literalVal; @@ -259,39 +273,42 @@ public class CaseElement { /** * Get 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. */ public int getStart() { - switch(type) { + switch (type) { case RANGE: break; + default: throw new IllegalStateException( - String.format("Type '%s' doesn't have a starting integer value", type)); + String.format("Type '%s' doesn't have a starting integer value", type)); } + return start; } /** * Get 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. */ public int getEnd() { - switch(type) { + switch (type) { case RANGE: break; + default: throw new IllegalStateException( - String.format("Type '%s' doesn't have a ending integer value", type)); + String.format("Type '%s' doesn't have a ending integer value", type)); } return end; @@ -299,17 +316,18 @@ public class CaseElement { /** * Get the variable name for this element. - * + * * @return The variable name of this element. - * + * * @throws IllegalStateException * If the type doesn't have a variable name. */ public String getName() { - switch(type) { + switch (type) { case VARDEF: case EXPVARDEF: break; + default: throw new IllegalStateException(String.format("Type '%s' doesn't have a name", type)); } @@ -319,17 +337,18 @@ public class CaseElement { /** * Get the variable definition for this element. - * + * * @return The variable definition of this element. - * + * * @throws IllegalStateException * If the type doesn't have a variable definition. */ public String getDefn() { - switch(type) { + switch (type) { case VARDEF: case EXPVARDEF: break; + default: throw new IllegalStateException(String.format("Type '%s' doesn't have a name", type)); } @@ -339,16 +358,20 @@ public class CaseElement { @Override public String toString() { - switch(type) { + switch (type) { 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); } @@ -356,36 +379,36 @@ public class CaseElement { /** * Create a case element from a string. - * + * * @param csepart * The string to convert. - * + * * @return A case element representing the string. */ public static CaseElement createElement(String csepart) { - if(csepart == null) { + if (csepart == null) { throw new NullPointerException("Case part cannot be null"); } - if(csepart.matches(SPECIAL_CASELEM)) { + if (csepart.matches(SPECIAL_CASELEM)) { /* * Handle special cases. */ String specialBody = csepart.substring(1, csepart.length() - 1); - if(specialBody.matches("\\S+:=\\S+")) { + if (specialBody.matches("\\S+:=\\S+")) { /* * Handle expanding variable definitions. */ String[] parts = specialBody.split(":="); - if(parts.length != 2) { + if (parts.length != 2) { throw new GrammarException("Expanded variables must be a name and a definition," - + " seperated by :="); + + " seperated by :="); } return new CaseElement(EXPVARDEF, parts[0], parts[1]); - } else if(specialBody.matches("\\S+=\\S+")) { + } else if (specialBody.matches("\\S+=\\S+")) { /* * Handle regular variable definitions. */ @@ -394,23 +417,23 @@ public class CaseElement { */ String[] parts = specialBody.split("="); - if(parts.length != 2) { + if (parts.length != 2) { throw new GrammarException("Variables must be a name and a definition," - + " seperated by ="); + + " seperated by ="); } return new CaseElement(VARDEF, parts[0], parts[1]); - } else if(specialBody.matches("{empty}")) { + } else if (specialBody.matches("{empty}")) { /* * Literal blank, for empty cases. */ return new CaseElement(LITERAL, ""); } else { throw new IllegalArgumentException( - String.format("Unknown special case part '%s'", specialBody)); + String.format("Unknown special case part '%s'", specialBody)); } - } else if(csepart.matches(REFER_CASELEM)) { - if(csepart.matches(RANGE_CASELM)) { + } else if (csepart.matches(REFER_CASELEM)) { + if (csepart.matches(RANGE_CASELM)) { /* * Handle ranges */ @@ -421,7 +444,7 @@ public class CaseElement { return new CaseElement(RANGE, firstNum, secondNum); } - + return new CaseElement(RULEREF, csepart); } else { return new CaseElement(LITERAL, csepart); diff --git a/RGens/src/main/java/bjc/rgens/newparser/GrammarException.java b/RGens/src/main/java/bjc/rgens/newparser/GrammarException.java index c9f2723..ac37f7a 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/GrammarException.java +++ b/RGens/src/main/java/bjc/rgens/newparser/GrammarException.java @@ -3,7 +3,7 @@ package bjc.rgens.newparser; /** * The exception thrown when something goes wrong while parsing a * grammar. - * + * * @author student * */ @@ -15,7 +15,7 @@ public class GrammarException extends RuntimeException { /** * Create a new grammar exception with the specified message. - * + * * @param msg * The message for this exception. */ @@ -26,10 +26,10 @@ public class GrammarException extends RuntimeException { /** * Create a new grammar exception with the specified message and * cause. - * + * * @param msg * The message for this exception. - * + * * @param cause * The cause of this exception. */ diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammar.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammar.java index 5f1c3aa..2c389a5 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammar.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammar.java @@ -19,7 +19,7 @@ import edu.gatech.gtri.bktree.MutableBkTree; /** * Represents a randomized grammar. - * + * * @author EVE * */ @@ -43,8 +43,8 @@ public class RGrammar { } private static class GenerationState { - public StringBuilder contents; - public Random rnd; + public StringBuilder contents; + public Random rnd; public Map<String, String> vars; @@ -57,16 +57,16 @@ public class RGrammar { private static Pattern NAMEVAR_PATTERN = Pattern.compile("\\$(\\w+)"); - private Map<String, Rule> rules; - private Map<String, RGrammar> importRules; - private Set<String> exportRules; - private String initialRule; + private Map<String, Rule> rules; + private Map<String, RGrammar> importRules; + private Set<String> exportRules; + private String initialRule; private BkTreeSearcher<String> ruleSearcher; /** * Create a new randomized grammar using the specified set of rules. - * + * * @param ruls * The rules to use. */ @@ -76,10 +76,10 @@ public class RGrammar { /** * Sets the imported rules to use. - * + * * Imported rules are checked for rule definitions after local * definitions are checked. - * + * * @param exportedRules * The set of imported rules to use. */ @@ -104,11 +104,11 @@ public class RGrammar { /** * Generate a string from this grammar, starting from the specified * rule. - * + * * @param startRule * The rule to start generating at, or null to use the * initial rule for this grammar. - * + * * @return A possible string from the grammar. */ public String generate(String startRule) { @@ -118,17 +118,17 @@ public class RGrammar { /** * Generate a string from this grammar, starting from the specified * rule. - * + * * @param startRule * The rule to start generating at, or null to use the * initial rule for this grammar. - * + * * @param rnd * The random number generator to use. - * + * * @param vars * The set of variables to use. - * + * * @return A possible string from the grammar. */ public String generate(String startRule, Random rnd, Map<String, String> vars) { @@ -137,7 +137,7 @@ public class RGrammar { if (startRule == null) { if (initialRule == null) { throw new GrammarException( - "Must specify a start rule for grammars with no initial rule"); + "Must specify a start rule for grammars with no initial rule"); } fromRule = initialRule; @@ -166,7 +166,9 @@ public class RGrammar { for (CaseElement elm : start.getElements()) { generateElement(elm, state); } + break; + default: throw new GrammarException(String.format("Unknown case type '%s'", start.type)); } @@ -185,9 +187,11 @@ 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(); @@ -198,17 +202,21 @@ 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: throw new GrammarException(String.format("Unknown element type '%s'", elm.type)); } } catch (GrammarException gex) { - throw new GrammarException(String.format("Error in generating case element (%s)", elm), gex); + throw new GrammarException(String.format("Error in generating case element (%s)", elm), + gex); } } @@ -216,7 +224,8 @@ public class RGrammar { * 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(); @@ -247,7 +256,8 @@ public class RGrammar { 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("$")) { /* @@ -268,17 +278,17 @@ public class RGrammar { if (!state.vars.containsKey(var)) { throw new GrammarException( - String.format("No variable '%s' defined", var)); + String.format("No variable '%s' defined", var)); } String name = state.vars.get(var); if (name.contains(" ")) { throw new GrammarException( - "Variables substituted into names cannot contain spaces"); + "Variables substituted into names cannot contain spaces"); } else if (name.equals("")) { throw new GrammarException( - "Variables substituted into names cannot be empty"); + "Variables substituted into names cannot be empty"); } nameMatcher.appendReplacement(nameBuffer, name); @@ -320,10 +330,10 @@ public class RGrammar { Set<Match<? extends String>> results = ruleSearcher.search(refersTo, MAX_DISTANCE); String[] resArray = results.stream().map((mat) -> mat.getMatch()) - .toArray((i) -> new String[i]); + .toArray((i) -> new String[i]); throw new GrammarException(String.format("No rule '%s' defined (perhaps you meant %s?)", - refersTo, StringUtils.toEnglishList(resArray, false))); + refersTo, StringUtils.toEnglishList(resArray, false))); } throw new GrammarException(String.format("No rule '%s' defined", refersTo)); @@ -341,7 +351,7 @@ public class RGrammar { /** * Get the initial rule of this grammar. - * + * * @return The initial rule of this grammar. */ public String getInitialRule() { @@ -350,7 +360,7 @@ 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. @@ -368,7 +378,7 @@ public class RGrammar { throw new GrammarException("The empty string is not a valid rule name"); } else if (!rules.containsKey(initRule)) { throw new GrammarException( - String.format("No rule '%s' local to this grammar defined.", initRule)); + String.format("No rule '%s' local to this grammar defined.", initRule)); } initialRule = initRule; @@ -376,9 +386,9 @@ public class RGrammar { /** * Gets the rules exported by this grammar. - * + * * The initial rule is exported by default if specified. - * + * * @return The rules exported by this grammar. */ public Set<Rule> getExportedRules() { @@ -387,7 +397,7 @@ public class RGrammar { for (String rname : exportRules) { if (!rules.containsKey(rname)) { throw new GrammarException(String.format("No rule '%s' local to this grammar defined", - initialRule)); + initialRule)); } res.add(rules.get(rname)); @@ -402,7 +412,7 @@ public class RGrammar { /** * Set the rules exported by this grammar. - * + * * @param exportedRules * The rules exported by this grammar. */ @@ -412,7 +422,7 @@ public class RGrammar { /** * Get all the rules in this grammar. - * + * * @return All the rules in this grammar. */ public Map<String, Rule> getRules() { diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarBuilder.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarBuilder.java index d71578b..b4f9f45 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarBuilder.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarBuilder.java @@ -12,7 +12,7 @@ import static bjc.rgens.newparser.RuleCase.CaseType.*; /** * Construct randomized grammars piece by piece. - * + * * @author EVE * */ @@ -40,20 +40,20 @@ public class RGrammarBuilder { /** * Starts a rule with the provided name. - * + * * If the rule already exists, it will be opened for adding additional * cases instead. - * + * * @param rName * The name of the rule currently being built. - * + * * @throws IllegalArgumentException * If the rule name is the empty string. */ public void startRule(String rName) { - if(rName == null) { + if (rName == null) { throw new NullPointerException("Rule name must not be null"); - } else if(rName.equals("")) { + } else if (rName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid rule name"); } @@ -62,7 +62,7 @@ public class RGrammarBuilder { /** * Convert this builder into a grammar. - * + * * @return The grammar built by this builder */ public RGrammar toRGrammar() { @@ -77,7 +77,7 @@ public class RGrammarBuilder { /** * Adds a case part to this rule. - * + * * <h2>Case part formatting</h2> * <dl> * <dt>Rule Reference</dt> @@ -86,7 +86,7 @@ public class RGrammarBuilder { * <dt>Literal Strings</dt> * <dd>Literal strings are the default case part type.</dd> * </dl> - * + * * @param csepart */ public void addCasePart(String csepart) { @@ -97,14 +97,14 @@ public class RGrammarBuilder { /** * Finalizes editing a rule. - * + * * Saves the rule to the rule map. - * + * * @throws IllegalStateException * Must be invoked while a rule is being edited. */ public void finishRule() { - if(currRule == null) { + if (currRule == null) { throw new IllegalStateException("Must start a rule before finishing one"); } @@ -113,12 +113,12 @@ public class RGrammarBuilder { /** * Finishes the current case being edited. - * + * * @throws IllegalStateException * Must be invoked while a rule is being edited. */ public void finishCase() { - if(currRule == null) { + if (currRule == null) { throw new IllegalStateException("Must start a rule before finishing a case"); } @@ -129,30 +129,30 @@ public class RGrammarBuilder { /** * Begins a case for the current rule. - * + * * @throws IllegalStateException * Must be invoked while a rule is being edited. */ public void beginCase() { - if(currRule == null) { + if (currRule == null) { throw new IllegalStateException("Must start a rule before adding cases"); } } /** * Set the initial rule of the grammar. - * + * * @param init * The initial rule of the grammar. - * + * * @throws IllegalArgumentException * If the rule is either not valid or not defined in the * grammar. */ public void setInitialRule(String init) { - if(init == null) { + if (init == null) { throw new NullPointerException("init must not be null"); - } else if(init.equals("")) { + } else if (init.equals("")) { throw new IllegalArgumentException("The empty string is not a valid rule name"); } @@ -161,18 +161,18 @@ public class RGrammarBuilder { /** * Add an exported rule to this grammar. - * + * * @param export * The name of the rule to export. - * + * * @throws IllegalArgumentException * If the rule is either not valid or not defined in the * grammar. */ public void addExport(String export) { - if(export == null) { + if (export == null) { throw new NullPointerException("Export name must not be null"); - } else if(export.equals("")) { + } else if (export.equals("")) { throw new NullPointerException("The empty string is not a valid rule name"); } @@ -181,54 +181,54 @@ public class RGrammarBuilder { /** * Suffix a given case element to every case of a specific rule. - * + * * @param ruleName * The rule to suffix. - * + * * @param suffix * 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. */ public void suffixWith(String ruleName, String suffix) { - if(ruleName == null) { + if (ruleName == null) { throw new NullPointerException("Rule name must not be null"); - } else if(ruleName.equals("")) { + } else if (ruleName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid rule name"); } CaseElement element = CaseElement.createElement(suffix); - for(RuleCase ruleCase : rules.get(ruleName).getCases()) { + for (RuleCase ruleCase : rules.get(ruleName).getCases()) { ruleCase.getElements().add(element); } } /** * Prefix a given case element to every case of a specific rule. - * + * * @param ruleName * The rule to prefix. - * + * * @param prefix * 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. */ public void prefixWith(String ruleName, String prefix) { - if(ruleName == null) { + if (ruleName == null) { throw new NullPointerException("Rule name must not be null"); - } else if(ruleName.equals("")) { + } else if (ruleName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid rule name"); } CaseElement element = CaseElement.createElement(prefix); - for(RuleCase ruleCase : rules.get(ruleName).getCases()) { + for (RuleCase ruleCase : rules.get(ruleName).getCases()) { ruleCase.getElements().add(element); } } diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarFormatter.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarFormatter.java index 202d9ef..168fb7b 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarFormatter.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarFormatter.java @@ -8,17 +8,17 @@ 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. - * + * * @return The formatted grammar. */ public static String formatGrammar(RGrammar gram) { @@ -30,16 +30,16 @@ public class RGrammarFormatter { Set<String> processedRules = new HashSet<>(); - if(initRuleName != null) { + if (initRuleName != null) { processRule(rules.get(initRuleName), sb); processedRules.add(initRuleName); } - for(Rule rule : rules.values()) { - if(!processedRules.contains(rule.name)) { + for (Rule rule : rules.values()) { + if (!processedRules.contains(rule.name)) { sb.append("\n\n"); - + processRule(rule, sb); } @@ -65,10 +65,10 @@ public class RGrammarFormatter { ruleBuilder = new StringBuilder(); - for(RuleCase cse : cases.tail()) { + for (RuleCase cse : cases.tail()) { sb.append("\n\t"); - for(int i = 8; i < markerPos; i++) { + for (int i = 8; i < markerPos; i++) { ruleBuilder.append(" "); } @@ -85,7 +85,7 @@ public class RGrammarFormatter { /* * Process each element, adding a space. */ - for(CaseElement element : cse.getElements()) { + for (CaseElement element : cse.getElements()) { sb.append(element.toString()); sb.append(" "); } diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarParser.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarParser.java index 51aeb78..9717eee 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarParser.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarParser.java @@ -12,7 +12,7 @@ import java.util.Map; /** * Reads {@link RGrammar} from a input stream. - * + * * @author student * */ @@ -59,7 +59,7 @@ public class RGrammarParser { if (parts.length != 2) { throw new GrammarException("Suffix-with pragma takes two arguments," - + " the name of the rule to suffix, then what to suffix it with"); + + " the name of the rule to suffix, then what to suffix it with"); } String name = parts[0]; @@ -77,7 +77,7 @@ public class RGrammarParser { if (parts.length != 2) { throw new GrammarException("Prefix-with pragma takes two arguments," - + " the name of the rule to prefix, then what to prefix it with"); + + " the name of the rule to prefix, then what to prefix it with"); } String name = parts[0]; @@ -93,17 +93,18 @@ public class RGrammarParser { /** * Read a {@link RGrammar} from an input stream. - * + * * @param is * The input stream to read from. - * + * * @return The grammar represented by the stream. - * + * * @throws GrammarException * Thrown if the grammar has a syntax error. */ public static RGrammar readGrammar(Reader is) throws GrammarException { - try (BlockReader reader = new SimpleBlockReader(String.format(TMPL_TOPLEVEL_BLOCK_DELIM, 0), is)) { + try (BlockReader reader = new SimpleBlockReader(String.format(TMPL_TOPLEVEL_BLOCK_DELIM, + 0), is)) { if (!reader.hasNextBlock()) { throw new GrammarException("At least one top-level block must be present"); } @@ -131,14 +132,17 @@ public class RGrammarParser { /* * Handles an arbitrary block. */ - private static void handleBlock(RGrammarBuilder build, String block, int level) throws GrammarException { + private static void handleBlock(RGrammarBuilder build, String block, + int level) throws GrammarException { /* * Discard empty blocks */ if (block.equals("")) return; + if (block.equals("\n")) return; + if (block.equals("\r\n")) return; @@ -146,7 +150,7 @@ public class RGrammarParser { if (typeSep == -1) { throw new GrammarException( - "A block must start with a type, followed by a space, then the rest of the block"); + "A block must start with a type, followed by a space, then the rest of the block"); } String blockType = block.substring(0, typeSep); @@ -170,9 +174,11 @@ public class RGrammarParser { /* * Handle reading a block of pragmas. */ - private static void handlePragmaBlock(String block, RGrammarBuilder build, int level) throws GrammarException { - try (BlockReader pragmaReader = new SimpleBlockReader(String.format(TMPL_PRAGMA_BLOCK_DELIM, level), - new StringReader(block))) { + private static void handlePragmaBlock(String block, RGrammarBuilder build, + int level) throws GrammarException { + try (BlockReader pragmaReader = new SimpleBlockReader(String.format( + TMPL_PRAGMA_BLOCK_DELIM, level), + new StringReader(block))) { try { pragmaReader.forEachBlock((pragma) -> { String pragmaContents = pragma.contents; @@ -181,7 +187,7 @@ public class RGrammarParser { if (pragmaSep == -1) { throw new GrammarException("A pragma invocation must consist of the word pragma," - + " followed by a space, then the body of the pragma"); + + " followed by a space, then the body of the pragma"); } String pragmaLeader = pragmaContents.substring(0, pragmaSep); @@ -189,7 +195,7 @@ public class RGrammarParser { if (!pragmaLeader.equalsIgnoreCase("pragma")) { throw new GrammarException( - String.format("Illegal line leader in pragma block: '%s'", pragmaLeader)); + String.format("Illegal line leader in pragma block: '%s'", pragmaLeader)); } handlePragma(pragmaBody, build, level); @@ -207,7 +213,8 @@ public class RGrammarParser { /*msg * Handle an individual pragma in a block. */ - private static void handlePragma(String pragma, RGrammarBuilder build, int level) throws GrammarException { + private static void handlePragma(String pragma, RGrammarBuilder build, + int level) throws GrammarException { int bodySep = pragma.indexOf(' '); if (bodySep == -1) @@ -230,9 +237,11 @@ public class RGrammarParser { /* * Handle a block of a rule declaration and one or more cases. */ - private static void handleRuleBlock(String ruleBlock, RGrammarBuilder build, int level) throws GrammarException { - try (BlockReader ruleReader = new SimpleBlockReader(String.format(TMPL_RULEDECL_BLOCK_DELIM, level), - new StringReader(ruleBlock))) { + private static void handleRuleBlock(String ruleBlock, RGrammarBuilder build, + int level) throws GrammarException { + try (BlockReader ruleReader = new SimpleBlockReader(String.format( + TMPL_RULEDECL_BLOCK_DELIM, level), + new StringReader(ruleBlock))) { try { if (ruleReader.hasNextBlock()) { /* @@ -258,7 +267,8 @@ public class RGrammarParser { build.finishRule(); } } catch (GrammarException gex) { - throw new GrammarException(String.format("Error in rule case (%s)", ruleReader.getBlock()), gex); + throw new GrammarException(String.format("Error in rule case (%s)", + ruleReader.getBlock()), gex); } } catch (Exception ex) { throw new GrammarException("Unknown error handling rule block", ex); @@ -280,11 +290,11 @@ public class RGrammarParser { 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"); + + "seperated from that case by \u2192"); } System.out.println( - "WARNING: Empty space separating a declaration and its case is deprecated. Use \u2192 instead"); + "WARNING: Empty space separating a declaration and its case is deprecated. Use \u2192 instead"); } String ruleName = declContents.substring(0, declSep).trim(); @@ -323,21 +333,26 @@ public class RGrammarParser { /* * Handle a where block (a block with local rules). */ - private static void handleWhereBlock(String block, RGrammarBuilder build, int level) throws GrammarException { + private static void handleWhereBlock(String block, RGrammarBuilder build, + int level) throws GrammarException { int nlIndex = block.indexOf("\\n"); - if(nlIndex == -1) { + + if (nlIndex == -1) { throw new GrammarException("Where block must be a context followed by a body"); } - + String trimBlock = block.substring(nlIndex).trim(); - + String whereDelim = String.format(TMPL_WHERE_BLOCK_DELIM, level); - try (BlockReader whereReader = new SimpleBlockReader(whereDelim, new StringReader(trimBlock))) { + + try (BlockReader whereReader = new SimpleBlockReader(whereDelim, + new StringReader(trimBlock))) { try { Block whereCtx = whereReader.next(); StringReader ctxReader = new StringReader(whereCtx.contents.trim()); String ctxDelim = String.format(TMPL_TOPLEVEL_BLOCK_DELIM, level + 1); + try (BlockReader bodyReader = new SimpleBlockReader(ctxDelim, ctxReader)) { } @@ -346,12 +361,13 @@ public class RGrammarParser { /** * TODO implement where blocks. - * + * * 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)", whereReader.getBlock()), gex); + throw new GrammarException(String.format("Error in where block (%s)", + whereReader.getBlock()), gex); } } catch (Exception ex) { throw new GrammarException("Unknown error in where block", ex); diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarSet.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarSet.java index 452c5f5..e1b9823 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarSet.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarSet.java @@ -12,7 +12,7 @@ import java.util.Set; /** * Represents a set of grammars that can share rules via exports. - * + * * @author EVE * */ @@ -51,28 +51,28 @@ public class RGrammarSet { /** * Add a grammar to this grammar set. - * + * * @param grammarName * The name of the grammar to add. - * + * * @param gram * The grammar to add. - * + * * @throws IllegalArgumentException * If the grammar name is invalid. */ public void addGrammar(String grammarName, RGrammar gram) { - if(grammarName == null) { + if (grammarName == null) { throw new NullPointerException("Grammar name must not be null"); - } else if(gram == null) { + } else if (gram == null) { throw new NullPointerException("Grammar must not be null"); - } else if(grammarName.equals("")) { + } else if (grammarName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid grammar name"); } grammars.put(grammarName, gram); - for(Rule export : gram.getExportedRules()) { + for (Rule export : gram.getExportedRules()) { exportedRules.put(export.name, gram); exportFrom.put(export.name, grammarName); } @@ -82,24 +82,24 @@ public class RGrammarSet { /** * Get a grammar from this grammar set. - * + * * @param grammarName * The name of the grammar to get. - * + * * @return The grammar with that name. - * + * * @throws IllegalArgumentException * If the grammar name is invalid or not present in this * set. */ public RGrammar getGrammar(String grammarName) { - if(grammarName == null) { + if (grammarName == null) { throw new NullPointerException("Grammar name must not be null"); - } else if(grammarName.equals("")) { + } else if (grammarName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid grammar name"); - } else if(!grammars.containsKey(grammarName)) { + } else if (!grammars.containsKey(grammarName)) { throw new IllegalArgumentException( - String.format("No grammar with name '%s' found", grammarName)); + String.format("No grammar with name '%s' found", grammarName)); } return grammars.get(grammarName); @@ -107,24 +107,24 @@ public class RGrammarSet { /** * Get the grammar a rule was exported from. - * + * * @param exportName * The name of the exported rule. - * + * * @return The grammar the exported rule came from. - * + * * @throws IllegalArgumentException * If the export name is invalid or not present in this * set. */ public RGrammar getExportSource(String exportName) { - if(exportName == null) { + if (exportName == null) { throw new NullPointerException("Export name must not be null"); - } else if(exportName.equals("")) { + } else if (exportName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid rule name"); - } else if(!exportedRules.containsKey(exportName)) { + } else if (!exportedRules.containsKey(exportName)) { throw new IllegalArgumentException( - String.format("No export with name '%s' defined", exportName)); + String.format("No export with name '%s' defined", exportName)); } return exportedRules.get(exportName); @@ -132,26 +132,26 @@ public class RGrammarSet { /** * Get the source of an exported rule. - * + * * This will often be a grammar name, but is not required to be one. - * + * * @param exportName * The name of the exported rule. - * + * * @return The source of an exported rule. - * + * * @throws IllegalArgumentException * If the exported rule is invalid or not present in * this set. */ public String exportedFrom(String exportName) { - if(exportName == null) { + if (exportName == null) { throw new NullPointerException("Export name must not be null"); - } else if(exportName.equals("")) { + } else if (exportName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid rule name"); - } else if(!exportedRules.containsKey(exportName)) { + } else if (!exportedRules.containsKey(exportName)) { throw new IllegalArgumentException( - String.format("No export with name '%s' defined", exportName)); + String.format("No export with name '%s' defined", exportName)); } return exportFrom.getOrDefault(exportName, "unknown"); @@ -159,29 +159,29 @@ public class RGrammarSet { /** * Get the source of an grammar - * + * * This will often be a file name, but is not required to be one. - * + * * @param grammarName * The name of the exported grammar. - * + * * @return The source of an exported grammar. - * + * * @throws IllegalArgumentException * If the exported grammar is invalid or not present in * this set. */ public String loadedFrom(String grammarName) { - if(grammarName == null) { + if (grammarName == null) { throw new NullPointerException("Grammar name must not be null"); - } else if(grammarName.equals("")) { + } else if (grammarName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid grammar name"); - } else if(grammarName.equals("unknown")) { + } else if (grammarName.equals("unknown")) { return grammarName; - } else if(!grammars.containsKey(grammarName)) { + } else if (!grammars.containsKey(grammarName)) { throw new IllegalArgumentException( - String.format("No grammar with name '%s' defined", grammarName)); + String.format("No grammar with name '%s' defined", grammarName)); } return loadedFrom.getOrDefault(grammarName, "unknown"); @@ -189,7 +189,7 @@ public class RGrammarSet { /** * Get the names of all the grammars in this set. - * + * * @return The names of all the grammars in this set. */ public Set<String> getGrammars() { @@ -198,7 +198,7 @@ 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. */ public Set<String> getExportedRules() { @@ -207,12 +207,12 @@ public class RGrammarSet { /** * Load a grammar set from a configuration file. - * + * * @param cfgFile * The configuration file to load from. - * + * * @return The grammar set created by the configuration file. - * + * * @throws IOException * If something goes wrong during configuration loading. */ @@ -225,14 +225,15 @@ public class RGrammarSet { /* * Execute lines from the configuration file. */ - while(scn.hasNextLine()) { + while (scn.hasNextLine()) { String ln = scn.nextLine().trim(); /* * Ignore blank/comment lines. */ - if(ln.equals("")) continue; - if(ln.startsWith("#")) continue; + if (ln.equals("")) continue; + + if (ln.startsWith("#")) continue; /* * Handle mixed whitespace @@ -241,7 +242,7 @@ public class RGrammarSet { int nameIdx = ln.indexOf(" "); - if(nameIdx == -1) { + if (nameIdx == -1) { throw new GrammarException("Must specify a name for a loaded grammar"); } @@ -258,12 +259,12 @@ public class RGrammarSet { File fle = convPath.toFile(); - if(fle.isDirectory()) { + if (fle.isDirectory()) { /* * TODO implement subset grammars */ throw new GrammarException("Sub-grammar sets aren't implemented yet"); - } else if(fle.getName().endsWith(".gram")) { + } else if (fle.getName().endsWith(".gram")) { /* * Load grammar files. */ @@ -271,13 +272,13 @@ public class RGrammarSet { FileReader fis = new FileReader(fle); RGrammar gram = RGrammarParser.readGrammar(fis); fis.close(); - + set.addGrammar(name, gram); set.loadedFrom.put(name, path.toString()); - } catch(GrammarException gex) { + } catch (GrammarException gex) { throw new GrammarException( - String.format("Error loading file '%s'", path), gex); + String.format("Error loading file '%s'", path), gex); } } else { throw new GrammarException(String.format("Unrecognized file '%s'")); diff --git a/RGens/src/main/java/bjc/rgens/newparser/RGrammarTest.java b/RGens/src/main/java/bjc/rgens/newparser/RGrammarTest.java index 7d8ed9c..7bfd762 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RGrammarTest.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RGrammarTest.java @@ -7,14 +7,14 @@ import java.nio.file.Paths; /** * Test for new grammar syntax. - * + * * @author EVE * */ public class RGrammarTest { /** * Main method. - * + * * @param args * Unused CLI args. */ @@ -24,20 +24,20 @@ public class RGrammarTest { try { RGrammarSet gramSet = RGrammarSet.fromConfigFile(Paths.get(rsc.toURI())); - for(String gramName : gramSet.getGrammars()) { + for (String gramName : gramSet.getGrammars()) { gramSet.getGrammar(gramName).generateSuggestions(); } - for(String exportName : gramSet.getExportedRules()) { + for (String exportName : gramSet.getExportedRules()) { RGrammar grammar = gramSet.getExportSource(exportName); - for(int i = 0; i < 10; i++) { + for (int i = 0; i < 10; i++) { try { grammar.generate(exportName); - } catch(GrammarException gex) { + } catch (GrammarException gex) { System.out.println("Error in exported rule " + exportName - + " (loaded from " - + gramSet.loadedFrom(gramSet.exportedFrom(exportName))); + + " (loaded from " + + gramSet.loadedFrom(gramSet.exportedFrom(exportName))); System.out.println(); @@ -48,9 +48,9 @@ public class RGrammarTest { } } } - } catch(IOException ioex) { + } catch (IOException ioex) { ioex.printStackTrace(); - } catch(URISyntaxException urisex) { + } catch (URISyntaxException urisex) { urisex.printStackTrace(); } } diff --git a/RGens/src/main/java/bjc/rgens/newparser/Rule.java b/RGens/src/main/java/bjc/rgens/newparser/Rule.java index 0197860..aee1a89 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/Rule.java +++ b/RGens/src/main/java/bjc/rgens/newparser/Rule.java @@ -7,7 +7,7 @@ import java.util.Random; /** * A rule in a randomized grammar. - * + * * @author EVE * */ @@ -21,17 +21,17 @@ public class Rule { /** * Create a new grammar rule. - * + * * @param ruleName * The name of the grammar rule. - * + * * @throws IllegalArgumentException * If the rule name is invalid. */ public Rule(String ruleName) { - if(ruleName == null) { + if (ruleName == null) { throw new NullPointerException("Rule name must not be null"); - } else if(ruleName.equals("")) { + } else if (ruleName.equals("")) { throw new IllegalArgumentException("The empty string is not a valid rule name"); } @@ -42,12 +42,12 @@ public class Rule { /** * Adds a case to the rule. - * + * * @param cse * The case to add. */ public void addCase(RuleCase cse) { - if(cse == null) { + if (cse == null) { throw new NullPointerException("Case must not be null"); } @@ -56,7 +56,7 @@ public class Rule { /** * Get a random case from this rule. - * + * * @return A random case from this rule. */ public RuleCase getCase() { @@ -65,10 +65,10 @@ public class Rule { /** * Get a random case from this rule. - * + * * @param rnd * The random number generator to use. - * + * * @return A random case from this rule. */ public RuleCase getCase(Random rnd) { @@ -77,7 +77,7 @@ public class Rule { /** * Get all the cases of this rule. - * + * * @return All the cases in this rule. */ public IList<RuleCase> getCases() { @@ -97,19 +97,21 @@ public class Rule { @Override public boolean equals(Object obj) { - if(this == obj) return true; - if(obj == null) return false; - if(!(obj instanceof Rule)) return false; + if (this == obj) return true; + + if (obj == null) return false; + + if (!(obj instanceof Rule)) return false; Rule other = (Rule) obj; - if(cases == null) { - if(other.cases != null) return false; - } else if(!cases.equals(other.cases)) return false; + if (cases == null) { + if (other.cases != null) return false; + } else if (!cases.equals(other.cases)) return false; - if(name == null) { - if(other.name != null) return false; - } else if(!name.equals(other.name)) return false; + if (name == null) { + if (other.name != null) return false; + } else if (!name.equals(other.name)) return false; return true; } diff --git a/RGens/src/main/java/bjc/rgens/newparser/RuleCase.java b/RGens/src/main/java/bjc/rgens/newparser/RuleCase.java index 9652273..3f971c3 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/RuleCase.java +++ b/RGens/src/main/java/bjc/rgens/newparser/RuleCase.java @@ -4,13 +4,13 @@ import bjc.utils.funcdata.IList; /** * A case in a rule in a randomized grammar. - * + * * @author EVE */ public class RuleCase { /** * The possible types of a case. - * + * * @author EVE * */ @@ -28,7 +28,7 @@ public class RuleCase { /** * The list of element values for this case. - * + * * <h2>Used For</h2> * <dl> * <dt>NORMAL</dt> @@ -39,17 +39,18 @@ public class RuleCase { /** * Create a new case of the specified type. - * + * * @param typ * The type of case to create. - * + * * @throws IllegalArgumentException * If the type requires parameters. */ public RuleCase(CaseType typ) { - switch(typ) { + switch (typ) { case NORMAL: throw new IllegalArgumentException("This type requires an element list parameter"); + default: break; } @@ -60,20 +61,21 @@ public class RuleCase { /** * Create a new case of the specified type that takes a element list * parameter. - * + * * @param typ * The type of case to create. - * + * * @param elements * The element list parameter of the case. - * + * * @throws IllegalArgumentException * If this type doesn't take a element list parameter. */ public RuleCase(CaseType typ, IList<CaseElement> elements) { - switch(typ) { + switch (typ) { case NORMAL: break; + default: throw new IllegalArgumentException("This type doesn't have a element list parameter"); } @@ -85,7 +87,7 @@ 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. */ diff --git a/RGens/src/main/java/bjc/rgens/newparser/new-syntax.txt b/RGens/src/main/java/bjc/rgens/newparser/new-syntax.txt index 3e5738c..f6578b4 100644 --- a/RGens/src/main/java/bjc/rgens/newparser/new-syntax.txt +++ b/RGens/src/main/java/bjc/rgens/newparser/new-syntax.txt @@ -1,13 +1,13 @@ -[grammar] → ([block] (/\n\.\n?/ [block])*)? +[grammar] → ([block] ( / \n\.\n ? / [block])*) ? -[block] → [pragma-block] - → [rule-block] - → [where-block] +[block] → [pragma - block] +→ [rule - block] +→ [where - block] -[pragma-block] → [pragma] (/\n(?!\t)/ [pragma])* +[pragma - block] → [pragma] ( / \n( ? !\t) / [pragma])* -[rule-block] → [rule-decl] [rule-case] (/\n\t/ [rule-case])* +[rule - block] → [rule - decl] [rule - case] ( / \n\t / [rule - case])* -[where-block] -> where /\n\t/ ([rule-block] /\n\t/)+ in /\n\t/ [rule-block] +[where - block] → where / \n\t / ([rule - block] / \n\t / ) + in / \n\t / [rule - block] -[pragma] → pragma [pragma-name] [pragma-body] +[pragma] → pragma [pragma - name] [pragma - body] 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 9eb4134..df8b06c 100755..100644 --- a/RGens/src/main/java/bjc/rgens/text/markov/Markov.java +++ b/RGens/src/main/java/bjc/rgens/text/markov/Markov.java @@ -6,19 +6,19 @@ import java.util.*; /** * Represents a k-character substring. Can give a pseudo-random suffix character * based on probability. - * + * * @author Daniel Friedman (Fall 2011) * */ public class Markov { - String substring; - int count = 0; + String substring; + int count = 0; TreeMap<Character, Integer> map; /** * Constructs a Markov object from a given substring. - * + * * @param substr * the given substring. */ @@ -33,7 +33,7 @@ public class Markov { /** * Constructs a Markov object from a given substring and suffix * character. Suffix characters are stored in a TreeMap. - * + * * @param substr * the specified substring. * @param suffix @@ -57,7 +57,7 @@ public class Markov { /** * Adds a suffix character to the TreeMap. - * + * * @param c * the suffix character to be added. */ @@ -73,7 +73,7 @@ public class Markov { /** * Gives the frequency count of a suffix character; that is, the number * of times the specified suffix follows the substring in a text. - * + * * @param c * the specified suffix. * @return the frequency count. @@ -88,7 +88,7 @@ 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 @@ -103,7 +103,7 @@ 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. @@ -118,7 +118,7 @@ public class Markov { /** * Gives the number of times this substring occurs in a text. - * + * * @return said number of times. */ public int count() { @@ -127,7 +127,7 @@ public class Markov { /** * Gives the TreeMap. - * + * * @return the TreeMap. */ public TreeMap<Character, Integer> getMap() { @@ -142,7 +142,7 @@ public class Markov { * 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. */ public char random() { @@ -170,7 +170,7 @@ public class Markov { /** * Gives a String representation of the Markov object. - * + * * @return said String representation. */ @Override @@ -183,6 +183,7 @@ public class Markov { int value = entry.getValue(); ret += "\n" + "Suffix: " + key + ", frequency count: " + value; } + return ret; } } 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 8934daa..29f8446 100644 --- a/RGens/src/main/java/bjc/rgens/text/markov/StandaloneMarkov.java +++ b/RGens/src/main/java/bjc/rgens/text/markov/StandaloneMarkov.java @@ -4,25 +4,25 @@ import java.util.Map; /** * A standalone Markov generator. - * + * * @author bjculkin * */ public class StandaloneMarkov { private int ord; - private Map<String, Markov> hash; - private String first; + private Map<String, Markov> hash; + private String first; /** * Create a new standalone Markov generator. - * + * * @param order * The order of this generator. - * + * * @param markovHash * The generators to use. - * + * * @param firstSub * The string to start out with. */ @@ -34,10 +34,10 @@ public class StandaloneMarkov { /** * Generate random text from the markov generator. - * + * * @param charsToGenerate * The number of characters of text to generate. - * + * * @return The randomly generate text. */ public String generateTextFromMarkov(int charsToGenerate) { 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 17cd670..c6eea0d 100644 --- a/RGens/src/main/java/bjc/rgens/text/markov/StandaloneTextGenerator.java +++ b/RGens/src/main/java/bjc/rgens/text/markov/StandaloneTextGenerator.java @@ -7,20 +7,20 @@ 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. - * + * * @param reader * The source to seed the generator from. - * + * * @return The markov generator for the provided text. */ public static StandaloneMarkov generateMarkovMap(int order, Reader reader) { 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 7d20d79..0ec40df 100755..100644 --- a/RGens/src/main/java/bjc/rgens/text/markov/TextGenerator.java +++ b/RGens/src/main/java/bjc/rgens/text/markov/TextGenerator.java @@ -4,20 +4,20 @@ import java.io.*; /** * Generate text from a markov model of an input text - * + * * @author ben * */ 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 two arguments, the first represents the * k-order of the Markov objects, and the second * represents the file to be read. The generated text diff --git a/RGens/src/main/sql/db_schema.sql b/RGens/src/main/sql/db_schema.sql index 10df3f0..553c7a8 100644 --- a/RGens/src/main/sql/db_schema.sql +++ b/RGens/src/main/sql/db_schema.sql @@ -1,15 +1,15 @@ create table Rules ( - ruleid serial, - name varchar(255) not null, - casecount int, - primary key(id) + ruleid serial, + name varchar(255) not null, + casecount int, + primary key(id) ); create index Rules_name on Rules(name); create table RuleCases ( - ruleid serial, - cse varchar(255) array + ruleid serial, + cse varchar(255) array ); create index RuleCase_id on RuleCases(ruleid); |
