diff options
Diffstat (limited to 'base/src/main')
85 files changed, 2465 insertions, 1550 deletions
diff --git a/base/src/main/java/bjc/utils/cli/Command.java b/base/src/main/java/bjc/utils/cli/Command.java index 7451cf7..68351bf 100644 --- a/base/src/main/java/bjc/utils/cli/Command.java +++ b/base/src/main/java/bjc/utils/cli/Command.java @@ -7,13 +7,6 @@ package bjc.utils.cli; */ public interface Command { /** - * Create a command that serves as an alias to this one - * - * @return A command that serves as an alias to this one - */ - Command aliased(); - - /** * Get the handler that executes this command * * @return The handler that executes this command @@ -26,7 +19,16 @@ public interface Command { * @return The help entry for this command */ CommandHelp getHelp(); - + + /** + * Create a command that serves as an alias to this one + * + * @return A command that serves as an alias to this one + */ + default Command aliased() { + return new DelegatingCommand(this); + }; + /** * Check if this command is an alias of another command * @@ -35,4 +37,21 @@ public interface Command { default boolean isAlias() { return false; } + + /** + * Create a new basic command. + * + * @param summary The summary of the command. This is used as a short help + * message displayed when listing commands. + * @param description The description of the command. This is what is shown + * when the detailed help for a command is asked for. + * @param handler The implementation for the command. + * + * @return A command with the given implementation. + */ + static Command from( + String summary, String description, CommandHandler handler) + { + return new GenericCommand(handler, summary, description); + } } diff --git a/base/src/main/java/bjc/utils/cli/DelegatingCommand.java b/base/src/main/java/bjc/utils/cli/DelegatingCommand.java index f17b6b5..fa2d1db 100644 --- a/base/src/main/java/bjc/utils/cli/DelegatingCommand.java +++ b/base/src/main/java/bjc/utils/cli/DelegatingCommand.java @@ -21,6 +21,7 @@ class DelegatingCommand implements Command { @Override public Command aliased() { + // Prevent double-indirections return new DelegatingCommand(delegate); } diff --git a/base/src/main/java/bjc/utils/cli/GenericCommand.java b/base/src/main/java/bjc/utils/cli/GenericCommand.java index a847bea..6903152 100644 --- a/base/src/main/java/bjc/utils/cli/GenericCommand.java +++ b/base/src/main/java/bjc/utils/cli/GenericCommand.java @@ -12,40 +12,25 @@ public class GenericCommand implements Command { /* The help for the command. */ private CommandHelp help; - /** - * Create a new generic command. + /** Create a new generic command. * - * @param handler - * The handler to use for the command. - * - * @param description - * The description of the command. May be null, in which case - * a default is provided. - * - * @param help - * The detailed help message for the command. May be null, in - * which case the description is repeated for the detailed - * help. - */ - public GenericCommand(final CommandHandler handler, final String description, - final String help) { + * @param handler The handler to use for the command. + * @param summary The summary of the command. May be null, in which case a + * default is provided. + * @param description The detailed help message for the command. May be null, + * in which case the summary is repeated for the + * detailed help. */ + public GenericCommand(final CommandHandler handler, final String summary, + final String description) { if (handler == null) throw new NullPointerException("Command handler must not be null"); this.handler = handler; - if (description == null) { - this.help = new NullHelp(); - } else { - this.help = new GenericHelp(description, help); - } - } - - @Override - public Command aliased() { - return new DelegatingCommand(this); + if (summary == null) this.help = new NullHelp(); + else this.help = new GenericHelp(summary, description); } - + @Override public CommandHandler getHandler() { return handler; @@ -57,16 +42,6 @@ public class GenericCommand implements Command { } @Override - public boolean isAlias() { - return false; - } - - /* - * (non-Javadoc) - * - * @see java.lang.Object#toString() - */ - @Override public String toString() { return String.format("GenericCommand [help=%s]", help); } diff --git a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java index 328bbee..3642137 100644 --- a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java +++ b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java @@ -5,7 +5,7 @@ import java.util.function.BiConsumer; import java.util.function.Consumer; import bjc.funcdata.FunctionalMap; -import bjc.funcdata.IMap; +import bjc.funcdata.MapEx; /** * A general command mode, with a customizable set of commands. @@ -18,12 +18,12 @@ import bjc.funcdata.IMap; */ public class GenericCommandMode implements CommandMode { /* Contains the commands this mode handles. */ - private final IMap<String, Command> commandHandlers; + private final MapEx<String, Command> commandHandlers; /* Commands to execute in every mode. */ - private final IMap<String, Command> defaultHandlers; + private final MapEx<String, Command> defaultHandlers; /* Contains help topics without an associated command */ - private final IMap<String, CommandHelp> helpTopics; + private final MapEx<String, CommandHelp> helpTopics; /* The action to execute upon encountering an unknown command */ private BiConsumer<String, String[]> unknownCommandHandler; @@ -55,12 +55,12 @@ public class GenericCommandMode implements CommandMode { throw new NullPointerException("Error output source must be non-null"); this.normalOutput = normalOutput; - this.errorOutput = errorOutput; + this.errorOutput = errorOutput; /* Initialize maps so that they sort in alphabetical order. */ commandHandlers = new FunctionalMap<>(new TreeMap<>()); defaultHandlers = new FunctionalMap<>(new TreeMap<>()); - helpTopics = new FunctionalMap<>(new TreeMap<>()); + helpTopics = new FunctionalMap<>(new TreeMap<>()); /* Setup default commands. */ setupDefaultCommands(); @@ -84,17 +84,16 @@ public class GenericCommandMode implements CommandMode { if (commandName == null) { throw new NullPointerException("Command name must not be null"); } else if (aliasName == null) { - String msg = "Alias name must not be null"; - throw new NullPointerException(msg); + throw new NullPointerException("Alias name must not be null"); } else if (!commandHandlers.containsKey(commandName) && !defaultHandlers.containsKey(commandName)) { - String msg = String.format("Cannot alias non-existant command '%s'", + String msg = String.format("Cannot alias non-existing command '%s'", commandName); throw new IllegalArgumentException(msg); } else if (commandHandlers.containsKey(aliasName) || defaultHandlers.containsKey(aliasName)) { String msg = String.format( - "Cannot bind alias '%s' to an already bound command.", aliasName); + "Cannot bind alias '%s' to an already used name.", aliasName); throw new IllegalArgumentException(msg); } else { /* The command that will be aliased. */ @@ -102,9 +101,9 @@ public class GenericCommandMode implements CommandMode { /* Get the alias. */ if (defaultHandlers.containsKey(commandName)) { - aliasedCommand = defaultHandlers.get(commandName).aliased(); + aliasedCommand = defaultHandlers.get(commandName).get().aliased(); } else { - aliasedCommand = commandHandlers.get(commandName).aliased(); + aliasedCommand = commandHandlers.get(commandName).get().aliased(); } commandHandlers.put(aliasName, aliasedCommand); @@ -262,16 +261,16 @@ public class GenericCommandMode implements CommandMode { private void doHelpCommand(final String commandName) { if (commandHandlers.containsKey(commandName)) { final String desc - = commandHandlers.get(commandName).getHelp().getDescription(); + = commandHandlers.get(commandName).get().getHelp().getDescription(); normalOutput.accept("\n" + desc); } else if (defaultHandlers.containsKey(commandName)) { final String desc - = defaultHandlers.get(commandName).getHelp().getDescription(); + = defaultHandlers.get(commandName).get().getHelp().getDescription(); normalOutput.accept("\n" + desc); } else if (helpTopics.containsKey(commandName)) { - normalOutput.accept("\n" + helpTopics.get(commandName).getDescription()); + normalOutput.accept("\n" + helpTopics.get(commandName).get().getDescription()); } else { String msg = String.format("ERROR: No help available for '%s'", commandName); @@ -371,9 +370,9 @@ public class GenericCommandMode implements CommandMode { normalOutput.accept("\n"); if (defaultHandlers.containsKey(command)) - return defaultHandlers.get(command).getHandler().handle(args); + return defaultHandlers.get(command).get().getHandler().handle(args); else if (commandHandlers.containsKey(command)) - return commandHandlers.get(command).getHandler().handle(args); + return commandHandlers.get(command).get().getHandler().handle(args); else { if (args != null) { String argString = String.join(", ", args); diff --git a/base/src/main/java/bjc/utils/cli/GenericHelp.java b/base/src/main/java/bjc/utils/cli/GenericHelp.java index 45d3a88..0157d4f 100644 --- a/base/src/main/java/bjc/utils/cli/GenericHelp.java +++ b/base/src/main/java/bjc/utils/cli/GenericHelp.java @@ -1,17 +1,14 @@ package bjc.utils.cli; -/** - * Generic implementation of a help topic. +/** Generic implementation of a help topic. * - * @author ben - */ + * @author ben */ public class GenericHelp implements CommandHelp { /* The strings for this help topic. */ private final String summary; private final String description; - /** - * Create a new help topic. + /** Create a new help topic. * * @param summary * The summary of this help topic. @@ -31,9 +28,7 @@ public class GenericHelp implements CommandHelp { @Override public String getDescription() { - if (description == null) { - return summary; - } + if (description == null) return summary; return description; } diff --git a/base/src/main/java/bjc/utils/cli/NullHelp.java b/base/src/main/java/bjc/utils/cli/NullHelp.java index 5e5fb67..048b6e7 100644 --- a/base/src/main/java/bjc/utils/cli/NullHelp.java +++ b/base/src/main/java/bjc/utils/cli/NullHelp.java @@ -1,10 +1,8 @@ package bjc.utils.cli; -/** - * Implementation of a help topic that doesn't exist. +/** Implementation of a help topic that doesn't exist or isn't provided. * - * @author ben - */ + * @author ben */ public class NullHelp implements CommandHelp { @Override public String getDescription() { @@ -15,5 +13,4 @@ public class NullHelp implements CommandHelp { public String getSummary() { return "No summary provided"; } - -} +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/cli/objects/Command.java b/base/src/main/java/bjc/utils/cli/objects/Command.java index af22643..3b287ea 100644 --- a/base/src/main/java/bjc/utils/cli/objects/Command.java +++ b/base/src/main/java/bjc/utils/cli/objects/Command.java @@ -3,341 +3,288 @@ package bjc.utils.cli.objects; import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * A single-line command read from the user. +/** A single-line command read from the user. * - * @author Ben Culkin - */ + * @author Ben Culkin */ public class Command { - /** - * Command status values. - * - * @author Ben Culkin - */ - public static enum CommandStatus { - /** - * The command succeeded. - */ - SUCCESS, - /** - * The command failed non-fatally. - */ - FAIL, - /** - * The command failed fatally. - */ - ERROR, - /** - * The command was the last one. - */ - FINISH, - } - - /** - * The line number of this command. - */ - public final int lno; - - /** - * The full text of this command. - */ - public final String full; - /** - * The text of this command without its name. - */ - public String remn; - /** - * The name of this command. - */ - public final String name; - - /** - * The name of the I/O source this command was read from. - */ - public final String src; - - /** - * Create a new command. - * - * @param ln - * The string to get the command from. - * - * @param lno - * The number of the line the command came from. - * - * @param ioSrc - * The name of where the I/O came from. - */ - public Command(String ln, int lno, String ioSrc) { - int idx = ln.indexOf(' '); - - if (idx == -1) - idx = ln.length(); - - /* Grab command parts. */ - full = ln; - name = ln.substring(0, idx).trim(); - remn = ln.substring(idx).trim(); - - this.lno = lno; - - src = ioSrc; - } - - /** - * Removes up until the first occurrence of a particular string for the - * remaining command, and returns the removed string. - * - * By default, both the substring and the remaining text are trimmed - * (leading/trailing spaces removed). - * - * @param delm - * The delimiter to stop substringing at. - * - * @return The substring, or null if there is no occurrence of the delimiter. - */ - public String trimTo(String delm) { - return trimTo(delm, true); - } - - /** - * Removes up until the first occurrence of a particular string for the - * remaining command, and returns the removed string. - * - * @param delm - * The delimiter to stop substringing at. - * @param doTrim - * Whether or not to trim the substring and remaining command - * (Remove leading/trailing spaces). - * - * @return The substring, or null if there is no occurrence of the delimiter. - */ - public String trimTo(String delm, boolean doTrim) { - int idx = remn.indexOf(delm); - if (idx == -1) - return null; - - String tmp = remn.substring(0, idx); - remn = remn.substring(idx); - - if (doTrim) { - tmp = tmp.trim(); - remn = remn.trim(); - } - - return tmp; - } - - /** - * Removes up until the first occurrence of a particular regex for the remaining - * command, and returns the removed string. - * - * By default, both the substring and the remaining text are trimmed - * (leading/trailing spaces removed). - * - * @param rDelm - * The regex to stop substringing at. - * - * @return The string, up to the matched pattern. - */ - public String trimToRX(String rDelm) { - return trimToRX(Pattern.compile(rDelm), true); - } - - /** - * Removes up until the first occurrence of a particular regex for the remaining - * command, and returns the removed string. - * - * By default, both the substring and the remaining text are trimmed - * (leading/trailing spaces removed). - * - * @param delm - * The regex to stop substringing at. - * - * @return The string, up to the matched pattern. - */ - public String trimToRX(Pattern delm) { - return trimToRX(delm, true); - } - - /** - * Removes up until the first occurrence of a particular regex for the remaining - * command, and returns the removed string. - * - * @param rDelm - * The regex to stop substringing at. - * @param doTrim - * Whether or not to trim the substring and remaining command - * (Remove leading/trailing spaces). - * - * @return The string, up to the matched pattern. - */ - public String trimToRX(String rDelm, boolean doTrim) { - return trimToRX(Pattern.compile(rDelm), doTrim); - } - - /** - * Removes up until the first occurrence of a particular regex for the remaining - * command, and returns the removed string. - * - * @param delm - * The regex to stop substringing at. - * @param doTrim - * Whether or not to trim the substring and remaining command - * (Remove leading/trailing spaces). - * - * @return The string, up to the matched pattern. - */ - public String trimToRX(Pattern delm, boolean doTrim) { - Matcher mat = delm.matcher(remn); - if (!mat.find()) - return null; - - String tmp = remn.substring(0, mat.start()); - remn = remn.substring(mat.end()); - - if (doTrim) { - tmp = tmp.trim(); - remn = remn.trim(); - } - - return tmp; - } - - /** - * Removes up until the first occurrence of a particular string for the - * remaining command, and returns the removed string. - * - * By default, both the substring and the remaining text are trimmed - * (leading/trailing spaces removed). - * - * @param delm - * The delimiter to stop substringing at. - * - * @return The substring, or null if there is no occurrence of the delimiter. - */ - public String trimTo(char delm) { - return trimTo(delm, true); - } - - /** - * Removes up until the first occurrence of a particular string for the - * remaining command, and returns the removed string. - * - * @param delm - * The delimiter to stop substringing at. - * @param doTrim - * Whether or not to trim the substring and remaining command - * (Remove leading/trailing spaces). - * - * @return The substring, or null if there is no occurrence of the delimiter. - */ - public String trimTo(char delm, boolean doTrim) { - int idx = remn.indexOf(delm); - if (idx == -1) - return null; - - String tmp = remn.substring(0, idx); - remn = remn.substring(idx); - - if (doTrim) { - tmp = tmp.trim(); - remn = remn.trim(); - } - - return tmp; - } - - /** - * Check if this command has text after its name. - * - * @return Whether or not this command has text after its name. - */ - public boolean hasRemaining() { - return !remn.equals(""); - } - - /** - * Parse a command from a string. - * - * The main thing this does is ignore blank lines, as well as comments marked by - * #'s either at the start of the line or part of the way through the line. - * - * @param lne - * The string to get the command from. - * - * @param lno - * The line number of the command. - * - * @param srcName - * The name of where the I/O came from. - * @return The parsed command - */ - public static Command fromString(String lne, int lno, String srcName) { - String ln = lne; - - /* Ignore blank lines and comments. */ - if (ln.equals("")) - return null; - if (ln.startsWith("#")) - return null; - - /* Trim off comments part-way through the line. */ - int idxHash = ln.indexOf('#'); - if (idxHash != -1) { - ln = ln.substring(0, idxHash).trim(); - } - - return new Command(ln, lno, srcName); - } - - /** - * Give an informational message about something in relation to this command. - * - * @param info - * The informational message. - * - * @param parms - * The parameters for the informational message. - * @return The information message. - */ - public String info(String info, Object... parms) { - String msg = String.format(info, parms); - - return String.format("INFO (%s:%d): %s", src, lno, msg); - } - - /** - * Warn about something in relation to this command. - * - * @param warning - * The warning message. - * - * @param parms - * The parameters for the warning message. - * - * @return The formatted warning. - */ - public String warn(String warning, Object... parms) { - String msg = String.format(warning, parms); - - return String.format("WARNING (%s:%d): %s", src, lno, msg); - } - - /** - * Give an error about something in relation to this command. - * - * @param err - * The error message. - * - * @param parms - * The parameters for the error message. - * - * @return The formatted error - */ - public String error(String err, Object... parms) { - String msg = String.format(err, parms); - - return String.format("ERROR (%s:%d): %s", src, lno, msg); - } -} + /** Command status values. + * + * @author Ben Culkin */ + public static enum CommandStatus { + /** The command succeeded. */ + SUCCESS, + /** The command failed non-fatally. */ + FAIL, + /** The command failed fatally. */ + ERROR, + /** The command was the last one. */ + FINISH, + } + + /** The line number of this command. */ + public final int lno; + + /** The full text of this command. */ + public final String full; + /** The text of this command without its name. */ + public String remn; + /** The name of this command. */ + public final String name; + + /** The name of the I/O source this command was read from. */ + public final String src; + + /** Create a new command. + * + * @param ln + * The string to get the command from. + * + * @param lno + * The number of the line the command came from. + * + * @param ioSrc + * The name of where the I/O came from. */ + public Command(String ln, int lno, String ioSrc) { + int idx = ln.indexOf(' '); + if (idx == -1) idx = ln.length(); + + /* Grab command parts. */ + full = ln; + name = ln.substring(0, idx).trim(); + remn = ln.substring(idx).trim(); + + this.lno = lno; + + src = ioSrc; + } + + /** Removes up until the first occurrence of a particular string for the + * remaining command, and returns the removed string. + * + * By default, both the substring and the remaining text are trimmed + * (leading/trailing spaces removed). + * + * @param delm + * The delimiter to stop substringing at. + * + * @return The substring, or null if there is no occurrence of the delimiter. */ + public String trimTo(String delm) { + return trimTo(delm, true); + } + + /** Removes up until the first occurrence of a particular string for the + * remaining command, and returns the removed string. + * + * @param delm + * The delimiter to stop substringing at. + * @param doTrim + * Whether or not to trim the substring and remaining command + * (Remove leading/trailing spaces). + * + * @return The substring, or null if there is no occurrence of the delimiter. */ + public String trimTo(String delm, boolean doTrim) { + int idx = remn.indexOf(delm); + if (idx == -1) return null; + + String tmp = remn.substring(0, idx); + remn = remn.substring(idx); + + if (doTrim) { + tmp = tmp.trim(); + remn = remn.trim(); + } + + return tmp; + } + + /** Removes up until the first occurrence of a particular regex for the + * remaining + * command, and returns the removed string. + * + * By default, both the substring and the remaining text are trimmed + * (leading/trailing spaces removed). + * + * @param rDelm + * The regex to stop substringing at. + * + * @return The string, up to the matched pattern. */ + public String trimToRX(String rDelm) { + return trimToRX(Pattern.compile(rDelm), true); + } + + /** Removes up until the first occurrence of a particular regex for the + * remaining + * command, and returns the removed string. + * + * By default, both the substring and the remaining text are trimmed + * (leading/trailing spaces removed). + * + * @param delm + * The regex to stop substringing at. + * + * @return The string, up to the matched pattern. */ + public String trimToRX(Pattern delm) { + return trimToRX(delm, true); + } + + /** Removes up until the first occurrence of a particular regex for the + * remaining + * command, and returns the removed string. + * + * @param rDelm + * The regex to stop substringing at. + * @param doTrim + * Whether or not to trim the substring and remaining command + * (Remove leading/trailing spaces). + * + * @return The string, up to the matched pattern. */ + public String trimToRX(String rDelm, boolean doTrim) { + return trimToRX(Pattern.compile(rDelm), doTrim); + } + + /** Removes up until the first occurrence of a particular regex for the + * remaining + * command, and returns the removed string. + * + * @param delm + * The regex to stop substringing at. + * @param doTrim + * Whether or not to trim the substring and remaining command + * (Remove leading/trailing spaces). + * + * @return The string, up to the matched pattern. */ + public String trimToRX(Pattern delm, boolean doTrim) { + Matcher mat = delm.matcher(remn); + if (!mat.find()) return null; + + String tmp = remn.substring(0, mat.start()); + remn = remn.substring(mat.end()); + + if (doTrim) { + tmp = tmp.trim(); + remn = remn.trim(); + } + + return tmp; + } + + /** Removes up until the first occurrence of a particular string for the + * remaining command, and returns the removed string. + * + * By default, both the substring and the remaining text are trimmed + * (leading/trailing spaces removed). + * + * @param delm + * The delimiter to stop substringing at. + * + * @return The substring, or null if there is no occurrence of the delimiter. */ + public String trimTo(char delm) { + return trimTo(delm, true); + } + + /** Removes up until the first occurrence of a particular string for the + * remaining command, and returns the removed string. + * + * @param delm + * The delimiter to stop substringing at. + * @param doTrim + * Whether or not to trim the substring and remaining command + * (Remove leading/trailing spaces). + * + * @return The substring, or null if there is no occurrence of the delimiter. */ + public String trimTo(char delm, boolean doTrim) { + int idx = remn.indexOf(delm); + if (idx == -1) return null; + + String tmp = remn.substring(0, idx); + remn = remn.substring(idx); + + if (doTrim) { + tmp = tmp.trim(); + remn = remn.trim(); + } + + return tmp; + } + + /** Check if this command has text after its name. + * + * @return Whether or not this command has text after its name. */ + public boolean hasRemaining() { + return !remn.equals(""); + } + + /** Parse a command from a string. + * + * The main thing this does is ignore blank lines, as well as comments marked by + * #'s either at the start of the line or part of the way through the line. + * + * @param lne + * The string to get the command from. + * + * @param lno + * The line number of the command. + * + * @param srcName + * The name of where the I/O came from. + * + * @return The parsed command */ + public static Command fromString(String lne, int lno, String srcName) { + String ln = lne; + + /* Ignore blank lines and comments. */ + if (ln.equals("")) return null; + if (ln.startsWith("#")) return null; + + /* Trim off comments part-way through the line. */ + int idxHash = ln.indexOf('#'); + if (idxHash != -1) ln = ln.substring(0, idxHash).trim(); + + return new Command(ln, lno, srcName); + } + + /** Give an informational message about something in relation to this command. + * + * @param info + * The informational message. + * + * @param parms + * The parameters for the informational message. + * + * @return The information message. */ + public String info(String info, Object... parms) { + String msg = String.format(info, parms); + + return String.format("INFO (%s:%d): %s", src, lno, msg); + } + + /** Warn about something in relation to this command. + * + * @param warning + * The warning message. + * + * @param parms + * The parameters for the warning message. + * + * @return The formatted warning. */ + public String warn(String warning, Object... parms) { + String msg = String.format(warning, parms); + + return String.format("WARNING (%s:%d): %s", src, lno, msg); + } + + /** Give an error about something in relation to this command. + * + * @param err + * The error message. + * + * @param parms + * The parameters for the error message. + * + * @return The formatted error */ + public String error(String err, Object... parms) { + String msg = String.format(err, parms); + + return String.format("ERROR (%s:%d): %s", src, lno, msg); + } +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java b/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java index d2595d6..613b223 100644 --- a/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java +++ b/base/src/main/java/bjc/utils/cli/objects/DefineCLI.java @@ -14,7 +14,7 @@ import java.util.logging.Logger; import java.util.regex.Pattern; import bjc.utils.cli.objects.Command.CommandStatus; -import bjc.utils.funcutils.StringUtils; +import bjc.utils.parserutils.*; /* * @TODO 10/09/17 :DefineCLIFinish @@ -130,7 +130,7 @@ public class DefineCLI { } private CommandStatus defString(Command com) { - List<String> arguments = StringUtils.processArguments(com.remn); + List<String> arguments = TokenUtils.processArguments(com.remn); if (arguments.size() < 1) { LOGGER.severe(com.error( @@ -158,7 +158,7 @@ public class DefineCLI { } private CommandStatus defFormat(Command com) { - List<String> arguments = StringUtils.processArguments(com.remn); + List<String> arguments = TokenUtils.processArguments(com.remn); if (arguments.size() < 1) { LOGGER.severe(com.error( @@ -186,7 +186,7 @@ public class DefineCLI { } private CommandStatus bindFormat(Command com) { - List<String> strings = StringUtils.processArguments(com.remn); + List<String> strings = TokenUtils.processArguments(com.remn); if (strings.size() < 2) { LOGGER.severe(com.error( diff --git a/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java b/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java index a6820f2..53d6d1e 100644 --- a/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java +++ b/base/src/main/java/bjc/utils/cli/objects/DelimSplitterCLI.java @@ -10,9 +10,9 @@ import java.util.List; import java.util.Map; import java.util.Scanner; -import bjc.data.ITree; +import bjc.data.Tree; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.utils.funcutils.StringUtils; import bjc.utils.ioutils.MirrorDB; import bjc.utils.parserutils.delims.DelimiterException; @@ -359,7 +359,7 @@ public class DelimSplitterCLI { private void handleDelim(final String args) { try { - final ITree<String> res = dlm.delimitSequence(args.split(" ")); + final Tree<String> res = dlm.delimitSequence(args.split(" ")); printDelimSeq(res); } catch (final DelimiterException dex) { @@ -372,14 +372,14 @@ public class DelimSplitterCLI { for (int i = 0; i < argArray.length; i++) { final String arg = argArray[i]; - final IList<String> strangs = split.split(arg); + final ListEx<String> strangs = split.split(arg); System.out.printf("%d '%s' %s\n", i, arg, strangs); } } private void handleTest(final String inp, final boolean splitWS) { - IList<String> strings; + ListEx<String> strings; try { strings = split.split(inp); @@ -400,7 +400,7 @@ public class DelimSplitterCLI { strings = new FunctionalList<>(tks); } try { - final ITree<String> delim + final Tree<String> delim = dlm.delimitSequence(strings.toArray(new String[0])); printDelimSeq(delim); @@ -410,7 +410,7 @@ public class DelimSplitterCLI { } } - private void printDelimSeq(final ITree<String> delim) { + private void printDelimSeq(final Tree<String> delim) { System.out.println("Delimited tokens:\n" + delim.getChild(1).toString()); System.out.print("Delimited expr: "); printDelimTree(delim); @@ -420,7 +420,7 @@ public class DelimSplitterCLI { System.out.println(); } - private void printDelimTree(final ITree<String> tree) { + private void printDelimTree(final Tree<String> tree) { final StringBuilder sb = new StringBuilder(); intPrintDelimTree(tree.getChild(1), sb); @@ -428,13 +428,13 @@ public class DelimSplitterCLI { System.out.println(sb.toString().replaceAll("\\s+", " ")); } - private void intPrintDelimTree(final ITree<String> tree, final StringBuilder sb) { + private void intPrintDelimTree(final Tree<String> tree, final StringBuilder sb) { tree.doForChildren(child -> { intPrintDelimNode(child, sb); }); } - private void intPrintDelimNode(final ITree<String> tree, final StringBuilder sb) { + private void intPrintDelimNode(final Tree<String> tree, final StringBuilder sb) { if (tree.getHead().equals("contents")) { intPrintDelimTree(tree, sb); return; @@ -458,7 +458,7 @@ public class DelimSplitterCLI { case 3: intPrintDelimNode(tree.getChild(0), sb); - final ITree<String> contents = tree.getChild(1); + final Tree<String> contents = tree.getChild(1); intPrintDelimTree(contents.getChild(0), sb); intPrintDelimNode(tree.getChild(2), sb); diff --git a/base/src/main/java/bjc/utils/components/ComponentDescription.java b/base/src/main/java/bjc/utils/components/ComponentDescription.java index 189ef90..2feed8d 100644 --- a/base/src/main/java/bjc/utils/components/ComponentDescription.java +++ b/base/src/main/java/bjc/utils/components/ComponentDescription.java @@ -5,7 +5,7 @@ package bjc.utils.components; * * @author ben */ -public class ComponentDescription implements IDescribedComponent { +public class ComponentDescription implements DescribedComponent { /* Check arguments are good. */ @SuppressWarnings("unused") private static void sanityCheckArgs(final String name, final String author, @@ -58,7 +58,7 @@ public class ComponentDescription implements IDescribedComponent { @Override public String getAuthor() { if (author == null) { - return IDescribedComponent.super.getAuthor(); + return DescribedComponent.super.getAuthor(); } return author; @@ -67,7 +67,7 @@ public class ComponentDescription implements IDescribedComponent { @Override public String getDescription() { if (description == null) { - return IDescribedComponent.super.getDescription(); + return DescribedComponent.super.getDescription(); } return description; diff --git a/base/src/main/java/bjc/utils/components/IComponentRepository.java b/base/src/main/java/bjc/utils/components/ComponentRepository.java index 5ebb1de..120edc8 100644 --- a/base/src/main/java/bjc/utils/components/IComponentRepository.java +++ b/base/src/main/java/bjc/utils/components/ComponentRepository.java @@ -1,25 +1,25 @@ package bjc.utils.components; -import bjc.funcdata.IList; -import bjc.funcdata.IMap; +import bjc.funcdata.ListEx; +import bjc.funcdata.MapEx; /** * A collection of implementations of a particular type of - * {@link IDescribedComponent}. + * {@link DescribedComponent}. * * @author ben * * @param <ComponentType> * The type of components contained in this repository. */ -public interface IComponentRepository<ComponentType extends IDescribedComponent> { +public interface ComponentRepository<ComponentType extends DescribedComponent> { /** * Get all of the components this repository knows about. * * @return A map from component name to component, containing all of the * components in the repositories. */ - public IMap<String, ComponentType> getAll(); + public MapEx<String, ComponentType> getAll(); /** * Get a component with a specific name. @@ -36,7 +36,7 @@ public interface IComponentRepository<ComponentType extends IDescribedComponent> * * @return A list of all the registered components. */ - public default IList<ComponentType> getList() { + public default ListEx<ComponentType> getList() { return getAll().valueList(); } diff --git a/base/src/main/java/bjc/utils/components/IDescribedComponent.java b/base/src/main/java/bjc/utils/components/DescribedComponent.java index ae3e06c..dcbaf59 100644 --- a/base/src/main/java/bjc/utils/components/IDescribedComponent.java +++ b/base/src/main/java/bjc/utils/components/DescribedComponent.java @@ -7,7 +7,7 @@ package bjc.utils.components; * @author ben * */ -public interface IDescribedComponent extends Comparable<IDescribedComponent> { +public interface DescribedComponent extends Comparable<DescribedComponent> { /** * Get the author of this component. * @@ -52,7 +52,7 @@ public interface IDescribedComponent extends Comparable<IDescribedComponent> { } @Override - default int compareTo(final IDescribedComponent o) { + default int compareTo(final DescribedComponent o) { int res = getName().compareTo(o.getName()); if (res == 0) { diff --git a/base/src/main/java/bjc/utils/components/FileComponentRepository.java b/base/src/main/java/bjc/utils/components/FileComponentRepository.java index 82d2770..e0e929f 100644 --- a/base/src/main/java/bjc/utils/components/FileComponentRepository.java +++ b/base/src/main/java/bjc/utils/components/FileComponentRepository.java @@ -9,11 +9,11 @@ import java.util.function.Function; import java.util.logging.Level; import java.util.logging.Logger; -import bjc.data.IHolder; +import bjc.data.Holder; import bjc.data.Identity; import bjc.funcdata.FunctionalMap; -import bjc.funcdata.IList; -import bjc.funcdata.IMap; +import bjc.funcdata.ListEx; +import bjc.funcdata.MapEx; import bjc.utils.funcutils.FileUtils; /** @@ -24,14 +24,14 @@ import bjc.utils.funcutils.FileUtils; * @param <ComponentType> * The type of component being read in. */ -public class FileComponentRepository<ComponentType extends IDescribedComponent> - implements IComponentRepository<ComponentType> { +public class FileComponentRepository<ComponentType extends DescribedComponent> + implements ComponentRepository<ComponentType> { /* The logger to use for storing data about this class. */ private static final Logger CLASS_LOGGER = Logger.getLogger("FileComponentRepository"); /* The internal storage of components. */ - private IMap<String, ComponentType> components; + private MapEx<String, ComponentType> components; /* The path that all the components came from. */ private Path sourceDirectory; @@ -69,7 +69,7 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> sourceDirectory = directory.toPath().toAbsolutePath(); /* Marker for making sure we don't skip the parent. */ - final IHolder<Boolean> isFirstDir = new Identity<>(true); + final Holder<Boolean> isFirstDir = new Identity<>(true); /* * Predicate to use to traverse all the files in a directory, but not recurse @@ -110,17 +110,17 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> } @Override - public IMap<String, ComponentType> getAll() { + public MapEx<String, ComponentType> getAll() { return components; } @Override public ComponentType getByName(final String name) { - return components.get(name); + return components.get(name).get(); } @Override - public IList<ComponentType> getList() { + public ListEx<ComponentType> getList() { return components.valueList(); } diff --git a/base/src/main/java/bjc/utils/components/MemoryComponentRepository.java b/base/src/main/java/bjc/utils/components/MemoryComponentRepository.java index ec3911e..f83c293 100644 --- a/base/src/main/java/bjc/utils/components/MemoryComponentRepository.java +++ b/base/src/main/java/bjc/utils/components/MemoryComponentRepository.java @@ -1,6 +1,6 @@ package bjc.utils.components; -import bjc.funcdata.IMap; +import bjc.funcdata.MapEx; /** * A repository of components stored in memory. @@ -10,9 +10,9 @@ import bjc.funcdata.IMap; * @param <ComponentType> * The type of component stored in the repository. */ -public class MemoryComponentRepository<ComponentType extends IDescribedComponent> - implements IComponentRepository<ComponentType> { - private final IMap<String, ComponentType> repo; +public class MemoryComponentRepository<ComponentType extends DescribedComponent> + implements ComponentRepository<ComponentType> { + private final MapEx<String, ComponentType> repo; private final String source; @@ -22,7 +22,7 @@ public class MemoryComponentRepository<ComponentType extends IDescribedComponent * @param repo * The set of components to use. */ - public MemoryComponentRepository(IMap<String, ComponentType> repo) { + public MemoryComponentRepository(MapEx<String, ComponentType> repo) { this(repo, "memory"); } @@ -34,20 +34,20 @@ public class MemoryComponentRepository<ComponentType extends IDescribedComponent * @param source * Where the components came from. */ - public MemoryComponentRepository(IMap<String, ComponentType> repo, String source) { + public MemoryComponentRepository(MapEx<String, ComponentType> repo, String source) { this.repo = repo; this.source = source; } @Override - public IMap<String, ComponentType> getAll() { + public MapEx<String, ComponentType> getAll() { return repo; } @Override public ComponentType getByName(String name) { - return repo.get(name); + return repo.get(name).get(); } @Override diff --git a/base/src/main/java/bjc/utils/funcutils/IBuilder.java b/base/src/main/java/bjc/utils/funcutils/Builder.java index b1a2020..72c045d 100644 --- a/base/src/main/java/bjc/utils/funcutils/IBuilder.java +++ b/base/src/main/java/bjc/utils/funcutils/Builder.java @@ -8,7 +8,7 @@ package bjc.utils.funcutils; * @param <E> * The type of object being built. */ -public interface IBuilder<E> { +public interface Builder<E> { /** * Build the object this builder is building. * diff --git a/base/src/main/java/bjc/utils/funcutils/Callables.java b/base/src/main/java/bjc/utils/funcutils/Callables.java new file mode 100644 index 0000000..5895347 --- /dev/null +++ b/base/src/main/java/bjc/utils/funcutils/Callables.java @@ -0,0 +1,60 @@ +package bjc.utils.funcutils; + +import java.util.concurrent.*; +import java.util.function.*; + +/** + * Utility function for dealing with callables and other things. + * + * @author Ben Culkin + * + */ +public class Callables +{ + /** + * Perform a 'bind' that appends a function to a callable. + * + * @param <Input> The type originally returned by the callable. + * @param <Output> The type returned by the function. + * + * @param call The original callable. + * @param func The function to use to transform the result. + * + * @return A callable which applies the given function to the result of them. + */ + public static <Input, Output> Callable<Output> bind( + Callable<Input> call, Function<Input, Callable<Output>> func) + { + return () -> func.apply(call.call()).call(); + } + + /** + * Convert a normal function to a function on callables. + * + * @param <Input> The input to the function. + * @param <Output> The output from the function. + * + * @param func The function to convert. + * + * @return The function, made to work over callables. + */ + public static <Input, Output> Function<Callable<Input>, Callable<Output>> + fmap(Function<Input, Output> func) + { + return (inp) -> () -> func.apply(inp.call()); + } + + /** + * Convert a future into a callable. + * + * @param <Output> The type returned by the future. + * + * @param fut The future to convert. + * + * @return A future which yields that value. + */ + public static <Output> Callable<Output> obtain(Future<Output> fut) + { + return () -> fut.get(); + } +} diff --git a/base/src/main/java/bjc/utils/funcutils/ChainIterator.java b/base/src/main/java/bjc/utils/funcutils/ChainIterator.java new file mode 100644 index 0000000..36f94e5 --- /dev/null +++ b/base/src/main/java/bjc/utils/funcutils/ChainIterator.java @@ -0,0 +1,54 @@ +package bjc.utils.funcutils; + +import java.util.*; +import java.util.function.*; + +/** + * A chain iterator. This is essentially flatMap in iterator form. + * + * @author bjculkin + * + * @param <T1> + * The type of the input values. + * + * @param <T2> + * The type of the output values. + */ +public class ChainIterator<T1, T2> implements Iterator<T2> { + private Iterator<T1> mainItr; + private Function<T1, Iterator<T2>> trans; + + private Iterator<T2> curItr; + + /** + * Create a new chain iterator. + * + * @param mainItr + * The main iterator for input. + * + * @param trans + * The transformation to use to produce the outputs. + */ + public ChainIterator(Iterator<T1> mainItr, Function<T1, Iterator<T2>> trans) { + this.mainItr = mainItr; + this.trans = trans; + } + + @Override + public boolean hasNext() { + if (curItr != null) { + return curItr.hasNext() ? true : mainItr.hasNext(); + } + + return mainItr.hasNext(); + } + + @Override + public T2 next() { + if (curItr == null || !curItr.hasNext()) { + curItr = trans.apply(mainItr.next()); + } + + return curItr.next(); + } +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java b/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java index 81313c8..a92c2d1 100644 --- a/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/CollectorUtils.java @@ -2,8 +2,8 @@ package bjc.utils.funcutils; import java.util.stream.Collector; -import bjc.data.IHolder; -import bjc.data.IPair; +import bjc.data.Holder; +import bjc.data.Pair; /** * Utilities for producing implementations of {@link Collector} @@ -38,8 +38,8 @@ public class CollectorUtils { * @return A collector that functions as mentioned above. */ public static <InitialType, AuxType1, AuxType2, FinalType1, FinalType2> - Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, - IPair<FinalType1, FinalType2>> + Collector<InitialType, Holder<Pair<AuxType1, AuxType2>>, + Pair<FinalType1, FinalType2>> compoundCollect(final Collector<InitialType, AuxType1, FinalType1> first, final Collector<InitialType, AuxType2, FinalType2> second) { return new CompoundCollector<>(first, second); diff --git a/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java b/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java index 5e51c20..5aa266e 100644 --- a/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java +++ b/base/src/main/java/bjc/utils/funcutils/CompoundCollector.java @@ -7,10 +7,10 @@ import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collector; -import bjc.data.IHolder; -import bjc.data.IPair; -import bjc.data.Identity; +import bjc.data.Holder; import bjc.data.Pair; +import bjc.data.Identity; +import bjc.data.SimplePair; /** * Implementation of a collecter that uses two collectors. @@ -18,8 +18,8 @@ import bjc.data.Pair; * @author Ben Culkin */ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, FinalType2> - implements Collector<InitialType, IHolder<IPair<AuxType1, AuxType2>>, - IPair<FinalType1, FinalType2>> { + implements Collector<InitialType, Holder<Pair<AuxType1, AuxType2>>, + Pair<FinalType1, FinalType2>> { /* Our characteristics. */ private final Set<java.util.stream.Collector.Characteristics> characteristicSet; @@ -48,7 +48,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final } @Override - public BiConsumer<IHolder<IPair<AuxType1, AuxType2>>, InitialType> accumulator() { + public BiConsumer<Holder<Pair<AuxType1, AuxType2>>, InitialType> accumulator() { final BiConsumer<AuxType1, InitialType> firstAccumulator = first.accumulator(); final BiConsumer<AuxType2, InitialType> secondAccumulator = second.accumulator(); @@ -68,7 +68,7 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final } @Override - public BinaryOperator<IHolder<IPair<AuxType1, AuxType2>>> combiner() { + public BinaryOperator<Holder<Pair<AuxType1, AuxType2>>> combiner() { final BinaryOperator<AuxType1> firstCombiner = first.combiner(); final BinaryOperator<AuxType2> secondCombiner = second.combiner(); @@ -80,25 +80,25 @@ final class CompoundCollector<InitialType, AuxType1, AuxType2, FinalType1, Final } @Override - public Function<IHolder<IPair<AuxType1, AuxType2>>, IPair<FinalType1, FinalType2>> + public Function<Holder<Pair<AuxType1, AuxType2>>, Pair<FinalType1, FinalType2>> finisher() { return state -> state.unwrap(pair -> { return pair.bind((left, right) -> { final FinalType1 finalLeft = first.finisher().apply(left); final FinalType2 finalRight = second.finisher().apply(right); - return new Pair<>(finalLeft, finalRight); + return new SimplePair<>(finalLeft, finalRight); }); }); } @Override - public Supplier<IHolder<IPair<AuxType1, AuxType2>>> supplier() { + public Supplier<Holder<Pair<AuxType1, AuxType2>>> supplier() { return () -> { final AuxType1 initialLeft = first.supplier().get(); final AuxType2 initialRight = second.supplier().get(); - return new Identity<>(new Pair<>(initialLeft, initialRight)); + return new Identity<>(new SimplePair<>(initialLeft, initialRight)); }; } } diff --git a/base/src/main/java/bjc/utils/funcutils/EnumUtils.java b/base/src/main/java/bjc/utils/funcutils/EnumUtils.java index e8898ca..6d53952 100644 --- a/base/src/main/java/bjc/utils/funcutils/EnumUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/EnumUtils.java @@ -4,7 +4,7 @@ import java.util.Random; import java.util.function.Consumer; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * Utility methods on enums. @@ -34,7 +34,7 @@ public class EnumUtils { final int nValues, final Consumer<E> action, final Random rnd) { final E[] enumValues = clasz.getEnumConstants(); - final IList<E> valueList = new FunctionalList<>(enumValues); + final ListEx<E> valueList = new FunctionalList<>(enumValues); final int randomValueCount = enumValues.length - nValues; diff --git a/base/src/main/java/bjc/utils/funcutils/FuncUtils.java b/base/src/main/java/bjc/utils/funcutils/FuncUtils.java index 70e521a..2c65876 100644 --- a/base/src/main/java/bjc/utils/funcutils/FuncUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/FuncUtils.java @@ -29,9 +29,12 @@ public class FuncUtils { * * @return The function transformed into a unary function returning a function. */ - public static <A, B, C> Function<A, Function<B, C>> - curry2(final BiFunction<A, B, C> func) { - return arg1 -> arg2 -> func.apply(arg1, arg2); + public static <A, B, C> Function<A, Function<B, C>> curry2( + final BiFunction<A, B, C> func) + { + return arg1 -> + arg2 -> + func.apply(arg1, arg2); } /** @@ -43,14 +46,17 @@ public class FuncUtils { * @param cons * The action to perform. */ - public static void doTimes(final int nTimes, final Consumer<Integer> cons) { - for (int i = 0; i < nTimes; i++) { - cons.accept(i); - } + public static void doTimes( + final int nTimes, + final Consumer<Integer> cons) + { + for (int i = 0; i < nTimes; i++) cons.accept(i); } /** * Return an operator that executes until it converges. + * + * @param <T> The type the operator is on. * * @param op * The operator to execute. @@ -62,12 +68,15 @@ public class FuncUtils { * @return The requested operator. */ public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, - final int maxTries) { + final int maxTries) + { return converge(op, Object::equals, maxTries); } /** * Return an operator that executes until it converges. + * + * @param <T> The type the operator is on. * * @param op * The operator to execute. @@ -81,11 +90,14 @@ public class FuncUtils { * * @return The requested operator. */ - public static <T> UnaryOperator<T> converge(final UnaryOperator<T> op, - final BiPredicate<T, T> converged, final int maxTries) { + public static <T> UnaryOperator<T> converge( + final UnaryOperator<T> op, + final BiPredicate<T, T> converged, + final int maxTries) + { return val -> { T newVal = op.apply(val); - T oldVal; + T oldVal = newVal; int tries = 0; diff --git a/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java b/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java deleted file mode 100644 index 681d707..0000000 --- a/base/src/main/java/bjc/utils/funcutils/GroupPartIteration.java +++ /dev/null @@ -1,86 +0,0 @@ -package bjc.utils.funcutils; - -import java.util.function.Consumer; -import java.util.function.Function; - -import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; - -/** - * Implements a single group partitioning pass on a list. - * - * @author ben - * - * @param <E> - * The type of element in the list being partitioned - */ -final class GroupPartIteration<E> implements Consumer<E> { - /* The list we're returning. */ - private final IList<IList<E>> returnedList; - - /* The current partition of the list. */ - public IList<E> currentPartition; - /* The items rejected from the current partition. */ - private final IList<E> rejectedItems; - - /* The number of items in the current partition. */ - private int numberInCurrentPartition; - /* The number of items in each partition. */ - private final int numberPerPartition; - - /* The function to use to count an item. */ - private final Function<E, Integer> elementCounter; - - /** - * Create a new group partitioning iteration. - * - * @param returned - * The list containing all of the existing partitions. - * - * @param rejects - * The items that have been rejected from a partition for being - * too large. - * - * @param nPerPart - * The combined value of items that should go into each - * partition. - * - * @param eleCount - * The function to use to determine the value of an item. - */ - public GroupPartIteration(final IList<IList<E>> returned, final IList<E> rejects, - final int nPerPart, final Function<E, Integer> eleCount) { - this.returnedList = returned; - this.rejectedItems = rejects; - this.numberPerPartition = nPerPart; - this.elementCounter = eleCount; - - this.currentPartition = new FunctionalList<>(); - this.numberInCurrentPartition = 0; - } - - @Override - public void accept(final E value) { - final boolean shouldStartPartition - = numberInCurrentPartition >= numberPerPartition; - - if (shouldStartPartition) { - returnedList.add(currentPartition); - - currentPartition = new FunctionalList<>(); - numberInCurrentPartition = 0; - } else { - final int currentElementCount = elementCounter.apply(value); - - final boolean shouldReject = (numberInCurrentPartition + currentElementCount) - >= numberPerPartition; - - if (shouldReject) { - rejectedItems.add(value); - } else { - currentPartition.add(value); - numberInCurrentPartition += currentElementCount; - } - } - } -} diff --git a/base/src/main/java/bjc/utils/funcutils/Isomorphism.java b/base/src/main/java/bjc/utils/funcutils/Isomorphism.java deleted file mode 100644 index c219d7f..0000000 --- a/base/src/main/java/bjc/utils/funcutils/Isomorphism.java +++ /dev/null @@ -1,59 +0,0 @@ -package bjc.utils.funcutils; - -import java.util.function.Function; - -/** - * A pair of functions to transform between a pair of types. - * - * @author bjculkin - * - * @param <S> - * The source type of the isomorphism. - * - * @param <D> - * The destination type of isomorphism. - */ -public class Isomorphism<S, D> { - /* The function to the destination type. */ - private Function<S, D> toFunc; - /* The function to the source type. */ - private Function<D, S> fromFunc; - - /** - * Create a new isomorphism. - * - * @param to - * The 'forward' function, from the source to the definition. - * - * @param from - * The 'backward' function, from the definition to the source. - */ - public Isomorphism(Function<S, D> to, Function<D, S> from) { - toFunc = to; - fromFunc = from; - } - - /** - * Apply the isomorphism forward. - * - * @param val - * The source value. - * - * @return The destination value. - */ - public D to(S val) { - return toFunc.apply(val); - } - - /** - * Apply the isomorphism backward. - * - * @param val - * The destination value. - * - * @return The source value. - */ - public S from(D val) { - return fromFunc.apply(val); - } -} diff --git a/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java b/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java index 8d51996..662b1bf 100644 --- a/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/IteratorUtils.java @@ -3,7 +3,7 @@ package bjc.utils.funcutils; import java.util.*; import java.util.function.*; -import bjc.data.ArrayIterator; +import bjc.data.*; /** * Utility methods for dealing with iterators. @@ -13,57 +13,9 @@ import bjc.data.ArrayIterator; */ public class IteratorUtils { /** - * A chain iterator. This is essentially flatMap in iterator form. - * - * @author bjculkin - * - * @param <T1> - * The type of the input values. - * - * @param <T2> - * The type of the output values. - */ - public static class ChainIterator<T1, T2> implements Iterator<T2> { - private Iterator<T1> mainItr; - private Function<T1, Iterator<T2>> trans; - - private Iterator<T2> curItr; - - /** - * Create a new chain iterator. - * - * @param mainItr - * The main iterator for input. - * - * @param trans - * The transformation to use to produce the outputs. - */ - public ChainIterator(Iterator<T1> mainItr, Function<T1, Iterator<T2>> trans) { - this.mainItr = mainItr; - this.trans = trans; - } - - @Override - public boolean hasNext() { - if (curItr != null) { - return curItr.hasNext() ? true : mainItr.hasNext(); - } - - return mainItr.hasNext(); - } - - @Override - public T2 next() { - if (curItr == null || !curItr.hasNext()) { - curItr = trans.apply(mainItr.next()); - } - - return curItr.next(); - } - } - - /** * Convert an iterator to an iterable. + * + * @param <E> The type being iterated over. * * @param itr * The iterator to convert. @@ -77,6 +29,8 @@ public class IteratorUtils { /** * Convert an iterable to an iterator. * + * @param <E> The type being iterated over. + * * @param itr * The iterable to convert. * @@ -89,18 +43,23 @@ public class IteratorUtils { /** * Convert an array to an iterator. * + * @param <E> The type being iterated over. + * * @param parms * The array to iterate over. * * @return An iterator over the provided array. */ @SafeVarargs - public static <E> Iterator<E> AI(E... parms) { + public static <E> Iterator<E> I(E... parms) { return new ArrayIterator<>(parms); } /** * Create a chain iterator. + * + * @param <A> The initial type being iterated over. + * @param <B> The resulting type being iterated over. * * @param itrA * The iterator for input values. @@ -114,4 +73,43 @@ public class IteratorUtils { Function<A, Iterator<B>> itrB) { return new ChainIterator<>(itrA, itrB); } + + /** + * Perform a left-fold over an iterator. + * + * @param <ElementType> The type of elements in the iterator. + * @param <ResultType> The result from the fold. + * + * @param itr The items to iterate over. + * @param zero The initial element for the fold. + * @param folder The function that does the folding. + * + * @return The result of folding over the iterator. + */ + public static <ElementType, ResultType> ResultType foldLeft( + Iterable<ElementType> itr, + ResultType zero, + BiFunction<ElementType, ResultType, ResultType> folder) + { + ResultType state = zero; + for (ElementType elem : itr) { + state = folder.apply(elem, state); + } + return state; + } + + /** + * Creates an 'entangled' pair of a consumer and an iterator. + * + * @param <ElementType> The type of value involved. + * + * @return A pair consisting of a consumer of values, and an iterator that + * yields the consumed values. + */ + public static <ElementType> + Pair<Consumer<ElementType>, Iterator<ElementType>> entangle() + { + Queue<ElementType> backer = new ArrayDeque<>(); + return Pair.pair(backer::add, new QueueBackedIterator<>(backer)); + } } diff --git a/base/src/main/java/bjc/utils/funcutils/LambdaLock.java b/base/src/main/java/bjc/utils/funcutils/LambdaLock.java index f3637f9..c7ba09a 100644 --- a/base/src/main/java/bjc/utils/funcutils/LambdaLock.java +++ b/base/src/main/java/bjc/utils/funcutils/LambdaLock.java @@ -36,8 +36,9 @@ public class LambdaLock { /** * Execute an action with the read lock taken. * - * @param supp - * The action to call. + * @param <T> The type returned by the action. + * + * @param supp The action to call. * * @return The result of the action. */ @@ -53,9 +54,10 @@ public class LambdaLock { /** * Execute an action with the write lock taken. - * - * @param supp - * The action to call. + * + * @param <T> The type returned by the action. + * + * @param supp The action to call. * * @return The result of the action. */ diff --git a/base/src/main/java/bjc/utils/funcutils/ListUtils.java b/base/src/main/java/bjc/utils/funcutils/ListUtils.java index f689d6c..ab32ccc 100644 --- a/base/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -1,14 +1,10 @@ package bjc.utils.funcutils; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.LinkedList; -import java.util.List; -import java.util.function.Function; -import java.util.function.Supplier; +import java.util.*; +import java.util.function.*; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * Utilities for manipulating FunctionalLists and regular Collections lists that @@ -28,9 +24,8 @@ public class ListUtils { * * @return The collapsed string of tokens. */ - public static String collapseTokens(final IList<String> input) { - if (input == null) - throw new NullPointerException("Input must not be null"); + public static String collapseTokens(final ListEx<String> input) { + if (input == null) throw new NullPointerException("Input must not be null"); return collapseTokens(input, ""); } @@ -47,13 +42,10 @@ public class ListUtils { * * @return The collapsed string of tokens. */ - public static String collapseTokens(final IList<String> input, + public static String collapseTokens(final ListEx<String> input, final String seperator) { - if (input == null) { - throw new NullPointerException("Input must not be null"); - } else if (seperator == null) { - throw new NullPointerException("Seperator must not be null"); - } + if (input == null) throw new NullPointerException("Input must not be null"); + else if (seperator == null) throw new NullPointerException("Seperator must not be null"); if (input.getSize() < 1) { return ""; @@ -66,9 +58,7 @@ public class ListUtils { for (final String itm : input.toIterable()) { state.append(itm); - if (i != input.getSize()) { - state.append(seperator); - } + if (i != input.getSize()) state.append(seperator); i += 1; } @@ -96,9 +86,9 @@ public class ListUtils { * @return A new list containing the desired number of items randomly selected * from the specified list without replacement. */ - public static <E> IList<E> drawWithoutReplacement(final IList<E> list, + public static <E> ListEx<E> drawWithoutReplacement(final ListEx<E> list, final int number, final Function<Integer, Integer> rng) { - final IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); + final ListEx<E> selected = new FunctionalList<>(new ArrayList<>(number)); final int total = list.getSize(); @@ -140,13 +130,11 @@ public class ListUtils { * @return A new list containing the desired number of items randomly selected * from the specified list. */ - public static <E> IList<E> drawWithReplacement(final IList<E> list, final int number, + public static <E> ListEx<E> drawWithReplacement(final ListEx<E> list, final int number, final Function<Integer, Integer> rng) { - final IList<E> selected = new FunctionalList<>(new ArrayList<>(number)); + final ListEx<E> selected = new FunctionalList<>(new ArrayList<>(number)); - for (int i = 0; i < number; i++) { - selected.add(list.randItem(rng)); - } + for (int i = 0; i < number; i++) selected.add(list.randItem(rng)); return selected; } @@ -170,7 +158,7 @@ public class ListUtils { * * @return A list partitioned according to the above rules. */ - public static <E> IList<IList<E>> groupPartition(final IList<E> input, + public static <E> ListEx<ListEx<E>> groupPartition(final ListEx<E> input, final Function<E, Integer> counter, final int partitionSize) { if (input == null) { throw new NullPointerException("Input list must not be null"); @@ -185,10 +173,10 @@ public class ListUtils { } /* List that holds our results. */ - final IList<IList<E>> returned = new FunctionalList<>(); + final ListEx<ListEx<E>> returned = new FunctionalList<>(); /* List that holds elements rejected during current pass. */ - final IList<E> rejected = new FunctionalList<>(); + final ListEx<E> rejected = new FunctionalList<>(); final GroupPartIteration<E> it = new GroupPartIteration<>(returned, rejected, partitionSize, counter); @@ -199,10 +187,8 @@ public class ListUtils { numberOfIterations++) { input.forEach(it); - if (rejected.isEmpty()) { - /* Nothing was rejected, so we're done. */ - return returned; - } + /* Nothing was rejected, so we're done. */ + if (rejected.isEmpty()) return returned; } final String fmt @@ -226,13 +212,11 @@ public class ListUtils { * @return A list containing all the elements of the lists. */ @SafeVarargs - public static <E> IList<E> mergeLists(final IList<E>... lists) { - final IList<E> returned = new FunctionalList<>(); + public static <E> ListEx<E> mergeLists(final ListEx<E>... lists) { + final ListEx<E> returned = new FunctionalList<>(); - for (final IList<E> list : lists) { - for (final E itm : list.toIterable()) { - returned.add(itm); - } + for (final ListEx<E> list : lists) { + for (final E itm : list.toIterable()) returned.add(itm); } return returned; @@ -262,12 +246,12 @@ public class ListUtils { * If the list couldn't be padded to the * desired size. */ - public static <E> IList<E> padList(final IList<E> list, + public static <E> ListEx<E> padList(final ListEx<E> list, final Function<E, Integer> counter, final int size, final Supplier<E> padder) { int count = 0; - final IList<E> returned = new FunctionalList<>(); + final ListEx<E> returned = new FunctionalList<>(); for (final E itm : list.toIterable()) { count += counter.apply(itm); @@ -334,8 +318,9 @@ public class ListUtils { * * This is a version of Algorith P (Plain Changes) from Knuth (vol 4A, pg 322) * - * @param list - * The list to generate permutations from. + * @param <T> The type of elements in the list. + * + * @param list The list to generate permutations from. * @return The list of permutations of the list. */ public static <T> List<List<T>> permuteList(List<T> list) { @@ -344,9 +329,7 @@ public class ListUtils { /* * Special-case small usages. */ - if (list.size() == 0) { - return permutes; - } + if (list.size() == 0) return permutes; if (list.size() == 1) { permutes.add(list); @@ -358,19 +341,8 @@ public class ListUtils { T elm1 = list.get(0); T elm2 = list.get(1); - List<T> currPerm = new ArrayList<>(2); - - currPerm.add(elm1); - currPerm.add(elm2); - - permutes.add(currPerm); - - currPerm = new ArrayList<>(2); - - currPerm.add(elm2); - currPerm.add(elm1); - - permutes.add(currPerm); + permutes.add(Arrays.asList(elm1, elm2)); + permutes.add(Arrays.asList(elm2, elm1)); return permutes; } @@ -384,9 +356,7 @@ public class ListUtils { } List<T> currentPermute = new ArrayList<>(list.size()); - for (T elm : list) { - currentPermute.add(elm); - } + for (T elm : list) currentPermute.add(elm); permutes.add(currentPermute); int j = list.size() - 1; @@ -422,9 +392,7 @@ public class ListUtils { auxC[j] = q; currentPermute = new ArrayList<>(list.size()); - for (T elm : list) { - currentPermute.add(elm); - } + for (T elm : list) currentPermute.add(elm); permutes.add(currentPermute); j = list.size() - 1; @@ -441,3 +409,82 @@ public class ListUtils { list.set(b, tmp); } } + +/** + * Implements a single group partitioning pass on a list. + * + * @author ben + * + * @param <E> + * The type of element in the list being partitioned + */ +class GroupPartIteration<E> implements Consumer<E> { + /* The list we're returning. */ + private final ListEx<ListEx<E>> returnedList; + + /* The current partition of the list. */ + public ListEx<E> currentPartition; + /* The items rejected from the current partition. */ + private final ListEx<E> rejectedItems; + + /* The number of items in the current partition. */ + private int numberInCurrentPartition; + /* The number of items in each partition. */ + private final int numberPerPartition; + + /* The function to use to count an item. */ + private final Function<E, Integer> elementCounter; + + /** + * Create a new group partitioning iteration. + * + * @param returned + * The list containing all of the existing partitions. + * + * @param rejects + * The items that have been rejected from a partition for being + * too large. + * + * @param nPerPart + * The combined value of items that should go into each + * partition. + * + * @param eleCount + * The function to use to determine the value of an item. + */ + public GroupPartIteration(final ListEx<ListEx<E>> returned, final ListEx<E> rejects, + final int nPerPart, final Function<E, Integer> eleCount) { + this.returnedList = returned; + this.rejectedItems = rejects; + this.numberPerPartition = nPerPart; + this.elementCounter = eleCount; + + this.currentPartition = new FunctionalList<>(); + this.numberInCurrentPartition = 0; + } + + @Override + public void accept(final E value) { + final boolean shouldStartPartition + = numberInCurrentPartition >= numberPerPartition; + + if (shouldStartPartition) { + returnedList.add(currentPartition); + + currentPartition = new FunctionalList<>(); + numberInCurrentPartition = 0; + } else { + final int currentElementCount = elementCounter.apply(value); + + final boolean shouldReject = (numberInCurrentPartition + currentElementCount) + >= numberPerPartition; + + if (shouldReject) { + rejectedItems.add(value); + } else { + currentPartition.add(value); + numberInCurrentPartition += currentElementCount; + } + } + } +} diff --git a/base/src/main/java/bjc/utils/funcutils/QueueBackedIterator.java b/base/src/main/java/bjc/utils/funcutils/QueueBackedIterator.java new file mode 100644 index 0000000..8b9f401 --- /dev/null +++ b/base/src/main/java/bjc/utils/funcutils/QueueBackedIterator.java @@ -0,0 +1,36 @@ +package bjc.utils.funcutils; + +import java.util.*; + +/** + * An iterator backed by a queue. + * + * @author Ben Culkin + * + * @param <ElementType> The type of element + */ +public class QueueBackedIterator<ElementType> + implements Iterator<ElementType> +{ + private final Queue<ElementType> backer; + + /** + * Create a new queue-backed iterator. + * + * @param backer The queue which backs this iterator. + */ + public QueueBackedIterator(Queue<ElementType> backer) + { + this.backer = backer; + } + + @Override + public boolean hasNext() { + return !backer.isEmpty(); + } + + @Override + public ElementType next() { + return backer.remove(); + } +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/funcutils/SetUtils.java b/base/src/main/java/bjc/utils/funcutils/SetUtils.java index 83c191b..b721d10 100644 --- a/base/src/main/java/bjc/utils/funcutils/SetUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/SetUtils.java @@ -15,8 +15,8 @@ public class SetUtils { /** * Create a power-set (set of all subsets) of a given set. * - * @param originalSet - * The set to create a power-set of. + * @param <T> The type of elements contained in the set. + * @param originalSet The set to create a power-set of. * @return The power-set of the set. */ public static <T> Set<Set<T>> powerSet(Set<T> originalSet) { @@ -55,17 +55,15 @@ public class SetUtils { /** * Utility method for set construction. * - * @param elms - * The elements to stick in the set. + * @param <T> The type of elements in the set. + * @param elms The elements to stick in the set. * @return A set containing the specified elements. */ @SafeVarargs public static <T> Set<T> toSet(T... elms) { Set<T> set = new HashSet<>(); - for (T elm : elms) { - set.add(elm); - } + for (T elm : elms) set.add(elm); return set; } diff --git a/base/src/main/java/bjc/utils/funcutils/Strategy.java b/base/src/main/java/bjc/utils/funcutils/Strategy.java new file mode 100644 index 0000000..316879f --- /dev/null +++ b/base/src/main/java/bjc/utils/funcutils/Strategy.java @@ -0,0 +1,81 @@ +package bjc.utils.funcutils; + +import java.util.concurrent.*; +import java.util.function.*; + +/** + * Strategy for dealing with parallel execution. + * + * @author Ben Culkin + * + * @param <Output> The type returned by the tasks. + * + */ +public interface Strategy<Output> extends Function<Callable<Output>, Future<Output>> +{ + /** + * Convert a function into one which operates concurrently, using this strategy. + * + * @param <Input> The type of the function argument. + * + * @param func The type of the function. + * + * @return A function which executes concurrently. + */ + public default <Input> Function<Input, Future<Output>> using(Function<Input, Output> func) + { + return (input) -> this.apply(() -> func.apply(input)); + } + + /** + * A strategy which will run tasks in serial. + * + * @param <Output> The type returned by the task. + * + * @return A strategy which executes things serially. + */ + public static <Output> Strategy<Output> serial() + { + return (call) -> { + FutureTask<Output> task = new FutureTask<>(call); + task.run(); + return task; + }; + } + /** + * A strategy which creates a fresh thread to execute a task on. + * + * @param <Output> The type returned by the task. + * + * @return A strategy which uses threads to create tasks. + */ + public static <Output> Strategy<Output> simpleThread() + { + // I leave this as an example as of what is possible with combinators. + // return (call) -> invoke(introducing( + // () -> new FutureTask<>(call), + // (task, input) -> doWith( + // (FutureTask<Output> tsk) -> + // new Thread(task).start()).apply(task) + // )); + return (call) -> { + FutureTask<Output> task = new FutureTask<>(call); + new Thread(task).start(); + return task; + }; + } + + /** + * A strategy that uses an executor service. + * + * @param <Output> The type returned by the task. + * + * @param svc The executor service to use. + * + * @return A strategy which uses the provided executor. + */ + public static <Output> Strategy<Output> executorService(ExecutorService svc) + { + return svc::submit; + } +} diff --git a/base/src/main/java/bjc/utils/funcutils/StringUtils.java b/base/src/main/java/bjc/utils/funcutils/StringUtils.java index b7a6835..0b57e18 100644 --- a/base/src/main/java/bjc/utils/funcutils/StringUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/StringUtils.java @@ -1,79 +1,53 @@ package bjc.utils.funcutils; -import java.util.ArrayList; -import java.util.Deque; -import java.util.Iterator; -import java.util.List; -import java.util.Scanner; - +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.ibm.icu.text.BreakIterator; -import bjc.data.BooleanToggle; import bjc.utils.ioutils.LevelSplitter; -import bjc.utils.parserutils.TokenUtils; -/** - * Utility methods for operations on strings. +/** Utility methods for operations on strings. * - * @author ben - */ + * @author ben */ public class StringUtils { - /** - * Check if a string consists only of one or more matches of a regular + /**Check if a string consists only of one or more matches of a regular * expression. * - * @param input - * The string to check. - * - * @param rRegex - * The regex to see if the string only contains matches of. + * @param input The string to check. + * @param rRegex The regex to see if the string only contains matches of. * * @return Whether or not the string consists only of multiple matches of the * provided regex. */ public static boolean containsOnly(final String input, final String rRegex) { - if (input == null) - throw new NullPointerException("Input must not be null"); - else if (rRegex == null) - throw new NullPointerException("Regex must not be null"); + if (input == null) throw new NullPointerException("Input must not be null"); + else if (rRegex == null) throw new NullPointerException("Regex must not be null"); - /* - * This regular expression is fairly simple. + /* This regular expression is fairly simple. * * First, we match the beginning of the string. Then, we start a non-capturing * group whose contents are the passed in regex. That group is then matched one - * or more times and the pattern matches to the end of the string. - */ + * or more times and the pattern matches to the end of the string. */ return input.matches("\\A(?:" + rRegex + ")+\\Z"); } - /** - * Indent the string being built in a StringBuilder n levels. - * - * @param builder - * The builder to indent in. + /** Indent the string being built in a StringBuilder n levels. * - * @param levels - * The number of levels to indent. + * @param builder The builder to indent in. + * @param levels The number of levels to indent. */ public static void indentNLevels(final StringBuilder builder, final int levels) { - for (int i = 0; i < levels; i++) { - builder.append("\t"); - } + for (int i = 0; i < levels; i++) builder.append("\t"); } - /** - * Print out a deque with a special case for easily showing a deque is empty. - * - * @param <ContainedType> - * The type in the deque. + /** Print out a deque with a special case for easily showing a deque is empty. * - * @param queue - * The deque to print. + * @param <ContainedType> The type in the deque. * + * @param queue The deque to print. + * * @return A string version of the deque, with allowance for an empty deque. */ public static <ContainedType> String printDeque(final Deque<ContainedType> queue) { @@ -83,15 +57,10 @@ public class StringUtils { /** * Converts a sequence to an English list. * - * @param objects - * The sequence to convert to an English list. - * + * @param objects The sequence to convert to an English list. * @param join - * The string to use for separating the last element from the - * rest. - * - * @param comma - * The string to use as a comma + * The string to use for separating the last element from the rest. + * @param comma The string to use as a comma * * @return The sequence as an English list. */ @@ -140,15 +109,11 @@ public class StringUtils { return sb.toString(); } - /** - * Converts a sequence to an English list. - * - * @param objects - * The sequence to convert to an English list. + /** Converts a sequence to an English list. * + * @param objects The sequence to convert to an English list. * @param join - * The string to use for separating the last element from the - * rest. + * The string to use for separating the last element from the rest. * * @return The sequence as an English list. */ @@ -156,30 +121,21 @@ public class StringUtils { return toEnglishList(objects, join, ","); } - /** - * Converts a sequence to an English list. - * - * @param objects - * The sequence to convert to an English list. + /** Converts a sequence to an English list. * - * @param and - * Whether to use 'and' or 'or'. + * @param objects The sequence to convert to an English list. + * @param and Whether to use 'and' or 'or'. * * @return The sequence as an English list. */ public static String toEnglishList(final Object[] objects, final boolean and) { - if (and) { - return toEnglishList(objects, "and"); - } - - return toEnglishList(objects, "or"); + if (and) return toEnglishList(objects, "and"); + else return toEnglishList(objects, "or"); } - /** - * Count the number of graphemes in a string. + /** Count the number of graphemes in a string. * - * @param value - * The string to check. + * @param value The string to check. * * @return The number of graphemes in the string. */ @@ -188,97 +144,57 @@ public class StringUtils { it.setText(value); int count = 0; - while (it.next() != BreakIterator.DONE) { - count++; - } + while (it.next() != BreakIterator.DONE) count++; return count; } - /** - * Count the number of times a pattern matches in a given string. - * - * @param value - * The string to count occurances in. + /** Count the number of times a pattern matches in a given string. * - * @param pattern - * The pattern to count occurances of. + * @param value The string to count occurrences in. + * @param pattern The pattern to count occurrences of. + * * @return The number of times the pattern matches. */ public static int countMatches(final String value, final String pattern) { Matcher mat = Pattern.compile(pattern).matcher(value); int num = 0; - while (mat.find()) - num += 1; + while (mat.find()) num += 1; return num; } - /** - * Get a substring until a specified string. + /** Get a substring until a specified string. * - * @param strang - * The string to substring. - * @param vx - * The place to substring until. + * @param strang The string to substring. + * @param until The place to substring until. * * @return The specified substring. */ - public static String substringTo(String strang, String vx) { - return substringTo(strang, vx, true); + public static String substringTo(String strang, String until) { + return substringTo(strang, until, true); } /** * Get a substring until a specified string. * - * @param strang - * The string to substring. - * @param vx - * The place to substring until. - * @param allowFail - * Whether or not to allow failure. + * @param strang The string to substring. + * @param until The place to substring until. + * @param allowFail Whether or not to allow failure. * * @return The specified substring, or null if the specified place to substring * to was not found, and we were not allowed to fail. */ - public static String substringTo(String strang, String vx, boolean allowFail) { - int idx = strang.indexOf(vx); + public static String substringTo(String strang, String until, boolean allowFail) { + int idx = strang.indexOf(until); if (idx == -1) { - if (allowFail) - return strang; - - return null; - } - - return strang.substring(0, strang.indexOf(vx)); - } - - /** - * Split a line into a series of space-separated arguments, including string - * literals. - * - * @param com - * The command to split from - * @return The split arguments. - */ - public static List<String> processArguments(String com) { - List<String> strings = new ArrayList<>(); - - BooleanToggle togg = new BooleanToggle(); - - for (String strang : TokenUtils.removeDQuotedStrings(com)) { - if (togg.get()) { - strings.add(TokenUtils.descapeString(strang)); - } else { - for (String strung : strang.split("\\s+")) { - strings.add(strung); - } - } + if (allowFail) return strang; + else return null; } - return strings; + return strang.substring(0, strang.indexOf(until)); } private static class LineIterator implements Iterator<String> { @@ -306,16 +222,13 @@ public class StringUtils { boolean doLoop = true; do { - if (!scn.hasNextLine()) - break; + if (!scn.hasNextLine()) break; tmp = scn.nextLine().trim(); // Skip blank lines - if (skipBlanks && tmp.equals("")) - continue; - if (processComments && tmp.startsWith(commentInd)) - continue; + if (skipBlanks && tmp.equals("")) continue; + if (processComments && tmp.startsWith(commentInd)) continue; doLoop = tmp.endsWith("\\") && !tmp.endsWith("\\\\"); @@ -330,11 +243,9 @@ public class StringUtils { } } - /** - * Read a series of lines from an input source. + /** Read a series of lines from an input source. * - * @param scn - * The source to read the lines from. + * @param scn The source to read the lines from. * * @return An iterator over the lines from the input source. */ @@ -345,17 +256,10 @@ public class StringUtils { /** * Read a series of lines from an input source. * - * @param scn - * The source to read the lines from. - * - * @param processComments - * Whether or not to skip comment lines. - * - * @param commentInd - * Indicator for starting comment lines. - * - * @param skipBlanks - * Whether or not to skip blank lines. + * @param scn The source to read the lines from. + * @param processComments Whether or not to skip comment lines. + * @param commentInd Indicator for starting comment lines. + * @param skipBlanks Whether or not to skip blank lines. * * @return An iterator over the lines from the input source. */ @@ -371,27 +275,23 @@ public class StringUtils { return itr; } - /** - * Check if a string contains any one of a specified number of things, + /** Check if a string contains any one of a specified number of things, * respecting groups. * - * @param haystack - * The string to look in. - * @param needles - * The strings to look for. + * @param haystack The string to look in. + * @param needles The strings to look for. + * * @return Whether or not any of the strings were contained outside of groups. */ public static boolean levelContains(String haystack, String... needles) { return LevelSplitter.def.levelContains(haystack, needles); } - /** - * Split a string, respecting groups. + /** Split a string, respecting groups. * - * @param phrase - * The string to split. - * @param splits - * The strings to split on. + * @param phrase The string to split. + * @param splits The strings to split on. + * * @return A list of split strings. If keepDelims is true, it also includes the * delimiters in between the split strings. */ @@ -399,15 +299,12 @@ public class StringUtils { return LevelSplitter.def.levelSplit(phrase, false, splits); } - /** - * Split a string, respecting groups. + /** Split a string, respecting groups. * - * @param phrase - * The string to split. - * @param keepDelims - * Whether or not to include the delimiters in the results. - * @param splits - * The strings to split on. + * @param phrase The string to split. + * @param keepDelims Whether or not to include the delimiters in the results. + * @param splits The strings to split on. + * * @return A list of split strings. If keepDelims is true, it also includes the * delimiters in between the split strings. */ @@ -415,4 +312,4 @@ public class StringUtils { String... splits) { return LevelSplitter.def.levelSplit(phrase, keepDelims, splits); } -} +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/funcutils/TestUtils.java b/base/src/main/java/bjc/utils/funcutils/TestUtils.java index 3aa20a2..bf38cbe 100644 --- a/base/src/main/java/bjc/utils/funcutils/TestUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/TestUtils.java @@ -15,27 +15,22 @@ public class TestUtils { /** * Assert an iterator provides a particular sequence of values. * - * @param src - * The iterator to pull values from. - * @param vals - * The values to expect from the iterator. + * @param <T> The type of the values. + * @param src The iterator to pull values from. + * @param vals The values to expect from the iterator. */ @SafeVarargs public static <T> void assertIteratorEquals(Iterator<T> src, T... vals) { - for (T val : vals) { - assertEquals(val, src.next()); - } + for (T val : vals) assertEquals(val, src.next()); } /** * Assert an iterator provides a particular sequence of values. * - * @param src - * The iterator to pull values from. - * @param hasMore - * The expected value of hasNext for the iterator. - * @param vals - * The values to expect from the iterator. + * @param <T> The type of the values. + * @param src The iterator to pull values from. + * @param hasMore The expected value of hasNext for the iterator. + * @param vals The values to expect from the iterator. */ @SafeVarargs public static <T> void assertIteratorEquals(boolean hasMore, Iterator<T> src, @@ -46,6 +41,8 @@ public class TestUtils { * Even though it's awkward, the boolean has to come first. Otherwise, there are * cases where the compiler will get confused as to what the right value for T * is, and be unable to pick an overload. + * + * This is a case where named parameter would be rather useful. */ assertIteratorEquals(src, vals); @@ -55,11 +52,9 @@ public class TestUtils { /** * Assert that a list has a given set of contents. * - * @param src - * The list of actual elements. - * - * @param exps - * The list of expected elements. + * @param <T> The type of the values. + * @param src The list of actual elements. + * @param exps The list of expected elements. */ @SafeVarargs public static <T> void assertListEquals(List<T> src, T... exps) { diff --git a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java index d525773..5a1d9c8 100644 --- a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java @@ -1,11 +1,10 @@ package bjc.utils.funcutils; import java.util.LinkedList; -import java.util.function.Predicate; +import java.util.function.*; -import bjc.data.ITree; -import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.data.*; +import bjc.funcdata.*; /** * Implements various utilities for trees. @@ -16,14 +15,13 @@ public class TreeUtils { /** * Convert a tree into a list of outline nodes that match a certain path. * - * @param tre - * The tree to outline. - * @param leafMarker - * The path to mark nodes with. + * @param <T> The type of the values. + * @param tre The tree to outline. + * @param leafMarker The path to mark nodes with. * @return The list of marked paths. */ - public static <T> IList<IList<T>> outlineTree(ITree<T> tre, Predicate<T> leafMarker) { - IList<IList<T>> paths = new FunctionalList<>(); + public static <T> ListEx<ListEx<T>> outlineTree(Tree<T> tre, Predicate<T> leafMarker) { + ListEx<ListEx<T>> paths = new FunctionalList<>(); LinkedList<T> path = new LinkedList<>(); path.add(tre.getHead()); @@ -34,15 +32,13 @@ public class TreeUtils { } /* Find a path in a tree. */ - private static <T> void findPath(ITree<T> subtree, LinkedList<T> path, - Predicate<T> leafMarker, IList<IList<T>> paths) { + private static <T> void findPath(Tree<T> subtree, LinkedList<T> path, + Predicate<T> leafMarker, ListEx<ListEx<T>> paths) { if (subtree.getChildrenCount() == 0 && leafMarker.test(subtree.getHead())) { /* We're at a matching leaf node. Add it. */ - IList<T> finalPath = new FunctionalList<>(); + ListEx<T> finalPath = new FunctionalList<>(); - for (T ePath : path) { - finalPath.add(ePath); - } + for (T ePath : path) finalPath.add(ePath); finalPath.add(subtree.getHead()); @@ -56,4 +52,43 @@ public class TreeUtils { path.removeLast(); } } + + /** + * Performs 'variable substitution' or something along those lines on a tree. + * + * @param <ContainedType> The type of element contained in the tree. + * @param tree The tree to do expansion in. + * @param marker The function to mark which nodes should be expanded. + * @param expander The function to expand nodes. + * @return A transformed copy of the tree. + */ + public static <ContainedType> Tree<ContainedType> substitute( + Tree<ContainedType> tree, + Predicate<ContainedType> marker, + Function<ContainedType, Tree<ContainedType>> expander) { + tree.topDownTransform((contents) -> { + if (marker.test(contents)) return TopDownTransformResult.TRANSFORM; + else return TopDownTransformResult.PASSTHROUGH; + }, (node) -> { + return expander.apply(node.getHead()); + }); + return tree; + } + + /** + * Performs 'variable substitution' or something along those lines on a tree. + * + * @param <ContainedType> The type of element contained in the tree. + * @param tree The tree to do expansion in. + * @param environment A map which contains the variables to substitute. + * @return A transformed copy of the tree. + */ + public static <ContainedType> Tree<ContainedType> substitute( + Tree<ContainedType> tree, + MapEx<ContainedType, Tree<ContainedType>> environment) { + return substitute( + tree, + environment::containsKey, + (element) -> environment.get(element).get()); + } } diff --git a/base/src/main/java/bjc/utils/gen/RandomGrammar.java b/base/src/main/java/bjc/utils/gen/RandomGrammar.java index 050165b..620cc5b 100644 --- a/base/src/main/java/bjc/utils/gen/RandomGrammar.java +++ b/base/src/main/java/bjc/utils/gen/RandomGrammar.java @@ -1,7 +1,7 @@ package bjc.utils.gen; import bjc.funcdata.FunctionalMap; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * A weighted grammar where all the rules have a equal chance of occuring. @@ -27,8 +27,8 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * The cases to add for this rule. */ @SafeVarargs - public final void addCases(final E rule, final IList<E>... cases) { - for (final IList<E> currentCase : cases) { + public final void addCases(final E rule, final ListEx<E>... cases) { + for (final ListEx<E> currentCase : cases) { super.addCase(rule, 1, currentCase); } } @@ -43,10 +43,10 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * The cases to add for this rule. */ @SafeVarargs - public final void makeRule(final E rule, final IList<E>... cases) { + public final void makeRule(final E rule, final ListEx<E>... cases) { super.addRule(rule); - for (final IList<E> currentCase : cases) { + for (final ListEx<E> currentCase : cases) { super.addCase(rule, 1, currentCase); } } @@ -60,7 +60,7 @@ public class RandomGrammar<E> extends WeightedGrammar<E> { * @param cases * The cases to add for this rule. */ - public void makeRule(final E rule, final IList<IList<E>> cases) { + public void makeRule(final E rule, final ListEx<ListEx<E>> cases) { if (cases == null) throw new NullPointerException("Cases must not be null"); diff --git a/base/src/main/java/bjc/utils/gen/WeightedGrammar.java b/base/src/main/java/bjc/utils/gen/WeightedGrammar.java index 324a80c..48cc658 100644 --- a/base/src/main/java/bjc/utils/gen/WeightedGrammar.java +++ b/base/src/main/java/bjc/utils/gen/WeightedGrammar.java @@ -6,12 +6,12 @@ import java.util.function.Function; import java.util.function.Predicate; import java.util.function.Supplier; -import bjc.data.IPair; import bjc.data.Pair; +import bjc.data.SimplePair; import bjc.funcdata.FunctionalList; import bjc.funcdata.FunctionalMap; -import bjc.funcdata.IList; -import bjc.funcdata.IMap; +import bjc.funcdata.ListEx; +import bjc.funcdata.MapEx; /** * A random grammar, where certain rules will come up more often than others. @@ -26,22 +26,22 @@ public class WeightedGrammar<E> { protected String initialRule; /** The rules currently in this grammar */ - protected IMap<E, WeightedRandom<IList<E>>> rules; + protected MapEx<E, WeightedRandom<ListEx<E>>> rules; /** The random number generator used for random numbers */ private Random rng; /** All of the subgrammars of this grammar */ - protected IMap<E, WeightedGrammar<E>> subgrammars; + protected MapEx<E, WeightedGrammar<E>> subgrammars; /** Rules that require special handling */ - private IMap<E, Supplier<IList<E>>> specialRules; + private MapEx<E, Supplier<ListEx<E>>> specialRules; /** Predicate for marking special tokens */ private Predicate<E> specialMarker; /** Action for special tokens */ - private BiFunction<E, WeightedGrammar<E>, IList<E>> specialAction; + private BiFunction<E, WeightedGrammar<E>, ListEx<E>> specialAction; /** Create a new weighted grammar. */ public WeightedGrammar() { @@ -75,7 +75,7 @@ public class WeightedGrammar<E> { * The action to take on those tokens. */ public void configureSpecial(final Predicate<E> marker, - final BiFunction<E, WeightedGrammar<E>, IList<E>> action) { + final BiFunction<E, WeightedGrammar<E>, ListEx<E>> action) { specialMarker = marker; specialAction = action; } @@ -89,7 +89,7 @@ public class WeightedGrammar<E> { * @param cse * The case for the rule. */ - public void addSpecialRule(final E ruleName, final Supplier<IList<E>> cse) { + public void addSpecialRule(final E ruleName, final Supplier<ListEx<E>> cse) { if (ruleName == null) { throw new NullPointerException("Rule name must not be null"); } else if (cse == null) { @@ -111,14 +111,14 @@ public class WeightedGrammar<E> { * @param cse * The case being added. */ - public void addCase(final E ruleName, final int probability, final IList<E> cse) { + public void addCase(final E ruleName, final int probability, final ListEx<E> cse) { if (ruleName == null) { throw new NullPointerException("Rule name must be not null"); } else if (cse == null) { throw new NullPointerException("Case body must not be null"); } - rules.get(ruleName).addProbability(probability, cse); + rules.get(ruleName).get().addProbability(probability, cse); } /** @@ -143,7 +143,7 @@ public class WeightedGrammar<E> { return false; if (subgrammars.containsKey(name)) { - subgrammars.put(alias, subgrammars.get(name)); + subgrammars.put(alias, subgrammars.get(name).get()); return true; } @@ -180,7 +180,7 @@ public class WeightedGrammar<E> { * * @return Whether or not the rule was succesfully added. */ - public boolean addRule(final E name, final WeightedRandom<IList<E>> cases) { + public boolean addRule(final E name, final WeightedRandom<ListEx<E>> cases) { if (name == null) { throw new NullPointerException("Name must not be null"); } else if (cases == null) { @@ -255,13 +255,13 @@ public class WeightedGrammar<E> { * * @return A set of sentences generated by the specified rule. */ - public IList<IList<E>> generateDebugValues(final E ruleName) { + public ListEx<ListEx<E>> generateDebugValues(final E ruleName) { if (ruleName == null) throw new NullPointerException("Rule name must not be null"); - final IList<IList<E>> returnedList = new FunctionalList<>(); + final ListEx<ListEx<E>> returnedList = new FunctionalList<>(); - final WeightedRandom<IList<E>> ruleGenerator = rules.get(ruleName); + final WeightedRandom<ListEx<E>> ruleGenerator = rules.get(ruleName).get(); for (int i = 0; i < 10; i++) { returnedList.add(ruleGenerator.generateValue()); @@ -288,7 +288,7 @@ public class WeightedGrammar<E> { * * @return A randomly generated sentence from the specified initial rule. */ - public <T> IList<T> generateGenericValues(final E initRules, + public <T> ListEx<T> generateGenericValues(final E initRules, final Function<E, T> tokenTransformer, final T spacer) { if (initRules == null) { throw new NullPointerException("Initial rule must not be null"); @@ -298,9 +298,9 @@ public class WeightedGrammar<E> { throw new NullPointerException("Spacer must not be null"); } - final IList<T> returnedList = new FunctionalList<>(); + final ListEx<T> returnedList = new FunctionalList<>(); - IList<E> genRules = new FunctionalList<>(initRules); + ListEx<E> genRules = new FunctionalList<>(initRules); if (specialMarker != null) { if (specialMarker.test(initRules)) { @@ -313,7 +313,7 @@ public class WeightedGrammar<E> { */ for (final E initRule : genRules.toIterable()) { if (specialRules.containsKey(initRule)) { - for (final E rulePart : specialRules.get(initRule).get().toIterable()) { + for (final E rulePart : specialRules.get(initRule).get().get().toIterable()) { final Iterable<T> generatedRuleParts = generateGenericValues(rulePart, tokenTransformer, spacer) .toIterable(); @@ -324,7 +324,7 @@ public class WeightedGrammar<E> { } } } else if (subgrammars.containsKey(initRule)) { - final Iterable<T> ruleParts = subgrammars.get(initRule) + final Iterable<T> ruleParts = subgrammars.get(initRule).get() .generateGenericValues(initRule, tokenTransformer, spacer) .toIterable(); @@ -334,7 +334,7 @@ public class WeightedGrammar<E> { } } else if (rules.containsKey(initRule)) { final Iterable<E> ruleParts - = rules.get(initRule).generateValue().toIterable(); + = rules.get(initRule).get().generateValue().toIterable(); for (final E rulePart : ruleParts) { final Iterable<T> generatedRuleParts @@ -371,8 +371,8 @@ public class WeightedGrammar<E> { * * @return A list of random grammar elements generated by the specified rule. */ - public IList<E> generateListValues(final E initRule, final E spacer) { - final IList<E> retList + public ListEx<E> generateListValues(final E initRule, final E spacer) { + final ListEx<E> retList = generateGenericValues(initRule, strang -> strang, spacer); return retList; @@ -401,8 +401,8 @@ public class WeightedGrammar<E> { * * @return The set of all rule names in this grammar. */ - public IList<E> getRuleNames() { - final IList<E> ruleNames = new FunctionalList<>(); + public ListEx<E> getRuleNames() { + final ListEx<E> ruleNames = new FunctionalList<>(); ruleNames.addAll(rules.keyList()); ruleNames.addAll(specialRules.keyList()); @@ -422,7 +422,7 @@ public class WeightedGrammar<E> { if (name == null) throw new NullPointerException("Subgrammar name must not be null"); - return subgrammars.get(name); + return subgrammars.get(name).get(); } /** @@ -471,19 +471,19 @@ public class WeightedGrammar<E> { throw new IllegalArgumentException( "Number of times to prefix must be positive."); - final WeightedRandom<IList<E>> rule = rules.get(ruleName); + final WeightedRandom<ListEx<E>> rule = rules.get(ruleName).get(); - final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); + final ListEx<Pair<Integer, ListEx<E>>> newResults = new FunctionalList<>(); /* * @NOTE Can this be simplified? */ rule.getValues().forEach(pair -> { - final IList<IList<E>> newRule = new FunctionalList<>(); + final ListEx<ListEx<E>> newRule = new FunctionalList<>(); for (int i = 1; i <= numberOfTimes; i++) { - final IList<E> newCase = pair.merge((left, right) -> { - final IList<E> returnVal = new FunctionalList<>(); + final ListEx<E> newCase = pair.merge((left, right) -> { + final ListEx<E> returnVal = new FunctionalList<>(); for (final E val : right.toIterable()) { returnVal.add(val); @@ -502,7 +502,7 @@ public class WeightedGrammar<E> { newRule.forEach((list) -> { final Integer currentProb = pair.merge((left, right) -> left); - newResults.add(new Pair<>(currentProb + additionalProbability, list)); + newResults.add(new SimplePair<>(currentProb + additionalProbability, list)); }); }); @@ -534,13 +534,13 @@ public class WeightedGrammar<E> { throw new NullPointerException("Prefix token must not be null"); } - final WeightedRandom<IList<E>> rule = rules.get(ruleName); + final WeightedRandom<ListEx<E>> rule = rules.get(ruleName).get(); - final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); + final ListEx<Pair<Integer, ListEx<E>>> newResults = new FunctionalList<>(); rule.getValues().forEach(pair -> { - final IList<E> newCase = pair.merge((left, right) -> { - final IList<E> returnVal = new FunctionalList<>(); + final ListEx<E> newCase = pair.merge((left, right) -> { + final ListEx<E> returnVal = new FunctionalList<>(); for (final E val : right.toIterable()) { returnVal.add(val); @@ -551,7 +551,7 @@ public class WeightedGrammar<E> { newCase.prepend(prefixToken); - newResults.add(new Pair<>( + newResults.add(new SimplePair<>( pair.merge((left, right) -> left) + additionalProbability, newCase)); }); @@ -589,13 +589,13 @@ public class WeightedGrammar<E> { throw new NullPointerException("Prefix token must not be null"); } - final WeightedRandom<IList<E>> rule = rules.get(ruleName); + final WeightedRandom<ListEx<E>> rule = rules.get(ruleName).get(); - final IList<IPair<Integer, IList<E>>> newResults = new FunctionalList<>(); + final ListEx<Pair<Integer, ListEx<E>>> newResults = new FunctionalList<>(); rule.getValues().forEach(par -> { - final IList<E> newCase = par.merge((left, right) -> { - final IList<E> returnVal = new FunctionalList<>(); + final ListEx<E> newCase = par.merge((left, right) -> { + final ListEx<E> returnVal = new FunctionalList<>(); for (final E val : right.toIterable()) { returnVal.add(val); @@ -606,7 +606,7 @@ public class WeightedGrammar<E> { newCase.add(suffixToken); - newResults.add(new Pair<>( + newResults.add(new SimplePair<>( par.merge((left, right) -> left) + additionalProbability, newCase)); }); diff --git a/base/src/main/java/bjc/utils/gen/WeightedRandom.java b/base/src/main/java/bjc/utils/gen/WeightedRandom.java index b17017b..01a961f 100644 --- a/base/src/main/java/bjc/utils/gen/WeightedRandom.java +++ b/base/src/main/java/bjc/utils/gen/WeightedRandom.java @@ -2,10 +2,10 @@ package bjc.utils.gen; import java.util.Random; -import bjc.data.IPair; import bjc.data.Pair; +import bjc.data.SimplePair; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * Represents a random number generator where certain results are weighted more @@ -17,7 +17,7 @@ import bjc.funcdata.IList; * The type of values that are randomly selected. */ public class WeightedRandom<E> { - private final IList<IPair<Integer, E>> values; + private final ListEx<Pair<Integer, E>> values; /* The source for any needed random numbers */ private Random source; @@ -38,8 +38,7 @@ public class WeightedRandom<E> { public WeightedRandom(Random src) { values = new FunctionalList<>(); - if (src == null) - throw new NullPointerException("Source of randomness must not be null"); + if (src == null) throw new NullPointerException("Source of randomness must not be null"); source = src; } @@ -51,7 +50,7 @@ public class WeightedRandom<E> { this(BASE); } - private WeightedRandom(Random src, IList<IPair<Integer, E>> vals, int chance) { + private WeightedRandom(Random src, ListEx<Pair<Integer, E>> vals, int chance) { source = src; values = vals; @@ -69,7 +68,7 @@ public class WeightedRandom<E> { * The result to get when the chance comes up. */ public void addProbability(final int chance, final E result) { - values.add(new Pair<>(chance, result)); + values.add(new SimplePair<>(chance, result)); totalChance += chance; } @@ -92,7 +91,7 @@ public class WeightedRandom<E> { */ public E generateValue(Random rn) { int target = rn.nextInt(totalChance); - for (IPair<Integer, E> val : values) { + for (Pair<Integer, E> val : values) { int prob = val.getLeft(); if (target < prob) { @@ -115,8 +114,8 @@ public class WeightedRandom<E> { * * @return A list of all the values that can be generated */ - public IList<E> getResults() { - return values.map(IPair::getRight); + public ListEx<E> getResults() { + return values.map(Pair::getRight); } /** @@ -125,7 +124,7 @@ public class WeightedRandom<E> { * * @return A list of pairs of values and value probabilities */ - public IList<IPair<Integer, E>> getValues() { + public ListEx<Pair<Integer, E>> getValues() { return values; } @@ -156,12 +155,10 @@ public class WeightedRandom<E> { * @return A random value. */ public E getDescent(int factor, Random rn) { - if (values.getSize() == 0) - return null; + if (values.getSize() == 0) return null; - for (IPair<Integer, E> val : values) { - if (rn.nextInt(factor) == 0) - continue; + for (Pair<Integer, E> val : values) { + if (rn.nextInt(factor) == 0) continue; if (exhaust) { totalChance -= val.getLeft(); @@ -172,9 +169,8 @@ public class WeightedRandom<E> { return val.getRight(); } - IPair<Integer, E> val = values.getByIndex(values.getSize() - 1); - if (exhaust) - values.removeMatching(val); + Pair<Integer, E> val = values.getByIndex(values.getSize() - 1); + if (exhaust) values.removeMatching(val); return val.getRight(); } @@ -214,8 +210,7 @@ public class WeightedRandom<E> { * @return The value at the index corresponding to the number of successes. */ public E getBinomial(int target, int bound, int trials, Random rn) { - if (values.getSize() == 0) - return null; + if (values.getSize() == 0) return null; int numSuc = 0; @@ -236,7 +231,7 @@ public class WeightedRandom<E> { // System.err.printf("\tTRACE: got %d success for binomial trials (%d <= 1d%d, // %d times)\n", numSuc, target, bound, trials); - IPair<Integer, E> val = values.getByIndex(Math.min(numSuc, values.getSize() - 1)); + Pair<Integer, E> val = values.getByIndex(Math.min(numSuc, values.getSize() - 1)); if (exhaust) { totalChance -= val.getLeft(); @@ -253,10 +248,8 @@ public class WeightedRandom<E> { * @return A new WeightedRandom that is exhaustible. */ public WeightedRandom<E> exhaustible() { - IList<IPair<Integer, E>> lst = new FunctionalList<>(); - for (IPair<Integer, E> val : values) { - lst.add(val); - } + ListEx<Pair<Integer, E>> lst = new FunctionalList<>(); + for (Pair<Integer, E> val : values) lst.add(val); WeightedRandom<E> res = new WeightedRandom<>(source, lst, totalChance); diff --git a/base/src/main/java/bjc/utils/graph/AdjacencyMap.java b/base/src/main/java/bjc/utils/graph/AdjacencyMap.java index e046fb5..978b21d 100644 --- a/base/src/main/java/bjc/utils/graph/AdjacencyMap.java +++ b/base/src/main/java/bjc/utils/graph/AdjacencyMap.java @@ -6,12 +6,12 @@ import java.io.PrintStream; import java.util.InputMismatchException; import java.util.Scanner; -import bjc.data.IHolder; +import bjc.data.Holder; import bjc.data.Identity; import bjc.funcdata.FunctionalList; import bjc.funcdata.FunctionalMap; -import bjc.funcdata.IList; -import bjc.funcdata.IMap; +import bjc.funcdata.ListEx; +import bjc.funcdata.MapEx; import bjc.utils.funcutils.FuncUtils; /** @@ -32,8 +32,7 @@ public class AdjacencyMap<T> { * @return An adjacency map defined by the text */ public static AdjacencyMap<Integer> fromStream(final InputStream stream) { - if (stream == null) - throw new NullPointerException("Input source must not be null"); + if (stream == null) throw new NullPointerException("Input source must not be null"); /* Create the adjacency map. */ AdjacencyMap<Integer> adjacency; @@ -60,17 +59,16 @@ public class AdjacencyMap<T> { throw imex; } - if (vertexCount <= 0) - throw new InputMismatchException( + if (vertexCount <= 0) throw new InputMismatchException( "The number of vertices must be greater than 0"); - final IList<Integer> vertices = new FunctionalList<>(); + final ListEx<Integer> vertices = new FunctionalList<>(); FuncUtils.doTimes(vertexCount, vertexNo -> vertices.add(vertexNo)); adjacency = new AdjacencyMap<>(vertices); - final IHolder<Integer> row = new Identity<>(0); + final Holder<Integer> row = new Identity<>(0); input.forEachRemaining(strang -> { readRow(adjacency, vertexCount, row, strang); @@ -82,7 +80,7 @@ public class AdjacencyMap<T> { /* Read a row of edges. */ private static void readRow(final AdjacencyMap<Integer> adjacency, - final int vertexCount, final IHolder<Integer> row, final String strang) { + final int vertexCount, final Holder<Integer> row, final String strang) { final String[] parts = strang.split(" "); if (parts.length != vertexCount) { @@ -117,7 +115,7 @@ public class AdjacencyMap<T> { } /** The backing storage of the map */ - private final IMap<T, IMap<T, Integer>> adjacency = new FunctionalMap<>(); + private final MapEx<T, MapEx<T, Integer>> adjacency = new FunctionalMap<>(); /** * Create a new map from a set of vertices @@ -125,12 +123,11 @@ public class AdjacencyMap<T> { * @param vertices * The set of vertices to create a map from */ - public AdjacencyMap(final IList<T> vertices) { - if (vertices == null) - throw new NullPointerException("Vertices must not be null"); + public AdjacencyMap(final ListEx<T> vertices) { + if (vertices == null) throw new NullPointerException("Vertices must not be null"); vertices.forEach(vertex -> { - final IMap<T, Integer> row = new FunctionalMap<>(); + final MapEx<T, Integer> row = new FunctionalMap<>(); vertices.forEach(target -> { row.put(target, 0); @@ -146,15 +143,13 @@ public class AdjacencyMap<T> { * @return Whether or not the graph is directed */ public boolean isDirected() { - final IHolder<Boolean> result = new Identity<>(true); + final Holder<Boolean> result = new Identity<>(true); adjacency.forEach((sourceKey, sourceValue) -> { sourceValue.forEach((targetKey, targetValue) -> { - final int inverseValue = adjacency.get(targetKey).get(sourceKey); + final int inverseValue = adjacency.get(targetKey).get().get(sourceKey).get(); - if (targetValue != inverseValue) { - result.replace(false); - } + if (targetValue != inverseValue) result.replace(false); }); }); @@ -172,11 +167,8 @@ public class AdjacencyMap<T> { * The weight of the edge. */ public void setWeight(final T source, final T target, final int weight) { - if (source == null) { - throw new NullPointerException("Source vertex must not be null"); - } else if (target == null) { - throw new NullPointerException("Target vertex must not be null"); - } + if (source == null) throw new NullPointerException("Source vertex must not be null"); + else if (target == null) throw new NullPointerException("Target vertex must not be null"); if (!adjacency.containsKey(source)) { String msg = String.format("Source vertex %s isn't present in map", source); @@ -188,7 +180,7 @@ public class AdjacencyMap<T> { throw new IllegalArgumentException(msg); } - adjacency.get(source).put(target, weight); + adjacency.get(source).get().put(target, weight); } /** @@ -215,8 +207,7 @@ public class AdjacencyMap<T> { * The stream to convert to. */ public void toStream(final OutputStream sink) { - if (sink == null) - throw new NullPointerException("Output source must not be null"); + if (sink == null) throw new NullPointerException("Output source must not be null"); final PrintStream outputPrinter = new PrintStream(sink); diff --git a/base/src/main/java/bjc/utils/graph/Edge.java b/base/src/main/java/bjc/utils/graph/Edge.java index fe3d891..b48fcd0 100644 --- a/base/src/main/java/bjc/utils/graph/Edge.java +++ b/base/src/main/java/bjc/utils/graph/Edge.java @@ -28,11 +28,8 @@ public class Edge<T> { * The distance between initial and terminal edge. */ public Edge(final T initial, final T terminal, final int distance) { - if (initial == null) { - throw new NullPointerException("Initial node must not be null"); - } else if (terminal == null) { - throw new NullPointerException("Terminal node must not be null"); - } + if (initial == null) throw new NullPointerException("Initial node must not be null"); + else if (terminal == null) throw new NullPointerException("Terminal node must not be null"); this.source = initial; this.target = terminal; @@ -41,27 +38,23 @@ public class Edge<T> { @Override public boolean equals(final Object obj) { - if (this == obj) - return true; - else if (obj == null) - return false; - else if (getClass() != obj.getClass()) - return false; + if (this == obj) return true; + else if (obj == null) return false; + else if (getClass() != obj.getClass()) return false; else { final Edge<?> other = (Edge<?>) obj; - if (distance != other.distance) + if (distance != other.distance) { return false; - else if (source == null) { - if (other.source != null) - return false; - } else if (!source.equals(other.source)) + } else if (source == null) { + if (other.source != null) return false; + } else if (!source.equals(other.source)) { return false; - else if (target == null) { - if (other.target != null) - return false; - } else if (!target.equals(other.target)) + } else if (target == null) { + if (other.target != null) return false; + } else if (!target.equals(other.target)) { return false; + } return true; } diff --git a/base/src/main/java/bjc/utils/graph/Graph.java b/base/src/main/java/bjc/utils/graph/Graph.java index 8ff5647..f32e07f 100644 --- a/base/src/main/java/bjc/utils/graph/Graph.java +++ b/base/src/main/java/bjc/utils/graph/Graph.java @@ -10,11 +10,11 @@ import java.util.Set; import java.util.function.BiConsumer; import java.util.function.BiPredicate; -import bjc.data.IHolder; +import bjc.data.Holder; import bjc.data.Identity; import bjc.funcdata.FunctionalMap; -import bjc.funcdata.IList; -import bjc.funcdata.IMap; +import bjc.funcdata.ListEx; +import bjc.funcdata.MapEx; /** * A directed weighted graph, where the vertices have some arbitrary label. @@ -47,7 +47,7 @@ public class Graph<T> { } /** The backing representation of the graph. */ - private final IMap<T, IMap<T, Integer>> backing; + private final MapEx<T, MapEx<T, Integer>> backing; /** Create a new empty graph. */ public Graph() { @@ -72,19 +72,14 @@ public class Graph<T> { public void addEdge(final T source, final T target, final int distance, final boolean directed) { /* Can't add edges with a null source or target. */ - if (source == null) { - throw new NullPointerException("The source vertex cannot be null"); - } else if (target == null) { - throw new NullPointerException("The target vertex cannot be null"); - } + if (source == null) throw new NullPointerException("The source vertex cannot be null"); + else if (target == null) throw new NullPointerException("The target vertex cannot be null"); /* Initialize adjacency list for vertices if necessary. */ - if (!backing.containsKey(source)) { - backing.put(source, new FunctionalMap<T, Integer>()); - } + if (!backing.containsKey(source)) backing.put(source, new FunctionalMap<T, Integer>()); /* Add the edge to the graph. */ - backing.get(source).put(target, distance); + backing.get(source).get().put(target, distance); /* Handle possible directed edges. */ if (!directed) { @@ -92,7 +87,7 @@ public class Graph<T> { backing.put(target, new FunctionalMap<T, Integer>()); } - backing.get(target).put(source, distance); + backing.get(target).get().put(source, distance); } } @@ -110,16 +105,11 @@ public class Graph<T> { */ public void forAllEdgesMatchingAt(final T source, final BiPredicate<T, Integer> matcher, final BiConsumer<T, Integer> action) { - if (matcher == null) { - throw new NullPointerException("Matcher must not be null"); - } else if (action == null) { - throw new NullPointerException("Action must not be null"); - } + if (matcher == null) throw new NullPointerException("Matcher must not be null"); + else if (action == null) throw new NullPointerException("Action must not be null"); getEdges(source).forEach((target, weight) -> { - if (matcher.test(target, weight)) { - action.accept(target, weight); - } + if (matcher.test(target, weight)) action.accept(target, weight); }); } @@ -130,14 +120,15 @@ public class Graph<T> { * The vertex to use as a source. * @return All of the edges with the specified vertex as a source. */ - public IMap<T, Integer> getEdges(final T source) { + public MapEx<T, Integer> getEdges(final T source) { /* Can't find edges for a null source. */ - if (source == null) + if (source == null) { throw new NullPointerException("The source cannot be null."); - else if (!backing.containsKey(source)) + } else if (!backing.containsKey(source)) { throw new IllegalArgumentException("Vertex " + source + " is not in graph"); + } - return backing.get(source); + return backing.get(source).get(); } /** @@ -168,7 +159,7 @@ public class Graph<T> { final Set<T> visited = new HashSet<>(); /* Start at the initial vertex and visit it */ - final IHolder<T> source = new Identity<>(getInitial()); + final Holder<T> source = new Identity<>(getInitial()); visited.add(source.getValue()); @@ -176,14 +167,17 @@ public class Graph<T> { while (visited.size() != getVertexCount()) { /* Grab all edges adjacent to the provided edge. */ - forAllEdgesMatchingAt(source.getValue(), (target, weight) -> !visited.contains(target), (target, weight) -> { - final T vert = source.unwrap(vertex -> vertex); + forAllEdgesMatchingAt(source.getValue(), + (target, weight) -> !visited.contains(target), + (target, weight) -> { + final T vert = source.unwrap(vertex -> vertex); - available.add(new Edge<>(vert, target, weight)); - }); + available.add(new Edge<>(vert, target, weight)); + } + ); /* Get the edge with the minimum distance. */ - final IHolder<Edge<T>> minimum = new Identity<>(available.poll()); + final Holder<Edge<T>> minimum = new Identity<>(available.poll()); /* * Only consider edges where we haven't visited the target of the edge. @@ -219,7 +213,7 @@ public class Graph<T> { * * @return A unmodifiable set of all the vertices in the graph. */ - public IList<T> getVertices() { + public ListEx<T> getVertices() { return backing.keyList(); } @@ -253,7 +247,7 @@ public class Graph<T> { throw new NoSuchElementException(msg); } - backing.get(source).remove(target); + backing.get(source).get().remove(target); /* * Uncomment this to turn the graph undirected diff --git a/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java b/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java index d9ebda5..c07543f 100644 --- a/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java +++ b/base/src/main/java/bjc/utils/gui/ExtensionFileFilter.java @@ -6,7 +6,7 @@ import java.util.List; import javax.swing.filechooser.FileFilter; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * A file filter based on extensions. @@ -20,7 +20,7 @@ public class ExtensionFileFilter extends FileFilter { /** * The list holding all filtered extensions */ - private final IList<String> extensions; + private final ListEx<String> extensions; /** * Create a new filter only showing files with the specified extensions. diff --git a/base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java b/base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java index 0c40fbe..976b259 100644 --- a/base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java +++ b/base/src/main/java/bjc/utils/gui/SimpleKeyedButton.java @@ -59,8 +59,9 @@ public class SimpleKeyedButton extends JButton { * @param aevListener * The listener that handles the implementation of the * action. + * @return The action that was bound to the button. */ - public void setGlobalDefaultKeystroke(String eventName, String keystroke, + public Action setGlobalDefaultKeystroke(String eventName, String keystroke, Consumer<ActionEvent> aevListener) { Action act = new KeyedButtonAction(eventName, aevListener); KeyStroke stroke = KeyStroke.getKeyStroke(keystroke); @@ -69,6 +70,8 @@ public class SimpleKeyedButton extends JButton { this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(stroke, eventName); this.getActionMap().put(eventName, act); this.setText(label); + + return act; } /** @@ -82,8 +85,9 @@ public class SimpleKeyedButton extends JButton { * @param aevListener * The listener that handles the implementation of the * action. + * @return The action that was bound to the button. */ - public void addGlobalKeystroke(String eventName, String keystroke, + public Action addGlobalKeystroke(String eventName, String keystroke, Consumer<ActionEvent> aevListener) { Action act = new KeyedButtonAction(eventName, aevListener); KeyStroke stroke = KeyStroke.getKeyStroke(keystroke); @@ -91,5 +95,7 @@ public class SimpleKeyedButton extends JButton { this.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(stroke, eventName); this.getActionMap().put(eventName, act); this.setText(label); + + return act; } } diff --git a/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java b/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java index 04b0b68..9b55306 100644 --- a/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java +++ b/base/src/main/java/bjc/utils/gui/awt/ExtensionFileFilter.java @@ -5,7 +5,7 @@ import java.io.FilenameFilter; import java.util.List; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * Filter a set of filenames by extension. @@ -16,7 +16,7 @@ import bjc.funcdata.IList; */ public class ExtensionFileFilter implements FilenameFilter { /* The list of extensions to filter */ - private final IList<String> extensions; + private final ListEx<String> extensions; /** * Create a new filter only showing files with the specified extensions. diff --git a/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java b/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java index 8f65577..465be02 100644 --- a/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/DropdownListPanel.java @@ -9,7 +9,7 @@ import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.utils.gui.layout.AutosizeLayout; import bjc.utils.gui.layout.HLayout; @@ -35,7 +35,7 @@ public class DropdownListPanel extends JPanel { * The items to choose from */ public <T> DropdownListPanel(final String type, final DefaultListModel<T> model, - final IList<T> choices) { + final ListEx<T> choices) { setLayout(new AutosizeLayout()); final JPanel itemInputPanel = new JPanel(); diff --git a/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java b/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java index d0b5383..dbf70f0 100644 --- a/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/HolderOutputPanel.java @@ -4,11 +4,11 @@ import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.Timer; -import bjc.data.IHolder; +import bjc.data.Holder; import bjc.utils.gui.layout.HLayout; /** - * A panel that outputs a value bound to a {@link IHolder} + * A panel that outputs a value bound to a {@link Holder} * * @author ben * @@ -19,7 +19,7 @@ public class HolderOutputPanel extends JPanel { private Timer updater; private final JLabel value; private final int nDelay; - private final IHolder<String> val; + private final Holder<String> val; /** * Create a new display panel, backed by a holder @@ -31,7 +31,7 @@ public class HolderOutputPanel extends JPanel { * @param nDelay * The delay in ms between value updates */ - public HolderOutputPanel(final String lab, final IHolder<String> valueHolder, + public HolderOutputPanel(final String lab, final Holder<String> valueHolder, final int nDelay) { this.val = valueHolder; this.nDelay = nDelay; diff --git a/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java b/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java index 3b48309..4ba5a01 100644 --- a/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/ListParameterPanel.java @@ -9,7 +9,7 @@ import javax.swing.JList; import javax.swing.JPanel; import javax.swing.ListSelectionModel; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.utils.gui.SimpleJList; import bjc.utils.gui.layout.HLayout; import bjc.utils.gui.layout.VLayout; @@ -54,7 +54,7 @@ public class ListParameterPanel<E> extends JPanel { * The default values to put in the list */ public ListParameterPanel(final Supplier<E> add, final Consumer<E> edit, - final Consumer<E> remove, final IList<E> defaults) { + final Consumer<E> remove, final ListEx<E> defaults) { setLayout(new VLayout(2)); JList<E> list; diff --git a/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java b/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java index 8ca6f2b..406929a 100644 --- a/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/SimpleSpinnerPanel.java @@ -8,7 +8,7 @@ import javax.swing.JSpinner; import javax.swing.SpinnerModel; /** - * A simple spinner control + * A simple spinner control alongside a label * * @author ben * diff --git a/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java b/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java index 835513a..dacba42 100644 --- a/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java +++ b/base/src/main/java/bjc/utils/gui/panels/SliderInputPanel.java @@ -9,6 +9,7 @@ import javax.swing.JPanel; import javax.swing.JSlider; import bjc.utils.gui.layout.HLayout; +import bjc.utils.gui.panels.SliderInputPanel.*; /** * A simple input panel for a slider-controlled value and a manual-input field @@ -18,51 +19,6 @@ import bjc.utils.gui.layout.HLayout; * */ public class SliderInputPanel extends JPanel { - private final class NumberFormatter extends JFormattedTextField.AbstractFormatter { - private static final long serialVersionUID = -4448291795913908270L; - - private final int minValue; - private final int maxValue; - - private final int initValue; - - public NumberFormatter(final SliderSettings settings) { - minValue = settings.minValue; - maxValue = settings.maxValue; - - initValue = settings.initValue; - } - - @Override - public Object stringToValue(final String text) throws ParseException { - try { - final int val = Integer.parseInt(text); - - if (val < minValue) - throw new ParseException("Value must be greater than " + minValue, 0); - else if (val > maxValue) - throw new ParseException("Value must be smaller than " + maxValue, 0); - else - return val; - } catch (final NumberFormatException nfex) { - final ParseException pex - = new ParseException("Value must be a valid integer", 0); - - pex.initCause(nfex); - - throw pex; - } - } - - @Override - public String valueToString(final Object value) throws ParseException { - if (value == null) - return Integer.toString(initValue); - - return Integer.toString((Integer) value); - } - } - /** * Represents the settings for a slider * @@ -104,7 +60,7 @@ public class SliderInputPanel extends JPanel { * @param max * The maximum slider value * @param init - * Th initial slider value + * The initial slider value */ public SliderSettings(final int min, final int max, final int init) { minValue = min; @@ -153,7 +109,6 @@ public class SliderInputPanel extends JPanel { final int val = slider.getValue(); field.setValue(val); - action.accept(val); } }); @@ -187,3 +142,46 @@ public class SliderInputPanel extends JPanel { field.setValue(value); } } + +final class NumberFormatter extends JFormattedTextField.AbstractFormatter { + private static final long serialVersionUID = -4448291795913908270L; + + private final int minValue; + private final int maxValue; + + private final int initValue; + + public NumberFormatter(final SliderSettings settings) { + minValue = settings.minValue; + maxValue = settings.maxValue; + + initValue = settings.initValue; + } + + @Override + public Object stringToValue(final String text) throws ParseException { + try { + final int val = Integer.parseInt(text); + + if (val < minValue) throw new ParseException( + "Value must be greater than " + minValue, 0); + else if (val > maxValue) throw new ParseException( + "Value must be smaller than " + maxValue, 0); + else return val; + } catch (final NumberFormatException nfex) { + final ParseException pex + = new ParseException("Value must be a valid integer", 0); + + pex.initCause(nfex); + + throw pex; + } + } + + @Override + public String valueToString(final Object value) throws ParseException { + if (value == null) return Integer.toString(initValue); + + return Integer.toString((Integer) value); + } +} diff --git a/base/src/main/java/bjc/utils/ioutils/LevelSplitter.java b/base/src/main/java/bjc/utils/ioutils/LevelSplitter.java index c2467ae..93bc424 100644 --- a/base/src/main/java/bjc/utils/ioutils/LevelSplitter.java +++ b/base/src/main/java/bjc/utils/ioutils/LevelSplitter.java @@ -5,29 +5,24 @@ import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; -/** - * Splits a string on a delimiter, respecting grouping delimiters. +/** Splits a string on a delimiter, respecting grouping delimiters. * * By default, grouping delimiters are (), [], {}, and <>, as well as single and * double quoted strings. * - * @author bjculkin - * - */ + * @author bjculkin */ public class LevelSplitter { - /** - * Defaultly configured level splitter. - */ + /** Default configured level splitter. */ public final static LevelSplitter def = new LevelSplitter(); - /** - * Check if a string contains any one of a specified number of things, + /** Should empty strings be ignored? */ + public boolean ignoreEmpty = false; + + /** Check if a string contains any one of a specified number of things, * respecting groups. * - * @param haystack - * The string to look in. - * @param needles - * The strings to look for. + * @param haystack The string to look in. + * @param needles The strings to look for. * @return Whether or not any of the strings were contained outside of groups. */ public boolean levelContains(String haystack, String... needles) { @@ -88,13 +83,11 @@ public class LevelSplitter { return false; } - /** - * Split a string, respecting groups. + /** Split a string, respecting groups. * - * @param phrase - * The string to split. - * @param splits - * The strings to split on. + * @param phrase The string to split. + * @param splits The strings to split on. + * * @return A list of split strings. If keepDelims is true, it also includes the * delimiters in between the split strings. */ @@ -102,15 +95,12 @@ public class LevelSplitter { return levelSplit(phrase, false, splits); } - /** - * Split a string, respecting groups. + /** Split a string, respecting groups. * - * @param phrase - * The string to split. - * @param keepDelims - * Whether or not to include the delimiters in the results. - * @param splits - * The strings to split on. + * @param phrase The string to split. + * @param keepDelims Whether or not to include the delimiters in the results. + * @param splits The strings to split on. + * * @return A list of split strings. If keepDelims is true, it also includes the * delimiters in between the split strings. */ @@ -140,8 +130,7 @@ public class LevelSplitter { if (work.regionMatches(i, split, 0, split.length())) { strangs.add(work.substring(0, i)); - if (keepDelims) - strangs.add(split); + if (keepDelims) strangs.add(split); work = work.substring(i + split.length()); i = 0; diff --git a/base/src/main/java/bjc/utils/ioutils/LineReader.java b/base/src/main/java/bjc/utils/ioutils/LineReader.java deleted file mode 100644 index 2ac2797..0000000 --- a/base/src/main/java/bjc/utils/ioutils/LineReader.java +++ /dev/null @@ -1,18 +0,0 @@ -package bjc.utils.ioutils; - -/** - * A line reader - * - * @author bjculkin - * - */ -public class LineReader implements AutoCloseable { - //private Scanner scn; - - @Override - public void close() { - //scn.close(); - } - - // @TODO Implement me - ben, 1/6/20 -} diff --git a/base/src/main/java/bjc/utils/ioutils/LogStream.java b/base/src/main/java/bjc/utils/ioutils/LogStream.java new file mode 100644 index 0000000..f5271dc --- /dev/null +++ b/base/src/main/java/bjc/utils/ioutils/LogStream.java @@ -0,0 +1,341 @@ +package bjc.utils.ioutils; + +import java.io.*; + +/** + * Simple class used for logging with various levels. + * + * @author Ben Culkin + */ +public class LogStream { + /** + * Log level for printing nothing. + */ + public static final int NOTHING = -1; + + /** + * Log level for printing only fatal errors. + */ + public static final int FATAL = 0; + + /** + * Log level for printing all errors. + */ + public static final int ERROR = 1; + + /** + * Log level for printing warnings. + */ + public static final int WARN = 2; + + /** + * Log level for printing info messages. + */ + public static final int INFO = 3; + + /** + * Log level for printing debug messages. + */ + public static final int DEBUG = 4; + + /** + * Log level for printing trace messages. + */ + public static final int TRACE = 5; + + private int verbosity; + + private PrintStream output; + + /** + * Create a new log stream. + * + * Defaults to printing only fatal errors. + * + * @param out + * The output stream to place things into. + */ + public LogStream(PrintStream out) { + output = out; + verbosity = FATAL; + } + + /** + * Create a new log stream. + * + * @param out + * The output stream to place things into. + * @param level + * The verbosity level. Use the constants in this class for the + * values. + */ + public LogStream(PrintStream out, int level) { + output = out; + verbosity = level; + } + + /** + * Create a new log stream. + * + * Defaults to printing only fatal errors. + * + * @param out + * The output stream to place things into. + */ + public LogStream(OutputStream out) { + output = new PrintStream(out); + verbosity = FATAL; + } + + /** + * Create a new log stream. + * + * @param out + * The output stream to place things into. + * @param level + * The verbosity level. Use the constants in this class for the + * values. + */ + public LogStream(OutputStream out, int level) { + output = new PrintStream(out); + verbosity = level; + } + + /** + * Get the verbosity of the stream. + * + * @return The verbosity of the stream. + */ + public int verbosity() { + return verbosity; + } + + /** + * Set the verbosity of the stream. + * + * @param verb + * The verbosity of the stream. + */ + public void verbosity(int verb) { + verbosity = verb; + } + + /** + * Increment the verbosity of the stream. + */ + public void louder() { + louder(1); + } + + /** + * Increase the verbosity of the stream by an amount. + * + * @param amt + * The amount to increase the verbosity by. + */ + public void louder(int amt) { + verbosity += amt; + } + + /** + * Decrement the verbosity of the stream. + */ + public void quieter() { + quieter(1); + } + + /** + * Decrease the verbosity of the stream by an amount. + * + * @param amt + * The amount to decrease the verbosity by. + */ + public void quieter(int amt) { + verbosity -= amt; + } + + /** + * Print a message that will always be visible. + * + * @param msg + * The message to print. + */ + public void print(String msg) { + output.print(msg); + } + + /** + * Print a formatted message that will always be visible. + * + * @param msg + * The format string for the message to print. + * + * @param args + * The arguments to the format string. + */ + public void printf(String msg, Object... args) { + output.printf(msg, args); + } + + /** + * Print a message at a given verbosity level. + * + * @param lvl + * The verbosity level. + * @param msg + * The message to print. + */ + public void message(int lvl, String msg) { + if (verbosity >= lvl) { + output.print(msg); + } + } + + /** + * Print a formatted message at a given verbosity level. + * + * @param lvl + * The verbosity level. + * @param msg + * The message to print. + * @param args + * The arguments to the message. + */ + public void messagef(int lvl, String msg, Object... args) { + if (verbosity >= lvl) { + output.printf(msg, args); + } + } + + /** + * Emit a fatal error message. + * + * @param msg + * The message to emit. + */ + public void fatal(String msg) { + message(FATAL, msg); + } + + /** + * Emit a formatted fatal error message. + * + * @param msg + * The message to emit. + * @param args + * The arguments to the message. + */ + public void fatalf(String msg, Object... args) { + messagef(FATAL, msg, args); + } + + /** + * Emit a normal error message. + * + * @param msg + * The message to emit. + */ + public void error(String msg) { + message(ERROR, msg); + } + + /** + * Emit a formatted normal error message. + * + * @param msg + * The message to emit. + * @param args + * The arguments to the message. + */ + public void errorf(String msg, Object... args) { + messagef(ERROR, msg, args); + } + + /** + * Emit a warning message. + * + * @param msg + * The message to emit. + */ + public void warn(String msg) { + message(WARN, msg); + } + + /** + * Emit a formatted warning message. + * + * @param msg + * The message to emit. + * @param args + * The arguments to the message. + */ + public void warnf(String msg, Object... args) { + messagef(WARN, msg, args); + } + + /** + * Emit an info message. + * + * @param msg + * The message to emit. + */ + public void info(String msg) { + message(INFO, msg); + } + + /** + * Emit a formatted info message. + * + * @param msg + * The message to emit. + * @param args + * The arguments to the message. + */ + public void infof(String msg, Object... args) { + messagef(INFO, msg, args); + } + + /** + * Emit a debug message. + * + * @param msg + * The message to emit. + */ + public void debug(String msg) { + message(DEBUG, msg); + } + + /** + * Emit a formatted debug message. + * + * @param msg + * The message to emit. + * @param args + * The arguments to the message. + */ + public void debugf(String msg, Object... args) { + messagef(DEBUG, msg, args); + } + + /** + * Emit a tracing message. + * + * @param msg + * The message to emit. + */ + public void trace(String msg) { + message(TRACE, msg); + } + + /** + * Emit a formatted tracing message. + * + * @param msg + * The message to emit. + * @param args + * The arguments to the message. + */ + public void tracef(String msg, Object... args) { + messagef(TRACE, msg, args); + } +} diff --git a/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java b/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java index 3dad724..e7d8c54 100644 --- a/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java +++ b/base/src/main/java/bjc/utils/ioutils/RegexStringEditor.java @@ -8,7 +8,7 @@ import java.util.regex.Pattern; import bjc.data.Toggle; import bjc.data.ValueToggle; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.functypes.ID; /** @@ -84,7 +84,7 @@ public class RegexStringEditor { /* * Get all of the occurances. */ - final IList<String> occurances = listOccurances(input, rPatt); + final ListEx<String> occurances = listOccurances(input, rPatt); /* * Execute the correct action on every occurance. @@ -118,13 +118,13 @@ public class RegexStringEditor { * * @return The string, with both actions applied. */ - public static IList<String> mapOccurances(final String input, final Pattern rPatt, + public static ListEx<String> mapOccurances(final String input, final Pattern rPatt, final UnaryOperator<String> betweenAction, final UnaryOperator<String> onAction) { /* * Get all of the occurances. */ - final IList<String> occurances = listOccurances(input, rPatt); + final ListEx<String> occurances = listOccurances(input, rPatt); /* * Execute the correct action on every occurance. @@ -146,8 +146,8 @@ public class RegexStringEditor { * @return The string, as a list of match/non-match segments, starting/ending * with a non-match segment. */ - public static IList<String> listOccurances(final String input, final Pattern rPatt) { - final IList<String> res = new FunctionalList<>(); + public static ListEx<String> listOccurances(final String input, final Pattern rPatt) { + final ListEx<String> res = new FunctionalList<>(); /* * Create the matcher and work buffer. diff --git a/base/src/main/java/bjc/utils/ioutils/ReportWriter.java b/base/src/main/java/bjc/utils/ioutils/ReportWriter.java index 3815f25..a04102f 100644 --- a/base/src/main/java/bjc/utils/ioutils/ReportWriter.java +++ b/base/src/main/java/bjc/utils/ioutils/ReportWriter.java @@ -26,8 +26,7 @@ public class ReportWriter extends Writer { // Indent string w/ tabs replaced with spaces public String indentStrSpacedTabs; - public IndentVal() { - } + public IndentVal() {} } // Writer to print to @@ -265,9 +264,7 @@ public class ReportWriter extends Writer { // that case; whether we should continue calling the function, // or just adjust the counts and pretend that nothing // significant happened - while (pageLine > linesPerPage) { - writePage(); - } + while (pageLine > linesPerPage) writePage(); } /** @@ -328,6 +325,11 @@ public class ReportWriter extends Writer { refreshIndents(lvl); } + // @FIXME Ben Culkin 11/13/2020 IntArgument + // Overloading an argument like this is bogus. This should be restructured, + // probably as three different functions; one to refresh a general level, + // one to refresh every level, and one to refresh the default indentation + // Parameter is the level of indents to refresh. // // Pass a index to refresh that level @@ -345,9 +347,7 @@ public class ReportWriter extends Writer { if (lvl == -2) { refreshIndent(defIVal); } else if (lvl == -1) { - for (IndentVal ival : iVals) { - refreshIndent(ival); - } + for (IndentVal ival : iVals) refreshIndent(ival); refreshIndent(defIVal); } else { @@ -364,10 +364,9 @@ public class ReportWriter extends Writer { StringBuilder conv = new StringBuilder(); for (int i = 0; i < indentLength; i++) { char c = vl.indentStr.charAt(i); + if (c == '\t') { - for (int j = 0; j < tabEqv; j++) { - conv.append(' '); - } + for (int j = 0; j < tabEqv; j++) conv.append(' '); vl.indentStrPos += tabEqv; } else { @@ -534,17 +533,14 @@ public class ReportWriter extends Writer { // If we're printing CRLF pairs, make sure that we don't // print incomplete pairs. if (i < lineSpacing - 1) { - if (c == '\n' && lastChar == '\r') - contained.write('\r'); + if (c == '\n' && lastChar == '\r') contained.write('\r'); } } // @NOTE 9/17/18 // // Not sure if this should be here, or before the above loop - if (pageLine > linesPerPage || c == '\f') { - writePage(); - } + if (pageLine > linesPerPage || c == '\f') writePage(); linePos = 0; indentPos = 0; @@ -553,8 +549,7 @@ public class ReportWriter extends Writer { @Override public void write(char[] cbuf, int off, int len) throws IOException { // Skip empty writes - if (len == 0) - return; + if (len == 0) return; // Last character was a new line, print the indent string if (lastCharWasNL) { @@ -568,7 +563,10 @@ public class ReportWriter extends Writer { char c = cbuf[idx]; - if ((c == '\n' && lastChar != '\r') || c == '\n' || c == '\r' || c == '\f') { + if ((c == '\n' && lastChar != '\r') + || c == '\n' + || c == '\r' + || c == '\f') { writeNL(c); } else { if (lastCharWasNL) { @@ -580,9 +578,7 @@ public class ReportWriter extends Writer { if (c == '\t') { linePos += tabEqv; - for (int j = 0; j < tabEqv; j++) { - contained.write(' '); - } + for (int j = 0; j < tabEqv; j++) contained.write(' '); } else { linePos += 1; contained.write(c); @@ -597,12 +593,10 @@ public class ReportWriter extends Writer { for (int j = 0; j < indentLevel; j++) { IndentVal ival = iVals.get(j); - if (printTabsAsSpaces) - contained.write(ival.indentStrSpacedTabs); - else - contained.write(ival.indentStr); + if (printTabsAsSpaces) contained.write(ival.indentStrSpacedTabs); + else contained.write(ival.indentStr); - linePos += ival.indentStrPos; + linePos += ival.indentStrPos; indentPos += ival.indentStrPos; } } @@ -626,4 +620,15 @@ public class ReportWriter extends Writer { public String toString() { return contained.toString(); } + + /** + * Write out a formatted string. + * + * @param format The format string. + * @param items The arguments to the format string. + * @throws IOException Thrown if something goes wrong. + */ + public void writef(String format, Object... items) throws IOException { + write(String.format(format, items)); + } } diff --git a/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java b/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java index 2ce2591..12534bd 100644 --- a/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java +++ b/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java @@ -6,14 +6,14 @@ import java.util.Scanner; import java.util.function.BiConsumer; import java.util.function.Consumer; -import bjc.data.IHolder; -import bjc.data.IPair; -import bjc.data.Identity; +import bjc.data.Holder; import bjc.data.Pair; +import bjc.data.Identity; +import bjc.data.SimplePair; import bjc.utils.exceptions.UnknownPragma; import bjc.funcdata.FunctionalMap; import bjc.funcdata.FunctionalStringTokenizer; -import bjc.funcdata.IMap; +import bjc.funcdata.MapEx; /** * This class parses a rules based config file, and uses it to drive a provided @@ -31,7 +31,7 @@ public class RuleBasedConfigReader<E> { * * Takes the tokenizer, and a pair of the read token and application state */ - private BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start; + private BiConsumer<FunctionalStringTokenizer, Pair<String, E>> start; /* * Function to use when continuing a rule. @@ -52,7 +52,7 @@ public class RuleBasedConfigReader<E> { * * Pragma actions are functions taking a tokenizer and application state */ - private final IMap<String, BiConsumer<FunctionalStringTokenizer, E>> pragmas; + private final MapEx<String, BiConsumer<FunctionalStringTokenizer, E>> pragmas; /** * Create a new rule-based config reader @@ -65,7 +65,7 @@ public class RuleBasedConfigReader<E> { * The action to fire when ending a rule */ public RuleBasedConfigReader( - final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start, + final BiConsumer<FunctionalStringTokenizer, Pair<String, E>> start, final BiConsumer<FunctionalStringTokenizer, E> continueRule, final Consumer<E> end) { this.start = start; @@ -161,7 +161,7 @@ public class RuleBasedConfigReader<E> { /* * This is true when a rule's open */ - final IHolder<Boolean> isRuleOpen = new Identity<>(false); + final Holder<Boolean> isRuleOpen = new Identity<>(false); /* * Do something for every line of the file @@ -237,7 +237,7 @@ public class RuleBasedConfigReader<E> { * The action to execute on starting of a rule */ public void setStartRule( - final BiConsumer<FunctionalStringTokenizer, IPair<String, E>> start) { + final BiConsumer<FunctionalStringTokenizer, Pair<String, E>> start) { if (start == null) throw new NullPointerException("Action on rule start must be non-null"); @@ -270,7 +270,7 @@ public class RuleBasedConfigReader<E> { /* * Handle pragmas */ - pragmas.getOrDefault(token, (tokenzer, stat) -> { + pragmas.get(token).orElse((tokenzer, stat) -> { throw new UnknownPragma("Unknown pragma " + token); }).accept(tokenizer, state); } else { @@ -284,7 +284,7 @@ public class RuleBasedConfigReader<E> { /* * Start a rule */ - start.accept(tokenizer, new Pair<>(nextToken, state)); + start.accept(tokenizer, new SimplePair<>(nextToken, state)); isRuleOpen = true; } diff --git a/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java b/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java index 754ed45..d380866 100644 --- a/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java +++ b/base/src/main/java/bjc/utils/ioutils/SimpleProperties.java @@ -170,17 +170,20 @@ public class SimpleProperties implements Map<String, String> { return props.isEmpty(); } - @Override + @SuppressWarnings("unlikely-arg-type") + @Override public boolean containsKey(final Object key) { return props.containsKey(key); } - @Override + @SuppressWarnings("unlikely-arg-type") + @Override public boolean containsValue(final Object value) { return props.containsValue(value); } - @Override + @SuppressWarnings("unlikely-arg-type") + @Override public String get(final Object key) { return props.get(key); } @@ -190,7 +193,8 @@ public class SimpleProperties implements Map<String, String> { return props.put(key, value); } - @Override + @SuppressWarnings("unlikely-arg-type") + @Override public String remove(final Object key) { return props.remove(key); } diff --git a/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java b/base/src/main/java/bjc/utils/ioutils/TextAreaOutputStream.java index fbc58ed..10f5104 100644 --- a/base/src/main/java/bjc/utils/gui/TextAreaOutputStream.java +++ b/base/src/main/java/bjc/utils/ioutils/TextAreaOutputStream.java @@ -1,4 +1,4 @@ -package bjc.utils.gui; +package bjc.utils.ioutils; import java.io.IOException; import java.io.OutputStream; diff --git a/base/src/main/java/bjc/utils/misc/Direction.java b/base/src/main/java/bjc/utils/misc/Direction.java index cc24b49..2026349 100644 --- a/base/src/main/java/bjc/utils/misc/Direction.java +++ b/base/src/main/java/bjc/utils/misc/Direction.java @@ -7,7 +7,7 @@ import org.apache.commons.lang3.text.WordUtils; import bjc.utils.exceptions.DirectionInvalid; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * A set of cardinal directions @@ -54,7 +54,7 @@ public enum Direction { * * @return A list of all the cardinal directions */ - public static IList<Direction> cardinals() { + public static ListEx<Direction> cardinals() { return new FunctionalList<>(NORTH, SOUTH, EAST, WEST); } @@ -84,7 +84,7 @@ public enum Direction { + nCardinals); } - IList<Direction> cards = cardinals(); + ListEx<Direction> cards = cardinals(); for (int i = 0; i <= 4 - nCardinals; i++) { Direction rDir = cards.randItem(RNG::nextInt); diff --git a/base/src/main/java/bjc/utils/misc/RelativeDirection.java b/base/src/main/java/bjc/utils/misc/RelativeDirection.java index 4239b0d..87d9e10 100644 --- a/base/src/main/java/bjc/utils/misc/RelativeDirection.java +++ b/base/src/main/java/bjc/utils/misc/RelativeDirection.java @@ -5,7 +5,7 @@ import java.util.function.Consumer; import bjc.utils.exceptions.DirectionInvalid; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * Represents a direction that is relative to another direction @@ -62,7 +62,7 @@ public enum RelativeDirection { + numDirections); } - IList<RelativeDirection> relativeDirs = new FunctionalList<>(values()); + ListEx<RelativeDirection> relativeDirs = new FunctionalList<>(values()); if (ignoreBackwards) { relativeDirs.removeMatching(BACKWARD); diff --git a/base/src/main/java/bjc/utils/parserutils/IPrecedent.java b/base/src/main/java/bjc/utils/parserutils/Precedent.java index eb164b3..33b032c 100644 --- a/base/src/main/java/bjc/utils/parserutils/IPrecedent.java +++ b/base/src/main/java/bjc/utils/parserutils/Precedent.java @@ -7,7 +7,7 @@ package bjc.utils.parserutils; * */ @FunctionalInterface -public interface IPrecedent { +public interface Precedent { /** * Create a new object with set precedence * @@ -15,7 +15,7 @@ public interface IPrecedent { * The precedence of the object to handle * @return A new object with set precedence */ - public static IPrecedent newSimplePrecedent(final int precedence) { + public static Precedent newSimplePrecedent(final int precedence) { return () -> precedence; } diff --git a/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java b/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java index 2418517..f0475ff 100644 --- a/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java +++ b/base/src/main/java/bjc/utils/parserutils/ShuntingYard.java @@ -6,8 +6,8 @@ import java.util.function.Function; import bjc.funcdata.FunctionalList; import bjc.funcdata.FunctionalMap; -import bjc.funcdata.IList; -import bjc.funcdata.IMap; +import bjc.funcdata.ListEx; +import bjc.funcdata.MapEx; import bjc.utils.funcutils.StringUtils; /** @@ -25,7 +25,7 @@ public class ShuntingYard<TokenType> { * @author ben * */ - public static enum Operator implements IPrecedent { + public static enum Operator implements Precedent { /** * Represents addition. */ @@ -59,7 +59,7 @@ public class ShuntingYard<TokenType> { /* * Holds all the shuntable operations. */ - private IMap<String, IPrecedent> operators; + private MapEx<String, Precedent> operators; /** * Create a new shunting yard with a default set of operators. @@ -95,7 +95,7 @@ public class ShuntingYard<TokenType> { /* * Create the precedence marker */ - final IPrecedent prec = IPrecedent.newSimplePrecedent(precedence); + final Precedent prec = Precedent.newSimplePrecedent(precedence); this.addOp(operator, prec); } @@ -109,14 +109,12 @@ public class ShuntingYard<TokenType> { * @param precedence * The precedence of the operator. */ - public void addOp(final String operator, final IPrecedent precedence) { + public void addOp(final String operator, final Precedent precedence) { /* * Complain about trying to add an incorrect operator */ - if (operator == null) - throw new NullPointerException("Operator must not be null"); - else if (precedence == null) - throw new NullPointerException("Precedence must not be null"); + if (operator == null) throw new NullPointerException("Operator must not be null"); + else if (precedence == null) throw new NullPointerException("Precedence must not be null"); /* * Add the operator to the ones we handle @@ -140,8 +138,8 @@ public class ShuntingYard<TokenType> { /* * Get the precedence of operators */ - final int rightPrecedence = operators.get(right).getPrecedence(); - final int leftPrecedence = operators.get(left).getPrecedence(); + final int rightPrecedence = operators.get(right).get().getPrecedence(); + final int leftPrecedence = operators.get(left).get().getPrecedence(); /* * Evaluate what we were asked @@ -160,20 +158,18 @@ public class ShuntingYard<TokenType> { * * @return A list of tokens in postfix notation. */ - public IList<TokenType> postfix(final IList<String> input, + public ListEx<TokenType> postfix(final ListEx<String> input, final Function<String, TokenType> transformer) { /* * Check our input */ - if (input == null) - throw new NullPointerException("Input must not be null"); - else if (transformer == null) - throw new NullPointerException("Transformer must not be null"); + if (input == null) throw new NullPointerException("Input must not be null"); + else if (transformer == null) throw new NullPointerException("Transformer must not be null"); /* * Here's what we're handing back */ - final IList<TokenType> output = new FunctionalList<>(); + final ListEx<TokenType> output = new FunctionalList<>(); /* * The stack to put operators on @@ -226,9 +222,7 @@ public class ShuntingYard<TokenType> { } } - for (String token : stack) { - output.add(transformer.apply(token)); - } + for (String token : stack) output.add(transformer.apply(token)); return output; } @@ -244,10 +238,7 @@ public class ShuntingYard<TokenType> { /* * Check if we want to remove all operators */ - if (operator == null) { - operators = new FunctionalMap<>(); - } else { - operators.remove(operator); - } + if (operator == null) operators = new FunctionalMap<>(); + else operators.remove(operator); } } diff --git a/base/src/main/java/bjc/utils/parserutils/StringDescaper.java b/base/src/main/java/bjc/utils/parserutils/StringDescaper.java index f8868e6..7052588 100644 --- a/base/src/main/java/bjc/utils/parserutils/StringDescaper.java +++ b/base/src/main/java/bjc/utils/parserutils/StringDescaper.java @@ -12,7 +12,7 @@ import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; /** - * <<<<<<< Updated upstream Customizable string escapes. + * Customizable string escapes. * * @author Benjamin Culkin */ diff --git a/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java b/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java deleted file mode 100644 index 6cf2da5..0000000 --- a/base/src/main/java/bjc/utils/parserutils/TokenTransformer.java +++ /dev/null @@ -1,148 +0,0 @@ -package bjc.utils.parserutils; - -import java.util.Deque; -import java.util.function.Consumer; -import java.util.function.Function; -import java.util.function.Predicate; -import java.util.function.UnaryOperator; - -import bjc.data.IHolder; -import bjc.data.ITree; -import bjc.data.Pair; -import bjc.data.Tree; -import bjc.utils.parserutils.TreeConstructor.ConstructorState; -import bjc.utils.parserutils.TreeConstructor.QueueFlattener; - -/* - * Handle creating ASTs from tokens. - */ -final class TokenTransformer<TokenType> implements Consumer<TokenType> { - /* - * Handle operators - */ - private final class OperatorHandler - implements UnaryOperator<ConstructorState<TokenType>> { - /* The handled element. */ - private final TokenType element; - - /* Create a new operator handler. */ - public OperatorHandler(final TokenType element) { - this.element = element; - } - - @Override - public ConstructorState<TokenType> apply(final ConstructorState<TokenType> pair) { - /* - * Replace the current AST with the result of handling an operator - */ - return new ConstructorState<>( - pair.bindLeft(queuedASTs -> handleOperator(queuedASTs))); - } - - private ConstructorState<TokenType> - handleOperator(final Deque<ITree<TokenType>> queuedASTs) { - /* - * The AST we're going to hand back - */ - ITree<TokenType> newAST; - - /* - * Handle special operators - */ - if (isSpecialOperator.test(element)) { - newAST = handleSpecialOperator.apply(element).apply(queuedASTs); - } else { - /* - * Error if we don't have enough for a binary operator - */ - if (queuedASTs.size() < 2) { - final String msg = String.format( - "Attempted to parse binary operator without enough operands\n\tProblem operator is: %s\n\tPossible operand is: %s", - element.toString(), queuedASTs.peek().toString()); - - throw new IllegalStateException(msg); - } - - /* - * Grab the two operands - */ - final ITree<TokenType> right = queuedASTs.pop(); - final ITree<TokenType> left = queuedASTs.pop(); - - /* - * Create a new AST - */ - newAST = new Tree<>(element, left, right); - } - - /* - * Stick it onto the stack - */ - queuedASTs.push(newAST); - - /* - * Hand back the state - */ - return new ConstructorState<>(queuedASTs, newAST); - } - } - - /* The initial state of the transformer. */ - private final IHolder<ConstructorState<TokenType>> initialState; - - /* The predicate tot use to detect operators. */ - private final Predicate<TokenType> operatorPredicate; - - /* The predicate for detecting special operators. */ - private final Predicate<TokenType> isSpecialOperator; - /* The function for handling special operators. */ - private final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator; - - /** - * Create a new transformer - * - * @param initialState - * The initial state of the transformer. - * - * @param operatorPredicate - * The predicate to use to identify operators. - * - * @param isSpecialOperator - * The predicate used to identify special - * operators. - * - * @param handleSpecialOperator - * The function used for handling special - * operators. - */ - public TokenTransformer(final IHolder<ConstructorState<TokenType>> initialState, - final Predicate<TokenType> operatorPredicate, - final Predicate<TokenType> isSpecialOperator, - final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { - this.initialState = initialState; - this.operatorPredicate = operatorPredicate; - this.isSpecialOperator = isSpecialOperator; - this.handleSpecialOperator = handleSpecialOperator; - } - - @Override - public void accept(final TokenType element) { - /* - * Handle operators - */ - if (operatorPredicate.test(element)) { - initialState.transform(new OperatorHandler(element)); - } else { - final ITree<TokenType> newAST = new Tree<>(element); - - /* - * Insert the new tree into the AST - */ - initialState.transform(pair -> new ConstructorState<>(pair.bindLeft(queue -> { - queue.push(newAST); - - return new Pair<>(queue, newAST); - }))); - } - } -} diff --git a/base/src/main/java/bjc/utils/parserutils/TokenUtils.java b/base/src/main/java/bjc/utils/parserutils/TokenUtils.java index 81a7ba0..860bbdf 100644 --- a/base/src/main/java/bjc/utils/parserutils/TokenUtils.java +++ b/base/src/main/java/bjc/utils/parserutils/TokenUtils.java @@ -4,13 +4,13 @@ import static bjc.utils.misc.PropertyDB.applyFormat; import static bjc.utils.misc.PropertyDB.getCompiledRegex; import static bjc.utils.misc.PropertyDB.getRegex; -import java.util.LinkedList; -import java.util.List; +import java.util.*; import java.util.regex.Matcher; import java.util.regex.Pattern; +import bjc.data.*; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.utils.parserutils.splitter.TokenSplitter; /** @@ -28,7 +28,7 @@ public class TokenUtils { */ public static class StringTokenSplitter implements TokenSplitter { @Override - public IList<String> split(final String input) { + public ListEx<String> split(final String input) { return new FunctionalList<>(TokenUtils.removeDQuotedStrings(input)); } } @@ -316,4 +316,28 @@ public class TokenUtils { return false; } } + + /** + * Split a line into a series of space-separated arguments, including string + * literals. + * + * @param com + * The command to split from + * @return The split arguments. + */ + public static List<String> processArguments(String com) { + List<String> strings = new ArrayList<>(); + + BooleanToggle togg = new BooleanToggle(); + + for (String strang : removeDQuotedStrings(com)) { + if (togg.get()) { + strings.add(descapeString(strang)); + } else { + for (String strung : strang.split("\\s+")) strings.add(strung); + } + } + + return strings; + } } diff --git a/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java b/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java index 3c7509b..bd907b5 100644 --- a/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java +++ b/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java @@ -2,15 +2,11 @@ package bjc.utils.parserutils; import java.util.Deque; import java.util.LinkedList; -import java.util.function.Function; -import java.util.function.Predicate; +import java.util.function.*; -import bjc.data.IHolder; -import bjc.data.IPair; -import bjc.data.ITree; -import bjc.data.Identity; -import bjc.data.Pair; -import bjc.funcdata.IList; +import bjc.data.*; +import bjc.funcdata.ListEx; +import bjc.utils.parserutils.TreeConstructor.*; /** * Creates a parse tree from a postfix expression. @@ -26,7 +22,7 @@ public class TreeConstructor { * The token type of the tree. */ public interface QueueFlattener<TokenType> - extends Function<Deque<ITree<TokenType>>, ITree<TokenType>> { + extends Function<Deque<Tree<TokenType>>, Tree<TokenType>> { /* * Alias */ @@ -34,14 +30,14 @@ public class TreeConstructor { /* Alias for constructor state. */ static final class ConstructorState<TokenType> - extends Pair<Deque<ITree<TokenType>>, ITree<TokenType>> { - public ConstructorState(final Deque<ITree<TokenType>> left, - final ITree<TokenType> right) { + extends SimplePair<Deque<Tree<TokenType>>, Tree<TokenType>> { + public ConstructorState(final Deque<Tree<TokenType>> left, + final Tree<TokenType> right) { super(left, right); } public ConstructorState( - final IPair<Deque<ITree<TokenType>>, ITree<TokenType>> par) { + final Pair<Deque<Tree<TokenType>>, Tree<TokenType>> par) { super(par.getLeft(), par.getRight()); } } @@ -63,8 +59,8 @@ public class TreeConstructor { * * @return A AST from the expression. */ - public static <TokenType> ITree<TokenType> constructTree( - final IList<TokenType> tokens, final Predicate<TokenType> isOperator) { + public static <TokenType> Tree<TokenType> constructTree( + final ListEx<TokenType> tokens, final Predicate<TokenType> isOperator) { /* Construct a tree with no special operators */ return constructTree(tokens, isOperator, op -> false, null); } @@ -96,26 +92,27 @@ public class TreeConstructor { * @return A AST from the expression. * */ - public static <TokenType> ITree<TokenType> constructTree( - final IList<TokenType> tokens, final Predicate<TokenType> isOperator, + public static <TokenType> Tree<TokenType> constructTree( + final ListEx<TokenType> tokens, final Predicate<TokenType> isOperator, final Predicate<TokenType> isSpecialOperator, final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { /* * Make sure our parameters are valid */ - if (tokens == null) + if (tokens == null) { throw new NullPointerException("Tokens must not be null"); - else if (isOperator == null) + } else if (isOperator == null) { throw new NullPointerException("Operator predicate must not be null"); - else if (isSpecialOperator == null) + } else if (isSpecialOperator == null) { throw new NullPointerException( "Special operator determiner must not be null"); + } final ConstructorState<TokenType> cstate = new ConstructorState<>(new LinkedList<>(), null); /* Here is the state for the tree construction */ - final IHolder<ConstructorState<TokenType>> initialState = new Identity<>(cstate); + final Holder<ConstructorState<TokenType>> initialState = new Identity<>(cstate); /* Transform each of the tokens */ final TokenTransformer<TokenType> trans = new TokenTransformer<>(initialState, @@ -127,3 +124,140 @@ public class TreeConstructor { return initialState.unwrap(ConstructorState::getRight); } } + +/* + * Transform function on tokens + */ +class TokenTransformer<TokenType> implements Consumer<TokenType> { + /* + * Handle operators + */ + private final class OperatorHandler + implements UnaryOperator<ConstructorState<TokenType>> { + /* The handled element. */ + private final TokenType element; + + /* Create a new operator handler. */ + public OperatorHandler(final TokenType element) { + this.element = element; + } + + @Override + public ConstructorState<TokenType> apply(final ConstructorState<TokenType> pair) { + /* + * Replace the current AST with the result of handling an operator + */ + return new ConstructorState<>( + pair.bindLeft(queuedASTs -> handleOperator(queuedASTs))); + } + + private ConstructorState<TokenType> + handleOperator(final Deque<Tree<TokenType>> queuedASTs) { + /* + * The AST we're going to hand back + */ + Tree<TokenType> newAST; + + /* + * Handle special operators + */ + if (isSpecialOperator.test(element)) { + newAST = handleSpecialOperator.apply(element).apply(queuedASTs); + } else { + /* + * Error if we don't have enough for a binary operator + */ + if (queuedASTs.size() < 2) { + final String msg = String.format( + "Attempted to parse binary operator without enough operands\n\tProblem operator is: %s\n\tPossible operand is: %s", + element.toString(), queuedASTs.peek().toString()); + + throw new IllegalStateException(msg); + } + + /* + * Grab the two operands + */ + final Tree<TokenType> right = queuedASTs.pop(); + final Tree<TokenType> left = queuedASTs.pop(); + + /* + * Create a new AST + */ + newAST = new SimpleTree<>(element, left, right); + } + + /* + * Stick it onto the stack + */ + queuedASTs.push(newAST); + + /* + * Hand back the state + */ + return new ConstructorState<>(queuedASTs, newAST); + } + } + + /* The initial state of the transformer. */ + private final Holder<ConstructorState<TokenType>> initialState; + + /* The predicate tot use to detect operators. */ + private final Predicate<TokenType> operatorPredicate; + + /* The predicate for detecting special operators. */ + private final Predicate<TokenType> isSpecialOperator; + /* The function for handling special operators. */ + private final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator; + + /** + * Create a new transformer + * + * @param initialState + * The initial state of the transformer. + * + * @param operatorPredicate + * The predicate to use to identify operators. + * + * @param isSpecialOperator + * The predicate used to identify special + * operators. + * + * @param handleSpecialOperator + * The function used for handling special + * operators. + */ + public TokenTransformer(final Holder<ConstructorState<TokenType>> initialState, + final Predicate<TokenType> operatorPredicate, + final Predicate<TokenType> isSpecialOperator, + final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { + this.initialState = initialState; + this.operatorPredicate = operatorPredicate; + this.isSpecialOperator = isSpecialOperator; + this.handleSpecialOperator = handleSpecialOperator; + } + + @Override + public void accept(final TokenType element) { + /* + * Handle operators + */ + if (operatorPredicate.test(element)) { + initialState.transform(new OperatorHandler(element)); + } else { + final Tree<TokenType> newAST = new SimpleTree<>(element); + + /* + * Insert the new tree into the AST + */ + initialState.transform(pair -> new ConstructorState<>( + pair.bindLeft(queue -> { + queue.push(newAST); + + return new SimplePair<>(queue, newAST); + }) + ) + ); + } + } +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java index ba61531..75f777c 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/DelimiterGroup.java @@ -11,12 +11,12 @@ import java.util.Set; import java.util.function.BiPredicate; import java.util.function.Function; -import bjc.data.IPair; -import bjc.data.ITree; import bjc.data.Pair; import bjc.data.Tree; +import bjc.data.SimplePair; +import bjc.data.SimpleTree; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * Represents a possible delimiter group to match. @@ -37,12 +37,12 @@ public class DelimiterGroup<T> { /* * The contents of this group. */ - private final Deque<ITree<T>> contents; + private final Deque<Tree<T>> contents; /* * The contents of the current subgroup. */ - private IList<ITree<T>> currentGroup; + private ListEx<Tree<T>> currentGroup; /* * The token that opened the group, and any opening parameters. @@ -74,7 +74,7 @@ public class DelimiterGroup<T> { * @param itm * The item to add to this group instance. */ - public void addItem(final ITree<T> itm) { + public void addItem(final Tree<T> itm) { currentGroup.add(itm); } @@ -91,8 +91,8 @@ public class DelimiterGroup<T> { /* * Add all of the contents to the subgroup. */ - final ITree<T> subgroupContents = new Tree<>(chars.contents); - for (final ITree<T> itm : currentGroup) { + final Tree<T> subgroupContents = new SimpleTree<>(chars.contents); + for (final Tree<T> itm : currentGroup) { subgroupContents.addChild(itm); } @@ -100,7 +100,7 @@ public class DelimiterGroup<T> { * Handle subordinate sub-groups. */ while (!contents.isEmpty()) { - final ITree<T> possibleSubordinate = contents.peek(); + final Tree<T> possibleSubordinate = contents.peek(); /* * Subordinate lower priority subgroups. @@ -118,8 +118,8 @@ public class DelimiterGroup<T> { } } - final Tree<T> subgroup - = new Tree<>(chars.subgroup, subgroupContents, new Tree<>(marker)); + final SimpleTree<T> subgroup + = new SimpleTree<>(chars.subgroup, subgroupContents, new SimpleTree<>(marker)); contents.push(subgroup); @@ -137,7 +137,7 @@ public class DelimiterGroup<T> { * * @return This group as a tree. */ - public ITree<T> toTree(final T closer, final SequenceCharacteristics<T> chars) { + public Tree<T> toTree(final T closer, final SequenceCharacteristics<T> chars) { /* * Mark any implied subgroups. */ @@ -146,7 +146,7 @@ public class DelimiterGroup<T> { } /* The resulting tree. */ - final ITree<T> res = new Tree<>(chars.contents); + final Tree<T> res = new SimpleTree<>(chars.contents); /* * Add either the contents of the current group, or subgroups if they're @@ -162,7 +162,7 @@ public class DelimiterGroup<T> { currentGroup.forEach(res::addChild); } - return new Tree<>(groupName, new Tree<>(opener), res, new Tree<>(closer)); + return new SimpleTree<>(groupName, new SimpleTree<>(opener), res, new SimpleTree<>(closer)); } @Override @@ -259,18 +259,18 @@ public class DelimiterGroup<T> { * * @return The name of the group T opens, or null if it doesn't open one. */ - public IPair<T, T[]> doesOpen(final T marker) { + public Pair<T, T[]> doesOpen(final T marker) { if (openDelimiters.containsKey(marker)) - return new Pair<>(openDelimiters.get(marker), null); + return new SimplePair<>(openDelimiters.get(marker), null); - for (final Function<T, IPair<T, T[]>> pred : predOpeners) { - final IPair<T, T[]> par = pred.apply(marker); + for (final Function<T, Pair<T, T[]>> pred : predOpeners) { + final Pair<T, T[]> par = pred.apply(marker); if (par.getLeft() != null) return par; } - return new Pair<>(null, null); + return new SimplePair<>(null, null); } /** @@ -312,7 +312,7 @@ public class DelimiterGroup<T> { private final Map<T, T> impliedSubgroups; /* Allows more complex openings */ - private final List<Function<T, IPair<T, T[]>>> predOpeners; + private final List<Function<T, Pair<T, T[]>>> predOpeners; /* Allow more complex closings */ private final List<BiPredicate<T, T[]>> predClosers; @@ -562,7 +562,7 @@ public class DelimiterGroup<T> { * @param pred * The predicate that defines the opener and its parameters. */ - public void addPredOpener(final Function<T, IPair<T, T[]>> pred) { + public void addPredOpener(final Function<T, Pair<T, T[]>> pred) { predOpeners.add(pred); } diff --git a/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java b/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java index f08201c..db5c3ca 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/RegexOpener.java @@ -4,8 +4,8 @@ import java.util.function.Function; import java.util.regex.Matcher; import java.util.regex.Pattern; -import bjc.data.IPair; import bjc.data.Pair; +import bjc.data.SimplePair; /** * A predicated opener for use with {@link RegexCloser} @@ -13,7 +13,7 @@ import bjc.data.Pair; * @author bjculkin * */ -public class RegexOpener implements Function<String, IPair<String, String[]>> { +public class RegexOpener implements Function<String, Pair<String, String[]>> { /* The name of the group. */ private final String name; /* The pattern that marks an opening group. */ @@ -35,7 +35,7 @@ public class RegexOpener implements Function<String, IPair<String, String[]>> { } @Override - public IPair<String, String[]> apply(final String str) { + public Pair<String, String[]> apply(final String str) { final Matcher m = patt.matcher(str); if (m.matches()) { @@ -47,9 +47,9 @@ public class RegexOpener implements Function<String, IPair<String, String[]>> { parms[i] = m.group(i); } - return new Pair<>(name, parms); + return new SimplePair<>(name, parms); } - return new Pair<>(null, null); + return new SimplePair<>(null, null); } } diff --git a/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java b/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java index 195c1f1..b3f6dc4 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/SequenceDelimiter.java @@ -9,13 +9,13 @@ import com.google.common.collect.HashMultiset; import com.google.common.collect.Multimap; import com.google.common.collect.Multiset; -import bjc.data.IPair; -import bjc.data.ITree; +import bjc.data.Pair; import bjc.data.Tree; +import bjc.data.SimpleTree; import bjc.esodata.PushdownMap; import bjc.esodata.SimpleStack; import bjc.esodata.Stack; -import bjc.funcdata.IMap; +import bjc.funcdata.MapEx; import bjc.utils.funcutils.StringUtils; /** @@ -82,7 +82,7 @@ public class SequenceDelimiter<T> { * delimitation. * */ - public ITree<T> delimitSequence(final SequenceCharacteristics<T> chars, + public Tree<T> delimitSequence(final SequenceCharacteristics<T> chars, @SuppressWarnings("unchecked") final T... seq) throws DelimiterException { if (initialGroup == null) { throw new NullPointerException("Initial group must be specified."); @@ -105,7 +105,7 @@ public class SequenceDelimiter<T> { allowedDelimiters.push(HashMultimap.create()); /* Map of who forbid what for debugging purposes. */ - final IMap<T, T> whoForbid = new PushdownMap<>(); + final MapEx<T, T> whoForbid = new PushdownMap<>(); /* * Process each member of the sequence. @@ -114,7 +114,7 @@ public class SequenceDelimiter<T> { final T tok = seq[i]; /* Check if this token could open a group. */ - final IPair<T, T[]> possibleOpenPar = groupStack.top().doesOpen(tok); + final Pair<T, T[]> possibleOpenPar = groupStack.top().doesOpen(tok); T possibleOpen = possibleOpenPar.getLeft(); if (possibleOpen == null) { @@ -143,11 +143,7 @@ public class SequenceDelimiter<T> { if (isForbidden(groupStack, forbiddenDelimiters, possibleOpen)) { T forbiddenBy; - if (whoForbid.containsKey(tok)) { - forbiddenBy = whoForbid.get(tok); - } else { - forbiddenBy = groupStack.top().getName(); - } + forbiddenBy = whoForbid.get(tok).orElse(groupStack.top().getName()); final String ctxList = StringUtils.toEnglishList(groupStack.toArray(), "then"); @@ -221,7 +217,7 @@ public class SequenceDelimiter<T> { groupStack.top().markSubgroup(tok, chars); } else { /* Add an item to the group. */ - groupStack.top().addItem(new Tree<>(tok)); + groupStack.top().addItem(new SimpleTree<>(tok)); } } diff --git a/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java b/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java index 6035ede..575066d 100644 --- a/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java +++ b/base/src/main/java/bjc/utils/parserutils/delims/StringDelimiter.java @@ -1,6 +1,6 @@ package bjc.utils.parserutils.delims; -import bjc.data.ITree; +import bjc.data.Tree; /** * A sequence delimiter specialized for strings. @@ -26,7 +26,7 @@ public class StringDelimiter extends SequenceDelimiter<String> { * * @see SequenceDelimiter */ - public ITree<String> delimitSequence(final String... seq) throws DelimiterException { + public Tree<String> delimitSequence(final String... seq) throws DelimiterException { return super.delimitSequence( new SequenceCharacteristics<>("root", "contents", "subgroup"), seq); } diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java index 0844b5b..c60b6f2 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/ChainTokenSplitter.java @@ -1,7 +1,7 @@ package bjc.utils.parserutils.splitter; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * A token splitter that chains several other splitters together. @@ -10,7 +10,7 @@ import bjc.funcdata.IList; * */ public class ChainTokenSplitter implements TokenSplitter { - private final IList<TokenSplitter> spliters; + private final ListEx<TokenSplitter> spliters; /** * Create a new chain token splitter. @@ -40,8 +40,8 @@ public class ChainTokenSplitter implements TokenSplitter { } @Override - public IList<String> split(final String input) { - final IList<String> initList = new FunctionalList<>(input); + public ListEx<String> split(final String input) { + final ListEx<String> initList = new FunctionalList<>(input); return spliters.reduceAux(initList, (splitter, strangs) -> strangs.flatMap(splitter::split)); } diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java index 16c1dc3..26d9dbe 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/ConfigurableTokenSplitter.java @@ -6,7 +6,7 @@ import java.util.LinkedHashSet; import java.util.Set; import java.util.regex.Pattern; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * Split a string into pieces around a regular expression, and offer an easy way @@ -111,7 +111,7 @@ public class ConfigurableTokenSplitter extends SimpleTokenSplitter { } @Override - public IList<String> split(final String input) { + public ListEx<String> split(final String input) { if (spliter == null) throw new IllegalStateException("Must compile splitter before use"); diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java index 9a0cd65..52ce4bf 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/ExcludingTokenSplitter.java @@ -5,7 +5,7 @@ import java.util.Set; import java.util.function.Predicate; import bjc.funcdata.FunctionalList; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * A token splitter that will not split certain tokens. @@ -15,7 +15,7 @@ import bjc.funcdata.IList; */ public class ExcludingTokenSplitter implements TokenSplitter { private final Set<String> literalExclusions; - private final IList<Predicate<String>> predExclusions; + private final ListEx<Predicate<String>> predExclusions; private final TokenSplitter spliter; @@ -59,7 +59,7 @@ public class ExcludingTokenSplitter implements TokenSplitter { } @Override - public IList<String> split(final String input) { + public ListEx<String> split(final String input) { if (literalExclusions.contains(input)) return new FunctionalList<>(input); else if (predExclusions.anyMatch(pred -> pred.test(input))) diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java index 85d72e2..70abbbc 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/FilteredTokenSplitter.java @@ -2,7 +2,7 @@ package bjc.utils.parserutils.splitter; import java.util.function.Predicate; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * A token splitter that removes tokens that match a predicate from the stream @@ -31,7 +31,7 @@ public class FilteredTokenSplitter implements TokenSplitter { } @Override - public IList<String> split(String input) { + public ListEx<String> split(String input) { return source.split(input).getMatching(filter); } } diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/IdentityTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/IdentityTokenSplitter.java new file mode 100644 index 0000000..b3b1b29 --- /dev/null +++ b/base/src/main/java/bjc/utils/parserutils/splitter/IdentityTokenSplitter.java @@ -0,0 +1,16 @@ +package bjc.utils.parserutils.splitter; + +import bjc.funcdata.*; + +/** + * The token splitter that doesn't actually perform any splitting. + * + * @author Ben Culkin + * + */ +public class IdentityTokenSplitter implements TokenSplitter { + @Override + public ListEx<String> split(String input) { + return new FunctionalList<>(input); + } +} diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java index 6d88b20..df9ce70 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/SimpleTokenSplitter.java @@ -2,7 +2,7 @@ package bjc.utils.parserutils.splitter; import java.util.regex.Pattern; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.functypes.ID; import bjc.utils.ioutils.RegexStringEditor; @@ -39,7 +39,7 @@ public class SimpleTokenSplitter implements TokenSplitter { } @Override - public IList<String> split(final String input) { + public ListEx<String> split(final String input) { if (keepDelim) { return RegexStringEditor.mapOccurances(input, spliter, ID.id(), ID.id()); } diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java index 59e73e8..e833c21 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitter.java @@ -1,6 +1,6 @@ package bjc.utils.parserutils.splitter; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * Split a string into a list of pieces. @@ -17,5 +17,5 @@ public interface TokenSplitter { * * @return The pieces of the string. */ - public IList<String> split(String input); + public ListEx<String> split(String input); } diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java index 15d6b8b..4aed8f6 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/TokenSplitters.java @@ -25,6 +25,15 @@ public class TokenSplitters { } /** + * Create a new identity token splitter, which doesn't actually do any splitting. + * + * @return A new identity splitter. + */ + public static TokenSplitter identitySplitter() { + return new IdentityTokenSplitter(); + } + + /** * Create a new transforming token splitter. * * @param splitter diff --git a/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java b/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java index b9fbedc..63c3206 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/TransformTokenSplitter.java @@ -2,7 +2,7 @@ package bjc.utils.parserutils.splitter; import java.util.function.UnaryOperator; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; /** * A token splitter that performs a transform on the tokens from another @@ -31,7 +31,7 @@ public class TransformTokenSplitter implements TokenSplitter { } @Override - public IList<String> split(String input) { + public ListEx<String> split(String input) { return source.split(input).map(transform); } diff --git a/base/src/main/java/bjc/utils/patterns/ComplexPattern.java b/base/src/main/java/bjc/utils/patterns/ComplexPattern.java new file mode 100644 index 0000000..c6d72ec --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/ComplexPattern.java @@ -0,0 +1,223 @@ +package bjc.utils.patterns; + +import java.util.function.*; +import java.util.regex.*; + +import bjc.data.*; + +/** + * A pattern that can be matched against. + * + * @author Ben Culkin + * + * @param <InputType> The type of object being matched against. + * @param <ReturnType> The type returned by the pattern. + * @param <PredType> The state type returned by the predicate. + */ +public interface ComplexPattern<ReturnType, PredType, InputType> { + /** + * Whether or not the given input matches this pattern. + * + * @param input The object to check against this pattern. + * + * @return Whether or not this pattern is matched, as well as a state value + * that will get passed to the pattern if it did match. + */ + Pair<Boolean, PredType> matches(InputType input); + + /** + * Apply this pattern, once it has matched. + * + * @param input The object to apply this pattern to. + * @param state The state from the matcher. + * + * @return The result of applying this pattern. + */ + ReturnType apply(InputType input, PredType state); + + /* Pattern producing functions */ + + /** + * Create a pattern composed from a predicate & a function. + * + * @param <RetType> The type returned by the pattern. + * @param <PreType> The type used as intermediate state. + * @param <InpType> The type initially matched against. + * + * @param matcher The predicate that says what this pattern matches. + * @param accepter The action that happens when this pattern matches. + * + * @return A pattern composed from the passed in functions. + */ + static <RetType, PreType, InpType> ComplexPattern<RetType, PreType, InpType> from( + Function<InpType, Pair<Boolean, PreType>> matcher, + BiFunction<InpType, PreType, RetType> accepter) + { + return new FunctionalPattern<>(matcher, accepter); + } + + /** + * Create a pattern which checks if an object is of a given type (or a subtype of it). + * + * @param <ClassType> The type to check if the object is an instance of. + * @param <RetType> The type returned by the action. + * @param <InpType> The type of the thing to match. + * + * @param clasz The Class instance for the type you want to check. + * @param action The action to execute if the pattern does match. + * + * @return A pattern which follows the specified condition. + */ + @SuppressWarnings("unchecked") + static <ClassType, RetType, InpType> ComplexPattern<RetType, ?, InpType> ofClass( + Class<ClassType> clasz, + Function<ClassType, RetType> action) + { + return from( + (input) -> Pair.pair(clasz.isInstance(input), null), + (input, ignored) -> action.apply((ClassType)input) + ); + } + + /** + * Creates a pattern which matches a given object. + * + * @param <RetType> The type returned when the pattern matches. + * @param <InpType> The type of the thing to match. + * + * @param obj The object being tested for equality. + * @param action The action to execute when the object matches. + * + * @return A pattern which tests against the equality of an object. + */ + static <RetType, InpType> ComplexPattern<RetType, ?, InpType> matchesObject( + InpType obj, + Function<InpType, RetType> action + ) + { + return from( + (input) -> Pair.pair(obj.equals(input), null), + (input, ignored) -> action.apply(input) + ); + } + + /** + * Tests if the toString rendition of an object matches a given condition. + * + * @param <RetType> The type returned by the pattern. + * @param <InpType> The type of the thing to match. + * + * @param pattern The string to check against. + * @param action The action to check when the toString of the object matches + * the provided string. This is passed both the object, and its + * string form (in the event that you don't want to call toString + * multiple times, for whatever reason) + * + * @return A pattern which tests against the toString representation of an object. + */ + static <RetType, InpType> ComplexPattern<RetType, ?, InpType> equalsString( + String pattern, + BiFunction<InpType, String, RetType> action + ) + { + Function<InpType, Pair<Boolean, String>> matcher = (input) -> { + String objString = input.toString(); + + return Pair.pair(pattern.equals(objString), objString); + }; + + return from( + matcher, + (input, objString) -> action.apply(input, objString) + ); + } + + /** + * Check if the toString of a given object matches a regex. + * + * @param <RetType> The type returned by the pattern. + * @param <InpType> The type of object to match against. + * + * @param regex The regex to match against. + * @param cond The predicate to use to determine if the regex matched. + * @param action The action to call when the regex matched. + * + * @return A pattern which does the regex matching. + */ + static <RetType, InpType> ComplexPattern<RetType, Matcher, InpType> matchesRegex( + String regex, + Predicate<Matcher> cond, + BiFunction<InpType, Matcher, RetType> action + ) + { + java.util.regex.Pattern regexPat = java.util.regex.Pattern.compile(regex); + + Function<InpType, Pair<Boolean, Matcher>> matcher = (input) -> { + String inpString = input.toString(); + + Matcher mat = regexPat.matcher(inpString); + + if (cond.test(mat)) return Pair.pair(true, mat); + else return Pair.pair(false, null); + }; + + return from( + matcher, + (input, res) -> action.apply(input, res) + ); + } + + // @TODO Nov 21, 2020 Ben Culkin :MorePatterns + // Try and write something to iterate over Iterator in a type-safe manner + // Also, something for doing a sub-pattern match + + /** + * Create a pattern which will always execute. + * + * @param <RetType> The type returned. + * @param <InpType> The type being matched against. + * + * @param action The action to execute. + * + * @return A pattern which will be executed. + */ + static <RetType, InpType> ComplexPattern<RetType, ?, InpType> otherwise( + Function<InpType, RetType> action + ) + { + return from( + (input) -> Pair.pair(true, null), + (input, ignored) -> action.apply(input) + ); + } + + /** + * Create a pattern which checks if the string form of a given object starts + * with a specific string. + * + * @param <RetType> The type returned by the matcher. + * @param <InpType> The type being matched against. + * + * @param pattern The string to check against. + * @param action The action to execute. + * + * @return A pattern which functions as described. + */ + static <RetType, InpType> ComplexPattern<RetType, String, InpType> startsWith( + String pattern, + Function<String, RetType> action) + { + return from((input) -> { + String objString = input.toString(); + + if (objString.startsWith(pattern)) { + return Pair.pair( + true, + objString.substring( + pattern.length())); + } else { + return Pair.pair(false, null); + } + }, (ignored, input) -> action.apply(input)); + } +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/patterns/FunctionalPattern.java b/base/src/main/java/bjc/utils/patterns/FunctionalPattern.java new file mode 100644 index 0000000..1e9dbab --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/FunctionalPattern.java @@ -0,0 +1,47 @@ +package bjc.utils.patterns; + +import java.util.*; +import java.util.function.*; + +import bjc.data.*; + +class FunctionalPattern<ReturnType, PredType, InputType> + implements ComplexPattern<ReturnType, PredType, InputType> { + private final Function<InputType, Pair<Boolean, PredType>> matcher; + private final BiFunction<InputType, PredType, ReturnType> accepter; + + FunctionalPattern( + Function<InputType, Pair<Boolean, PredType>> matcher, + BiFunction<InputType, PredType, ReturnType> accepter) { + super(); + this.matcher = matcher; + this.accepter = accepter; + } + + @Override + public Pair<Boolean, PredType> matches(InputType input) { + return matcher.apply(input); + } + + @Override + public ReturnType apply(InputType input, PredType state) { + return accepter.apply(input, state); + } + + @Override + public int hashCode() { + return Objects.hash(accepter, matcher); + } + + @Override + public boolean equals(Object obj) { + if (this == obj) return true; + if (obj == null) return false; + if (getClass() != obj.getClass()) return false; + + FunctionalPattern<?, ?, ?> other = (FunctionalPattern<?, ?, ?>) obj; + + return Objects.equals(accepter, other.accepter) + && Objects.equals(matcher, other.matcher); + } +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/patterns/FunctionalPatternMatcher.java b/base/src/main/java/bjc/utils/patterns/FunctionalPatternMatcher.java new file mode 100644 index 0000000..e370fa0 --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/FunctionalPatternMatcher.java @@ -0,0 +1,31 @@ +package bjc.utils.patterns; + +import bjc.functypes.*; + +/** + * A simple pattern matcher backed by a function. + * + * @author Ben Culkin + * + * @param <ReturnType> The type returned by the matcher. + * @param <InputType> The type to match against. + */ +public class FunctionalPatternMatcher<ReturnType, InputType> + implements PatternMatcher<ReturnType, InputType> { + + private final ThrowFunction<InputType, ReturnType, NonExhaustiveMatch> matcher; + + /** + * Create a new function-backed pattern matcher. + * + * @param matcher The function backing this matcher. + */ + public FunctionalPatternMatcher(ThrowFunction<InputType, ReturnType, NonExhaustiveMatch> matcher) { + this.matcher = matcher; + } + + @Override + public ReturnType matchFor(InputType input) throws NonExhaustiveMatch { + return matcher.apply(input); + } +} diff --git a/base/src/main/java/bjc/utils/patterns/MutablePatternMatcher.java b/base/src/main/java/bjc/utils/patterns/MutablePatternMatcher.java new file mode 100644 index 0000000..176f588 --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/MutablePatternMatcher.java @@ -0,0 +1,86 @@ +package bjc.utils.patterns; + +import java.util.*; + +import bjc.data.*; + +/** + * A pattern matcher over a mutable set of patterns. + * + * Note that modifying a pattern matcher while it is currently doing pattern + * matching is a wonderful way to cause strange behavior. + * + * @author Ben Culkin + * + * @param <ReturnType> The type returned by the pattern matcher. + * @param <InputType> The type of the input to match against. + */ +public class MutablePatternMatcher<ReturnType, InputType> + implements PatternMatcher<ReturnType, InputType> { + private final List<ComplexPattern<ReturnType, Object, InputType>> patterns; + + /** + * Create a new mutable pattern matcher with no patterns. + */ + public MutablePatternMatcher() { + patterns = new ArrayList<>(); + } + + /** + * Create a new mutable pattern matcher with the given set of patterns. + * + * @param patterns The set of patterns to match on. + */ + @SuppressWarnings("unchecked") + public MutablePatternMatcher(ComplexPattern<ReturnType, ?, InputType>... patterns) { + this(); + + for (ComplexPattern<ReturnType, ?, InputType> pattern : patterns) { + // Note: this may seem a somewhat questionable cast, but because we never + // actually do anything with the value who has a type matching the second + // parameter, this should be safe + this.patterns.add((ComplexPattern<ReturnType, Object, InputType>) pattern); + } + } + + @Override + public ReturnType matchFor(InputType input) throws NonExhaustiveMatch { + Iterator<ComplexPattern<ReturnType, Object, InputType>> iterator; + iterator = new NonCMEIterator<>(patterns); + while(iterator.hasNext()) { + ComplexPattern<ReturnType, Object, InputType> pattern = iterator.next(); + + Pair<Boolean, Object> matches = pattern.matches(input); + + matches.doWith((bool, obj) -> { + if (bool) pattern.apply(input, obj); + }); + } + + throw new NonExhaustiveMatch("Non-exhaustive match against " + input); + } + + /** + * Add a pattern to this pattern matcher. + * + * @param pattern The pattern to add. + * + * @return Whether or not the pattern was added. + */ + @SuppressWarnings("unchecked") + public boolean addPattern(ComplexPattern<ReturnType, ?, InputType> pattern) { + return patterns.add((ComplexPattern<ReturnType, Object, InputType>) pattern); + } + + /** + * Remove a pattern from this pattern matcher. + * + * @param pattern The pattern to remove. + * + * @return Whether or not the pattern was removed. + */ + @SuppressWarnings("unlikely-arg-type") + public boolean removePattern(ComplexPattern<ReturnType, ?, InputType> pattern) { + return patterns.remove(pattern); + } +} diff --git a/base/src/main/java/bjc/utils/patterns/NonExhaustiveMatch.java b/base/src/main/java/bjc/utils/patterns/NonExhaustiveMatch.java new file mode 100644 index 0000000..aaa7e89 --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/NonExhaustiveMatch.java @@ -0,0 +1,20 @@ +package bjc.utils.patterns; + +/** + * Exception thrown when a non-exhaustive match happens. + * @author Ben Culkin + * + */ +public class NonExhaustiveMatch extends Exception { + private static final long serialVersionUID = 3892904574888418544L; + + /** + * Create a new non-exhaustive match. + * + * @param message The message for the exception. + */ + public NonExhaustiveMatch(String message) { + super(message); + } + +} diff --git a/base/src/main/java/bjc/utils/patterns/Pattern.java b/base/src/main/java/bjc/utils/patterns/Pattern.java new file mode 100644 index 0000000..c9902e8 --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/Pattern.java @@ -0,0 +1,14 @@ +package bjc.utils.patterns; + +/** + * A simpler version of ComplexPattern, which always applies against Object + * + * @author Ben Culkin + * + * @param <ReturnType> The type returned by the pattern. + * @param <PredType> The state type returned by the predicate. + */ +public interface Pattern<ReturnType, PredType> + extends ComplexPattern<ReturnType, PredType, Object> { + /* Pattern factory methods */ +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/patterns/PatternMatcher.java b/base/src/main/java/bjc/utils/patterns/PatternMatcher.java new file mode 100644 index 0000000..40bf42b --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/PatternMatcher.java @@ -0,0 +1,85 @@ +package bjc.utils.patterns; + +import java.util.function.*; + +import bjc.functypes.*; + +/** + * Represents a pattern matcher against a series of patterns. + * + * @author Ben Culkin + * + * @param <ReturnType> The type returned from matching the patterns. + * @param <InputType> The type to match against. + */ +@FunctionalInterface +public interface PatternMatcher<ReturnType, InputType> { + /** + * Match an input object against a set of patterns. + * + * @param input The object to match against. + * + * @return The result of matching against the object. + * + * @throws NonExhaustiveMatch If none of the patterns in this set match + */ + ReturnType matchFor(InputType input) throws NonExhaustiveMatch; + + /** + * Create a pattern matcher against a static set of patterns. + * + * @param <RetType> The type returned from matching the patterns. + * @param <InpType> The type to match against. + * + * @param patterns The set of patterns to match on. + * + * @return A pattern matcher which matches on the given patterns. + */ + @SafeVarargs + static <RetType, InpType> PatternMatcher<RetType, InpType> matchingOn( + ComplexPattern<RetType, ?, InpType>... patterns) { + return new SimplePatternMatcher<>(patterns); + } + + /** + * Create a pattern matcher from a handler function. + * + * @param <RetType> The type returned by the matcher. + * @param <InpType> The type to match against. + * + * @param handler The handler function. + * + * @return A pattern matcher defined by the given handler. + */ + static <RetType, InpType> PatternMatcher<RetType, InpType> from( + ThrowFunction<InpType, RetType, NonExhaustiveMatch> handler) { + return new FunctionalPatternMatcher<>(handler); + } + + /** + * Create a pattern matcher which applies a transform to its input. + * + * @param <NewInput> The new input type to use. + * @param transformer The function to convert from the new input to the old input. + * + * @return A pattern matcher which takes values of the new type instead. + */ + default <NewInput> PatternMatcher<ReturnType, NewInput> transformInput( + Function<NewInput, InputType> transformer) { + return from(inp -> matchFor(transformer.apply(inp))); + } + + /** + * Create a pattern matcher which applies a transform to its output. + * + * @param <NewOutput> The new output type to use. + * + * @param transformer The function to convert from the new output to the old output. + * + * @return A pattern matcher which takes values of the new type instead. + */ + default <NewOutput> PatternMatcher<NewOutput, InputType> transformOutput( + Function<ReturnType, NewOutput> transformer) { + return from(inp -> transformer.apply(matchFor(inp))); + } +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/patterns/SimplePatternMatcher.java b/base/src/main/java/bjc/utils/patterns/SimplePatternMatcher.java new file mode 100644 index 0000000..9fae976 --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/SimplePatternMatcher.java @@ -0,0 +1,42 @@ +package bjc.utils.patterns; + +import bjc.data.*; + +/** + * Implements pattern-matching (of a sort) against a collection of patterns. + * + * @author Ben Culkin + * + * @param <InputType> The type input to the pattern matcher. + * @param <ReturnType> The type returned by the pattern. + */ +public class SimplePatternMatcher<ReturnType, InputType> + implements PatternMatcher<ReturnType, InputType> { + private final ComplexPattern<ReturnType, Object, InputType>[] patterns; + + /** + * Create a new pattern matcher. + * + * @param patterns The set of patterns to match against. + */ + @SuppressWarnings("unchecked") + @SafeVarargs + public SimplePatternMatcher(ComplexPattern<ReturnType, ?, InputType>...patterns) { + // Note: this may seem a somewhat questionable cast, but because we never + // actually do anything with the value who has a type matching the second + // parameter, this should be safe + this.patterns = (ComplexPattern<ReturnType, Object, InputType>[]) patterns; + } + + @Override + public ReturnType matchFor(InputType input) throws NonExhaustiveMatch { + for (ComplexPattern<ReturnType, Object, InputType> pattern : patterns) { + Pair<Boolean, Object> matches = pattern.matches(input); + if (matches.getLeft()) { + pattern.apply(input, matches.getRight()); + } + } + + throw new NonExhaustiveMatch("Non-exhaustive match against " + input); + } +} diff --git a/base/src/main/java/bjc/utils/patterns/SimplePatttern.java b/base/src/main/java/bjc/utils/patterns/SimplePatttern.java new file mode 100644 index 0000000..db53287 --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/SimplePatttern.java @@ -0,0 +1,40 @@ +package bjc.utils.patterns; + +import bjc.data.*; + +/** + * A simpler form of a pattern. + * + * @author Ben Culkin + * + * @param <ReturnType> The type returned by matching the pattern. + */ +public interface SimplePatttern<ReturnType> extends Pattern<ReturnType, Void> { + /** + * Test if this pattern does match a given object. + * + * @param input The object to test against. + * + * @return Whether the object matches this pattern. + */ + boolean doesMatch(Object input); + + /** + * Applies this pattern to the input object. + * + * @param input The object that passed the condition. + * + * @return The result of applying this action to the input. + */ + ReturnType doApply(Object input); + + @Override + default ReturnType apply(Object input, Void state) { + return doApply(input); + } + + @Override + default Pair<Boolean, Void> matches(Object input) { + return new SimplePair<>(doesMatch(input), null); + } +}
\ No newline at end of file diff --git a/base/src/main/java/bjc/utils/patterns/package-info.java b/base/src/main/java/bjc/utils/patterns/package-info.java new file mode 100644 index 0000000..a562d95 --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/package-info.java @@ -0,0 +1,6 @@ +package bjc.utils.patterns; + +/* + * Pattern matching (of a sort) in Java. Based off of + * http://kerflyn.wordpress.com/2012/05/09/towards-pattern-matching-in-java/ + */
\ No newline at end of file |
