From 635d3150e3e85c01b777ff165e21fa8965d58440 Mon Sep 17 00:00:00 2001 From: EVE Date: Tue, 14 Mar 2017 12:08:11 -0400 Subject: Cleanup --- dice-lang/src/bjc/dicelang/CLIArgsParser.java | 89 ++++++------- dice-lang/src/bjc/dicelang/CompilerTweaker.java | 23 ++-- dice-lang/src/bjc/dicelang/Define.java | 66 ++++----- dice-lang/src/bjc/dicelang/DiceLangConsole.java | 62 ++++----- dice-lang/src/bjc/dicelang/DiceLangEngine.java | 147 +++++++++------------ dice-lang/src/bjc/dicelang/Errors.java | 8 +- dice-lang/src/bjc/dicelang/Evaluator.java | 141 ++++++++++---------- dice-lang/src/bjc/dicelang/EvaluatorResult.java | 11 +- dice-lang/src/bjc/dicelang/Node.java | 20 +-- dice-lang/src/bjc/dicelang/Parser.java | 46 +++---- dice-lang/src/bjc/dicelang/Shunter.java | 117 ++++++++-------- dice-lang/src/bjc/dicelang/Token.java | 14 +- dice-lang/src/bjc/dicelang/Tokenizer.java | 38 +++--- dice-lang/src/bjc/dicelang/dice/CompoundDie.java | 4 +- .../src/bjc/dicelang/dice/CompoundingDie.java | 13 +- dice-lang/src/bjc/dicelang/dice/DiceBox.java | 74 +++++------ dice-lang/src/bjc/dicelang/dice/Die.java | 2 +- dice-lang/src/bjc/dicelang/dice/DieExpression.java | 10 +- dice-lang/src/bjc/dicelang/dice/ExplodingDice.java | 18 +-- dice-lang/src/bjc/dicelang/dice/FudgeDie.java | 7 +- dice-lang/src/bjc/dicelang/dice/MathDie.java | 14 +- dice-lang/src/bjc/dicelang/dice/ScalarDie.java | 5 + dice-lang/src/bjc/dicelang/dice/SimpleDie.java | 21 +-- dice-lang/src/bjc/dicelang/dice/SimpleDieList.java | 17 ++- .../src/bjc/dicelang/scl/StreamControlEngine.java | 118 +++++++---------- dice-lang/src/bjc/dicelang/scl/StreamEngine.java | 64 ++++----- .../src/bjc/dicelang/util/ResourceLoader.java | 28 ++-- .../src/bjc/dicelang/v1/BindingDiceExpression.java | 20 ++- dice-lang/src/bjc/dicelang/v1/ComplexDice.java | 37 ++---- dice-lang/src/bjc/dicelang/v1/CompoundDice.java | 16 +-- .../src/bjc/dicelang/v1/DiceExpressionBuilder.java | 24 ++-- .../src/bjc/dicelang/v1/DiceExpressionParser.java | 24 ++-- .../src/bjc/dicelang/v1/DiceExpressionType.java | 2 +- dice-lang/src/bjc/dicelang/v1/Die.java | 12 +- dice-lang/src/bjc/dicelang/v1/IDiceExpression.java | 28 ++-- .../bjc/dicelang/v1/OperatorDiceExpression.java | 8 +- dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java | 30 ++--- .../bjc/dicelang/v1/ReferenceDiceExpression.java | 13 +- dice-lang/src/bjc/dicelang/v1/ScalarDie.java | 4 +- .../bjc/dicelang/v1/ast/ArithmeticCollapser.java | 30 ++--- dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java | 6 +- .../src/bjc/dicelang/v1/ast/DiceASTEvaluator.java | 48 +++---- .../src/bjc/dicelang/v1/ast/DiceASTInliner.java | 32 ++--- .../src/bjc/dicelang/v1/ast/DiceASTOptimizer.java | 6 +- .../src/bjc/dicelang/v1/ast/DiceASTParser.java | 43 +++--- .../dicelang/v1/ast/DiceASTReferenceChecker.java | 12 +- .../dicelang/v1/ast/DiceASTReferenceSanitizer.java | 54 +++----- .../src/bjc/dicelang/v1/ast/DiceASTUtils.java | 18 ++- dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java | 6 +- .../bjc/dicelang/v1/ast/IOperatorCollapser.java | 6 +- dice-lang/src/bjc/dicelang/v1/ast/IResult.java | 4 +- .../src/bjc/dicelang/v1/ast/IntegerResult.java | 6 +- dice-lang/src/bjc/dicelang/v1/ast/ResultType.java | 2 +- .../src/bjc/dicelang/v1/ast/nodes/DiceASTType.java | 2 +- .../bjc/dicelang/v1/ast/nodes/DiceLiteralNode.java | 6 +- .../bjc/dicelang/v1/ast/nodes/DiceLiteralType.java | 2 +- .../dicelang/v1/ast/nodes/DiceOperatorType.java | 4 +- .../bjc/dicelang/v1/ast/nodes/IDiceASTNode.java | 6 +- .../dicelang/v1/ast/nodes/ILiteralDiceNode.java | 19 ++- .../dicelang/v1/ast/nodes/IntegerLiteralNode.java | 6 +- .../dicelang/v1/ast/nodes/OperatorDiceNode.java | 8 +- .../dicelang/v1/ast/nodes/VariableDiceNode.java | 34 +++-- .../bjc/dicelang/v1/ast/nodes/package-info.java | 2 +- .../v1/ast/optimization/ArithmeticCollapser.java | 17 +-- .../v1/ast/optimization/ConstantCollapser.java | 22 +-- .../v1/ast/optimization/IOptimizationPass.java | 6 +- .../v1/ast/optimization/OperationCondenser.java | 22 ++- .../dicelang/v1/ast/optimization/package-info.java | 2 +- .../src/bjc/dicelang/v1/ast/package-info.java | 2 +- .../dicelang/v1/examples/DiceASTLanguageTest.java | 20 +-- .../bjc/dicelang/v1/examples/DiceASTPragma.java | 8 +- .../v1/examples/DiceExpressionParserTest.java | 12 +- .../v1/examples/DiceExpressionPreparer.java | 16 +-- .../dicelang/v1/examples/DiceLanguageState.java | 8 +- .../bjc/dicelang/v1/examples/DiceLanguageTest.java | 16 +-- 75 files changed, 897 insertions(+), 1011 deletions(-) diff --git a/dice-lang/src/bjc/dicelang/CLIArgsParser.java b/dice-lang/src/bjc/dicelang/CLIArgsParser.java index 16a8f34..6b96ac6 100644 --- a/dice-lang/src/bjc/dicelang/CLIArgsParser.java +++ b/dice-lang/src/bjc/dicelang/CLIArgsParser.java @@ -10,28 +10,29 @@ import static bjc.dicelang.Errors.ErrorKey.*; /** * Parse CLI arguments. - * + * * @author Ben Culkin - * + * */ public class CLIArgsParser { /** * Parse the provided set of CLI arguments. - * - * @param args The CLI arguments to parse. - * @param eng The engine to affect with parsing. - * + * + * @param args + * The CLI arguments to parse. + * @param eng + * The engine to affect with parsing. + * * @return Whether or not to continue to the DiceLang repl. */ 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"))) { System.out.println("Help for DiceLang v0.2 CLI arguments:"); System.out.println("\t-d or --debug\tTurn on debug mode."); - System.out.println("\t\tTurns on debug mode, which prints additional information that may be useful."); + System.out.println( + "\t\tTurns on debug mode, which prints additional information that may be useful."); System.out.println("\t-nd or --no-debug\tTurn off debug mode."); System.out.println("\t\tTurns off debug mode."); System.out.println("\t-po or --postfix\tTurn on postfix mode."); @@ -39,84 +40,82 @@ public class CLIArgsParser { System.out.println("\t-npo or --no-postfix\tTurn off postfix mode."); System.out.println("\t\tTurns off postfix mode."); System.out.println("\t-pr or --prefix\tTurn on prefix mode."); - System.out.println("\t\tTurns on prefix mode, which reverses the expression instead of shunting it."); + System.out.println( + "\t\tTurns on prefix mode, which reverses the expression instead of shunting it."); System.out.println("\t-npr or --no-prefix\tTurn off prefix mode."); System.out.println("\t\tTurns off prefix mode."); System.out.println("\t-se or --step-eval\tTurn on step-eval mode."); - System.out.println("\t\tTurns on step-evaluation, which shows the evaluation process step-by-step. Currently slightly broken."); + System.out.println( + "\t\tTurns on step-evaluation, which shows the evaluation process step-by-step. Currently slightly broken."); System.out.println("\t-nse or --no-step-eval\tTurn off step-eval mode."); System.out.println("\t\tTurns off step-evaluation."); System.out.println("\t-D or "); 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) { + switch(arg) { case "-d": case "--debug": - if (!eng.toggleDebug()) { + if(!eng.toggleDebug()) { eng.toggleDebug(); } break; case "-nd": case "--no-debug": - if (eng.toggleDebug()) { + if(eng.toggleDebug()) { eng.toggleDebug(); } break; case "-po": case "--postfix": - if (!eng.togglePostfix()) { + if(!eng.togglePostfix()) { eng.togglePostfix(); } break; case "-npo": case "--no-postfix": - if (eng.togglePostfix()) { + if(eng.togglePostfix()) { eng.togglePostfix(); } break; case "-pr": case "--prefix": - if (!eng.togglePrefix()) { + if(!eng.togglePrefix()) { eng.togglePrefix(); } break; case "-npr": case "--no-prefix": - if (eng.togglePrefix()) { + if(eng.togglePrefix()) { eng.togglePrefix(); } break; case "-se": case "--stepeval": - if (!eng.toggleStepEval()) { + if(!eng.toggleStepEval()) { eng.toggleStepEval(); } break; case "-nse": case "--no-stepeval": - if (eng.toggleStepEval()) { + if(eng.toggleStepEval()) { eng.toggleStepEval(); } break; case "-D": case "--define": i = simpleDefine(i, args, eng); - if (i == -1) { - return false; - } + if(i == -1) return false; break; case "-df": case "--define-file": i = defineFile(i, args, eng); - if (i == -1) { - return false; - } + if(i == -1) return false; break; case "-ctf": case "--compiler-tweak-file": @@ -133,17 +132,15 @@ 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; @@ -151,35 +148,31 @@ public class CLIArgsParser { 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(dfn == null || dfn.inError) return -1; - if (ln.startsWith("line")) { + if(ln.startsWith("line")) { eng.addLineDefine(dfn); - } else if (ln.startsWith("token")) { + } else if(ln.startsWith("token")) { eng.addTokenDefine(dfn); } else { String defnType = ln.substring(0, ln.indexOf(' ')); @@ -189,10 +182,10 @@ public class CLIArgsParser { } } } - } catch (FileNotFoundException fnfex) { + } catch(FileNotFoundException fnfex) { Errors.inst.printError(EK_MISC_NOFILE, fName); return -1; - } catch (IOException ioex) { + } catch(IOException ioex) { Errors.inst.printError(EK_MISC_IOEX, fName); return -1; } diff --git a/dice-lang/src/bjc/dicelang/CompilerTweaker.java b/dice-lang/src/bjc/dicelang/CompilerTweaker.java index 95a8761..c711e9f 100644 --- a/dice-lang/src/bjc/dicelang/CompilerTweaker.java +++ b/dice-lang/src/bjc/dicelang/CompilerTweaker.java @@ -4,15 +4,15 @@ import bjc.utils.funcutils.NeoTokenSplitter; /** * Contains methods for customizing the DiceLang and SCL compilers. - * + * * @author Ben Culkin */ public class CompilerTweaker { /* * Bits of the compiler necessary */ - private DiceLangEngine eng; - private NeoTokenSplitter opExpander; + private DiceLangEngine eng; + private NeoTokenSplitter opExpander; public CompilerTweaker(DiceLangEngine eng) { this.eng = eng; @@ -22,10 +22,10 @@ public class CompilerTweaker { /** * Add a string literal to the compiler's internal banks. - * + * * @param val * The string literal to add. - * + * * @return The key into the string literal table for this string. */ public int addStringLiteral(String val) { @@ -37,7 +37,7 @@ public class CompilerTweaker { /** * Add a line defn to the compiler. - * + * * @param dfn * The defn to add. */ @@ -47,7 +47,7 @@ public class CompilerTweaker { /** * Add a token defn to the compiler. - * + * * @param dfn * The defn to add. */ @@ -57,7 +57,7 @@ public class CompilerTweaker { /** * Adds a delimiter that is expanded from tokens. - * + * * @param delim * The delimiter to expand on. */ @@ -67,7 +67,7 @@ public class CompilerTweaker { /** * Adds a multi-character delimiter that is expanded from tokens. - * + * * @param delim * The multi-character delimiter to expand on. */ @@ -84,8 +84,9 @@ public class CompilerTweaker { /** * Change the max no. of times defines are allowed to recur. - * - * @param times The number of times to allow defines to recur. + * + * @param times + * The number of times to allow defines to recur. */ public void setDefineRecurLimit(int times) { Define.MAX_RECURS = times; diff --git a/dice-lang/src/bjc/dicelang/Define.java b/dice-lang/src/bjc/dicelang/Define.java index b7d196d..d9e1f84 100644 --- a/dice-lang/src/bjc/dicelang/Define.java +++ b/dice-lang/src/bjc/dicelang/Define.java @@ -2,14 +2,16 @@ package bjc.dicelang; import bjc.utils.data.CircularIterator; -import static bjc.dicelang.Errors.ErrorKey.*; - import java.util.Iterator; import java.util.function.UnaryOperator; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; +import static bjc.dicelang.Errors.ErrorKey.EK_DFN_PREDSYN; +import static bjc.dicelang.Errors.ErrorKey.EK_DFN_RECUR; +import static bjc.dicelang.Errors.ErrorKey.EK_DFN_SRCSYN; + public class Define implements UnaryOperator, Comparable { public static enum Type { LINE, TOKEN @@ -17,17 +19,17 @@ public class Define implements UnaryOperator, Comparable { public static int MAX_RECURS = 10; - public final int priority; - public final boolean inError; + public final int priority; + public final boolean inError; - private boolean doRecur; - private boolean subType; + private boolean doRecur; + private boolean subType; - private Pattern predicate; - private Pattern searcher; + private Pattern predicate; + private Pattern searcher; - private Iterator replacers; - private String replacer; + private Iterator replacers; + private String replacer; public Define(int priorty, boolean isSub, boolean recur, boolean isCircular, String predicte, String searchr, Iterable replacrs) { @@ -38,10 +40,10 @@ public class Define implements UnaryOperator, Comparable { /* * Only try to compile non-null predicates */ - if (predicte != null) { + if(predicte != null) { try { predicate = Pattern.compile(predicte); - } catch (PatternSyntaxException psex) { + } catch(PatternSyntaxException psex) { Errors.inst.printError(EK_DFN_PREDSYN, psex.getMessage()); inError = true; return; @@ -53,7 +55,7 @@ public class Define implements UnaryOperator, Comparable { */ try { searcher = Pattern.compile(searchr); - } catch (PatternSyntaxException psex) { + } catch(PatternSyntaxException psex) { Errors.inst.printError(EK_DFN_SRCSYN, psex.getMessage()); inError = true; return; @@ -63,8 +65,8 @@ public class Define implements UnaryOperator, Comparable { /* * 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; @@ -72,39 +74,38 @@ public class Define implements UnaryOperator, Comparable { } else { Iterator itr = replacrs.iterator(); - if (itr.hasNext()) + if(itr.hasNext()) { replacer = itr.next(); - else + } else { replacer = ""; + } } } + @Override public String apply(String tok) { - if (inError) - return tok; + if(inError) return tok; - if (predicate != null) { - if (!predicate.matcher(tok).matches()) { - return tok; - } + 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 { + else { String oldStrang = strang; 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; } @@ -117,10 +118,10 @@ public class Define implements UnaryOperator, Comparable { private String doPass(String tok) { Matcher searcherMatcher = searcher.matcher(tok); - if (subType) { + if(subType) { StringBuffer sb = new StringBuffer(); - while (searcherMatcher.find()) { - if (replacers == null) { + while(searcherMatcher.find()) { + if(replacers == null) { searcherMatcher.appendReplacement(sb, ""); } else { String replac = replacers.next(); @@ -130,9 +131,8 @@ public class Define implements UnaryOperator, Comparable { searcherMatcher.appendTail(sb); return sb.toString(); - } else { + } else return searcherMatcher.replaceAll(replacer); - } } @Override diff --git a/dice-lang/src/bjc/dicelang/DiceLangConsole.java b/dice-lang/src/bjc/dicelang/DiceLangConsole.java index 1e4bf32..3a53322 100644 --- a/dice-lang/src/bjc/dicelang/DiceLangConsole.java +++ b/dice-lang/src/bjc/dicelang/DiceLangConsole.java @@ -1,13 +1,14 @@ package bjc.dicelang; -import static bjc.dicelang.Errors.ErrorKey.*; - import java.io.IOException; -import java.util.List; import java.util.LinkedList; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; +import static bjc.dicelang.Errors.ErrorKey.EK_CONS_INVDEFINE; +import static bjc.dicelang.Errors.ErrorKey.EK_CONS_INVPRAG; + import jline.ConsoleReader; import jline.Terminal; @@ -23,7 +24,7 @@ public class DiceLangConsole { eng = new DiceLangEngine(); - if (!CLIArgsParser.parseArgs(args, eng)) { + if(!CLIArgsParser.parseArgs(args, eng)) { System.exit(1); } @@ -33,7 +34,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; } @@ -44,35 +45,37 @@ public class DiceLangConsole { try { comm = read.readLine(String.format("(%d) dice-lang> ", commandNumber)); - } catch (IOException ioex) { + } catch(IOException ioex) { System.out.println("ERROR: I/O failed"); 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) + if(success) { System.out.println("Pragma completed succesfully"); - else + } else { System.out.println("Pragma execution failed"); + } } else { System.out.printf("\tRaw command: %s\n", comm); boolean success = eng.runCommand(comm); - if (success) + if(success) { System.out.println("Command completed succesfully"); - else + } else { System.out.println("Command execution failed"); + } commandNumber += 1; } try { comm = read.readLine(String.format("(%d) dice-lang> ", commandNumber)); - } catch (IOException ioex) { + } catch(IOException ioex) { System.out.println("ERROR: I/O failed"); return; } @@ -84,13 +87,13 @@ 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) { + switch(pragmaName) { case "debug": System.out.println("\tDebug mode is now " + eng.toggleDebug()); break; @@ -116,7 +119,7 @@ public class DiceLangConsole { } private boolean helpMode(String pragma) { - switch (pragma.trim()) { + switch(pragma.trim()) { case "help": System.out.println("\tGet help on pragmas"); break; @@ -164,22 +167,22 @@ public class DiceLangConsole { int fifthIndex = defineText.indexOf(' ', fourthIndex + 1); int sixthIndex = defineText.indexOf(' ', fifthIndex + 1); - if (firstIndex == -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; } @@ -191,7 +194,7 @@ public class DiceLangConsole { Define.Type type; boolean subMode = false; - switch (defineType) { + switch(defineType) { case "line": type = Define.Type.LINE; break; @@ -220,8 +223,8 @@ public class DiceLangConsole { String guardPattern = null; - if (hasGuard) { - if (!patMatcher.find()) { + if(hasGuard) { + if(!patMatcher.find()) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no guard pattern)"); return false; } @@ -229,7 +232,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; } @@ -237,17 +240,16 @@ public class DiceLangConsole { String searchPattern = patMatcher.group(1); List 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; + 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 f65f5dd..d16e9f4 100644 --- a/dice-lang/src/bjc/dicelang/DiceLangEngine.java +++ b/dice-lang/src/bjc/dicelang/DiceLangEngine.java @@ -1,7 +1,6 @@ package bjc.dicelang; import bjc.dicelang.scl.StreamEngine; - import bjc.utils.data.ITree; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.FunctionalMap; @@ -14,12 +13,13 @@ import bjc.utils.funcutils.StringUtils; import java.util.Deque; import java.util.Iterator; -import java.util.List; import java.util.LinkedList; +import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static bjc.dicelang.Errors.ErrorKey.*; +import static bjc.dicelang.Errors.ErrorKey.EK_ENG_NOCLOSING; +import static bjc.dicelang.Errors.ErrorKey.EK_ENG_NOOPENING; import static bjc.dicelang.Token.Type.*; /** @@ -83,14 +83,14 @@ public class DiceLangEngine { */ public final IMap symTable; - private IMap stringLits; - private IMap stringLiterals; + private IMap stringLits; + private IMap stringLiterals; /* * Lists of defns. */ - private IList lineDefns; - private IList tokenDefns; + private IList lineDefns; + private IList tokenDefns; /* * Are defns sorted by priority? @@ -249,7 +249,7 @@ public class DiceLangEngine { * * @param command * The command to run - * + * * @return Whether or not the command ran successfully */ public boolean runCommand(String command) { @@ -258,18 +258,14 @@ public class DiceLangEngine { */ IList preprocessedTokens = preprocessCommand(command); - if (preprocessedTokens == null) { - return false; - } + if(preprocessedTokens == null) return false; /* * Lex the string tokens into token-tokens */ IList lexedTokens = lexTokens(preprocessedTokens); - if (lexedTokens == null) { - return false; - } + if(lexedTokens == null) return false; /* * Parse the tokens into an AST forest @@ -277,9 +273,7 @@ public class DiceLangEngine { IList> astForest = new FunctionalList<>(); boolean succ = parsr.parseTokens(lexedTokens, astForest); - if (!succ) { - return false; - } + if(!succ) return false; /* * Evaluate the AST forest @@ -295,13 +289,13 @@ public class DiceLangEngine { private IList lexTokens(IList preprocessedTokens) { IList 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); } @@ -310,22 +304,22 @@ 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 */ return null; - } else { + else { lexedTokens.add(tk); } } - if (debugMode) { + if(debugMode) { System.out.printf("\tCommand after tokenization: %s\n", lexedTokens.toString()); } @@ -337,25 +331,21 @@ public class DiceLangEngine { boolean succ = removePreshuntTokens(lexedTokens, preparedTokens); - if (!succ) { - return null; - } + 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) { - return null; - } - } else if (prefixMode) { + if(!succ) return null; + } else if(prefixMode) { /* * Reverse directional tokens */ @@ -363,7 +353,7 @@ public class DiceLangEngine { shuntedTokens = preparedTokens.map(this::reverseToken); } - if (debugMode && !postfixMode) { + if(debugMode && !postfixMode) { System.out.printf("\tCommand after shunting: %s\n", shuntedTokens.toString()); } @@ -371,16 +361,15 @@ public class DiceLangEngine { * Expand token groups */ IList 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 { + else return new FunctionalList<>(tk); - } }); - if (debugMode && !postfixMode) { + if(debugMode && !postfixMode) { System.out.printf("\tCommand after re-preshunting: %s\n", readyTokens.toString()); } @@ -389,11 +378,11 @@ public class DiceLangEngine { /* * Reverse orientation-sensitive tokens. - * + * * These are mostly just things like (, {, and [ */ private Token reverseToken(Token tk) { - switch (tk.type) { + switch(tk.type) { case OBRACE: return new Token(CBRACE, tk.intValue); case OPAREN: @@ -418,7 +407,7 @@ public class DiceLangEngine { /* * Sort the defines if they aren't sorted */ - if (!defnsSorted) { + if(!defnsSorted) { sortDefns(); } @@ -428,24 +417,22 @@ public class DiceLangEngine { IList streamToks = new FunctionalList<>(); boolean succ = streamEng.doStreams(command.split(" "), streamToks); - if (!succ) { - return null; - } + if(!succ) return null; /* * 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); } @@ -455,11 +442,11 @@ public class DiceLangEngine { List 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. */ @@ -482,13 +469,13 @@ public class DiceLangEngine { } } - 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) -> { @@ -510,17 +497,16 @@ 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)); return tkName; - } else { + } else return tk; - } }); - if (debugMode) { + if(debugMode) { System.out.printf("\tCommand after removal of non-expanders: %s\n", tokens.toString()); } @@ -535,14 +521,13 @@ public class DiceLangEngine { * Reinsert non-expanded tokens */ fullyExpandedTokens = fullyExpandedTokens.map(tk -> { - if (tk.startsWith("nonExpandToken")) { + if(tk.startsWith("nonExpandToken")) return nonExpandedTokens.get(tk); - } else { + else return tk; - } }); - if (debugMode) { + if(debugMode) { System.out.printf("\tCommand after non-expander reinsertion: %s\n", fullyExpandedTokens.toString()); } @@ -551,24 +536,24 @@ public class DiceLangEngine { } private void evaluateForest(IList> astForest) { - if (debugMode) { + if(debugMode) { System.out.println("\tParsed forest of asts"); } int treeNo = 1; - for (ITree ast : astForest) { - if (debugMode) { + for(ITree 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> itr = eval.stepDebug(ast); itr.hasNext();) { + for(Iterator> itr = eval.stepDebug(ast); itr.hasNext();) { ITree nodeStep = itr.next(); System.out.printf("\t\tStep %d: Node is %s", step, nodeStep); @@ -576,7 +561,7 @@ public class DiceLangEngine { /* * Don't evaluate null steps */ - if (nodeStep == null) { + if(nodeStep == null) { System.out.println(); step += 1; @@ -586,16 +571,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); } @@ -614,10 +599,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() + ")"); } } @@ -644,14 +629,14 @@ public class DiceLangEngine { Deque> bracedTokens = new LinkedList<>(); IList 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. @@ -660,11 +645,11 @@ public class DiceLangEngine { } 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. @@ -682,16 +667,14 @@ public class DiceLangEngine { */ boolean success = shunt.shuntTokens(curBracedTokens, preshuntTokens); - if (debugMode) { + if(debugMode) { System.out.println("\t\tPreshunted " + curBracedTokens + " into " + preshuntTokens); } - if (!success) { - return false; - } + if(!success) return false; - if (curBraceCount >= 1) { + if(curBraceCount >= 1) { /* * Add the preshunt group to the * previous group. @@ -711,7 +694,7 @@ public class DiceLangEngine { * 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); @@ -719,7 +702,7 @@ public class DiceLangEngine { } } - if (curBraceCount > 0) { + if(curBraceCount > 0) { /* * There was an unclosed group. */ diff --git a/dice-lang/src/bjc/dicelang/Errors.java b/dice-lang/src/bjc/dicelang/Errors.java index 8689861..6fa8072 100644 --- a/dice-lang/src/bjc/dicelang/Errors.java +++ b/dice-lang/src/bjc/dicelang/Errors.java @@ -119,7 +119,7 @@ public class Errors { EK_CLI_MISARG, // Invalid define type EK_CLI_INVDFNTYPE, - + // Misc. errors // Unknown I/O problem EK_MISC_IOEX, @@ -134,9 +134,9 @@ public class Errors { private ErrorMode mode; public void printError(ErrorKey key, String... args) { - switch (mode) { + switch(mode) { case WIZARD: - if (key == ErrorKey.EK_MISC_NOFILE) { + if(key == ErrorKey.EK_MISC_NOFILE) { System.out.println("\t? 404"); } else { System.out.println("\t? " + key.ordinal()); @@ -151,7 +151,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; diff --git a/dice-lang/src/bjc/dicelang/Evaluator.java b/dice-lang/src/bjc/dicelang/Evaluator.java index 5ecff25..190e911 100644 --- a/dice-lang/src/bjc/dicelang/Evaluator.java +++ b/dice-lang/src/bjc/dicelang/Evaluator.java @@ -8,18 +8,18 @@ import bjc.dicelang.dice.SimpleDie; import bjc.dicelang.dice.SimpleDieList; import bjc.utils.data.ITree; import bjc.utils.data.SingleIterator; -import bjc.utils.data.Tree; import bjc.utils.data.TopDownTransformIterator; import bjc.utils.data.TopDownTransformResult; - -import static bjc.dicelang.Errors.ErrorKey.*; -import static bjc.dicelang.EvaluatorResult.Type.*; +import bjc.utils.data.Tree; import java.util.Deque; import java.util.Iterator; import java.util.LinkedList; import java.util.function.Consumer; +import static bjc.dicelang.Errors.ErrorKey.*; +import static bjc.dicelang.EvaluatorResult.Type.*; + public class Evaluator { private static enum CoerceSteps { INTEGER, FLOAT; @@ -62,8 +62,9 @@ public class Evaluator { // It's only for stepwise evaluation // but we don't know if stepping the iterator causes // something to happen - while (itr.hasNext()) + while(itr.hasNext()) { itr.next(); + } }; return comm.topDownTransform(this::pickEvaluationType, (node) -> this.evaluateNode(node, ctx)) @@ -84,9 +85,9 @@ public class Evaluator { } 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: @@ -98,7 +99,7 @@ public class Evaluator { } private ITree evaluateNode(ITree ast, Context ctx) { - switch (ast.getHead().type) { + switch(ast.getHead().type) { case UNARYOP: return evaluateUnaryOp(ast, ctx); case BINOP: @@ -116,12 +117,12 @@ public class Evaluator { } private ITree evaluateUnaryOp(ITree 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 */ @@ -132,39 +133,41 @@ public class Evaluator { CoerceSteps curLevel = CoerceSteps.INTEGER; - for (int i = 0; i < toCoerce.getChildrenCount(); i++) { + for(int i = 0; i < toCoerce.getChildrenCount(); i++) { ITree child = toCoerce.getChild(i); ITree nChild = null; - if (ctx.isDebug) { + if(ctx.isDebug) { Iterator> 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) + if(nChild != null) { ctx.thunk.accept(new SingleIterator<>(nChild)); + } } Node childNode = nChild.getHead(); EvaluatorResult res = childNode.resultVal; - if (res.type == FLOAT) + if(res.type == FLOAT) { curLevel = CoerceSteps.FLOAT; + } children.add(nChild); } - for (ITree child : children) { + for(ITree child : children) { Node nd = child.getHead(); EvaluatorResult res = nd.resultVal; - switch (res.type) { + switch(res.type) { case INT: - if (curLevel == CoerceSteps.FLOAT) { + if(curLevel == CoerceSteps.FLOAT) { nd.resultVal = new EvaluatorResult(FLOAT, (double) res.intVal); } default: @@ -179,7 +182,7 @@ 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()); } @@ -188,7 +191,7 @@ public class Evaluator { 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()); } @@ -203,7 +206,7 @@ public class Evaluator { private ITree evaluateBinaryOp(ITree ast, Context ctx) { Token.Type binOp = ast.getHead().operatorType; - if (ast.getChildrenCount() != 2) { + if(ast.getChildrenCount() != 2) { Errors.inst.printError(EK_EVAL_INVBIN, Integer.toString(ast.getChildrenCount()), ast.toString()); @@ -213,7 +216,7 @@ public class Evaluator { ITree left = ast.getChild(0); ITree right = ast.getChild(1); - switch (binOp) { + switch(binOp) { case ADD: case SUBTRACT: case MULTIPLY: @@ -235,16 +238,16 @@ public class Evaluator { private ITree evaluateStringBinary(Token.Type op, EvaluatorResult left, EvaluatorResult right, Context ctx) { - if (left.type != STRING) { + 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 { @@ -253,13 +256,13 @@ public class Evaluator { 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))); @@ -274,24 +277,24 @@ public class Evaluator { 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) { + } else if(right.type == INT) { 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) { + } 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) { + } else if(right.type == INT) { res = new EvaluatorResult(DICE, new SimpleDie(left.intVal, right.intVal)); } else { Errors.inst.printError(EK_EVAL_INVDGROUP, right.type.toString()); @@ -302,10 +305,10 @@ 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 { @@ -314,10 +317,10 @@ public class Evaluator { } 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 { @@ -335,42 +338,42 @@ public class Evaluator { private ITree evaluateMathBinary(Token.Type op, EvaluatorResult left, EvaluatorResult right, Context ctx) { - if (left.type == STRING || right.type == STRING) { + 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)); } @@ -382,13 +385,13 @@ public class Evaluator { } 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)); } @@ -400,13 +403,13 @@ public class Evaluator { } 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)); } @@ -418,15 +421,15 @@ public class Evaluator { } 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 { @@ -438,15 +441,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 { @@ -468,7 +471,7 @@ public class Evaluator { private ITree evaluateTokenRef(Token tk, Context ctx) { EvaluatorResult res = null; - switch (tk.type) { + switch(tk.type) { case INT_LIT: res = new EvaluatorResult(INT, tk.intValue); break; @@ -479,7 +482,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 2c3c74c..276e801 100644 --- a/dice-lang/src/bjc/dicelang/EvaluatorResult.java +++ b/dice-lang/src/bjc/dicelang/EvaluatorResult.java @@ -15,10 +15,10 @@ public class EvaluatorResult { // These may or may not have values based // off of the result type - public long intVal; - public double floatVal; - public DieExpression diceVal; - public String stringVal; + public long intVal; + public double floatVal; + public DieExpression diceVal; + public String stringVal; // Original node data public ITree origVal; @@ -77,8 +77,9 @@ public class EvaluatorResult { stringVal = strang; } + @Override public String toString() { - switch (type) { + switch(type) { case INT: return type.toString() + "(" + intVal + ")"; case FLOAT: diff --git a/dice-lang/src/bjc/dicelang/Node.java b/dice-lang/src/bjc/dicelang/Node.java index 15ae66e..df966ba 100644 --- a/dice-lang/src/bjc/dicelang/Node.java +++ b/dice-lang/src/bjc/dicelang/Node.java @@ -12,10 +12,10 @@ 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 EvaluatorResult resultVal; + public Token tokenVal; + public Token.Type operatorType; + public GroupType groupType; + public EvaluatorResult resultVal; public Node(Type typ) { type = typ; @@ -45,8 +45,9 @@ public class Node { resultVal = res; } + @Override public String toString() { - switch (type) { + switch(type) { case UNARYOP: case BINOP: return "(" + type.name() + " : " + operatorType + ")"; @@ -62,16 +63,15 @@ public class Node { } } + @Override public boolean equals(Object other) { - if (!(other instanceof Node)) - return false; + if(!(other instanceof Node)) return false; Node otk = (Node) other; - if (otk.type != type) - return false; + if(otk.type != type) return false; - switch (type) { + switch(type) { case OGROUP: return tokenVal.equals(otk.tokenVal); default: diff --git a/dice-lang/src/bjc/dicelang/Parser.java b/dice-lang/src/bjc/dicelang/Parser.java index 828cad7..bfb7a03 100644 --- a/dice-lang/src/bjc/dicelang/Parser.java +++ b/dice-lang/src/bjc/dicelang/Parser.java @@ -1,15 +1,16 @@ package bjc.dicelang; -import static bjc.dicelang.Errors.ErrorKey.*; -import static bjc.dicelang.Node.Type.*; -import static bjc.dicelang.Token.Type.*; +import bjc.utils.data.ITree; +import bjc.utils.data.Tree; +import bjc.utils.funcdata.IList; import java.util.Deque; import java.util.LinkedList; -import bjc.utils.data.ITree; -import bjc.utils.data.Tree; -import bjc.utils.funcdata.IList; +import static bjc.dicelang.Errors.ErrorKey.*; +import static bjc.dicelang.Node.Type.*; +import static bjc.dicelang.Token.Type.CBRACE; +import static bjc.dicelang.Token.Type.CBRACKET; public class Parser { public Parser() { @@ -19,8 +20,8 @@ public class Parser { public boolean parseTokens(IList tokens, IList> results) { Deque> working = new LinkedList<>(); - for (Token tk : tokens) { - switch (tk.type) { + for(Token tk : tokens) { + switch(tk.type) { case OBRACKET: case OBRACE: working.push(new Tree<>(new Node(OGROUP, tk))); @@ -28,8 +29,7 @@ public class Parser { case CBRACKET: case CBRACE: boolean sc = parseClosingGrouper(working, tk); - if (!sc) - return false; + if(!sc) return false; break; case MULTIPLY: case DIVIDE: @@ -41,7 +41,7 @@ public class Parser { case STRREP: case LET: case BIND: - if (working.size() < 2) { + if(working.size() < 2) { Errors.inst.printError(EK_PARSE_BINARY); return false; } else { @@ -58,10 +58,10 @@ public class Parser { break; case ADD: case SUBTRACT: - if (working.size() == 0) { + if(working.size() == 0) { Errors.inst.printError(EK_PARSE_UNOPERAND, tk.toString()); return false; - } else if (working.size() == 1) { + } else if(working.size() == 1) { ITree operand = working.pop(); ITree opNode = new Tree<>(new Node(UNARYOP, tk.type)); @@ -84,7 +84,7 @@ public class Parser { case COERCE: case DICESCALAR: case DICEFUDGE: - if (working.size() == 0) { + if(working.size() == 0) { Errors.inst.printError(EK_PARSE_UNOPERAND, tk.toString()); } else { ITree operand = working.pop(); @@ -108,7 +108,7 @@ public class Parser { } } - for (ITree ast : working) { + for(ITree ast : working) { results.add(ast); } @@ -116,13 +116,13 @@ public class Parser { } private boolean parseClosingGrouper(Deque> working, Token tk) { - if (working.size() == 0) { + if(working.size() == 0) { Errors.inst.printError(EK_PARSE_NOCLOSE); return false; } ITree groupNode = null; - switch (tk.type) { + switch(tk.type) { case CBRACE: groupNode = new Tree<>(new Node(GROUP, Node.GroupType.CODE)); break; @@ -134,20 +134,20 @@ public class Parser { } 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 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 ast : working) { + for(ITree ast : working) { System.out.println("Tree " + treeNo++ + ": " + ast.toString()); } @@ -155,14 +155,14 @@ public class Parser { } else { Deque> childs = new LinkedList<>(); - while (!working.peek().equals(matchNode)) { + while(!working.peek().equals(matchNode)) { childs.push(working.pop()); } // Discard opener working.pop(); - for (ITree child : childs) { + for(ITree child : childs) { groupNode.addChild(child); } diff --git a/dice-lang/src/bjc/dicelang/Shunter.java b/dice-lang/src/bjc/dicelang/Shunter.java index 48c5c67..4faabb1 100644 --- a/dice-lang/src/bjc/dicelang/Shunter.java +++ b/dice-lang/src/bjc/dicelang/Shunter.java @@ -5,14 +5,14 @@ import bjc.utils.funcdata.FunctionalMap; import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; -import static bjc.dicelang.Errors.ErrorKey.*; -import static bjc.dicelang.Token.Type.*; - import java.util.Deque; import java.util.HashSet; import java.util.LinkedList; import java.util.Set; +import static bjc.dicelang.Errors.ErrorKey.*; +import static bjc.dicelang.Token.Type.*; + public class Shunter { // The binary operators and their // priorities @@ -40,10 +40,10 @@ public class Shunter { // applied to operator tokens and yield data tokens Set unaryGerunds; - public final int MATH_PREC = 30; - public final int DICE_PREC = 20; - public final int STR_PREC = 10; - public final int EXPR_PREC = 0; + public final int MATH_PREC = 30; + public final int DICE_PREC = 20; + public final int STR_PREC = 10; + public final int EXPR_PREC = 0; public Shunter() { ops = new FunctionalMap<>(); @@ -86,30 +86,26 @@ public class Shunter { Deque 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) { - return false; - } + if(!succ) return false; } succ = shuntToken(tk, opStack, unaryOps, currReturned, feed); - if (!succ) { - return false; - } + 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); } @@ -118,8 +114,8 @@ public class Shunter { private boolean shuntToken(Token tk, Deque opStack, Deque unaryStack, Deque currReturned, Deque feed) { - if (unaryStack.size() != 0) { - if (isUnary(tk)) { + if(unaryStack.size() != 0) { + if(isUnary(tk)) { unaryStack.add(tk); return true; } @@ -128,15 +124,15 @@ public class Shunter { 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); @@ -146,15 +142,15 @@ public class Shunter { 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); @@ -167,14 +163,14 @@ public class Shunter { } } - 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()); } @@ -182,15 +178,16 @@ public class Shunter { } 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) + if(tk.type == OBRACE) { currReturned.addLast(tk); - } else if (tk.type == CPAREN || tk.type == CBRACE) { + } + } else if(tk.type == CPAREN || tk.type == CBRACE) { Token matching = null; - switch (tk.type) { + switch(tk.type) { case CPAREN: matching = new Token(OPAREN, tk.intValue); break; @@ -201,32 +198,32 @@ public class Shunter { 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 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; } @@ -245,49 +242,42 @@ public class Shunter { boolean exists = ops.containsKey(right); - if (rght.type == TAGOPR) + if(rght.type == TAGOPR) { exists = true; + } // If it doesn't, the left is higher precedence. - if (!exists) { - return false; - } + if(!exists) return false; int rightPrecedence; int leftPrecedence; - if (rght.type == TAGOPR) { + if(rght.type == TAGOPR) { rightPrecedence = (int) rght.intValue; } else { rightPrecedence = ops.get(right); } - if (lft.type == TAGOPR) { + if(lft.type == TAGOPR) { leftPrecedence = (int) lft.intValue; } else { leftPrecedence = ops.get(left); } - if (rightAssoc.contains(left)) { + if(rightAssoc.contains(left)) return rightPrecedence > leftPrecedence; - } else { + else return rightPrecedence >= leftPrecedence; - } } 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; } @@ -295,12 +285,9 @@ public class Shunter { 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 e53cba8..71968a7 100644 --- a/dice-lang/src/bjc/dicelang/Token.java +++ b/dice-lang/src/bjc/dicelang/Token.java @@ -72,8 +72,9 @@ public class Token { tokenValues = tkVals; } + @Override public String toString() { - switch (type) { + switch(type) { case INT_LIT: case STRING_LIT: case VREF: @@ -97,16 +98,15 @@ public class Token { } } + @Override public boolean equals(Object other) { - if (!(other instanceof Token)) - return false; + if(!(other instanceof Token)) return false; Token otk = (Token) other; - if (otk.type != type) - return false; + if(otk.type != type) return false; - switch (type) { + switch(type) { case OBRACE: case OBRACKET: return intValue == otk.intValue; @@ -116,7 +116,7 @@ public class Token { } public boolean isGrouper() { - switch (type) { + switch(type) { case OPAREN: case OBRACE: case OBRACKET: diff --git a/dice-lang/src/bjc/dicelang/Tokenizer.java b/dice-lang/src/bjc/dicelang/Tokenizer.java index b73c0a5..7292d2c 100644 --- a/dice-lang/src/bjc/dicelang/Tokenizer.java +++ b/dice-lang/src/bjc/dicelang/Tokenizer.java @@ -1,7 +1,6 @@ package bjc.dicelang; import bjc.dicelang.dice.DiceBox; - import bjc.utils.funcdata.FunctionalMap; import bjc.utils.funcdata.IMap; import bjc.utils.funcutils.StringUtils; @@ -9,7 +8,9 @@ import bjc.utils.funcutils.StringUtils; import java.util.regex.Matcher; import java.util.regex.Pattern; -import static bjc.dicelang.Errors.ErrorKey.*; +import static bjc.dicelang.Errors.ErrorKey.EK_TOK_INVBASE; +import static bjc.dicelang.Errors.ErrorKey.EK_TOK_INVFLEX; +import static bjc.dicelang.Errors.ErrorKey.EK_TOK_UNGROUP; import static bjc.dicelang.Token.Type.*; public class Tokenizer { @@ -44,15 +45,14 @@ public class Tokenizer { } public Token lexToken(String token, IMap 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)) { + switch(token.charAt(0)) { case '(': case ')': case '[': @@ -72,8 +72,8 @@ public class Tokenizer { private Token tokenizeGrouping(String token) { Token tk = Token.NIL_TOKEN; - if (StringUtils.containsOnly(token, "\\" + token.charAt(0))) { - switch (token.charAt(0)) { + if(StringUtils.containsOnly(token, "\\" + token.charAt(0))) { + switch(token.charAt(0)) { case '(': tk = new Token(OPAREN, token.length()); break; @@ -101,23 +101,23 @@ public class Tokenizer { return tk; } - 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 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 Token tokenizeLiteral(String token, IMap 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; } @@ -126,18 +126,18 @@ public class Tokenizer { try { tk = new Token(INT_LIT, Long.parseLong(flexNum, parseBase)); - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { 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 d4bb4b5..adbd102 100644 --- a/dice-lang/src/bjc/dicelang/dice/CompoundDie.java +++ b/dice-lang/src/bjc/dicelang/dice/CompoundDie.java @@ -9,8 +9,8 @@ public class CompoundDie implements Die { /* * The dice that form this die */ - private Die left; - private Die right; + private Die left; + private Die right; /** * Create a new compound die. diff --git a/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java b/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java index 28badf4..a25696a 100644 --- a/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java +++ b/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java @@ -13,8 +13,8 @@ import java.util.function.Predicate; public class CompoundingDie implements Die { private Die source; - private Predicate compoundOn; - private String compoundPattern; + private Predicate compoundOn; + private String compoundPattern; /** * Create a new compounding die with no pattern. @@ -61,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; @@ -78,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; @@ -89,10 +89,9 @@ public class CompoundingDie implements Die { @Override public String toString() { - if (compoundPattern == null) { + if(compoundPattern == null) return source + "!!"; - } else { + 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 85edc77..7a7e7c4 100644 --- a/dice-lang/src/bjc/dicelang/dice/DiceBox.java +++ b/dice-lang/src/bjc/dicelang/dice/DiceBox.java @@ -21,24 +21,23 @@ 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. */ @@ -48,14 +47,14 @@ 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 */ @@ -65,7 +64,7 @@ public class DiceBox { 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 */ @@ -76,7 +75,7 @@ public class DiceBox { 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 */ @@ -87,7 +86,7 @@ public class DiceBox { 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 */ @@ -98,7 +97,7 @@ public class DiceBox { 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 */ @@ -128,16 +127,16 @@ public class DiceBox { * * 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. @@ -145,16 +144,16 @@ 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. @@ -170,8 +169,8 @@ 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 Pattern compoundingDiePattern = Pattern.compile("\\A" + compoundingDie + "\\Z"); + private static final String compoundingDie = compoundGroup + "!!" + comparePoint; + private static final Pattern compoundingDiePattern = Pattern.compile("\\A" + compoundingDie + "\\Z"); /* * Defines an exploding die. @@ -179,8 +178,8 @@ 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 Pattern explodingDiePattern = Pattern.compile("\\A" + explodingDie + "\\Z"); + private static final String explodingDie = compoundGroup + "!" + comparePoint; + private static final Pattern explodingDiePattern = Pattern.compile("\\A" + explodingDie + "\\Z"); /* * Defines a penetrating die. @@ -188,16 +187,16 @@ 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 Pattern penetratingDiePattern = Pattern.compile("\\A" + penetratingDie + "\\Z"); + private static final String penetratingDie = compoundGroup + "!" + comparePoint; + private static final Pattern penetratingDiePattern = Pattern.compile("\\A" + penetratingDie + "\\Z"); /* * Defines a die list. * * 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. @@ -208,25 +207,24 @@ public class DiceBox { * @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()) { + else if(diceListPattern.matcher(exp).matches()) return true; - } else { + else return false; - } } /* @@ -235,7 +233,7 @@ public class DiceBox { private static Predicate deriveCond(String patt) { 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 0ce7d3b..630e8b9 100644 --- a/dice-lang/src/bjc/dicelang/dice/Die.java +++ b/dice-lang/src/bjc/dicelang/dice/Die.java @@ -2,7 +2,7 @@ package bjc.dicelang.dice; /** * Represents one or more dice that produce a scalar result. - * + * * @author Ben Culkin */ public interface Die { diff --git a/dice-lang/src/bjc/dicelang/dice/DieExpression.java b/dice-lang/src/bjc/dicelang/dice/DieExpression.java index 95e7dae..576660d 100644 --- a/dice-lang/src/bjc/dicelang/dice/DieExpression.java +++ b/dice-lang/src/bjc/dicelang/dice/DieExpression.java @@ -4,7 +4,7 @@ import java.util.Arrays; /** * Represents either a die or a die list - * + * * @author Ben Culkin */ public class DieExpression { @@ -16,11 +16,11 @@ 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. */ - public DieList list; + public DieList list; /** * Create a scalar die expression. @@ -46,7 +46,7 @@ public class DieExpression { @Override public String toString() { - if (isList) + if(isList) return list.toString(); else return scalar.toString(); @@ -56,7 +56,7 @@ public class DieExpression { * Get the value of this expression as a string. */ public String value() { - if (isList) + if(isList) return Arrays.toString(list.roll()); else return Long.toString(scalar.roll()); diff --git a/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java b/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java index eeafbd1..928ae25 100644 --- a/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java +++ b/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java @@ -21,9 +21,9 @@ public class ExplodingDice implements DieList { /* * The conditions for exploding. */ - private Predicate explodeOn; - private String explodePattern; - private boolean explodePenetrates; + private Predicate explodeOn; + private String explodePattern; + private boolean explodePenetrates; /** * Create a new exploding die. @@ -89,11 +89,12 @@ public class ExplodingDice implements DieList { List resList = new LinkedList<>(); - while (explodeOn.test(oldRes)) { + while(explodeOn.test(oldRes)) { oldRes = source.rollSingle(); - if (explodePenetrates) + if(explodePenetrates) { oldRes -= 1; + } resList.add(oldRes); } @@ -101,7 +102,7 @@ public class ExplodingDice implements DieList { newRes[0] = res; int i = 1; - for (long rll : resList) { + for(long rll : resList) { newRes[i] = rll; i += 1; } @@ -111,10 +112,9 @@ public class ExplodingDice implements DieList { @Override public String toString() { - if (explodePattern == null) { + if(explodePattern == null) return source + (explodePenetrates ? "p" : "") + "!"; - } else { + 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 8061475..0385239 100644 --- a/dice-lang/src/bjc/dicelang/dice/FudgeDie.java +++ b/dice-lang/src/bjc/dicelang/dice/FudgeDie.java @@ -11,30 +11,35 @@ public class FudgeDie implements Die { numDice = nDice; } + @Override public boolean canOptimize() { return numDice.canOptimize() && numDice.optimize() == 0; } + @Override public long optimize() { return 0; } + @Override 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(); } return res; } + @Override public long rollSingle() { return DiceBox.rng.nextInt(3) - 1; } + @Override public String toString() { return numDice + "dF"; } diff --git a/dice-lang/src/bjc/dicelang/dice/MathDie.java b/dice-lang/src/bjc/dicelang/dice/MathDie.java index 2e82a6e..1d6b2fa 100644 --- a/dice-lang/src/bjc/dicelang/dice/MathDie.java +++ b/dice-lang/src/bjc/dicelang/dice/MathDie.java @@ -4,8 +4,9 @@ public class MathDie implements Die { public static enum MathOp { ADD, SUBTRACT, MULTIPLY; + @Override public String toString() { - switch (this) { + switch(this) { case ADD: return "+"; case SUBTRACT: @@ -20,8 +21,8 @@ public class MathDie implements Die { private MathDie.MathOp type; - private Die left; - private Die right; + private Die left; + private Die right; public MathDie(MathDie.MathOp op, Die lft, Die rght) { type = op; @@ -30,12 +31,13 @@ public class MathDie implements Die { right = rght; } + @Override public boolean canOptimize() { return left.canOptimize() && right.canOptimize(); } private long performOp(long lft, long rght) { - switch (type) { + switch(type) { case ADD: return lft + rght; case SUBTRACT: @@ -47,6 +49,7 @@ public class MathDie implements Die { } } + @Override public long optimize() { long lft = left.optimize(); long rght = right.optimize(); @@ -54,6 +57,7 @@ public class MathDie implements Die { return performOp(lft, rght); } + @Override public long roll() { long lft = left.roll(); long rght = right.roll(); @@ -61,6 +65,7 @@ public class MathDie implements Die { return performOp(lft, rght); } + @Override public long rollSingle() { long lft = left.rollSingle(); long rght = right.rollSingle(); @@ -68,6 +73,7 @@ public class MathDie implements Die { return performOp(lft, rght); } + @Override public String toString() { return left.toString() + " " + type.toString() + " " + right.toString(); } diff --git a/dice-lang/src/bjc/dicelang/dice/ScalarDie.java b/dice-lang/src/bjc/dicelang/dice/ScalarDie.java index ac64d1c..b9c3eba 100644 --- a/dice-lang/src/bjc/dicelang/dice/ScalarDie.java +++ b/dice-lang/src/bjc/dicelang/dice/ScalarDie.java @@ -7,22 +7,27 @@ public class ScalarDie implements Die { val = vl; } + @Override public boolean canOptimize() { return true; } + @Override public long optimize() { return val; } + @Override public long roll() { return val; } + @Override public long rollSingle() { return val; } + @Override public String toString() { return Long.toString(val); } diff --git a/dice-lang/src/bjc/dicelang/dice/SimpleDie.java b/dice-lang/src/bjc/dicelang/dice/SimpleDie.java index fc1aacd..f8dd945 100644 --- a/dice-lang/src/bjc/dicelang/dice/SimpleDie.java +++ b/dice-lang/src/bjc/dicelang/dice/SimpleDie.java @@ -1,8 +1,8 @@ package bjc.dicelang.dice; public class SimpleDie implements Die { - private Die numDice; - private Die diceSize; + private Die numDice; + private Die diceSize; public SimpleDie(long nDice, long size) { numDice = new ScalarDie(nDice); @@ -24,39 +24,44 @@ public class SimpleDie implements Die { diceSize = size; } + @Override public boolean canOptimize() { - if (diceSize.canOptimize() && (diceSize.optimize() <= 1)) { + if(diceSize.canOptimize() && diceSize.optimize() <= 1) return numDice.canOptimize(); - } else + else return false; } + @Override public long optimize() { long optSize = diceSize.optimize(); - if (optSize == 0) + if(optSize == 0) return 0; else return numDice.optimize(); } + @Override public long roll() { long total = 0; long nDice = numDice.roll(); long dSize = diceSize.roll(); - for (int i = 0; i < nDice; i++) { - total += (Math.abs(DiceBox.rng.nextLong()) % dSize) + 1; + for(int i = 0; i < nDice; i++) { + total += Math.abs(DiceBox.rng.nextLong()) % dSize + 1; } return total; } + @Override public long rollSingle() { - return (Math.abs(DiceBox.rng.nextLong()) % diceSize.roll()) + 1; + return Math.abs(DiceBox.rng.nextLong()) % diceSize.roll() + 1; } + @Override public String toString() { return numDice + "d" + diceSize; } diff --git a/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java b/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java index e166949..54f8e7a 100644 --- a/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java +++ b/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java @@ -1,47 +1,50 @@ package bjc.dicelang.dice; public class SimpleDieList implements DieList { - private Die numDice; - private Die size; + private Die numDice; + private Die size; public SimpleDieList(Die nDice, Die sze) { numDice = nDice; size = sze; } + @Override public boolean canOptimize() { - if (size.canOptimize() && size.optimize() <= 1) { + if(size.canOptimize() && size.optimize() <= 1) return numDice.canOptimize(); - } else { + else return false; - } } + @Override public long[] 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; } return ret; } + @Override public long[] 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(); } return ret; } + @Override public String toString() { return numDice.toString() + "dl" + size.toString(); } diff --git a/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java b/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java index 8d63be2..0da5364 100644 --- a/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java +++ b/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java @@ -1,11 +1,10 @@ package bjc.dicelang.scl; import bjc.dicelang.Errors; - -import bjc.utils.esodata.Stack; import bjc.utils.esodata.SimpleStack; -import bjc.utils.funcdata.IList; +import bjc.utils.esodata.Stack; import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.IList; import bjc.utils.funcutils.StringUtils; import java.util.HashMap; @@ -126,28 +125,28 @@ 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 { + else { Errors.inst.printError(EK_SCL_INVTOKEN, token); return null; } } - private static final Map litTokens; - private static final Map builtinWords; + private static final Map litTokens; + private static final Map builtinWords; static { litTokens = new HashMap<>(); @@ -198,29 +197,24 @@ public class StreamControlEngine { * @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) { - return false; - } + 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; @@ -239,44 +233,37 @@ 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())); @@ -285,7 +272,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; } @@ -293,11 +280,10 @@ 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; } @@ -306,8 +292,7 @@ public class StreamControlEngine { 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()); @@ -320,14 +305,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) { + if(curStack.size() < n) { Errors.inst.printError(EK_SCL_SUNDERFLOW, NNIP.toString()); return false; } @@ -339,14 +324,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) { + if(curStack.size() < n) { Errors.inst.printError(EK_SCL_SUNDERFLOW, NDROP.toString()); return false; } @@ -358,15 +343,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; } @@ -380,13 +365,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 arr = new FunctionalList<>(); - for (int i = 0; i < num.intVal; i++) { + for(int i = 0; i < num.intVal; i++) { arr.add(curStack.pop()); } @@ -399,32 +384,29 @@ public class StreamControlEngine { IList toks = new FunctionalList<>(); int n = i + 1; - if (n >= tokens.length) { + 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; @@ -435,7 +417,7 @@ public class StreamControlEngine { * Move to the next token */ n += 1; - if (n >= tokens.length) { + if(n >= tokens.length) { Errors.inst.printError(EK_SCL_MMQUOTE); return -1; } @@ -456,14 +438,14 @@ public class StreamControlEngine { StringBuilder sb = new StringBuilder(); int n = i + 1; - if (n >= tokens.length) { + 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. */ @@ -476,7 +458,7 @@ public class StreamControlEngine { * Move to the next token */ n += 1; - if (n >= tokens.length) { + 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 9bcad9b..f8d6e09 100644 --- a/dice-lang/src/bjc/dicelang/scl/StreamEngine.java +++ b/dice-lang/src/bjc/dicelang/scl/StreamEngine.java @@ -2,16 +2,16 @@ package bjc.dicelang.scl; import bjc.dicelang.DiceLangEngine; import bjc.dicelang.Errors; - +import bjc.utils.esodata.SingleTape; +import bjc.utils.esodata.Tape; +import bjc.utils.esodata.TapeLibrary; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; import bjc.utils.funcutils.ListUtils; -import static bjc.dicelang.Errors.ErrorKey.*; - -import bjc.utils.esodata.SingleTape; -import bjc.utils.esodata.Tape; -import bjc.utils.esodata.TapeLibrary; +import static bjc.dicelang.Errors.ErrorKey.EK_STRM_INVCOM; +import static bjc.dicelang.Errors.ErrorKey.EK_STRM_LAST; +import static bjc.dicelang.Errors.ErrorKey.EK_STRM_NONEX; /** * Implements multiple interleaved parse streams, as well as a command language @@ -31,8 +31,8 @@ public class StreamEngine { /* * Our streams. */ - Tape> streams; - IList currStream; + Tape> streams; + IList currStream; /* * Saved streams @@ -94,23 +94,18 @@ 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)) { - return false; - } - /* - * Command ran correctly, continue - */ + } else if(!processCommand(tk)) return false; } 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); @@ -118,7 +113,7 @@ public class StreamEngine { } } - for (String tk : currStream) { + for(String tk : currStream) { dest.add(tk); } @@ -130,7 +125,7 @@ public class StreamEngine { } public boolean rightStream() { - if (!streams.right()) { + if(!streams.right()) { Errors.inst.printError(EK_STRM_NONEX); return false; } @@ -140,7 +135,7 @@ public class StreamEngine { } public boolean leftStream() { - if (!streams.left()) { + if(!streams.left()) { Errors.inst.printError(EK_STRM_NONEX); return false; } @@ -150,7 +145,7 @@ public class StreamEngine { } public boolean deleteStream() { - if (streams.size() == 1) { + if(streams.size() == 1) { Errors.inst.printError(EK_STRM_LAST); return false; } else { @@ -162,7 +157,7 @@ public class StreamEngine { } public boolean mergeStream() { - if (streams.size() == 1) { + if(streams.size() == 1) { Errors.inst.printError(EK_STRM_LAST); return false; } else { @@ -177,7 +172,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]; @@ -186,35 +181,30 @@ 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/util/ResourceLoader.java b/dice-lang/src/bjc/dicelang/util/ResourceLoader.java index 1cb29b0..65dc1e4 100644 --- a/dice-lang/src/bjc/dicelang/util/ResourceLoader.java +++ b/dice-lang/src/bjc/dicelang/util/ResourceLoader.java @@ -1,40 +1,42 @@ package bjc.dicelang.util; +import bjc.dicelang.Errors; + import java.io.IOException; import java.net.URISyntaxException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; -import bjc.dicelang.Errors; - -import static bjc.dicelang.Errors.ErrorKey.*; +import static bjc.dicelang.Errors.ErrorKey.EK_MISC_IOEX; /** * Load resources bundled with DiceLang - * + * * @author EVE * */ public class ResourceLoader { /** * Loads a .help file from the data/help directory. - * - * @param name The name of the help file to load. - * - * @return The contents of the help file, or null if it could not be opened + * + * @param name + * The name of the help file to load. + * + * @return The contents of the help file, or null if it could not be + * opened */ public String[] loadHelpFile(String name) { URL fle = this.getClass().getResource("/data/help/" + name + ".help"); - + try { return Files.lines(Paths.get(fle.toURI())).toArray(sze -> new String[sze]); - } catch (IOException ioex) { + } catch(IOException ioex) { + Errors.inst.printError(EK_MISC_IOEX, fle.toString()); + } catch(URISyntaxException usex) { Errors.inst.printError(EK_MISC_IOEX, fle.toString()); - } catch (URISyntaxException usex) { - Errors.inst.printError(EK_MISC_IOEX, fle.toString()); } - + return null; } } diff --git a/dice-lang/src/bjc/dicelang/v1/BindingDiceExpression.java b/dice-lang/src/bjc/dicelang/v1/BindingDiceExpression.java index cce31a2..14dbc42 100644 --- a/dice-lang/src/bjc/dicelang/v1/BindingDiceExpression.java +++ b/dice-lang/src/bjc/dicelang/v1/BindingDiceExpression.java @@ -5,7 +5,7 @@ import java.util.Map; /** * A variable expression that represents binding a variable to a name in an * enviroment - * + * * @author ben * */ @@ -23,7 +23,7 @@ public class BindingDiceExpression implements IDiceExpression { /** * 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 @@ -34,12 +34,10 @@ public class BindingDiceExpression implements IDiceExpression { */ public BindingDiceExpression(IDiceExpression left, IDiceExpression right, Map 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); - } + 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); String varName = ((ReferenceDiceExpression) left).getName(); @@ -48,7 +46,7 @@ public class BindingDiceExpression implements IDiceExpression { /** * Create a new dice expression binder - * + * * @param name * The name of the variable to bind * @param expression @@ -69,7 +67,7 @@ public class BindingDiceExpression implements IDiceExpression { /* * (non-Javadoc) - * + * * @see bjc.utils.dice.IDiceExpression#roll() */ @Override @@ -79,7 +77,7 @@ public class BindingDiceExpression implements IDiceExpression { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override diff --git a/dice-lang/src/bjc/dicelang/v1/ComplexDice.java b/dice-lang/src/bjc/dicelang/v1/ComplexDice.java index b9796f9..76a34ba 100644 --- a/dice-lang/src/bjc/dicelang/v1/ComplexDice.java +++ b/dice-lang/src/bjc/dicelang/v1/ComplexDice.java @@ -3,14 +3,14 @@ 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. - * + * * @author ben * */ public class ComplexDice implements IDiceExpression { /** * Create a dice from a string expression - * + * * @param expression * The string to parse the dice from * @return A dice group parsed from the string @@ -18,9 +18,7 @@ public class ComplexDice implements IDiceExpression { public static IDiceExpression fromString(String expression) { // Handle the case where someone passes us a simple expression // containing a single die - if (!expression.contains("d")) { - return new Die(Integer.parseInt(expression)); - } + if(!expression.contains("d")) return new Die(Integer.parseInt(expression)); // Split it on the dice type marker @@ -30,7 +28,7 @@ public class ComplexDice implements IDiceExpression { // Create the actual group of dice return new ComplexDice(new ScalarDie(Integer.parseInt(strangs[0])), new Die(Integer.parseInt(strangs[1]))); - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { // We don't care about details // Tell the user the expression is invalid @@ -52,7 +50,7 @@ public class ComplexDice implements IDiceExpression { /** * Create a new collection of dice - * + * * @param nDce * The number of dice in the collection * @param de @@ -65,7 +63,7 @@ public class ComplexDice implements IDiceExpression { /** * Create a new collection of dice - * + * * @param nSides * The number of dice in the collection * @param de @@ -80,20 +78,15 @@ public class ComplexDice implements IDiceExpression { public boolean canOptimize() { // Can only optimize this dice group if both components can be // optimized and the die itself has only one value - if (nDice.canOptimize() && die.canOptimize()) { - return die.optimize() == 1; - } + if(nDice.canOptimize() && die.canOptimize()) return die.optimize() == 1; return false; } @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."); - } + 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."); return nDice.optimize(); } @@ -107,13 +100,11 @@ 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); - } + if(nRoll < 0) throw new UnsupportedOperationException("Attempted to roll a negative number of dice. " + + "The problematic expression is " + nDice); // Roll all the dice and combine them - for (int i = 0; i < nRoll; i++) { + for(int i = 0; i < nRoll; i++) { res += die.roll(); } @@ -123,9 +114,7 @@ public class ComplexDice implements IDiceExpression { @Override public String toString() { // Print simple dice groups in a much clearer manner - if (nDice instanceof ScalarDie && die instanceof Die) { - return nDice.toString() + die.toString(); - } + if(nDice instanceof ScalarDie && die instanceof Die) return nDice.toString() + 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 a70ae39..43d64e8 100644 --- a/dice-lang/src/bjc/dicelang/v1/CompoundDice.java +++ b/dice-lang/src/bjc/dicelang/v1/CompoundDice.java @@ -2,10 +2,10 @@ 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. - * + * * @author ben * */ @@ -22,7 +22,7 @@ public class CompoundDice implements IDiceExpression { /** * Create a new compound dice using the specified dice - * + * * @param lft * The die to use on the left * @param rght @@ -35,7 +35,7 @@ public class CompoundDice implements IDiceExpression { /** * Create a new compound dice from two dice strings - * + * * @param lft * The left side dice as a string * @param rght @@ -47,7 +47,7 @@ public class CompoundDice implements IDiceExpression { /** * Create a new compound dice from an array of dice strings - * + * * @param exps * An array of two dice strings */ @@ -62,10 +62,8 @@ 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"); - } + if(!canOptimize()) 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()); } diff --git a/dice-lang/src/bjc/dicelang/v1/DiceExpressionBuilder.java b/dice-lang/src/bjc/dicelang/v1/DiceExpressionBuilder.java index e0c62c1..3b20d03 100644 --- a/dice-lang/src/bjc/dicelang/v1/DiceExpressionBuilder.java +++ b/dice-lang/src/bjc/dicelang/v1/DiceExpressionBuilder.java @@ -7,7 +7,7 @@ import static bjc.dicelang.v1.DiceExpressionType.SUBTRACT; /** * Build a dice expression piece by piece - * + * * @author ben * */ @@ -19,7 +19,7 @@ public class DiceExpressionBuilder { /** * Build a dice expression from a seed dice expression - * + * * @param seed * The dice expression to use as a seed */ @@ -29,7 +29,7 @@ public class DiceExpressionBuilder { /** * Build a dice expression from a seed dice - * + * * @param nSides * The number of sides in the dice * @param nDice @@ -41,7 +41,7 @@ public class DiceExpressionBuilder { /** * Add a term to this dice expression - * + * * @param exp * The expression to use on the left * @return A new expression adding the two dice @@ -53,7 +53,7 @@ public class DiceExpressionBuilder { /** * Add a scalar to this dice - * + * * @param num * The scalar to add to the dice * @return A dice expression adding a scalar to this @@ -65,7 +65,7 @@ public class DiceExpressionBuilder { /** * Bake the expression being built to completion - * + * * @return A usable dice expression */ public IDiceExpression bake() { @@ -74,7 +74,7 @@ public class DiceExpressionBuilder { /** * Divide a term from dice expression - * + * * @param exp * The expression to use on the left * @return A new expression dividing the two dice @@ -86,7 +86,7 @@ public class DiceExpressionBuilder { /** * Divide a scalar from this dice - * + * * @param num * The scalar to add to the dice * @return A dice expression dividing a scalar from this @@ -98,7 +98,7 @@ public class DiceExpressionBuilder { /** * Multiply a term by this dice expression - * + * * @param exp * The expression to use on the left * @return A new expression multiplying the two dice @@ -110,7 +110,7 @@ public class DiceExpressionBuilder { /** * Multiply a scalar by this dice - * + * * @param num * The scalar to multiply to the dice * @return A dice expression multiplying a scalar to this @@ -122,7 +122,7 @@ public class DiceExpressionBuilder { /** * Add a term to this dice expression - * + * * @param exp * The expression to use on the left * @return A new expression adding the two dice @@ -134,7 +134,7 @@ public class DiceExpressionBuilder { /** * Add a scalar to this dice - * + * * @param num * The scalar to add to the dice * @return A dice expression adding a scalar to this diff --git a/dice-lang/src/bjc/dicelang/v1/DiceExpressionParser.java b/dice-lang/src/bjc/dicelang/v1/DiceExpressionParser.java index 38a842e..ff2e800 100644 --- a/dice-lang/src/bjc/dicelang/v1/DiceExpressionParser.java +++ b/dice-lang/src/bjc/dicelang/v1/DiceExpressionParser.java @@ -1,24 +1,24 @@ package bjc.dicelang.v1; -import java.util.Map; -import java.util.Stack; - import bjc.utils.funcdata.FunctionalStringTokenizer; import bjc.utils.funcdata.IList; import bjc.utils.parserutils.ShuntingYard; +import java.util.Map; +import java.util.Stack; + import org.apache.commons.lang3.StringUtils; /** * Parse a dice expression from a string - * + * * @author ben * */ public class DiceExpressionParser { /** * Parse a dice expression from a string - * + * * @param expression * The string to parse an expression from * @param enviroment @@ -65,12 +65,12 @@ public class DiceExpressionParser { /* * Handle compound dice */ - if (StringUtils.countMatches(expressionPart, 'c') == 1 + if(StringUtils.countMatches(expressionPart, 'c') == 1 && !expressionPart.equalsIgnoreCase("c")) { String[] strangs = expressionPart.split("c"); expressions.push(new CompoundDice(strangs)); - } else if (StringUtils.countMatches(expressionPart, 'd') == 1 + } else if(StringUtils.countMatches(expressionPart, 'd') == 1 && !expressionPart.equalsIgnoreCase("d")) { /* * Handle dice groups @@ -82,10 +82,10 @@ public class DiceExpressionParser { * Handle scalar numbers */ expressions.push(new ScalarDie(Integer.parseInt(expressionPart))); - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { // We don't care about details, just // that it failed - if (expressions.size() >= 2) { + if(expressions.size() >= 2) { /* * Apply an operation to two * dice @@ -93,7 +93,7 @@ public class DiceExpressionParser { IDiceExpression right = expressions.pop(); IDiceExpression left = expressions.pop(); - switch (expressionPart) { + switch(expressionPart) { case ":=": expressions.push(new BindingDiceExpression(left, right, enviroment)); @@ -124,7 +124,7 @@ public class DiceExpressionParser { /* * Parse it as a * variable reference - * + * * Make sure to restore * popped variables */ @@ -146,7 +146,7 @@ public class DiceExpressionParser { } }); - if (expressions.size() != 1) { + if(expressions.size() != 1) { System.err.println( "WARNING: Leftovers found on dice expression stack. Remember, := is assignment."); } diff --git a/dice-lang/src/bjc/dicelang/v1/DiceExpressionType.java b/dice-lang/src/bjc/dicelang/v1/DiceExpressionType.java index 8ffe78d..7c0510f 100644 --- a/dice-lang/src/bjc/dicelang/v1/DiceExpressionType.java +++ b/dice-lang/src/bjc/dicelang/v1/DiceExpressionType.java @@ -26,7 +26,7 @@ public enum DiceExpressionType { @Override public String toString() { - switch (this) { + switch(this) { case ADD: return "+"; case DIVIDE: diff --git a/dice-lang/src/bjc/dicelang/v1/Die.java b/dice-lang/src/bjc/dicelang/v1/Die.java index ffb6093..667e18c 100644 --- a/dice-lang/src/bjc/dicelang/v1/Die.java +++ b/dice-lang/src/bjc/dicelang/v1/Die.java @@ -4,7 +4,7 @@ import java.util.Random; /** * A single polyhedral dice - * + * * @author ben * */ @@ -21,14 +21,12 @@ public class Die implements IDiceExpression { /** * Create a die with the specified number of sides - * + * * @param nSides * 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"); - } + if(nSides < 1) throw new UnsupportedOperationException("Dice with less than 1 side are not supported"); this.nSides = nSides; } @@ -40,9 +38,7 @@ public class Die implements IDiceExpression { @Override public int optimize() { - if (nSides != 1) { - throw new UnsupportedOperationException("Can't optimize " + nSides + "-sided dice"); - } + if(nSides != 1) 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 86c4d6a..5bf062b 100644 --- a/dice-lang/src/bjc/dicelang/v1/IDiceExpression.java +++ b/dice-lang/src/bjc/dicelang/v1/IDiceExpression.java @@ -4,7 +4,7 @@ import bjc.utils.funcutils.StringUtils; /** * An expression for something that can be rolled like a polyhedral die - * + * * @author ben * */ @@ -12,7 +12,7 @@ import bjc.utils.funcutils.StringUtils; public interface IDiceExpression { /** * Parse a string into an expression. - * + * * It can accept the following types of expressions *
    *
  • Simple integers - '2'
  • @@ -21,13 +21,13 @@ public interface IDiceExpression { *
  • Number concatenation - '2c6'
  • *
  • Dice concatenation - '1d10c1d10
  • *
- * + * * 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 - * + * * @return The string, converted into expression form */ static IDiceExpression toExpression(String expression) { @@ -35,22 +35,22 @@ public interface IDiceExpression { String diceMatcher = "\\Ad\\d+\\Z"; - if (StringUtils.containsInfixOperator(literalData, "c")) { + if(StringUtils.containsInfixOperator(literalData, "c")) { // Parse a compound die String[] strangs = literalData.split("c"); return new CompoundDice(strangs); - } else if (StringUtils.containsInfixOperator(literalData, "d")) { + } else if(StringUtils.containsInfixOperator(literalData, "d")) // Handle groups of similiar dice return ComplexDice.fromString(literalData); - } else if (literalData.matches(diceMatcher)) { + else if(literalData.matches(diceMatcher)) // Handle people who put 'd6' instead of '1d6' return new Die(Integer.parseInt(literalData.substring(1))); - } else { + else { // Parse a scalar number try { return new ScalarDie(Integer.parseInt(literalData)); - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { UnsupportedOperationException usex = new UnsupportedOperationException( "Found malformed leaf token " + expression + ". Floating point numbers " + "are not supported."); @@ -64,7 +64,7 @@ public interface IDiceExpression { /** * Check if this expression can be optimized to a scalar value - * + * * @return Whether or not this expression can be optimized to a scalar * value */ @@ -74,9 +74,9 @@ public interface IDiceExpression { /** * Optimize this expression to a scalar value - * + * * @return This expression, optimized to a scalar value - * + * * @throws UnsupportedOperationException * if this type of expression can't be optimized */ @@ -86,7 +86,7 @@ public interface IDiceExpression { /** * Roll the dice once - * + * * @return The result of rowing the dice */ public int roll(); diff --git a/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java b/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java index bf9254e..a5d37e2 100644 --- a/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java +++ b/dice-lang/src/bjc/dicelang/v1/OperatorDiceExpression.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1; /** * Implements a class for combining two dice with an operator - * + * * @author ben * */ @@ -24,7 +24,7 @@ public class OperatorDiceExpression implements IDiceExpression { /** * Create a new compound expression using the specified parameters - * + * * @param rght * The die on the right side of the expression * @param lft @@ -43,7 +43,7 @@ public class OperatorDiceExpression implements IDiceExpression { /* * Handle each operator */ - switch (type) { + switch(type) { case ADD: return right.roll() + left.roll(); case SUBTRACT: @@ -58,7 +58,7 @@ public class OperatorDiceExpression implements IDiceExpression { */ try { return right.roll() / left.roll(); - } catch (ArithmeticException aex) { + } catch(ArithmeticException aex) { UnsupportedOperationException usex = new UnsupportedOperationException( "Attempted to divide by zero." + " Problematic expression is " + left); diff --git a/dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java b/dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java index e20a12a..402de18 100644 --- a/dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java +++ b/dice-lang/src/bjc/dicelang/v1/PolyhedralDice.java @@ -2,14 +2,14 @@ package bjc.dicelang.v1; /** * Utility class that produces common polyhedral dice - * + * * @author ben * */ public class PolyhedralDice { /** * Produce a single d10 - * + * * @return A single d10 */ public static IDiceExpression d10() { @@ -18,7 +18,7 @@ public class PolyhedralDice { /** * Produce the specified number of 10-sided dice - * + * * @param nDice * The number of ten-sided dice to produce * @return A group of ten-sided dice of the specified size @@ -29,7 +29,7 @@ public class PolyhedralDice { /** * Produce a single d100 - * + * * @return A single d100 */ public static IDiceExpression d100() { @@ -38,7 +38,7 @@ public class PolyhedralDice { /** * Produce the specified number of 100-sided dice - * + * * @param nDice * The number of hundred-sided dice to produce * @return A group of hundred-sided dice of the specified size @@ -49,7 +49,7 @@ public class PolyhedralDice { /** * Produce a single d12 - * + * * @return A single d12 */ public static IDiceExpression d12() { @@ -58,7 +58,7 @@ public class PolyhedralDice { /** * Produce the specified number of 12-sided dice - * + * * @param nDice * The number of twelve-sided dice to produce * @return A group of twelve-sided dice of the specified size @@ -69,7 +69,7 @@ public class PolyhedralDice { /** * Produce a single d20 - * + * * @return A single d20 */ public static IDiceExpression d20() { @@ -78,7 +78,7 @@ public class PolyhedralDice { /** * Produce the specified number of 20-sided dice - * + * * @param nDice * The number of twenty-sided dice to produce * @return A group of twenty-sided dice of the specified size @@ -89,7 +89,7 @@ public class PolyhedralDice { /** * Produce a single d4 - * + * * @return A single d4 */ public static IDiceExpression d4() { @@ -98,7 +98,7 @@ public class PolyhedralDice { /** * Produce the specified number of 4-sided dice - * + * * @param nDice * The number of four-sided dice to produce * @return A group of four-sided dice of the specified size @@ -109,7 +109,7 @@ public class PolyhedralDice { /** * Produce a single d6 - * + * * @return A single d6 */ public static IDiceExpression d6() { @@ -118,7 +118,7 @@ public class PolyhedralDice { /** * Produce the specified number of 6-sided dice - * + * * @param nDice * The number of six-sided dice to produce * @return A group of six-sided dice of the specified size @@ -129,7 +129,7 @@ public class PolyhedralDice { /** * Produce a single d8 - * + * * @return A single d8 */ public static IDiceExpression d8() { @@ -138,7 +138,7 @@ public class PolyhedralDice { /** * Produce the specified number of 8-sided dice - * + * * @param nDice * The number of eight-sided dice to produce * @return A group of eight-sided dice of the specified size diff --git a/dice-lang/src/bjc/dicelang/v1/ReferenceDiceExpression.java b/dice-lang/src/bjc/dicelang/v1/ReferenceDiceExpression.java index b3b979a..11f466e 100644 --- a/dice-lang/src/bjc/dicelang/v1/ReferenceDiceExpression.java +++ b/dice-lang/src/bjc/dicelang/v1/ReferenceDiceExpression.java @@ -4,7 +4,7 @@ import java.util.Map; /** * A dice expression that refers to a variable bound in a mutable enviroment - * + * * @author ben * */ @@ -22,7 +22,7 @@ public class ReferenceDiceExpression implements IDiceExpression { /** * Create a new reference dice expression referring to the given name in * an enviroment - * + * * @param nme * The name of the bound variable * @param env @@ -35,7 +35,7 @@ public class ReferenceDiceExpression implements IDiceExpression { /** * Get the name of the referenced variable - * + * * @return the name of the referenced variable */ public String getName() { @@ -44,18 +44,15 @@ public class ReferenceDiceExpression implements IDiceExpression { @Override public int roll() { - if (!enviroment.containsKey(name)) { + if(!enviroment.containsKey(name)) throw new UnsupportedOperationException("Attempted to reference undefined variable " + name); - } return enviroment.get(name).roll(); } @Override public String toString() { - if (enviroment.containsKey(name)) { - return enviroment.get(name).toString() + "(bound to " + name + ")"; - } + if(enviroment.containsKey(name)) return enviroment.get(name).toString() + "(bound to " + name + ")"; return name + "(unbound)"; } diff --git a/dice-lang/src/bjc/dicelang/v1/ScalarDie.java b/dice-lang/src/bjc/dicelang/v1/ScalarDie.java index c0bb3a9..62ca151 100644 --- a/dice-lang/src/bjc/dicelang/v1/ScalarDie.java +++ b/dice-lang/src/bjc/dicelang/v1/ScalarDie.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1; /** * A die that represents a static number - * + * * @author ben * */ @@ -14,7 +14,7 @@ public class ScalarDie implements IDiceExpression { /** * Create a dice with the specified number - * + * * @param num * The number used for the dice */ diff --git a/dice-lang/src/bjc/dicelang/v1/ast/ArithmeticCollapser.java b/dice-lang/src/bjc/dicelang/v1/ast/ArithmeticCollapser.java index 1a41ce6..28f29f0 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/ArithmeticCollapser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/ArithmeticCollapser.java @@ -1,18 +1,18 @@ package bjc.dicelang.v1.ast; -import java.util.function.BinaryOperator; - import bjc.dicelang.v1.ast.nodes.IDiceASTNode; import bjc.dicelang.v1.ast.nodes.OperatorDiceNode; import bjc.utils.data.IPair; import bjc.utils.data.ITree; import bjc.utils.data.Pair; -import bjc.utils.funcdata.IList; import bjc.utils.data.Tree; +import bjc.utils.funcdata.IList; + +import java.util.function.BinaryOperator; /** * Responsible for collapsing arithmetic operators - * + * * @author ben * */ @@ -54,17 +54,15 @@ final class ArithmeticCollapser implements IOperatorCollapser { IList currentList = ((ArrayResult) currentValue).getValue(); IList accumulatedList = ((ArrayResult) accumulatedValue).getValue(); - if (currentList.getSize() != accumulatedList.getSize()) { + if(currentList.getSize() != accumulatedList.getSize()) throw new UnsupportedOperationException("Can only apply operations to equal-length arrays"); - } IList resultList = currentList.combineWith(accumulatedList, (currentNode, accumulatedNode) -> { boolean currentNotInt = currentNode.getType() != ResultType.INTEGER; boolean accumulatedNotInt = accumulatedNode.getType() != ResultType.INTEGER; - if (currentNotInt || accumulatedNotInt) { + if(currentNotInt || accumulatedNotInt) throw new UnsupportedOperationException("Nesting of array operations isn't allowed"); - } int accumulatedInt = ((IntegerResult) accumulatedNode).getValue(); int currentInt = ((IntegerResult) currentNode).getValue(); @@ -77,7 +75,7 @@ final class ArithmeticCollapser implements IOperatorCollapser { private IPair> doArithmeticCollapse(IResult accumulatedValue, ITree accumulatedTree, IResult currentValue) { - if (accumulatedValue.getType() == ResultType.DUMMY || currentValue.getType() == ResultType.DUMMY) { + 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() + ")."); @@ -88,8 +86,8 @@ final class ArithmeticCollapser implements IOperatorCollapser { boolean currentIsInt = currentValue.getType() == ResultType.INTEGER; boolean accumulatedIsInt = accumulatedValue.getType() == ResultType.INTEGER; - if (!currentIsInt) { - if (!accumulatedIsInt) { + if(!currentIsInt) { + if(!accumulatedIsInt) { IList resultList = combineArrayResults(accumulatedValue, currentValue); return new Pair<>(new ArrayResult(resultList), accumulatedTree); @@ -99,7 +97,7 @@ final class ArithmeticCollapser implements IOperatorCollapser { accumulatedValue, true); return new Pair<>(new ArrayResult(resultList), accumulatedTree); - } else if (!accumulatedIsInt) { + } else if(!accumulatedIsInt) { IList resultList = halfCombineLists(((ArrayResult) accumulatedValue).getValue(), currentValue, false); @@ -115,22 +113,20 @@ final class ArithmeticCollapser implements IOperatorCollapser { } private IList halfCombineLists(IList list, IResult scalar, boolean scalarLeft) { - if (scalar.getType() != ResultType.INTEGER) { + if(scalar.getType() != ResultType.INTEGER) throw new UnsupportedOperationException("Nested array operations not supported"); - } int scalarInt = ((IntegerResult) scalar).getValue(); return list.map((element) -> { - if (element.getType() != ResultType.INTEGER) { + if(element.getType() != ResultType.INTEGER) throw new UnsupportedOperationException("Nested array operations not supported"); - } int elementInt = ((IntegerResult) element).getValue(); IResult combinedValue; - if (scalarLeft) { + if(scalarLeft) { combinedValue = new IntegerResult(valueOp.apply(scalarInt, elementInt)); } else { combinedValue = new IntegerResult(valueOp.apply(elementInt, scalarInt)); diff --git a/dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java b/dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java index c8a35a6..1053360 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/ArrayResult.java @@ -4,7 +4,7 @@ import bjc.utils.funcdata.IList; /** * Represents a result that is an array of other results - * + * * @author ben * * TODO finish implementing me @@ -14,7 +14,7 @@ public class ArrayResult implements IResult { /** * Create a new array-valued result - * + * * @param results * The results in the array */ @@ -29,7 +29,7 @@ public class ArrayResult implements IResult { /** * Get the value of this result - * + * * @return The value of this result */ public IList getValue() { diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTEvaluator.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTEvaluator.java index af31ad7..8273525 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTEvaluator.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTEvaluator.java @@ -1,7 +1,5 @@ package bjc.dicelang.v1.ast; -import java.util.function.Supplier; - import bjc.dicelang.v1.ComplexDice; import bjc.dicelang.v1.ast.nodes.DiceASTType; import bjc.dicelang.v1.ast.nodes.DiceLiteralNode; @@ -17,15 +15,17 @@ import bjc.utils.data.ITree; import bjc.utils.data.Identity; import bjc.utils.data.LazyPair; import bjc.utils.data.Pair; +import bjc.utils.data.Tree; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.FunctionalMap; import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; -import bjc.utils.data.Tree; + +import java.util.function.Supplier; /** * Evaluate a dice AST to an integer value - * + * * @author ben * */ @@ -33,7 +33,7 @@ public class DiceASTEvaluator { private static IResult bindLiteralValue(IDiceASTNode leafNode, IMap> enviroment) { String variableName = ((VariableDiceNode) leafNode).getVariable(); - if (enviroment.containsKey(variableName)) { + if(enviroment.containsKey(variableName)) { IResult result = evaluateAST(enviroment.get(variableName), enviroment); return result; @@ -45,7 +45,7 @@ public class DiceASTEvaluator { /** * Build the map of operations to use when collapsing the AST - * + * * @param enviroment * The enviroment to evaluate bindings and such against * @return The operations to use when collapsing the AST @@ -114,11 +114,9 @@ public class DiceASTEvaluator { private static void doArrayAssign(IMap> enviroment, IPair> nameNode, ITree nameTree, ITree valueTree, IHolder childCount, ITree child) { - if (nameTree.getHead().getType() != DiceASTType.VARIABLE) { - throw new UnsupportedOperationException( - "Assigning to complex variables isn't supported. Problem node is " - + nameNode.getRight()); - } + if(nameTree.getHead().getType() != DiceASTType.VARIABLE) throw new UnsupportedOperationException( + "Assigning to complex variables isn't supported. Problem node is " + + nameNode.getRight()); String varName = child.transformHead((nameNod) -> { return ((VariableDiceNode) nameNod).getVariable(); @@ -131,7 +129,7 @@ public class DiceASTEvaluator { /** * Evaluate the provided AST to a numeric value - * + * * @param expression * The expression to evaluate * @param enviroment @@ -150,7 +148,7 @@ public class DiceASTEvaluator { IMap> enviroment) { ITree returnedAST = new Tree<>(leafNode); - switch (leafNode.getType()) { + switch(leafNode.getType()) { case LITERAL: return new Pair<>(evaluateLiteral(leafNode), returnedAST); @@ -168,7 +166,7 @@ public class DiceASTEvaluator { private static IResult evaluateLiteral(IDiceASTNode leafNode) { DiceLiteralType literalType = ((ILiteralDiceNode) leafNode).getLiteralType(); - switch (literalType) { + switch(literalType) { case DICE: int diceRoll = ((DiceLiteralNode) leafNode).getValue().roll(); @@ -185,17 +183,15 @@ public class DiceASTEvaluator { private static IPair> parseBinding(IMap> enviroment, IList>> nodes) { - if (nodes.getSize() != 2) { - throw new UnsupportedOperationException( - "Can only bind nodes with two children. Problem children are " + nodes); - } + if(nodes.getSize() != 2) throw new UnsupportedOperationException( + "Can only bind nodes with two children. Problem children are " + nodes); IPair> nameNode = nodes.getByIndex(0); IPair> valueNode = nodes.getByIndex(1); return nameNode.bindRight((nameTree) -> { return valueNode.bind((valueValue, valueTree) -> { - if (DiceASTUtils.containsSimpleVariable(nameTree)) { + if(DiceASTUtils.containsSimpleVariable(nameTree)) { String varName = nameTree.transformHead((nameNod) -> { return ((VariableDiceNode) nameNod).getVariable(); }); @@ -203,12 +199,11 @@ public class DiceASTEvaluator { enviroment.put(varName, valueTree); return new Pair<>(valueValue, nameTree); - } else if (nameTree.getHead() == OperatorDiceNode.ARRAY) { - if (valueTree.getHead() == OperatorDiceNode.ARRAY) { - if (nameTree.getChildrenCount() != valueTree.getChildrenCount()) { + } else if(nameTree.getHead() == OperatorDiceNode.ARRAY) { + if(valueTree.getHead() == OperatorDiceNode.ARRAY) { + if(nameTree.getChildrenCount() != valueTree.getChildrenCount()) throw new UnsupportedOperationException( "Array assignment must be between two equal length arrays"); - } IHolder childCount = new Identity<>(0); @@ -242,9 +237,7 @@ public class DiceASTEvaluator { private static IPair> parseGroup( IList>> nodes) { - if (nodes.getSize() != 2) { - throw new UnsupportedOperationException("Can only form a group from two dice"); - } + if(nodes.getSize() != 2) throw new UnsupportedOperationException("Can only form a group from two dice"); IPair> numberDiceNode = nodes.getByIndex(0); IPair> diceTypeNode = nodes.getByIndex(1); @@ -262,9 +255,8 @@ public class DiceASTEvaluator { private static IPair> parseLet(IMap> enviroment, IList>> nodes) { - if (nodes.getSize() != 2) { + if(nodes.getSize() != 2) throw new UnsupportedOperationException("Can only use let with two expressions."); - } ITree bindTree = nodes.getByIndex(0).getRight(); ITree expressionTree = nodes.getByIndex(1).getRight(); diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTInliner.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTInliner.java index 38e1361..74e59c6 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTInliner.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTInliner.java @@ -4,21 +4,21 @@ import bjc.dicelang.v1.ast.nodes.DiceASTType; import bjc.dicelang.v1.ast.nodes.IDiceASTNode; import bjc.dicelang.v1.ast.nodes.VariableDiceNode; import bjc.utils.data.ITree; +import bjc.utils.data.Tree; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; -import bjc.utils.data.Tree; /** * Inline variables in a dice AST - * + * * @author ben * */ public class DiceASTInliner { /** * Inline all the variables in the AST - * + * * @param ast * The AST to inline variables into * @param enviroment @@ -35,22 +35,18 @@ public class DiceASTInliner { private static ITree inlineNode(IDiceASTNode node, IMap> enviroment, boolean specificInline, IList variableNames) { // Only variables get inlined - if (node.getType() != DiceASTType.VARIABLE) { - return new Tree<>(node); - } + if(node.getType() != DiceASTType.VARIABLE) return new Tree<>(node); // Get the name of what we're inlining String variableName = ((VariableDiceNode) node).getVariable(); // If we're inlining only certain variables, do so - if (specificInline) { + if(specificInline) { // Only inline the variable if we're supposed to - if (variableNames.contains(variableName)) { + if(variableNames.contains(variableName)) { // You can't inline non-existent variables - if (!enviroment.containsKey(variableName)) { - throw new UnsupportedOperationException( - "Attempted to inline non-existant variable " + variableName); - } + if(!enviroment.containsKey(variableName)) throw new UnsupportedOperationException( + "Attempted to inline non-existant variable " + variableName); // Return the tree for the variable return enviroment.get(variableName); @@ -61,10 +57,8 @@ public class DiceASTInliner { } // You can't inline non-existent variables - if (!enviroment.containsKey(variableName)) { - throw new UnsupportedOperationException( - "Attempted to inline non-existant variable " + variableName); - } + if(!enviroment.containsKey(variableName)) throw new UnsupportedOperationException( + "Attempted to inline non-existant variable " + variableName); // Return the tree for the variable return enviroment.get(variableName); @@ -72,7 +66,7 @@ public class DiceASTInliner { /** * Inline the specified variables in the AST - * + * * @param ast * The AST to inline variables into * @param enviroment @@ -89,7 +83,7 @@ public class DiceASTInliner { /** * Inline the specified variables in the AST - * + * * @param ast * The AST to inline variables into * @param enviroment @@ -101,7 +95,7 @@ public class DiceASTInliner { public static ITree selectiveInline(ITree ast, IMap> enviroment, String... variables) { // If we're selectively inlining, do so - if (variables != null && variables.length > 0) { + if(variables != null && variables.length > 0) { IList variableNames = new FunctionalList<>(variables); // Selectively inline each tree node diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java index a93de33..fa4f0ca 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTOptimizer.java @@ -9,7 +9,7 @@ import bjc.utils.funcdata.IMap; /** * Contains optimizations appliable to a dice AST - * + * * @author ben * */ @@ -25,7 +25,7 @@ public class DiceASTOptimizer { /** * Add a pass to the list of optimization passes - * + * * @param pass * The pass to add */ @@ -35,7 +35,7 @@ public class DiceASTOptimizer { /** * Optimize the passed in tree - * + * * @param ast * The tree to optimize * @param enviroment diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTParser.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTParser.java index 87f3640..4a2822c 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTParser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTParser.java @@ -1,10 +1,5 @@ package bjc.dicelang.v1.ast; -import java.util.Deque; -import java.util.InputMismatchException; -import java.util.function.Function; -import java.util.function.Predicate; - import bjc.dicelang.v1.IDiceExpression; import bjc.dicelang.v1.ast.nodes.DiceLiteralNode; import bjc.dicelang.v1.ast.nodes.DiceLiteralType; @@ -14,17 +9,22 @@ import bjc.dicelang.v1.ast.nodes.IntegerLiteralNode; import bjc.dicelang.v1.ast.nodes.OperatorDiceNode; import bjc.dicelang.v1.ast.nodes.VariableDiceNode; import bjc.utils.data.ITree; +import bjc.utils.data.Tree; import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.FunctionalMap; import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; -import bjc.utils.data.Tree; import bjc.utils.funcutils.StringUtils; import bjc.utils.parserutils.TreeConstructor; +import java.util.Deque; +import java.util.InputMismatchException; +import java.util.function.Function; +import java.util.function.Predicate; + /** * Parse a string expression into AST form. Doesn't do anything else - * + * * @author ben * */ @@ -32,8 +32,8 @@ public class DiceASTParser { private static IDiceASTNode convertLeafNode(String leafNode) { DiceLiteralType literalType = ILiteralDiceNode.getLiteralType(leafNode); - if (literalType != null) { - switch (literalType) { + if(literalType != null) { + switch(literalType) { case DICE: return new DiceLiteralNode(IDiceExpression.toExpression(leafNode)); case INTEGER: @@ -44,9 +44,8 @@ public class DiceASTParser { } } - if (leafNode.matches("[+-]?\\d*\\.\\d+")) { + if(leafNode.matches("[+-]?\\d*\\.\\d+")) throw new InputMismatchException("Floating point literals are not supported"); - } return new VariableDiceNode(leafNode); } @@ -54,7 +53,7 @@ public class DiceASTParser { private static IDiceASTNode convertOperatorNode(String operatorNode) { try { return OperatorDiceNode.fromString(operatorNode); - } catch (IllegalArgumentException iaex) { + } catch(IllegalArgumentException iaex) { InputMismatchException imex = new InputMismatchException( "Attempted to parse invalid operator " + operatorNode); @@ -66,7 +65,7 @@ public class DiceASTParser { /** * Create an AST from a list of tokens - * + * * @param tokens * The list of tokens to convert * @return An AST built from the tokens @@ -74,9 +73,8 @@ public class DiceASTParser { public static ITree createFromString(IList tokens) { // Mark arrays as special operators Predicate specialPicker = (operator) -> { - if (StringUtils.containsOnly(operator, "\\[") || StringUtils.containsOnly(operator, "\\]")) { + if(StringUtils.containsOnly(operator, "\\[") || StringUtils.containsOnly(operator, "\\]")) return true; - } return false; }; @@ -108,21 +106,18 @@ public class DiceASTParser { } private static boolean isOperatorNode(String token) { - if (StringUtils.containsOnly(token, "\\[")) { - return true; - } else if (StringUtils.containsOnly(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 ] + if(token.equals("[]")) // This is a synthetic operator, + // constructed by [ and ] return true; - } try { OperatorDiceNode.fromString(token); return true; - } catch (IllegalArgumentException iaex) { + } catch(IllegalArgumentException iaex) { // We don't care about details return false; } @@ -131,7 +126,7 @@ public class DiceASTParser { private static ITree parseCloseArray(Deque> queuedTrees) { IList> children = new FunctionalList<>(); - while (shouldContinuePopping(queuedTrees)) { + while(shouldContinuePopping(queuedTrees)) { children.add(queuedTrees.pop()); } diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java index 5be2090..f668c72 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceChecker.java @@ -1,15 +1,15 @@ package bjc.dicelang.v1.ast; -import java.util.function.Consumer; - import bjc.dicelang.v1.ast.nodes.DiceASTType; import bjc.dicelang.v1.ast.nodes.IDiceASTNode; import bjc.dicelang.v1.ast.nodes.VariableDiceNode; import bjc.utils.data.IHolder; +import java.util.function.Consumer; + /** * Check if the specified node references a particular variable - * + * * @author ben * */ @@ -23,7 +23,7 @@ public final class DiceASTReferenceChecker implements Consumer { /** * Create a new reference checker - * + * * @param referencesVar * The holder of whether the variable is referenced or * not @@ -42,13 +42,13 @@ public final class DiceASTReferenceChecker implements Consumer { /** * Check if a given AST node directly references the specified variable - * + * * @param astNode * The node to check * @return Whether or not the node directly the variable */ private boolean isDirectReference(IDiceASTNode astNode) { - if (astNode.getType() == DiceASTType.VARIABLE) { + if(astNode.getType() == DiceASTType.VARIABLE) { VariableDiceNode node = (VariableDiceNode) astNode; return node.getVariable().equals(varName); diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceSanitizer.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceSanitizer.java index 5bb07fd..ec595ea 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceSanitizer.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTReferenceSanitizer.java @@ -6,61 +6,55 @@ import bjc.dicelang.v1.ast.nodes.VariableDiceNode; import bjc.utils.data.IHolder; import bjc.utils.data.ITree; import bjc.utils.data.Identity; - -import bjc.utils.funcdata.IMap; import bjc.utils.data.TopDownTransformResult; import bjc.utils.data.Tree; +import bjc.utils.funcdata.IMap; /** * 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 * */ public class DiceASTReferenceSanitizer { private static ITree doSanitize(ITree ast, IMap> enviroment) { - if (ast.getChildrenCount() != 2) { + if(ast.getChildrenCount() != 2) throw new UnsupportedOperationException("Assignment must have two arguments."); - } ITree nameTree = ast.getChild(0); ITree valueTree = ast.getChild(1); - if (!DiceASTUtils.containsSimpleVariable(nameTree)) { - if (nameTree.getHead() == OperatorDiceNode.ARRAY) { + if(!DiceASTUtils.containsSimpleVariable(nameTree)) { + if(nameTree.getHead() == OperatorDiceNode.ARRAY) { IHolder allSimpleVariables = new Identity<>(true); nameTree.doForChildren((child) -> { - if (allSimpleVariables.getValue()) { + if(allSimpleVariables.getValue()) { boolean isSimple = DiceASTUtils.containsSimpleVariable(child); allSimpleVariables.replace(isSimple); } }); - if (!allSimpleVariables.getValue()) { - throw new UnsupportedOperationException( - "Array assignment must be between variables and" - + " a expression/array of expressions"); - } + if(!allSimpleVariables.getValue()) throw new UnsupportedOperationException( + "Array assignment must be between variables and" + + " a expression/array of expressions"); - if (valueTree.getHead() == OperatorDiceNode.ARRAY) { - if (nameTree.getChildrenCount() != valueTree.getChildrenCount()) { + if(valueTree.getHead() == OperatorDiceNode.ARRAY) { + if(nameTree.getChildrenCount() != valueTree.getChildrenCount()) throw new UnsupportedOperationException( "Array assignment between arrays must be" + " between two arrays of equal length"); - } } - } else { + } else throw new UnsupportedOperationException( "Assignment must be between a variable and a expression"); - } } - if (nameTree.getHead() == OperatorDiceNode.ARRAY) { - if (valueTree.getHead() == OperatorDiceNode.ARRAY) { + if(nameTree.getHead() == OperatorDiceNode.ARRAY) { + if(valueTree.getHead() == OperatorDiceNode.ARRAY) { IHolder childCounter = new Identity<>(0); ITree returnTree = new Tree<>(OperatorDiceNode.ARRAY); @@ -75,7 +69,7 @@ public class DiceASTReferenceSanitizer { ITree sanitizedSubtree = doSingleSanitize(ast, enviroment, child, currentValue, variableName); - if (sanitizedSubtree == null) { + if(sanitizedSubtree == null) { ITree oldTree = new Tree<>(ast.getHead(), child, currentValue); @@ -98,7 +92,7 @@ public class DiceASTReferenceSanitizer { ITree sanitizedChild = doSingleSanitize(ast, enviroment, child, valueTree, variableName); - if (sanitizedChild == null) { + if(sanitizedChild == null) { ITree oldTree = new Tree<>(ast.getHead(), child, valueTree); returnTree.addChild(oldTree); @@ -115,9 +109,7 @@ public class DiceASTReferenceSanitizer { ITree sanitizedTree = doSingleSanitize(ast, enviroment, nameTree, valueTree, variableName); - if (sanitizedTree == null) { - return ast; - } + if(sanitizedTree == null) return ast; return sanitizedTree; } @@ -125,7 +117,7 @@ public class DiceASTReferenceSanitizer { private static ITree doSingleSanitize(ITree ast, IMap> enviroment, ITree nameTree, ITree valueTree, String variableName) { - if (enviroment.containsKey(variableName)) { + if(enviroment.containsKey(variableName)) { // @ is a meta-variable standing for the left side of an // assignment ITree oldVal = enviroment.put("@", enviroment.get(variableName)); @@ -136,7 +128,7 @@ public class DiceASTReferenceSanitizer { ITree inlinedValue = DiceASTInliner.selectiveInline(valueTree, enviroment, variableName, "last", "@"); - if (oldVal != null) { + if(oldVal != null) { enviroment.put("@", oldVal); } else { enviroment.remove("@"); @@ -150,7 +142,7 @@ public class DiceASTReferenceSanitizer { /** * Sanitize the references in an AST - * + * * @param ast * @param enviroment * @return The sanitized AST @@ -163,11 +155,9 @@ public class DiceASTReferenceSanitizer { } private static TopDownTransformResult shouldSanitize(IDiceASTNode node) { - if (!node.isOperator()) { - return TopDownTransformResult.SKIP; - } + if(!node.isOperator()) return TopDownTransformResult.SKIP; - switch (((OperatorDiceNode) node)) { + switch((OperatorDiceNode) node) { case ASSIGN: return TopDownTransformResult.TRANSFORM; case ARRAY: diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTUtils.java b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTUtils.java index 4d710fe..e37d3c3 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DiceASTUtils.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DiceASTUtils.java @@ -11,14 +11,14 @@ import bjc.utils.data.ITree; /** * Functions that are useful when dealing with dice ASTs - * + * * @author ben * */ public class DiceASTUtils { /** * Check if a dice AST contains a simple variable reference - * + * * @param nameTree * The tree to check for a reference in * @return Whether or not a dice AST contains a simple variable @@ -26,9 +26,7 @@ public class DiceASTUtils { */ public static boolean containsSimpleVariable(ITree nameTree) { return nameTree.transformHead((nameNode) -> { - if (nameNode.getType() != DiceASTType.VARIABLE) { - return false; - } + if(nameNode.getType() != DiceASTType.VARIABLE) return false; return true; }); @@ -36,11 +34,11 @@ public class DiceASTUtils { /** * Convert an literal AST node to a dice expression, if possible. - * + * * @param tree * 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}) @@ -50,7 +48,7 @@ public class DiceASTUtils { public static IDiceExpression literalToExpression(ITree tree) { ILiteralDiceNode literalNode = (ILiteralDiceNode) tree.getHead(); - switch (literalNode.getLiteralType()) { + switch(literalNode.getLiteralType()) { case DICE: return ((DiceLiteralNode) literalNode).getValue(); case INTEGER: @@ -63,11 +61,11 @@ public class DiceASTUtils { /** * Convert an literal AST node to an integer, if possible. - * + * * @param 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}) diff --git a/dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java b/dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java index 6858022..2328d3c 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/DummyResult.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1.ast; /** * A dummy result - * + * * @author ben * */ @@ -14,7 +14,7 @@ public class DummyResult implements IResult { /** * Create a new dummy result with a reason - * + * * @param data * The reason why the result is a dummy */ @@ -24,7 +24,7 @@ public class DummyResult implements IResult { /** * Get the data in this dummy - * + * * @return The reason why this result is a dummy */ public String getData() { diff --git a/dice-lang/src/bjc/dicelang/v1/ast/IOperatorCollapser.java b/dice-lang/src/bjc/dicelang/v1/ast/IOperatorCollapser.java index bd120a8..ab097db 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/IOperatorCollapser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/IOperatorCollapser.java @@ -1,15 +1,15 @@ package bjc.dicelang.v1.ast; -import java.util.function.Function; - import bjc.dicelang.v1.ast.nodes.IDiceASTNode; import bjc.utils.data.IPair; import bjc.utils.data.ITree; import bjc.utils.funcdata.IList; +import java.util.function.Function; + /** * Alias for operator collapsers. Because 68-char types are too long - * + * * @author ben * */ diff --git a/dice-lang/src/bjc/dicelang/v1/ast/IResult.java b/dice-lang/src/bjc/dicelang/v1/ast/IResult.java index 093cfd0..df67061 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/IResult.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/IResult.java @@ -2,14 +2,14 @@ package bjc.dicelang.v1.ast; /** * Represents a result from an expression evaluation - * + * * @author ben * */ public interface IResult { /** * Get the type of this result - * + * * @return The type of this result */ public ResultType getType(); diff --git a/dice-lang/src/bjc/dicelang/v1/ast/IntegerResult.java b/dice-lang/src/bjc/dicelang/v1/ast/IntegerResult.java index b365282..61d57b7 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/IntegerResult.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/IntegerResult.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1.ast; /** * Represents a integer-valued result - * + * * @author ben * */ @@ -11,7 +11,7 @@ public class IntegerResult implements IResult { /** * Create a new integer valued result - * + * * @param val * The value of the result */ @@ -26,7 +26,7 @@ public class IntegerResult implements IResult { /** * Get the value of this result - * + * * @return The value of this result */ public int getValue() { diff --git a/dice-lang/src/bjc/dicelang/v1/ast/ResultType.java b/dice-lang/src/bjc/dicelang/v1/ast/ResultType.java index 73616ee..c5afee8 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/ResultType.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/ResultType.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1.ast; /** * Represents the result of a computation - * + * * @author ben * */ diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceASTType.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceASTType.java index ea85b2a..47e8b39 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceASTType.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceASTType.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1.ast.nodes; /** * An enum to represent the type of node an AST node is - * + * * @author ben * */ 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 bb979d1..4241463 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralNode.java @@ -4,7 +4,7 @@ import bjc.dicelang.v1.IDiceExpression; /** * Represents a literal backed by a dice expression - * + * * @author ben * */ @@ -13,7 +13,7 @@ public class DiceLiteralNode implements ILiteralDiceNode { /** * Create a new literal from an expression - * + * * @param exp * The expression to attempt to create a literal from */ @@ -33,7 +33,7 @@ public class DiceLiteralNode implements ILiteralDiceNode { /** * Return the expression being represented - * + * * @return The expression being represented */ public IDiceExpression getValue() { diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralType.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralType.java index 9440f85..d48104c 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralType.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceLiteralType.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1.ast.nodes; /** * Represents the type of literals that can be in an AST - * + * * @author ben * */ 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 a5a79a6..b842604 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceOperatorType.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/DiceOperatorType.java @@ -2,10 +2,10 @@ 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 - * + * * @author ben * */ diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/IDiceASTNode.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/IDiceASTNode.java index 219cf4a..7e8bb81 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/IDiceASTNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/IDiceASTNode.java @@ -2,21 +2,21 @@ package bjc.dicelang.v1.ast.nodes; /** * The interface for a node in a dice AST - * + * * @author ben * */ public interface IDiceASTNode { /** * Get the type of AST node this node is - * + * * @return The type of AST node this AST node is */ public DiceASTType getType(); /** * Check if this node represents an operator or not - * + * * @return Whether or not this node represents an operator */ public boolean isOperator(); 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 ece528b..5a3f5b3 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/ILiteralDiceNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/ILiteralDiceNode.java @@ -2,14 +2,14 @@ package bjc.dicelang.v1.ast.nodes; /** * Represents a literal of some type in the AST - * + * * @author ben * */ 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 @@ -19,18 +19,15 @@ public interface ILiteralDiceNode extends IDiceASTNode { String diceGroupOrNumber = "[(?:" + diceGroup + ")(?:\\d+)]"; - if (tok.matches("\\A" + diceGroupOrNumber + "?" + "c" + diceGroupOrNumber + "\\Z")) { + if(tok.matches("\\A" + diceGroupOrNumber + "?" + "c" + diceGroupOrNumber + "\\Z")) return DiceLiteralType.DICE; - } - if (tok.matches("\\A" + diceGroup + "Z")) { - return DiceLiteralType.DICE; - } + if(tok.matches("\\A" + diceGroup + "Z")) return DiceLiteralType.DICE; try { Integer.parseInt(tok); return DiceLiteralType.INTEGER; - } catch (NumberFormatException nfex) { + } catch(NumberFormatException nfex) { // We don't care about details // This probably shouldn't return null, but I believe it // does so @@ -41,7 +38,7 @@ public interface ILiteralDiceNode extends IDiceASTNode { /** * Check if this node can be optimized to a constant - * + * * @return Whether or not this node can be optimized to a constant * @see bjc.dicelang.v1.IDiceExpression#canOptimize() */ @@ -49,7 +46,7 @@ public interface ILiteralDiceNode extends IDiceASTNode { /** * Get the type of literal this node represents - * + * * @return The type of literal this node represents */ DiceLiteralType getLiteralType(); @@ -66,7 +63,7 @@ public interface ILiteralDiceNode extends IDiceASTNode { /** * Optimize this node to a constant if possible - * + * * @return This node in constant form if possible * @see bjc.dicelang.v1.IDiceExpression#optimize() */ 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 1c8aa56..fd1a1e6 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/IntegerLiteralNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/IntegerLiteralNode.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1.ast.nodes; /** * Represents an integer literal of some kind - * + * * @author ben * */ @@ -11,7 +11,7 @@ public class IntegerLiteralNode implements ILiteralDiceNode { /** * Create a new integer literal from the given number - * + * * @param val * The value this node represents */ @@ -31,7 +31,7 @@ public class IntegerLiteralNode implements ILiteralDiceNode { /** * Get the value this node represents - * + * * @return The integer value of this node */ public int getValue() { 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 0af9d81..0181314 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/OperatorDiceNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/OperatorDiceNode.java @@ -6,7 +6,7 @@ import static bjc.dicelang.v1.ast.nodes.DiceOperatorType.MATH; /** * A node that represents an operator - * + * * @author ben * */ @@ -50,13 +50,13 @@ public enum OperatorDiceNode implements IDiceASTNode { /** * Create a operator node from a string - * + * * @param s * The string to convert to a node * @return The operator corresponding to the node */ public static OperatorDiceNode fromString(String s) { - switch (s) { + switch(s) { case ":=": return ASSIGN; case "+": @@ -84,7 +84,7 @@ public enum OperatorDiceNode implements IDiceASTNode { /** * Represents the group of operator this operator is sorted into. - * + * */ public final DiceOperatorType type; 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 22ddf17..e44f2ab 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/VariableDiceNode.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/VariableDiceNode.java @@ -2,7 +2,7 @@ package bjc.dicelang.v1.ast.nodes; /** * A node that represents a reference to a variable - * + * * @author ben * */ @@ -14,7 +14,7 @@ public class VariableDiceNode implements IDiceASTNode { /** * Create a new node representing the specified variable - * + * * @param varName * The name of the variable being referenced */ @@ -24,28 +24,24 @@ public class VariableDiceNode implements IDiceASTNode { /* * (non-Javadoc) - * + * * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object obj) { // Handle special cases - if (this == obj) { + if(this == obj) return true; - } else if (obj == null) { + else if(obj == null) return false; - } else if (getClass() != obj.getClass()) { + else if(getClass() != obj.getClass()) return false; - } else { + else { VariableDiceNode other = (VariableDiceNode) obj; - if (variableName == null) { - if (other.variableName != null) { - return false; - } - } else if (!variableName.equals(other.variableName)) { - return false; - } + if(variableName == null) { + if(other.variableName != null) return false; + } else if(!variableName.equals(other.variableName)) return false; return true; } @@ -58,7 +54,7 @@ public class VariableDiceNode implements IDiceASTNode { /** * Get the variable referenced by this AST node - * + * * @return the variable referenced by this AST node */ public String getVariable() { @@ -67,20 +63,20 @@ public class VariableDiceNode implements IDiceASTNode { /* * (non-Javadoc) - * + * * @see java.lang.Object#hashCode() */ @Override 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; } /* * (non-Javadoc) - * + * * @see bjc.utils.dice.ast.IDiceASTNode#isOperator() */ @Override @@ -90,7 +86,7 @@ public class VariableDiceNode implements IDiceASTNode { /* * (non-Javadoc) - * + * * @see java.lang.Object#toString() */ @Override diff --git a/dice-lang/src/bjc/dicelang/v1/ast/nodes/package-info.java b/dice-lang/src/bjc/dicelang/v1/ast/nodes/package-info.java index 098157d..cdd63e9 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/nodes/package-info.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/nodes/package-info.java @@ -1,6 +1,6 @@ /** * Classes for nodes in the dice-lang AST - * + * * @author ben * */ 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 9fb0a5e..acc1afa 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/ArithmeticCollapser.java @@ -1,7 +1,5 @@ package bjc.dicelang.v1.ast.optimization; -import java.util.function.BinaryOperator; - import bjc.dicelang.v1.ast.DiceASTUtils; import bjc.dicelang.v1.ast.nodes.DiceASTType; import bjc.dicelang.v1.ast.nodes.IDiceASTNode; @@ -9,12 +7,14 @@ import bjc.dicelang.v1.ast.nodes.ILiteralDiceNode; import bjc.dicelang.v1.ast.nodes.IntegerLiteralNode; import bjc.dicelang.v1.ast.nodes.OperatorDiceNode; import bjc.utils.data.ITree; -import bjc.utils.funcdata.IList; import bjc.utils.data.Tree; +import bjc.utils.funcdata.IList; + +import java.util.function.BinaryOperator; class ArithmeticCollapser { - private BinaryOperator reducer; - private OperatorDiceNode type; + private BinaryOperator reducer; + private OperatorDiceNode type; public ArithmeticCollapser(BinaryOperator reducr, OperatorDiceNode typ) { reducer = reducr; @@ -24,17 +24,14 @@ class ArithmeticCollapser { public ITree collapse(IList> children) { boolean allConstant = children.allMatch((subtree) -> { return subtree.transformHead((node) -> { - if (node.getType() == DiceASTType.LITERAL) { + if(node.getType() == DiceASTType.LITERAL) return ((ILiteralDiceNode) node).canOptimize(); - } return false; }); }); - if (!allConstant) { - return new Tree<>(type, children); - } + if(!allConstant) return new Tree<>(type, children); int initState = DiceASTUtils.literalToInteger(children.first()); 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 a0daf31..bf44953 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/ConstantCollapser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/ConstantCollapser.java @@ -6,12 +6,12 @@ import bjc.dicelang.v1.ast.nodes.IDiceASTNode; import bjc.dicelang.v1.ast.nodes.IntegerLiteralNode; import bjc.dicelang.v1.ast.nodes.OperatorDiceNode; import bjc.utils.data.ITree; -import bjc.utils.funcdata.IList; import bjc.utils.data.Tree; +import bjc.utils.funcdata.IList; /** * Collapses operations with constants to constants - * + * * @author ben * */ @@ -40,11 +40,9 @@ public class ConstantCollapser implements IOptimizationPass { @Override public ITree optimizeOperator(IDiceASTNode operator, IList> children) { - if (!operator.isOperator()) { - return new Tree<>(operator, children); - } + if(!operator.isOperator()) return new Tree<>(operator, children); - switch ((OperatorDiceNode) operator) { + switch((OperatorDiceNode) operator) { case ADD: return additionCollapser.collapse(children); case DIVIDE: @@ -56,22 +54,16 @@ public class ConstantCollapser implements IOptimizationPass { case COMPOUND: return compoundCollapser.collapse(children); case GROUP: - if (children.getSize() != 2) { - return new Tree<>(operator, children); - } + if(children.getSize() != 2) return new Tree<>(operator, children); 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); - } + if(children.getSize() != 1) return new Tree<>(operator, children); return children.first(); case ASSIGN: 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 b09d95d..082f042 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/IOptimizationPass.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/IOptimizationPass.java @@ -6,14 +6,14 @@ import bjc.utils.funcdata.IList; /** * Represents a pass of optimizations over a dice AST - * + * * @author ben * */ public interface IOptimizationPass { /** * Optimize a leaf in the tree - * + * * @param leafNode * The node to optimize * @return The optimized node @@ -22,7 +22,7 @@ public interface IOptimizationPass { /** * Optimize an operator in an AST node - * + * * @param operator * The operator being optimized * @param 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 f00d390..7ce6f5d 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/OperationCondenser.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/OperationCondenser.java @@ -11,14 +11,14 @@ import bjc.utils.data.Tree; /** * Condenses chained operations into a single level - * + * * @author ben * */ public class OperationCondenser { /** * Condense chained similiar operations into a single level - * + * * @param ast * The AST to condense * @return The condensed AST @@ -33,12 +33,10 @@ public class OperationCondenser { IHolder canCondense = new Identity<>(true); ast.doForChildren((child) -> { - if (canCondense.getValue()) { + if(canCondense.getValue()) { canCondense.replace(child.transformHead((node) -> { - if (node.getType() == DiceASTType.OPERATOR) { - if (operation.equals(node)) { - return true; - } + if(node.getType() == DiceASTType.OPERATOR) { + if(operation.equals(node)) return true; return false; } @@ -48,14 +46,12 @@ public class OperationCondenser { } }); - if (!canCondense.getValue()) { - return ast; - } + if(!canCondense.getValue()) return ast; ITree condensedAST = new Tree<>(operation); ast.doForChildren((child) -> { - if (child.getHead().getType() == DiceASTType.OPERATOR) { + if(child.getHead().getType() == DiceASTType.OPERATOR) { child.doForChildren((subChild) -> { condensedAST.addChild(subChild); }); @@ -68,7 +64,7 @@ public class OperationCondenser { } private static TopDownTransformResult pickNode(IDiceASTNode node) { - switch (node.getType()) { + switch(node.getType()) { case LITERAL: return TopDownTransformResult.SKIP; case OPERATOR: @@ -81,7 +77,7 @@ public class OperationCondenser { } private static TopDownTransformResult pickOperator(OperatorDiceNode node) { - switch (node) { + switch(node) { case ADD: case MULTIPLY: case SUBTRACT: diff --git a/dice-lang/src/bjc/dicelang/v1/ast/optimization/package-info.java b/dice-lang/src/bjc/dicelang/v1/ast/optimization/package-info.java index 04727d7..3c74a21 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/optimization/package-info.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/optimization/package-info.java @@ -1,6 +1,6 @@ /** * Contains optimizations on dice ASTs - * + * * @author ben * */ diff --git a/dice-lang/src/bjc/dicelang/v1/ast/package-info.java b/dice-lang/src/bjc/dicelang/v1/ast/package-info.java index 4c79a45..f1de4f7 100644 --- a/dice-lang/src/bjc/dicelang/v1/ast/package-info.java +++ b/dice-lang/src/bjc/dicelang/v1/ast/package-info.java @@ -1,6 +1,6 @@ /** * New implementation of AST for dice-lang - * + * * @author ben * */ diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceASTLanguageTest.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceASTLanguageTest.java index f20e276..205d986 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceASTLanguageTest.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceASTLanguageTest.java @@ -1,8 +1,5 @@ package bjc.dicelang.v1.examples; -import java.util.InputMismatchException; -import java.util.Scanner; - import bjc.dicelang.v1.ast.DiceASTEvaluator; import bjc.dicelang.v1.ast.DiceASTInliner; import bjc.dicelang.v1.ast.DiceASTOptimizer; @@ -18,9 +15,12 @@ import bjc.utils.funcdata.FunctionalStringTokenizer; import bjc.utils.funcdata.IList; import bjc.utils.funcdata.IMap; +import java.util.InputMismatchException; +import java.util.Scanner; + /** * Test interface for AST-based dice language - * + * * @author ben * */ @@ -66,7 +66,7 @@ public class DiceASTLanguageTest { // Get the pragma arguments IList pragmaArgs = tokenizer.toList(); - if (pragmaArgs.getSize() < 3) { + 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." @@ -91,7 +91,7 @@ public class DiceASTLanguageTest { /** * Main method of class - * + * * @param args * Unused CLI args */ @@ -107,12 +107,12 @@ public class DiceASTLanguageTest { IMap> enviroment = new FunctionalMap<>(); // Handle commands - while (!currentLine.equalsIgnoreCase("quit")) { + while(!currentLine.equalsIgnoreCase("quit")) { // Get the name of a possible action String possibleActionName = currentLine.split(" ")[0]; // Check and see if we're executing an action - if (actions.containsKey(possibleActionName)) { + if(actions.containsKey(possibleActionName)) { // Execute action FunctionalStringTokenizer tokenizer = new FunctionalStringTokenizer(currentLine); @@ -146,7 +146,7 @@ public class DiceASTLanguageTest { System.out.println("Command parsed in " + (double) (System.nanoTime() - time) / 1000000000 + " s"); - } catch (InputMismatchException | IllegalStateException | UnsupportedOperationException ex) { + } catch(InputMismatchException | IllegalStateException | UnsupportedOperationException ex) { // Tell the user there was an error in parsing System.out.println("PARSING ERROR: " + ex.getLocalizedMessage()); @@ -187,7 +187,7 @@ public class DiceASTLanguageTest { // Update the 'last' meta-variable enviroment.put("last", transformedAST); - } catch (UnsupportedOperationException usex) { + } catch(UnsupportedOperationException usex) { // Tell the user there was an error in // evaluation System.out.println("EVALUATION ERROR: " + usex.getLocalizedMessage()); diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceASTPragma.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceASTPragma.java index a29b8b5..502dafd 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceASTPragma.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceASTPragma.java @@ -1,18 +1,18 @@ package bjc.dicelang.v1.examples; -import java.util.function.BiConsumer; - import bjc.dicelang.v1.ast.nodes.IDiceASTNode; import bjc.utils.data.ITree; import bjc.utils.funcdata.FunctionalStringTokenizer; import bjc.utils.funcdata.IMap; +import java.util.function.BiConsumer; + /** * 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 - * + * * @author ben * */ diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionParserTest.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionParserTest.java index adffc69..9d51c28 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionParserTest.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionParserTest.java @@ -1,21 +1,21 @@ package bjc.dicelang.v1.examples; -import java.util.HashMap; -import java.util.Scanner; - import bjc.dicelang.v1.DiceExpressionParser; import bjc.dicelang.v1.IDiceExpression; +import java.util.HashMap; +import java.util.Scanner; + /** * Driver class for testing expression parser - * + * * @author ben * */ public class DiceExpressionParserTest { /** * Run the parser test - * + * * @param args * Unused CLI arguments */ @@ -44,7 +44,7 @@ public class DiceExpressionParserTest { /* * Roll the dice a specified amount of times */ - for (int i = 1; i <= nTimes; i++) { + for(int i = 1; i <= nTimes; i++) { int roll = dexp.roll(); System.out.println("Rolled " + roll); diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionPreparer.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionPreparer.java index 121847c..5f38374 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionPreparer.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceExpressionPreparer.java @@ -1,8 +1,5 @@ package bjc.dicelang.v1.examples; -import java.util.Deque; -import java.util.LinkedList; - import bjc.utils.data.IPair; import bjc.utils.data.Pair; import bjc.utils.funcdata.FunctionalStringTokenizer; @@ -10,9 +7,12 @@ import bjc.utils.funcdata.IList; import bjc.utils.funcutils.ListUtils; import bjc.utils.parserutils.ShuntingYard; +import java.util.Deque; +import java.util.LinkedList; + /** * Prepare a dice expression to be parsed - * + * * @author ben * */ @@ -22,9 +22,9 @@ public class DiceExpressionPreparer { */ private static ShuntingYard 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 { @@ -54,7 +54,7 @@ public class DiceExpressionPreparer { /** * Prepare a command, turning raw tokens into input for the tree builder - * + * * @param currentLine * The command to prepare * @return A stream of tokens representing the command diff --git a/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageState.java b/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageState.java index e2a71b4..17c147c 100644 --- a/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageState.java +++ b/dice-lang/src/bjc/dicelang/v1/examples/DiceLanguageState.java @@ -1,14 +1,14 @@ package bjc.dicelang.v1.examples; -import java.util.Map; - import bjc.dicelang.v1.DiceExpressionParser; import bjc.dicelang.v1.IDiceExpression; import bjc.utils.data.Pair; +import java.util.Map; + /** * Internal state of dice language - * + * * @author ben * */ @@ -22,7 +22,7 @@ public class DiceLanguageState extends Pair env = new HashMap<>(); DiceLanguageState state = new DiceLanguageState(dep, env); - while (!ln.equalsIgnoreCase("quit")) { + while(!ln.equalsIgnoreCase("quit")) { String header = ln.split(" ")[0]; - if (acts.containsKey(header)) { + if(acts.containsKey(header)) { acts.get(header).accept(ln, state); } else { IDiceExpression exp = DiceExpressionParser.parse(ln, env); @@ -86,7 +86,7 @@ public class DiceLanguageTest { IDiceExpression dexp = stat.merge((dep, env) -> env.get(strangs[1])); - for (int i = 1; i <= nRolls; i++) { + for(int i = 1; i <= nRolls; i++) { int roll = dexp.roll(); System.out.println("\tRolled " + roll); -- cgit v1.2.3