diff options
| author | bculkin2442 <bjculkin@mix.wvu.edu> | 2017-04-11 21:48:50 -0400 |
|---|---|---|
| committer | bculkin2442 <bjculkin@mix.wvu.edu> | 2017-04-11 21:48:50 -0400 |
| commit | 57f9a3bfdad20bead5b35ee540e8790e80a6b9a4 (patch) | |
| tree | 1e7184825eaa8d22077b505513df3e0d8502fb39 /dice-lang/src/bjc | |
| parent | 675ae734dd7b7a47d93ee3527dd1eb7195be047b (diff) | |
Cleanup
Diffstat (limited to 'dice-lang/src/bjc')
32 files changed, 1042 insertions, 943 deletions
diff --git a/dice-lang/src/bjc/dicelang/CLIArgsParser.java b/dice-lang/src/bjc/dicelang/CLIArgsParser.java index 91917a0..e324e67 100644 --- a/dice-lang/src/bjc/dicelang/CLIArgsParser.java +++ b/dice-lang/src/bjc/dicelang/CLIArgsParser.java @@ -1,6 +1,10 @@ package bjc.dicelang; -import bjc.dicelang.util.ResourceLoader; +import static bjc.dicelang.Errors.ErrorKey.EK_CLI_INVDFNTYPE; +import static bjc.dicelang.Errors.ErrorKey.EK_CLI_MISARG; +import static bjc.dicelang.Errors.ErrorKey.EK_CLI_UNARG; +import static bjc.dicelang.Errors.ErrorKey.EK_MISC_IOEX; +import static bjc.dicelang.Errors.ErrorKey.EK_MISC_NOFILE; import java.io.FileInputStream; import java.io.FileNotFoundException; @@ -8,7 +12,7 @@ import java.io.IOException; import java.util.Arrays; import java.util.Scanner; -import static bjc.dicelang.Errors.ErrorKey.*; +import bjc.dicelang.util.ResourceLoader; /** * Parse CLI arguments. @@ -27,78 +31,78 @@ public class CLIArgsParser { * * @return Whether or not to continue to the DiceLang repl. */ - public static boolean parseArgs(String[] args, DiceLangEngine eng) { - if(args.length < 0) return true; + public static boolean parseArgs(final String[] args, final DiceLangEngine eng) { + if (args.length < 0) return true; - if(args.length == 1 && (args[0].equals("--help") || args[0].equals("-h"))) { - for(String lne : ResourceLoader.loadHelpFile("cli")) { + if (args.length == 1 && (args[0].equals("--help") || args[0].equals("-h"))) { + for (final String lne : ResourceLoader.loadHelpFile("cli")) { System.out.println(lne); } System.exit(0); } - for(int i = 0; i < args.length; i++) { - String arg = args[i]; + for (int i = 0; i < args.length; i++) { + final String arg = args[i]; - 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": @@ -114,62 +118,61 @@ public class CLIArgsParser { return true; } - private static int simpleDefine(int i, String[] args, DiceLangEngine eng) { - if(i >= args.length - 1) { + private static int simpleDefine(final int i, final String[] args, final DiceLangEngine eng) { + if (i >= args.length - 1) { Errors.inst.printError(EK_CLI_MISARG, "define"); return -1; } - if(i >= args.length - 2) { - Define dfn = new Define(5, false, false, false, null, args[i + 1], Arrays.asList("")); + if (i >= args.length - 2) { + final Define dfn = new Define(5, false, false, false, null, args[i + 1], Arrays.asList("")); - if(dfn.inError) return -1; + if (dfn.inError) return -1; eng.addLineDefine(dfn); return i + 1; } - Define dfn = new Define(5, false, false, false, null, args[i + 1], Arrays.asList(args[i + 2])); + final 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; } - @SuppressWarnings("unused") - private static int defineFile(int i, String[] args, DiceLangEngine eng) { - if(i >= args.length - 1) { + private static int defineFile(final int i, final String[] args, final DiceLangEngine eng) { + if (i >= args.length - 1) { Errors.inst.printError(EK_CLI_MISARG, "define-file"); return -1; } - String fName = args[i + 1]; + final String fName = args[i + 1]; - try(FileInputStream fis = new FileInputStream(fName)) { - try(Scanner scan = new Scanner(fis)) { - while(scan.hasNextLine()) { - String ln = scan.nextLine(); + try (FileInputStream fis = new FileInputStream(fName)) { + try (Scanner scan = new Scanner(fis)) { + while (scan.hasNextLine()) { + final String ln = scan.nextLine(); - Define dfn = parseDefine(ln.substring(ln.indexOf(' '))); - if(dfn == null || dfn.inError) return -1; + final Define dfn = parseDefine(ln.substring(ln.indexOf(' '))); + 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(' ')); + final String defnType = ln.substring(0, ln.indexOf(' ')); Errors.inst.printError(EK_CLI_INVDFNTYPE, defnType); return -1; } } } - } catch(FileNotFoundException fnfex) { + } catch (final FileNotFoundException fnfex) { Errors.inst.printError(EK_MISC_NOFILE, fName); return -1; - } catch(IOException ioex) { + } catch (final IOException ioex) { Errors.inst.printError(EK_MISC_IOEX, fName); return -1; } @@ -177,8 +180,8 @@ public class CLIArgsParser { return i + 1; } - private static Define parseDefine(@SuppressWarnings("unused") String ln) { - Define res = null; + private static Define parseDefine(final String ln) { + final Define res = null; // @TODO move this functionality from DiceLangConsole to some // common ground where it can be used by both functions diff --git a/dice-lang/src/bjc/dicelang/CompilerTweaker.java b/dice-lang/src/bjc/dicelang/CompilerTweaker.java index cbc7577..68c50dd 100644 --- a/dice-lang/src/bjc/dicelang/CompilerTweaker.java +++ b/dice-lang/src/bjc/dicelang/CompilerTweaker.java @@ -11,19 +11,19 @@ public class CompilerTweaker { /* * Bits of the compiler necessary */ - private DiceLangEngine eng; - private ConfigurableTokenSplitter opExpander; + private final DiceLangEngine eng; + private final ConfigurableTokenSplitter opExpander; /** * Create a new compiler tweaker. * - * @param eng + * @param engine * The engine to tweak. */ - public CompilerTweaker(DiceLangEngine eng) { - this.eng = eng; + public CompilerTweaker(final DiceLangEngine engine) { + eng = engine; - this.opExpander = eng.opExpander; + this.opExpander = engine.opExpander; } /** @@ -34,7 +34,7 @@ public class CompilerTweaker { * * @return The key into the string literal table for this string. */ - public int addStringLiteral(String val) { + public int addStringLiteral(final String val) { eng.addStringLiteral(eng.nextLiteral, val); eng.nextLiteral += 1; @@ -47,7 +47,7 @@ public class CompilerTweaker { * @param dfn * The defn to add. */ - public void addLineDefine(Define dfn) { + public void addLineDefine(final Define dfn) { eng.addLineDefine(dfn); } @@ -57,7 +57,7 @@ public class CompilerTweaker { * @param dfn * The defn to add. */ - public void addTokenDefine(Define dfn) { + public void addTokenDefine(final Define dfn) { eng.addTokenDefine(dfn); } @@ -67,7 +67,7 @@ public class CompilerTweaker { * @param delims * The delimiters to expand on. */ - public void addDelimiter(String... delims) { + public void addDelimiter(final String... delims) { opExpander.addSimpleDelimiters(delims); } @@ -77,7 +77,7 @@ public class CompilerTweaker { * @param delims * The multi-character delimiters to expand on. */ - public void addMultiDelimiter(String... delims) { + public void addMultiDelimiter(final String... delims) { opExpander.addMultiDelimiters(delims); } @@ -94,7 +94,7 @@ public class CompilerTweaker { * @param times * The number of times to allow defines to recur. */ - public static void setDefineRecurLimit(int times) { + public static void setDefineRecurLimit(final 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 89618e4..94708fd 100644 --- a/dice-lang/src/bjc/dicelang/Define.java +++ b/dice-lang/src/bjc/dicelang/Define.java @@ -1,6 +1,8 @@ package bjc.dicelang; -import bjc.utils.data.CircularIterator; +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; import java.util.Iterator; import java.util.function.UnaryOperator; @@ -8,9 +10,7 @@ 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; +import bjc.utils.data.CircularIterator; /** * A regular expression based pre-processor define. @@ -83,8 +83,8 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { * @param replacrs * The source for replacement strings. */ - public Define(int priorty, boolean isSub, boolean recur, boolean isCircular, String predicte, String searchr, - Iterable<String> replacrs) { + public Define(final int priorty, final boolean isSub, final boolean recur, final boolean isCircular, + final String predicte, final String searchr, final Iterable<String> replacrs) { priority = priorty; doRecur = recur; subType = isSub; @@ -92,10 +92,10 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { /* * Only try to compile non-null predicates */ - if(predicte != null) { + if (predicte != null) { try { predicate = Pattern.compile(predicte); - } catch(PatternSyntaxException psex) { + } catch (final PatternSyntaxException psex) { Errors.inst.printError(EK_DFN_PREDSYN, psex.getMessage()); inError = true; return; @@ -107,7 +107,7 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { */ try { searcher = Pattern.compile(searchr); - } catch(PatternSyntaxException psex) { + } catch (final PatternSyntaxException psex) { Errors.inst.printError(EK_DFN_SRCSYN, psex.getMessage()); inError = true; return; @@ -117,16 +117,16 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { /* * Check whether or not we do sub-replacements */ - if(subType) { - if(replacrs.iterator().hasNext()) { + if (subType) { + if (replacrs.iterator().hasNext()) { replacers = new CircularIterator<>(replacrs, isCircular); } else { replacers = null; } } else { - Iterator<String> itr = replacrs.iterator(); + final Iterator<String> itr = replacrs.iterator(); - if(itr.hasNext()) { + if (itr.hasNext()) { replacer = itr.next(); } else { replacer = ""; @@ -135,60 +135,59 @@ public class Define implements UnaryOperator<String>, Comparable<Define> { } @Override - public String apply(String tok) { - if(inError) return tok; + public String apply(final String 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)) - return strang; - else { - String oldStrang = strang; + if (strang.equals(tok)) return strang; - do { - strang = doPass(tok); - recurCount += 1; - } while(!strang.equals(oldStrang) && recurCount < MAX_RECURS); + final String oldStrang = strang; - if(recurCount >= MAX_RECURS) { - Errors.inst.printError(EK_DFN_RECUR, Integer.toString(MAX_RECURS), tok, strang); - return strang; - } + do { + strang = doPass(tok); + recurCount += 1; + } while (!strang.equals(oldStrang) && recurCount < MAX_RECURS); + + if (recurCount >= MAX_RECURS) { + Errors.inst.printError(EK_DFN_RECUR, Integer.toString(MAX_RECURS), tok, strang); + return strang; } } return strang; } - private String doPass(String tok) { - Matcher searcherMatcher = searcher.matcher(tok); + private String doPass(final String tok) { + final Matcher searcherMatcher = searcher.matcher(tok); - if(subType) { - StringBuffer sb = new StringBuffer(); - while(searcherMatcher.find()) { - if(replacers == null) { + if (subType) { + final StringBuffer sb = new StringBuffer(); + while (searcherMatcher.find()) { + if (replacers == null) { searcherMatcher.appendReplacement(sb, ""); } else { - String replac = replacers.next(); + final String replac = replacers.next(); searcherMatcher.appendReplacement(sb, replac); } } searcherMatcher.appendTail(sb); return sb.toString(); - } else - return searcherMatcher.replaceAll(replacer); + } + + return searcherMatcher.replaceAll(replacer); } @Override - public int compareTo(Define o) { + public int compareTo(final Define o) { return priority - o.priority; } } diff --git a/dice-lang/src/bjc/dicelang/DiceLangConsole.java b/dice-lang/src/bjc/dicelang/DiceLangConsole.java index 5f1d3f9..e06cccb 100644 --- a/dice-lang/src/bjc/dicelang/DiceLangConsole.java +++ b/dice-lang/src/bjc/dicelang/DiceLangConsole.java @@ -1,14 +1,14 @@ package bjc.dicelang; +import static bjc.dicelang.Errors.ErrorKey.EK_CONS_INVDEFINE; +import static bjc.dicelang.Errors.ErrorKey.EK_CONS_INVPRAG; + import java.io.IOException; 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; @@ -21,7 +21,7 @@ import jline.Terminal; public class DiceLangConsole { private int commandNumber; - private DiceLangEngine eng; + private final DiceLangEngine eng; private ConsoleReader read; @@ -31,12 +31,12 @@ public class DiceLangConsole { * @param args * The CLI args for the console. */ - public DiceLangConsole(String[] args) { + public DiceLangConsole(final String[] args) { commandNumber = 0; eng = new DiceLangEngine(); - if(!CLIArgsParser.parseArgs(args, eng)) { + if (!CLIArgsParser.parseArgs(args, eng)) { System.exit(1); } @@ -49,7 +49,7 @@ public class DiceLangConsole { public void run() { try { read = new ConsoleReader(); - } catch(@SuppressWarnings("unused") IOException ioex) { + } catch (final IOException ioex) { System.out.println("ERROR: Console init failed"); return; } @@ -60,16 +60,16 @@ public class DiceLangConsole { try { comm = read.readLine(String.format("(%d) dice-lang> ", commandNumber)); - } catch(@SuppressWarnings("unused") IOException ioex) { + } catch (final IOException ioex) { System.out.println("ERROR: I/O failed"); return; } - while(!comm.equals("quit") && !comm.equals("exit")) { - if(comm.startsWith("pragma")) { - boolean success = handlePragma(comm.substring(7)); + while (!comm.equals("quit") && !comm.equals("exit")) { + if (comm.startsWith("pragma")) { + final boolean success = handlePragma(comm.substring(7)); - if(success) { + if (success) { System.out.println("Pragma completed succesfully"); } else { System.out.println("Pragma execution failed"); @@ -77,9 +77,9 @@ public class DiceLangConsole { } else { System.out.printf("\tRaw command: %s\n", comm); - boolean success = eng.runCommand(comm); + final boolean success = eng.runCommand(comm); - if(success) { + if (success) { System.out.println("Command completed succesfully"); } else { System.out.println("Command execution failed"); @@ -90,25 +90,25 @@ public class DiceLangConsole { try { comm = read.readLine(String.format("(%d) dice-lang> ", commandNumber)); - } catch(@SuppressWarnings("unused") IOException ioex) { + } catch (final IOException ioex) { System.out.println("ERROR: I/O failed"); return; } } } - private boolean handlePragma(String pragma) { + private boolean handlePragma(final String pragma) { System.out.println("\tRaw pragma: " + pragma); String pragmaName = null; - int firstIndex = pragma.indexOf(' '); - if(firstIndex == -1) { + final int firstIndex = pragma.indexOf(' '); + 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; @@ -133,8 +133,8 @@ public class DiceLangConsole { return true; } - private boolean helpMode(String pragma) { - switch(pragma.trim()) { + private static boolean helpMode(final String pragma) { + switch (pragma.trim()) { case "help": System.out.println("\tGet help on pragmas"); break; @@ -172,44 +172,44 @@ public class DiceLangConsole { * Then, we just follow the pattern, escape it for java strings, and add * the enclosing slashes */ - private Pattern slashPattern = Pattern.compile("/((?:\\\\.|[^/\\\\])*)/"); + private final Pattern slashPattern = Pattern.compile("/((?:\\\\.|[^/\\\\])*)/"); - private boolean defineMode(String defineText) { - int firstIndex = defineText.indexOf(' '); - int secondIndex = defineText.indexOf(' ', firstIndex + 1); - int thirdIndex = defineText.indexOf(' ', secondIndex + 1); - int fourthIndex = defineText.indexOf(' ', thirdIndex + 1); - int fifthIndex = defineText.indexOf(' ', fourthIndex + 1); - int sixthIndex = defineText.indexOf(' ', fifthIndex + 1); + private boolean defineMode(final String defineText) { + final int firstIndex = defineText.indexOf(' '); + final int secondIndex = defineText.indexOf(' ', firstIndex + 1); + final int thirdIndex = defineText.indexOf(' ', secondIndex + 1); + final int fourthIndex = defineText.indexOf(' ', thirdIndex + 1); + final int fifthIndex = defineText.indexOf(' ', fourthIndex + 1); + final 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; } - int priority = Integer.parseInt(defineText.substring(0, firstIndex)); + final int priority = Integer.parseInt(defineText.substring(0, firstIndex)); - String defineType = defineText.substring(firstIndex + 1, secondIndex); + final String defineType = defineText.substring(firstIndex + 1, secondIndex); Define.Type type; boolean subMode = false; - switch(defineType) { + switch (defineType) { case "line": type = Define.Type.LINE; break; @@ -229,17 +229,17 @@ public class DiceLangConsole { return false; } - boolean doRecur = defineText.substring(secondIndex + 1, thirdIndex).equalsIgnoreCase("true"); - boolean hasGuard = defineText.substring(thirdIndex + 1, fourthIndex).equalsIgnoreCase("true"); - boolean isCircular = defineText.substring(thirdIndex + 1, fourthIndex).equalsIgnoreCase("true"); + final boolean doRecur = defineText.substring(secondIndex + 1, thirdIndex).equalsIgnoreCase("true"); + final boolean hasGuard = defineText.substring(thirdIndex + 1, fourthIndex).equalsIgnoreCase("true"); + final boolean isCircular = defineText.substring(thirdIndex + 1, fourthIndex).equalsIgnoreCase("true"); - String pats = defineText.substring(fifthIndex + 1).trim(); - Matcher patMatcher = slashPattern.matcher(pats); + final String pats = defineText.substring(fifthIndex + 1).trim(); + final Matcher patMatcher = slashPattern.matcher(pats); String guardPattern = null; - if(hasGuard) { - if(!patMatcher.find()) { + if (hasGuard) { + if (!patMatcher.find()) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no guard pattern)"); return false; } @@ -247,24 +247,24 @@ public class DiceLangConsole { guardPattern = patMatcher.group(1); } - if(!patMatcher.find()) { + if (!patMatcher.find()) { Errors.inst.printError(EK_CONS_INVDEFINE, "(no search pattern)"); return false; } - String searchPattern = patMatcher.group(1); - List<String> replacePatterns = new LinkedList<>(); + final String searchPattern = patMatcher.group(1); + final List<String> replacePatterns = new LinkedList<>(); - while(patMatcher.find()) { + while (patMatcher.find()) { replacePatterns.add(patMatcher.group(1)); } - Define dfn = new Define(priority, subMode, doRecur, isCircular, guardPattern, searchPattern, + final 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); @@ -279,8 +279,8 @@ public class DiceLangConsole { * @param args * CLI arguments. */ - public static void main(String[] args) { - DiceLangConsole console = new DiceLangConsole(args); + public static void main(final String[] args) { + final DiceLangConsole console = new DiceLangConsole(args); console.run(); } diff --git a/dice-lang/src/bjc/dicelang/DiceLangEngine.java b/dice-lang/src/bjc/dicelang/DiceLangEngine.java index d37332d..7736db4 100644 --- a/dice-lang/src/bjc/dicelang/DiceLangEngine.java +++ b/dice-lang/src/bjc/dicelang/DiceLangEngine.java @@ -1,5 +1,21 @@ package bjc.dicelang; +import static bjc.dicelang.Errors.ErrorKey.EK_ENG_NOCLOSING; +import static bjc.dicelang.Errors.ErrorKey.EK_ENG_NOOPENING; +import static bjc.dicelang.Token.Type.CBRACE; +import static bjc.dicelang.Token.Type.CBRACKET; +import static bjc.dicelang.Token.Type.CPAREN; +import static bjc.dicelang.Token.Type.OBRACE; +import static bjc.dicelang.Token.Type.OBRACKET; +import static bjc.dicelang.Token.Type.OPAREN; + +import java.util.Deque; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.List; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import bjc.dicelang.scl.StreamEngine; import bjc.utils.data.ITree; import bjc.utils.funcdata.FunctionalList; @@ -11,17 +27,6 @@ import bjc.utils.funcutils.ListUtils; import bjc.utils.parserutils.TokenUtils; import bjc.utils.parserutils.splitter.ConfigurableTokenSplitter; -import java.util.Deque; -import java.util.Iterator; -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_ENG_NOCLOSING; -import static bjc.dicelang.Errors.ErrorKey.EK_ENG_NOOPENING; -import static bjc.dicelang.Token.Type.*; - /** * Implements the orchestration necessary for processing DiceLang commands. * @@ -86,14 +91,14 @@ public class DiceLangEngine { */ public final IMap<Integer, String> symTable; - private IMap<Integer, String> stringLits; - private IMap<String, String> stringLiterals; + private final IMap<Integer, String> stringLits; + private final IMap<String, String> stringLiterals; /* * Lists of defns. */ - private IList<Define> lineDefns; - private IList<Define> tokenDefns; + private final IList<Define> lineDefns; + private final IList<Define> tokenDefns; /* * Are defns sorted by priority? @@ -182,7 +187,7 @@ public class DiceLangEngine { * @param dfn * The defn to add. */ - public void addLineDefine(Define dfn) { + public void addLineDefine(final Define dfn) { lineDefns.add(dfn); defnsSorted = false; @@ -194,7 +199,7 @@ public class DiceLangEngine { * @param dfn * The defn to add. */ - public void addTokenDefine(Define dfn) { + public void addTokenDefine(final Define dfn) { tokenDefns.add(dfn); defnsSorted = false; @@ -247,7 +252,7 @@ public class DiceLangEngine { /* * Matches double-angle bracketed strings. */ - private Pattern nonExpandPattern = Pattern.compile("<<([^\\>]*(?:\\>(?:[^\\>])*)*)>>"); + private final Pattern nonExpandPattern = Pattern.compile("<<([^\\>]*(?:\\>(?:[^\\>])*)*)>>"); /** * Run a command to completion. @@ -257,28 +262,28 @@ public class DiceLangEngine { * * @return Whether or not the command ran successfully */ - public boolean runCommand(String command) { + public boolean runCommand(final String command) { /* * Preprocess the command into tokens */ - IList<String> preprocessedTokens = preprocessCommand(command); + final IList<String> preprocessedTokens = preprocessCommand(command); - if(preprocessedTokens == null) return false; + if (preprocessedTokens == null) return false; /* * Lex the string tokens into token-tokens */ - IList<Token> lexedTokens = lexTokens(preprocessedTokens); + final IList<Token> lexedTokens = lexTokens(preprocessedTokens); - if(lexedTokens == null) return false; + if (lexedTokens == null) return false; /* * Parse the tokens into an AST forest */ - IList<ITree<Node>> astForest = new FunctionalList<>(); - boolean succ = parsr.parseTokens(lexedTokens, astForest); + final IList<ITree<Node>> astForest = new FunctionalList<>(); + final boolean succ = Parser.parseTokens(lexedTokens, astForest); - if(!succ) return false; + if (!succ) return false; /* * Evaluate the AST forest @@ -291,30 +296,30 @@ public class DiceLangEngine { /* * Lex string tokens into token-tokens */ - private IList<Token> lexTokens(IList<String> preprocessedTokens) { - IList<Token> lexedTokens = new FunctionalList<>(); + private IList<Token> lexTokens(final IList<String> preprocessedTokens) { + final IList<Token> lexedTokens = new FunctionalList<>(); - for(String token : preprocessedTokens) { + for (final String token : preprocessedTokens) { String newTok = token; /* * Apply token defns */ - for(Define dfn : tokenDefns.toIterable()) { + for (final Define dfn : tokenDefns.toIterable()) { newTok = dfn.apply(newTok); } /* * Lex the token */ - Token tk = tokenzer.lexToken(token, stringLiterals); + final 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 */ @@ -324,7 +329,7 @@ public class DiceLangEngine { } } - if(debugMode) { + if (debugMode) { System.out.printf("\tCommand after tokenization: %s\n", lexedTokens.toString()); } @@ -332,25 +337,25 @@ public class DiceLangEngine { * Preshunt preshunt-marked groups of tokens */ IList<Token> shuntedTokens = lexedTokens; - IList<Token> preparedTokens = new FunctionalList<>(); + final IList<Token> preparedTokens = new FunctionalList<>(); 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 */ @@ -358,23 +363,22 @@ public class DiceLangEngine { shuntedTokens = preparedTokens.map(this::reverseToken); } - if(debugMode && !postfixMode) { + if (debugMode && !postfixMode) { System.out.printf("\tCommand after shunting: %s\n", shuntedTokens.toString()); } /* * Expand token groups */ - IList<Token> readyTokens = shuntedTokens.flatMap(tk -> { - if(tk.type == Token.Type.TOKGROUP) + final IList<Token> readyTokens = shuntedTokens.flatMap(tk -> { + if (tk.type == Token.Type.TOKGROUP) return tk.tokenValues; - else if(tk.type == Token.Type.TAGOP || tk.type == Token.Type.TAGOPR) + else if (tk.type == Token.Type.TAGOP || tk.type == Token.Type.TAGOPR) return tk.tokenValues; - else - return new FunctionalList<>(tk); + else return new FunctionalList<>(tk); }); - if(debugMode && !postfixMode) { + if (debugMode && !postfixMode) { System.out.printf("\tCommand after re-preshunting: %s\n", readyTokens.toString()); } @@ -386,8 +390,8 @@ public class DiceLangEngine { * * These are mostly just things like (, {, and [ */ - private Token reverseToken(Token tk) { - switch(tk.type) { + private Token reverseToken(final Token tk) { + switch (tk.type) { case OBRACE: return new Token(CBRACE, tk.intValue); case OPAREN: @@ -408,55 +412,55 @@ public class DiceLangEngine { /* * Preprocess a command into a list of string tokens. */ - private IList<String> preprocessCommand(String command) { + private IList<String> preprocessCommand(final String command) { /* * Sort the defines if they aren't sorted */ - if(!defnsSorted) { + if (!defnsSorted) { sortDefns(); } /* * Run the tokens through the stream engine */ - IList<String> streamToks = new FunctionalList<>(); - boolean succ = streamEng.doStreams(command.split(" "), streamToks); + final IList<String> streamToks = new FunctionalList<>(); + final 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 (final Define dfn : lineDefns.toIterable()) { newComm = dfn.apply(newComm); } - if(debugMode) { + if (debugMode) { System.out.println("\tCommand after line defines: " + newComm); } /* * Remove string literals. */ - List<String> destringedParts = TokenUtils.removeDQuotedStrings(newComm); - StringBuffer destringedCommand = new StringBuffer(); + final List<String> destringedParts = TokenUtils.removeDQuotedStrings(newComm); + final StringBuffer destringedCommand = new StringBuffer(); - for(String part : destringedParts) { + for (final String part : destringedParts) { /* * Handle string literals */ - if(part.startsWith("\"") && part.endsWith("\"")) { + if (part.startsWith("\"") && part.endsWith("\"")) { /* * Get the actual string. */ - String litName = "stringLiteral" + nextLiteral; - String litVal = part.substring(1, part.length() - 1); + final String litName = "stringLiteral" + nextLiteral; + final String litVal = part.substring(1, part.length() - 1); /* * Insert the string with its escape sequences @@ -474,13 +478,13 @@ public class DiceLangEngine { } } - if(debugMode) { + if (debugMode) { System.out.println("\tCommand after destringing: " + destringedCommand); /* * Print the string table if it exists. */ - if(stringLiterals.size() > 0) { + if (stringLiterals.size() > 0) { System.out.println("\tString literals in table"); stringLiterals.forEach((key, val) -> { @@ -492,26 +496,27 @@ public class DiceLangEngine { /* * Split the command into tokens */ - String strang = destringedCommand.toString(); + final String strang = destringedCommand.toString(); IList<String> tokens = FunctionalStringTokenizer.fromString(strang).toList(); /* * Temporarily remove non-expanding tokens */ - IMap<String, String> nonExpandedTokens = new FunctionalMap<>(); + final IMap<String, String> nonExpandedTokens = new FunctionalMap<>(); tokens = tokens.map(tk -> { - Matcher nonExpandMatcher = nonExpandPattern.matcher(tk); + final Matcher nonExpandMatcher = nonExpandPattern.matcher(tk); - if(nonExpandMatcher.matches()) { - String tkName = "nonExpandToken" + nextLiteral++; + if (nonExpandMatcher.matches()) { + final String tkName = "nonExpandToken" + nextLiteral++; nonExpandedTokens.put(tkName, nonExpandMatcher.group(1)); return tkName; - } else - return tk; + } + + return tk; }); - if(debugMode) { + if (debugMode) { System.out.printf("\tCommand after removal of non-expanders: %s\n", tokens.toString()); } @@ -525,13 +530,12 @@ public class DiceLangEngine { * Reinsert non-expanded tokens */ fullyExpandedTokens = fullyExpandedTokens.map(tk -> { - if(tk.startsWith("nonExpandToken")) - return nonExpandedTokens.get(tk); - else - return tk; + if (tk.startsWith("nonExpandToken")) return nonExpandedTokens.get(tk); + + return tk; }); - if(debugMode) { + if (debugMode) { System.out.printf("\tCommand after non-expander reinsertion: %s\n", fullyExpandedTokens.toString()); } @@ -539,33 +543,33 @@ public class DiceLangEngine { return fullyExpandedTokens; } - private void evaluateForest(IList<ITree<Node>> astForest) { - if(debugMode) { + private void evaluateForest(final IList<ITree<Node>> astForest) { + if (debugMode) { System.out.println("\tParsed forest of asts"); } int treeNo = 1; - for(ITree<Node> ast : astForest) { - if(debugMode) { + for (final ITree<Node> ast : astForest) { + if (debugMode) { System.out.printf("\t\tTree %d in forest:\n%s\n", treeNo, ast.toString()); } - if(debugMode && stepEval) { + if (debugMode && stepEval) { int step = 1; /* * Evaluate it step by step */ - for(Iterator<ITree<Node>> itr = eval.stepDebug(ast); itr.hasNext();) { - ITree<Node> nodeStep = itr.next(); + for (final Iterator<ITree<Node>> itr = eval.stepDebug(ast); itr.hasNext();) { + final ITree<Node> nodeStep = itr.next(); System.out.printf("\t\tStep %d: Node is %s", step, nodeStep); /* * Don't evaluate null steps */ - if(nodeStep == null) { + if (nodeStep == null) { System.out.println(); step += 1; @@ -575,16 +579,16 @@ public class DiceLangEngine { /* * Print out details for results */ - if(nodeStep.getHead().type == Node.Type.RESULT) { - EvaluatorResult res = nodeStep.getHead().resultVal; + if (nodeStep.getHead().type == Node.Type.RESULT) { + final 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); } @@ -601,12 +605,12 @@ public class DiceLangEngine { /* * Evaluate it normally */ - EvaluatorResult res = eval.evaluate(ast); + final 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() + ")"); } } @@ -621,7 +625,7 @@ public class DiceLangEngine { /* * Preshunt preshunt-marked groups of tokens. */ - private boolean removePreshuntTokens(IList<Token> lexedTokens, IList<Token> preparedTokens) { + private boolean removePreshuntTokens(final IList<Token> lexedTokens, final IList<Token> preparedTokens) { /* * Current nesting level of tokens. */ @@ -630,17 +634,17 @@ public class DiceLangEngine { /* * Data storage. */ - Deque<IList<Token>> bracedTokens = new LinkedList<>(); + final Deque<IList<Token>> bracedTokens = new LinkedList<>(); IList<Token> curBracedTokens = new FunctionalList<>(); - for(Token tk : lexedTokens) { - if(tk.type == Token.Type.OBRACE && tk.intValue == 2) { + for (final 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. @@ -649,11 +653,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. @@ -664,21 +668,21 @@ public class DiceLangEngine { curBraceCount -= 1; - IList<Token> preshuntTokens = new FunctionalList<>(); + final IList<Token> preshuntTokens = new FunctionalList<>(); /* * Shunt preshunt group. */ - boolean success = shunt.shuntTokens(curBracedTokens, preshuntTokens); + final 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. @@ -698,7 +702,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); @@ -706,7 +710,7 @@ public class DiceLangEngine { } } - if(curBraceCount > 0) { + if (curBraceCount > 0) { /* * There was an unclosed group. */ @@ -717,11 +721,11 @@ public class DiceLangEngine { return true; } - String getStringLiteral(int key) { + String getStringLiteral(final int key) { return stringLits.get(key); } - void addStringLiteral(int key, String val) { + void addStringLiteral(final int key, final String val) { stringLits.put(key, val); } }
\ No newline at end of file diff --git a/dice-lang/src/bjc/dicelang/Errors.java b/dice-lang/src/bjc/dicelang/Errors.java index 55a8530..f5ced44 100644 --- a/dice-lang/src/bjc/dicelang/Errors.java +++ b/dice-lang/src/bjc/dicelang/Errors.java @@ -269,10 +269,10 @@ public class Errors { * @param args * The arguments for the error. */ - public void printError(ErrorKey key, String... args) { - switch(mode) { + public void printError(final ErrorKey key, final String... args) { + 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()); @@ -286,8 +286,8 @@ public class Errors { } } - private void devError(ErrorKey key, String[] args) { - switch(key) { + private static void devError(final ErrorKey key, final String[] args) { + 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 41e7e52..5260bab 100644 --- a/dice-lang/src/bjc/dicelang/Evaluator.java +++ b/dice-lang/src/bjc/dicelang/Evaluator.java @@ -1,5 +1,33 @@ package bjc.dicelang; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_DIVDICE; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_DIVZERO; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_INVBIN; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_INVDCREATE; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_INVDGROUP; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_INVDICE; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_INVNODE; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_INVSTRING; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_INVUNARY; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_MISMATH; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_STRINGMATH; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_UNBIN; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_UNDICE; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_UNMATH; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_UNSTRING; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_UNTOK; +import static bjc.dicelang.Errors.ErrorKey.EK_EVAL_UNUNARY; +import static bjc.dicelang.EvaluatorResult.Type.DICE; +import static bjc.dicelang.EvaluatorResult.Type.FAILURE; +import static bjc.dicelang.EvaluatorResult.Type.FLOAT; +import static bjc.dicelang.EvaluatorResult.Type.INT; +import static bjc.dicelang.EvaluatorResult.Type.STRING; + +import java.util.Deque; +import java.util.Iterator; +import java.util.LinkedList; +import java.util.function.Consumer; + import bjc.dicelang.dice.CompoundDie; import bjc.dicelang.dice.FudgeDie; import bjc.dicelang.dice.MathDie; @@ -12,14 +40,6 @@ import bjc.utils.data.TopDownTransformIterator; import bjc.utils.data.TopDownTransformResult; 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.*; - /** * Evaluate DiceLang ASTs * @@ -28,33 +48,36 @@ import static bjc.dicelang.EvaluatorResult.Type.*; */ public class Evaluator { private static enum CoerceSteps { - INTEGER, FLOAT; + INTEGER, DOUBLE; } private static class Context { public Consumer<Iterator<ITree<Node>>> thunk; public boolean isDebug; + + public Context() { + } } private static Node FAIL() { return new Node(Node.Type.RESULT, new EvaluatorResult(FAILURE)); } - private static Node FAIL(ITree<Node> orig) { + private static Node FAIL(final ITree<Node> orig) { return new Node(Node.Type.RESULT, new EvaluatorResult(FAILURE, orig)); } @SuppressWarnings("unused") - private static Node FAIL(Node orig) { + private static Node FAIL(final Node orig) { return new Node(Node.Type.RESULT, new EvaluatorResult(FAILURE, orig)); } - private static Node FAIL(EvaluatorResult res) { + private static Node FAIL(final EvaluatorResult res) { return new Node(Node.Type.RESULT, new EvaluatorResult(FAILURE, new Node(Node.Type.RESULT, res))); } - private DiceLangEngine eng; + private final DiceLangEngine eng; /** * Create a new evaluator. @@ -62,7 +85,7 @@ public class Evaluator { * @param en * The engine. */ - public Evaluator(DiceLangEngine en) { + public Evaluator(final DiceLangEngine en) { eng = en; } @@ -74,32 +97,32 @@ public class Evaluator { * * @return The result of the tree. */ - public EvaluatorResult evaluate(ITree<Node> comm) { - Context ctx = new Context(); + public EvaluatorResult evaluate(final ITree<Node> comm) { + final Context ctx = new Context(); ctx.isDebug = false; - ctx.thunk = (itr) -> { + ctx.thunk = itr -> { /** * Deliberately finish the iterator, but ignore results. * It's only for stepwise evaluation but we don't know * if stepping the iterator causes something to happen. * */ - while(itr.hasNext()) { + while (itr.hasNext()) { itr.next(); } }; - ITree<Node> res = comm.topDownTransform(this::pickEvaluationType, - (node) -> this.evaluateNode(node, ctx)); + final ITree<Node> res = comm.topDownTransform(this::pickEvaluationType, + node -> this.evaluateNode(node, ctx)); return res.getHead().resultVal; } // FIXME Something's broken with step evaluation @SuppressWarnings("javadoc") - public Iterator<ITree<Node>> stepDebug(ITree<Node> comm) { - Context ctx = new Context(); + public Iterator<ITree<Node>> stepDebug(final ITree<Node> comm) { + final Context ctx = new Context(); ctx.isDebug = true; @@ -110,10 +133,10 @@ public class Evaluator { }, comm); } - private TopDownTransformResult pickEvaluationType(Node nd) { - switch(nd.type) { + private TopDownTransformResult pickEvaluationType(final Node nd) { + switch (nd.type) { case UNARYOP: - switch(nd.operatorType) { + switch (nd.operatorType) { case COERCE: return TopDownTransformResult.RTRANSFORM; default: @@ -124,8 +147,8 @@ public class Evaluator { } } - private ITree<Node> evaluateNode(ITree<Node> ast, Context ctx) { - switch(ast.getHead().type) { + private ITree<Node> evaluateNode(final ITree<Node> ast, final Context ctx) { + switch (ast.getHead().type) { case UNARYOP: return evaluateUnaryOp(ast, ctx); case BINOP: @@ -142,31 +165,31 @@ public class Evaluator { } } - private ITree<Node> evaluateUnaryOp(ITree<Node> ast, Context ctx) { - if(ast.getChildrenCount() != 1) { + private ITree<Node> evaluateUnaryOp(final ITree<Node> ast, final Context ctx) { + if (ast.getChildrenCount() != 1) { Errors.inst.printError(EK_EVAL_UNUNARY, Integer.toString(ast.getChildrenCount())); return new Tree<>(FAIL(ast)); } - switch(ast.getHead().operatorType) { + switch (ast.getHead().operatorType) { /* * TODO move coercing to its own class */ case COERCE: - ITree<Node> toCoerce = ast.getChild(0); - ITree<Node> retVal = new Tree<>(toCoerce.getHead()); - Deque<ITree<Node>> children = new LinkedList<>(); + final ITree<Node> toCoerce = ast.getChild(0); + final ITree<Node> retVal = new Tree<>(toCoerce.getHead()); + final Deque<ITree<Node>> children = new LinkedList<>(); CoerceSteps curLevel = CoerceSteps.INTEGER; - for(int i = 0; i < toCoerce.getChildrenCount(); i++) { - ITree<Node> child = toCoerce.getChild(i); + for (int i = 0; i < toCoerce.getChildrenCount(); i++) { + final ITree<Node> child = toCoerce.getChild(i); ITree<Node> nChild = null; - if(ctx.isDebug) { - Iterator<ITree<Node>> nd = stepDebug(child); + if (ctx.isDebug) { + final Iterator<ITree<Node>> nd = stepDebug(child); - for(; nd.hasNext(); nChild = nd.next()) { + for (; nd.hasNext(); nChild = nd.next()) { ctx.thunk.accept(new SingleIterator<>(child)); } } else { @@ -175,28 +198,28 @@ public class Evaluator { ctx.thunk.accept(new SingleIterator<>(nChild)); } - if(nChild == null) { + if (nChild == null) { Errors.inst.printError(EK_EVAL_INVNODE); return new Tree<>(FAIL(ast)); } - Node childNode = nChild.getHead(); - EvaluatorResult res = childNode.resultVal; + final Node childNode = nChild.getHead(); + final EvaluatorResult res = childNode.resultVal; - if(res.type == FLOAT) { - curLevel = CoerceSteps.FLOAT; + if (res.type == FLOAT) { + curLevel = CoerceSteps.DOUBLE; } children.add(nChild); } - for(ITree<Node> child : children) { - Node nd = child.getHead(); - EvaluatorResult res = nd.resultVal; + for (final ITree<Node> child : children) { + final Node nd = child.getHead(); + final EvaluatorResult res = nd.resultVal; - switch(res.type) { + switch (res.type) { case INT: - if(curLevel == CoerceSteps.FLOAT) { + if (curLevel == CoerceSteps.DOUBLE) { nd.resultVal = new EvaluatorResult(FLOAT, (double) res.intVal); } default: @@ -211,18 +234,18 @@ public class Evaluator { return retVal; case DICESCALAR: - EvaluatorResult opr = ast.getChild(0).getHead().resultVal; + final EvaluatorResult opr = ast.getChild(0).getHead().resultVal; - if(opr.type != INT) { + if (opr.type != INT) { Errors.inst.printError(EK_EVAL_INVDCREATE, opr.type.toString()); } return new Tree<>(new Node(Node.Type.RESULT, new EvaluatorResult(DICE, new ScalarDie(opr.intVal)))); case DICEFUDGE: - EvaluatorResult oprn = ast.getChild(0).getHead().resultVal; + final EvaluatorResult oprn = ast.getChild(0).getHead().resultVal; - if(oprn.type != INT) { + if (oprn.type != INT) { Errors.inst.printError(EK_EVAL_INVDCREATE, oprn.type.toString()); } @@ -234,20 +257,20 @@ public class Evaluator { } } - private ITree<Node> evaluateBinaryOp(ITree<Node> ast, Context ctx) { - Token.Type binOp = ast.getHead().operatorType; + private static ITree<Node> evaluateBinaryOp(final ITree<Node> ast, final Context ctx) { + final 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()); return new Tree<>(FAIL(ast)); } - ITree<Node> left = ast.getChild(0); - ITree<Node> right = ast.getChild(1); + final ITree<Node> left = ast.getChild(0); + final ITree<Node> right = ast.getChild(1); - switch(binOp) { + switch (binOp) { case ADD: case SUBTRACT: case MULTIPLY: @@ -267,65 +290,64 @@ public class Evaluator { } } - private ITree<Node> evaluateStringBinary(Token.Type op, EvaluatorResult left, EvaluatorResult right, - @SuppressWarnings("unused") Context ctx) { - if(left.type != STRING) { + private static ITree<Node> evaluateStringBinary(final Token.Type op, final EvaluatorResult left, + final EvaluatorResult right, final Context ctx) { + if (left.type != STRING) { Errors.inst.printError(EK_EVAL_INVSTRING, left.type.toString()); return new Tree<>(FAIL(left)); } - String strang = left.stringVal; + final String strang = left.stringVal; - switch(op) { + switch (op) { case STRCAT: - if(right.type != STRING) { + if (right.type != STRING) { Errors.inst.printError(EK_EVAL_UNSTRING, right.type.toString()); return new Tree<>(FAIL(right)); - } else { - String strung = right.stringVal; - return new Tree<>(new Node(Node.Type.RESULT, - new EvaluatorResult(STRING, strang + strung))); } + + final String strung = right.stringVal; + return new Tree<>(new Node(Node.Type.RESULT, new EvaluatorResult(STRING, strang + strung))); case STRREP: - if(right.type != INT) { + if (right.type != INT) { Errors.inst.printError(EK_EVAL_INVSTRING, right.type.toString()); return new Tree<>(FAIL(right)); - } else { - String res = strang; - long count = right.intVal; - for(long i = 1; i < count; i++) { - res += strang; - } - return new Tree<>(new Node(Node.Type.RESULT, new EvaluatorResult(STRING, res))); } + + String res = strang; + final long count = right.intVal; + for (long i = 1; i < count; i++) { + res += strang; + } + return new Tree<>(new Node(Node.Type.RESULT, new EvaluatorResult(STRING, res))); default: Errors.inst.printError(EK_EVAL_UNSTRING, op.toString()); return new Tree<>(FAIL()); } } - private ITree<Node> evaluateDiceBinary(Token.Type op, EvaluatorResult left, EvaluatorResult right, - @SuppressWarnings("unused") Context ctx) { + private static ITree<Node> evaluateDiceBinary(final Token.Type op, final EvaluatorResult left, + final EvaluatorResult right, final 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()); @@ -336,10 +358,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 { @@ -348,10 +370,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 { @@ -367,44 +389,44 @@ public class Evaluator { return new Tree<>(new Node(Node.Type.RESULT, res)); } - private ITree<Node> evaluateMathBinary(Token.Type op, EvaluatorResult left, EvaluatorResult right, - @SuppressWarnings("unused") Context ctx) { - if(left.type == STRING || right.type == STRING) { + private static ITree<Node> evaluateMathBinary(final Token.Type op, final EvaluatorResult left, + final EvaluatorResult right, final Context ctx) { + if (left.type == STRING || right.type == STRING) { Errors.inst.printError(EK_EVAL_STRINGMATH); return new Tree<>(FAIL()); - } else if(left.type == FAILURE || right.type == FAILURE) + } else if (left.type == FAILURE || right.type == FAILURE) return new Tree<>(FAIL()); - else if(left.type == INT && right.type != INT) { + else if (left.type == INT && right.type != INT) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(right)); - } else if(left.type == FLOAT && right.type != FLOAT) { + } else if (left.type == FLOAT && right.type != FLOAT) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(right)); - } else if(left.type == DICE && right.type != DICE) { + } else if (left.type == DICE && right.type != DICE) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(right)); - } else if(right.type == INT && left.type != INT) { + } else if (right.type == INT && left.type != INT) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(left)); - } else if(right.type == FLOAT && left.type != FLOAT) { + } else if (right.type == FLOAT && left.type != FLOAT) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(left)); - } else if(right.type == DICE && left.type != DICE) { + } else if (right.type == DICE && left.type != DICE) { Errors.inst.printError(EK_EVAL_MISMATH); return new Tree<>(FAIL(left)); } EvaluatorResult res = null; - switch(op) { + switch (op) { case ADD: - if(left.type == INT) { + if (left.type == INT) { res = new EvaluatorResult(INT, left.intVal + right.intVal); - } else if(left.type == DICE) { - if(left.diceVal.isList) { + } else if (left.type == DICE) { + if (left.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, left.toString()); return new Tree<>(FAIL(left)); - } else if(right.diceVal.isList) { + } else if (right.diceVal.isList) { Errors.inst.printError(EK_EVAL_INVDICE, right.toString()); return new Tree<>(FAIL(right)); } @@ -416,13 +438,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)); } @@ -434,13 +456,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)); } @@ -452,15 +474,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 { @@ -472,15 +494,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 { @@ -499,10 +521,10 @@ public class Evaluator { return new Tree<>(new Node(Node.Type.RESULT, res)); } - private ITree<Node> evaluateTokenRef(Token tk, @SuppressWarnings("unused") Context ctx) { + private ITree<Node> evaluateTokenRef(final Token tk, final Context ctx) { EvaluatorResult res = null; - switch(tk.type) { + switch (tk.type) { case INT_LIT: res = new EvaluatorResult(INT, tk.intValue); break; diff --git a/dice-lang/src/bjc/dicelang/EvaluatorResult.java b/dice-lang/src/bjc/dicelang/EvaluatorResult.java index f21cd6f..d81612f 100644 --- a/dice-lang/src/bjc/dicelang/EvaluatorResult.java +++ b/dice-lang/src/bjc/dicelang/EvaluatorResult.java @@ -77,7 +77,7 @@ public class EvaluatorResult { * @param typ * The type of the result. */ - public EvaluatorResult(EvaluatorResult.Type typ) { + public EvaluatorResult(final EvaluatorResult.Type typ) { type = typ; } @@ -90,7 +90,7 @@ public class EvaluatorResult { * @param orig * The original value of the result. */ - public EvaluatorResult(EvaluatorResult.Type typ, ITree<Node> orig) { + public EvaluatorResult(final EvaluatorResult.Type typ, final ITree<Node> orig) { this(typ); origVal = orig; @@ -105,7 +105,7 @@ public class EvaluatorResult { * @param orig * The original value of the result. */ - public EvaluatorResult(EvaluatorResult.Type typ, Node orig) { + public EvaluatorResult(final EvaluatorResult.Type typ, final Node orig) { this(typ, new Tree<>(orig)); } @@ -115,7 +115,7 @@ public class EvaluatorResult { * @param typ * @param orig */ - public EvaluatorResult(EvaluatorResult.Type typ, EvaluatorResult orig) { + public EvaluatorResult(final EvaluatorResult.Type typ, final EvaluatorResult orig) { this(typ, new Node(Node.Type.RESULT, orig)); } @@ -125,7 +125,7 @@ public class EvaluatorResult { * @param typ * @param iVal */ - public EvaluatorResult(EvaluatorResult.Type typ, long iVal) { + public EvaluatorResult(final EvaluatorResult.Type typ, final long iVal) { this(typ); intVal = iVal; @@ -137,7 +137,7 @@ public class EvaluatorResult { * @param typ * @param dVal */ - public EvaluatorResult(EvaluatorResult.Type typ, double dVal) { + public EvaluatorResult(final EvaluatorResult.Type typ, final double dVal) { this(typ); floatVal = dVal; @@ -149,7 +149,7 @@ public class EvaluatorResult { * @param typ * @param dVal */ - public EvaluatorResult(EvaluatorResult.Type typ, DieExpression dVal) { + public EvaluatorResult(final EvaluatorResult.Type typ, final DieExpression dVal) { this(typ); diceVal = dVal; @@ -161,7 +161,7 @@ public class EvaluatorResult { * @param typ * @param dVal */ - public EvaluatorResult(EvaluatorResult.Type typ, Die dVal) { + public EvaluatorResult(final EvaluatorResult.Type typ, final Die dVal) { this(typ); diceVal = new DieExpression(dVal); @@ -173,7 +173,7 @@ public class EvaluatorResult { * @param typ * @param dVal */ - public EvaluatorResult(EvaluatorResult.Type typ, DieList dVal) { + public EvaluatorResult(final EvaluatorResult.Type typ, final DieList dVal) { this(typ); diceVal = new DieExpression(dVal); @@ -185,7 +185,7 @@ public class EvaluatorResult { * @param typ * @param strang */ - public EvaluatorResult(EvaluatorResult.Type typ, String strang) { + public EvaluatorResult(final EvaluatorResult.Type typ, final String strang) { this(typ); stringVal = strang; @@ -193,7 +193,7 @@ public class EvaluatorResult { @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 f58cb14..af26870 100644 --- a/dice-lang/src/bjc/dicelang/Node.java +++ b/dice-lang/src/bjc/dicelang/Node.java @@ -18,29 +18,29 @@ public class Node { public GroupType groupType; public EvaluatorResult resultVal; - public Node(Type typ) { + public Node(final Type typ) { type = typ; } - public Node(Type typ, Token tokenVl) { + public Node(final Type typ, final Token tokenVl) { this(typ); tokenVal = tokenVl; } - public Node(Type typ, Token.Type opType) { + public Node(final Type typ, final Token.Type opType) { this(typ); operatorType = opType; } - public Node(Type typ, GroupType grupType) { + public Node(final Type typ, final GroupType grupType) { this(typ); groupType = grupType; } - public Node(Type typ, EvaluatorResult res) { + public Node(final Type typ, final EvaluatorResult res) { this(typ); resultVal = res; @@ -48,7 +48,7 @@ public class Node { @Override public String toString() { - switch(type) { + switch (type) { case UNARYOP: case BINOP: return "(" + type.name() + " : " + operatorType + ")"; @@ -65,14 +65,14 @@ public class Node { } @Override - public boolean equals(Object other) { - if(!(other instanceof Node)) return false; + public boolean equals(final Object other) { + if (!(other instanceof Node)) return false; - Node otk = (Node) other; + final 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 7907137..1029943 100644 --- a/dice-lang/src/bjc/dicelang/Parser.java +++ b/dice-lang/src/bjc/dicelang/Parser.java @@ -1,16 +1,24 @@ package bjc.dicelang; -import bjc.utils.data.ITree; -import bjc.utils.data.Tree; -import bjc.utils.funcdata.IList; +import static bjc.dicelang.Errors.ErrorKey.EK_PARSE_BINARY; +import static bjc.dicelang.Errors.ErrorKey.EK_PARSE_INVTOKEN; +import static bjc.dicelang.Errors.ErrorKey.EK_PARSE_NOCLOSE; +import static bjc.dicelang.Errors.ErrorKey.EK_PARSE_UNCLOSE; +import static bjc.dicelang.Errors.ErrorKey.EK_PARSE_UNOPERAND; +import static bjc.dicelang.Node.Type.BINOP; +import static bjc.dicelang.Node.Type.GROUP; +import static bjc.dicelang.Node.Type.OGROUP; +import static bjc.dicelang.Node.Type.TOKREF; +import static bjc.dicelang.Node.Type.UNARYOP; +import static bjc.dicelang.Token.Type.CBRACE; +import static bjc.dicelang.Token.Type.CBRACKET; import java.util.Deque; import java.util.LinkedList; -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; +import bjc.utils.data.ITree; +import bjc.utils.data.Tree; +import bjc.utils.funcdata.IList; /** * Parse a series of tree into tokens. @@ -37,19 +45,19 @@ public class Parser { * * @return Whether or not the parse was successful. */ - public boolean parseTokens(IList<Token> tokens, IList<ITree<Node>> results) { - Deque<ITree<Node>> working = new LinkedList<>(); + public static boolean parseTokens(final IList<Token> tokens, final IList<ITree<Node>> results) { + final Deque<ITree<Node>> working = new LinkedList<>(); - for(Token tk : tokens) { - switch(tk.type) { + for (final Token tk : tokens) { + switch (tk.type) { case OBRACKET: case OBRACE: working.push(new Tree<>(new Node(OGROUP, tk))); break; case CBRACKET: case CBRACE: - boolean sc = parseClosingGrouper(working, tk); - if(!sc) return false; + final boolean sc = parseClosingGrouper(working, tk); + if (!sc) return false; break; case MULTIPLY: case DIVIDE: @@ -61,54 +69,38 @@ 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 { - ITree<Node> right = working.pop(); - ITree<Node> left = working.pop(); - - ITree<Node> opNode = new Tree<>(new Node(BINOP, tk.type)); - - opNode.addChild(left); - opNode.addChild(right); - - working.push(opNode); } + + handleBinaryNode(working, tk); 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) { - ITree<Node> operand = working.pop(); + } else if (working.size() == 1) { + final ITree<Node> operand = working.pop(); - ITree<Node> opNode = new Tree<>(new Node(UNARYOP, tk.type)); + final ITree<Node> opNode = new Tree<>(new Node(UNARYOP, tk.type)); opNode.addChild(operand); working.push(opNode); } else { - ITree<Node> right = working.pop(); - ITree<Node> left = working.pop(); - - ITree<Node> opNode = new Tree<>(new Node(BINOP, tk.type)); - - opNode.addChild(left); - opNode.addChild(right); - - working.push(opNode); + handleBinaryNode(working, tk); } break; case COERCE: case DICESCALAR: case DICEFUDGE: - if(working.size() == 0) { + if (working.size() == 0) { Errors.inst.printError(EK_PARSE_UNOPERAND, tk.toString()); } else { - ITree<Node> operand = working.pop(); - ITree<Node> opNode = new Tree<>(new Node(UNARYOP, tk.type)); + final ITree<Node> operand = working.pop(); + final ITree<Node> opNode = new Tree<>(new Node(UNARYOP, tk.type)); opNode.addChild(operand); @@ -128,21 +120,33 @@ public class Parser { } } - for(ITree<Node> ast : working) { + for (final ITree<Node> ast : working) { results.add(ast); } return true; } - private boolean parseClosingGrouper(Deque<ITree<Node>> working, Token tk) { - if(working.size() == 0) { + private static void handleBinaryNode(final Deque<ITree<Node>> working, final Token tk) { + final ITree<Node> right = working.pop(); + final ITree<Node> left = working.pop(); + + final ITree<Node> opNode = new Tree<>(new Node(BINOP, tk.type)); + + opNode.addChild(left); + opNode.addChild(right); + + working.push(opNode); + } + + private static boolean parseClosingGrouper(final Deque<ITree<Node>> working, final Token tk) { + if (working.size() == 0) { Errors.inst.printError(EK_PARSE_NOCLOSE); return false; } ITree<Node> groupNode = null; - switch(tk.type) { + switch (tk.type) { case CBRACE: groupNode = new Tree<>(new Node(GROUP, Node.GroupType.CODE)); break; @@ -155,41 +159,41 @@ 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<Node> matchNode = new Tree<>(new Node(OGROUP, matching)); - if(!working.contains(matchNode)) { + final ITree<Node> matchNode = new Tree<>(new Node(OGROUP, matching)); + if (!working.contains(matchNode)) { Errors.inst.printError(EK_PARSE_UNCLOSE, tk.toString(), matchNode.toString()); System.out.println("\tCurrent forest is: "); int treeNo = 1; - for(ITree<Node> ast : working) { + for (final ITree<Node> ast : working) { System.out.println("Tree " + treeNo++ + ": " + ast.toString()); } return false; - } else { - Deque<ITree<Node>> childs = new LinkedList<>(); + } - while(!working.peek().equals(matchNode)) { - childs.push(working.pop()); - } + final Deque<ITree<Node>> childs = new LinkedList<>(); - // Discard opener - working.pop(); + while (!working.peek().equals(matchNode)) { + childs.push(working.pop()); + } - for(ITree<Node> child : childs) { - groupNode.addChild(child); - } + // Discard opener + working.pop(); - working.push(groupNode); + for (final ITree<Node> child : childs) { + groupNode.addChild(child); } + working.push(groupNode); + return true; } } diff --git a/dice-lang/src/bjc/dicelang/Shunter.java b/dice-lang/src/bjc/dicelang/Shunter.java index 5ac4614..ffe730b 100644 --- a/dice-lang/src/bjc/dicelang/Shunter.java +++ b/dice-lang/src/bjc/dicelang/Shunter.java @@ -1,17 +1,41 @@ package bjc.dicelang; -import bjc.utils.funcdata.FunctionalList; -import bjc.utils.funcdata.FunctionalMap; -import bjc.utils.funcdata.IList; -import bjc.utils.funcdata.IMap; +import static bjc.dicelang.Errors.ErrorKey.EK_SHUNT_INVSEP; +import static bjc.dicelang.Errors.ErrorKey.EK_SHUNT_NOGROUP; +import static bjc.dicelang.Errors.ErrorKey.EK_SHUNT_NOTADJ; +import static bjc.dicelang.Errors.ErrorKey.EK_SHUNT_NOTADV; +import static bjc.dicelang.Errors.ErrorKey.EK_SHUNT_NOTASSOC; +import static bjc.dicelang.Token.Type.ADD; +import static bjc.dicelang.Token.Type.BIND; +import static bjc.dicelang.Token.Type.CBRACE; +import static bjc.dicelang.Token.Type.COERCE; +import static bjc.dicelang.Token.Type.CPAREN; +import static bjc.dicelang.Token.Type.DICECONCAT; +import static bjc.dicelang.Token.Type.DICEGROUP; +import static bjc.dicelang.Token.Type.DICELIST; +import static bjc.dicelang.Token.Type.DIVIDE; +import static bjc.dicelang.Token.Type.GROUPSEP; +import static bjc.dicelang.Token.Type.IDIVIDE; +import static bjc.dicelang.Token.Type.LET; +import static bjc.dicelang.Token.Type.MULTIPLY; +import static bjc.dicelang.Token.Type.OBRACE; +import static bjc.dicelang.Token.Type.OPAREN; +import static bjc.dicelang.Token.Type.STRCAT; +import static bjc.dicelang.Token.Type.STRREP; +import static bjc.dicelang.Token.Type.SUBTRACT; +import static bjc.dicelang.Token.Type.TAGOP; +import static bjc.dicelang.Token.Type.TAGOPR; +import static bjc.dicelang.Token.Type.TOKGROUP; 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.*; +import bjc.utils.funcdata.FunctionalList; +import bjc.utils.funcdata.FunctionalMap; +import bjc.utils.funcdata.IList; +import bjc.utils.funcdata.IMap; /** * Shunt a set of infix tokens to postfix tokens. @@ -110,61 +134,61 @@ public class Shunter { * * @return Whether or not the shunt succeeded. */ - public boolean shuntTokens(IList<Token> tks, IList<Token> returned) { - Deque<Token> opStack = new LinkedList<>(); - Deque<Token> unaryOps = new LinkedList<>(); + public boolean shuntTokens(final IList<Token> tks, final IList<Token> returned) { + final Deque<Token> opStack = new LinkedList<>(); + final Deque<Token> unaryOps = new LinkedList<>(); - Deque<Token> currReturned = new LinkedList<>(); + final Deque<Token> currReturned = new LinkedList<>(); - Deque<Token> feed = new LinkedList<>(); + final Deque<Token> feed = new LinkedList<>(); - for(Token tk : tks.toIterable()) { + for (final 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 (final Token tk : currReturned) { returned.add(tk); } return true; } - private boolean shuntToken(Token tk, Deque<Token> opStack, Deque<Token> unaryStack, Deque<Token> currReturned, - @SuppressWarnings("unused") Deque<Token> feed) { - if(unaryStack.size() != 0) { - if(isUnary(tk)) { + private boolean shuntToken(final Token tk, final Deque<Token> opStack, final Deque<Token> unaryStack, + final Deque<Token> currReturned, final Deque<Token> feed) { + if (unaryStack.size() != 0) { + if (isUnary(tk)) { unaryStack.add(tk); return true; } - Token unaryOp = unaryStack.pop(); + final Token unaryOp = unaryStack.pop(); - Token.Type unaryType = unaryOp.type; + final 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); + final Token newTok = new Token(TAGOPR); - if(tk.type == TAGOP) { + if (tk.type == TAGOP) { newTok.tokenValues = tk.tokenValues; } else { newTok.tokenValues = new FunctionalList<>(tk); @@ -174,15 +198,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); + final Token newTok = new Token(TAGOPR); - if(tk.type == TAGOP) { + if (tk.type == TAGOP) { newTok.tokenValues = tk.tokenValues; } else { newTok.tokenValues = new FunctionalList<>(tk); @@ -195,14 +219,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())) { - Token newOp = opStack.pop(); + } else if (isOp(tk)) { + while (!opStack.isEmpty() && isHigherPrec(tk, opStack.peek())) { + final 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()); } @@ -210,16 +234,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; @@ -231,32 +255,32 @@ public class Shunter { return false; } - 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) { - IList<Token> group = new FunctionalList<>(); + } else if (tk.type == GROUPSEP) { + final IList<Token> group = new FunctionalList<>(); - while(currReturned.size() != 0 && !currReturned.peek().isGrouper()) { + while (currReturned.size() != 0 && !currReturned.peek().isGrouper()) { group.add(currReturned.pop()); } - while(opStack.size() != 0 && !opStack.peek().isGrouper()) { + while (opStack.size() != 0 && !opStack.peek().isGrouper()) { group.add(opStack.pop()); } - if(currReturned.size() == 0) { + if (currReturned.size() == 0) { Errors.inst.printError(EK_SHUNT_INVSEP); return false; } @@ -269,58 +293,57 @@ public class Shunter { return true; } - private boolean isHigherPrec(Token lft, Token rght) { - Token.Type left = lft.type; - Token.Type right = rght.type; + private boolean isHigherPrec(final Token lft, final Token rght) { + final Token.Type left = lft.type; + final Token.Type right = rght.type; 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)) - return rightPrecedence > leftPrecedence; - else - return rightPrecedence >= leftPrecedence; + if (rightAssoc.contains(left)) return rightPrecedence > leftPrecedence; + + return rightPrecedence >= leftPrecedence; } - private boolean isOp(Token tk) { - Token.Type ty = tk.type; + private boolean isOp(final Token tk) { + final Token.Type ty = tk.type; - if(ops.containsKey(ty)) return true; - if(unaryAdjectives.contains(ty)) return true; - if(unaryAdverbs.contains(ty)) return true; - if(unaryGerunds.contains(ty)) return true; - if(ty == TAGOPR) return true; + if (ops.containsKey(ty)) return true; + if (unaryAdjectives.contains(ty)) return true; + if (unaryAdverbs.contains(ty)) return true; + if (unaryGerunds.contains(ty)) return true; + if (ty == TAGOPR) return true; return false; } - private boolean isUnary(Token tk) { - Token.Type ty = tk.type; + private boolean isUnary(final Token tk) { + final 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 1e5f356..22df90b 100644 --- a/dice-lang/src/bjc/dicelang/Token.java +++ b/dice-lang/src/bjc/dicelang/Token.java @@ -45,29 +45,29 @@ public class Token { // TAG* (the tagged construct) public IList<Token> tokenValues; - public Token(Type typ) { + public Token(final Type typ) { type = typ; } - public Token(Type typ, long val) { + public Token(final Type typ, final long val) { this(typ); intValue = val; } - public Token(Type typ, double val) { + public Token(final Type typ, final double val) { this(typ); floatValue = val; } - public Token(Type typ, DieExpression val) { + public Token(final Type typ, final DieExpression val) { this(typ); diceValue = val; } - public Token(Type typ, IList<Token> tkVals) { + public Token(final Type typ, final IList<Token> tkVals) { this(typ); tokenValues = tkVals; @@ -75,7 +75,7 @@ public class Token { @Override public String toString() { - switch(type) { + switch (type) { case INT_LIT: case STRING_LIT: case VREF: @@ -100,14 +100,14 @@ public class Token { } @Override - public boolean equals(Object other) { - if(!(other instanceof Token)) return false; + public boolean equals(final Object other) { + if (!(other instanceof Token)) return false; - Token otk = (Token) other; + final 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; @@ -117,7 +117,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 8c1d53b..3ca9a94 100644 --- a/dice-lang/src/bjc/dicelang/Tokenizer.java +++ b/dice-lang/src/bjc/dicelang/Tokenizer.java @@ -1,29 +1,55 @@ package bjc.dicelang; +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.ADD; +import static bjc.dicelang.Token.Type.BIND; +import static bjc.dicelang.Token.Type.CBRACE; +import static bjc.dicelang.Token.Type.CBRACKET; +import static bjc.dicelang.Token.Type.COERCE; +import static bjc.dicelang.Token.Type.CPAREN; +import static bjc.dicelang.Token.Type.DICECONCAT; +import static bjc.dicelang.Token.Type.DICEFUDGE; +import static bjc.dicelang.Token.Type.DICEGROUP; +import static bjc.dicelang.Token.Type.DICELIST; +import static bjc.dicelang.Token.Type.DICESCALAR; +import static bjc.dicelang.Token.Type.DICE_LIT; +import static bjc.dicelang.Token.Type.DIVIDE; +import static bjc.dicelang.Token.Type.FLOAT_LIT; +import static bjc.dicelang.Token.Type.GROUPSEP; +import static bjc.dicelang.Token.Type.IDIVIDE; +import static bjc.dicelang.Token.Type.INT_LIT; +import static bjc.dicelang.Token.Type.LET; +import static bjc.dicelang.Token.Type.MULTIPLY; +import static bjc.dicelang.Token.Type.OBRACE; +import static bjc.dicelang.Token.Type.OBRACKET; +import static bjc.dicelang.Token.Type.OPAREN; +import static bjc.dicelang.Token.Type.STRCAT; +import static bjc.dicelang.Token.Type.STRING_LIT; +import static bjc.dicelang.Token.Type.STRREP; +import static bjc.dicelang.Token.Type.SUBTRACT; +import static bjc.dicelang.Token.Type.VREF; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; + import bjc.dicelang.dice.DiceBox; import bjc.utils.funcdata.FunctionalMap; import bjc.utils.funcdata.IMap; import bjc.utils.funcutils.StringUtils; import bjc.utils.parserutils.TokenUtils; -import java.util.regex.Matcher; -import java.util.regex.Pattern; - -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.*; - @SuppressWarnings("javadoc") public class Tokenizer { // Literal tokens for tokenization - private IMap<String, Token.Type> litTokens; + private final IMap<String, Token.Type> litTokens; - private DiceLangEngine eng; + private final DiceLangEngine eng; private int nextSym = 0; - public Tokenizer(DiceLangEngine engine) { + public Tokenizer(final DiceLangEngine engine) { eng = engine; litTokens = new FunctionalMap<>(); @@ -46,15 +72,15 @@ public class Tokenizer { litTokens.put("crc", COERCE); } - public Token lexToken(String token, IMap<String, String> stringLts) { - if(token.equals("")) return null; + public Token lexToken(final String token, final IMap<String, String> stringLts) { + 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 '[': @@ -71,11 +97,11 @@ public class Tokenizer { return tk; } - private Token tokenizeGrouping(String token) { + private static Token tokenizeGrouping(final 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; @@ -103,44 +129,44 @@ 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 final Pattern hexadecimalMatcher = Pattern.compile("\\A[\\-\\+]?0x[0-9A-Fa-f]+\\Z"); + private final Pattern flexadecimalMatcher = Pattern.compile("\\A[\\-\\+]?[0-9][0-9A-Za-z]+B\\d{1,2}\\Z"); + private final Pattern stringLitMatcher = Pattern.compile("\\AstringLiteral(\\d+)\\Z"); - private Token tokenizeLiteral(String token, IMap<String, String> stringLts) { + private Token tokenizeLiteral(final String token, final IMap<String, String> stringLts) { Token tk = Token.NIL_TOKEN; - if(TokenUtils.isInt(token)) { + if (TokenUtils.isInt(token)) { tk = new Token(INT_LIT, Long.parseLong(token)); - } else if(hexadecimalMatcher.matcher(token).matches()) { - String newToken = token.substring(0, 1) + token.substring(token.indexOf('x')); + } else if (hexadecimalMatcher.matcher(token).matches()) { + final 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()) { - int parseBase = Integer.parseInt(token.substring(token.lastIndexOf('B') + 1)); + } else if (flexadecimalMatcher.matcher(token).matches()) { + final 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; } - String flexNum = token.substring(0, token.lastIndexOf('B')); + final String flexNum = token.substring(0, token.lastIndexOf('B')); try { tk = new Token(INT_LIT, Long.parseLong(flexNum, parseBase)); - } catch(@SuppressWarnings("unused") NumberFormatException nfex) { + } catch (final NumberFormatException nfex) { Errors.inst.printError(EK_TOK_INVFLEX, flexNum, Integer.toString(parseBase)); return Token.NIL_TOKEN; } - } else if(TokenUtils.isDouble(token)) { + } else if (TokenUtils.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); + final Matcher stringLit = stringLitMatcher.matcher(token); - if(stringLit.matches()) { - int litNum = Integer.parseInt(stringLit.group(1)); + if (stringLit.matches()) { + final int litNum = Integer.parseInt(stringLit.group(1)); eng.addStringLiteral(litNum, stringLts.get(token)); tk = new Token(STRING_LIT, litNum); diff --git a/dice-lang/src/bjc/dicelang/dice/CompoundDie.java b/dice-lang/src/bjc/dicelang/dice/CompoundDie.java index adbd102..7cd8fcf 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 final Die left;
+ private final Die right;
/**
* Create a new compound die.
@@ -20,7 +20,7 @@ public class CompoundDie implements Die { * @param rght
* The right die
*/
- public CompoundDie(Die lft, Die rght) {
+ public CompoundDie(final Die lft, final Die rght) {
left = lft;
right = rght;
}
diff --git a/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java b/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java index a25696a..73d910a 100644 --- a/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java +++ b/dice-lang/src/bjc/dicelang/dice/CompoundingDie.java @@ -11,10 +11,10 @@ import java.util.function.Predicate; * @author Ben Culkin
*/
public class CompoundingDie implements Die {
- private Die source;
+ private final Die source;
- private Predicate<Long> compoundOn;
- private String compoundPattern;
+ private final Predicate<Long> compoundOn;
+ private final String compoundPattern;
/**
* Create a new compounding die with no pattern.
@@ -24,7 +24,7 @@ public class CompoundingDie implements Die { * @param compound
* The conditions to compound on
*/
- public CompoundingDie(Die src, Predicate<Long> compound) {
+ public CompoundingDie(final Die src, final Predicate<Long> compound) {
this(src, compound, null);
}
@@ -39,7 +39,7 @@ public class CompoundingDie implements Die { * The string pattern the condition came from, for
* printing
*/
- public CompoundingDie(Die src, Predicate<Long> compound, String patt) {
+ public CompoundingDie(final Die src, final Predicate<Long> compound, final String patt) {
source = src;
compoundOn = compound;
@@ -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,9 +89,8 @@ public class CompoundingDie implements Die { @Override
public String toString() {
- if(compoundPattern == null)
- return source + "!!";
- else
- return source + "!!" + compoundPattern;
+ if (compoundPattern == null) return source + "!!";
+
+ return source + "!!" + compoundPattern;
}
}
diff --git a/dice-lang/src/bjc/dicelang/dice/DiceBox.java b/dice-lang/src/bjc/dicelang/dice/DiceBox.java index 168dda1..c956977 100644 --- a/dice-lang/src/bjc/dicelang/dice/DiceBox.java +++ b/dice-lang/src/bjc/dicelang/dice/DiceBox.java @@ -20,97 +20,97 @@ public class DiceBox { * * @return The die expression from the string, or null if it wasn't one */ - public static DieExpression parseExpression(String expString) { + public static DieExpression parseExpression(final String expString) { /* * Only bother with valid expressions. */ - if(!isValidExpression(expString)) return null; + if (!isValidExpression(expString)) return null; - if(scalarDiePattern.matcher(expString).matches()) { + if (scalarDiePattern.matcher(expString).matches()) { /* * Parse scalar die. */ - String dieString = expString.substring(0, expString.indexOf('s')); - Die scal = new ScalarDie(Long.parseLong(dieString)); + final String dieString = expString.substring(0, expString.indexOf('s')); + final Die scal = new ScalarDie(Long.parseLong(dieString)); return new DieExpression(scal); - } else if(simpleDiePattern.matcher(expString).matches()) { + } else if (simpleDiePattern.matcher(expString).matches()) { /* * Parse simple die groups. */ - String[] dieParts = expString.split("d"); + final String[] dieParts = expString.split("d"); - long right = Long.parseLong(dieParts[1]); - if(dieParts[0].equals("")) { + final long right = Long.parseLong(dieParts[1]); + if (dieParts[0].equals("")) { /* * Handle short-form expressions. */ - Die scal = new SimpleDie(1, right); - return new DieExpression(scal); - } else { - Die scal = new SimpleDie(Long.parseLong(dieParts[0]), right); + final Die scal = new SimpleDie(1, right); return new DieExpression(scal); } - } else if(fudgeDiePattern.matcher(expString).matches()) { + + final Die scal = new SimpleDie(Long.parseLong(dieParts[0]), right); + return new DieExpression(scal); + } else if (fudgeDiePattern.matcher(expString).matches()) { /* * Parse fudge dice. */ - String nDice = expString.substring(0, expString.indexOf('d')); + final String nDice = expString.substring(0, expString.indexOf('d')); return new DieExpression(new FudgeDie(Long.parseLong(nDice))); - } else if(compoundDiePattern.matcher(expString).matches()) { + } else if (compoundDiePattern.matcher(expString).matches()) { /* * Parse compound die expressions. */ - String[] dieParts = expString.split("c"); + final String[] dieParts = expString.split("c"); - DieExpression left = parseExpression(dieParts[0]); - DieExpression right = parseExpression(dieParts[1]); + final DieExpression left = parseExpression(dieParts[0]); + final DieExpression right = parseExpression(dieParts[1]); return new DieExpression(new CompoundDie(left.scalar, right.scalar)); - } else if(compoundingDiePattern.matcher(expString).matches()) { + } else if (compoundingDiePattern.matcher(expString).matches()) { /* * Parse compounding die expressions. */ - String[] dieParts = expString.split("!!"); + final String[] dieParts = expString.split("!!"); - DieExpression left = parseExpression(dieParts[0]); - Predicate<Long> right = deriveCond(dieParts[1]); + final DieExpression left = parseExpression(dieParts[0]); + final Predicate<Long> right = deriveCond(dieParts[1]); - Die scal = new CompoundingDie(left.scalar, right, dieParts[1]); + final Die scal = new CompoundingDie(left.scalar, right, dieParts[1]); return new DieExpression(scal); - } else if(explodingDiePattern.matcher(expString).matches()) { + } else if (explodingDiePattern.matcher(expString).matches()) { /* * Parse exploding die expressions. */ - String[] dieParts = expString.split("!"); + final String[] dieParts = expString.split("!"); - DieExpression left = parseExpression(dieParts[0]); - Predicate<Long> right = deriveCond(dieParts[1]); + final DieExpression left = parseExpression(dieParts[0]); + final Predicate<Long> right = deriveCond(dieParts[1]); - DieList lst = new ExplodingDice(left.scalar, right, dieParts[1], false); + final DieList lst = new ExplodingDice(left.scalar, right, dieParts[1], false); return new DieExpression(lst); - } else if(penetratingDiePattern.matcher(expString).matches()) { + } else if (penetratingDiePattern.matcher(expString).matches()) { /* * Parse penetrating die expressions. */ - String[] dieParts = expString.split("p!"); + final String[] dieParts = expString.split("p!"); - DieExpression left = parseExpression(dieParts[0]); - Predicate<Long> right = deriveCond(dieParts[1]); + final DieExpression left = parseExpression(dieParts[0]); + final Predicate<Long> right = deriveCond(dieParts[1]); - DieList lst = new ExplodingDice(left.scalar, right, dieParts[1], true); + final DieList lst = new ExplodingDice(left.scalar, right, dieParts[1], true); return new DieExpression(lst); - } else if(diceListPattern.matcher(expString).matches()) { + } else if (diceListPattern.matcher(expString).matches()) { /* * Parse simple die lists. */ - String[] dieParts = expString.split("dl"); + final String[] dieParts = expString.split("dl"); - DieExpression left = parseExpression(dieParts[0]); - DieExpression right = parseExpression(dieParts[1]); + final DieExpression left = parseExpression(dieParts[0]); + final DieExpression right = parseExpression(dieParts[1]); - DieList lst = new SimpleDieList(left.scalar, right.scalar); + final DieList lst = new SimpleDieList(left.scalar, right.scalar); return new DieExpression(lst); } @@ -210,34 +210,33 @@ public class DiceBox { * * @return Whether or not the string is a valid command. */ - public static boolean isValidExpression(String exp) { - if(scalarDiePattern.matcher(exp).matches()) + public static boolean isValidExpression(final String exp) { + 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 - return false; + else return false; } /* * Derive a predicate from a compare point */ - private static Predicate<Long> deriveCond(String patt) { - long num = Long.parseLong(patt.substring(1)); + private static Predicate<Long> deriveCond(final String patt) { + final 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/DieExpression.java b/dice-lang/src/bjc/dicelang/dice/DieExpression.java index a8d793a..b114da6 100644 --- a/dice-lang/src/bjc/dicelang/dice/DieExpression.java +++ b/dice-lang/src/bjc/dicelang/dice/DieExpression.java @@ -28,7 +28,7 @@ public class DieExpression { * @param scal * The scalar value of this expression. */ - public DieExpression(Die scal) { + public DieExpression(final Die scal) { isList = false; scalar = scal; } @@ -39,17 +39,16 @@ public class DieExpression { * @param lst * The list value of this expression. */ - public DieExpression(DieList lst) { + public DieExpression(final DieList lst) { isList = true; list = lst; } @Override public String toString() { - if(isList) - return list.toString(); - else - return scalar.toString(); + if (isList) return list.toString(); + + return scalar.toString(); } /** @@ -58,9 +57,8 @@ public class DieExpression { * @return The value of the expression as a string. */ public String value() { - if(isList) - return Arrays.toString(list.roll()); - else - return Long.toString(scalar.roll()); + if (isList) return Arrays.toString(list.roll()); + + 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 928ae25..15d6572 100644 --- a/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java +++ b/dice-lang/src/bjc/dicelang/dice/ExplodingDice.java @@ -16,14 +16,14 @@ public class ExplodingDice implements DieList { /*
* The source die to use.
*/
- private Die source;
+ private final Die source;
/*
* The conditions for exploding.
*/
- private Predicate<Long> explodeOn;
- private String explodePattern;
- private boolean explodePenetrates;
+ private final Predicate<Long> explodeOn;
+ private final String explodePattern;
+ private final boolean explodePenetrates;
/**
* Create a new exploding die.
@@ -33,7 +33,7 @@ public class ExplodingDice implements DieList { * @param explode
* The condition to explode on.
*/
- public ExplodingDice(Die src, Predicate<Long> explode) {
+ public ExplodingDice(final Die src, final Predicate<Long> explode) {
this(src, explode, null, false);
}
@@ -48,7 +48,7 @@ public class ExplodingDice implements DieList { * Whether or not for explosions to penetrate (-1 to
* exploded die).
*/
- public ExplodingDice(Die src, Predicate<Long> explode, boolean penetrate) {
+ public ExplodingDice(final Die src, final Predicate<Long> explode, final boolean penetrate) {
this(src, explode, null, penetrate);
}
@@ -65,7 +65,7 @@ public class ExplodingDice implements DieList { * @param patt
* The string the condition came from, for printing.
*/
- public ExplodingDice(Die src, Predicate<Long> explode, String patt, boolean penetrate) {
+ public ExplodingDice(final Die src, final Predicate<Long> explode, final String patt, final boolean penetrate) {
source = src;
explodeOn = explode;
explodePattern = patt;
@@ -84,25 +84,25 @@ public class ExplodingDice implements DieList { @Override
public long[] roll() {
- long res = source.roll();
+ final long res = source.roll();
long oldRes = res;
- List<Long> resList = new LinkedList<>();
+ final List<Long> resList = new LinkedList<>();
- while(explodeOn.test(oldRes)) {
+ while (explodeOn.test(oldRes)) {
oldRes = source.rollSingle();
- if(explodePenetrates) {
+ if (explodePenetrates) {
oldRes -= 1;
}
resList.add(oldRes);
}
- long[] newRes = new long[resList.size() + 1];
+ final long[] newRes = new long[resList.size() + 1];
newRes[0] = res;
int i = 1;
- for(long rll : resList) {
+ for (final long rll : resList) {
newRes[i] = rll;
i += 1;
}
@@ -112,9 +112,8 @@ public class ExplodingDice implements DieList { @Override
public String toString() {
- if(explodePattern == null)
- return source + (explodePenetrates ? "p" : "") + "!";
- else
- return source + (explodePenetrates ? "p" : "") + "!" + explodePattern;
+ if (explodePattern == null) return source + (explodePenetrates ? "p" : "") + "!";
+
+ 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 2064a39..9457b58 100644 --- a/dice-lang/src/bjc/dicelang/dice/FudgeDie.java +++ b/dice-lang/src/bjc/dicelang/dice/FudgeDie.java @@ -7,7 +7,7 @@ package bjc.dicelang.dice; * */ public class FudgeDie implements Die { - private Die numDice; + private final Die numDice; /** * Create a new fudge die. @@ -15,7 +15,7 @@ public class FudgeDie implements Die { * @param nDice * The number of dice to roll. */ - public FudgeDie(long nDice) { + public FudgeDie(final long nDice) { numDice = new ScalarDie(nDice); } @@ -25,7 +25,7 @@ public class FudgeDie implements Die { * @param nDice * The number of dice to roll. */ - public FudgeDie(Die nDice) { + public FudgeDie(final Die nDice) { numDice = nDice; } @@ -43,9 +43,9 @@ public class FudgeDie implements Die { public long roll() { long res = 0; - long nDice = numDice.roll(); + final long nDice = numDice.roll(); - for(int i = 0; i < nDice; i++) { + for (int i = 0; i < nDice; i++) { res += rollSingle(); } diff --git a/dice-lang/src/bjc/dicelang/dice/MathDie.java b/dice-lang/src/bjc/dicelang/dice/MathDie.java index 07150cb..5feb193 100644 --- a/dice-lang/src/bjc/dicelang/dice/MathDie.java +++ b/dice-lang/src/bjc/dicelang/dice/MathDie.java @@ -29,7 +29,7 @@ public class MathDie implements Die { @Override public String toString() { - switch(this) { + switch (this) { case ADD: return "+"; case SUBTRACT: @@ -42,10 +42,10 @@ public class MathDie implements Die { } } - private MathDie.MathOp type; + private final MathDie.MathOp type; - private Die left; - private Die right; + private final Die left; + private final Die right; /** * Create a new math die. @@ -59,7 +59,7 @@ public class MathDie implements Die { * @param rght * The right operand. */ - public MathDie(MathDie.MathOp op, Die lft, Die rght) { + public MathDie(final MathDie.MathOp op, final Die lft, final Die rght) { type = op; left = lft; @@ -71,8 +71,8 @@ public class MathDie implements Die { return left.canOptimize() && right.canOptimize(); } - private long performOp(long lft, long rght) { - switch(type) { + private long performOp(final long lft, final long rght) { + switch (type) { case ADD: return lft + rght; case SUBTRACT: @@ -86,24 +86,24 @@ public class MathDie implements Die { @Override public long optimize() { - long lft = left.optimize(); - long rght = right.optimize(); + final long lft = left.optimize(); + final long rght = right.optimize(); return performOp(lft, rght); } @Override public long roll() { - long lft = left.roll(); - long rght = right.roll(); + final long lft = left.roll(); + final long rght = right.roll(); return performOp(lft, rght); } @Override public long rollSingle() { - long lft = left.rollSingle(); - long rght = right.rollSingle(); + final long lft = left.rollSingle(); + final long rght = right.rollSingle(); return performOp(lft, rght); } diff --git a/dice-lang/src/bjc/dicelang/dice/ScalarDie.java b/dice-lang/src/bjc/dicelang/dice/ScalarDie.java index 3fed00c..e7b5afa 100644 --- a/dice-lang/src/bjc/dicelang/dice/ScalarDie.java +++ b/dice-lang/src/bjc/dicelang/dice/ScalarDie.java @@ -7,7 +7,7 @@ package bjc.dicelang.dice; * */ public class ScalarDie implements Die { - private long val; + private final long val; /** * Create a new scalar die with a set value. @@ -15,7 +15,7 @@ public class ScalarDie implements Die { * @param vl * The value to use. */ - public ScalarDie(long vl) { + public ScalarDie(final long vl) { val = vl; } diff --git a/dice-lang/src/bjc/dicelang/dice/SimpleDie.java b/dice-lang/src/bjc/dicelang/dice/SimpleDie.java index 35921d0..5610535 100644 --- a/dice-lang/src/bjc/dicelang/dice/SimpleDie.java +++ b/dice-lang/src/bjc/dicelang/dice/SimpleDie.java @@ -7,8 +7,8 @@ package bjc.dicelang.dice; * */ public class SimpleDie implements Die { - private Die numDice; - private Die diceSize; + private final Die numDice; + private final Die diceSize; /** * Create a new dice group. @@ -19,7 +19,7 @@ public class SimpleDie implements Die { * @param size * The size of the dice. */ - public SimpleDie(long nDice, long size) { + public SimpleDie(final long nDice, final long size) { this(new ScalarDie(nDice), new ScalarDie(size)); } @@ -32,7 +32,7 @@ public class SimpleDie implements Die { * @param size * The size of the dice. */ - public SimpleDie(Die nDice, long size) { + public SimpleDie(final Die nDice, final long size) { this(nDice, new ScalarDie(size)); } @@ -45,7 +45,7 @@ public class SimpleDie implements Die { * @param size * The size of the dice. */ - public SimpleDie(long nDice, Die size) { + public SimpleDie(final long nDice, final Die size) { this(new ScalarDie(nDice), size); } @@ -58,37 +58,35 @@ public class SimpleDie implements Die { * @param size * The size of the dice. */ - public SimpleDie(Die nDice, Die size) { + public SimpleDie(final Die nDice, final Die size) { numDice = nDice; diceSize = size; } @Override public boolean canOptimize() { - if(diceSize.canOptimize() && diceSize.optimize() <= 1) - return numDice.canOptimize(); - else - return false; + if (diceSize.canOptimize() && diceSize.optimize() <= 1) return numDice.canOptimize(); + + return false; } @Override public long optimize() { - long optSize = diceSize.optimize(); + final long optSize = diceSize.optimize(); + + if (optSize == 0) return 0; - if(optSize == 0) - return 0; - else - return numDice.optimize(); + return numDice.optimize(); } @Override public long roll() { long total = 0; - long nDice = numDice.roll(); - long dSize = diceSize.roll(); + final long nDice = numDice.roll(); + final long dSize = diceSize.roll(); - for(int i = 0; i < nDice; i++) { + for (int i = 0; i < nDice; i++) { total += Math.abs(DiceBox.rng.nextLong()) % dSize + 1; } diff --git a/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java b/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java index 7b1ac76..f382361 100644 --- a/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java +++ b/dice-lang/src/bjc/dicelang/dice/SimpleDieList.java @@ -7,8 +7,8 @@ package bjc.dicelang.dice; * */ public class SimpleDieList implements DieList { - private Die numDice; - private Die size; + private final Die numDice; + private final Die size; /** * Create a new list of dice. @@ -19,27 +19,26 @@ public class SimpleDieList implements DieList { * @param sze * The size of dice in the list. */ - public SimpleDieList(Die nDice, Die sze) { + public SimpleDieList(final Die nDice, final Die sze) { numDice = nDice; size = sze; } @Override public boolean canOptimize() { - if(size.canOptimize() && size.optimize() <= 1) - return numDice.canOptimize(); - else - return false; + if (size.canOptimize() && size.optimize() <= 1) return numDice.canOptimize(); + + return false; } @Override public long[] optimize() { - int sze = (int) numDice.optimize(); - long res = size.optimize(); + final int sze = (int) numDice.optimize(); + final long res = size.optimize(); - long[] ret = new long[sze]; + final long[] ret = new long[sze]; - for(int i = 0; i < sze; i++) { + for (int i = 0; i < sze; i++) { ret[i] = res; } @@ -48,11 +47,11 @@ public class SimpleDieList implements DieList { @Override public long[] roll() { - int num = (int) numDice.roll(); + final int num = (int) numDice.roll(); - long[] ret = new long[num]; + final long[] ret = new long[num]; - for(int i = 0; i < num; i++) { + for (int i = 0; i < num; i++) { ret[i] = size.roll(); } diff --git a/dice-lang/src/bjc/dicelang/expr/Lexer.java b/dice-lang/src/bjc/dicelang/expr/Lexer.java index 52be56c..bac866b 100644 --- a/dice-lang/src/bjc/dicelang/expr/Lexer.java +++ b/dice-lang/src/bjc/dicelang/expr/Lexer.java @@ -1,11 +1,11 @@ package bjc.dicelang.expr; -import bjc.utils.funcdata.IList; -import bjc.utils.parserutils.splitter.ConfigurableTokenSplitter; - import java.util.LinkedList; import java.util.List; +import bjc.utils.funcdata.IList; +import bjc.utils.parserutils.splitter.ConfigurableTokenSplitter; + /** * Implements the lexer for simple expression operations. * @@ -15,7 +15,7 @@ public class Lexer { /* * Splitter we use. */ - private ConfigurableTokenSplitter split; + private final ConfigurableTokenSplitter split; /** * Create a new expression lexer. @@ -38,14 +38,14 @@ public class Lexer { * * @return A series of infix tokens representing the command. */ - public Token[] lexString(String inp, Tokens tks) { - String[] spacedTokens = inp.split("[ \t]"); + public Token[] lexString(final String inp, final Tokens tks) { + final String[] spacedTokens = inp.split("[ \t]"); - List<Token> tokens = new LinkedList<>(); + final List<Token> tokens = new LinkedList<>(); - for(String spacedToken : spacedTokens) { - IList<String> splitTokens = split.split(spacedToken); - IList<Token> rawTokens = splitTokens.map(tok -> tks.lexToken(tok, spacedToken)); + for (final String spacedToken : spacedTokens) { + final IList<String> splitTokens = split.split(spacedToken); + final IList<Token> rawTokens = splitTokens.map(tok -> tks.lexToken(tok, spacedToken)); rawTokens.forEach(tokens::add); } diff --git a/dice-lang/src/bjc/dicelang/expr/Parser.java b/dice-lang/src/bjc/dicelang/expr/Parser.java index 71a88fc..90a6b38 100644 --- a/dice-lang/src/bjc/dicelang/expr/Parser.java +++ b/dice-lang/src/bjc/dicelang/expr/Parser.java @@ -1,12 +1,12 @@ package bjc.dicelang.expr; +import java.util.Arrays; +import java.util.Scanner; + import bjc.utils.data.ITree; import bjc.utils.funcdata.FunctionalList; import bjc.utils.parserutils.TreeConstructor; -import java.util.Arrays; -import java.util.Scanner; - /** * Parser for simple math expressions. * @@ -19,17 +19,17 @@ public class Parser { * @param args * Unused CLI args. */ - public static void main(String[] args) { + public static void main(final String[] args) { /* * Create our objects. */ - Tokens toks = new Tokens(); - Lexer lex = new Lexer(); + final Tokens toks = new Tokens(); + final Lexer lex = new Lexer(); /* * Prepare our input. */ - Scanner scan = new Scanner(System.in); + final Scanner scan = new Scanner(System.in); /* * Read initial command. @@ -40,7 +40,7 @@ public class Parser { /* * Enter REPL loop. */ - while(!ln.equals("")) { + while (!ln.equals("")) { /* * Print raw command. */ @@ -50,9 +50,9 @@ public class Parser { /* * Lex command to infix tokens. */ - Token[] infixTokens = lex.lexString(ln, toks); + final Token[] infixTokens = lex.lexString(ln, toks); System.out.println("Lexed tokens: "); - for(Token tok : infixTokens) { + for (final Token tok : infixTokens) { System.out.println("\t" + tok); } @@ -60,7 +60,7 @@ public class Parser { * Print out infix expression. */ System.out.print("Lexed expression: "); - for(Token tok : infixTokens) { + for (final Token tok : infixTokens) { System.out.print(tok.toExpr() + " "); } System.out.println(); @@ -69,9 +69,9 @@ public class Parser { /* * Shunt infix tokens to postfix tokens. */ - Token[] postfixTokens = Shunter.shuntTokens(infixTokens); + final Token[] postfixTokens = Shunter.shuntTokens(infixTokens); System.out.println("Lexed tokens: "); - for(Token tok : postfixTokens) { + for (final Token tok : postfixTokens) { System.out.println("\t" + tok); } @@ -79,14 +79,14 @@ public class Parser { * Print out postfix tokens. */ System.out.print("Shunted expression: "); - for(Token tok : postfixTokens) { + for (final Token tok : postfixTokens) { System.out.print(tok.toExpr() + " "); } System.out.println(); System.out.println(); - FunctionalList<Token> tokList = new FunctionalList<>(Arrays.asList(postfixTokens)); - ITree<Token> ast = TreeConstructor.constructTree(tokList, tok -> tok.type.isOperator); + final FunctionalList<Token> tokList = new FunctionalList<>(Arrays.asList(postfixTokens)); + final ITree<Token> ast = TreeConstructor.constructTree(tokList, tok -> tok.typ.isOperator); /* * Print the tree, then the canonical expression for it. @@ -114,40 +114,39 @@ public class Parser { * Convert an expression to one that uses the smallest necessary amount * of parens. */ - private static String toCanonicalExpr(ITree<Token> ast) { - Token data = ast.getHead(); + private static String toCanonicalExpr(final ITree<Token> ast) { + final Token data = ast.getHead(); - if(ast.getChildrenCount() == 0) + if (ast.getChildrenCount() == 0) /* * Handle leaf nodes. */ return data.toExpr(); - else { - ITree<Token> left = ast.getChild(0); - ITree<Token> right = ast.getChild(1); - String leftExpr = toCanonicalExpr(left); - String rightExpr = toCanonicalExpr(right); + final ITree<Token> left = ast.getChild(0); + final ITree<Token> right = ast.getChild(1); - /* - * Add parens if the left was higher priority. - */ - if(left.getChildrenCount() == 0) { - if(left.getHead().type.operatorPriority >= data.type.operatorPriority) { - leftExpr = "(" + leftExpr + ")"; - } - } + String leftExpr = toCanonicalExpr(left); + String rightExpr = toCanonicalExpr(right); - /* - * Add parens if the right was higher priority. - */ - if(right.getChildrenCount() == 0) { - if(right.getHead().type.operatorPriority >= data.type.operatorPriority) { - rightExpr = "(" + rightExpr + ")"; - } + /* + * Add parens if the left was higher priority. + */ + if (left.getChildrenCount() == 0) { + if (left.getHead().typ.operatorPriority >= data.typ.operatorPriority) { + leftExpr = "(" + leftExpr + ")"; } + } - return leftExpr + " " + data.toExpr() + " " + rightExpr; + /* + * Add parens if the right was higher priority. + */ + if (right.getChildrenCount() == 0) { + if (right.getHead().typ.operatorPriority >= data.typ.operatorPriority) { + rightExpr = "(" + rightExpr + ")"; + } } + + return leftExpr + " " + data.toExpr() + " " + rightExpr; } }
\ No newline at end of file diff --git a/dice-lang/src/bjc/dicelang/expr/Shunter.java b/dice-lang/src/bjc/dicelang/expr/Shunter.java index 3b2bee2..19b30c3 100644 --- a/dice-lang/src/bjc/dicelang/expr/Shunter.java +++ b/dice-lang/src/bjc/dicelang/expr/Shunter.java @@ -19,32 +19,32 @@ public class Shunter { * * @return The tokens in postfix order. */ - public static Token[] shuntTokens(Token[] infixTokens) { - List<Token> postfixTokens = new ArrayList<>(infixTokens.length); + public static Token[] shuntTokens(final Token[] infixTokens) { + final List<Token> postfixTokens = new ArrayList<>(infixTokens.length); - Deque<Token> opStack = new LinkedList<>(); + final Deque<Token> opStack = new LinkedList<>(); /* * Shunt each token. */ - for(Token tok : infixTokens) { + for (final Token tok : infixTokens) { /* * Handle operators. */ - if(tok.type.isOperator) { + if (tok.typ.isOperator) { Token curOp = opStack.peek(); /* * Check if an operator is higher priority, * respecting their left associativity. */ - int leftPriority = tok.type.operatorPriority; + int leftPriority = tok.typ.operatorPriority; int rightPriority; - if(curOp == null) { + if (curOp == null) { rightPriority = 0; } else { - rightPriority = curOp.type.operatorPriority; + rightPriority = curOp.typ.operatorPriority; } boolean isHigherPrec = leftPriority >= rightPriority; @@ -53,41 +53,41 @@ public class Shunter { * Pop all operators that are lower precedence * than us. */ - while(!opStack.isEmpty() && isHigherPrec) { + while (!opStack.isEmpty() && isHigherPrec) { postfixTokens.add(opStack.pop()); curOp = opStack.peek(); - leftPriority = tok.type.operatorPriority; + leftPriority = tok.typ.operatorPriority; - if(curOp == null) { + if (curOp == null) { rightPriority = 0; } else { - rightPriority = curOp.type.operatorPriority; + rightPriority = curOp.typ.operatorPriority; } isHigherPrec = leftPriority >= rightPriority; } opStack.push(tok); - } else if(tok.type == TokenType.OPAREN) { + } else if (tok.typ == TokenType.OPAREN) { opStack.push(tok); - } else if(tok.type == TokenType.CPAREN) { + } else if (tok.typ == TokenType.CPAREN) { Token curOp = opStack.peek(); /* * Pop things until we find the matching * parenthesis. */ - while(curOp.type != TokenType.OPAREN) { - Token tk = opStack.pop(); + while (curOp.typ != TokenType.OPAREN) { + final Token tk = opStack.pop(); postfixTokens.add(tk); curOp = opStack.peek(); } - if(!opStack.isEmpty()) { + if (!opStack.isEmpty()) { opStack.pop(); } } else { @@ -98,7 +98,7 @@ public class Shunter { /* * Flush remaining operators. */ - while(!opStack.isEmpty()) { + while (!opStack.isEmpty()) { postfixTokens.add(opStack.pop()); } diff --git a/dice-lang/src/bjc/dicelang/expr/Token.java b/dice-lang/src/bjc/dicelang/expr/Token.java index dac90aa..d7fc0e2 100644 --- a/dice-lang/src/bjc/dicelang/expr/Token.java +++ b/dice-lang/src/bjc/dicelang/expr/Token.java @@ -9,14 +9,14 @@ public class Token { /* * The state for this token. */ - private Tokens tks; + private final Tokens tks; /** * The type of the token. * * Determines which fields have a value. */ - public final TokenType type; + public final TokenType typ; /** * The integer value attached to this token. @@ -40,8 +40,8 @@ public class Token { * @param toks * The state for this token */ - public Token(TokenType type, String raw, Tokens toks) { - this.type = type; + public Token(final TokenType type, final String raw, final Tokens toks) { + this.typ = type; rawValue = raw; @@ -50,10 +50,10 @@ public class Token { @Override public String toString() { - String typeStr = type.toString(); - typeStr += " (" + type.name() + ")"; + String typeStr = typ.toString(); + typeStr += " (" + typ.name() + ")"; - if(type == TokenType.VREF) { + if (typ == TokenType.VREF) { typeStr += " (ind. " + intValue; typeStr += ", sym. \"" + tks.symbolTable.get(intValue) + "\")"; } @@ -67,7 +67,7 @@ public class Token { * @return The string representation of it. */ public String toExpr() { - switch(type) { + switch (typ) { case ADD: return "+"; case SUBTRACT: diff --git a/dice-lang/src/bjc/dicelang/expr/TokenType.java b/dice-lang/src/bjc/dicelang/expr/TokenType.java index 9e4bbc2..fa20813 100644 --- a/dice-lang/src/bjc/dicelang/expr/TokenType.java +++ b/dice-lang/src/bjc/dicelang/expr/TokenType.java @@ -50,7 +50,7 @@ public enum TokenType { */ public final int operatorPriority; - private TokenType(int num, boolean isOp, int priority) { + private TokenType(final int num, final boolean isOp, final int priority) { nVal = num; isOperator = isOp; @@ -58,7 +58,7 @@ public enum TokenType { operatorPriority = priority; } - private TokenType(int num) { + private TokenType(final int num) { this(num, false, -1); } diff --git a/dice-lang/src/bjc/dicelang/expr/Tokens.java b/dice-lang/src/bjc/dicelang/expr/Tokens.java index 88bd99e..6bdcde0 100644 --- a/dice-lang/src/bjc/dicelang/expr/Tokens.java +++ b/dice-lang/src/bjc/dicelang/expr/Tokens.java @@ -66,20 +66,19 @@ public class Tokens { * * @return The token the string represents. */ - public Token lexToken(String tok, String raw) { - if(litTokens.containsKey(tok)) - return new Token(litTokens.get(tok), raw, this); - else - return parseVRef(tok, raw); + public Token lexToken(final String tok, final String raw) { + if (litTokens.containsKey(tok)) return new Token(litTokens.get(tok), raw, this); + + return parseVRef(tok, raw); } /* * Parse a variable reference. */ - private Token parseVRef(String tok, String raw) { - Token tk = new Token(TokenType.VREF, raw, this); + private Token parseVRef(final String tok, final String raw) { + final Token tk = new Token(TokenType.VREF, raw, this); - if(revSymTab.containsKey(tok)) { + if (revSymTab.containsKey(tok)) { /* * Reuse the entry if it exists. */ diff --git a/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java b/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java index 76133e7..ac9e880 100644 --- a/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java +++ b/dice-lang/src/bjc/dicelang/scl/StreamControlEngine.java @@ -1,5 +1,40 @@ package bjc.dicelang.scl; +import static bjc.dicelang.Errors.ErrorKey.EK_SCL_INVARG; +import static bjc.dicelang.Errors.ErrorKey.EK_SCL_INVTOKEN; +import static bjc.dicelang.Errors.ErrorKey.EK_SCL_MMQUOTE; +import static bjc.dicelang.Errors.ErrorKey.EK_SCL_SUNDERFLOW; +import static bjc.dicelang.Errors.ErrorKey.EK_SCL_UNWORD; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.ARRAY; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.BLIT; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.DELETESTREAM; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.DQUOTE; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.DROP; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.FLIT; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.ILIT; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.LEFTSTREAM; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.MAKEARRAY; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.MAKEEXEC; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.MAKEUNEXEC; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.MERGESTREAM; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.NDROP; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.NEWSTREAM; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.NIP; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.NNIP; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.OBRACE; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.OBRACKET; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.RIGHTSTREAM; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.SLIT; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.SQUOTE; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.STACKCOUNT; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.STACKEMPTY; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.SYMBOL; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.WORD; +import static bjc.dicelang.scl.StreamControlEngine.Token.Type.WORDS; + +import java.util.HashMap; +import java.util.Map; + import bjc.dicelang.Errors; import bjc.utils.esodata.SimpleStack; import bjc.utils.esodata.Stack; @@ -7,12 +42,6 @@ import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; import bjc.utils.parserutils.TokenUtils; -import java.util.HashMap; -import java.util.Map; - -import static bjc.dicelang.Errors.ErrorKey.*; -import static bjc.dicelang.scl.StreamControlEngine.Token.Type.*; - /** * Runs a Stream Control Language (SCL) program. * @@ -80,64 +109,64 @@ public class StreamControlEngine { */ public IList<Token> tokenVals; - public Token(Type typ) { + public Token(final Type typ) { type = typ; } - public Token(Type typ, long iVal) { + public Token(final Type typ, final long iVal) { this(typ); intVal = iVal; } - public Token(Type typ, double dVal) { + public Token(final Type typ, final double dVal) { this(typ); floatVal = dVal; } - public Token(Type typ, boolean bVal) { + public Token(final Type typ, final boolean bVal) { this(typ); boolVal = bVal; } - public Token(Type typ, String sVal) { + public Token(final Type typ, final String sVal) { this(typ); stringVal = sVal; } - public Token(Type typ, Token tVal) { + public Token(final Type typ, final Token tVal) { this(typ); tokenVal = tVal; } - public Token(Type typ, Token.Type tVal) { + public Token(final Type typ, final Token.Type tVal) { this(typ, new Token(tVal)); } - public Token(Type typ, IList<Token> tVals) { + public Token(final Type typ, final IList<Token> tVals) { this(typ); tokenVals = tVals; } - public static Token tokenizeString(String token) { - if(litTokens.containsKey(token)) + public static Token tokenizeString(final String 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(TokenUtils.isInt(token)) + else if (TokenUtils.isInt(token)) return new Token(ILIT, Long.parseLong(token)); - else if(TokenUtils.isDouble(token)) + else if (TokenUtils.isDouble(token)) return new Token(FLIT, Double.parseDouble(token)); else { Errors.inst.printError(EK_SCL_INVTOKEN, token); @@ -175,21 +204,21 @@ public class StreamControlEngine { } } - private StreamEngine eng; + private final StreamEngine eng; - private Stack<Token> curStack; + private final Stack<Token> curStack; @SuppressWarnings("unused") - private Map<String, Token> words; + private final Map<String, Token> words; /** * Create a new stream control engine. * - * @param eng + * @param engine * The engine to control. */ - public StreamControlEngine(StreamEngine eng) { - this.eng = eng; + public StreamControlEngine(final StreamEngine engine) { + eng = engine; words = new HashMap<>(); curStack = new SimpleStack<>(); @@ -203,26 +232,26 @@ public class StreamControlEngine { * * @return Whether the program executed successfully. */ - public boolean runProgram(String[] tokens) { - for(int i = 0; i < tokens.length; i++) { - String token = tokens[i]; - Token tok = Token.tokenizeString(token); + public boolean runProgram(final String[] tokens) { + for (int i = 0; i < tokens.length; i++) { + final String token = tokens[i]; + final 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; - Token brak = curStack.pop(); + if (i == -1) return false; + final Token brak = curStack.pop(); curStack.push(new Token(ARRAY, brak.tokenVals)); break; case WORD: @@ -237,40 +266,40 @@ public class StreamControlEngine { return true; } - private boolean handleWord(Token tk) { + private boolean handleWord(final 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())); @@ -279,7 +308,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; } @@ -287,10 +316,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; } @@ -299,7 +328,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()); @@ -310,16 +339,16 @@ public class StreamControlEngine { } private boolean handleNNip() { - Token num = curStack.pop(); + final 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; + final int n = (int) num.intVal; - if(curStack.size() < n) { + if (curStack.size() < n) { Errors.inst.printError(EK_SCL_SUNDERFLOW, NNIP.toString()); return false; } @@ -329,16 +358,16 @@ public class StreamControlEngine { } private boolean handleNDrop() { - Token num = curStack.pop(); + final 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; + final int n = (int) num.intVal; - if(curStack.size() < n) { + if (curStack.size() < n) { Errors.inst.printError(EK_SCL_SUNDERFLOW, NDROP.toString()); return false; } @@ -347,18 +376,18 @@ public class StreamControlEngine { return true; } - private boolean toggleExec(boolean exec) { - Token top = curStack.top(); + private boolean toggleExec(final boolean exec) { + final 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; } @@ -370,15 +399,15 @@ public class StreamControlEngine { } private boolean makeArray() { - Token num = curStack.pop(); + final Token num = curStack.pop(); - if(num.type != ILIT) { + if (num.type != ILIT) { Errors.inst.printError(EK_SCL_INVARG, num.type.toString()); } - IList<Token> arr = new FunctionalList<>(); + final IList<Token> arr = new FunctionalList<>(); - for(int i = 0; i < num.intVal; i++) { + for (int i = 0; i < num.intVal; i++) { arr.add(curStack.pop()); } @@ -387,34 +416,34 @@ public class StreamControlEngine { return true; } - private int handleDelim(int i, String[] tokens, String delim) { - IList<Token> toks = new FunctionalList<>(); + private int handleDelim(final int i, final String[] tokens, final String delim) { + final IList<Token> 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)) { - Token ntok = Token.tokenizeString(tok); + while (!tok.equals(delim)) { + final 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; - Token brak = curStack.pop(); + n = handleDelim(i, tokens, "}"); + if (n == -1) return -1; + final Token brak = curStack.pop(); toks.add(new Token(ARRAY, brak.tokenVals)); break; default: @@ -424,7 +453,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; } @@ -441,18 +470,18 @@ public class StreamControlEngine { return n; } - private int handleSingleQuote(int i, String[] tokens) { - StringBuilder sb = new StringBuilder(); + private int handleSingleQuote(final int i, final String[] tokens) { + final 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. */ @@ -465,7 +494,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 c79d054..4717eaa 100644 --- a/dice-lang/src/bjc/dicelang/scl/StreamEngine.java +++ b/dice-lang/src/bjc/dicelang/scl/StreamEngine.java @@ -1,5 +1,9 @@ package bjc.dicelang.scl; +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; + import bjc.dicelang.DiceLangEngine; import bjc.dicelang.Errors; import bjc.utils.esodata.SingleTape; @@ -9,10 +13,6 @@ import bjc.utils.funcdata.FunctionalList; import bjc.utils.funcdata.IList; import bjc.utils.funcutils.ListUtils; -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 * for the streams. @@ -42,7 +42,7 @@ public class StreamEngine { /* * Handler for SCL programs */ - private StreamControlEngine scleng; + private final StreamControlEngine scleng; /** * Create a new stream engine. @@ -50,7 +50,7 @@ public class StreamEngine { * @param engine * The dice engine we're attached to. */ - public StreamEngine(DiceLangEngine engine) { + public StreamEngine(final DiceLangEngine engine) { eng = engine; savedStreams = new TapeLibrary<>(); @@ -81,7 +81,7 @@ public class StreamEngine { * * @return Whether or not the streams were successfully processed. */ - public boolean doStreams(String[] toks, IList<String> dest) { + public boolean doStreams(final String[] toks, final IList<String> dest) { /* * Initialize per-run state. */ @@ -95,18 +95,18 @@ public class StreamEngine { /* * Process each token. */ - for(String tk : toks) { + for (final 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; + } 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); @@ -114,7 +114,7 @@ public class StreamEngine { } } - for(String tk : currStream) { + for (final String tk : currStream) { dest.add(tk); } @@ -134,7 +134,7 @@ public class StreamEngine { * @return Whether or not the move was successful. */ public boolean rightStream() { - if(!streams.right()) { + if (!streams.right()) { Errors.inst.printError(EK_STRM_NONEX); return false; } @@ -149,7 +149,7 @@ public class StreamEngine { * @return Whether or not the move was successful. */ public boolean leftStream() { - if(!streams.left()) { + if (!streams.left()) { Errors.inst.printError(EK_STRM_NONEX); return false; } @@ -164,14 +164,14 @@ public class StreamEngine { * @return Whether or not the delete succeeded. */ public boolean deleteStream() { - if(streams.size() == 1) { + if (streams.size() == 1) { Errors.inst.printError(EK_STRM_LAST); return false; - } else { - streams.remove(); - currStream = streams.item(); } + streams.remove(); + currStream = streams.item(); + return true; } @@ -181,22 +181,22 @@ public class StreamEngine { * @return Whether or not the merge succeded. */ public boolean mergeStream() { - if(streams.size() == 1) { + if (streams.size() == 1) { Errors.inst.printError(EK_STRM_LAST); return false; - } else { - IList<String> stringLit = streams.remove(); - currStream = streams.item(); - currStream.add(ListUtils.collapseTokens(stringLit, " ")); } + final IList<String> stringLit = streams.remove(); + currStream = streams.item(); + currStream.add(ListUtils.collapseTokens(stringLit, " ")); + return true; } - private boolean processCommand(String tk) { + private boolean processCommand(final 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]; @@ -205,30 +205,30 @@ public class StreamEngine { boolean succ; - for(char comm : comms) { - switch(comm) { + for (final 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 c9b65d7..37cf5b3 100644 --- a/dice-lang/src/bjc/dicelang/util/ResourceLoader.java +++ b/dice-lang/src/bjc/dicelang/util/ResourceLoader.java @@ -1,6 +1,6 @@ package bjc.dicelang.util; -import bjc.dicelang.Errors; +import static bjc.dicelang.Errors.ErrorKey.EK_MISC_IOEX; import java.io.IOException; import java.net.URISyntaxException; @@ -8,7 +8,7 @@ import java.net.URL; import java.nio.file.Files; import java.nio.file.Paths; -import static bjc.dicelang.Errors.ErrorKey.EK_MISC_IOEX; +import bjc.dicelang.Errors; /** * Load resources bundled with DiceLang. @@ -26,13 +26,12 @@ public class ResourceLoader { * @return The contents of the help file, or null if it could not be * opened. */ - @SuppressWarnings("unused") - public static String[] loadHelpFile(String name) { - URL fle = ResourceLoader.class.getResource("/data/help/" + name + ".help"); + public static String[] loadHelpFile(final String name) { + final URL fle = ResourceLoader.class.getResource("/data/help/" + name + ".help"); try { return Files.lines(Paths.get(fle.toURI())).toArray(sze -> new String[sze]); - } catch(IOException | URISyntaxException ioex) { + } catch (IOException | URISyntaxException ioex) { Errors.inst.printError(EK_MISC_IOEX, fle.toString()); } |
