diff options
| author | EVE <EVE@EVE-PC> | 2017-03-13 16:41:45 -0400 |
|---|---|---|
| committer | EVE <EVE@EVE-PC> | 2017-03-13 16:41:45 -0400 |
| commit | 01136c6796e21f023713e026674576d8e623462d (patch) | |
| tree | e77886fe0e0adaf3c0430fba9ce248ef83f74fe4 | |
| parent | 870d769cfc152171d27b2331a7c590d0b307ad48 (diff) | |
Formatting
65 files changed, 1822 insertions, 1973 deletions
diff --git a/dice-lang/src/bjc/dicelang/CLIArgsParser.java b/dice-lang/src/bjc/dicelang/CLIArgsParser.java index de92ff1..702d20c 100644 --- a/dice-lang/src/bjc/dicelang/CLIArgsParser.java +++ b/dice-lang/src/bjc/dicelang/CLIArgsParser.java @@ -10,66 +10,77 @@ import static bjc.dicelang.Errors.ErrorKey.*; public class CLIArgsParser { public static boolean parseArgs(String[] args, DiceLangEngine eng) { - if(args.length < 0) return true; + if (args.length < 0) + return true; - if(args.length == 1 && (args[0].equals("--help") || args[0].equals("-h"))) { + if (args.length == 1 && (args[0].equals("--help") || args[0].equals("-h"))) { /* * @TODO show help */ System.exit(0); } - for(int i = 0; i < args.length; i++) { + for (int i = 0; i < args.length; i++) { String arg = args[i]; boolean succ = true; - switch(arg) { - case "-d": - case "--debug": - if(!eng.toggleDebug()) eng.toggleDebug(); - break; - case "-nd": - case "--no-debug": - if(eng.toggleDebug()) eng.toggleDebug(); - break; - case "-po": - case "--postfix": - if(!eng.togglePostfix()) eng.togglePostfix(); - break; - case "-npo": - case "--no-postfix": - if(eng.togglePostfix()) eng.togglePostfix(); - break; - case "-pr": - case "--prefix": - if(!eng.togglePrefix()) eng.togglePrefix(); - break; - case "-npr": - case "--no-prefix": - if(eng.togglePrefix()) eng.togglePrefix(); - break; - case "-se": - case "--stepeval": - if(!eng.toggleStepEval()) eng.toggleStepEval(); - break; - case "-nse": - case "--no-stepeval": - if(eng.toggleStepEval()) eng.toggleStepEval(); - break; - case "-D": - case "--define": - i = simpleDefine(i, args, eng); - if(i == -1) return false; - break; - case "-df": - case "--define-file": - i = defineFile(i, args, eng); - if(i == -1) return false; - break; - default: - Errors.inst.printError(EK_CLI_UNARG, arg); + switch (arg) { + case "-d": + case "--debug": + if (!eng.toggleDebug()) + eng.toggleDebug(); + break; + case "-nd": + case "--no-debug": + if (eng.toggleDebug()) + eng.toggleDebug(); + break; + case "-po": + case "--postfix": + if (!eng.togglePostfix()) + eng.togglePostfix(); + break; + case "-npo": + case "--no-postfix": + if (eng.togglePostfix()) + eng.togglePostfix(); + break; + case "-pr": + case "--prefix": + if (!eng.togglePrefix()) + eng.togglePrefix(); + break; + case "-npr": + case "--no-prefix": + if (eng.togglePrefix()) + eng.togglePrefix(); + break; + case "-se": + case "--stepeval": + if (!eng.toggleStepEval()) + eng.toggleStepEval(); + break; + case "-nse": + case "--no-stepeval": + if (eng.toggleStepEval()) + eng.toggleStepEval(); + break; + case "-D": + case "--define": + i = simpleDefine(i, args, eng); + if (i == -1) return false; + break; + case "-df": + case "--define-file": + i = defineFile(i, args, eng); + if (i == -1) + return false; + break; + default: + Errors.inst.printError(EK_CLI_UNARG, arg); + return false; } } @@ -77,47 +88,51 @@ public class CLIArgsParser { } private static int simpleDefine(int i, String[] args, DiceLangEngine eng) { - if(i >= (args.length - 1)) { + if (i >= (args.length - 1)) { Errors.inst.printError(EK_CLI_MISARG, "define"); return -1; } - if(i >= (args.length - 2)) { + if (i >= (args.length - 2)) { Define dfn = new Define(5, false, false, false, null, args[i + 1], Arrays.asList("")); - - if(dfn.inError) return -1; + + if (dfn.inError) + return -1; eng.addLineDefine(dfn); return i + 1; } Define dfn = new Define(5, false, false, false, null, args[i + 1], Arrays.asList(args[i + 2])); - if(dfn.inError) return -1; + if (dfn.inError) + return -1; eng.addLineDefine(dfn); return i + 2; } private static int defineFile(int i, String[] args, DiceLangEngine eng) { - if(i >= (args.length - 1)) { + if (i >= (args.length - 1)) { Errors.inst.printError(EK_CLI_MISARG, "define-file"); return -1; } String fName = args[i + 1]; - try(FileInputStream fis = new FileInputStream(fName)) { - try(Scanner scan = new Scanner(fis)) { - while(scan.hasNextLine()) { + try (FileInputStream fis = new FileInputStream(fName)) { + try (Scanner scan = new Scanner(fis)) { + while (scan.hasNextLine()) { String ln = scan.nextLine(); - + Define dfn = parseDefine(ln.substring(ln.indexOf(' '))); - if(dfn == null || dfn.inError) return -1; - - if(ln.startsWith("line")) { + if (dfn == null || dfn.inError) + return -1; + + if (ln.startsWith("line")) { eng.addLineDefine(dfn); - } else if(ln.startsWith("token")) { + } else if (ln.startsWith("token")) { eng.addTokenDefine(dfn); } else { - Errors.inst.printError(EK_CLI_INVDFNTYPE, ln.substring(0, ln.indexOf(' '))); + Errors.inst.printError(EK_CLI_INVDFNTYPE, + ln.substring(0, ln.indexOf(' '))); return -1; } } diff --git a/dice-lang/src/bjc/dicelang/Define.java b/dice-lang/src/bjc/dicelang/Define.java index e96a873..1e4d89b 100644 --- a/dice-lang/src/bjc/dicelang/Define.java +++ b/dice-lang/src/bjc/dicelang/Define.java @@ -11,11 +11,13 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; public class Define implements UnaryOperator<String>, Comparable<Define> { - public static enum Type { LINE, TOKEN } + public static enum Type { + LINE, TOKEN + } public static final int MAX_RECURS = 10; - public final int priority; + public final int priority; public final boolean inError; private boolean doRecur; @@ -24,20 +26,19 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { private Pattern predicate; private Pattern searcher; - private Iterator<String> replacers; - private String replacer; + private Iterator<String> replacers; + private String replacer; - public Define(int priorty, - boolean isSub, boolean recur, boolean isCircular, - String predicte, String searchr, Iterable<String> replacrs) { + public Define(int priorty, boolean isSub, boolean recur, boolean isCircular, String predicte, String searchr, + Iterable<String> replacrs) { priority = priorty; - doRecur = recur; - subType = isSub; + doRecur = recur; + subType = isSub; /* * Only try to compile non-null predicates */ - if(predicte != null) { + if (predicte != null) { try { predicate = Pattern.compile(predicte); } catch (PatternSyntaxException psex) { @@ -51,7 +52,7 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { * Compile the search pattern */ try { - searcher = Pattern.compile(searchr); + searcher = Pattern.compile(searchr); } catch (PatternSyntaxException psex) { Errors.inst.printError(EK_DFN_SRCSYN, psex.getMessage()); inError = true; @@ -62,8 +63,8 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { /* * Check whether or not we do sub-replacements */ - if(subType) { - if(replacrs.iterator().hasNext()) { + if (subType) { + if (replacrs.iterator().hasNext()) { replacers = new CircularIterator<>(replacrs, isCircular); } else { replacers = null; @@ -71,26 +72,29 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { } else { Iterator<String> itr = replacrs.iterator(); - if(itr.hasNext()) replacer = itr.next(); - else replacer = ""; + if (itr.hasNext()) + replacer = itr.next(); + else + replacer = ""; } } public String apply(String tok) { - if(inError) return tok; + if (inError) + return tok; - if(predicate != null) { - if(!predicate.matcher(tok).matches()) { + if (predicate != null) { + if (!predicate.matcher(tok).matches()) { return tok; } } String strang = doPass(tok); - if(doRecur) { + if (doRecur) { int recurCount = 0; - if(strang.equals(tok)) { + if (strang.equals(tok)) { return strang; } else { String oldStrang = strang; @@ -98,9 +102,9 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { do { strang = doPass(tok); recurCount += 1; - } while(!strang.equals(oldStrang) && recurCount < MAX_RECURS); + } while (!strang.equals(oldStrang) && recurCount < MAX_RECURS); - if(recurCount >= MAX_RECURS) { + if (recurCount >= MAX_RECURS) { Errors.inst.printError(EK_DFN_RECUR, Integer.toString(MAX_RECURS), tok, strang); return strang; } @@ -113,11 +117,11 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { private String doPass(String tok) { Matcher searcherMatcher = searcher.matcher(tok); - if(subType) { + if (subType) { StringBuffer sb = new StringBuffer(); - while(searcherMatcher.find()) { - if(replacers == null) { - searcherMatcher.appendReplacement(sb,""); + while (searcherMatcher.find()) { + if (replacers == null) { + searcherMatcher.appendReplacement(sb, ""); } else { String replac = replacers.next(); searcherMatcher.appendReplacement(sb, replac); diff --git a/dice-lang/src/bjc/dicelang/DiceLangConsole.java b/dice-lang/src/bjc/dicelang/DiceLangConsole.java index ff6fe45..1b91746 100644 --- a/dice-lang/src/bjc/dicelang/DiceLangConsole.java +++ b/dice-lang/src/bjc/dicelang/DiceLangConsole.java @@ -23,7 +23,8 @@ public class DiceLangConsole { eng = new DiceLangEngine(); - if(!CLIArgsParser.parseArgs(args, eng)) System.exit(1); + if (!CLIArgsParser.parseArgs(args, eng)) + System.exit(1); Terminal.setupTerminal(); } @@ -31,7 +32,7 @@ public class DiceLangConsole { public void run() { try { read = new ConsoleReader(); - } catch(IOException ioex) { + } catch (IOException ioex) { System.out.println("ERROR: Console init failed"); return; } @@ -47,19 +48,23 @@ public class DiceLangConsole { return; } - while(!comm.equals("quit") && !comm.equals("exit")) { - if(comm.startsWith("pragma")) { + while (!comm.equals("quit") && !comm.equals("exit")) { + if (comm.startsWith("pragma")) { boolean success = handlePragma(comm.substring(7)); - if(success) System.out.println("Pragma completed succesfully"); - else System.out.println("Pragma execution failed"); + if (success) + System.out.println("Pragma completed succesfully"); + else + System.out.println("Pragma execution failed"); } else { System.out.printf("\tRaw command: %s\n", comm); boolean success = eng.runCommand(comm); - if(success) System.out.println("Command completed succesfully"); - else System.out.println("Command execution failed"); + if (success) + System.out.println("Command completed succesfully"); + else + System.out.println("Command execution failed"); commandNumber += 1; } @@ -78,60 +83,60 @@ public class DiceLangConsole { String pragmaName = null; int firstIndex = pragma.indexOf(' '); - if(firstIndex == -1) { + if (firstIndex == -1) { pragmaName = pragma; } else { pragmaName = pragma.substring(0, firstIndex); } - switch(pragmaName) { - case "debug": - System.out.println("\tDebug mode is now " + eng.toggleDebug()); - break; - case "postfix": - System.out.println("\tPostfix mode is now " + eng.togglePostfix()); - break; - case "prefix": - System.out.println("\tPrefix mode is now " + eng.togglePrefix()); - break; - case "stepeval": - System.out.println("\tStepeval mode is now" + eng.toggleStepEval()); - break; - case "define": - return defineMode(pragma.substring(7)); - case "help": - return helpMode(pragma.substring(5)); - default: - Errors.inst.printError(EK_CONS_INVPRAG, pragma); - return false; + switch (pragmaName) { + case "debug": + System.out.println("\tDebug mode is now " + eng.toggleDebug()); + break; + case "postfix": + System.out.println("\tPostfix mode is now " + eng.togglePostfix()); + break; + case "prefix": + System.out.println("\tPrefix mode is now " + eng.togglePrefix()); + break; + case "stepeval": + System.out.println("\tStepeval mode is now" + eng.toggleStepEval()); + break; + case "define": + return defineMode(pragma.substring(7)); + case "help": + return helpMode(pragma.substring(5)); + default: + Errors.inst.printError(EK_CONS_INVPRAG, pragma); + return false; } return true; } - + private boolean helpMode(String pragma) { - switch(pragma.trim()) { - case "help": - System.out.println("\tGet help on pragmas"); - break; - case "debug": - System.out.println("\tToggle debug mode. (Output stage results)"); - break; - case "postfix": - System.out.println("\tToggle postfix mode. (Don't shunt tokens)"); - break; - case "prefix": - System.out.println("\tToggle prefix mode. (Reverse token order instead of shunting)"); - break; - case "stepeval": - System.out.println("\tToggle stepeval mode. (Print out evaluation progress)"); - break; - case "define": - System.out.println("\tAdd a macro rewrite directive."); - System.out.println("\tdefine <priority> <type> <recursion> <guard> <circular> <patterns>..."); - break; - default: - System.out.println("\tNo help available for pragma " + pragma); + switch (pragma.trim()) { + case "help": + System.out.println("\tGet help on pragmas"); + break; + case "debug": + System.out.println("\tToggle debug mode. (Output stage results)"); + break; + case "postfix": + System.out.println("\tToggle postfix mode. (Don't shunt tokens)"); + break; + case "prefix": + System.out.println("\tToggle prefix mode. (Reverse token order instead of shunting)"); + break; + case "stepeval": + System.out.println("\tToggle stepeval mode. (Print out evaluation progress)"); + break; + case "define": + System.out.println("\tAdd a macro rewrite directive."); + System.out.println("\tdefine <priority> <type> <recursion> <guard> <circular> <patterns>..."); + break; + default: + System.out.println("\tNo help available for pragma " + pragma); } // Help always works @@ -139,43 +144,41 @@ public class DiceLangConsole { } /* - * Matches slash-delimited strings - * (like /text/ or /text\/text/) - * Uses the "normal* (special normal*)*" pattern style - * recommended in 'Mastering regular expressions' - * Here, the normal is 'anything but a forward or backslash' - * (in regex, thats '[^/\\]') and the special is 'an escaped forward slash' - * (in regex, thats '\\\\/') + * Matches slash-delimited strings (like /text/ or /text\/text/) Uses + * the "normal* (special normal*)*" pattern style recommended in + * 'Mastering regular expressions' Here, the normal is 'anything but a + * forward or backslash' (in regex, thats '[^/\\]') and the special is + * 'an escaped forward slash' (in regex, thats '\\\\/') * - * Then, we just follow the pattern, escape it for java strings, and - * add the enclosing slashes + * Then, we just follow the pattern, escape it for java strings, and add + * the enclosing slashes */ private Pattern slashPattern = Pattern.compile("/((?:\\\\.|[^/\\\\])*)/"); private boolean defineMode(String defineText) { - int firstIndex = defineText.indexOf(' '); - int secondIndex = defineText.indexOf(' ', firstIndex + 1); - int thirdIndex = defineText.indexOf(' ', secondIndex + 1); - int fourthIndex = defineText.indexOf(' ', thirdIndex + 1); - int fifthIndex = defineText.indexOf(' ', fourthIndex + 1); - int sixthIndex = defineText.indexOf(' ', fifthIndex + 1); - - if(firstIndex == -1) { + int firstIndex = defineText.indexOf(' '); + int secondIndex = defineText.indexOf(' ', firstIndex + 1); + int thirdIndex = defineText.indexOf(' ', secondIndex + 1); + int fourthIndex = defineText.indexOf(' ', thirdIndex + 1); + int fifthIndex = defineText.indexOf(' ', fourthIndex + 1); + int sixthIndex = defineText.indexOf(' ', fifthIndex + 1); + + if (firstIndex == -1) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no priority)"); return false; - } else if(secondIndex == -1) { + } else if (secondIndex == -1) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no define type)"); return false; - } else if(thirdIndex == -1) { + } else if (thirdIndex == -1) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no recursion type)"); return false; - } else if(fourthIndex == -1) { + } else if (fourthIndex == -1) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no guard type)"); return false; - } else if(fifthIndex == -1) { + } else if (fifthIndex == -1) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no circularity)"); return false; - } else if(sixthIndex == -1) { + } else if (sixthIndex == -1) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no patterns)"); return false; } @@ -185,42 +188,39 @@ public class DiceLangConsole { String defineType = defineText.substring(firstIndex + 1, secondIndex); Define.Type type; - boolean subMode = false; - - switch(defineType) { - case "line": - type = Define.Type.LINE; - break; - case "token": - type = Define.Type.TOKEN; - break; - case "subline": - type = Define.Type.LINE; - subMode = true; - break; - case "subtoken": - type = Define.Type.TOKEN; - subMode = true; - break; - default: - Errors.inst.printError(EK_CONS_INVDEFINE, "(unknown type)"); - return false; + boolean subMode = false; + + switch (defineType) { + case "line": + type = Define.Type.LINE; + break; + case "token": + type = Define.Type.TOKEN; + break; + case "subline": + type = Define.Type.LINE; + subMode = true; + break; + case "subtoken": + type = Define.Type.TOKEN; + subMode = true; + break; + default: + Errors.inst.printError(EK_CONS_INVDEFINE, "(unknown type)"); + return false; } - boolean doRecur = defineText.substring(secondIndex + 1, thirdIndex) - .equalsIgnoreCase("true"); - boolean hasGuard = defineText.substring(thirdIndex + 1, fourthIndex) - .equalsIgnoreCase("true"); - boolean isCircular = defineText.substring(thirdIndex + 1, fourthIndex) - .equalsIgnoreCase("true"); + boolean doRecur = defineText.substring(secondIndex + 1, thirdIndex).equalsIgnoreCase("true"); + boolean hasGuard = defineText.substring(thirdIndex + 1, fourthIndex).equalsIgnoreCase("true"); + boolean isCircular = defineText.substring(thirdIndex + 1, fourthIndex).equalsIgnoreCase("true"); String pats = defineText.substring(fifthIndex + 1).trim(); Matcher patMatcher = slashPattern.matcher(pats); String guardPattern = null; - if(hasGuard) { - if(!patMatcher.find()) { + if (hasGuard) { + if (!patMatcher.find()) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no guard pattern)"); return false; } @@ -228,7 +228,7 @@ public class DiceLangConsole { guardPattern = patMatcher.group(1); } - if(!patMatcher.find()) { + if (!patMatcher.find()) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no search pattern)"); return false; } @@ -236,16 +236,17 @@ public class DiceLangConsole { String searchPattern = patMatcher.group(1); List<String> replacePatterns = new LinkedList<>(); - while(patMatcher.find()) { + while (patMatcher.find()) { replacePatterns.add(patMatcher.group(1)); } - Define dfn = new Define(priority, subMode, doRecur, isCircular, - guardPattern, searchPattern, replacePatterns); - - if(dfn.inError) return false; + Define dfn = new Define(priority, subMode, doRecur, isCircular, guardPattern, searchPattern, + replacePatterns); + + if (dfn.inError) + return false; - if(type == Define.Type.LINE) { + if (type == Define.Type.LINE) { eng.addLineDefine(dfn); } else { eng.addTokenDefine(dfn); diff --git a/dice-lang/src/bjc/dicelang/DiceLangEngine.java b/dice-lang/src/bjc/dicelang/DiceLangEngine.java index d52e242..f65f5dd 100644 --- a/dice-lang/src/bjc/dicelang/DiceLangEngine.java +++ b/dice-lang/src/bjc/dicelang/DiceLangEngine.java @@ -21,6 +21,7 @@ import java.util.regex.Pattern; import static bjc.dicelang.Errors.ErrorKey.*; import static bjc.dicelang.Token.Type.*; + /** * Implements the orchestration necessary for processing DiceLang commands. * @@ -29,9 +30,10 @@ import static bjc.dicelang.Token.Type.*; public class DiceLangEngine { /* * The random fields that are package private instead of private-private - * are for the benefit of the tweaker, so that it can mess around with them. + * are for the benefit of the tweaker, so that it can mess around with + * them. */ - + /* * Split tokens around operators with regex */ @@ -80,7 +82,7 @@ public class DiceLangEngine { * Tables for various things. */ public final IMap<Integer, String> symTable; - + private IMap<Integer, String> stringLits; private IMap<String, String> stringLiterals; @@ -104,17 +106,17 @@ public class DiceLangEngine { /* * Initialize defns. */ - lineDefns = new FunctionalList<>(); - tokenDefns = new FunctionalList<>(); + lineDefns = new FunctionalList<>(); + tokenDefns = new FunctionalList<>(); defnsSorted = true; /* * Init tables. */ - symTable = new FunctionalMap<>(); + symTable = new FunctionalMap<>(); stringLits = new FunctionalMap<>(); stringLiterals = new FunctionalMap<>(); - + /* * Initialize operator expansion list. */ @@ -144,19 +146,19 @@ public class DiceLangEngine { /* * Initial mode settings. */ - debugMode = true; + debugMode = true; postfixMode = false; - prefixMode = false; - stepEval = false; + prefixMode = false; + stepEval = false; /* * Create components. */ streamEng = new StreamEngine(this); - shunt = new Shunter(); - tokenzer = new Tokenizer(this); - parsr = new Parser(); - eval = new Evaluator(this); + shunt = new Shunter(); + tokenzer = new Tokenizer(this); + parsr = new Parser(); + eval = new Evaluator(this); } /** @@ -172,7 +174,8 @@ public class DiceLangEngine { /** * Add a defn that's applied to lines. * - * @param dfn The defn to add. + * @param dfn + * The defn to add. */ public void addLineDefine(Define dfn) { lineDefns.add(dfn); @@ -183,7 +186,8 @@ public class DiceLangEngine { /** * Add a defn that's applied to tokens. * - * @param dfn The defn to add. + * @param dfn + * The defn to add. */ public void addTokenDefine(Define dfn) { tokenDefns.add(dfn); @@ -243,7 +247,8 @@ public class DiceLangEngine { /** * Run a command to completion. * - * @param command The command to run + * @param command + * The command to run * * @return Whether or not the command ran successfully */ @@ -252,8 +257,8 @@ public class DiceLangEngine { * Preprocess the command into tokens */ IList<String> preprocessedTokens = preprocessCommand(command); - - if(preprocessedTokens == null) { + + if (preprocessedTokens == null) { return false; } @@ -261,18 +266,18 @@ public class DiceLangEngine { * Lex the string tokens into token-tokens */ IList<Token> lexedTokens = lexTokens(preprocessedTokens); - - if(lexedTokens == null) { + + if (lexedTokens == null) { return false; } - + /* * Parse the tokens into an AST forest */ IList<ITree<Node>> astForest = new FunctionalList<>(); boolean succ = parsr.parseTokens(lexedTokens, astForest); - - if(!succ) { + + if (!succ) { return false; } @@ -289,14 +294,14 @@ public class DiceLangEngine { */ private IList<Token> lexTokens(IList<String> preprocessedTokens) { IList<Token> lexedTokens = new FunctionalList<>(); - - for(String token : preprocessedTokens) { + + for (String token : preprocessedTokens) { String newTok = token; /* * Apply token defns */ - for(Define dfn : tokenDefns.toIterable()) { + for (Define dfn : tokenDefns.toIterable()) { newTok = dfn.apply(newTok); } @@ -305,12 +310,12 @@ public class DiceLangEngine { */ Token tk = tokenzer.lexToken(token, stringLiterals); - if(tk == null) { + if (tk == null) { /* * Ignore blank tokens */ continue; - } else if(tk == Token.NIL_TOKEN) { + } else if (tk == Token.NIL_TOKEN) { /* * Fail on bad tokens */ @@ -319,46 +324,46 @@ public class DiceLangEngine { lexedTokens.add(tk); } } - - if(debugMode) { + + if (debugMode) { System.out.printf("\tCommand after tokenization: %s\n", lexedTokens.toString()); } /* * Preshunt preshunt-marked groups of tokens */ - IList<Token> shuntedTokens = lexedTokens; + IList<Token> shuntedTokens = lexedTokens; IList<Token> preparedTokens = new FunctionalList<>(); - + boolean succ = removePreshuntTokens(lexedTokens, preparedTokens); - - if(!succ) { + + if (!succ) { return null; } - - if(debugMode && !postfixMode) { + + if (debugMode && !postfixMode) { System.out.printf("\tCommand after pre-shunter removal: %s\n", preparedTokens.toString()); } - if(!postfixMode && !prefixMode) { + if (!postfixMode && !prefixMode) { /* * Shunt the tokens */ shuntedTokens = new FunctionalList<>(); - succ = shunt.shuntTokens(preparedTokens, shuntedTokens); - - if(!succ) { + succ = shunt.shuntTokens(preparedTokens, shuntedTokens); + + if (!succ) { return null; } - } else if(prefixMode) { + } else if (prefixMode) { /* * Reverse directional tokens */ preparedTokens.reverse(); shuntedTokens = preparedTokens.map(this::reverseToken); } - - if(debugMode && !postfixMode) { + + if (debugMode && !postfixMode) { System.out.printf("\tCommand after shunting: %s\n", shuntedTokens.toString()); } @@ -366,19 +371,19 @@ public class DiceLangEngine { * Expand token groups */ IList<Token> readyTokens = shuntedTokens.flatMap(tk -> { - if(tk.type == Token.Type.TOKGROUP) { + if (tk.type == Token.Type.TOKGROUP) { return tk.tokenValues; - } else if(tk.type == Token.Type.TAGOP || tk.type == Token.Type.TAGOPR) { + } else if (tk.type == Token.Type.TAGOP || tk.type == Token.Type.TAGOPR) { return tk.tokenValues; } else { return new FunctionalList<>(tk); } }); - - if(debugMode && !postfixMode) { + + if (debugMode && !postfixMode) { System.out.printf("\tCommand after re-preshunting: %s\n", readyTokens.toString()); } - + return readyTokens; } @@ -388,21 +393,21 @@ public class DiceLangEngine { * These are mostly just things like (, {, and [ */ private Token reverseToken(Token tk) { - switch(tk.type) { - case OBRACE: - return new Token(CBRACE, tk.intValue); - case OPAREN: - return new Token(CPAREN, tk.intValue); - case OBRACKET: - return new Token(CBRACKET, tk.intValue); - case CBRACE: - return new Token(OBRACE, tk.intValue); - case CPAREN: - return new Token(OPAREN, tk.intValue); - case CBRACKET: - return new Token(OBRACKET, tk.intValue); - default: - return tk; + switch (tk.type) { + case OBRACE: + return new Token(CBRACE, tk.intValue); + case OPAREN: + return new Token(CPAREN, tk.intValue); + case OBRACKET: + return new Token(CBRACKET, tk.intValue); + case CBRACE: + return new Token(OBRACE, tk.intValue); + case CPAREN: + return new Token(OPAREN, tk.intValue); + case CBRACKET: + return new Token(OBRACKET, tk.intValue); + default: + return tk; } } @@ -413,7 +418,7 @@ public class DiceLangEngine { /* * Sort the defines if they aren't sorted */ - if(!defnsSorted) { + if (!defnsSorted) { sortDefns(); } @@ -423,7 +428,7 @@ public class DiceLangEngine { IList<String> streamToks = new FunctionalList<>(); boolean succ = streamEng.doStreams(command.split(" "), streamToks); - if(!succ) { + if (!succ) { return null; } @@ -431,16 +436,16 @@ public class DiceLangEngine { * Apply line defns */ String newComm = ListUtils.collapseTokens(streamToks, " "); - - if(debugMode) { + + if (debugMode) { System.out.println("\tCommand after stream commands: " + newComm); } - - for(Define dfn : lineDefns.toIterable()) { + + for (Define dfn : lineDefns.toIterable()) { newComm = dfn.apply(newComm); } - - if(debugMode) { + + if (debugMode) { System.out.println("\tCommand after line defines: " + newComm); } @@ -449,20 +454,21 @@ public class DiceLangEngine { */ List<String> destringedParts = StringUtils.removeDQuotedStrings(newComm); StringBuffer destringedCommand = new StringBuffer(); - - for(String part : destringedParts) { + + for (String part : destringedParts) { /* * Handle string literals */ - if(part.startsWith("\"") && part.endsWith("\"")) { + if (part.startsWith("\"") && part.endsWith("\"")) { /* * Get the actual string. */ String litName = "stringLiteral" + nextLiteral; String litVal = part.substring(1, part.length() - 1); - + /* - * Insert the string with its escape sequences interpreted. + * Insert the string with its escape sequences + * interpreted. */ stringLiterals.put(litName, StringUtils.descapeString(litVal)); nextLiteral += 1; @@ -475,14 +481,14 @@ public class DiceLangEngine { destringedCommand.append(part); } } - - if(debugMode) { + + if (debugMode) { System.out.println("\tCommand after destringing: " + destringedCommand); /* * Print the string table if it exists. */ - if(stringLiterals.getSize() > 0) { + if (stringLiterals.getSize() > 0) { System.out.println("\tString literals in table"); stringLiterals.forEach((key, val) -> { @@ -504,7 +510,7 @@ public class DiceLangEngine { tokens = tokens.map(tk -> { Matcher nonExpandMatcher = nonExpandPattern.matcher(tk); - if(nonExpandMatcher.matches()) { + if (nonExpandMatcher.matches()) { String tkName = "nonExpandToken" + nextLiteral++; nonExpandedTokens.put(tkName, nonExpandMatcher.group(1)); @@ -513,55 +519,56 @@ public class DiceLangEngine { return tk; } }); - - if(debugMode) { + + if (debugMode) { System.out.printf("\tCommand after removal of non-expanders: %s\n", tokens.toString()); } /* * Expand tokens */ - IList<String> fullyExpandedTokens = tokens.flatMap((token) -> new FunctionalList<>(opExpander.split(token))); + IList<String> fullyExpandedTokens = tokens + .flatMap((token) -> new FunctionalList<>(opExpander.split(token))); System.out.println("\tCommand after token expansion: " + fullyExpandedTokens.toString()); /* * Reinsert non-expanded tokens */ fullyExpandedTokens = fullyExpandedTokens.map(tk -> { - if(tk.startsWith("nonExpandToken")) { + if (tk.startsWith("nonExpandToken")) { return nonExpandedTokens.get(tk); } else { return tk; } }); - - if(debugMode) { - System.out.printf("\tCommand after non-expander reinsertion: %s\n", + + if (debugMode) { + System.out.printf("\tCommand after non-expander reinsertion: %s\n", fullyExpandedTokens.toString()); } - + return fullyExpandedTokens; } private void evaluateForest(IList<ITree<Node>> astForest) { - if(debugMode) { + if (debugMode) { System.out.println("\tParsed forest of asts"); } - + int treeNo = 1; - for(ITree<Node> ast : astForest) { - if(debugMode) { + for (ITree<Node> ast : astForest) { + if (debugMode) { System.out.printf("\t\tTree %d in forest:\n%s\n", treeNo, ast.toString()); } - if(debugMode && stepEval) { + if (debugMode && stepEval) { int step = 1; /* * Evaluate it step by step */ - for(Iterator<ITree<Node>> itr = eval.stepDebug(ast); itr.hasNext();){ + for (Iterator<ITree<Node>> itr = eval.stepDebug(ast); itr.hasNext();) { ITree<Node> nodeStep = itr.next(); System.out.printf("\t\tStep %d: Node is %s", step, nodeStep); @@ -569,7 +576,7 @@ public class DiceLangEngine { /* * Don't evaluate null steps */ - if(nodeStep == null) { + if (nodeStep == null) { System.out.println(); step += 1; @@ -579,16 +586,16 @@ public class DiceLangEngine { /* * Print out details for results */ - if(nodeStep.getHead().type == Node.Type.RESULT) { + if (nodeStep.getHead().type == Node.Type.RESULT) { EvaluatorResult res = nodeStep.getHead().resultVal; System.out.printf(" (result is %s", res); - if(res.type == EvaluatorResult.Type.DICE) { + if (res.type == EvaluatorResult.Type.DICE) { System.out.printf(" (sample roll %s)", res.diceVal.value()); } - if(res.origVal != null) { + if (res.origVal != null) { System.out.printf(" (original tree is %s)", res.origVal); } @@ -607,10 +614,10 @@ public class DiceLangEngine { */ EvaluatorResult res = eval.evaluate(ast); - if(debugMode) { + if (debugMode) { System.out.printf("\t\tEvaluates to %s", res); - if(res.type == EvaluatorResult.Type.DICE) { + if (res.type == EvaluatorResult.Type.DICE) { System.out.println("\t\t (sample roll " + res.diceVal.value() + ")"); } } @@ -630,35 +637,37 @@ public class DiceLangEngine { * Current nesting level of tokens. */ int curBraceCount = 0; - + /* * Data storage. */ - Deque<IList<Token>> bracedTokens = new LinkedList<>(); - IList<Token> curBracedTokens = null; + Deque<IList<Token>> bracedTokens = new LinkedList<>(); + IList<Token> curBracedTokens = null; - for(Token tk : lexedTokens) { - if(tk.type == Token.Type.OBRACE && tk.intValue == 2) { + for (Token tk : lexedTokens) { + if (tk.type == Token.Type.OBRACE && tk.intValue == 2) { /* * Open a preshunt group. */ curBraceCount += 1; - if(curBraceCount != 1) { + if (curBraceCount != 1) { /* - * Push the old group onto the group stack. + * Push the old group onto the group + * stack. */ bracedTokens.push(curBracedTokens); } curBracedTokens = new FunctionalList<>(); - } else if(tk.type == Token.Type.CBRACE && tk.intValue == 2) { + } else if (tk.type == Token.Type.CBRACE && tk.intValue == 2) { /* * Close a preshunt group. */ - if(curBraceCount == 0) { + if (curBraceCount == 0) { /* - * Error if there couldn't have been an opening. + * Error if there couldn't have been an + * opening. */ Errors.inst.printError(EK_ENG_NOOPENING); return false; @@ -673,32 +682,36 @@ public class DiceLangEngine { */ boolean success = shunt.shuntTokens(curBracedTokens, preshuntTokens); - if(debugMode) { - System.out.println("\t\tPreshunted " + curBracedTokens + " into " + preshuntTokens); + if (debugMode) { + System.out.println("\t\tPreshunted " + curBracedTokens + " into " + + preshuntTokens); } - if(!success) { + if (!success) { return false; } - if(curBraceCount >= 1) { + if (curBraceCount >= 1) { /* - * Add the preshunt group to the previous group. + * Add the preshunt group to the + * previous group. */ curBracedTokens = bracedTokens.pop(); curBracedTokens.add(new Token(Token.Type.TOKGROUP, preshuntTokens)); } else { /* - * Add the preshunt group to the token stream.. + * Add the preshunt group to the token + * stream.. */ preparedTokens.add(new Token(Token.Type.TOKGROUP, preshuntTokens)); } } else { /* - * Add the token to the active preshunt group, if there is one.. + * Add the token to the active preshunt group, + * if there is one.. */ - if(curBraceCount >= 1) { + if (curBraceCount >= 1) { curBracedTokens.add(tk); } else { preparedTokens.add(tk); @@ -706,21 +719,21 @@ public class DiceLangEngine { } } - if(curBraceCount > 0) { + if (curBraceCount > 0) { /* * There was an unclosed group. */ Errors.inst.printError(EK_ENG_NOCLOSING); return false; } - + return true; } - + String getStringLiteral(int key) { return stringLits.get(key); } - + void addStringLiteral(int key, String val) { stringLits.put(key, val); } diff --git a/dice-lang/src/bjc/dicelang/Errors.java b/dice-lang/src/bjc/dicelang/Errors.java index 053ad9f..3af4e39 100644 --- a/dice-lang/src/bjc/dicelang/Errors.java +++ b/dice-lang/src/bjc/dicelang/Errors.java @@ -132,9 +132,9 @@ public class Errors { private ErrorMode mode; public void printError(ErrorKey key, String... args) { - switch(mode) { + switch (mode) { case WIZARD: - if(key == ErrorKey.EK_CLI_NOFILE) { + if (key == ErrorKey.EK_CLI_NOFILE) { System.out.println("\t? 404"); } else { System.out.println("\t? " + key.ordinal()); @@ -149,7 +149,7 @@ public class Errors { } private void devError(ErrorKey key, String[] args) { - switch(key) { + switch (key) { case EK_DFN_PREDSYN: System.out.printf("\tERROR: Incorrect define guard syntax %s\n", args[0]); break; @@ -157,8 +157,9 @@ public class Errors { System.out.printf("\tERROR: Incorrect define match syntax %s\n", args[0]); break; case EK_DFN_RECUR: - System.out.printf("\tERROR: Recursive define didn't converge after %s iterations." - + " Original string was %s, last iteration was %s\n", + System.out.printf( + "\tERROR: Recursive define didn't converge after %s iterations." + + " Original string was %s, last iteration was %s\n", args[0], args[1], args[2]); break; case EK_CONS_INVPRAG: @@ -212,12 +213,11 @@ public class Errors { System.out.printf("\tERROR: Unknown dice operator %s\n", args[0]); break; case EK_EVAL_INVDCREATE: - System.out.printf("\tERROR: Dice creation operator expects integers," - + " not %s\n", args[0]); + System.out.printf("\tERROR: Dice creation operator expects integers," + " not %s\n", args[0]); break; case EK_EVAL_INVDGROUP: - System.out.printf("\tERROR: Dice group operator expects scalar dice or integers," - + " not %s\n", args[0]); + System.out.printf("\tERROR: Dice group operator expects scalar dice or integers," + " not %s\n", + args[0]); break; case EK_EVAL_INVDICE: System.out.printf("\tERROR: Dice operators expect scalar dice, not %s\n", args[0]); @@ -260,8 +260,8 @@ public class Errors { + " to apply it to\n", args[0]); break; case EK_SHUNT_NOGROUP: - System.out.printf("\tERROR: Couldn't find matching grouping %s (expected %s)\n", - args[0], args[1]); + System.out.printf("\tERROR: Couldn't find matching grouping %s (expected %s)\n", args[0], + args[1]); break; case EK_SHUNT_NOTASSOC: System.out.printf("\tERROR: Attempted to chain non-associative operator %s\n", args[0]); diff --git a/dice-lang/src/bjc/dicelang/Evaluator.java b/dice-lang/src/bjc/dicelang/Evaluator.java index 286af5c..5ecff25 100644 --- a/dice-lang/src/bjc/dicelang/Evaluator.java +++ b/dice-lang/src/bjc/dicelang/Evaluator.java @@ -58,13 +58,16 @@ public class Evaluator { ctx.isDebug = false; ctx.thunk = (itr) -> { - // Deliberately finish the iterator, but ignore results. It's only for stepwise evaluation - // but we don't know if stepping the iterator causes something to happen - while(itr.hasNext()) itr.next(); + // Deliberately finish the iterator, but ignore results. + // It's only for stepwise evaluation + // but we don't know if stepping the iterator causes + // something to happen + while (itr.hasNext()) + itr.next(); }; - return comm.topDownTransform(this::pickEvaluationType, - (node) -> this.evaluateNode(node, ctx)).getHead().resultVal; + return comm.topDownTransform(this::pickEvaluationType, (node) -> this.evaluateNode(node, ctx)) + .getHead().resultVal; } // @FIXME Something's broken with step evaluation @@ -76,14 +79,14 @@ public class Evaluator { return new TopDownTransformIterator<>(this::pickEvaluationType, (node, thnk) -> { ctx.thunk = thnk; - return this.evaluateNode(node, ctx); + return this.evaluateNode(node, ctx); }, comm); } private TopDownTransformResult pickEvaluationType(Node nd) { - switch(nd.type) { + switch (nd.type) { case UNARYOP: - switch(nd.operatorType) { + switch (nd.operatorType) { case COERCE: return TopDownTransformResult.RTRANSFORM; default: @@ -95,7 +98,7 @@ public class Evaluator { } private ITree<Node> evaluateNode(ITree<Node> ast, Context ctx) { - switch(ast.getHead().type) { + switch (ast.getHead().type) { case UNARYOP: return evaluateUnaryOp(ast, ctx); case BINOP: @@ -113,54 +116,56 @@ public class Evaluator { } private ITree<Node> evaluateUnaryOp(ITree<Node> ast, Context ctx) { - if(ast.getChildrenCount() != 1) { + if (ast.getChildrenCount() != 1) { Errors.inst.printError(EK_EVAL_UNUNARY, Integer.toString(ast.getChildrenCount())); return new Tree<>(FAIL(ast)); } - switch(ast.getHead().operatorType) { + switch (ast.getHead().operatorType) { /* * @TODO move coercing to its own class */ case COERCE: ITree<Node> toCoerce = ast.getChild(0); - ITree<Node> retVal = new Tree<>(toCoerce.getHead()); + ITree<Node> retVal = new Tree<>(toCoerce.getHead()); Deque<ITree<Node>> children = new LinkedList<>(); CoerceSteps curLevel = CoerceSteps.INTEGER; - for(int i = 0; i < toCoerce.getChildrenCount(); i++) { - ITree<Node> child = toCoerce.getChild(i); + for (int i = 0; i < toCoerce.getChildrenCount(); i++) { + ITree<Node> child = toCoerce.getChild(i); ITree<Node> nChild = null; - if(ctx.isDebug) { + if (ctx.isDebug) { Iterator<ITree<Node>> nd = stepDebug(child); - for(; nd.hasNext(); nChild = nd.next()) { + for (; nd.hasNext(); nChild = nd.next()) { ctx.thunk.accept(new SingleIterator<>(child)); } } else { nChild = new Tree<>(new Node(Node.Type.RESULT, evaluate(child))); - if(nChild != null) ctx.thunk.accept(new SingleIterator<>(nChild)); + if (nChild != null) + ctx.thunk.accept(new SingleIterator<>(nChild)); } - Node childNode = nChild.getHead(); + Node childNode = nChild.getHead(); EvaluatorResult res = childNode.resultVal; - if(res.type == FLOAT) curLevel = CoerceSteps.FLOAT; + if (res.type == FLOAT) + curLevel = CoerceSteps.FLOAT; children.add(nChild); } - for(ITree<Node> child : children) { + for (ITree<Node> child : children) { Node nd = child.getHead(); EvaluatorResult res = nd.resultVal; - switch(res.type) { + switch (res.type) { case INT: - if(curLevel == CoerceSteps.FLOAT) { - nd.resultVal = new EvaluatorResult(FLOAT, (double)res.intVal); + if (curLevel == CoerceSteps.FLOAT) { + nd.resultVal = new EvaluatorResult(FLOAT, (double) res.intVal); } default: // Do nothing @@ -174,23 +179,21 @@ public class Evaluator { case DICESCALAR: EvaluatorResult opr = ast.getChild(0).getHead().resultVal; - if(opr.type != INT) { + if (opr.type != INT) { Errors.inst.printError(EK_EVAL_INVDCREATE, opr.type.toString()); } return new Tree<>(new Node(Node.Type.RESULT, - new EvaluatorResult(DICE, - new ScalarDie(opr.intVal)))); + new EvaluatorResult(DICE, new ScalarDie(opr.intVal)))); case DICEFUDGE: EvaluatorResult oprn = ast.getChild(0).getHead().resultVal; - if(oprn.type != INT) { + if (oprn.type != INT) { Errors.inst.printError(EK_EVAL_INVDCREATE, oprn.type.toString()); } return new Tree<>(new Node(Node.Type.RESULT, - new EvaluatorResult(DICE, - new FudgeDie(oprn.intVal)))); + new EvaluatorResult(DICE, new FudgeDie(oprn.intVal)))); default: Errors.inst.printError(EK_EVAL_INVUNARY, ast.getHead().operatorType.toString()); return new Tree<>(FAIL(ast)); @@ -200,67 +203,63 @@ public class Evaluator { private ITree<Node> evaluateBinaryOp(ITree<Node> ast, Context ctx) { Token.Type binOp = ast.getHead().operatorType; - if(ast.getChildrenCount() != 2) { - Errors.inst.printError(EK_EVAL_INVBIN, Integer.toString(ast.getChildrenCount()), ast.toString()); + if (ast.getChildrenCount() != 2) { + Errors.inst.printError(EK_EVAL_INVBIN, Integer.toString(ast.getChildrenCount()), + ast.toString()); return new Tree<>(FAIL(ast)); } - ITree<Node> left = ast.getChild(0); + ITree<Node> left = ast.getChild(0); ITree<Node> right = ast.getChild(1); - switch(binOp) { + switch (binOp) { case ADD: case SUBTRACT: case MULTIPLY: case DIVIDE: case IDIVIDE: - return evaluateMathBinary(binOp, - left.getHead().resultVal, right.getHead().resultVal, - ctx); + return evaluateMathBinary(binOp, left.getHead().resultVal, right.getHead().resultVal, ctx); case DICEGROUP: case DICECONCAT: case DICELIST: - return evaluateDiceBinary(binOp, - left.getHead().resultVal, right.getHead().resultVal, - ctx); + return evaluateDiceBinary(binOp, left.getHead().resultVal, right.getHead().resultVal, ctx); case STRCAT: case STRREP: - return evaluateStringBinary(binOp, - left.getHead().resultVal, right.getHead().resultVal, - ctx); + return evaluateStringBinary(binOp, left.getHead().resultVal, right.getHead().resultVal, ctx); default: Errors.inst.printError(EK_EVAL_UNBIN, binOp.toString()); return new Tree<>(FAIL(ast)); } } - private ITree<Node> evaluateStringBinary(Token.Type op, - EvaluatorResult left, EvaluatorResult right, Context ctx) { - if(left.type != STRING) { + private ITree<Node> evaluateStringBinary(Token.Type op, EvaluatorResult left, EvaluatorResult right, + Context ctx) { + if (left.type != STRING) { Errors.inst.printError(EK_EVAL_INVSTRING, left.type.toString()); return new Tree<>(FAIL(left)); } String strang = left.stringVal; - switch(op) { + switch (op) { case STRCAT: - if(right.type != STRING) { + if (right.type != STRING) { Errors.inst.printError(EK_EVAL_UNSTRING, right.type.toString()); return new Tree<>(FAIL(right)); } else { String strung = right.stringVal; - return new Tree<>(new Node(Node.Type.RESULT, new EvaluatorResult(STRING, strang + strung))); + return new Tree<>(new Node(Node.Type.RESULT, + new EvaluatorResult(STRING, strang + strung))); } case STRREP: - if(right.type != INT) { + if (right.type != INT) { Errors.inst.printError(EK_EVAL_INVSTRING, right.type.toString()); return new Tree<>(FAIL(right)); } else { String res = strang; long count = right.intVal; - for(long i = 1; i < count; i++) { + for (long i = 1; i < count; i++) { res += strang; } return new Tree<>(new Node(Node.Type.RESULT, new EvaluatorResult(STRING, res))); @@ -271,25 +270,27 @@ public class Evaluator { } } - private ITree<Node> evaluateDiceBinary(Token.Type op, - EvaluatorResult left, EvaluatorResult right, Context ctx) { + private ITree<Node> evaluateDiceBinary(Token.Type op, EvaluatorResult left, EvaluatorResult right, + Context ctx) { EvaluatorResult res = null; - switch(op) { + switch (op) { case DICEGROUP: - if(left.type == DICE && !left.diceVal.isList) { - if(right.type == DICE && !right.diceVal.isList) { + if (left.type == DICE && !left.diceVal.isList) { + if (right.type == DICE && !right.diceVal.isList) { res = new EvaluatorResult(DICE, new SimpleDie(left.diceVal.scalar, right.diceVal.scalar)); } else if (right.type == INT) { - res = new EvaluatorResult(DICE, new SimpleDie(left.diceVal.scalar, right.intVal)); + res = new EvaluatorResult(DICE, + new SimpleDie(left.diceVal.scalar, right.intVal)); } else { Errors.inst.printError(EK_EVAL_INVDGROUP, right.type.toString()); return new Tree<>(FAIL(right)); } - } else if(left.type == INT) { - if(right.type == DICE && !right.diceVal.isList) { - res = new EvaluatorResult(DICE, new SimpleDie(left.intVal, right.diceVal.scalar)); + } else if (left.type == INT) { + if (right.type == DICE && !right.diceVal.isList) { + res = new EvaluatorResult(DICE, + new SimpleDie(left.intVal, right.diceVal.scalar)); } else if (right.type == INT) { res = new EvaluatorResult(DICE, new SimpleDie(left.intVal, right.intVal)); } else { @@ -301,22 +302,22 @@ public class Evaluator { return new Tree<>(FAIL(left)); } case DICECONCAT: - if(left.type != DICE || left.diceVal.isList) { + if (left.type != DICE || left.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, left.type.toString()); return new Tree<>(FAIL(left)); - } else if(right.type != DICE || right.diceVal.isList) { + } else if (right.type != DICE || right.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, right.type.toString()); return new Tree<>(FAIL(right)); } else { - res = new EvaluatorResult(DICE, + res = new EvaluatorResult(DICE, new CompoundDie(left.diceVal.scalar, right.diceVal.scalar)); } break; case DICELIST: - if(left.type != DICE || left.diceVal.isList) { + if (left.type != DICE || left.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, left.type.toString()); return new Tree<>(FAIL(left)); - } else if(right.type != DICE || right.diceVal.isList) { + } else if (right.type != DICE || right.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, right.type.toString()); return new Tree<>(FAIL(right)); } else { @@ -332,100 +333,100 @@ public class Evaluator { return new Tree<>(new Node(Node.Type.RESULT, res)); } - private ITree<Node> evaluateMathBinary(Token.Type op, - EvaluatorResult left, EvaluatorResult right, Context ctx) { - if(left.type == STRING || right.type == STRING) { + private ITree<Node> evaluateMathBinary(Token.Type op, EvaluatorResult left, EvaluatorResult right, + Context ctx) { + if (left.type == STRING || right.type == STRING) { Errors.inst.printError(EK_EVAL_STRINGMATH); return new Tree<>(FAIL()); - } else if(left.type == FAILURE || right.type == FAILURE) { + } else if (left.type == FAILURE || right.type == FAILURE) { return new Tree<>(FAIL()); - } else if(left.type == INT && right.type != INT) { + } else if (left.type == INT && right.type != INT) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(right)); - } else if(left.type == FLOAT && right.type != FLOAT) { + } else if (left.type == FLOAT && right.type != FLOAT) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(right)); - } else if(left.type == DICE && right.type != DICE) { + } else if (left.type == DICE && right.type != DICE) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(right)); - } else if(right.type == INT && left.type != INT) { + } else if (right.type == INT && left.type != INT) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(left)); - } else if(right.type == FLOAT && left.type != FLOAT) { + } else if (right.type == FLOAT && left.type != FLOAT) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(left)); - } else if(right.type == DICE && left.type != DICE) { + } else if (right.type == DICE && left.type != DICE) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(left)); } EvaluatorResult res = null; - switch(op) { + switch (op) { case ADD: - if(left.type == INT) { + if (left.type == INT) { res = new EvaluatorResult(INT, left.intVal + right.intVal); - } else if(left.type == DICE) { - if(left.diceVal.isList) { + } else if (left.type == DICE) { + if (left.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, left.toString()); return new Tree<>(FAIL(left)); - } else if(right.diceVal.isList) { + } else if (right.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, right.toString()); return new Tree<>(FAIL(right)); } - res = new EvaluatorResult(DICE, new MathDie(MathDie.MathOp.ADD, - left.diceVal.scalar, right.diceVal.scalar)); + res = new EvaluatorResult(DICE, new MathDie(MathDie.MathOp.ADD, left.diceVal.scalar, + right.diceVal.scalar)); } else { res = new EvaluatorResult(FLOAT, left.floatVal + right.floatVal); } break; case SUBTRACT: - if(left.type == INT) { + if (left.type == INT) { res = new EvaluatorResult(INT, left.intVal - right.intVal); - } else if(left.type == DICE) { - if(left.diceVal.isList) { + } else if (left.type == DICE) { + if (left.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, left.toString()); return new Tree<>(FAIL(left)); - } else if(right.diceVal.isList) { + } else if (right.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, right.toString()); return new Tree<>(FAIL(right)); } res = new EvaluatorResult(DICE, new MathDie(MathDie.MathOp.SUBTRACT, - left.diceVal.scalar, right.diceVal.scalar)); + left.diceVal.scalar, right.diceVal.scalar)); } else { res = new EvaluatorResult(FLOAT, left.floatVal - right.floatVal); } break; case MULTIPLY: - if(left.type == INT) { + if (left.type == INT) { res = new EvaluatorResult(INT, left.intVal * right.intVal); - } else if(left.type == DICE) { - if(left.diceVal.isList) { + } else if (left.type == DICE) { + if (left.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, left.toString()); return new Tree<>(FAIL(left)); - } else if(right.diceVal.isList) { + } else if (right.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, right.toString()); return new Tree<>(FAIL(right)); } res = new EvaluatorResult(DICE, new MathDie(MathDie.MathOp.MULTIPLY, - left.diceVal.scalar, right.diceVal.scalar)); + left.diceVal.scalar, right.diceVal.scalar)); } else { res = new EvaluatorResult(FLOAT, left.floatVal * right.floatVal); } break; case DIVIDE: - if(left.type == INT) { - if(right.intVal == 0) { + if (left.type == INT) { + if (right.intVal == 0) { Errors.inst.printError(EK_EVAL_DIVZERO); res = new EvaluatorResult(FAILURE, right); } else { res = new EvaluatorResult(FLOAT, left.intVal / right.intVal); } - } else if(left.type == FLOAT) { - if(right.floatVal == 0) { + } else if (left.type == FLOAT) { + if (right.floatVal == 0) { Errors.inst.printError(EK_EVAL_DIVZERO); res = new EvaluatorResult(FAILURE, right); } else { @@ -437,15 +438,15 @@ public class Evaluator { } break; case IDIVIDE: - if(left.type == INT) { - if(right.intVal == 0) { + if (left.type == INT) { + if (right.intVal == 0) { Errors.inst.printError(EK_EVAL_DIVZERO); res = new EvaluatorResult(FAILURE, right); } else { res = new EvaluatorResult(INT, (int) (left.intVal / right.intVal)); } - } else if(left.type == FLOAT) { - if(right.floatVal == 0) { + } else if (left.type == FLOAT) { + if (right.floatVal == 0) { Errors.inst.printError(EK_EVAL_DIVZERO); res = new EvaluatorResult(FAILURE, right); } else { @@ -467,7 +468,7 @@ public class Evaluator { private ITree<Node> evaluateTokenRef(Token tk, Context ctx) { EvaluatorResult res = null; - switch(tk.type) { + switch (tk.type) { case INT_LIT: res = new EvaluatorResult(INT, tk.intValue); break; @@ -478,7 +479,7 @@ public class Evaluator { res = new EvaluatorResult(DICE, tk.diceValue); break; case STRING_LIT: - res = new EvaluatorResult(STRING, eng.getStringLiteral((int)(tk.intValue))); + res = new EvaluatorResult(STRING, eng.getStringLiteral((int) (tk.intValue))); break; default: Errors.inst.printError(EK_EVAL_UNTOK, tk.type.toString()); diff --git a/dice-lang/src/bjc/dicelang/EvaluatorResult.java b/dice-lang/src/bjc/dicelang/EvaluatorResult.java index ef70d3d..2c3c74c 100644 --- a/dice-lang/src/bjc/dicelang/EvaluatorResult.java +++ b/dice-lang/src/bjc/dicelang/EvaluatorResult.java @@ -8,21 +8,20 @@ import bjc.utils.data.Tree; public class EvaluatorResult {
public static enum Type {
- FAILURE,
- INT, FLOAT, DICE, STRING
+ FAILURE, INT, FLOAT, DICE, STRING
}
public final EvaluatorResult.Type type;
// These may or may not have values based
// off of the result type
- public long intVal;
- public double floatVal;
+ public long intVal;
+ public double floatVal;
public DieExpression diceVal;
- public String stringVal;
+ public String stringVal;
// Original node data
- public ITree<Node> origVal;
+ public ITree<Node> origVal;
public EvaluatorResult(EvaluatorResult.Type typ) {
type = typ;
@@ -79,19 +78,19 @@ public class EvaluatorResult { }
public String toString() {
- switch(type) {
- case INT:
- return type.toString() + "(" + intVal + ")";
- case FLOAT:
- return type.toString() + "(" + floatVal + ")";
- case DICE:
- return type.toString() + "(" + diceVal + ")";
- case STRING:
- return type.toString() + "(" + stringVal + ")";
- case FAILURE:
- return type.toString();
- default:
- return "Unknown result type " + type.toString();
+ switch (type) {
+ case INT:
+ return type.toString() + "(" + intVal + ")";
+ case FLOAT:
+ return type.toString() + "(" + floatVal + ")";
+ case DICE:
+ return type.toString() + "(" + diceVal + ")";
+ case STRING:
+ return type.toString() + "(" + stringVal + ")";
+ case FAILURE:
+ return type.toString();
+ default:
+ return "Unknown result type " + type.toString();
}
}
}
\ No newline at end of file diff --git a/dice-lang/src/bjc/dicelang/Node.java b/dice-lang/src/bjc/dicelang/Node.java index 3ae54e3..15ae66e 100644 --- a/dice-lang/src/bjc/dicelang/Node.java +++ b/dice-lang/src/bjc/dicelang/Node.java @@ -2,10 +2,7 @@ package bjc.dicelang; public class Node { public static enum Type { - ROOT, TOKREF, - UNARYOP, BINOP, - GROUP, OGROUP, - RESULT + ROOT, TOKREF, UNARYOP, BINOP, GROUP, OGROUP, RESULT } public static enum GroupType { @@ -15,9 +12,9 @@ public class Node { public final Type type; // These can have or not have values based of the node type - public Token tokenVal; - public Token.Type operatorType; - public GroupType groupType; + public Token tokenVal; + public Token.Type operatorType; + public GroupType groupType; public EvaluatorResult resultVal; public Node(Type typ) { @@ -49,34 +46,36 @@ public class Node { } public String toString() { - switch(type) { - case UNARYOP: - case BINOP: - return "(" + type.name() + " : " + operatorType + ")"; - case OGROUP: - case TOKREF: - return "(" + type.name() + " : " + tokenVal + ")"; - case GROUP: - return "(" + type.name() + " : " + groupType + ")"; - case RESULT: - return "(" + type.name() + " : " + resultVal + ")"; - default: - return "Unknown node type " + type; + switch (type) { + case UNARYOP: + case BINOP: + return "(" + type.name() + " : " + operatorType + ")"; + case OGROUP: + case TOKREF: + return "(" + type.name() + " : " + tokenVal + ")"; + case GROUP: + return "(" + type.name() + " : " + groupType + ")"; + case RESULT: + return "(" + type.name() + " : " + resultVal + ")"; + default: + return "Unknown node type " + type; } } public boolean equals(Object other) { - if(!(other instanceof Node)) return false; + if (!(other instanceof Node)) + return false; - Node otk = (Node)other; + Node otk = (Node) other; - if(otk.type != type) return false; + if (otk.type != type) + return false; - switch(type) { - case OGROUP: - return tokenVal.equals(otk.tokenVal); - default: - return true; + switch (type) { + case OGROUP: + return tokenVal.equals(otk.tokenVal); + default: + return true; } } } diff --git a/dice-lang/src/bjc/dicelang/Parser.java b/dice-lang/src/bjc/dicelang/Parser.java index 5f8d552..828cad7 100644 --- a/dice-lang/src/bjc/dicelang/Parser.java +++ b/dice-lang/src/bjc/dicelang/Parser.java @@ -16,99 +16,99 @@ public class Parser { } - public boolean parseTokens(IList<Token> tokens, - IList<ITree<Node>> results) { + public boolean parseTokens(IList<Token> tokens, IList<ITree<Node>> results) { Deque<ITree<Node>> working = new LinkedList<>(); - for(Token tk : tokens) { - switch(tk.type) { - case OBRACKET: - case OBRACE: - working.push(new Tree<>(new Node(OGROUP, tk))); - break; - case CBRACKET: - case CBRACE: - boolean sc = parseClosingGrouper(working, tk); - if(!sc) return false; - break; - case MULTIPLY: - case DIVIDE: - case IDIVIDE: - case DICEGROUP: - case DICECONCAT: - case DICELIST: - case STRCAT: - case STRREP: - case LET: - case BIND: - if(working.size() < 2) { - Errors.inst.printError(EK_PARSE_BINARY); - return false; - } else { - ITree<Node> right = working.pop(); - ITree<Node> left = working.pop(); - - ITree<Node> opNode = new Tree<>(new Node(BINOP, tk.type)); - - opNode.addChild(left); - opNode.addChild(right); - - working.push(opNode); - } - break; - case ADD: - case SUBTRACT: - if(working.size() == 0) { - Errors.inst.printError(EK_PARSE_UNOPERAND, tk.toString()); - return false; - } else if(working.size() == 1) { - ITree<Node> operand = working.pop(); - - ITree<Node> opNode = new Tree<>(new Node(UNARYOP, tk.type)); - - opNode.addChild(operand); - - working.push(opNode); - } else { - ITree<Node> right = working.pop(); - ITree<Node> left = working.pop(); - - ITree<Node> opNode = new Tree<>(new Node(BINOP, tk.type)); - - opNode.addChild(left); - opNode.addChild(right); - - working.push(opNode); - } - break; - case COERCE: - case DICESCALAR: - case DICEFUDGE: - if(working.size() == 0) { - Errors.inst.printError(EK_PARSE_UNOPERAND, tk.toString()); - } else { - ITree<Node> operand = working.pop(); - ITree<Node> opNode = new Tree<>(new Node(UNARYOP, tk.type)); - - opNode.addChild(operand); - - working.push(opNode); - } - break; - case INT_LIT: - case FLOAT_LIT: - case STRING_LIT: - case VREF: - case DICE_LIT: - working.push(new Tree<>(new Node(TOKREF, tk))); - break; - default: - Errors.inst.printError(EK_PARSE_INVTOKEN, tk.type.toString()); + for (Token tk : tokens) { + switch (tk.type) { + case OBRACKET: + case OBRACE: + working.push(new Tree<>(new Node(OGROUP, tk))); + break; + case CBRACKET: + case CBRACE: + boolean sc = parseClosingGrouper(working, tk); + if (!sc) + return false; + break; + case MULTIPLY: + case DIVIDE: + case IDIVIDE: + case DICEGROUP: + case DICECONCAT: + case DICELIST: + case STRCAT: + case STRREP: + case LET: + case BIND: + if (working.size() < 2) { + Errors.inst.printError(EK_PARSE_BINARY); return false; + } else { + ITree<Node> right = working.pop(); + ITree<Node> left = working.pop(); + + ITree<Node> opNode = new Tree<>(new Node(BINOP, tk.type)); + + opNode.addChild(left); + opNode.addChild(right); + + working.push(opNode); + } + break; + case ADD: + case SUBTRACT: + if (working.size() == 0) { + Errors.inst.printError(EK_PARSE_UNOPERAND, tk.toString()); + return false; + } else if (working.size() == 1) { + ITree<Node> operand = working.pop(); + + ITree<Node> opNode = new Tree<>(new Node(UNARYOP, tk.type)); + + opNode.addChild(operand); + + working.push(opNode); + } else { + ITree<Node> right = working.pop(); + ITree<Node> left = working.pop(); + + ITree<Node> opNode = new Tree<>(new Node(BINOP, tk.type)); + + opNode.addChild(left); + opNode.addChild(right); + + working.push(opNode); + } + break; + case COERCE: + case DICESCALAR: + case DICEFUDGE: + if (working.size() == 0) { + Errors.inst.printError(EK_PARSE_UNOPERAND, tk.toString()); + } else { + ITree<Node> operand = working.pop(); + ITree<Node> opNode = new Tree<>(new Node(UNARYOP, tk.type)); + + opNode.addChild(operand); + + working.push(opNode); + } + break; + case INT_LIT: + case FLOAT_LIT: + case STRING_LIT: + case VREF: + case DICE_LIT: + working.push(new Tree<>(new Node(TOKREF, tk))); + break; + default: + Errors.inst.printError(EK_PARSE_INVTOKEN, tk.type.toString()); + return false; } } - for(ITree<Node> ast : working) { + for (ITree<Node> ast : working) { results.add(ast); } @@ -116,38 +116,38 @@ public class Parser { } private boolean parseClosingGrouper(Deque<ITree<Node>> working, Token tk) { - if(working.size() == 0) { + if (working.size() == 0) { Errors.inst.printError(EK_PARSE_NOCLOSE); return false; } - + ITree<Node> groupNode = null; - switch(tk.type) { - case CBRACE: - groupNode = new Tree<>(new Node(GROUP, Node.GroupType.CODE)); - break; - case CBRACKET: - groupNode = new Tree<>(new Node(GROUP, Node.GroupType.ARRAY)); - break; - default: - break; + switch (tk.type) { + case CBRACE: + groupNode = new Tree<>(new Node(GROUP, Node.GroupType.CODE)); + break; + case CBRACKET: + groupNode = new Tree<>(new Node(GROUP, Node.GroupType.ARRAY)); + break; + default: + break; } - + Token matching = null; - if(tk.type == CBRACKET) { + if (tk.type == CBRACKET) { matching = new Token(Token.Type.OBRACKET, tk.intValue); - } else if(tk.type == CBRACE) { + } else if (tk.type == CBRACE) { matching = new Token(Token.Type.OBRACE, tk.intValue); } ITree<Node> matchNode = new Tree<>(new Node(OGROUP, matching)); - if(!working.contains(matchNode)) { + if (!working.contains(matchNode)) { Errors.inst.printError(EK_PARSE_UNCLOSE, tk.toString(), matchNode.toString()); System.out.println("\tCurrent forest is: "); int treeNo = 1; - for(ITree<Node> ast : working) { + for (ITree<Node> ast : working) { System.out.println("Tree " + treeNo++ + ": " + ast.toString()); } @@ -155,20 +155,20 @@ public class Parser { } else { Deque<ITree<Node>> childs = new LinkedList<>(); - while(!working.peek().equals(matchNode)) { + while (!working.peek().equals(matchNode)) { childs.push(working.pop()); } // Discard opener working.pop(); - for(ITree<Node> child : childs) { + for (ITree<Node> child : childs) { groupNode.addChild(child); } working.push(groupNode); } - + return true; } } diff --git a/dice-lang/src/bjc/dicelang/Shunter.java b/dice-lang/src/bjc/dicelang/Shunter.java index 900f72c..48c5c67 100644 --- a/dice-lang/src/bjc/dicelang/Shunter.java +++ b/dice-lang/src/bjc/dicelang/Shunter.java @@ -22,16 +22,16 @@ public class Shunter { * Operators that are right-associative */ Set<Token.Type> rightAssoc; - + /* * Operators that aren't associative */ Set<Token.Type> notAssoc; - + // Unary operators that can only be // applied to non-operator tokens and yield operator tokens Set<Token.Type> unaryAdjectives; - + // Unary operators that can only be // applied to operator tokens and yield operator tokens Set<Token.Type> unaryAdverbs; @@ -42,210 +42,211 @@ public class Shunter { public final int MATH_PREC = 30; public final int DICE_PREC = 20; - public final int STR_PREC = 10; + public final int STR_PREC = 10; public final int EXPR_PREC = 0; public Shunter() { ops = new FunctionalMap<>(); - + rightAssoc = new HashSet<>(); - notAssoc = new HashSet<>(); + notAssoc = new HashSet<>(); unaryAdjectives = new HashSet<>(); - unaryAdverbs = new HashSet<>(); - unaryGerunds = new HashSet<>(); + unaryAdverbs = new HashSet<>(); + unaryGerunds = new HashSet<>(); unaryAdverbs.add(COERCE); - ops.put(ADD, 0 + MATH_PREC); - ops.put(SUBTRACT, 0 + MATH_PREC); + ops.put(ADD, 0 + MATH_PREC); + ops.put(SUBTRACT, 0 + MATH_PREC); - ops.put(MULTIPLY, 1 + MATH_PREC); - ops.put(IDIVIDE, 1 + MATH_PREC); - ops.put(DIVIDE, 1 + MATH_PREC); + ops.put(MULTIPLY, 1 + MATH_PREC); + ops.put(IDIVIDE, 1 + MATH_PREC); + ops.put(DIVIDE, 1 + MATH_PREC); - ops.put(DICEGROUP, 0 + DICE_PREC); + ops.put(DICEGROUP, 0 + DICE_PREC); ops.put(DICECONCAT, 1 + DICE_PREC); - ops.put(DICELIST, 2 + DICE_PREC); + ops.put(DICELIST, 2 + DICE_PREC); - ops.put(STRCAT, 0 + STR_PREC); - - ops.put(STRREP, 1 + STR_PREC); - - ops.put(LET, 0 + EXPR_PREC); - ops.put(BIND, 1 + EXPR_PREC); + ops.put(STRCAT, 0 + STR_PREC); + + ops.put(STRREP, 1 + STR_PREC); + + ops.put(LET, 0 + EXPR_PREC); + ops.put(BIND, 1 + EXPR_PREC); } public boolean shuntTokens(IList<Token> tks, IList<Token> returned) { - Deque<Token> opStack = new LinkedList<>(); + Deque<Token> opStack = new LinkedList<>(); Deque<Token> unaryOps = new LinkedList<>(); Deque<Token> currReturned = new LinkedList<>(); Deque<Token> feed = new LinkedList<>(); - for(Token tk : tks.toIterable()) { + for (Token tk : tks.toIterable()) { boolean succ; - - while(feed.size() != 0) { + + while (feed.size() != 0) { succ = shuntToken(feed.poll(), opStack, unaryOps, currReturned, feed); - - if(!succ) { + + if (!succ) { return false; } } - + succ = shuntToken(tk, opStack, unaryOps, currReturned, feed); - - if(!succ) { + + if (!succ) { return false; } } // Flush leftover operators - while(!opStack.isEmpty()) { + while (!opStack.isEmpty()) { currReturned.addLast(opStack.pop()); } - for(Token tk : currReturned) { + for (Token tk : currReturned) { returned.add(tk); } return true; } - private boolean shuntToken(Token tk, Deque<Token> opStack, - Deque<Token> unaryStack, Deque<Token> currReturned, + private boolean shuntToken(Token tk, Deque<Token> opStack, Deque<Token> unaryStack, Deque<Token> currReturned, Deque<Token> feed) { - if(unaryStack.size() != 0) { - if(isUnary(tk)) { + if (unaryStack.size() != 0) { + if (isUnary(tk)) { unaryStack.add(tk); return true; } - + Token unaryOp = unaryStack.pop(); - + Token.Type unaryType = unaryOp.type; - - if(unaryAdjectives.contains(unaryType)) { - if(isOp(tk)) { + + if (unaryAdjectives.contains(unaryType)) { + if (isOp(tk)) { Errors.inst.printError(EK_SHUNT_NOTADV, unaryOp.toString(), tk.toString()); return false; } - + Token newTok = new Token(TAGOPR); - - if(tk.type == TAGOP) { + + if (tk.type == TAGOP) { newTok.tokenValues = tk.tokenValues; } else { newTok.tokenValues = new FunctionalList<>(tk); } - + newTok.tokenValues.add(unaryOp); opStack.push(newTok); - + return true; - } else if(unaryAdverbs.contains(unaryType)) { - if(!isOp(tk)) { + } else if (unaryAdverbs.contains(unaryType)) { + if (!isOp(tk)) { Errors.inst.printError(EK_SHUNT_NOTADJ, unaryOp.toString(), tk.toString()); return false; } - + Token newTok = new Token(TAGOPR); - - if(tk.type == TAGOP) { + + if (tk.type == TAGOP) { newTok.tokenValues = tk.tokenValues; } else { newTok.tokenValues = new FunctionalList<>(tk); } - + newTok.tokenValues.add(unaryOp); opStack.push(newTok); - + return true; } } - - if(isUnary(tk)) { + + if (isUnary(tk)) { unaryStack.add(tk); return true; - } else if(isOp(tk)) { - while(!opStack.isEmpty() && isHigherPrec(tk, opStack.peek())) { + } else if (isOp(tk)) { + while (!opStack.isEmpty() && isHigherPrec(tk, opStack.peek())) { Token newOp = opStack.pop(); - - if(tk.type == newOp.type && notAssoc.contains(tk.type)) { + + if (tk.type == newOp.type && notAssoc.contains(tk.type)) { Errors.inst.printError(EK_SHUNT_NOTASSOC, tk.type.toString()); } - + currReturned.addLast(newOp); } - + opStack.push(tk); - } else if(tk.type == OPAREN || tk.type == OBRACE) { + } else if (tk.type == OPAREN || tk.type == OBRACE) { opStack.push(tk); - - if(tk.type == OBRACE) currReturned.addLast(tk); - } else if(tk.type == CPAREN || tk.type == CBRACE) { + + if (tk.type == OBRACE) + currReturned.addLast(tk); + } else if (tk.type == CPAREN || tk.type == CBRACE) { Token matching = null; - - switch(tk.type) { - case CPAREN: - matching = new Token(OPAREN, tk.intValue); - break; - case CBRACE: - matching = new Token(OBRACE, tk.intValue); - break; - default: - break; + + switch (tk.type) { + case CPAREN: + matching = new Token(OPAREN, tk.intValue); + break; + case CBRACE: + matching = new Token(OBRACE, tk.intValue); + break; + default: + break; } - - if(!opStack.contains(matching)) { + + if (!opStack.contains(matching)) { Errors.inst.printError(EK_SHUNT_NOGROUP, tk.toString(), matching.toString()); return false; } - - while(!opStack.peek().equals(matching)) { + + while (!opStack.peek().equals(matching)) { currReturned.addLast(opStack.pop()); } - - if(tk.type == CBRACE) { + + if (tk.type == CBRACE) { currReturned.addLast(tk); } - + opStack.pop(); - } else if(tk.type == GROUPSEP) { + } else if (tk.type == GROUPSEP) { IList<Token> group = new FunctionalList<>(); - - while(currReturned.size() != 0 && !currReturned.peek().isGrouper()) { + + while (currReturned.size() != 0 && !currReturned.peek().isGrouper()) { group.add(currReturned.pop()); } - - while(opStack.size() != 0 && !opStack.peek().isGrouper()) { + + while (opStack.size() != 0 && !opStack.peek().isGrouper()) { group.add(opStack.pop()); } - - if(currReturned.size() == 0) { + + if (currReturned.size() == 0) { Errors.inst.printError(EK_SHUNT_INVSEP); return false; } - + currReturned.addLast(new Token(TOKGROUP, group)); } else { currReturned.addLast(tk); } - + return true; } private boolean isHigherPrec(Token lft, Token rght) { - Token.Type left = lft.type; + Token.Type left = lft.type; Token.Type right = rght.type; boolean exists = ops.containsKey(right); - if(rght.type == TAGOPR) exists = true; + if (rght.type == TAGOPR) + exists = true; // If it doesn't, the left is higher precedence. if (!exists) { @@ -255,19 +256,19 @@ public class Shunter { int rightPrecedence; int leftPrecedence; - if(rght.type == TAGOPR) { - rightPrecedence = (int)rght.intValue; + if (rght.type == TAGOPR) { + rightPrecedence = (int) rght.intValue; } else { rightPrecedence = ops.get(right); } - if(lft.type == TAGOPR) { - leftPrecedence = (int)lft.intValue; + if (lft.type == TAGOPR) { + leftPrecedence = (int) lft.intValue; } else { - leftPrecedence = ops.get(left); + leftPrecedence = ops.get(left); } - - if(rightAssoc.contains(left)) { + + if (rightAssoc.contains(left)) { return rightPrecedence > leftPrecedence; } else { return rightPrecedence >= leftPrecedence; @@ -276,23 +277,31 @@ public class Shunter { private boolean isOp(Token tk) { Token.Type ty = tk.type; - - if(ops.containsKey(ty)) return true; - if(unaryAdjectives.contains(ty)) return true; - if(unaryAdverbs.contains(ty)) return true; - if(unaryGerunds.contains(ty)) return true; - if(ty == TAGOPR) return true; - + + if (ops.containsKey(ty)) + return true; + if (unaryAdjectives.contains(ty)) + return true; + if (unaryAdverbs.contains(ty)) + return true; + if (unaryGerunds.contains(ty)) + return true; + if (ty == TAGOPR) + return true; + return false; } private boolean isUnary(Token tk) { Token.Type ty = tk.type; - - if(unaryAdjectives.contains(ty)) return true; - if(unaryAdverbs.contains(ty)) return true; - if(unaryGerunds.contains(ty)) return true; - + + if (unaryAdjectives.contains(ty)) + return true; + if (unaryAdverbs.contains(ty)) + return true; + if (unaryGerunds.contains(ty)) + return true; + return false; } } diff --git a/dice-lang/src/bjc/dicelang/Token.java b/dice-lang/src/bjc/dicelang/Token.java index 4cc3f16..e53cba8 100644 --- a/dice-lang/src/bjc/dicelang/Token.java +++ b/dice-lang/src/bjc/dicelang/Token.java @@ -15,46 +15,34 @@ public class Token { public static enum Type { // Natural tokens // These are produced from lexemes - ADD, SUBTRACT, - MULTIPLY, - DIVIDE, IDIVIDE, - INT_LIT, FLOAT_LIT, STRING_LIT, - VREF, - DICE_LIT, DICESCALAR, DICEFUDGE, - DICEGROUP, DICECONCAT, DICELIST, - LET, BIND, COERCE, - STRCAT, STRREP, - OPAREN, CPAREN, - OBRACKET, CBRACKET, - OBRACE, CBRACE, + ADD, SUBTRACT, MULTIPLY, DIVIDE, IDIVIDE, INT_LIT, FLOAT_LIT, STRING_LIT, VREF, DICE_LIT, DICESCALAR, DICEFUDGE, DICEGROUP, DICECONCAT, DICELIST, LET, BIND, COERCE, STRCAT, STRREP, OPAREN, CPAREN, OBRACKET, CBRACKET, OBRACE, CBRACE, // Synthetic tokens // These are produced when needed - NIL, GROUPSEP, TOKGROUP, - TAGOP, TAGOPR + NIL, GROUPSEP, TOKGROUP, TAGOP, TAGOPR } - public final Type type; + public final Type type; // This is used for the following token types - // INT_LIT (int value) - // STRING_LIT (index into string table) - // VREF (index into sym table) - // O* and C* (sym-count of current token) - public long intValue; + // INT_LIT (int value) + // STRING_LIT (index into string table) + // VREF (index into sym table) + // O* and C* (sym-count of current token) + public long intValue; // This is used for the following token types - // FLOAT_LIT (float value) - public double floatValue; + // FLOAT_LIT (float value) + public double floatValue; // This is used for the following token types - // DICE_LIT (dice value) + // DICE_LIT (dice value) public DieExpression diceValue; // This is used for the following token types - // TOKGROUP (the tokens in the group) - // TAG* (the tagged construct) - public IList<Token> tokenValues; + // TOKGROUP (the tokens in the group) + // TAG* (the tagged construct) + public IList<Token> tokenValues; public Token(Type typ) { type = typ; @@ -85,58 +73,56 @@ public class Token { } public String toString() { - switch(type) { - case INT_LIT: - case STRING_LIT: - case VREF: - case OPAREN: - case CPAREN: - case OBRACKET: - case CBRACKET: - case OBRACE: - case CBRACE: - return type.toString() + "(" - + intValue + ")"; - case FLOAT_LIT: - return type.toString() + "(" - + floatValue + ")"; - case DICE_LIT: - return type.toString() + "(" - + diceValue + ")"; - case TAGOP: - case TAGOPR: - case TOKGROUP: - return type.toString() + "(" - + tokenValues + ")"; - default: - return type.toString(); + switch (type) { + case INT_LIT: + case STRING_LIT: + case VREF: + case OPAREN: + case CPAREN: + case OBRACKET: + case CBRACKET: + case OBRACE: + case CBRACE: + return type.toString() + "(" + intValue + ")"; + case FLOAT_LIT: + return type.toString() + "(" + floatValue + ")"; + case DICE_LIT: + return type.toString() + "(" + diceValue + ")"; + case TAGOP: + case TAGOPR: + case TOKGROUP: + return type.toString() + "(" + tokenValues + ")"; + default: + return type.toString(); } } public boolean equals(Object other) { - if(!(other instanceof Token)) return false; + if (!(other instanceof Token)) + return false; - Token otk = (Token)other; + Token otk = (Token) other; - if(otk.type != type) return false; + if (otk.type != type) + return false; - switch(type) { - case OBRACE: - case OBRACKET: - return intValue == otk.intValue; - default: - return true; + switch (type) { + case OBRACE: + case OBRACKET: + return intValue == otk.intValue; + default: + return true; } } public boolean isGrouper() { - switch(type) { - case OPAREN: - case OBRACE: - case OBRACKET: - return true; - default: - return false; + switch (type) { + case OPAREN: + case OBRACE: + case OBRACKET: + return true; + default: + return false; } } } diff --git a/dice-lang/src/bjc/dicelang/Tokenizer.java b/dice-lang/src/bjc/dicelang/Tokenizer.java index a4b72b9..b73c0a5 100644 --- a/dice-lang/src/bjc/dicelang/Tokenizer.java +++ b/dice-lang/src/bjc/dicelang/Tokenizer.java @@ -12,57 +12,57 @@ import java.util.regex.Pattern; import static bjc.dicelang.Errors.ErrorKey.*;
import static bjc.dicelang.Token.Type.*;
-
public class Tokenizer {
// Literal tokens for tokenization
private IMap<String, Token.Type> litTokens;
-
+
private DiceLangEngine eng;
private int nextSym = 0;
-
+
public Tokenizer(DiceLangEngine engine) {
eng = engine;
-
+
litTokens = new FunctionalMap<>();
- litTokens.put("+", ADD);
- litTokens.put("-", SUBTRACT);
- litTokens.put("*", MULTIPLY);
- litTokens.put("/", DIVIDE);
- litTokens.put("//", IDIVIDE);
- litTokens.put("sd", DICESCALAR);
- litTokens.put("df", DICEFUDGE);
- litTokens.put("dg", DICEGROUP);
- litTokens.put("dc", DICECONCAT);
- litTokens.put("dl", DICELIST);
- litTokens.put("=>", LET);
- litTokens.put(":=", BIND);
+ litTokens.put("+", ADD);
+ litTokens.put("-", SUBTRACT);
+ litTokens.put("*", MULTIPLY);
+ litTokens.put("/", DIVIDE);
+ litTokens.put("//", IDIVIDE);
+ litTokens.put("sd", DICESCALAR);
+ litTokens.put("df", DICEFUDGE);
+ litTokens.put("dg", DICEGROUP);
+ litTokens.put("dc", DICECONCAT);
+ litTokens.put("dl", DICELIST);
+ litTokens.put("=>", LET);
+ litTokens.put(":=", BIND);
litTokens.put(".+.", STRCAT);
litTokens.put(".*.", STRREP);
- litTokens.put(",", GROUPSEP);
+ litTokens.put(",", GROUPSEP);
litTokens.put("crc", COERCE);
}
-
+
public Token lexToken(String token, IMap<String, String> stringLts) {
- if(token.equals("")) return null;
+ if (token.equals(""))
+ return null;
Token tk = Token.NIL_TOKEN;
- if(litTokens.containsKey(token)) {
+ if (litTokens.containsKey(token)) {
tk = new Token(litTokens.get(token));
} else {
- switch(token.charAt(0)) {
- case '(':
- case ')':
- case '[':
- case ']':
- case '{':
- case '}':
- tk = tokenizeGrouping(token);
- break;
- default:
- tk = tokenizeLiteral(token, stringLts);
+ switch (token.charAt(0)) {
+ case '(':
+ case ')':
+ case '[':
+ case ']':
+ case '{':
+ case '}':
+ tk = tokenizeGrouping(token);
+ break;
+ default:
+ tk = tokenizeLiteral(token, stringLts);
}
}
@@ -72,52 +72,52 @@ public class Tokenizer { private Token tokenizeGrouping(String token) {
Token tk = Token.NIL_TOKEN;
- if(StringUtils.containsOnly(token, "\\" + token.charAt(0))) {
- switch(token.charAt(0)) {
- case '(':
- tk = new Token(OPAREN, token.length());
- break;
- case ')':
- tk = new Token(CPAREN, token.length());
- break;
- case '[':
- tk = new Token(OBRACKET, token.length());
- break;
- case ']':
- tk = new Token(CBRACKET, token.length());
- break;
- case '{':
- tk = new Token(OBRACE, token.length());
- break;
- case '}':
- tk = new Token(CBRACE, token.length());
- break;
- default:
- Errors.inst.printError(EK_TOK_UNGROUP, token);
- break;
+ if (StringUtils.containsOnly(token, "\\" + token.charAt(0))) {
+ switch (token.charAt(0)) {
+ case '(':
+ tk = new Token(OPAREN, token.length());
+ break;
+ case ')':
+ tk = new Token(CPAREN, token.length());
+ break;
+ case '[':
+ tk = new Token(OBRACKET, token.length());
+ break;
+ case ']':
+ tk = new Token(CBRACKET, token.length());
+ break;
+ case '{':
+ tk = new Token(OBRACE, token.length());
+ break;
+ case '}':
+ tk = new Token(CBRACE, token.length());
+ break;
+ default:
+ Errors.inst.printError(EK_TOK_UNGROUP, token);
+ break;
}
}
return tk;
}
- private Pattern hexadecimalMatcher = Pattern.compile("\\A[\\-\\+]?0x[0-9A-Fa-f]+\\Z");
+ private Pattern hexadecimalMatcher = Pattern.compile("\\A[\\-\\+]?0x[0-9A-Fa-f]+\\Z");
private Pattern flexadecimalMatcher = Pattern.compile("\\A[\\-\\+]?[0-9][0-9A-Za-z]+B\\d{1,2}\\Z");
- private Pattern stringLitMatcher = Pattern.compile("\\AstringLiteral(\\d+)\\Z");
+ private Pattern stringLitMatcher = Pattern.compile("\\AstringLiteral(\\d+)\\Z");
private Token tokenizeLiteral(String token, IMap<String, String> stringLts) {
Token tk = Token.NIL_TOKEN;
- if(StringUtils.isInt(token)) {
+ if (StringUtils.isInt(token)) {
tk = new Token(INT_LIT, Long.parseLong(token));
- } else if(hexadecimalMatcher.matcher(token).matches()) {
+ } else if (hexadecimalMatcher.matcher(token).matches()) {
String newToken = token.substring(0, 1) + token.substring(token.indexOf('x'));
tk = new Token(INT_LIT, Long.parseLong(newToken.substring(2).toUpperCase(), 16));
- } else if(flexadecimalMatcher.matcher(token).matches()) {
+ } else if (flexadecimalMatcher.matcher(token).matches()) {
int parseBase = Integer.parseInt(token.substring(token.lastIndexOf('B') + 1));
- if(parseBase < Character.MIN_RADIX || parseBase > Character.MAX_RADIX) {
+ if (parseBase < Character.MIN_RADIX || parseBase > Character.MAX_RADIX) {
Errors.inst.printError(EK_TOK_INVBASE, Integer.toString(parseBase));
return Token.NIL_TOKEN;
}
@@ -130,14 +130,14 @@ public class Tokenizer { Errors.inst.printError(EK_TOK_INVFLEX, flexNum, Integer.toString(parseBase));
return Token.NIL_TOKEN;
}
- } else if(StringUtils.isDouble(token)) {
+ } else if (StringUtils.isDouble(token)) {
tk = new Token(FLOAT_LIT, Double.parseDouble(token));
- } else if(DiceBox.isValidExpression(token)) {
+ } else if (DiceBox.isValidExpression(token)) {
tk = new Token(DICE_LIT, DiceBox.parseExpression(token));
} else {
Matcher stringLit = stringLitMatcher.matcher(token);
- if(stringLit.matches()) {
+ if (stringLit.matches()) {
int litNum = Integer.parseInt(stringLit.group(1));
eng.addStringLiteral(litNum, stringLts.get(token));
diff --git a/dice-lang/src/bjc/dicelang/dice/CompoundDie.java b/dice-lang/src/bjc/dicelang/dice/CompoundDie.java index a20095a..d4bb4b5 100644 --- a/dice-lang/src/bjc/dicelang/dice/CompoundDie.java +++ b/dice-lang/src/bjc/dicelang/dice/CompoundDie.java @@ -15,8 +15,10 @@ public class CompoundDie implements Die { /**
* Create a new compound die.
*
- * @param lft The left die
- * @param rght The right die
+ * @param lft
+ * The left die
+ * @param rght
+ * The right die
*/
public CompoundDie(Die lft, Die rght) {
left = lft;
diff --git a/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java b/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java index 3291b52..28badf4 100644 --- a/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java +++ b/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java @@ -14,13 +14,15 @@ public class CompoundingDie implements Die { private Die source;
private Predicate<Long> compoundOn;
- private String compoundPattern;
+ private String compoundPattern;
/**
* Create a new compounding die with no pattern.
*
- * @param src The die to compound from
- * @param compound The conditions to compound on
+ * @param src
+ * The die to compound from
+ * @param compound
+ * The conditions to compound on
*/
public CompoundingDie(Die src, Predicate<Long> compound) {
this(src, compound, null);
@@ -29,14 +31,18 @@ public class CompoundingDie implements Die { /**
* Create a new compounding die with a specified pattern.
*
- * @param src The die to compound from
- * @param compound The conditions to compound on
- * @param patt The string pattern the condition came from, for printing
+ * @param src
+ * The die to compound from
+ * @param compound
+ * The conditions to compound on
+ * @param patt
+ * The string pattern the condition came from, for
+ * printing
*/
public CompoundingDie(Die src, Predicate<Long> compound, String patt) {
source = src;
- compoundOn = compound;
+ compoundOn = compound;
compoundPattern = patt;
}
@@ -55,7 +61,7 @@ public class CompoundingDie implements Die { long res = source.roll();
long oldRes = res;
- while(compoundOn.test(oldRes)) {
+ while (compoundOn.test(oldRes)) {
oldRes = source.rollSingle();
res += oldRes;
@@ -72,7 +78,7 @@ public class CompoundingDie implements Die { long res = source.rollSingle();
long oldRes = res;
- while(compoundOn.test(oldRes)) {
+ while (compoundOn.test(oldRes)) {
oldRes = source.rollSingle();
res += oldRes;
@@ -83,7 +89,7 @@ public class CompoundingDie implements Die { @Override
public String toString() {
- if(compoundPattern == null) {
+ if (compoundPattern == null) {
return source + "!!";
} else {
return source + "!!" + compoundPattern;
diff --git a/dice-lang/src/bjc/dicelang/dice/DiceBox.java b/dice-lang/src/bjc/dicelang/dice/DiceBox.java index 92e58af..85edc77 100644 --- a/dice-lang/src/bjc/dicelang/dice/DiceBox.java +++ b/dice-lang/src/bjc/dicelang/dice/DiceBox.java @@ -21,23 +21,24 @@ public class DiceBox { /* * Only bother will valid expressions */ - if(!isValidExpression(exp)) return null; + if (!isValidExpression(exp)) + return null; - if(scalarDiePattern.matcher(exp).matches()) { + if (scalarDiePattern.matcher(exp).matches()) { /* * Parse scalar die */ Die scal = new ScalarDie(Long.parseLong(exp.substring(0, exp.indexOf('s')))); return new DieExpression(scal); - } else if(simpleDiePattern.matcher(exp).matches()) { + } else if (simpleDiePattern.matcher(exp).matches()) { /* * Parse simple die groups */ String[] dieParts = exp.split("d"); long right = Long.parseLong(dieParts[1]); - if(dieParts[0].equals("")) { + if (dieParts[0].equals("")) { /* * Handle short-form expressions. */ @@ -47,65 +48,65 @@ public class DiceBox { Die scal = new SimpleDie(Long.parseLong(dieParts[0]), right); return new DieExpression(scal); } - } else if(fudgeDiePattern.matcher(exp).matches()) { + } else if (fudgeDiePattern.matcher(exp).matches()) { /* * Parse fudge dice */ String nDice = exp.substring(0, exp.indexOf('d')); return new DieExpression(new FudgeDie(Long.parseLong(nDice))); - } else if(compoundDiePattern.matcher(exp).matches()) { + } else if (compoundDiePattern.matcher(exp).matches()) { /* * Parse compound die expressions */ String[] dieParts = exp.split("c"); - DieExpression left = parseExpression(dieParts[0]); + DieExpression left = parseExpression(dieParts[0]); DieExpression right = parseExpression(dieParts[1]); return new DieExpression(new CompoundDie(left.scalar, right.scalar)); - } else if(compoundingDiePattern.matcher(exp).matches()) { + } else if (compoundingDiePattern.matcher(exp).matches()) { /* * Parse compounding die expressions */ String[] dieParts = exp.split("!!"); - DieExpression left = parseExpression(dieParts[0]); + DieExpression left = parseExpression(dieParts[0]); Predicate<Long> right = deriveCond(dieParts[1]); Die scal = new CompoundingDie(left.scalar, right, dieParts[1]); return new DieExpression(scal); - } else if(explodingDiePattern.matcher(exp).matches()) { + } else if (explodingDiePattern.matcher(exp).matches()) { /* * Parse exploding die expressions */ String[] dieParts = exp.split("!"); - DieExpression left = parseExpression(dieParts[0]); + DieExpression left = parseExpression(dieParts[0]); Predicate<Long> right = deriveCond(dieParts[1]); DieList lst = new ExplodingDice(left.scalar, right, dieParts[1], false); return new DieExpression(lst); - } else if(penetratingDiePattern.matcher(exp).matches()) { + } else if (penetratingDiePattern.matcher(exp).matches()) { /* * Parse penetrating die expressions */ String[] dieParts = exp.split("p!"); - DieExpression left = parseExpression(dieParts[0]); + DieExpression left = parseExpression(dieParts[0]); Predicate<Long> right = deriveCond(dieParts[1]); DieList lst = new ExplodingDice(left.scalar, right, dieParts[1], true); return new DieExpression(lst); - } else if(diceListPattern.matcher(exp).matches()) { + } else if (diceListPattern.matcher(exp).matches()) { /* * Parse simple die lists */ String[] dieParts = exp.split("dl"); - DieExpression left = parseExpression(dieParts[0]); + DieExpression left = parseExpression(dieParts[0]); DieExpression right = parseExpression(dieParts[1]); - + DieList lst = new SimpleDieList(left.scalar, right.scalar); return new DieExpression(lst); } @@ -120,23 +121,23 @@ public class DiceBox { /* * Defines a comparison predicate */ - private static final String comparePoint = "[<>=]\\d+"; + private static final String comparePoint = "[<>=]\\d+"; /* * Defines a scalar die. * * This is just a number. */ - private static final String scalarDie = "[\\+\\-]?\\d+sd"; - private static final Pattern scalarDiePattern = Pattern.compile("\\A" + scalarDie + "\\Z"); + private static final String scalarDie = "[\\+\\-]?\\d+sd"; + private static final Pattern scalarDiePattern = Pattern.compile("\\A" + scalarDie + "\\Z"); /* * Defines a simple die. * * This is a group of one or more dice of the same size. */ - private static final String simpleDie = "(?:\\d+)?d\\d+"; - private static final Pattern simpleDiePattern = Pattern.compile("\\A" + simpleDie + "\\Z"); + private static final String simpleDie = "(?:\\d+)?d\\d+"; + private static final Pattern simpleDiePattern = Pattern.compile("\\A" + simpleDie + "\\Z"); /* * Defines a fudge die. @@ -144,24 +145,24 @@ public class DiceBox { * This is like a simple die, but all the die give -1, 0, or 1 as * results. */ - private static final String fudgeDie = "(?:\\d+)?dF"; - private static final Pattern fudgeDiePattern = Pattern.compile("\\A" + fudgeDie + "\\Z"); + private static final String fudgeDie = "(?:\\d+)?dF"; + private static final Pattern fudgeDiePattern = Pattern.compile("\\A" + fudgeDie + "\\Z"); /* * Defines a compound die. * * This is like using two d10's to simulate a d100 */ - private static final String compoundDie = simpleDie + "c(?:(?:" + simpleDie + ")|(?:\\d+))"; - private static final Pattern compoundDiePattern = Pattern.compile("\\A" + compoundDie + "\\Z"); + private static final String compoundDie = simpleDie + "c(?:(?:" + simpleDie + ")|(?:\\d+))"; + private static final Pattern compoundDiePattern = Pattern.compile("\\A" + compoundDie + "\\Z"); /* * Defines a compound group. * * This is used for forming die list type expressions. */ - private static final String compoundGroup = "(?:(?:" + scalarDie + ")|(?:" + simpleDie + ")|(?:" - + compoundDie + ")|(?:" + fudgeDie +"))"; + private static final String compoundGroup = "(?:(?:" + scalarDie + ")|(?:" + simpleDie + ")|(?:" + compoundDie + + ")|(?:" + fudgeDie + "))"; /* * Defines a compounding die. @@ -169,7 +170,7 @@ public class DiceBox { * This is like an exploding die, but is a single die, not a group of * them. */ - private static final String compoundingDie = compoundGroup + "!!" + comparePoint; + private static final String compoundingDie = compoundGroup + "!!" + comparePoint; private static final Pattern compoundingDiePattern = Pattern.compile("\\A" + compoundingDie + "\\Z"); /* @@ -178,7 +179,7 @@ public class DiceBox { * This is a die that you reroll the component of if it meets a certain * condition. */ - private static final String explodingDie = compoundGroup + "!" + comparePoint; + private static final String explodingDie = compoundGroup + "!" + comparePoint; private static final Pattern explodingDiePattern = Pattern.compile("\\A" + explodingDie + "\\Z"); /* @@ -187,7 +188,7 @@ public class DiceBox { * This is like an exploding die, but the exploded result gets a -1 * penalty. */ - private static final String penetratingDie = compoundGroup + "!" + comparePoint; + private static final String penetratingDie = compoundGroup + "!" + comparePoint; private static final Pattern penetratingDiePattern = Pattern.compile("\\A" + penetratingDie + "\\Z"); /* @@ -195,30 +196,31 @@ public class DiceBox { * * This is an array of dice of the specified size */ - private static final String diceList = compoundGroup + "dl" + compoundGroup; - private static final Pattern diceListPattern = Pattern.compile("\\A" + diceList + "\\Z"); + private static final String diceList = compoundGroup + "dl" + compoundGroup; + private static final Pattern diceListPattern = Pattern.compile("\\A" + diceList + "\\Z"); /** * Check if a given string is a valid die expression. * - * @param exp The string to check validity of. + * @param exp + * The string to check validity of. * * @return Whether or not the string is a valid command */ public static boolean isValidExpression(String exp) { - if(scalarDiePattern.matcher(exp).matches()) { + if (scalarDiePattern.matcher(exp).matches()) { return true; - } else if(simpleDiePattern.matcher(exp).matches()) { + } else if (simpleDiePattern.matcher(exp).matches()) { return true; - } else if(fudgeDiePattern.matcher(exp).matches()) { + } else if (fudgeDiePattern.matcher(exp).matches()) { return true; - } else if(compoundDiePattern.matcher(exp).matches()) { + } else if (compoundDiePattern.matcher(exp).matches()) { return true; - } else if(compoundingDiePattern.matcher(exp).matches()) { + } else if (compoundingDiePattern.matcher(exp).matches()) { return true; - } else if(explodingDiePattern.matcher(exp).matches()) { + } else if (explodingDiePattern.matcher(exp).matches()) { return true; - } else if(penetratingDiePattern.matcher(exp).matches()) { + } else if (penetratingDiePattern.matcher(exp).matches()) { return true; } else if (diceListPattern.matcher(exp).matches()) { return true; @@ -231,9 +233,9 @@ public class DiceBox { * Derive a predicate from a compare point */ private static Predicate<Long> deriveCond(String patt) { - long num = Long.parseLong(patt.substring(1)); + long num = Long.parseLong(patt.substring(1)); - switch(patt.charAt(0)) { + switch (patt.charAt(0)) { case '<': return (roll) -> roll < num; case '=': diff --git a/dice-lang/src/bjc/dicelang/dice/Die.java b/dice-lang/src/bjc/dicelang/dice/Die.java index 22ba522..0ce7d3b 100644 --- a/dice-lang/src/bjc/dicelang/dice/Die.java +++ b/dice-lang/src/bjc/dicelang/dice/Die.java @@ -12,6 +12,7 @@ public interface Die { * @return Whether this die can be optimized or not.
*/
boolean canOptimize();
+
/**
* Optimize this die to a single number.
*
@@ -20,7 +21,7 @@ public interface Die { *
* @return The optimized form of this die
*/
- long optimize();
+ long optimize();
/**
* Roll this die.
@@ -28,6 +29,7 @@ public interface Die { * @return A possible roll of this die
*/
long roll();
+
/**
* Roll only a single portion of this die.
*
diff --git a/dice-lang/src/bjc/dicelang/dice/DieExpression.java b/dice-lang/src/bjc/dicelang/dice/DieExpression.java index 81d0b7d..95e7dae 100644 --- a/dice-lang/src/bjc/dicelang/dice/DieExpression.java +++ b/dice-lang/src/bjc/dicelang/dice/DieExpression.java @@ -16,7 +16,7 @@ public class DieExpression { /**
* The scalar value in this expression, if there is one.
*/
- public Die scalar;
+ public Die scalar;
/**
* The list value in this expression, if there is one.
*/
@@ -25,7 +25,8 @@ public class DieExpression { /**
* Create a scalar die expression.
*
- * @param scal The scalar value of this expression.
+ * @param scal
+ * The scalar value of this expression.
*/
public DieExpression(Die scal) {
isList = false;
@@ -35,24 +36,29 @@ public class DieExpression { /**
* Create a list die expression.
*
- * @param lst The list value of this expression.
+ * @param lst
+ * The list value of this expression.
*/
public DieExpression(DieList lst) {
isList = true;
- list = lst;
+ list = lst;
}
@Override
public String toString() {
- if(isList) return list.toString();
- else return scalar.toString();
+ if (isList)
+ return list.toString();
+ else
+ return scalar.toString();
}
/**
* Get the value of this expression as a string.
*/
public String value() {
- if(isList) return Arrays.toString(list.roll());
- else return Long.toString(scalar.roll());
+ if (isList)
+ return Arrays.toString(list.roll());
+ else
+ return Long.toString(scalar.roll());
}
}
diff --git a/dice-lang/src/bjc/dicelang/dice/DieList.java b/dice-lang/src/bjc/dicelang/dice/DieList.java index 5454759..5cabc77 100644 --- a/dice-lang/src/bjc/dicelang/dice/DieList.java +++ b/dice-lang/src/bjc/dicelang/dice/DieList.java @@ -12,6 +12,7 @@ public interface DieList { * @return Whether or not this list cna be optimized.
*/
boolean canOptimize();
+
/**
* Optimize this list, if it can be done.
*
@@ -19,12 +20,13 @@ public interface DieList { *
* @return The optimized form of this list.
*/
- long[] optimize();
+ long[] optimize();
/**
* Roll this group of dice.
*
- * @param A possible roll of this group.
+ * @param A
+ * possible roll of this group.
*/
long[] roll();
}
diff --git a/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java b/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java index 59e739e..eeafbd1 100644 --- a/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java +++ b/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java @@ -16,20 +16,22 @@ public class ExplodingDice implements DieList { /*
* The source die to use.
*/
- private Die source;
+ private Die source;
/*
* The conditions for exploding.
*/
private Predicate<Long> explodeOn;
- private String explodePattern;
- private boolean explodePenetrates;
+ private String explodePattern;
+ private boolean explodePenetrates;
/**
* Create a new exploding die.
*
- * @param src The source die for exploding.
- * @param explode The condition to explode on.
+ * @param src
+ * The source die for exploding.
+ * @param explode
+ * The condition to explode on.
*/
public ExplodingDice(Die src, Predicate<Long> explode) {
this(src, explode, null, false);
@@ -38,10 +40,13 @@ public class ExplodingDice implements DieList { /**
* Create a new exploding die that may penetrate.
*
- * @param src The source die for exploding.
- * @param explode The condition to explode on.
- * @param penetrate Whether or not for explosions to penetrate (-1 to
- * exploded die).
+ * @param src
+ * The source die for exploding.
+ * @param explode
+ * The condition to explode on.
+ * @param penetrate
+ * Whether or not for explosions to penetrate (-1 to
+ * exploded die).
*/
public ExplodingDice(Die src, Predicate<Long> explode, boolean penetrate) {
this(src, explode, null, penetrate);
@@ -50,17 +55,20 @@ public class ExplodingDice implements DieList { /**
* Create a new exploding die that may penetrate.
*
- * @param src The source die for exploding.
- * @param explode The condition to explode on.
- * @param penetrate Whether or not for explosions to penetrate (-1 to
- * exploded die).
- * @param patt The string the condition came from, for printing.
+ * @param src
+ * The source die for exploding.
+ * @param explode
+ * The condition to explode on.
+ * @param penetrate
+ * Whether or not for explosions to penetrate (-1 to
+ * exploded die).
+ * @param patt
+ * The string the condition came from, for printing.
*/
- public ExplodingDice(Die src, Predicate<Long> explode, String patt,
- boolean penetrate) {
- source = src;
- explodeOn = explode;
- explodePattern = patt;
+ public ExplodingDice(Die src, Predicate<Long> explode, String patt, boolean penetrate) {
+ source = src;
+ explodeOn = explode;
+ explodePattern = patt;
explodePenetrates = penetrate;
}
@@ -81,10 +89,11 @@ public class ExplodingDice implements DieList { List<Long> resList = new LinkedList<>();
- while(explodeOn.test(oldRes)) {
+ while (explodeOn.test(oldRes)) {
oldRes = source.rollSingle();
- if(explodePenetrates) oldRes -= 1;
+ if (explodePenetrates)
+ oldRes -= 1;
resList.add(oldRes);
}
@@ -92,9 +101,9 @@ public class ExplodingDice implements DieList { newRes[0] = res;
int i = 1;
- for(long rll : resList) {
+ for (long rll : resList) {
newRes[i] = rll;
- i += 1;
+ i += 1;
}
return newRes;
@@ -102,7 +111,7 @@ public class ExplodingDice implements DieList { @Override
public String toString() {
- if(explodePattern == null) {
+ if (explodePattern == null) {
return source + (explodePenetrates ? "p" : "") + "!";
} else {
return source + (explodePenetrates ? "p" : "") + "!" + explodePattern;
diff --git a/dice-lang/src/bjc/dicelang/dice/FudgeDie.java b/dice-lang/src/bjc/dicelang/dice/FudgeDie.java index 554c7ff..8061475 100644 --- a/dice-lang/src/bjc/dicelang/dice/FudgeDie.java +++ b/dice-lang/src/bjc/dicelang/dice/FudgeDie.java @@ -21,10 +21,10 @@ public class FudgeDie implements Die { public long roll() {
long res = 0;
-
+
long nDice = numDice.roll();
- for(int i = 0; i < nDice; i++) {
+ for (int i = 0; i < nDice; i++) {
res += rollSingle();
}
diff --git a/dice-lang/src/bjc/dicelang/dice/MathDie.java b/dice-lang/src/bjc/dicelang/dice/MathDie.java index 7e9204d..2e82a6e 100644 --- a/dice-lang/src/bjc/dicelang/dice/MathDie.java +++ b/dice-lang/src/bjc/dicelang/dice/MathDie.java @@ -5,7 +5,7 @@ public class MathDie implements Die { ADD, SUBTRACT, MULTIPLY;
public String toString() {
- switch(this) {
+ switch (this) {
case ADD:
return "+";
case SUBTRACT:
@@ -26,7 +26,7 @@ public class MathDie implements Die { public MathDie(MathDie.MathOp op, Die lft, Die rght) {
type = op;
- left = lft;
+ left = lft;
right = rght;
}
@@ -35,7 +35,7 @@ public class MathDie implements Die { }
private long performOp(long lft, long rght) {
- switch(type) {
+ switch (type) {
case ADD:
return lft + rght;
case SUBTRACT:
@@ -48,21 +48,21 @@ public class MathDie implements Die { }
public long optimize() {
- long lft = left.optimize();
+ long lft = left.optimize();
long rght = right.optimize();
return performOp(lft, rght);
}
public long roll() {
- long lft = left.roll();
+ long lft = left.roll();
long rght = right.roll();
return performOp(lft, rght);
}
public long rollSingle() {
- long lft = left.rollSingle();
+ long lft = left.rollSingle();
long rght = right.rollSingle();
return performOp(lft, rght);
diff --git a/dice-lang/src/bjc/dicelang/dice/SimpleDie.java b/dice-lang/src/bjc/dicelang/dice/SimpleDie.java index 5ba76ef..fc1aacd 100644 --- a/dice-lang/src/bjc/dicelang/dice/SimpleDie.java +++ b/dice-lang/src/bjc/dicelang/dice/SimpleDie.java @@ -5,36 +5,39 @@ public class SimpleDie implements Die { private Die diceSize;
public SimpleDie(long nDice, long size) {
- numDice = new ScalarDie(nDice);
+ numDice = new ScalarDie(nDice);
diceSize = new ScalarDie(size);
}
public SimpleDie(Die nDice, long size) {
- numDice = nDice;
+ numDice = nDice;
diceSize = new ScalarDie(size);
}
public SimpleDie(long nDice, Die size) {
- numDice = new ScalarDie(nDice);
+ numDice = new ScalarDie(nDice);
diceSize = size;
}
public SimpleDie(Die nDice, Die size) {
- numDice = nDice;
+ numDice = nDice;
diceSize = size;
}
public boolean canOptimize() {
- if(diceSize.canOptimize() && (diceSize.optimize() <= 1)) {
+ if (diceSize.canOptimize() && (diceSize.optimize() <= 1)) {
return numDice.canOptimize();
- } else return false;
+ } else
+ return false;
}
public long optimize() {
long optSize = diceSize.optimize();
- if(optSize == 0) return 0;
- else return numDice.optimize();
+ if (optSize == 0)
+ return 0;
+ else
+ return numDice.optimize();
}
public long roll() {
@@ -43,7 +46,7 @@ public class SimpleDie implements Die { long nDice = numDice.roll();
long dSize = diceSize.roll();
- for(int i = 0; i < nDice; i++) {
+ for (int i = 0; i < nDice; i++) {
total += (Math.abs(DiceBox.rng.nextLong()) % dSize) + 1;
}
diff --git a/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java b/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java index cca1f04..e166949 100644 --- a/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java +++ b/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java @@ -10,7 +10,7 @@ public class SimpleDieList implements DieList { }
public boolean canOptimize() {
- if(size.canOptimize() && size.optimize() <= 1) {
+ if (size.canOptimize() && size.optimize() <= 1) {
return numDice.canOptimize();
} else {
return false;
@@ -18,12 +18,12 @@ public class SimpleDieList implements DieList { }
public long[] optimize() {
- int sze = (int)numDice.optimize();
+ int sze = (int) numDice.optimize();
long res = size.optimize();
long[] ret = new long[sze];
- for(int i = 0; i < sze; i++) {
+ for (int i = 0; i < sze; i++) {
ret[i] = res;
}
@@ -31,11 +31,11 @@ public class SimpleDieList implements DieList { }
public long[] roll() {
- int num = (int)numDice.roll();
+ int num = (int) numDice.roll();
long[] ret = new long[num];
- for(int i = 0; i < num; i++) {
+ for (int i = 0; i < num; i++) {
ret[i] = size.roll();
}
diff --git a/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java b/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java index 8759c84..8d63be2 100644 --- a/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java +++ b/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java @@ -24,42 +24,31 @@ public class StreamControlEngine { static class Token { public static enum Type { /* - * Natural tokens. - * These come directly from strings + * Natural tokens. These come directly from strings */ - ILIT, FLIT, BLIT, - SQUOTE, DQUOTE, - OBRACKET, OBRACE, - SYMBOL, WORD, + ILIT, FLIT, BLIT, SQUOTE, DQUOTE, OBRACKET, OBRACE, SYMBOL, WORD, /* - * Synthetic tokens. - * These are produced from special tokens. + * Synthetic tokens. These are produced from special + * tokens. */ - SLIT, - WORDS, ARRAY, + SLIT, WORDS, ARRAY, /* - * Word tokens - * These are subordinate to WORD tokens + * Word tokens These are subordinate to WORD tokens */ /* * Array manipulation */ - MAKEARRAY, - MAKEEXEC, MAKEUNEXEC, + MAKEARRAY, MAKEEXEC, MAKEUNEXEC, /* * Stream manipulation */ - NEWSTREAM, - LEFTSTREAM, RIGHTSTREAM, - DELETESTREAM, MERGESTREAM, + NEWSTREAM, LEFTSTREAM, RIGHTSTREAM, DELETESTREAM, MERGESTREAM, /* * Stack manipulation */ - STACKCOUNT, STACKEMPTY, - DROP, NDROP, - NIP, NNIP, + STACKCOUNT, STACKEMPTY, DROP, NDROP, NIP, NNIP, } /* @@ -68,35 +57,27 @@ public class StreamControlEngine { public Type type; /* - * Used for - * ILIT + * Used for ILIT */ public long intVal; /* - * Used for - * FLIT + * Used for FLIT */ public double floatVal; /* - * Used for - * BLIT + * Used for BLIT */ public boolean boolVal; /* - * Used for - * SYMBOL - * SLIT + * Used for SYMBOL SLIT */ public String stringVal; /* - * Used for - * WORD + * Used for WORD */ public Token tokenVal; /* - * Used for - * WORDS - * ARRAY + * Used for WORDS ARRAY */ public IList<Token> tokenVals; @@ -138,7 +119,6 @@ public class StreamControlEngine { this(typ, new Token(tVal)); } - public Token(Type typ, IList<Token> tVals) { this(typ); @@ -146,19 +126,19 @@ public class StreamControlEngine { } public static Token tokenizeString(String token) { - if(litTokens.containsKey(token)) { + if (litTokens.containsKey(token)) { return new Token(litTokens.get(token)); - } else if(token.startsWith("\\")) { + } else if (token.startsWith("\\")) { return new Token(SYMBOL, token.substring(1)); - } else if(builtinWords.containsKey(token)) { + } else if (builtinWords.containsKey(token)) { return new Token(WORD, builtinWords.get(token)); - } else if(token.equals("true")) { + } else if (token.equals("true")) { return new Token(BLIT, true); - } else if(token.equals("false")) { + } else if (token.equals("false")) { return new Token(BLIT, false); - } else if(StringUtils.isInt(token)) { + } else if (StringUtils.isInt(token)) { return new Token(ILIT, Long.parseLong(token)); - } else if(StringUtils.isDouble(token)) { + } else if (StringUtils.isDouble(token)) { return new Token(FLIT, Double.parseDouble(token)); } else { Errors.inst.printError(EK_SCL_INVTOKEN, token); @@ -167,32 +147,32 @@ public class StreamControlEngine { } private static final Map<String, Token.Type> litTokens; - private static final Map<String, Token.Type> builtinWords; + private static final Map<String, Token.Type> builtinWords; static { litTokens = new HashMap<>(); - litTokens.put("'", SQUOTE); + litTokens.put("'", SQUOTE); litTokens.put("\"", DQUOTE); - litTokens.put("[", OBRACKET); + litTokens.put("[", OBRACKET); litTokens.put("{", OBRACE); builtinWords = new HashMap<>(); builtinWords.put("makearray", MAKEARRAY); - builtinWords.put("+stream", NEWSTREAM); - builtinWords.put(">stream", LEFTSTREAM); - builtinWords.put("<stream", RIGHTSTREAM); - builtinWords.put("-stream", DELETESTREAM); - builtinWords.put("<-stream", MERGESTREAM); - builtinWords.put("cvx", MAKEEXEC); - builtinWords.put("cvux", MAKEUNEXEC); - builtinWords.put("#", STACKCOUNT); - builtinWords.put("empty?", STACKEMPTY); - builtinWords.put("drop", DROP); - builtinWords.put("ndrop", NDROP); - builtinWords.put("nip", NIP); - builtinWords.put("nnip", NNIP); + builtinWords.put("+stream", NEWSTREAM); + builtinWords.put(">stream", LEFTSTREAM); + builtinWords.put("<stream", RIGHTSTREAM); + builtinWords.put("-stream", DELETESTREAM); + builtinWords.put("<-stream", MERGESTREAM); + builtinWords.put("cvx", MAKEEXEC); + builtinWords.put("cvux", MAKEUNEXEC); + builtinWords.put("#", STACKCOUNT); + builtinWords.put("empty?", STACKEMPTY); + builtinWords.put("drop", DROP); + builtinWords.put("ndrop", NDROP); + builtinWords.put("nip", NIP); + builtinWords.put("nnip", NNIP); } } @@ -205,38 +185,42 @@ public class StreamControlEngine { public StreamControlEngine(StreamEngine eng) { this.eng = eng; - words = new HashMap<>(); + words = new HashMap<>(); curStack = new SimpleStack<>(); } /** * Run a SCL program. * - * @param tokens The program to run + * @param tokens + * The program to run * * @return Whether the program executed succesfully */ public boolean runProgram(String[] tokens) { - for(int i = 0; i < tokens.length; i++) { + for (int i = 0; i < tokens.length; i++) { String token = tokens[i]; Token tok = Token.tokenizeString(token); - - if(tok == null) { + + if (tok == null) { return false; } - switch(tok.type) { + switch (tok.type) { case SQUOTE: i = handleSingleQuote(i, tokens); - if(i == -1) return false; + if (i == -1) + return false; break; case OBRACKET: i = handleDelim(i, tokens, "]"); - if(i == -1) return false; + if (i == -1) + return false; break; case OBRACE: i = handleDelim(i, tokens, "}"); - if(i == -1) return false; + if (i == -1) + return false; Token brak = curStack.pop(); curStack.push(new Token(ARRAY, brak.tokenVals)); break; @@ -255,37 +239,44 @@ public class StreamControlEngine { private boolean handleWord(Token tk) { boolean succ = true; - switch(tk.tokenVal.type) { + switch (tk.tokenVal.type) { case NEWSTREAM: eng.newStream(); break; case LEFTSTREAM: succ = eng.leftStream(); - if(!succ) return false; + if (!succ) + return false; break; case RIGHTSTREAM: succ = eng.rightStream(); - if(!succ) return false; + if (!succ) + return false; break; case DELETESTREAM: succ = eng.deleteStream(); - if(!succ) return false; + if (!succ) + return false; break; case MERGESTREAM: succ = eng.mergeStream(); - if(!succ) return false; + if (!succ) + return false; break; case MAKEARRAY: succ = makeArray(); - if(!succ) return false; + if (!succ) + return false; break; case MAKEEXEC: succ = toggleExec(true); - if(!succ) return false; + if (!succ) + return false; break; case MAKEUNEXEC: succ = toggleExec(false); - if(!succ) return false; + if (!succ) + return false; break; case STACKCOUNT: curStack.push(new Token(ILIT, curStack.size())); @@ -294,7 +285,7 @@ public class StreamControlEngine { curStack.push(new Token(BLIT, curStack.empty())); break; case DROP: - if(curStack.size() == 0) { + if (curStack.size() == 0) { Errors.inst.printError(EK_SCL_SUNDERFLOW, tk.tokenVal.type.toString()); return false; } @@ -302,19 +293,21 @@ public class StreamControlEngine { break; case NDROP: succ = handleNDrop(); - if(!succ) return false; + if (!succ) + return false; break; case NIP: - if(curStack.size() < 2) { + if (curStack.size() < 2) { Errors.inst.printError(EK_SCL_SUNDERFLOW, tk.tokenVal.type.toString()); return false; } - + curStack.nip(); break; case NNIP: succ = handleNNip(); - if(!succ) return false; + if (!succ) + return false; break; default: Errors.inst.printError(EK_SCL_UNWORD, tk.tokenVal.type.toString()); @@ -327,14 +320,14 @@ public class StreamControlEngine { private boolean handleNNip() { Token num = curStack.pop(); - if(num.type != ILIT) { + if (num.type != ILIT) { Errors.inst.printError(EK_SCL_INVARG, num.type.toString()); return false; } - int n = (int)num.intVal; - - if(curStack.size() < n) { + int n = (int) num.intVal; + + if (curStack.size() < n) { Errors.inst.printError(EK_SCL_SUNDERFLOW, NNIP.toString()); return false; } @@ -346,14 +339,14 @@ public class StreamControlEngine { private boolean handleNDrop() { Token num = curStack.pop(); - if(num.type != ILIT) { + if (num.type != ILIT) { Errors.inst.printError(EK_SCL_INVARG, num.type.toString()); return false; } - int n = (int)num.intVal; - - if(curStack.size() < n) { + int n = (int) num.intVal; + + if (curStack.size() < n) { Errors.inst.printError(EK_SCL_SUNDERFLOW, NDROP.toString()); return false; } @@ -365,15 +358,15 @@ public class StreamControlEngine { private boolean toggleExec(boolean exec) { Token top = curStack.top(); - if(exec) { - if(top.type != ARRAY) { + if (exec) { + if (top.type != ARRAY) { Errors.inst.printError(EK_SCL_INVARG, top.toString()); return false; } top.type = WORDS; } else { - if(top.type != WORDS) { + if (top.type != WORDS) { Errors.inst.printError(EK_SCL_INVARG, top.toString()); return false; } @@ -387,13 +380,13 @@ public class StreamControlEngine { private boolean makeArray() { Token num = curStack.pop(); - if(num.type != ILIT) { + if (num.type != ILIT) { Errors.inst.printError(EK_SCL_INVARG, num.type.toString()); } IList<Token> arr = new FunctionalList<>(); - for(int i = 0; i < num.intVal; i++) { + for (int i = 0; i < num.intVal; i++) { arr.add(curStack.pop()); } @@ -405,30 +398,33 @@ public class StreamControlEngine { private int handleDelim(int i, String[] tokens, String delim) { IList<Token> toks = new FunctionalList<>(); - int n = i + 1; - if(n >= tokens.length) { + int n = i + 1; + if (n >= tokens.length) { Errors.inst.printError(EK_SCL_MMQUOTE); return -1; } String tok = tokens[n]; - while(!tok.equals(delim)) { + while (!tok.equals(delim)) { Token ntok = Token.tokenizeString(tok); - switch(ntok.type) { + switch (ntok.type) { case SQUOTE: n = handleSingleQuote(n, tokens); - if(n == -1) return -1; + if (n == -1) + return -1; toks.add(curStack.pop()); break; case OBRACKET: n = handleDelim(n, tokens, "]"); - if(n == -1) return -1; + if (n == -1) + return -1; toks.add(curStack.pop()); break; case OBRACE: i = handleDelim(i, tokens, "}"); - if(i == -1) return -1; + if (i == -1) + return -1; Token brak = curStack.pop(); toks.add(new Token(ARRAY, brak.tokenVals)); break; @@ -438,8 +434,8 @@ public class StreamControlEngine { /* * Move to the next token */ - n += 1; - if(n >= tokens.length) { + n += 1; + if (n >= tokens.length) { Errors.inst.printError(EK_SCL_MMQUOTE); return -1; } @@ -459,15 +455,15 @@ public class StreamControlEngine { private int handleSingleQuote(int i, String[] tokens) { StringBuilder sb = new StringBuilder(); - int n = i + 1; - if(n >= tokens.length) { + int n = i + 1; + if (n >= tokens.length) { Errors.inst.printError(EK_SCL_MMQUOTE); return -1; } String tok = tokens[n]; - while(!tok.equals("'")) { - if(tok.matches("\\\\+'")) { + while (!tok.equals("'")) { + if (tok.matches("\\\\+'")) { /* * Handle escaped quotes. */ @@ -479,8 +475,8 @@ public class StreamControlEngine { /* * Move to the next token */ - n += 1; - if(n >= tokens.length) { + n += 1; + if (n >= tokens.length) { Errors.inst.printError(EK_SCL_MMQUOTE); return -1; } diff --git a/dice-lang/src/bjc/dicelang/scl/StreamEngine.java b/dice-lang/src/bjc/dicelang/scl/StreamEngine.java index 65e566d..9bcad9b 100644 --- a/dice-lang/src/bjc/dicelang/scl/StreamEngine.java +++ b/dice-lang/src/bjc/dicelang/scl/StreamEngine.java @@ -32,7 +32,7 @@ public class StreamEngine { * Our streams. */ Tape<IList<String>> streams; - IList<String> currStream; + IList<String> currStream; /* * Saved streams @@ -47,7 +47,8 @@ public class StreamEngine { /** * Create a new stream engine. * - * @param engine The dice engine we're attached to. + * @param engine + * The dice engine we're attached to. */ public StreamEngine(DiceLangEngine engine) { eng = engine; @@ -72,8 +73,10 @@ public class StreamEngine { /** * Process a possibly interleaved set of streams from toks into dest. * - * @param toks The raw token to read streams from. - * @param dest The list to write the final stream to. + * @param toks + * The raw token to read streams from. + * @param dest + * The list to write the final stream to. * * @return Whether or not the streams were successfully processed. */ @@ -91,23 +94,23 @@ public class StreamEngine { /* * Process each token. */ - for(String tk : toks) { + for (String tk : toks) { /* * Process stream commands. */ - if(tk.startsWith("{@S") && !quoteMode) { - if(tk.equals("{@SQ}")) { + if (tk.startsWith("{@S") && !quoteMode) { + if (tk.equals("{@SQ}")) { quoteMode = true; - } else if(!processCommand(tk)) { + } else if (!processCommand(tk)) { return false; } /* * Command ran correctly, continue */ } else { - if(tk.equals("{@SU}")) { + if (tk.equals("{@SU}")) { quoteMode = false; - } else if(tk.startsWith("\\") && tk.endsWith("{@SU}")) { + } else if (tk.startsWith("\\") && tk.endsWith("{@SU}")) { currStream.add(tk.substring(1)); } else { currStream.add(tk); @@ -115,7 +118,7 @@ public class StreamEngine { } } - for(String tk : currStream) { + for (String tk : currStream) { dest.add(tk); } @@ -127,7 +130,7 @@ public class StreamEngine { } public boolean rightStream() { - if(!streams.right()) { + if (!streams.right()) { Errors.inst.printError(EK_STRM_NONEX); return false; } @@ -137,7 +140,7 @@ public class StreamEngine { } public boolean leftStream() { - if(!streams.left()) { + if (!streams.left()) { Errors.inst.printError(EK_STRM_NONEX); return false; } @@ -147,7 +150,7 @@ public class StreamEngine { } public boolean deleteStream() { - if(streams.size() == 1) { + if (streams.size() == 1) { Errors.inst.printError(EK_STRM_LAST); return false; } else { @@ -159,7 +162,7 @@ public class StreamEngine { } public boolean mergeStream() { - if(streams.size() == 1) { + if (streams.size() == 1) { Errors.inst.printError(EK_STRM_LAST); return false; } else { @@ -174,7 +177,7 @@ public class StreamEngine { private boolean processCommand(String tk) { char[] comms = null; - if(tk.length() > 5) { + if (tk.length() > 5) { comms = tk.substring(3, tk.length() - 1).toCharArray(); } else { comms = new char[1]; @@ -183,30 +186,35 @@ public class StreamEngine { boolean succ; - for(char comm : comms) { - switch(comm) { + for (char comm : comms) { + switch (comm) { case '+': newStream(); break; case '>': succ = rightStream(); - if(!succ) return false; + if (!succ) + return false; break; case '<': succ = leftStream(); - if(!succ) return false; + if (!succ) + return false; break; case '-': succ = deleteStream(); - if(!succ) return false; + if (!succ) + return false; break; case 'M': succ = mergeStream(); - if(!succ) return false; + if (!succ) + return false; break; case 'L': succ = scleng.runProgram(currStream.toArray(new String[0])); - if(!succ) return false; + if (!succ) + return false; break; default: Errors.inst.printError(EK_STRM_INVCOM, tk); diff --git a/dice-lang/src/bjc/dicelang/v1/BindingDiceExpression.java b/dice-lang/src/bjc/dicelang/v1/BindingDiceExpression.java index 019f5ee..cce31a2 100644 --- a/dice-lang/src/bjc/dicelang/v1/BindingDiceExpression.java +++ b/dice-lang/src/bjc/dicelang/v1/BindingDiceExpression.java @@ -13,33 +13,32 @@ public class BindingDiceExpression implements IDiceExpression { /* * The expression being bound to a name */ - private IDiceExpression expression; + private IDiceExpression expression; /* * The name to bind the expression to */ - private String name; + private String name; /** * Create a new dice expression binder from two expressions and an * enviroment * * @param left - * The left side expression to get a name from. Must be a - * ReferenceDiceExpression + * The left side expression to get a name from. Must be a + * ReferenceDiceExpression * @param right - * The right side to bind to the name + * The right side to bind to the name * @param enviroment - * The enviroment to bind into + * The enviroment to bind into */ - public BindingDiceExpression(IDiceExpression left, - IDiceExpression right, + public BindingDiceExpression(IDiceExpression left, IDiceExpression right, Map<String, IDiceExpression> enviroment) { if (!(left instanceof ReferenceDiceExpression)) { throw new UnsupportedOperationException( "Error: Binding an expression to something that is not a variable reference," - + " or array thereof. is unsupported." - + " Problematic expression is " + left); + + " or array thereof. is unsupported." + + " Problematic expression is " + left); } String varName = ((ReferenceDiceExpression) left).getName(); @@ -51,19 +50,17 @@ public class BindingDiceExpression implements IDiceExpression { * Create a new dice expression binder * * @param name - * The name of the variable to bind + * The name of the variable to bind * @param expression - * The expression to bind to the variable + * The expression to bind to the variable * @param enviroment - * The enviroment to bind it in + * The enviroment to bind it in */ - public BindingDiceExpression(String name, IDiceExpression expression, - Map<String, IDiceExpression> enviroment) { + public BindingDiceExpression(String name, IDiceExpression expression, Map<String, IDiceExpression> enviroment) { initialize(name, expression, enviroment); } - private void initialize(String name, IDiceExpression expr, - Map<String, IDiceExpression> enviroment) { + private void initialize(String name, IDiceExpression expr, Map<String, IDiceExpression> enviroment) { this.name = name; this.expression = expr; @@ -87,7 +84,6 @@ public class BindingDiceExpression implements IDiceExpression { */ @Override public String toString() { - return "assign[n=" + name + ", exp=" - + expression.toString() + "]"; + return "assign[n=" + name + ", exp=" + expression.toString() + "]"; } } diff --git a/dice-lang/src/bjc/dicelang/v1/ComplexDice.java b/dice-lang/src/bjc/dicelang/v1/ComplexDice.java index 62d59c6..b9796f9 100644 --- a/dice-lang/src/bjc/dicelang/v1/ComplexDice.java +++ b/dice-lang/src/bjc/dicelang/v1/ComplexDice.java @@ -1,8 +1,8 @@ package bjc.dicelang.v1; /** - * Implements a collection of one or more of a particular die, where the - * number of dice in the group is variable. + * Implements a collection of one or more of a particular die, where the number + * of dice in the group is variable. * * @author ben * @@ -12,7 +12,7 @@ public class ComplexDice implements IDiceExpression { * Create a dice from a string expression * * @param expression - * The string to parse the dice from + * The string to parse the dice from * @return A dice group parsed from the string */ public static IDiceExpression fromString(String expression) { @@ -28,38 +28,35 @@ public class ComplexDice implements IDiceExpression { try { // Create the actual group of dice - return new ComplexDice( - new ScalarDie(Integer.parseInt(strangs[0])), + return new ComplexDice(new ScalarDie(Integer.parseInt(strangs[0])), new Die(Integer.parseInt(strangs[1]))); } catch (NumberFormatException nfex) { // We don't care about details // Tell the user the expression is invalid - throw new IllegalArgumentException( - "Attempted to create a set of dice using invalid arguments." - + " They must be integers. " + strangs[0] - + " and " + strangs[1] - + " are likely culprits."); + throw new IllegalArgumentException("Attempted to create a set of dice using invalid arguments." + + " They must be integers. " + strangs[0] + " and " + strangs[1] + + " are likely culprits."); } } /* * The die being rolled */ - private IDiceExpression die; + private IDiceExpression die; /* * The number of the particular die to roll */ - private IDiceExpression nDice; + private IDiceExpression nDice; /** * Create a new collection of dice * * @param nDce - * The number of dice in the collection + * The number of dice in the collection * @param de - * The type of dice the collection is composed of + * The type of dice the collection is composed of */ public ComplexDice(IDiceExpression nDce, IDiceExpression de) { nDice = nDce; @@ -70,9 +67,9 @@ public class ComplexDice implements IDiceExpression { * Create a new collection of dice * * @param nSides - * The number of dice in the collection + * The number of dice in the collection * @param de - * The type of dice the collection is composed of + * The type of dice the collection is composed of */ public ComplexDice(int nSides, int de) { nDice = new ScalarDie(nSides); @@ -93,10 +90,9 @@ public class ComplexDice implements IDiceExpression { @Override public int optimize() { if (!canOptimize()) { - throw new UnsupportedOperationException( - "This complex dice cannot be optimized. " - + "Both the dice to be rolled and the number of" - + " dice must be optimizable."); + throw new UnsupportedOperationException("This complex dice cannot be optimized. " + + "Both the dice to be rolled and the number of" + + " dice must be optimizable."); } return nDice.optimize(); @@ -112,9 +108,8 @@ public class ComplexDice implements IDiceExpression { int nRoll = nDice.roll(); if (nRoll < 0) { - throw new UnsupportedOperationException( - "Attempted to roll a negative number of dice. " - + "The problematic expression is " + nDice); + throw new UnsupportedOperationException("Attempted to roll a negative number of dice. " + + "The problematic expression is " + nDice); } // Roll all the dice and combine them @@ -132,7 +127,6 @@ public class ComplexDice implements IDiceExpression { return nDice.toString() + die.toString(); } - return "complex[n=" + nDice.toString() + ", d=" + die.toString() - + "]"; + return "complex[n=" + nDice.toString() + ", d=" + die.toString() + "]"; } } diff --git a/dice-lang/src/bjc/dicelang/v1/CompoundDice.java b/dice-lang/src/bjc/dicelang/v1/CompoundDice.java index 2d53540..a70ae39 100644 --- a/dice-lang/src/bjc/dicelang/v1/CompoundDice.java +++ b/dice-lang/src/bjc/dicelang/v1/CompoundDice.java @@ -3,8 +3,8 @@ package bjc.dicelang.v1; /** * Implements a "compound dice" * - * To explain, a compound dice is something like a d100 composed from two - * d10s instead of a hundred sided die. + * To explain, a compound dice is something like a d100 composed from two d10s + * instead of a hundred sided die. * * @author ben * @@ -13,20 +13,20 @@ public class CompoundDice implements IDiceExpression { /* * The left die of the expression */ - private IDiceExpression left; + private IDiceExpression left; /* * The right die of the expression */ - private IDiceExpression right; + private IDiceExpression right; /** * Create a new compound dice using the specified dice * * @param lft - * The die to use on the left + * The die to use on the left * @param rght - * The die to use on the right + * The die to use on the right */ public CompoundDice(IDiceExpression lft, IDiceExpression rght) { this.left = lft; @@ -37,20 +37,19 @@ public class CompoundDice implements IDiceExpression { * Create a new compound dice from two dice strings * * @param lft - * The left side dice as a string + * The left side dice as a string * @param rght - * The right side dice as a string + * The right side dice as a string */ public CompoundDice(String lft, String rght) { - this(ComplexDice.fromString(lft), - ComplexDice.fromString(rght)); + this(ComplexDice.fromString(lft), ComplexDice.fromString(rght)); } /** * Create a new compound dice from an array of dice strings * * @param exps - * An array of two dice strings + * An array of two dice strings */ public CompoundDice(String[] exps) { this(exps[0], exps[1]); @@ -64,14 +63,11 @@ public class CompoundDice implements IDiceExpression { @Override public int optimize() { if (!canOptimize()) { - throw new UnsupportedOperationException( - "Cannot optimize this compound dice. " - + "Both component dice must be optimizable" - + " to optimize a compound dice"); + throw new UnsupportedOperationException("Cannot optimize this compound dice. " + + "Both component dice must be optimizable" + " to optimize a compound dice"); } - return Integer - .parseInt(left.optimize() + "" + right.optimize()); + return Integer.parseInt(left.optimize() + "" + right.optimize()); } @Override @@ -84,7 +80,6 @@ public class CompoundDice implements IDiceExpression { @Override public String toString() { - return "compound[l=" + left.toString() + ", r=" - + right.toString() + "]"; + return "compound[l=" + left.toString() + ", r=" + right.toString() + "]"; } } diff --git a/dice-lang/src/bjc/dicelang/v1/DiceExpressionBuilder.java b/dice-lang/src/bjc/dicelang/v1/DiceExpressionBuilder.java index eb19c2a..e0c62c1 100644 --- a/dice-lang/src/bjc/dicelang/v1/DiceExpressionBuilder.java +++ b/dice-lang/src/bjc/dicelang/v1/DiceExpressionBuilder.java @@ -21,7 +21,7 @@ public class DiceExpressionBuilder { * Build a dice expression from a seed dice expression * * @param seed - * The dice expression to use as a seed + * The dice expression to use as a seed */ public DiceExpressionBuilder(IDiceExpression seed) { baking = seed; @@ -31,9 +31,9 @@ public class DiceExpressionBuilder { * Build a dice expression from a seed dice * * @param nSides - * The number of sides in the dice + * The number of sides in the dice * @param nDice - * The number of dice in the group + * The number of dice in the group */ public DiceExpressionBuilder(int nSides, int nDice) { baking = new ComplexDice(nSides, nDice); @@ -43,7 +43,7 @@ public class DiceExpressionBuilder { * Add a term to this dice expression * * @param exp - * The expression to use on the left + * The expression to use on the left * @return A new expression adding the two dice */ public DiceExpressionBuilder add(IDiceExpression exp) { @@ -55,12 +55,11 @@ public class DiceExpressionBuilder { * Add a scalar to this dice * * @param num - * The scalar to add to the dice + * The scalar to add to the dice * @return A dice expression adding a scalar to this */ public DiceExpressionBuilder add(int num) { - baking = new OperatorDiceExpression(baking, new ScalarDie(num), - ADD); + baking = new OperatorDiceExpression(baking, new ScalarDie(num), ADD); return this; } @@ -77,7 +76,7 @@ public class DiceExpressionBuilder { * Divide a term from dice expression * * @param exp - * The expression to use on the left + * The expression to use on the left * @return A new expression dividing the two dice */ public DiceExpressionBuilder divide(IDiceExpression exp) { @@ -89,12 +88,11 @@ public class DiceExpressionBuilder { * Divide a scalar from this dice * * @param num - * The scalar to add to the dice + * The scalar to add to the dice * @return A dice expression dividing a scalar from this */ public DiceExpressionBuilder divide(int num) { - baking = new OperatorDiceExpression(baking, new ScalarDie(num), - DIVIDE); + baking = new OperatorDiceExpression(baking, new ScalarDie(num), DIVIDE); return this; } @@ -102,7 +100,7 @@ public class DiceExpressionBuilder { * Multiply a term by this dice expression * * @param exp - * The expression to use on the left + * The expression to use on the left * @return A new expression multiplying the two dice */ public DiceExpressionBuilder multiply(IDiceExpression exp) { @@ -114,12 +112,11 @@ public class DiceExpressionBuilder { * Multiply a scalar by this dice * * @param num - * The scalar to multiply to the dice + * The scalar to multiply to the dice * @return A dice expression multiplying a scalar to this */ public DiceExpressionBuilder multiply(int num) { - baking = new OperatorDiceExpression(baking, new ScalarDie(num), - MULTIPLY); + baking = new OperatorDiceExpression(baking, new ScalarDie(num), MULTIPLY); return this; } @@ -127,7 +124,7 @@ public class DiceExpressionBuilder { * Add a term to this dice expression * * @param exp - * The expression to use on the left + * The expression to use on the left * @return A new expression adding the two dice */ public DiceExpressionBuilder subtract(IDiceExpression exp) { @@ -139,12 +136,11 @@ public class DiceExpressionBuilder { * Add a scalar to this dice * * @param num - * The scalar to add to the dice + * The scalar to add to the dice * @return A dice expression adding a scalar to this */ public DiceExpressionBuilder subtract(int num) { - baking = new OperatorDiceExpression(baking, new ScalarDie(num), - SUBTRACT); + baking = new OperatorDiceExpression(baking, new ScalarDie(num), SUBTRACT); return this; } } diff --git a/dice-lang/src/bjc/dicelang/v1/DiceExpressionParser.java b/dice-lang/src/bjc/dicelang/v1/DiceExpressionParser.java index fd8f37b..38a842e 100644 --- a/dice-lang/src/bjc/dicelang/v1/DiceExpressionParser.java +++ b/dice-lang/src/bjc/dicelang/v1/DiceExpressionParser.java @@ -20,18 +20,16 @@ public class DiceExpressionParser { * Parse a dice expression from a string * * @param expression - * The string to parse an expression from + * The string to parse an expression from * @param enviroment - * The enviroment to use when parsing expressions + * The enviroment to use when parsing expressions * @return The parsed dice expression */ - public static IDiceExpression parse(String expression, - Map<String, IDiceExpression> enviroment) { + public static IDiceExpression parse(String expression, Map<String, IDiceExpression> enviroment) { /* * Create a tokenizer over the strings */ - FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer( - expression); + FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer(expression); /* * Create a shunter to rewrite the expression @@ -42,11 +40,13 @@ public class DiceExpressionParser { * Add our custom operators to the yard */ yard.addOp("d", 5); // dice operator: use for creating variable - // size dice groups - yard.addOp("c", 6); // compound operator: use for creating compound - // dice from expressions - yard.addOp(":=", 0); // binding operator: Bind a name to a variable - // expression + // size dice groups + yard.addOp("c", 6); // compound operator: use for creating + // compound + // dice from expressions + yard.addOp(":=", 0); // binding operator: Bind a name to a + // variable + // expression /* * Shunt the expression to postfix form @@ -81,80 +81,66 @@ public class DiceExpressionParser { /* * Handle scalar numbers */ - expressions.push(new ScalarDie( - Integer.parseInt(expressionPart))); + expressions.push(new ScalarDie(Integer.parseInt(expressionPart))); } catch (NumberFormatException nfex) { - // We don't care about details, just that it failed + // We don't care about details, just + // that it failed if (expressions.size() >= 2) { /* - * Apply an operation to two dice + * Apply an operation to two + * dice */ - IDiceExpression right = expressions - .pop(); + IDiceExpression right = expressions.pop(); IDiceExpression left = expressions.pop(); switch (expressionPart) { - case ":=": - expressions.push(new BindingDiceExpression( - left, right, - enviroment)); - break; - case "+": - expressions - .push(new OperatorDiceExpression( - right, - left, - DiceExpressionType.ADD)); - break; - case "-": - expressions - .push(new OperatorDiceExpression( - right, - left, - DiceExpressionType.SUBTRACT)); - break; - case "*": - expressions - .push(new OperatorDiceExpression( - right, - left, - DiceExpressionType.MULTIPLY)); - break; - case "/": - expressions - .push(new OperatorDiceExpression( - right, - left, - DiceExpressionType.DIVIDE)); - break; - case "c": - expressions.push(new CompoundDice( - left, right)); - break; - case "d": - expressions.push(new ComplexDice( - left, right)); - break; - default: - /* - * Parse it as a variable reference - * - * Make sure to restore popped variables - */ - expressions.push(left); - expressions.push(right); + case ":=": + expressions.push(new BindingDiceExpression(left, right, + enviroment)); + break; + case "+": + expressions.push(new OperatorDiceExpression(right, left, + DiceExpressionType.ADD)); + break; + case "-": + expressions.push(new OperatorDiceExpression(right, left, + DiceExpressionType.SUBTRACT)); + break; + case "*": + expressions.push(new OperatorDiceExpression(right, left, + DiceExpressionType.MULTIPLY)); + break; + case "/": + expressions.push(new OperatorDiceExpression(right, left, + DiceExpressionType.DIVIDE)); + break; + case "c": + expressions.push(new CompoundDice(left, right)); + break; + case "d": + expressions.push(new ComplexDice(left, right)); + break; + default: + /* + * Parse it as a + * variable reference + * + * Make sure to restore + * popped variables + */ + expressions.push(left); + expressions.push(right); - expressions - .push(new ReferenceDiceExpression( - expressionPart, - enviroment)); + expressions.push(new ReferenceDiceExpression(expressionPart, + enviroment)); } } else { /* - * Parse it as a variable reference + * Parse it as a variable + * reference */ - expressions.push(new ReferenceDiceExpression( - expressionPart, enviroment)); + expressions.push(new ReferenceDiceExpression(expressionPart, + enviroment)); } } } diff --git a/dice-lang/src/bjc/dicelang/v1/DiceExpressionType.java b/dice-lang/src/bjc/dicelang/v1/DiceExpressionType.java index 0c22f2a..8ffe78d 100644 --- a/dice-lang/src/bjc/dicelang/v1/DiceExpressionType.java +++ b/dice-lang/src/bjc/dicelang/v1/DiceExpressionType.java @@ -27,18 +27,17 @@ public enum DiceExpressionType { @Override public String toString() { switch (this) { - case ADD: - return "+"; - case DIVIDE: - return "/"; - case MULTIPLY: - return "*"; - case SUBTRACT: - return "-"; - default: - throw new IllegalArgumentException( - "Got passed a invalid ScalarExpressionType " - + this + ". WAT"); + case ADD: + return "+"; + case DIVIDE: + return "/"; + case MULTIPLY: + return "*"; + case SUBTRACT: + return "-"; + default: + throw new IllegalArgumentException( + "Got passed a invalid ScalarExpressionType " + this + ". WAT"); } }; } diff --git a/dice-lang/src/bjc/dicelang/v1/Die.java b/dice-lang/src/bjc/dicelang/v1/Die.java index 14c7a83..ffb6093 100644 --- a/dice-lang/src/bjc/dicelang/v1/Die.java +++ b/dice-lang/src/bjc/dicelang/v1/Die.java @@ -12,23 +12,22 @@ public class Die implements IDiceExpression { /* * Random # gen to use for dice */ - private static Random rng = new Random(); + private static Random rng = new Random(); /* * Number of sides this die has */ - private int nSides; + private int nSides; /** * Create a die with the specified number of sides * * @param nSides - * The number of sides this dice has + * The number of sides this dice has */ public Die(int nSides) { if (nSides < 1) { - throw new UnsupportedOperationException( - "Dice with less than 1 side are not supported"); + throw new UnsupportedOperationException("Dice with less than 1 side are not supported"); } this.nSides = nSides; @@ -42,8 +41,7 @@ public class Die implements IDiceExpression { @Override public int optimize() { if (nSides != 1) { - throw new UnsupportedOperationException( - "Can't optimize " + nSides + "-sided dice"); + throw new UnsupportedOperationException("Can't optimize " + nSides + "-sided dice"); } return 1; diff --git a/dice-lang/src/bjc/dicelang/v1/IDiceExpression.java b/dice-lang/src/bjc/dicelang/v1/IDiceExpression.java index a0b78b8..86c4d6a 100644 --- a/dice-lang/src/bjc/dicelang/v1/IDiceExpression.java +++ b/dice-lang/src/bjc/dicelang/v1/IDiceExpression.java @@ -22,11 +22,11 @@ public interface IDiceExpression { * <li>Dice concatenation - '1d10c1d10</li> * </ul> * - * Dice concatenation is like using 2 d10s to emulate a d100, so - * instead of adding them, it reads them side by side. + * Dice concatenation is like using 2 d10s to emulate a d100, so instead + * of adding them, it reads them side by side. * * @param expression - * The string to convert to an expression + * The string to convert to an expression * * @return The string, converted into expression form */ @@ -52,8 +52,8 @@ public interface IDiceExpression { return new ScalarDie(Integer.parseInt(literalData)); } catch (NumberFormatException nfex) { UnsupportedOperationException usex = new UnsupportedOperationException( - "Found malformed leaf token " + expression + ". Floating point numbers " + - "are not supported."); + "Found malformed leaf token " + expression + ". Floating point numbers " + + "are not supported."); usex.initCause(nfex); @@ -78,11 +78,10 @@ public interface IDiceExpression { * @return This expression, optimized to a scalar value * * @throws UnsupportedOperationException - * if this type of expression can't be optimized + * if this type of expression can't be optimized */ public default int optimize() { - throw new UnsupportedOperationException( - "Can't optimize this type of expression"); + throw new UnsupportedOperationException("Can't optimize this type of expression"); } /** diff --git a/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java b/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java index ac630a8..bf9254e 100644 --- a/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java +++ b/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java @@ -10,30 +10,29 @@ public class OperatorDiceExpression implements IDiceExpression { /* * The operator to use for combining the dice */ - private DiceExpressionType type; + private DiceExpressionType type; /* * The dice on the left side of the expression */ - private IDiceExpression left; + private IDiceExpression left; /* * The dice on the right side of the expression */ - private IDiceExpression right; + private IDiceExpression right; /** * Create a new compound expression using the specified parameters * * @param rght - * The die on the right side of the expression + * The die on the right side of the expression * @param lft - * The die on the left side of the expression + * The die on the left side of the expression * @param type - * The operator to use for combining the dices + * The operator to use for combining the dices */ - public OperatorDiceExpression(IDiceExpression rght, - IDiceExpression lft, DiceExpressionType type) { + public OperatorDiceExpression(IDiceExpression rght, IDiceExpression lft, DiceExpressionType type) { this.right = rght; this.left = lft; this.type = type; @@ -45,42 +44,37 @@ public class OperatorDiceExpression implements IDiceExpression { * Handle each operator */ switch (type) { - case ADD: - return right.roll() + left.roll(); - case SUBTRACT: - return right.roll() - left.roll(); - case MULTIPLY: - return right.roll() * left.roll(); - case DIVIDE: - /* - * Round to keep results as integers. We don't really have - * any need for floating-point dice, and continuous - * probability is a pain - */ - try { - return right.roll() / left.roll(); - } catch (ArithmeticException aex) { - UnsupportedOperationException usex = new UnsupportedOperationException( - "Attempted to divide by zero." - + " Problematic expression is " - + left); + case ADD: + return right.roll() + left.roll(); + case SUBTRACT: + return right.roll() - left.roll(); + case MULTIPLY: + return right.roll() * left.roll(); + case DIVIDE: + /* + * Round to keep results as integers. We don't really + * have any need for floating-point dice, and continuous + * probability is a pain + */ + try { + return right.roll() / left.roll(); + } catch (ArithmeticException aex) { + UnsupportedOperationException usex = new UnsupportedOperationException( + "Attempted to divide by zero." + " Problematic expression is " + left); - usex.initCause(aex); + usex.initCause(aex); - throw usex; - } - default: - throw new IllegalArgumentException( - "Got passed a invalid ScalarExpressionType (" - + type + "). WAT"); + throw usex; + } + default: + throw new IllegalArgumentException( + "Got passed a invalid ScalarExpressionType (" + type + "). WAT"); } } @Override public String toString() { - return "dice-exp[type=" + type + ", l=" - + left.toString() + ", r=" - + right.toString() + "]"; + return "dice-exp[type=" + type + ", l=" + left.toString() + ", r=" + right.toString() + "]"; } } diff --git a/dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java b/dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java index 4af521b..e20a12a 100644 --- a/dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java +++ b/dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java @@ -20,7 +20,7 @@ public class PolyhedralDice { * Produce the specified number of 10-sided dice * * @param nDice - * The number of ten-sided dice to produce + * The number of ten-sided dice to produce * @return A group of ten-sided dice of the specified size */ public static IDiceExpression d10(int nDice) { @@ -40,7 +40,7 @@ public class PolyhedralDice { * Produce the specified number of 100-sided dice * * @param nDice - * The number of hundred-sided dice to produce + * The number of hundred-sided dice to produce * @return A group of hundred-sided dice of the specified size */ public static IDiceExpression d100(int nDice) { @@ -60,7 +60,7 @@ public class PolyhedralDice { * Produce the specified number of 12-sided dice * * @param nDice - * The number of twelve-sided dice to produce + * The number of twelve-sided dice to produce * @return A group of twelve-sided dice of the specified size */ public static IDiceExpression d12(int nDice) { @@ -80,7 +80,7 @@ public class PolyhedralDice { * Produce the specified number of 20-sided dice * * @param nDice - * The number of twenty-sided dice to produce + * The number of twenty-sided dice to produce * @return A group of twenty-sided dice of the specified size */ public static IDiceExpression d20(int nDice) { @@ -100,7 +100,7 @@ public class PolyhedralDice { * Produce the specified number of 4-sided dice * * @param nDice - * The number of four-sided dice to produce + * The number of four-sided dice to produce * @return A group of four-sided dice of the specified size */ public static IDiceExpression d4(int nDice) { @@ -120,7 +120,7 @@ public class PolyhedralDice { * Produce the specified number of 6-sided dice * * @param nDice - * The number of six-sided dice to produce + * The number of six-sided dice to produce * @return A group of six-sided dice of the specified size */ public static IDiceExpression d6(int nDice) { @@ -140,7 +140,7 @@ public class PolyhedralDice { * Produce the specified number of 8-sided dice * * @param nDice - * The number of eight-sided dice to produce + * The number of eight-sided dice to produce * @return A group of eight-sided dice of the specified size */ public static IDiceExpression d8(int nDice) { diff --git a/dice-lang/src/bjc/dicelang/v1/ReferenceDiceExpression.java b/dice-lang/src/bjc/dicelang/v1/ReferenceDiceExpression.java index bb7ce02..b3b979a 100644 --- a/dice-lang/src/bjc/dicelang/v1/ReferenceDiceExpression.java +++ b/dice-lang/src/bjc/dicelang/v1/ReferenceDiceExpression.java @@ -3,8 +3,7 @@ package bjc.dicelang.v1; import java.util.Map; /** - * A dice expression that refers to a variable bound in a mutable - * enviroment + * A dice expression that refers to a variable bound in a mutable enviroment * * @author ben * @@ -13,24 +12,23 @@ public class ReferenceDiceExpression implements IDiceExpression { /* * The enviroment to do variable dereferencing against */ - private Map<String, IDiceExpression> enviroment; + private Map<String, IDiceExpression> enviroment; /* * The name of the bound variable */ - private String name; + private String name; /** - * Create a new reference dice expression referring to the given name - * in an enviroment + * Create a new reference dice expression referring to the given name in + * an enviroment * * @param nme - * The name of the bound variable + * The name of the bound variable * @param env - * The enviroment to resolve the variable against + * The enviroment to resolve the variable against */ - public ReferenceDiceExpression(String nme, - Map<String, IDiceExpression> env) { + public ReferenceDiceExpression(String nme, Map<String, IDiceExpression> env) { this.name = nme; this.enviroment = env; } @@ -47,9 +45,7 @@ public class ReferenceDiceExpression implements IDiceExpression { @Override public int roll() { if (!enviroment.containsKey(name)) { - throw new UnsupportedOperationException( - "Attempted to reference undefined variable " - + name); + throw new UnsupportedOperationException("Attempted to reference undefined variable " + name); } return enviroment.get(name).roll(); diff --git a/dice-lang/src/bjc/dicelang/v1/ScalarDie.java b/dice-lang/src/bjc/dicelang/v1/ScalarDie.java index 94cf687..c0bb3a9 100644 --- a/dice-lang/src/bjc/dicelang/v1/ScalarDie.java +++ b/dice-lang/src/bjc/dicelang/v1/ScalarDie.java @@ -16,7 +16,7 @@ public class ScalarDie implements IDiceExpression { * Create a dice with the specified number * * @param num - * The number used for the dice + * The number used for the dice */ public ScalarDie(int num) { this.number = num; diff --git a/dice-lang/src/bjc/dicelang/v1/ast/ArithmeticCollapser.java b/dice-lang/src/bjc/dicelang/v1/ast/ArithmeticCollapser.java index 5a69bf1..1a41ce6 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/ArithmeticCollapser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/ArithmeticCollapser.java @@ -18,28 +18,25 @@ import bjc.utils.data.Tree; */ final class ArithmeticCollapser implements IOperatorCollapser { // The type of operator we're collapsing - private OperatorDiceNode type; + private OperatorDiceNode type; // The operator to use to collapse operators - private BinaryOperator<Integer> valueOp; + private BinaryOperator<Integer> valueOp; - private int initialValue; + private int initialValue; - public ArithmeticCollapser(OperatorDiceNode type, - BinaryOperator<Integer> valueOp, int initVal) { + public ArithmeticCollapser(OperatorDiceNode type, BinaryOperator<Integer> valueOp, int initVal) { this.type = type; this.valueOp = valueOp; this.initialValue = initVal; } @Override - public IPair<IResult, ITree<IDiceASTNode>> apply( - IList<IPair<IResult, ITree<IDiceASTNode>>> nodes) { - IPair<IResult, ITree<IDiceASTNode>> initialState = new Pair<>( - new IntegerResult(initialValue), new Tree<>(type)); + public IPair<IResult, ITree<IDiceASTNode>> apply(IList<IPair<IResult, ITree<IDiceASTNode>>> nodes) { + IPair<IResult, ITree<IDiceASTNode>> initialState = new Pair<>(new IntegerResult(initialValue), + new Tree<>(type)); - BinaryOperator<IPair<IResult, ITree<IDiceASTNode>>> reducer = ( - currentState, accumulatedState) -> { + BinaryOperator<IPair<IResult, ITree<IDiceASTNode>>> reducer = (currentState, accumulatedState) -> { // Force evaluation of accumulated state to prevent // certain bugs from occuring // accumulatedState.merge((l, r) -> null); @@ -47,90 +44,66 @@ final class ArithmeticCollapser implements IOperatorCollapser { return reduceStates(accumulatedState, currentState); }; - IPair<IResult, ITree<IDiceASTNode>> reducedState = nodes - .reduceAux(initialState, reducer, (state) -> state); + IPair<IResult, ITree<IDiceASTNode>> reducedState = nodes.reduceAux(initialState, reducer, + (state) -> state); return reducedState; } - private IList<IResult> combineArrayResults(IResult accumulatedValue, - IResult currentValue) { - IList<IResult> currentList = ((ArrayResult) currentValue) - .getValue(); - IList<IResult> accumulatedList = ((ArrayResult) accumulatedValue) - .getValue(); + private IList<IResult> combineArrayResults(IResult accumulatedValue, IResult currentValue) { + IList<IResult> currentList = ((ArrayResult) currentValue).getValue(); + IList<IResult> accumulatedList = ((ArrayResult) accumulatedValue).getValue(); if (currentList.getSize() != accumulatedList.getSize()) { - throw new UnsupportedOperationException( - "Can only apply operations to equal-length arrays"); + throw new UnsupportedOperationException("Can only apply operations to equal-length arrays"); } - IList<IResult> resultList = currentList.combineWith( - accumulatedList, (currentNode, accumulatedNode) -> { - boolean currentNotInt = currentNode - .getType() != ResultType.INTEGER; - boolean accumulatedNotInt = accumulatedNode - .getType() != ResultType.INTEGER; - - if (currentNotInt || accumulatedNotInt) { - throw new UnsupportedOperationException( - "Nesting of array operations isn't allowed"); - } - - int accumulatedInt = ((IntegerResult) accumulatedNode) - .getValue(); - int currentInt = ((IntegerResult) currentNode) - .getValue(); - - IResult combinedValue = new IntegerResult( - valueOp.apply(accumulatedInt, currentInt)); - return combinedValue; - }); + IList<IResult> resultList = currentList.combineWith(accumulatedList, (currentNode, accumulatedNode) -> { + boolean currentNotInt = currentNode.getType() != ResultType.INTEGER; + boolean accumulatedNotInt = accumulatedNode.getType() != ResultType.INTEGER; + + if (currentNotInt || accumulatedNotInt) { + throw new UnsupportedOperationException("Nesting of array operations isn't allowed"); + } + + int accumulatedInt = ((IntegerResult) accumulatedNode).getValue(); + int currentInt = ((IntegerResult) currentNode).getValue(); + + IResult combinedValue = new IntegerResult(valueOp.apply(accumulatedInt, currentInt)); + return combinedValue; + }); return resultList; } - private IPair<IResult, ITree<IDiceASTNode>> doArithmeticCollapse( - IResult accumulatedValue, ITree<IDiceASTNode> accumulatedTree, - IResult currentValue) { - if (accumulatedValue.getType() == ResultType.DUMMY - || currentValue.getType() == ResultType.DUMMY) { - DummyResult result = new DummyResult( - "Found dummy result with either accumulated dummy (" - + ((DummyResult) accumulatedValue).getData() - + ") or current dummy (" - + ((DummyResult) currentValue).getData() - + ")."); + private IPair<IResult, ITree<IDiceASTNode>> doArithmeticCollapse(IResult accumulatedValue, + ITree<IDiceASTNode> accumulatedTree, IResult currentValue) { + if (accumulatedValue.getType() == ResultType.DUMMY || currentValue.getType() == ResultType.DUMMY) { + DummyResult result = new DummyResult("Found dummy result with either accumulated dummy (" + + ((DummyResult) accumulatedValue).getData() + ") or current dummy (" + + ((DummyResult) currentValue).getData() + ")."); return new Pair<>(result, accumulatedTree); } - boolean currentIsInt = currentValue - .getType() == ResultType.INTEGER; - boolean accumulatedIsInt = accumulatedValue - .getType() == ResultType.INTEGER; + boolean currentIsInt = currentValue.getType() == ResultType.INTEGER; + boolean accumulatedIsInt = accumulatedValue.getType() == ResultType.INTEGER; if (!currentIsInt) { if (!accumulatedIsInt) { - IList<IResult> resultList = combineArrayResults( - accumulatedValue, currentValue); + IList<IResult> resultList = combineArrayResults(accumulatedValue, currentValue); - return new Pair<>(new ArrayResult(resultList), - accumulatedTree); + return new Pair<>(new ArrayResult(resultList), accumulatedTree); } - IList<IResult> resultList = halfCombineLists( - ((ArrayResult) currentValue).getValue(), + IList<IResult> resultList = halfCombineLists(((ArrayResult) currentValue).getValue(), accumulatedValue, true); - return new Pair<>(new ArrayResult(resultList), - accumulatedTree); + return new Pair<>(new ArrayResult(resultList), accumulatedTree); } else if (!accumulatedIsInt) { - IList<IResult> resultList = halfCombineLists( - ((ArrayResult) accumulatedValue).getValue(), + IList<IResult> resultList = halfCombineLists(((ArrayResult) accumulatedValue).getValue(), currentValue, false); - return new Pair<>(new ArrayResult(resultList), - accumulatedTree); + return new Pair<>(new ArrayResult(resultList), accumulatedTree); } int accumulatedInt = ((IntegerResult) accumulatedValue).getValue(); @@ -138,23 +111,19 @@ final class ArithmeticCollapser implements IOperatorCollapser { int combinedValue = valueOp.apply(accumulatedInt, currentInt); - return new Pair<>(new IntegerResult(combinedValue), - accumulatedTree); + return new Pair<>(new IntegerResult(combinedValue), accumulatedTree); } - private IList<IResult> halfCombineLists(IList<IResult> list, - IResult scalar, boolean scalarLeft) { + private IList<IResult> halfCombineLists(IList<IResult> list, IResult scalar, boolean scalarLeft) { if (scalar.getType() != ResultType.INTEGER) { - throw new UnsupportedOperationException( - "Nested array operations not supported"); + throw new UnsupportedOperationException("Nested array operations not supported"); } int scalarInt = ((IntegerResult) scalar).getValue(); return list.map((element) -> { if (element.getType() != ResultType.INTEGER) { - throw new UnsupportedOperationException( - "Nested array operations not supported"); + throw new UnsupportedOperationException("Nested array operations not supported"); } int elementInt = ((IntegerResult) element).getValue(); @@ -162,30 +131,23 @@ final class ArithmeticCollapser implements IOperatorCollapser { IResult combinedValue; if (scalarLeft) { - combinedValue = new IntegerResult( - valueOp.apply(scalarInt, elementInt)); + combinedValue = new IntegerResult(valueOp.apply(scalarInt, elementInt)); } else { - combinedValue = new IntegerResult( - valueOp.apply(elementInt, scalarInt)); + combinedValue = new IntegerResult(valueOp.apply(elementInt, scalarInt)); } return combinedValue; }); } - private IPair<IResult, ITree<IDiceASTNode>> reduceStates( - IPair<IResult, ITree<IDiceASTNode>> accumulatedState, + private IPair<IResult, ITree<IDiceASTNode>> reduceStates(IPair<IResult, ITree<IDiceASTNode>> accumulatedState, IPair<IResult, ITree<IDiceASTNode>> currentState) { - return accumulatedState - .bind((accumulatedValue, accumulatedTree) -> { - return currentState - .bind((currentValue, currentTree) -> { - accumulatedTree.addChild(currentTree); - - return doArithmeticCollapse( - accumulatedValue, accumulatedTree, - currentValue); - }); - }); + return accumulatedState.bind((accumulatedValue, accumulatedTree) -> { + return currentState.bind((currentValue, currentTree) -> { + accumulatedTree.addChild(currentTree); + + return doArithmeticCollapse(accumulatedValue, accumulatedTree, currentValue); + }); + }); } }
\ No newline at end of file diff --git a/dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java b/dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java index 6cb9216..c8a35a6 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java @@ -16,7 +16,7 @@ public class ArrayResult implements IResult { * Create a new array-valued result * * @param results - * The results in the array + * The results in the array */ public ArrayResult(IList<IResult> results) { this.arrayContents = results; diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTEvaluator.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTEvaluator.java index c8c0032..af31ad7 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTEvaluator.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTEvaluator.java @@ -30,27 +30,24 @@ import bjc.utils.data.Tree; * */ public class DiceASTEvaluator { - private static IResult bindLiteralValue(IDiceASTNode leafNode, - IMap<String, ITree<IDiceASTNode>> enviroment) { + private static IResult bindLiteralValue(IDiceASTNode leafNode, IMap<String, ITree<IDiceASTNode>> enviroment) { String variableName = ((VariableDiceNode) leafNode).getVariable(); if (enviroment.containsKey(variableName)) { - IResult result = evaluateAST(enviroment.get(variableName), - enviroment); + IResult result = evaluateAST(enviroment.get(variableName), enviroment); return result; } // Return a DummyResult to handle lets properly - return new DummyResult( - "Attempted to deref unbound variable " + variableName); + return new DummyResult("Attempted to deref unbound variable " + variableName); } /** * Build the map of operations to use when collapsing the AST * * @param enviroment - * The enviroment to evaluate bindings and such against + * The enviroment to evaluate bindings and such against * @return The operations to use when collapsing the AST */ private static IMap<IDiceASTNode, IOperatorCollapser> buildOperations( @@ -58,34 +55,27 @@ public class DiceASTEvaluator { IMap<IDiceASTNode, IOperatorCollapser> operatorCollapsers = new FunctionalMap<>(); operatorCollapsers.put(OperatorDiceNode.ADD, - new ArithmeticCollapser(OperatorDiceNode.ADD, - (left, right) -> left + right, 0)); + new ArithmeticCollapser(OperatorDiceNode.ADD, (left, right) -> left + right, 0)); operatorCollapsers.put(OperatorDiceNode.SUBTRACT, - new ArithmeticCollapser(OperatorDiceNode.SUBTRACT, - (left, right) -> left - right, 0)); + new ArithmeticCollapser(OperatorDiceNode.SUBTRACT, (left, right) -> left - right, 0)); operatorCollapsers.put(OperatorDiceNode.MULTIPLY, - new ArithmeticCollapser(OperatorDiceNode.MULTIPLY, - (left, right) -> left * right, 1)); + new ArithmeticCollapser(OperatorDiceNode.MULTIPLY, (left, right) -> left * right, 1)); operatorCollapsers.put(OperatorDiceNode.DIVIDE, - new ArithmeticCollapser(OperatorDiceNode.DIVIDE, - (left, right) -> left / right, 1)); + new ArithmeticCollapser(OperatorDiceNode.DIVIDE, (left, right) -> left / right, 1)); operatorCollapsers.put(OperatorDiceNode.ASSIGN, (nodes) -> { return parseBinding(enviroment, nodes); }); operatorCollapsers.put(OperatorDiceNode.COMPOUND, - new ArithmeticCollapser(OperatorDiceNode.COMPOUND, - (left, right) -> { - return Integer.parseInt(Integer.toString(left) - + Integer.toString(right)); - }, 0)); + new ArithmeticCollapser(OperatorDiceNode.COMPOUND, (left, right) -> { + return Integer.parseInt(Integer.toString(left) + Integer.toString(right)); + }, 0)); - operatorCollapsers.put(OperatorDiceNode.GROUP, - DiceASTEvaluator::parseGroup); + operatorCollapsers.put(OperatorDiceNode.GROUP, DiceASTEvaluator::parseGroup); operatorCollapsers.put(OperatorDiceNode.LET, (nodes) -> { // @TODO Fix lets prematurely evaluating things @@ -106,8 +96,7 @@ public class DiceASTEvaluator { }; Supplier<ITree<IDiceASTNode>> treeSupplier = () -> { - ITree<IDiceASTNode> returnedTree = new Tree<>( - OperatorDiceNode.ARRAY); + ITree<IDiceASTNode> returnedTree = new Tree<>(OperatorDiceNode.ARRAY); nodes.forEach((element) -> { returnedTree.addChild(element.getRight()); @@ -122,11 +111,9 @@ public class DiceASTEvaluator { return operatorCollapsers; } - private static void doArrayAssign( - IMap<String, ITree<IDiceASTNode>> enviroment, - IPair<IResult, ITree<IDiceASTNode>> nameNode, - ITree<IDiceASTNode> nameTree, ITree<IDiceASTNode> valueTree, - IHolder<Integer> childCount, ITree<IDiceASTNode> child) { + private static void doArrayAssign(IMap<String, ITree<IDiceASTNode>> enviroment, + IPair<IResult, ITree<IDiceASTNode>> nameNode, ITree<IDiceASTNode> nameTree, + ITree<IDiceASTNode> valueTree, IHolder<Integer> childCount, ITree<IDiceASTNode> child) { if (nameTree.getHead().getType() != DiceASTType.VARIABLE) { throw new UnsupportedOperationException( "Assigning to complex variables isn't supported. Problem node is " @@ -146,75 +133,65 @@ public class DiceASTEvaluator { * Evaluate the provided AST to a numeric value * * @param expression - * The expression to evaluate + * The expression to evaluate * @param enviroment - * The enviroment to look up variables in + * The enviroment to look up variables in * @return The integer value of the expression */ public static IResult evaluateAST(ITree<IDiceASTNode> expression, IMap<String, ITree<IDiceASTNode>> enviroment) { - IMap<IDiceASTNode, IOperatorCollapser> collapsers = buildOperations( - enviroment); + IMap<IDiceASTNode, IOperatorCollapser> collapsers = buildOperations(enviroment); - return expression.collapse( - (node) -> evaluateLeaf(node, enviroment), collapsers::get, + return expression.collapse((node) -> evaluateLeaf(node, enviroment), collapsers::get, (pair) -> pair.getLeft()); } - private static IPair<IResult, ITree<IDiceASTNode>> evaluateLeaf( - IDiceASTNode leafNode, + private static IPair<IResult, ITree<IDiceASTNode>> evaluateLeaf(IDiceASTNode leafNode, IMap<String, ITree<IDiceASTNode>> enviroment) { ITree<IDiceASTNode> returnedAST = new Tree<>(leafNode); switch (leafNode.getType()) { - case LITERAL: - return new Pair<>(evaluateLiteral(leafNode), returnedAST); + case LITERAL: + return new Pair<>(evaluateLiteral(leafNode), returnedAST); - case VARIABLE: - return new LazyPair<>(() -> { - return bindLiteralValue(leafNode, enviroment); - }, () -> returnedAST); + case VARIABLE: + return new LazyPair<>(() -> { + return bindLiteralValue(leafNode, enviroment); + }, () -> returnedAST); - case OPERATOR: - default: - throw new UnsupportedOperationException( - "Node '" + leafNode + "' cannot be a leaf."); + case OPERATOR: + default: + throw new UnsupportedOperationException("Node '" + leafNode + "' cannot be a leaf."); } } private static IResult evaluateLiteral(IDiceASTNode leafNode) { - DiceLiteralType literalType = ((ILiteralDiceNode) leafNode) - .getLiteralType(); + DiceLiteralType literalType = ((ILiteralDiceNode) leafNode).getLiteralType(); switch (literalType) { - case DICE: - int diceRoll = ((DiceLiteralNode) leafNode).getValue() - .roll(); - - return new IntegerResult(diceRoll); - case INTEGER: - int val = ((IntegerLiteralNode) leafNode).getValue(); - - return new IntegerResult(val); - default: - throw new UnsupportedOperationException("Literal value '" - + leafNode + "' is of a type (" + literalType - + ") not currently supported."); + case DICE: + int diceRoll = ((DiceLiteralNode) leafNode).getValue().roll(); + + return new IntegerResult(diceRoll); + case INTEGER: + int val = ((IntegerLiteralNode) leafNode).getValue(); + + return new IntegerResult(val); + default: + throw new UnsupportedOperationException("Literal value '" + leafNode + "' is of a type (" + + literalType + ") not currently supported."); } } - private static IPair<IResult, ITree<IDiceASTNode>> parseBinding( - IMap<String, ITree<IDiceASTNode>> enviroment, + private static IPair<IResult, ITree<IDiceASTNode>> parseBinding(IMap<String, ITree<IDiceASTNode>> enviroment, IList<IPair<IResult, ITree<IDiceASTNode>>> nodes) { if (nodes.getSize() != 2) { throw new UnsupportedOperationException( - "Can only bind nodes with two children. Problem children are " - + nodes); + "Can only bind nodes with two children. Problem children are " + nodes); } IPair<IResult, ITree<IDiceASTNode>> nameNode = nodes.getByIndex(0); - IPair<IResult, ITree<IDiceASTNode>> valueNode = nodes - .getByIndex(1); + IPair<IResult, ITree<IDiceASTNode>> valueNode = nodes.getByIndex(1); return nameNode.bindRight((nameTree) -> { return valueNode.bind((valueValue, valueTree) -> { @@ -228,8 +205,7 @@ public class DiceASTEvaluator { return new Pair<>(valueValue, nameTree); } else if (nameTree.getHead() == OperatorDiceNode.ARRAY) { if (valueTree.getHead() == OperatorDiceNode.ARRAY) { - if (nameTree.getChildrenCount() != valueTree - .getChildrenCount()) { + if (nameTree.getChildrenCount() != valueTree.getChildrenCount()) { throw new UnsupportedOperationException( "Array assignment must be between two equal length arrays"); } @@ -237,8 +213,8 @@ public class DiceASTEvaluator { IHolder<Integer> childCount = new Identity<>(0); nameTree.doForChildren((child) -> { - doArrayAssign(enviroment, nameNode, nameTree, - valueTree, childCount, child); + doArrayAssign(enviroment, nameNode, nameTree, valueTree, + childCount, child); childCount.transform(val -> val + 1); }); @@ -248,8 +224,7 @@ public class DiceASTEvaluator { nameTree.doForChildren((child) -> { String varName = child.transformHead((nameNod) -> { - return ((VariableDiceNode) nameNod) - .getVariable(); + return ((VariableDiceNode) nameNod).getVariable(); }); enviroment.put(varName, valueTree); @@ -268,42 +243,33 @@ public class DiceASTEvaluator { private static IPair<IResult, ITree<IDiceASTNode>> parseGroup( IList<IPair<IResult, ITree<IDiceASTNode>>> nodes) { if (nodes.getSize() != 2) { - throw new UnsupportedOperationException( - "Can only form a group from two dice"); + throw new UnsupportedOperationException("Can only form a group from two dice"); } - IPair<IResult, ITree<IDiceASTNode>> numberDiceNode = nodes - .getByIndex(0); - IPair<IResult, ITree<IDiceASTNode>> diceTypeNode = nodes - .getByIndex(1); + IPair<IResult, ITree<IDiceASTNode>> numberDiceNode = nodes.getByIndex(0); + IPair<IResult, ITree<IDiceASTNode>> diceTypeNode = nodes.getByIndex(1); return numberDiceNode.bind((numberDiceValue, numberDiceTree) -> { return diceTypeNode.bind((diceTypeValue, diceTypeTree) -> { - ComplexDice cDice = new ComplexDice( - ((IntegerResult) numberDiceValue).getValue(), + ComplexDice cDice = new ComplexDice(((IntegerResult) numberDiceValue).getValue(), ((IntegerResult) diceTypeValue).getValue()); return new Pair<>(new IntegerResult(cDice.roll()), - new Tree<>(OperatorDiceNode.GROUP, numberDiceTree, - diceTypeTree)); + new Tree<>(OperatorDiceNode.GROUP, numberDiceTree, diceTypeTree)); }); }); } - private static IPair<IResult, ITree<IDiceASTNode>> parseLet( - IMap<String, ITree<IDiceASTNode>> enviroment, + private static IPair<IResult, ITree<IDiceASTNode>> parseLet(IMap<String, ITree<IDiceASTNode>> enviroment, IList<IPair<IResult, ITree<IDiceASTNode>>> nodes) { if (nodes.getSize() != 2) { - throw new UnsupportedOperationException( - "Can only use let with two expressions."); + throw new UnsupportedOperationException("Can only use let with two expressions."); } ITree<IDiceASTNode> bindTree = nodes.getByIndex(0).getRight(); - ITree<IDiceASTNode> expressionTree = nodes.getByIndex(1) - .getRight(); + ITree<IDiceASTNode> expressionTree = nodes.getByIndex(1).getRight(); - IMap<String, ITree<IDiceASTNode>> letEnviroment = enviroment - .extend(); + IMap<String, ITree<IDiceASTNode>> letEnviroment = enviroment.extend(); System.out.println("Evaluating tree for bound values"); @@ -311,10 +277,8 @@ public class DiceASTEvaluator { IResult exprResult = evaluateAST(expressionTree, letEnviroment); - IList<ITree<IDiceASTNode>> childrn = nodes - .map((pair) -> pair.getRight()); + IList<ITree<IDiceASTNode>> childrn = nodes.map((pair) -> pair.getRight()); - return new Pair<>(exprResult, - new Tree<>(OperatorDiceNode.LET, childrn)); + return new Pair<>(exprResult, new Tree<>(OperatorDiceNode.LET, childrn)); } } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTInliner.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTInliner.java index 51aba03..38e1361 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTInliner.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTInliner.java @@ -20,9 +20,9 @@ public class DiceASTInliner { * Inline all the variables in the AST * * @param ast - * The AST to inline variables into + * The AST to inline variables into * @param enviroment - * The enviroment to inline from + * The enviroment to inline from * @return The inlined AST */ public static ITree<IDiceASTNode> inlineAll(ITree<IDiceASTNode> ast, @@ -32,8 +32,7 @@ public class DiceASTInliner { return selectiveInline(ast, enviroment, (String[]) null); } - private static ITree<IDiceASTNode> inlineNode(IDiceASTNode node, - IMap<String, ITree<IDiceASTNode>> enviroment, + private static ITree<IDiceASTNode> inlineNode(IDiceASTNode node, IMap<String, ITree<IDiceASTNode>> enviroment, boolean specificInline, IList<String> variableNames) { // Only variables get inlined if (node.getType() != DiceASTType.VARIABLE) { @@ -50,8 +49,7 @@ public class DiceASTInliner { // You can't inline non-existent variables if (!enviroment.containsKey(variableName)) { throw new UnsupportedOperationException( - "Attempted to inline non-existant variable " - + variableName); + "Attempted to inline non-existant variable " + variableName); } // Return the tree for the variable @@ -61,12 +59,11 @@ public class DiceASTInliner { // We're not inlining this particular variable return new Tree<>(node); } - + // You can't inline non-existent variables if (!enviroment.containsKey(variableName)) { throw new UnsupportedOperationException( - "Attempted to inline non-existant variable " - + variableName); + "Attempted to inline non-existant variable " + variableName); } // Return the tree for the variable @@ -77,37 +74,32 @@ public class DiceASTInliner { * Inline the specified variables in the AST * * @param ast - * The AST to inline variables into + * The AST to inline variables into * @param enviroment - * The enviroment to inline from + * The enviroment to inline from * @param variables - * The variables to inline + * The variables to inline * @return The inlined AST */ - public static ITree<IDiceASTNode> selectiveInline( - ITree<IDiceASTNode> ast, - IMap<String, ITree<IDiceASTNode>> enviroment, - IList<String> variables) { + public static ITree<IDiceASTNode> selectiveInline(ITree<IDiceASTNode> ast, + IMap<String, ITree<IDiceASTNode>> enviroment, IList<String> variables) { // Inline the specified variables - return selectiveInline(ast, enviroment, - variables.toArray(new String[0])); + return selectiveInline(ast, enviroment, variables.toArray(new String[0])); } /** * Inline the specified variables in the AST * * @param ast - * The AST to inline variables into + * The AST to inline variables into * @param enviroment - * The enviroment to inline from + * The enviroment to inline from * @param variables - * The variables to inline + * The variables to inline * @return The inlined AST */ - public static ITree<IDiceASTNode> selectiveInline( - ITree<IDiceASTNode> ast, - IMap<String, ITree<IDiceASTNode>> enviroment, - String... variables) { + public static ITree<IDiceASTNode> selectiveInline(ITree<IDiceASTNode> ast, + IMap<String, ITree<IDiceASTNode>> enviroment, String... variables) { // If we're selectively inlining, do so if (variables != null && variables.length > 0) { IList<String> variableNames = new FunctionalList<>(variables); diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java index 178b175..a93de33 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java @@ -27,7 +27,7 @@ public class DiceASTOptimizer { * Add a pass to the list of optimization passes * * @param pass - * The pass to add + * The pass to add */ public void addPass(IOptimizationPass pass) { passes.add(pass); @@ -37,23 +37,19 @@ public class DiceASTOptimizer { * Optimize the passed in tree * * @param ast - * The tree to optimize + * The tree to optimize * @param enviroment - * The enviroment for variable references + * The enviroment for variable references * @return The optimized tree */ - public ITree<IDiceASTNode> optimizeTree(ITree<IDiceASTNode> ast, - IMap<String, ITree<IDiceASTNode>> enviroment) { - ITree<IDiceASTNode> optimizedTree = passes.reduceAux(ast, - (currentPass, currentTree) -> { - return currentTree.collapse(currentPass::optimizeLeaf, - (operator) -> { - return (nodes) -> { - return currentPass.optimizeOperator( - operator, nodes); - }; - }, (tree) -> tree); - }, (tree) -> tree); + public ITree<IDiceASTNode> optimizeTree(ITree<IDiceASTNode> ast, IMap<String, ITree<IDiceASTNode>> enviroment) { + ITree<IDiceASTNode> optimizedTree = passes.reduceAux(ast, (currentPass, currentTree) -> { + return currentTree.collapse(currentPass::optimizeLeaf, (operator) -> { + return (nodes) -> { + return currentPass.optimizeOperator(operator, nodes); + }; + }, (tree) -> tree); + }, (tree) -> tree); return optimizedTree; } } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTParser.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTParser.java index d536cc3..87f3640 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTParser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTParser.java @@ -29,135 +29,124 @@ import bjc.utils.parserutils.TreeConstructor; * */ public class DiceASTParser { - private static IDiceASTNode convertLeafNode(String leafNode) { - DiceLiteralType literalType = ILiteralDiceNode - .getLiteralType(leafNode); - - if (literalType != null) { - switch (literalType) { - case DICE: - return new DiceLiteralNode( - IDiceExpression.toExpression(leafNode)); - case INTEGER: - return new IntegerLiteralNode( - Integer.parseInt(leafNode)); - default: - throw new InputMismatchException( - "Cannot convert string '" + leafNode - + "' into a literal."); - } - } - - if (leafNode.matches("[+-]?\\d*\\.\\d+")) { - throw new InputMismatchException( - "Floating point literals are not supported"); - } - - return new VariableDiceNode(leafNode); + private static IDiceASTNode convertLeafNode(String leafNode) { + DiceLiteralType literalType = ILiteralDiceNode.getLiteralType(leafNode); + + if (literalType != null) { + switch (literalType) { + case DICE: + return new DiceLiteralNode(IDiceExpression.toExpression(leafNode)); + case INTEGER: + return new IntegerLiteralNode(Integer.parseInt(leafNode)); + default: + throw new InputMismatchException( + "Cannot convert string '" + leafNode + "' into a literal."); + } } - private static IDiceASTNode convertOperatorNode(String operatorNode) { - try { - return OperatorDiceNode.fromString(operatorNode); - } catch (IllegalArgumentException iaex) { - InputMismatchException imex = new InputMismatchException( - "Attempted to parse invalid operator " + operatorNode); + if (leafNode.matches("[+-]?\\d*\\.\\d+")) { + throw new InputMismatchException("Floating point literals are not supported"); + } + + return new VariableDiceNode(leafNode); + } - imex.initCause(iaex); + private static IDiceASTNode convertOperatorNode(String operatorNode) { + try { + return OperatorDiceNode.fromString(operatorNode); + } catch (IllegalArgumentException iaex) { + InputMismatchException imex = new InputMismatchException( + "Attempted to parse invalid operator " + operatorNode); - throw imex; - } + imex.initCause(iaex); + + throw imex; + } + } + + /** + * Create an AST from a list of tokens + * + * @param tokens + * The list of tokens to convert + * @return An AST built from the tokens + */ + public static ITree<IDiceASTNode> createFromString(IList<String> tokens) { + // Mark arrays as special operators + Predicate<String> specialPicker = (operator) -> { + if (StringUtils.containsOnly(operator, "\\[") || StringUtils.containsOnly(operator, "\\]")) { + return true; + } + + return false; + }; + + // Here is the map for holding special operators + IMap<String, Function<Deque<ITree<String>>, ITree<String>>> operators = new FunctionalMap<>(); + + // Handle open [ + operators.put("[", (queuedTrees) -> { + // Just put in a [ + Tree<String> openArray = new Tree<>("["); + + return openArray; + }); + + operators.put("]", (queuedTrees) -> { + // Parse closing an array + return parseCloseArray(queuedTrees); + }); + + ITree<String> rawTokens = TreeConstructor.constructTree(tokens, (token) -> { + return isOperatorNode(token); + }, specialPicker, operators::get); + + ITree<IDiceASTNode> tokenizedTree = rawTokens.rebuildTree(DiceASTParser::convertLeafNode, + DiceASTParser::convertOperatorNode); + + return tokenizedTree; + } + + private static boolean isOperatorNode(String token) { + if (StringUtils.containsOnly(token, "\\[")) { + return true; + } else if (StringUtils.containsOnly(token, "\\]")) { + return true; } - /** - * Create an AST from a list of tokens - * - * @param tokens - * The list of tokens to convert - * @return An AST built from the tokens - */ - public static ITree<IDiceASTNode> createFromString( - IList<String> tokens) { - // Mark arrays as special operators - Predicate<String> specialPicker = (operator) -> { - if (StringUtils.containsOnly(operator, "\\[") || - StringUtils.containsOnly(operator, "\\]")) { - return true; - } - - return false; - }; - - // Here is the map for holding special operators - IMap<String, Function<Deque<ITree<String>>, ITree<String>>> operators = new FunctionalMap<>(); - - // Handle open [ - operators.put("[", (queuedTrees) -> { - // Just put in a [ - Tree<String> openArray = new Tree<>("["); - - return openArray; - }); - - operators.put("]", (queuedTrees) -> { - // Parse closing an array - return parseCloseArray(queuedTrees); - }); - - ITree<String> rawTokens = TreeConstructor.constructTree(tokens, - (token) -> { - return isOperatorNode(token); - }, specialPicker, operators::get); - - ITree<IDiceASTNode> tokenizedTree = rawTokens.rebuildTree( - DiceASTParser::convertLeafNode, - DiceASTParser::convertOperatorNode); - - return tokenizedTree; - } - - private static boolean isOperatorNode(String token) { - if (StringUtils.containsOnly(token, "\\[")) { - return true; - } else if (StringUtils.containsOnly(token, "\\]")) { - return true; - } - - if (token.equals("[]")) { - // This is a synthetic operator, constructed by [ and ] - return true; - } - - try { - OperatorDiceNode.fromString(token); - return true; - } catch (IllegalArgumentException iaex) { - // We don't care about details - return false; - } + if (token.equals("[]")) { + // This is a synthetic operator, constructed by [ and ] + return true; } - private static ITree<String> parseCloseArray( - Deque<ITree<String>> queuedTrees) { - IList<ITree<String>> children = new FunctionalList<>(); + try { + OperatorDiceNode.fromString(token); + return true; + } catch (IllegalArgumentException iaex) { + // We don't care about details + return false; + } + } + + private static ITree<String> parseCloseArray(Deque<ITree<String>> queuedTrees) { + IList<ITree<String>> children = new FunctionalList<>(); - while (shouldContinuePopping(queuedTrees)) { - children.add(queuedTrees.pop()); - } + while (shouldContinuePopping(queuedTrees)) { + children.add(queuedTrees.pop()); + } - queuedTrees.pop(); + queuedTrees.pop(); - children.reverse(); + children.reverse(); - ITree<String> arrayTree = new Tree<>("[]", children); + ITree<String> arrayTree = new Tree<>("[]", children); - return arrayTree; - } + return arrayTree; + } - private static boolean shouldContinuePopping( - Deque<ITree<String>> queuedTrees) { - String peekToken = queuedTrees.peek().getHead(); + private static boolean shouldContinuePopping(Deque<ITree<String>> queuedTrees) { + String peekToken = queuedTrees.peek().getHead(); - return !peekToken.equals("["); - } + return !peekToken.equals("["); + } } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java index 5492cf7..5be2090 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java @@ -13,25 +13,24 @@ import bjc.utils.data.IHolder; * @author ben * */ -public final class DiceASTReferenceChecker - implements Consumer<IDiceASTNode> { +public final class DiceASTReferenceChecker implements Consumer<IDiceASTNode> { /** * This is true if the specified node references the set variable */ - private IHolder<Boolean> referencesVariable; + private IHolder<Boolean> referencesVariable; - private String varName; + private String varName; /** * Create a new reference checker * * @param referencesVar - * The holder of whether the variable is referenced or not + * The holder of whether the variable is referenced or + * not * @param varName - * The variable to check for references in + * The variable to check for references in */ - public DiceASTReferenceChecker(IHolder<Boolean> referencesVar, - String varName) { + public DiceASTReferenceChecker(IHolder<Boolean> referencesVar, String varName) { this.referencesVariable = referencesVar; this.varName = varName; } @@ -45,7 +44,7 @@ public final class DiceASTReferenceChecker * Check if a given AST node directly references the specified variable * * @param astNode - * The node to check + * The node to check * @return Whether or not the node directly the variable */ private boolean isDirectReference(IDiceASTNode astNode) { diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceSanitizer.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceSanitizer.java index 79c0ce7..5bb07fd 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceSanitizer.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceSanitizer.java @@ -12,9 +12,8 @@ import bjc.utils.data.TopDownTransformResult; import bjc.utils.data.Tree; /** - * Sanitize the references in an AST so that a variable that refers to - * itself in its definition has the occurance of it replaced with its - * previous definition + * Sanitize the references in an AST so that a variable that refers to itself in + * its definition has the occurance of it replaced with its previous definition * * @author ben * @@ -23,8 +22,7 @@ public class DiceASTReferenceSanitizer { private static ITree<IDiceASTNode> doSanitize(ITree<IDiceASTNode> ast, IMap<String, ITree<IDiceASTNode>> enviroment) { if (ast.getChildrenCount() != 2) { - throw new UnsupportedOperationException( - "Assignment must have two arguments."); + throw new UnsupportedOperationException("Assignment must have two arguments."); } ITree<IDiceASTNode> nameTree = ast.getChild(0); @@ -36,8 +34,7 @@ public class DiceASTReferenceSanitizer { nameTree.doForChildren((child) -> { if (allSimpleVariables.getValue()) { - boolean isSimple = DiceASTUtils - .containsSimpleVariable(child); + boolean isSimple = DiceASTUtils.containsSimpleVariable(child); allSimpleVariables.replace(isSimple); } @@ -50,8 +47,7 @@ public class DiceASTReferenceSanitizer { } if (valueTree.getHead() == OperatorDiceNode.ARRAY) { - if (nameTree.getChildrenCount() != valueTree - .getChildrenCount()) { + if (nameTree.getChildrenCount() != valueTree.getChildrenCount()) { throw new UnsupportedOperationException( "Array assignment between arrays must be" + " between two arrays of equal length"); @@ -67,24 +63,21 @@ public class DiceASTReferenceSanitizer { if (valueTree.getHead() == OperatorDiceNode.ARRAY) { IHolder<Integer> childCounter = new Identity<>(0); - ITree<IDiceASTNode> returnTree = new Tree<>( - OperatorDiceNode.ARRAY); + ITree<IDiceASTNode> returnTree = new Tree<>(OperatorDiceNode.ARRAY); nameTree.doForChildren((child) -> { String variableName = child.transformHead((node) -> { return ((VariableDiceNode) node).getVariable(); }); - ITree<IDiceASTNode> currentValue = valueTree - .getChild(childCounter.getValue()); + ITree<IDiceASTNode> currentValue = valueTree.getChild(childCounter.getValue()); - ITree<IDiceASTNode> sanitizedSubtree = doSingleSanitize( - ast, enviroment, child, currentValue, - variableName); + ITree<IDiceASTNode> sanitizedSubtree = doSingleSanitize(ast, enviroment, child, + currentValue, variableName); if (sanitizedSubtree == null) { - ITree<IDiceASTNode> oldTree = new Tree<>( - ast.getHead(), child, currentValue); + ITree<IDiceASTNode> oldTree = new Tree<>(ast.getHead(), child, + currentValue); returnTree.addChild(oldTree); } else { @@ -97,18 +90,16 @@ public class DiceASTReferenceSanitizer { return returnTree; } - ITree<IDiceASTNode> returnTree = new Tree<>( - OperatorDiceNode.ARRAY); + ITree<IDiceASTNode> returnTree = new Tree<>(OperatorDiceNode.ARRAY); nameTree.doForChildren((child) -> { - String variableName = child.transformHead( - (node) -> ((VariableDiceNode) node).getVariable()); + String variableName = child + .transformHead((node) -> ((VariableDiceNode) node).getVariable()); - ITree<IDiceASTNode> sanitizedChild = doSingleSanitize(ast, - enviroment, child, valueTree, variableName); + ITree<IDiceASTNode> sanitizedChild = doSingleSanitize(ast, enviroment, child, valueTree, + variableName); if (sanitizedChild == null) { - ITree<IDiceASTNode> oldTree = new Tree<>(ast.getHead(), - child, valueTree); + ITree<IDiceASTNode> oldTree = new Tree<>(ast.getHead(), child, valueTree); returnTree.addChild(oldTree); } else { @@ -119,11 +110,10 @@ public class DiceASTReferenceSanitizer { return returnTree; } - String variableName = nameTree.transformHead( - (node) -> ((VariableDiceNode) node).getVariable()); + String variableName = nameTree.transformHead((node) -> ((VariableDiceNode) node).getVariable()); - ITree<IDiceASTNode> sanitizedTree = doSingleSanitize(ast, - enviroment, nameTree, valueTree, variableName); + ITree<IDiceASTNode> sanitizedTree = doSingleSanitize(ast, enviroment, nameTree, valueTree, + variableName); if (sanitizedTree == null) { return ast; @@ -132,22 +122,19 @@ public class DiceASTReferenceSanitizer { return sanitizedTree; } - private static ITree<IDiceASTNode> doSingleSanitize( - ITree<IDiceASTNode> ast, - IMap<String, ITree<IDiceASTNode>> enviroment, - ITree<IDiceASTNode> nameTree, ITree<IDiceASTNode> valueTree, - String variableName) { + private static ITree<IDiceASTNode> doSingleSanitize(ITree<IDiceASTNode> ast, + IMap<String, ITree<IDiceASTNode>> enviroment, ITree<IDiceASTNode> nameTree, + ITree<IDiceASTNode> valueTree, String variableName) { if (enviroment.containsKey(variableName)) { // @ is a meta-variable standing for the left side of an // assignment - ITree<IDiceASTNode> oldVal = enviroment.put("@", - enviroment.get(variableName)); + ITree<IDiceASTNode> oldVal = enviroment.put("@", enviroment.get(variableName)); - // We should always inline out references to last, because it + // We should always inline out references to last, + // because it // will always change - ITree<IDiceASTNode> inlinedValue = DiceASTInliner - .selectiveInline(valueTree, enviroment, variableName, - "last", "@"); + ITree<IDiceASTNode> inlinedValue = DiceASTInliner.selectiveInline(valueTree, enviroment, + variableName, "last", "@"); if (oldVal != null) { enviroment.put("@", oldVal); @@ -170,32 +157,30 @@ public class DiceASTReferenceSanitizer { */ public static ITree<IDiceASTNode> sanitize(ITree<IDiceASTNode> ast, IMap<String, ITree<IDiceASTNode>> enviroment) { - return ast.topDownTransform( - DiceASTReferenceSanitizer::shouldSanitize, (subTree) -> { - return doSanitize(subTree, enviroment); - }); + return ast.topDownTransform(DiceASTReferenceSanitizer::shouldSanitize, (subTree) -> { + return doSanitize(subTree, enviroment); + }); } - private static TopDownTransformResult shouldSanitize( - IDiceASTNode node) { + private static TopDownTransformResult shouldSanitize(IDiceASTNode node) { if (!node.isOperator()) { return TopDownTransformResult.SKIP; } switch (((OperatorDiceNode) node)) { - case ASSIGN: - return TopDownTransformResult.TRANSFORM; - case ARRAY: - case LET: - return TopDownTransformResult.PASSTHROUGH; - case ADD: - case COMPOUND: - case DIVIDE: - case GROUP: - case MULTIPLY: - case SUBTRACT: - default: - return TopDownTransformResult.SKIP; + case ASSIGN: + return TopDownTransformResult.TRANSFORM; + case ARRAY: + case LET: + return TopDownTransformResult.PASSTHROUGH; + case ADD: + case COMPOUND: + case DIVIDE: + case GROUP: + case MULTIPLY: + case SUBTRACT: + default: + return TopDownTransformResult.SKIP; } } } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTUtils.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTUtils.java index 92658b6..4d710fe 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTUtils.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTUtils.java @@ -20,12 +20,11 @@ public class DiceASTUtils { * Check if a dice AST contains a simple variable reference * * @param nameTree - * The tree to check for a reference in + * The tree to check for a reference in * @return Whether or not a dice AST contains a simple variable * reference */ - public static boolean containsSimpleVariable( - ITree<IDiceASTNode> nameTree) { + public static boolean containsSimpleVariable(ITree<IDiceASTNode> nameTree) { return nameTree.transformHead((nameNode) -> { if (nameNode.getType() != DiceASTType.VARIABLE) { return false; @@ -39,28 +38,26 @@ public class DiceASTUtils { * Convert an literal AST node to a dice expression, if possible. * * @param tree - * The node to convert in tree form + * The node to convert in tree form * @return The tree as a dice expression * * @throws ClassCastException - * if the head of the tree is not a literal (implements - * {@link ILiteralDiceNode}) + * if the head of the tree is not a literal (implements + * {@link ILiteralDiceNode}) * @throws UnsupportedOperationException - * if the head of the tree is not optimizable + * if the head of the tree is not optimizable */ - public static IDiceExpression literalToExpression( - ITree<IDiceASTNode> tree) { + public static IDiceExpression literalToExpression(ITree<IDiceASTNode> tree) { ILiteralDiceNode literalNode = (ILiteralDiceNode) tree.getHead(); switch (literalNode.getLiteralType()) { - case DICE: - return ((DiceLiteralNode) literalNode).getValue(); - case INTEGER: - return new ScalarDie( - ((IntegerLiteralNode) literalNode).getValue()); - default: - throw new UnsupportedOperationException( - "This type of literal isn't convertable to an expression"); + case DICE: + return ((DiceLiteralNode) literalNode).getValue(); + case INTEGER: + return new ScalarDie(((IntegerLiteralNode) literalNode).getValue()); + default: + throw new UnsupportedOperationException( + "This type of literal isn't convertable to an expression"); } } @@ -68,14 +65,14 @@ public class DiceASTUtils { * Convert an literal AST node to an integer, if possible. * * @param tree - * The literal node to convert, as a tree + * The literal node to convert, as a tree * @return The node as an integer * * @throws ClassCastException - * if the head of the tree is not a literal (implements - * {@link ILiteralDiceNode}) + * if the head of the tree is not a literal (implements + * {@link ILiteralDiceNode}) * @throws UnsupportedOperationException - * if the head of the tree is not optimizable + * if the head of the tree is not optimizable */ public static int literalToInteger(ITree<IDiceASTNode> tree) { return tree.transformHead((node) -> { diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java b/dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java index 1dd7057..6858022 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java @@ -16,7 +16,7 @@ public class DummyResult implements IResult { * Create a new dummy result with a reason * * @param data - * The reason why the result is a dummy + * The reason why the result is a dummy */ public DummyResult(String data) { dummyData = data; diff --git a/dice-lang/src/bjc/dicelang/v1/ast/IOperatorCollapser.java b/dice-lang/src/bjc/dicelang/v1/ast/IOperatorCollapser.java index df5f95b..bd120a8 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/IOperatorCollapser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/IOperatorCollapser.java @@ -13,7 +13,7 @@ import bjc.utils.funcdata.IList; * @author ben * */ -public interface IOperatorCollapser extends - Function<IList<IPair<IResult, ITree<IDiceASTNode>>>, IPair<IResult, ITree<IDiceASTNode>>> { +public interface IOperatorCollapser + extends Function<IList<IPair<IResult, ITree<IDiceASTNode>>>, IPair<IResult, ITree<IDiceASTNode>>> { // Just an alias } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/IntegerResult.java b/dice-lang/src/bjc/dicelang/v1/ast/IntegerResult.java index 2934dfa..b365282 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/IntegerResult.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/IntegerResult.java @@ -13,7 +13,7 @@ public class IntegerResult implements IResult { * Create a new integer valued result * * @param val - * The value of the result + * The value of the result */ public IntegerResult(int val) { value = val; diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralNode.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralNode.java index 4e9b560..bb979d1 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralNode.java @@ -15,7 +15,7 @@ public class DiceLiteralNode implements ILiteralDiceNode { * Create a new literal from an expression * * @param exp - * The expression to attempt to create a literal from + * The expression to attempt to create a literal from */ public DiceLiteralNode(IDiceExpression exp) { expression = exp; diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceOperatorType.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceOperatorType.java index 35e5680..a5a79a6 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceOperatorType.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceOperatorType.java @@ -3,8 +3,8 @@ package bjc.dicelang.v1.ast.nodes; /** * Represents the different type of operators. * - * Mostly, what distinguishes groups is that all the operators in a group - * have similiar precedence, and operate on similiar things + * Mostly, what distinguishes groups is that all the operators in a group have + * similiar precedence, and operate on similiar things * * @author ben * diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/ILiteralDiceNode.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/ILiteralDiceNode.java index 11d0d90..ece528b 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/ILiteralDiceNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/ILiteralDiceNode.java @@ -11,17 +11,15 @@ public interface ILiteralDiceNode extends IDiceASTNode { * Check if a token represents a literal, and if so, what type * * @param tok - * The token to check - * @return The type the literal would be if it is one, or null - * otherwise + * The token to check + * @return The type the literal would be if it is one, or null otherwise */ static DiceLiteralType getLiteralType(String tok) { String diceGroup = "\\d*d\\d+\\"; String diceGroupOrNumber = "[(?:" + diceGroup + ")(?:\\d+)]"; - if (tok.matches("\\A" + diceGroupOrNumber + "?" + "c" - + diceGroupOrNumber + "\\Z")) { + if (tok.matches("\\A" + diceGroupOrNumber + "?" + "c" + diceGroupOrNumber + "\\Z")) { return DiceLiteralType.DICE; } @@ -34,7 +32,8 @@ public interface ILiteralDiceNode extends IDiceASTNode { return DiceLiteralType.INTEGER; } catch (NumberFormatException nfex) { // We don't care about details - // This probably shouldn't return null, but I believe it does so + // This probably shouldn't return null, but I believe it + // does so // because where its called checks that. @FIXME return null; } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/IntegerLiteralNode.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/IntegerLiteralNode.java index 4a756d6..1c8aa56 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/IntegerLiteralNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/IntegerLiteralNode.java @@ -13,7 +13,7 @@ public class IntegerLiteralNode implements ILiteralDiceNode { * Create a new integer literal from the given number * * @param val - * The value this node represents + * The value this node represents */ public IntegerLiteralNode(int val) { value = val; diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/OperatorDiceNode.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/OperatorDiceNode.java index b52ba49..0af9d81 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/OperatorDiceNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/OperatorDiceNode.java @@ -52,34 +52,33 @@ public enum OperatorDiceNode implements IDiceASTNode { * Create a operator node from a string * * @param s - * The string to convert to a node + * The string to convert to a node * @return The operator corresponding to the node */ public static OperatorDiceNode fromString(String s) { switch (s) { - case ":=": - return ASSIGN; - case "+": - return ADD; - case "-": - return SUBTRACT; - case "*": - return MULTIPLY; - case "/": - return DIVIDE; - case "d": - case "group": - return GROUP; - case "c": - case "compound": - return COMPOUND; - case "=>": - return LET; - case "[]": - return ARRAY; - default: - throw new IllegalArgumentException( - s + " is not a valid operator node"); + case ":=": + return ASSIGN; + case "+": + return ADD; + case "-": + return SUBTRACT; + case "*": + return MULTIPLY; + case "/": + return DIVIDE; + case "d": + case "group": + return GROUP; + case "c": + case "compound": + return COMPOUND; + case "=>": + return LET; + case "[]": + return ARRAY; + default: + throw new IllegalArgumentException(s + " is not a valid operator node"); } } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/VariableDiceNode.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/VariableDiceNode.java index d32b6b0..22ddf17 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/VariableDiceNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/VariableDiceNode.java @@ -16,7 +16,7 @@ public class VariableDiceNode implements IDiceASTNode { * Create a new node representing the specified variable * * @param varName - * The name of the variable being referenced + * The name of the variable being referenced */ public VariableDiceNode(String varName) { this.variableName = varName; @@ -74,8 +74,7 @@ public class VariableDiceNode implements IDiceASTNode { public int hashCode() { final int prime = 31; int result = 1; - result = prime * result - + ((variableName == null) ? 0 : variableName.hashCode()); + result = prime * result + ((variableName == null) ? 0 : variableName.hashCode()); return result; } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java b/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java index 0d10a07..9fb0a5e 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java @@ -13,17 +13,15 @@ import bjc.utils.funcdata.IList; import bjc.utils.data.Tree; class ArithmeticCollapser { - private BinaryOperator<Integer> reducer; - private OperatorDiceNode type; + private BinaryOperator<Integer> reducer; + private OperatorDiceNode type; - public ArithmeticCollapser(BinaryOperator<Integer> reducr, - OperatorDiceNode typ) { + public ArithmeticCollapser(BinaryOperator<Integer> reducr, OperatorDiceNode typ) { reducer = reducr; this.type = typ; } - public ITree<IDiceASTNode> collapse( - IList<ITree<IDiceASTNode>> children) { + public ITree<IDiceASTNode> collapse(IList<ITree<IDiceASTNode>> children) { boolean allConstant = children.allMatch((subtree) -> { return subtree.transformHead((node) -> { if (node.getType() == DiceASTType.LITERAL) { @@ -40,10 +38,8 @@ class ArithmeticCollapser { int initState = DiceASTUtils.literalToInteger(children.first()); - return children.tail().reduceAux(initState, - (currentNode, state) -> { - return reducer.apply(state, - DiceASTUtils.literalToInteger(currentNode)); - }, (state) -> new Tree<>(new IntegerLiteralNode(state))); + return children.tail().reduceAux(initState, (currentNode, state) -> { + return reducer.apply(state, DiceASTUtils.literalToInteger(currentNode)); + }, (state) -> new Tree<>(new IntegerLiteralNode(state))); } } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/optimization/ConstantCollapser.java b/dice-lang/src/bjc/dicelang/v1/ast/optimization/ConstantCollapser.java index 89f17db..a0daf31 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/ConstantCollapser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/ConstantCollapser.java @@ -16,21 +16,20 @@ import bjc.utils.data.Tree; * */ public class ConstantCollapser implements IOptimizationPass { - private static final ArithmeticCollapser additionCollapser = new ArithmeticCollapser( + private static final ArithmeticCollapser additionCollapser = new ArithmeticCollapser( (left, right) -> left + right, OperatorDiceNode.ADD); - private static final ArithmeticCollapser divideCollapser = new ArithmeticCollapser( + private static final ArithmeticCollapser divideCollapser = new ArithmeticCollapser( (left, right) -> left / right, OperatorDiceNode.DIVIDE); - private static final ArithmeticCollapser multiplyCollapser = new ArithmeticCollapser( + private static final ArithmeticCollapser multiplyCollapser = new ArithmeticCollapser( (left, right) -> left * right, OperatorDiceNode.MULTIPLY); - private static final ArithmeticCollapser subtractCollapser = new ArithmeticCollapser( + private static final ArithmeticCollapser subtractCollapser = new ArithmeticCollapser( (left, right) -> left - right, OperatorDiceNode.SUBTRACT); - private static final ArithmeticCollapser compoundCollapser = new ArithmeticCollapser( - (left, right) -> Integer.parseInt( - Integer.toString(left) + Integer.toString(left)), + private static final ArithmeticCollapser compoundCollapser = new ArithmeticCollapser( + (left, right) -> Integer.parseInt(Integer.toString(left) + Integer.toString(left)), OperatorDiceNode.COMPOUND); @Override @@ -40,51 +39,46 @@ public class ConstantCollapser implements IOptimizationPass { } @Override - public ITree<IDiceASTNode> optimizeOperator(IDiceASTNode operator, - IList<ITree<IDiceASTNode>> children) { + public ITree<IDiceASTNode> optimizeOperator(IDiceASTNode operator, IList<ITree<IDiceASTNode>> children) { if (!operator.isOperator()) { return new Tree<>(operator, children); } switch ((OperatorDiceNode) operator) { - case ADD: - return additionCollapser.collapse(children); - case DIVIDE: - return divideCollapser.collapse(children); - case MULTIPLY: - return multiplyCollapser.collapse(children); - case SUBTRACT: - return subtractCollapser.collapse(children); - case COMPOUND: - return compoundCollapser.collapse(children); - case GROUP: - if (children.getSize() != 2) { - return new Tree<>(operator, children); - } + case ADD: + return additionCollapser.collapse(children); + case DIVIDE: + return divideCollapser.collapse(children); + case MULTIPLY: + return multiplyCollapser.collapse(children); + case SUBTRACT: + return subtractCollapser.collapse(children); + case COMPOUND: + return compoundCollapser.collapse(children); + case GROUP: + if (children.getSize() != 2) { + return new Tree<>(operator, children); + } - ComplexDice dice = new ComplexDice( - DiceASTUtils.literalToExpression( - children.getByIndex(0)), - DiceASTUtils.literalToExpression( - children.getByIndex(1))); + ComplexDice dice = new ComplexDice(DiceASTUtils.literalToExpression(children.getByIndex(0)), + DiceASTUtils.literalToExpression(children.getByIndex(1))); - if (dice.canOptimize()) { - return new Tree<>( - new IntegerLiteralNode(dice.optimize())); - } + if (dice.canOptimize()) { + return new Tree<>(new IntegerLiteralNode(dice.optimize())); + } + return new Tree<>(operator, children); + case ARRAY: + if (children.getSize() != 1) { return new Tree<>(operator, children); - case ARRAY: - if (children.getSize() != 1) { - return new Tree<>(operator, children); - } + } - return children.first(); - case ASSIGN: - case LET: - default: - // We don't optimize these operators - return new Tree<>(operator, children); + return children.first(); + case ASSIGN: + case LET: + default: + // We don't optimize these operators + return new Tree<>(operator, children); } } } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/optimization/IOptimizationPass.java b/dice-lang/src/bjc/dicelang/v1/ast/optimization/IOptimizationPass.java index 58943fa..b09d95d 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/IOptimizationPass.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/IOptimizationPass.java @@ -15,7 +15,7 @@ public interface IOptimizationPass { * Optimize a leaf in the tree * * @param leafNode - * The node to optimize + * The node to optimize * @return The optimized node */ public ITree<IDiceASTNode> optimizeLeaf(IDiceASTNode leafNode); @@ -24,11 +24,10 @@ public interface IOptimizationPass { * Optimize an operator in an AST node * * @param operator - * The operator being optimized + * The operator being optimized * @param children - * The children of the operator being optimized + * The children of the operator being optimized * @return The optimized node */ - public ITree<IDiceASTNode> optimizeOperator(IDiceASTNode operator, - IList<ITree<IDiceASTNode>> children); + public ITree<IDiceASTNode> optimizeOperator(IDiceASTNode operator, IList<ITree<IDiceASTNode>> children); } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/optimization/OperationCondenser.java b/dice-lang/src/bjc/dicelang/v1/ast/optimization/OperationCondenser.java index 4a34167..f00d390 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/OperationCondenser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/OperationCondenser.java @@ -20,18 +20,15 @@ public class OperationCondenser { * Condense chained similiar operations into a single level * * @param ast - * The AST to condense + * The AST to condense * @return The condensed AST */ public static ITree<IDiceASTNode> condense(ITree<IDiceASTNode> ast) { - return ast.topDownTransform(OperationCondenser::pickNode, - OperationCondenser::doCondense); + return ast.topDownTransform(OperationCondenser::pickNode, OperationCondenser::doCondense); } - private static ITree<IDiceASTNode> doCondense( - ITree<IDiceASTNode> ast) { - OperatorDiceNode operation = ast - .transformHead((node) -> (OperatorDiceNode) node); + private static ITree<IDiceASTNode> doCondense(ITree<IDiceASTNode> ast) { + OperatorDiceNode operation = ast.transformHead((node) -> (OperatorDiceNode) node); IHolder<Boolean> canCondense = new Identity<>(true); @@ -72,35 +69,32 @@ public class OperationCondenser { private static TopDownTransformResult pickNode(IDiceASTNode node) { switch (node.getType()) { - case LITERAL: - return TopDownTransformResult.SKIP; - case OPERATOR: - return pickOperator((OperatorDiceNode) node); - case VARIABLE: - return TopDownTransformResult.SKIP; - default: - throw new UnsupportedOperationException( - "Attempted to traverse unknown node type " + node); + case LITERAL: + return TopDownTransformResult.SKIP; + case OPERATOR: + return pickOperator((OperatorDiceNode) node); + case VARIABLE: + return TopDownTransformResult.SKIP; + default: + throw new UnsupportedOperationException("Attempted to traverse unknown node type " + node); } } - private static TopDownTransformResult pickOperator( - OperatorDiceNode node) { + private static TopDownTransformResult pickOperator(OperatorDiceNode node) { switch (node) { - case ADD: - case MULTIPLY: - case SUBTRACT: - case DIVIDE: - case COMPOUND: - return TopDownTransformResult.PUSHDOWN; - case ARRAY: - case ASSIGN: - case GROUP: - case LET: - return TopDownTransformResult.PASSTHROUGH; - default: - throw new UnsupportedOperationException( - "Attempted to traverse unknown operator " + node); + case ADD: + case MULTIPLY: + case SUBTRACT: + case DIVIDE: + case COMPOUND: + return TopDownTransformResult.PUSHDOWN; + case ARRAY: + case ASSIGN: + case GROUP: + case LET: + return TopDownTransformResult.PASSTHROUGH; + default: + throw new UnsupportedOperationException("Attempted to traverse unknown operator " + node); } } } diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceASTLanguageTest.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceASTLanguageTest.java index 117bc98..f20e276 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceASTLanguageTest.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceASTLanguageTest.java @@ -25,9 +25,9 @@ import bjc.utils.funcdata.IMap; * */ public class DiceASTLanguageTest { - private static IMap<String, DiceASTPragma> actions; + private static IMap<String, DiceASTPragma> actions; - private static DiceASTOptimizer optimizer; + private static DiceASTOptimizer optimizer; // Set up things that need to be configured static { @@ -42,7 +42,7 @@ public class DiceASTLanguageTest { System.out.println(varName + " is bound to " + varValue); }); }); - + // Create and configure the optimizer optimizer = new DiceASTOptimizer(); @@ -50,8 +50,7 @@ public class DiceASTLanguageTest { } // Read in a command - private static String getNextCommand(Scanner inputSource, - int commandNumber) { + private static String getNextCommand(Scanner inputSource, int commandNumber) { // Print a prompt using the current command number System.out.print("\ndice-lang-" + commandNumber + "> "); @@ -59,8 +58,7 @@ public class DiceASTLanguageTest { return inputSource.nextLine(); } - private static void handleInlineAction( - FunctionalStringTokenizer tokenizer, + private static void handleInlineAction(FunctionalStringTokenizer tokenizer, IMap<String, ITree<IDiceASTNode>> enviroment) { // Skip the pragma name tokenizer.nextToken(); @@ -70,11 +68,10 @@ public class DiceASTLanguageTest { if (pragmaArgs.getSize() < 3) { // Complain about pragma arguments not being valid - System.err.println( - "ERROR: Inline requires at least 3 parameters. They are:" - + "\n\t1. The name of the expression to inline." - + "\n\t2. The name of the variable to bind the result to." - + "\n\t3 and onwards. Names of variables to inline in the expression."); + System.err.println("ERROR: Inline requires at least 3 parameters. They are:" + + "\n\t1. The name of the expression to inline." + + "\n\t2. The name of the variable to bind the result to." + + "\n\t3 and onwards. Names of variables to inline in the expression."); } else { // Get arguments String inlineExpression = pragmaArgs.getByIndex(0); @@ -84,9 +81,8 @@ public class DiceASTLanguageTest { IList<String> inlinedVariables = pragmaArgs.tail().tail(); // Actually inline the variable - ITree<IDiceASTNode> inlinedExpression = DiceASTInliner - .selectiveInline(enviroment.get(inlineExpression), - enviroment, inlinedVariables); + ITree<IDiceASTNode> inlinedExpression = DiceASTInliner.selectiveInline( + enviroment.get(inlineExpression), enviroment, inlinedVariables); // Stick the inlined variable into the enviroment enviroment.put(variableName, inlinedExpression); @@ -97,7 +93,7 @@ public class DiceASTLanguageTest { * Main method of class * * @param args - * Unused CLI args + * Unused CLI args */ public static void main(String[] args) { // Prepare the things we need for input @@ -118,12 +114,10 @@ public class DiceASTLanguageTest { // Check and see if we're executing an action if (actions.containsKey(possibleActionName)) { // Execute action - FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer( - currentLine); + FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer(currentLine); // Execute the action - actions.get(possibleActionName).accept(tokenizer, - enviroment); + actions.get(possibleActionName).accept(tokenizer, enviroment); // Get the next command currentLine = getNextCommand(inputSource, commandNumber); @@ -138,11 +132,9 @@ public class DiceASTLanguageTest { long time = System.nanoTime(); // Prepare the command - IList<String> preparedTokens = DiceExpressionPreparer - .prepareCommand(currentLine); + IList<String> preparedTokens = DiceExpressionPreparer.prepareCommand(currentLine); - System.out.println("Command prepared in " - + (double) (System.nanoTime() - time) / 1000000000 + System.out.println("Command prepared in " + (double) (System.nanoTime() - time) / 1000000000 + " s"); try { @@ -152,14 +144,9 @@ public class DiceASTLanguageTest { // Create the AST builtAST = DiceASTParser.createFromString(preparedTokens); - System.out - .println( - "Command parsed in " - + (double) (System.nanoTime() - - time) / 1000000000 - + " s"); - } catch (InputMismatchException | IllegalStateException - | UnsupportedOperationException ex) { + System.out.println("Command parsed in " + + (double) (System.nanoTime() - time) / 1000000000 + " s"); + } catch (InputMismatchException | IllegalStateException | UnsupportedOperationException ex) { // Tell the user there was an error in parsing System.out.println("PARSING ERROR: " + ex.getLocalizedMessage()); @@ -176,40 +163,33 @@ public class DiceASTLanguageTest { time = System.nanoTime(); // Transform the AST - ITree<IDiceASTNode> transformedAST = transformAST(builtAST, - enviroment); + ITree<IDiceASTNode> transformedAST = transformAST(builtAST, enviroment); - System.out.println("Command transformed in " - + (double) (System.nanoTime() - time) / 1000000000 + System.out.println("Command transformed in " + (double) (System.nanoTime() - time) / 1000000000 + " s"); // Print out the transformed AST - System.out - .println("\tTransformed: " + transformedAST.toString()); - + System.out.println("\tTransformed: " + transformedAST.toString()); try { // Time the evaluation time = System.nanoTime(); // Evaluate the expression once - IResult sampleResult = DiceASTEvaluator.evaluateAST(transformedAST, - enviroment); + IResult sampleResult = DiceASTEvaluator.evaluateAST(transformedAST, enviroment); - System.out - .println( - "Command evaluated in " - + (double) (System.nanoTime() - - time) / 1000000000 - + " s"); + System.out.println("Command evaluated in " + + (double) (System.nanoTime() - time) / 1000000000 + " s"); - // Print out the result of evaluating the expression + // Print out the result of evaluating the + // expression System.out.println("\t\tSample Result: " + sampleResult); - + // Update the 'last' meta-variable enviroment.put("last", transformedAST); } catch (UnsupportedOperationException usex) { - // Tell the user there was an error in evaluation + // Tell the user there was an error in + // evaluation System.out.println("EVALUATION ERROR: " + usex.getLocalizedMessage()); // Get the next command @@ -219,7 +199,6 @@ public class DiceASTLanguageTest { continue; } - // Increase the number of commands commandNumber++; @@ -234,20 +213,16 @@ public class DiceASTLanguageTest { } // Transform a parsed AST - private static ITree<IDiceASTNode> transformAST( - ITree<IDiceASTNode> builtAST, + private static ITree<IDiceASTNode> transformAST(ITree<IDiceASTNode> builtAST, IMap<String, ITree<IDiceASTNode>> enviroment) { // Optimize the tree first - ITree<IDiceASTNode> optimizedTree = optimizer - .optimizeTree(builtAST, enviroment); + ITree<IDiceASTNode> optimizedTree = optimizer.optimizeTree(builtAST, enviroment); // Then, condense unnecessary operations - ITree<IDiceASTNode> condensedTree = OperationCondenser - .condense(optimizedTree); + ITree<IDiceASTNode> condensedTree = OperationCondenser.condense(optimizedTree); // Next, sanitize references - ITree<IDiceASTNode> sanitizedTree = DiceASTReferenceSanitizer - .sanitize(condensedTree, enviroment); + ITree<IDiceASTNode> sanitizedTree = DiceASTReferenceSanitizer.sanitize(condensedTree, enviroment); // Re-optimize the sanitized & condensed tree optimizedTree = optimizer.optimizeTree(sanitizedTree, enviroment); diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceASTPragma.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceASTPragma.java index 2fe9d30..a29b8b5 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceASTPragma.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceASTPragma.java @@ -10,12 +10,12 @@ import bjc.utils.funcdata.IMap; /** * Alias for the type of a 'pragma' or special language command * - * To explain it, a pragma is a function that takes a tokenizer with the rest - * of the line, and an enviroment that contains variable bindings + * To explain it, a pragma is a function that takes a tokenizer with the rest of + * the line, and an enviroment that contains variable bindings + * * @author ben * */ -public interface DiceASTPragma extends - BiConsumer<FunctionalStringTokenizer, IMap<String, ITree<IDiceASTNode>>> { +public interface DiceASTPragma extends BiConsumer<FunctionalStringTokenizer, IMap<String, ITree<IDiceASTNode>>> { // Just an alias } diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionParserTest.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionParserTest.java index 68a0da5..adffc69 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionParserTest.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionParserTest.java @@ -17,7 +17,7 @@ public class DiceExpressionParserTest { * Run the parser test * * @param args - * Unused CLI arguments + * Unused CLI arguments */ public static void main(String[] args) { /* @@ -39,8 +39,7 @@ public class DiceExpressionParserTest { int nTimes = Integer.parseInt(scn.nextLine()); - IDiceExpression dexp = DiceExpressionParser.parse(exp, - new HashMap<>()); + IDiceExpression dexp = DiceExpressionParser.parse(exp, new HashMap<>()); /* * Roll the dice a specified amount of times diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionPreparer.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionPreparer.java index f498f51..121847c 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionPreparer.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionPreparer.java @@ -20,11 +20,11 @@ public class DiceExpressionPreparer { /** * The yard to use for shunting expressions */ - private static ShuntingYard<String> yard; + private static ShuntingYard<String> yard; - private static final int MATH_PREC = 20; - private static final int DICE_PREC = 10; - private static final int EXPR_PREC = 0; + private static final int MATH_PREC = 20; + private static final int DICE_PREC = 10; + private static final int EXPR_PREC = 0; // Do initialization for all parsers static { @@ -39,29 +39,29 @@ public class DiceExpressionPreparer { yard.addOp("*", 1 + MATH_PREC); yard.addOp("/", 1 + MATH_PREC); - yard.addOp("d", 0 + DICE_PREC); // dice operator: use for creating + yard.addOp("d", 0 + DICE_PREC); // dice operator: use for + // creating // variable size dice groups yard.addOp("c", 1 + DICE_PREC); // compound operator: use for // creating compound dice from expressions yard.addOp("=>", 0 + EXPR_PREC); // let operator: evaluate an // expression in the context of another - yard.addOp(":=", 1 + EXPR_PREC); // binding operator: Bind a name + yard.addOp(":=", 1 + EXPR_PREC); // binding operator: Bind a + // name // to a variable expression } /** - * Prepare a command, turning raw tokens into input for the tree - * builder + * Prepare a command, turning raw tokens into input for the tree builder * * @param currentLine - * The command to prepare + * The command to prepare * @return A stream of tokens representing the command */ public static IList<String> prepareCommand(String currentLine) { // Split the command into tokens - IList<String> tokens = FunctionalStringTokenizer - .fromString(currentLine).toList(); + IList<String> tokens = FunctionalStringTokenizer.fromString(currentLine).toList(); // The linked list to use for handling tokens Deque<IPair<String, String>> ops = new LinkedList<>(); @@ -75,8 +75,7 @@ public class DiceExpressionPreparer { ops.add(new Pair<>("=>", "=>")); // Expand infix single tokens to multiple infix tokens - IList<String> semiExpandedTokens = ListUtils.splitTokens(tokens, - ops); + IList<String> semiExpandedTokens = ListUtils.splitTokens(tokens, ops); // Reinitialize the list ops = new LinkedList<>(); @@ -88,8 +87,7 @@ public class DiceExpressionPreparer { ops.add(new Pair<>("]", "\\]")); // Deaffix ('s and ['s from tokens - IList<String> fullyExpandedTokens = ListUtils - .deAffixTokens(semiExpandedTokens, ops); + IList<String> fullyExpandedTokens = ListUtils.deAffixTokens(semiExpandedTokens, ops); // Remove blank tokens fullyExpandedTokens.removeIf((strang) -> strang.equals("")); diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageState.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageState.java index e402d73..e2a71b4 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageState.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageState.java @@ -12,8 +12,7 @@ import bjc.utils.data.Pair; * @author ben * */ -public class DiceLanguageState - extends Pair<DiceExpressionParser, Map<String, IDiceExpression>> { +public class DiceLanguageState extends Pair<DiceExpressionParser, Map<String, IDiceExpression>> { /** * Create a new state @@ -25,12 +24,11 @@ public class DiceLanguageState * Create a new state with the desired parameters * * @param left - * The parser to use + * The parser to use * @param right - * The enviroment to use + * The enviroment to use */ - public DiceLanguageState(DiceExpressionParser left, - Map<String, IDiceExpression> right) { + public DiceLanguageState(DiceExpressionParser left, Map<String, IDiceExpression> right) { super(left, right); } } diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageTest.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageTest.java index 257e646..2d90318 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageTest.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageTest.java @@ -28,7 +28,7 @@ public class DiceLanguageTest { * Main method * * @param args - * Unused CLI args + * Unused CLI args */ public static void main(String[] args) { Scanner scn = new Scanner(System.in); @@ -67,25 +67,24 @@ public class DiceLanguageTest { /** * @param ln - * Unused parameter, kept to comply with expected type sig + * Unused parameter, kept to comply with expected type + * sig */ private static void printEnv(String ln, DiceLanguageState stat) { System.out.println("Printing enviroment for debugging purposes."); - stat.doWith((dep, env) -> env.forEach((key, exp) -> System.out - .println("\tKey: " + key + "\tExp: " + exp.toString()))); + stat.doWith((dep, env) -> env.forEach( + (key, exp) -> System.out.println("\tKey: " + key + "\tExp: " + exp.toString()))); } private static void rollReference(String ln, DiceLanguageState stat) { String[] strangs = ln.split(" "); - System.out.println("\tRolling dice expression " + strangs[1] + " " - + strangs[2] + " times."); + System.out.println("\tRolling dice expression " + strangs[1] + " " + strangs[2] + " times."); int nRolls = Integer.parseInt(strangs[2]); - IDiceExpression dexp = stat - .merge((dep, env) -> env.get(strangs[1])); + IDiceExpression dexp = stat.merge((dep, env) -> env.get(strangs[1])); for (int i = 1; i <= nRolls; i++) { int roll = dexp.roll(); |
