diff options
77 files changed, 981 insertions, 761 deletions
diff --git a/base/.classpath b/base/.classpath index 9a48b8b..673da3f 100644 --- a/base/.classpath +++ b/base/.classpath @@ -13,9 +13,9 @@ </classpathentry> <classpathentry kind="src" output="target/test-classes" path="src/test/java"> <attributes> + <attribute name="test" value="true"/> <attribute name="optional" value="true"/> <attribute name="maven.pomderived" value="true"/> - <attribute name="test" value="true"/> </attributes> </classpathentry> <classpathentry kind="src" path="src/examples/java"/> diff --git a/base/.settings/org.eclipse.jdt.core.prefs b/base/.settings/org.eclipse.jdt.core.prefs index 51489b4..39e9a95 100644 --- a/base/.settings/org.eclipse.jdt.core.prefs +++ b/base/.settings/org.eclipse.jdt.core.prefs @@ -10,6 +10,7 @@ org.eclipse.jdt.core.compiler.debug.sourceFile=generate org.eclipse.jdt.core.compiler.problem.assertIdentifier=error
org.eclipse.jdt.core.compiler.problem.enablePreviewFeatures=disabled
org.eclipse.jdt.core.compiler.problem.enumIdentifier=error
+org.eclipse.jdt.core.compiler.problem.forbiddenReference=warning
org.eclipse.jdt.core.compiler.problem.reportPreviewFeatures=ignore
org.eclipse.jdt.core.compiler.release=disabled
org.eclipse.jdt.core.compiler.source=1.8
diff --git a/base/data/regexes.sprop b/base/data/regexes.sprop index f1e6787..53560c8 100644 --- a/base/data/regexes.sprop +++ b/base/data/regexes.sprop @@ -38,3 +38,6 @@ fpLeader [\x00-\x20]*[+-]?(?:NaN|Infinity| # Miscellaneous validation regular expressions ############################################## intLiteral \A[+\-]\d+\Z + +readerLineComments (?:#.*\R)* +readerLineBlock (\s*)\S.+\R(?:\1\s+\S.*\R)*
\ No newline at end of file diff --git a/base/src/examples/java/bjc/utils/examples/ShuntTest.java b/base/src/examples/java/bjc/utils/examples/ShuntTest.java index b62a5a6..c5defe4 100644 --- a/base/src/examples/java/bjc/utils/examples/ShuntTest.java +++ b/base/src/examples/java/bjc/utils/examples/ShuntTest.java @@ -3,7 +3,7 @@ package bjc.utils.examples; import java.util.Scanner; import bjc.funcdata.FunctionalStringTokenizer; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.utils.parserutils.ShuntingYard; /** @@ -27,9 +27,9 @@ public class ShuntTest { final ShuntingYard<String> yard = new ShuntingYard<>(true); - final IList<String> preTokens + final ListEx<String> preTokens = new FunctionalStringTokenizer(line).toList(strang -> strang); - final IList<String> shuntedTokens = yard.postfix(preTokens, strang -> strang); + final ListEx<String> shuntedTokens = yard.postfix(preTokens, strang -> strang); System.out.println(shuntedTokens.toString()); diff --git a/base/src/examples/java/bjc/utils/examples/rangen/DiabloItemGen.java b/base/src/examples/java/bjc/utils/examples/rangen/DiabloItemGen.java index 935a189..784ff03 100644 --- a/base/src/examples/java/bjc/utils/examples/rangen/DiabloItemGen.java +++ b/base/src/examples/java/bjc/utils/examples/rangen/DiabloItemGen.java @@ -1,7 +1,7 @@ package bjc.utils.examples.rangen; import bjc.funcdata.FunctionalStringTokenizer; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.utils.gen.WeightedGrammar; /** @@ -15,7 +15,7 @@ public class DiabloItemGen { private static void addCase(final String ruleName, final int probability, final String ruleParts) { - final IList<String> parts = FunctionalStringTokenizer.fromString(ruleParts) + final ListEx<String> parts = FunctionalStringTokenizer.fromString(ruleParts) .toList(strang -> strang); rules.addCase(ruleName, probability, parts); @@ -85,7 +85,7 @@ public class DiabloItemGen { addInfixRules(); for (int i = 0; i < 100; i++) { - final IList<String> ls = rules.generateListValues("<item>", " "); + final ListEx<String> ls = rules.generateListValues("<item>", " "); final StringBuilder sb = new StringBuilder(); ls.forEach(sb::append); diff --git a/base/src/examples/java/bjc/utils/examples/rangen/RandomStringExamples.java b/base/src/examples/java/bjc/utils/examples/rangen/RandomStringExamples.java index bdc4f53..8458de7 100644 --- a/base/src/examples/java/bjc/utils/examples/rangen/RandomStringExamples.java +++ b/base/src/examples/java/bjc/utils/examples/rangen/RandomStringExamples.java @@ -2,7 +2,7 @@ package bjc.utils.examples.rangen; import bjc.funcdata.FunctionalList; import bjc.funcdata.FunctionalStringTokenizer; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.utils.gen.RandomGrammar; /** @@ -15,10 +15,10 @@ public class RandomStringExamples { private static RandomGrammar<String> rg; private static void addRule(final String rule, final String... cases) { - final IList<IList<String>> cses = new FunctionalList<>(); + final ListEx<ListEx<String>> cses = new FunctionalList<>(); for (final String strang : cases) { - final IList<String> lst + final ListEx<String> lst = FunctionalStringTokenizer.fromString(strang).toList(s -> s); cses.add(lst); @@ -56,7 +56,7 @@ public class RandomStringExamples { addRule("<something>", "<activity>", "<activity> with <person>", "<object>"); for (int i = 0; i < 10; i++) { - final IList<String> ls = rg.generateListValues("<sentance>", " "); + final ListEx<String> ls = rg.generateListValues("<sentance>", " "); final StringBuilder sb = new StringBuilder(); ls.forEach(sb::append); diff --git a/base/src/main/java/bjc/utils/cli/GenericCommandMode.java b/base/src/main/java/bjc/utils/cli/GenericCommandMode.java index a96a8f0..60c51a8 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; 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 6e6e604..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,7 +110,7 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> } @Override - public IMap<String, ComponentType> getAll() { + public MapEx<String, ComponentType> getAll() { return components; } @@ -120,7 +120,7 @@ public class FileComponentRepository<ComponentType extends IDescribedComponent> } @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 bba0867..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,14 +34,14 @@ 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; } 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/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/ListUtils.java b/base/src/main/java/bjc/utils/funcutils/ListUtils.java index e3662af..17642ce 100644 --- a/base/src/main/java/bjc/utils/funcutils/ListUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/ListUtils.java @@ -7,7 +7,7 @@ import java.util.List; 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 @@ -27,7 +27,7 @@ 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) { if (input == null) throw new NullPointerException("Input must not be null"); return collapseTokens(input, ""); @@ -45,7 +45,7 @@ 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"); @@ -89,9 +89,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(); @@ -133,9 +133,9 @@ 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)); @@ -161,7 +161,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"); @@ -176,10 +176,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); @@ -215,10 +215,10 @@ 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 ListEx<E> list : lists) { for (final E itm : list.toIterable()) returned.add(itm); } @@ -249,12 +249,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); @@ -433,12 +433,12 @@ public class ListUtils { */ class GroupPartIteration<E> implements Consumer<E> { /* The list we're returning. */ - private final IList<IList<E>> returnedList; + private final ListEx<ListEx<E>> returnedList; /* The current partition of the list. */ - public IList<E> currentPartition; + public ListEx<E> currentPartition; /* The items rejected from the current partition. */ - private final IList<E> rejectedItems; + private final ListEx<E> rejectedItems; /* The number of items in the current partition. */ private int numberInCurrentPartition; @@ -465,7 +465,7 @@ class GroupPartIteration<E> implements Consumer<E> { * @param eleCount * The function to use to determine the value of an item. */ - public GroupPartIteration(final IList<IList<E>> returned, final IList<E> rejects, + 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; 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/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/TreeUtils.java b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java index 59f60a2..41a01d8 100644 --- a/base/src/main/java/bjc/utils/funcutils/TreeUtils.java +++ b/base/src/main/java/bjc/utils/funcutils/TreeUtils.java @@ -21,8 +21,8 @@ public class TreeUtils { * 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()); @@ -33,11 +33,11 @@ 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); @@ -63,10 +63,10 @@ public class TreeUtils { * @param expander The function to expand nodes. * @return A transformed copy of the tree. */ - public static <ContainedType> ITree<ContainedType> substitute( - ITree<ContainedType> tree, + public static <ContainedType> Tree<ContainedType> substitute( + Tree<ContainedType> tree, Predicate<ContainedType> marker, - Function<ContainedType, ITree<ContainedType>> expander) { + Function<ContainedType, Tree<ContainedType>> expander) { tree.topDownTransform((contents) -> { if (marker.test(contents)) return TopDownTransformResult.TRANSFORM; else return TopDownTransformResult.PASSTHROUGH; @@ -84,9 +84,9 @@ public class TreeUtils { * @param environment A map which contains the variables to substitute. * @return A transformed copy of the tree. */ - public static <ContainedType> ITree<ContainedType> substitute( - ITree<ContainedType> tree, - IMap<ContainedType, ITree<ContainedType>> environment) { + public static <ContainedType> Tree<ContainedType> substitute( + Tree<ContainedType> tree, + MapEx<ContainedType, Tree<ContainedType>> environment) { return substitute( tree, environment::containsKey, 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 540efbc..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,7 +111,7 @@ 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) { @@ -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).get(); + 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)) { @@ -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()); @@ -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).get(); + 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).get(); + 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).get(); + 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 969020e..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; @@ -50,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; @@ -68,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; } @@ -91,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) { @@ -114,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); } /** @@ -124,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; } @@ -157,7 +157,7 @@ public class WeightedRandom<E> { public E getDescent(int factor, Random rn) { if (values.getSize() == 0) return null; - for (IPair<Integer, E> val : values) { + for (Pair<Integer, E> val : values) { if (rn.nextInt(factor) == 0) continue; if (exhaust) { @@ -169,7 +169,7 @@ public class WeightedRandom<E> { return val.getRight(); } - IPair<Integer, E> val = values.getByIndex(values.getSize() - 1); + Pair<Integer, E> val = values.getByIndex(values.getSize() - 1); if (exhaust) values.removeMatching(val); return val.getRight(); @@ -231,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(); @@ -248,8 +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 46d27f5..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; /** @@ -62,13 +62,13 @@ public class AdjacencyMap<T> { 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); @@ -80,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) { @@ -115,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 @@ -123,11 +123,11 @@ public class AdjacencyMap<T> { * @param vertices * The set of vertices to create a map from */ - public AdjacencyMap(final IList<T> vertices) { + 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); @@ -143,7 +143,7 @@ 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) -> { diff --git a/base/src/main/java/bjc/utils/graph/Graph.java b/base/src/main/java/bjc/utils/graph/Graph.java index 88b0d08..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() { @@ -120,7 +120,7 @@ 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) { throw new NullPointerException("The source cannot be null."); @@ -159,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()); @@ -177,7 +177,7 @@ public class Graph<T> { ); /* 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. @@ -213,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(); } 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/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/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/RuleBasedConfigReader.java b/base/src/main/java/bjc/utils/ioutils/RuleBasedConfigReader.java index bc19dd9..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"); @@ -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/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 ac82388..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,7 +109,7 @@ 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 */ @@ -158,7 +158,7 @@ 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 @@ -169,7 +169,7 @@ public class ShuntingYard<TokenType> { /* * 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 diff --git a/base/src/main/java/bjc/utils/parserutils/TokenUtils.java b/base/src/main/java/bjc/utils/parserutils/TokenUtils.java index c6fdf5e..860bbdf 100644 --- a/base/src/main/java/bjc/utils/parserutils/TokenUtils.java +++ b/base/src/main/java/bjc/utils/parserutils/TokenUtils.java @@ -10,7 +10,7 @@ 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)); } } diff --git a/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java b/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java index 6780768..bd907b5 100644 --- a/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java +++ b/base/src/main/java/bjc/utils/parserutils/TreeConstructor.java @@ -5,7 +5,7 @@ import java.util.LinkedList; import java.util.function.*; import bjc.data.*; -import bjc.funcdata.IList; +import bjc.funcdata.ListEx; import bjc.utils.parserutils.TreeConstructor.*; /** @@ -22,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 */ @@ -30,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()); } } @@ -59,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); } @@ -92,8 +92,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, final Predicate<TokenType> isSpecialOperator, final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { /* @@ -112,7 +112,7 @@ public class TreeConstructor { = 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, @@ -152,11 +152,11 @@ class TokenTransformer<TokenType> implements Consumer<TokenType> { } private ConstructorState<TokenType> - handleOperator(final Deque<ITree<TokenType>> queuedASTs) { + handleOperator(final Deque<Tree<TokenType>> queuedASTs) { /* * The AST we're going to hand back */ - ITree<TokenType> newAST; + Tree<TokenType> newAST; /* * Handle special operators @@ -178,13 +178,13 @@ class TokenTransformer<TokenType> implements Consumer<TokenType> { /* * Grab the two operands */ - final ITree<TokenType> right = queuedASTs.pop(); - final ITree<TokenType> left = queuedASTs.pop(); + final Tree<TokenType> right = queuedASTs.pop(); + final Tree<TokenType> left = queuedASTs.pop(); /* * Create a new AST */ - newAST = new Tree<>(element, left, right); + newAST = new SimpleTree<>(element, left, right); } /* @@ -200,7 +200,7 @@ class TokenTransformer<TokenType> implements Consumer<TokenType> { } /* The initial state of the transformer. */ - private final IHolder<ConstructorState<TokenType>> initialState; + private final Holder<ConstructorState<TokenType>> initialState; /* The predicate tot use to detect operators. */ private final Predicate<TokenType> operatorPredicate; @@ -227,7 +227,7 @@ class TokenTransformer<TokenType> implements Consumer<TokenType> { * The function used for handling special * operators. */ - public TokenTransformer(final IHolder<ConstructorState<TokenType>> initialState, + public TokenTransformer(final Holder<ConstructorState<TokenType>> initialState, final Predicate<TokenType> operatorPredicate, final Predicate<TokenType> isSpecialOperator, final Function<TokenType, QueueFlattener<TokenType>> handleSpecialOperator) { @@ -245,7 +245,7 @@ class TokenTransformer<TokenType> implements Consumer<TokenType> { if (operatorPredicate.test(element)) { initialState.transform(new OperatorHandler(element)); } else { - final ITree<TokenType> newAST = new Tree<>(element); + final Tree<TokenType> newAST = new SimpleTree<>(element); /* * Insert the new tree into the AST @@ -254,7 +254,7 @@ class TokenTransformer<TokenType> implements Consumer<TokenType> { pair.bindLeft(queue -> { queue.push(newAST); - return new Pair<>(queue, newAST); + return new SimplePair<>(queue, newAST); }) ) ); 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 a73ac88..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) { @@ -217,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 index 6be0e7f..b3b1b29 100644 --- a/base/src/main/java/bjc/utils/parserutils/splitter/IdentityTokenSplitter.java +++ b/base/src/main/java/bjc/utils/parserutils/splitter/IdentityTokenSplitter.java @@ -10,7 +10,7 @@ import bjc.funcdata.*; */ public class IdentityTokenSplitter implements TokenSplitter { @Override - public IList<String> split(String input) { + 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/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 index 3926f2c..c6d72ec 100644 --- a/base/src/main/java/bjc/utils/patterns/ComplexPattern.java +++ b/base/src/main/java/bjc/utils/patterns/ComplexPattern.java @@ -23,7 +23,7 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { * @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. */ - IPair<Boolean, PredType> matches(InputType input); + Pair<Boolean, PredType> matches(InputType input); /** * Apply this pattern, once it has matched. @@ -35,6 +35,8 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { */ ReturnType apply(InputType input, PredType state); + /* Pattern producing functions */ + /** * Create a pattern composed from a predicate & a function. * @@ -48,8 +50,9 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { * @return A pattern composed from the passed in functions. */ static <RetType, PreType, InpType> ComplexPattern<RetType, PreType, InpType> from( - Function<InpType, IPair<Boolean, PreType>> matcher, - BiFunction<InpType, PreType, RetType> accepter) { + Function<InpType, Pair<Boolean, PreType>> matcher, + BiFunction<InpType, PreType, RetType> accepter) + { return new FunctionalPattern<>(matcher, accepter); } @@ -68,9 +71,10 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { @SuppressWarnings("unchecked") static <ClassType, RetType, InpType> ComplexPattern<RetType, ?, InpType> ofClass( Class<ClassType> clasz, - Function<ClassType, RetType> action) { + Function<ClassType, RetType> action) + { return from( - (input) -> IPair.pair(clasz.isInstance(input), null), + (input) -> Pair.pair(clasz.isInstance(input), null), (input, ignored) -> action.apply((ClassType)input) ); } @@ -89,11 +93,12 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { static <RetType, InpType> ComplexPattern<RetType, ?, InpType> matchesObject( InpType obj, Function<InpType, RetType> action - ) { + ) + { return from( - (input) -> IPair.pair(obj.equals(input), null), - (input, ignored) -> action.apply(input) - ); + (input) -> Pair.pair(obj.equals(input), null), + (input, ignored) -> action.apply(input) + ); } /** @@ -113,13 +118,16 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { 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( - (input) -> { - String objString = input.toString(); - - return IPair.pair(pattern.equals(objString), objString); - }, + matcher, (input, objString) -> action.apply(input, objString) ); } @@ -140,21 +148,21 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { 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( - (input) -> { - String inpString = input.toString(); - - Matcher mat = regexPat.matcher(inpString); - - if (cond.test(mat)) { - return IPair.pair(true, mat); - } else { - return IPair.pair(false, null); - } - }, + matcher, (input, res) -> action.apply(input, res) ); } @@ -162,6 +170,7 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { // @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. * @@ -174,10 +183,41 @@ public interface ComplexPattern<ReturnType, PredType, InputType> { */ static <RetType, InpType> ComplexPattern<RetType, ?, InpType> otherwise( Function<InpType, RetType> action - ) { + ) + { return from( - (input) -> IPair.pair(true, null), + (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 index e4b4a3d..1e9dbab 100644 --- a/base/src/main/java/bjc/utils/patterns/FunctionalPattern.java +++ b/base/src/main/java/bjc/utils/patterns/FunctionalPattern.java @@ -7,11 +7,11 @@ import bjc.data.*; class FunctionalPattern<ReturnType, PredType, InputType> implements ComplexPattern<ReturnType, PredType, InputType> { - private final Function<InputType, IPair<Boolean, PredType>> matcher; + private final Function<InputType, Pair<Boolean, PredType>> matcher; private final BiFunction<InputType, PredType, ReturnType> accepter; FunctionalPattern( - Function<InputType, IPair<Boolean, PredType>> matcher, + Function<InputType, Pair<Boolean, PredType>> matcher, BiFunction<InputType, PredType, ReturnType> accepter) { super(); this.matcher = matcher; @@ -19,7 +19,7 @@ class FunctionalPattern<ReturnType, PredType, InputType> } @Override - public IPair<Boolean, PredType> matches(InputType input) { + public Pair<Boolean, PredType> matches(InputType input) { return matcher.apply(input); } diff --git a/base/src/main/java/bjc/utils/patterns/FunctionalPatternMatcher.java b/base/src/main/java/bjc/utils/patterns/FunctionalPatternMatcher.java index 5a214d3..e370fa0 100644 --- a/base/src/main/java/bjc/utils/patterns/FunctionalPatternMatcher.java +++ b/base/src/main/java/bjc/utils/patterns/FunctionalPatternMatcher.java @@ -11,7 +11,7 @@ import bjc.functypes.*; * @param <InputType> The type to match against. */ public class FunctionalPatternMatcher<ReturnType, InputType> - implements IPatternMatcher<ReturnType, InputType> { + implements PatternMatcher<ReturnType, InputType> { private final ThrowFunction<InputType, ReturnType, NonExhaustiveMatch> matcher; diff --git a/base/src/main/java/bjc/utils/patterns/IPatternMatcher.java b/base/src/main/java/bjc/utils/patterns/IPatternMatcher.java deleted file mode 100644 index b688a47..0000000 --- a/base/src/main/java/bjc/utils/patterns/IPatternMatcher.java +++ /dev/null @@ -1,85 +0,0 @@ -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 IPatternMatcher<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> IPatternMatcher<RetType, InpType> matchingOn( - ComplexPattern<RetType, ?, InpType>... patterns) { - return new PatternMatcher<>(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> IPatternMatcher<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> IPatternMatcher<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> IPatternMatcher<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/MutablePatternMatcher.java b/base/src/main/java/bjc/utils/patterns/MutablePatternMatcher.java index 7900262..28e9cd7 100644 --- a/base/src/main/java/bjc/utils/patterns/MutablePatternMatcher.java +++ b/base/src/main/java/bjc/utils/patterns/MutablePatternMatcher.java @@ -13,9 +13,10 @@ import bjc.data.*; * @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 IPatternMatcher<ReturnType, InputType>{ + implements PatternMatcher<ReturnType, InputType> { private final List<ComplexPattern<ReturnType, Object, InputType>> patterns; /** @@ -45,15 +46,15 @@ public class MutablePatternMatcher<ReturnType, InputType> @Override public ReturnType matchFor(InputType input) throws NonExhaustiveMatch { Iterator<ComplexPattern<ReturnType, Object, InputType>> iterator; - for (iterator = new NonCMEIterator<>(patterns); - iterator.hasNext();) { + iterator = new NonCMEIterator<>(patterns); + while(iterator.hasNext()) { ComplexPattern<ReturnType, Object, InputType> pattern = iterator.next(); - IPair<Boolean, Object> matches = pattern.matches(input); + Pair<Boolean, Object> matches = pattern.matches(input); - if (matches.getLeft()) { - pattern.apply(input, matches.getRight()); - } + matches.doWith((bool, obj) -> { + if (bool) pattern.apply(input, obj); + }); } throw new NonExhaustiveMatch("Non-exhaustive match against " + input); diff --git a/base/src/main/java/bjc/utils/patterns/Pattern.java b/base/src/main/java/bjc/utils/patterns/Pattern.java index e03623e..c9902e8 100644 --- a/base/src/main/java/bjc/utils/patterns/Pattern.java +++ b/base/src/main/java/bjc/utils/patterns/Pattern.java @@ -1,11 +1,5 @@ package bjc.utils.patterns; -import java.util.*; -import java.util.function.*; -import java.util.regex.*; - -import bjc.data.*; - /** * A simpler version of ComplexPattern, which always applies against Object * diff --git a/base/src/main/java/bjc/utils/patterns/PatternMatcher.java b/base/src/main/java/bjc/utils/patterns/PatternMatcher.java index e2ae9f6..40bf42b 100644 --- a/base/src/main/java/bjc/utils/patterns/PatternMatcher.java +++ b/base/src/main/java/bjc/utils/patterns/PatternMatcher.java @@ -1,41 +1,85 @@ package bjc.utils.patterns; -import bjc.data.*; +import java.util.function.*; + +import bjc.functypes.*; /** - * Implements pattern-matching (of a sort) against a collection of patterns. + * Represents a pattern matcher against a series of patterns. * * @author Ben Culkin - * - * @param <ReturnType> The type returned by the pattern. + * + * @param <ReturnType> The type returned from matching the patterns. + * @param <InputType> The type to match against. */ -public class PatternMatcher<ReturnType, InputType> - implements IPatternMatcher<ReturnType, InputType> { - private final ComplexPattern<ReturnType, Object, InputType>[] patterns; +@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 new pattern matcher. + * Create a pattern matcher against a static set of patterns. * - * @param patterns The set of patterns to match against. + * @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. */ - @SuppressWarnings("unchecked") @SafeVarargs - public PatternMatcher(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; + 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))); } - @Override - public ReturnType matchFor(InputType input) throws NonExhaustiveMatch { - for (ComplexPattern<ReturnType, Object, InputType> pattern : patterns) { - IPair<Boolean, Object> matches = pattern.matches(input); - if (matches.getLeft()) { - pattern.apply(input, matches.getRight()); - } - } - - throw new NonExhaustiveMatch("Non-exhaustive match against " + input); + /** + * 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..fea947a --- /dev/null +++ b/base/src/main/java/bjc/utils/patterns/SimplePatternMatcher.java @@ -0,0 +1,41 @@ +package bjc.utils.patterns; + +import bjc.data.*; + +/** + * Implements pattern-matching (of a sort) against a collection of patterns. + * + * @author Ben Culkin + * + * @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 index 1601894..db53287 100644 --- a/base/src/main/java/bjc/utils/patterns/SimplePatttern.java +++ b/base/src/main/java/bjc/utils/patterns/SimplePatttern.java @@ -34,7 +34,7 @@ public interface SimplePatttern<ReturnType> extends Pattern<ReturnType, Void> { } @Override - default IPair<Boolean, Void> matches(Object input) { - return new Pair<>(doesMatch(input), null); + default Pair<Boolean, Void> matches(Object input) { + return new SimplePair<>(doesMatch(input), null); } }
\ No newline at end of file diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/CLFormatter.java b/clformat/src/main/java/bjc/utils/ioutils/format/CLFormatter.java index 34da857..c55fda4 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/CLFormatter.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/CLFormatter.java @@ -8,7 +8,6 @@ import bjc.utils.ioutils.ReportWriter; import bjc.utils.ioutils.format.directives.*; // Grab our easy converters/constructors -import static bjc.utils.funcutils.IteratorUtils.AI; import static bjc.utils.funcutils.IteratorUtils.I; /** @@ -143,7 +142,7 @@ public class CLFormatter { * if something goes wrong during formatting the string. */ public String formatString(String format, Object... params) throws IOException { - return formatString(format, I(AI(params))); + return formatString(format, I(I(params))); } /** @@ -300,7 +299,7 @@ public class CLFormatter { boolean isToplevel) throws IOException { try { while (cltok.hasNext()) { - Decree decr = cltok.next(); + SimpleDecree decr = cltok.next(); if (decr.isLiteral) { rw.write(decr.name); @@ -412,7 +411,7 @@ public class CLFormatter { * * @return A set of edicts compiled from the decrees. */ - public List<Edict> compile(Iterable<Decree> decrees) { + public List<Edict> compile(Iterable<SimpleDecree> decrees) { // If we have no decrees, there are no edicts. if (decrees == null) return new ArrayList<>(); @@ -445,7 +444,7 @@ public class CLFormatter { List<Edict> result = new ArrayList<>(); while (cltok.hasNext()) { - Decree decr = cltok.next(); + SimpleDecree decr = cltok.next(); String nam = decr.name; CompileContext compCTX = new CompileContext(cltok, this, decr); diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/CLTokenizer.java b/clformat/src/main/java/bjc/utils/ioutils/format/CLTokenizer.java index 94437ee..7ed76d2 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/CLTokenizer.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/CLTokenizer.java @@ -9,7 +9,7 @@ import java.util.regex.*; * @author bjculkin * */ -public class CLTokenizer implements Iterator<Decree> { +public class CLTokenizer implements Iterator<SimpleDecree> { /** * Whether or not the tokenizer is in debug mode or not. */ @@ -19,13 +19,13 @@ public class CLTokenizer implements Iterator<Decree> { * Internal class for a tokenizer that returns a specific set of tokens. */ private static class SetCLTokenizer extends CLTokenizer { - private Iterator<Decree> body; + private Iterator<SimpleDecree> body; - public SetCLTokenizer(Iterator<Decree> bod) { + public SetCLTokenizer(Iterator<SimpleDecree> bod) { body = bod; } - public SetCLTokenizer(Iterable<Decree> bod) { + public SetCLTokenizer(Iterable<SimpleDecree> bod) { body = bod.iterator(); } @@ -35,14 +35,14 @@ public class CLTokenizer implements Iterator<Decree> { } @Override - public Decree next() { + public SimpleDecree next() { return body.next(); } } private Matcher mat; - private Decree dir; + private SimpleDecree dir; /** * Empty constructor that should only be invoked if you are a subclass who @@ -70,7 +70,7 @@ public class CLTokenizer implements Iterator<Decree> { * * @return A tokenizer yielding the given set of decrees. */ - public static CLTokenizer fromTokens(Iterator<Decree> bod) { + public static CLTokenizer fromTokens(Iterator<SimpleDecree> bod) { return new SetCLTokenizer(bod); } @@ -82,7 +82,7 @@ public class CLTokenizer implements Iterator<Decree> { * * @return A tokenizer yielding the given set of decrees. */ - public static CLTokenizer fromTokens(Iterable<Decree> bod) { + public static CLTokenizer fromTokens(Iterable<SimpleDecree> bod) { return new SetCLTokenizer(bod); } @@ -92,15 +92,15 @@ public class CLTokenizer implements Iterator<Decree> { } @Override - public Decree next() { + public SimpleDecree next() { return getNext(); } - private Decree getNext() { + private SimpleDecree getNext() { if (!hasNext()) throw new NoSuchElementException("No possible decrees remaining"); if (dir != null) { - Decree tmp = dir; + SimpleDecree tmp = dir; dir = null; @@ -125,25 +125,25 @@ public class CLTokenizer implements Iterator<Decree> { boolean isUser = directiveName == null && directiveFunction != null; - dir = new Decree(directiveName, isUser, + dir = new SimpleDecree(directiveName, isUser, CLParameters.fromDirective(directiveParameterString), CLModifiers.fromString(directiveModifierString)); } if (tmp.equals("")) { - Decree dcr = dir; + SimpleDecree dcr = dir; dir = null; return dcr; } - return new Decree(sb.toString()); + return new SimpleDecree(sb.toString()); } mat.appendTail(sb); - return new Decree(sb.toString()); + return new SimpleDecree(sb.toString()); } /** @@ -157,7 +157,7 @@ public class CLTokenizer implements Iterator<Decree> { * * @return A group decree with the given properties. */ - public GroupDecree nextGroup(Decree openedWith, String desiredClosing) { + public GroupDecree nextGroup(SimpleDecree openedWith, String desiredClosing) { return nextGroup(openedWith, desiredClosing, null); } @@ -177,7 +177,7 @@ public class CLTokenizer implements Iterator<Decree> { * * @return A group decree with the given properties. */ - public GroupDecree nextGroup(Decree openedWith, String desiredClosing, + public GroupDecree nextGroup(SimpleDecree openedWith, String desiredClosing, String clauseSep) { GroupDecree newGroup = new GroupDecree(); newGroup.opening = openedWith; @@ -188,7 +188,7 @@ public class CLTokenizer implements Iterator<Decree> { int nestingLevel = 1; - Decree curDecree; + SimpleDecree curDecree; do { curDecree = next(); diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/ClauseDecree.java b/clformat/src/main/java/bjc/utils/ioutils/format/ClauseDecree.java index 9db248c..db38eca 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/ClauseDecree.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/ClauseDecree.java @@ -13,16 +13,16 @@ import bjc.utils.ioutils.ReportWriter; * * @author Ben Culkin */ -public class ClauseDecree implements IDecree { +public class ClauseDecree implements Decree { /** * The decrees that make up the body of this clause. */ - public List<Decree> body; + public List<SimpleDecree> body; /** * The decree that terminated this clause. */ - public Decree terminator; + public SimpleDecree terminator; /** * Create a new blank clause decree. @@ -38,10 +38,10 @@ public class ClauseDecree implements IDecree { * @param children * The decrees to form the body of the clause. */ - public ClauseDecree(Decree... children) { + public ClauseDecree(SimpleDecree... children) { this(); - for (Decree child : children) body.add(child); + for (SimpleDecree child : children) body.add(child); } /** @@ -53,7 +53,7 @@ public class ClauseDecree implements IDecree { * @param children * The decrees that form the body of the clause. */ - public ClauseDecree(Decree term, Decree... children) { + public ClauseDecree(SimpleDecree term, SimpleDecree... children) { this(children); this.terminator = term; @@ -65,7 +65,7 @@ public class ClauseDecree implements IDecree { * @param child * The decree to add to this clause. */ - public void addChild(Decree child) { + public void addChild(SimpleDecree child) { body.add(child); } @@ -96,7 +96,7 @@ public class ClauseDecree implements IDecree { writer.write("\n"); int idx = 0; - for (Decree kid : body) + for (SimpleDecree kid : body) writer.writef("Child %d: %s\n", idx, kid.toString()); writer.dedent(); diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/Decree.java b/clformat/src/main/java/bjc/utils/ioutils/format/Decree.java index 115ef0d..e06caf0 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/Decree.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/Decree.java @@ -1,129 +1,14 @@ package bjc.utils.ioutils.format; /** - * A decree is the building blocks of what we need to pick and call a directive. + * Interface for all decrees. + * + * At the moment, this is just a marker interface, but there may be things added + * here. + * + * @author Ben Culkin * - * Namely, it is the name of the directive, any modifiers attached to the - * directive, and any prefix parameters that are also attached to the directive. - * - * @author Ben Culkin. */ -public class Decree implements IDecree { - /** - * The name of the directive. - */ - public String name; - - /** - * Is this directive an actual directive, or just a literal string? - */ - public boolean isLiteral; - - /** - * Is this directive a user function call? - */ - public boolean isUserCall; - - /** - * The prefix parameters for this directive. - */ - public CLParameters parameters; - - /** - * The modifiers for this directive. - */ - public CLModifiers modifiers; - - /** - * Create a new blank decree. - */ - public Decree() { - - } - - /** - * Create a new literal text directive. - * - * @param txt - * The text of the directive. - */ - public Decree(String txt) { - this.name = txt; - - this.isLiteral = true; - } - - /** - * Create a new directive. - * - * @param name - * The name of the directive. Whether or not it is an actual - * directive will be auto-determined (if it starts with a ~, it's - * a directive.) - * - * @param params - * The prefix parameters to the directive. - * - * @param mods - * The modifiers to the directive. - */ - public Decree(String name, CLParameters params, CLModifiers mods) { - this.name = name; - - this.parameters = params; - - this.modifiers = mods; - - this.isLiteral = false; - } - - /** - * Create a new directive that may be a user function. - * - * @param name - * The name of the directive. Whether or not it is an actual - * directive will be auto-determined (if it starts with a ~ and is - * not a user function, it's a directive.) - * - * @param isUser - * Is this directive a user function? - * - * @param params - * The prefix parameters to the directive. - * - * @param mods - * The modifiers to the directive. - */ - public Decree(String name, boolean isUser, CLParameters params, CLModifiers mods) { - this.name = name; - - this.parameters = params; - - this.modifiers = mods; - - this.isUserCall = isUser; - - this.isLiteral = isUser; - } - - /** - * Check if this decree is a non-literal, with a particular name. - * - * @param nam - * The name to see if we have. - * - * @return Whether or not the provided name equals our name. - */ - public boolean isNamed(String nam) { - // Literals don't have a meaningful name - if (isLiteral) return false; - else return name.equals(nam); - } - - @Override - public String toString() { - return String.format( - "Decree [name='%s', isLiteral=%s, isUserCall=%s, parameters=%s, modifiers='%s']", - name, isLiteral, isUserCall, parameters, modifiers); - } +public interface Decree { + // Marker interface, for now } diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/GroupDecree.java b/clformat/src/main/java/bjc/utils/ioutils/format/GroupDecree.java index 7095aa5..c1c5c7b 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/GroupDecree.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/GroupDecree.java @@ -13,16 +13,16 @@ import bjc.utils.ioutils.ReportWriter; * * @author Ben Culkin */ -public class GroupDecree implements Iterable<ClauseDecree>, IDecree { +public class GroupDecree implements Iterable<ClauseDecree>, Decree { /** * The decree that opened this group. */ - public Decree opening; + public SimpleDecree opening; /** * The decree that closed this group. */ - public Decree closing; + public SimpleDecree closing; /** * The clauses that make up the body of this group. @@ -60,7 +60,7 @@ public class GroupDecree implements Iterable<ClauseDecree>, IDecree { * @param children * The decree making up the body of the group. */ - public GroupDecree(Decree opening, Decree closing, ClauseDecree... children) { + public GroupDecree(SimpleDecree opening, SimpleDecree closing, ClauseDecree... children) { this(children); this.opening = opening; @@ -103,7 +103,7 @@ public class GroupDecree implements Iterable<ClauseDecree>, IDecree { * * @return The decrees that make up the body of the first clause. */ - public List<Decree> unwrap() { + public List<SimpleDecree> unwrap() { return body.get(0).body; } diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/IDecree.java b/clformat/src/main/java/bjc/utils/ioutils/format/IDecree.java deleted file mode 100644 index 17b9ecf..0000000 --- a/clformat/src/main/java/bjc/utils/ioutils/format/IDecree.java +++ /dev/null @@ -1,14 +0,0 @@ -package bjc.utils.ioutils.format; - -/** - * Interface for all decrees. - * - * At the moment, this is just a marker interface, but there may be things added - * here. - * - * @author Ben Culkin - * - */ -public interface IDecree { - // Marker interface, for now -} diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/SimpleDecree.java b/clformat/src/main/java/bjc/utils/ioutils/format/SimpleDecree.java new file mode 100644 index 0000000..a7db42f --- /dev/null +++ b/clformat/src/main/java/bjc/utils/ioutils/format/SimpleDecree.java @@ -0,0 +1,129 @@ +package bjc.utils.ioutils.format; + +/** + * A decree is the building blocks of what we need to pick and call a directive. + * + * Namely, it is the name of the directive, any modifiers attached to the + * directive, and any prefix parameters that are also attached to the directive. + * + * @author Ben Culkin. + */ +public class SimpleDecree implements Decree { + /** + * The name of the directive. + */ + public String name; + + /** + * Is this directive an actual directive, or just a literal string? + */ + public boolean isLiteral; + + /** + * Is this directive a user function call? + */ + public boolean isUserCall; + + /** + * The prefix parameters for this directive. + */ + public CLParameters parameters; + + /** + * The modifiers for this directive. + */ + public CLModifiers modifiers; + + /** + * Create a new blank decree. + */ + public SimpleDecree() { + + } + + /** + * Create a new literal text directive. + * + * @param txt + * The text of the directive. + */ + public SimpleDecree(String txt) { + this.name = txt; + + this.isLiteral = true; + } + + /** + * Create a new directive. + * + * @param name + * The name of the directive. Whether or not it is an actual + * directive will be auto-determined (if it starts with a ~, it's + * a directive.) + * + * @param params + * The prefix parameters to the directive. + * + * @param mods + * The modifiers to the directive. + */ + public SimpleDecree(String name, CLParameters params, CLModifiers mods) { + this.name = name; + + this.parameters = params; + + this.modifiers = mods; + + this.isLiteral = false; + } + + /** + * Create a new directive that may be a user function. + * + * @param name + * The name of the directive. Whether or not it is an actual + * directive will be auto-determined (if it starts with a ~ and is + * not a user function, it's a directive.) + * + * @param isUser + * Is this directive a user function? + * + * @param params + * The prefix parameters to the directive. + * + * @param mods + * The modifiers to the directive. + */ + public SimpleDecree(String name, boolean isUser, CLParameters params, CLModifiers mods) { + this.name = name; + + this.parameters = params; + + this.modifiers = mods; + + this.isUserCall = isUser; + + this.isLiteral = isUser; + } + + /** + * Check if this decree is a non-literal, with a particular name. + * + * @param nam + * The name to see if we have. + * + * @return Whether or not the provided name equals our name. + */ + public boolean isNamed(String nam) { + // Literals don't have a meaningful name + if (isLiteral) return false; + else return name.equals(nam); + } + + @Override + public String toString() { + return String.format( + "Decree [name='%s', isLiteral=%s, isUserCall=%s, parameters=%s, modifiers='%s']", + name, isLiteral, isUserCall, parameters, modifiers); + } +} diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/directives/CompileContext.java b/clformat/src/main/java/bjc/utils/ioutils/format/directives/CompileContext.java index 3c5f692..77c8402 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/directives/CompileContext.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/directives/CompileContext.java @@ -21,7 +21,7 @@ public class CompileContext { /** * The decree that is currently being parsed. */ - public Decree decr; + public SimpleDecree decr; /** * Create a new compilation context. @@ -35,7 +35,7 @@ public class CompileContext { * @param dcr * The decree currently being compiled. */ - public CompileContext(CLTokenizer dirs, CLFormatter fmt, Decree dcr) { + public CompileContext(CLTokenizer dirs, CLFormatter fmt, SimpleDecree dcr) { directives = dirs; formatter = fmt; diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/directives/FormatParameters.java b/clformat/src/main/java/bjc/utils/ioutils/format/directives/FormatParameters.java index d206d17..e2884d3 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/directives/FormatParameters.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/directives/FormatParameters.java @@ -28,7 +28,7 @@ public class FormatParameters { /** * The current decree. */ - public Decree decr; + public SimpleDecree decr; /** * The current format parameters. @@ -66,7 +66,7 @@ public class FormatParameters { * @param formatter * The formatter we are using */ - public FormatParameters(ReportWriter writer, Object item, Decree decr, + public FormatParameters(ReportWriter writer, Object item, SimpleDecree decr, Tape<Object> tParams, CLTokenizer dirIter, CLFormatter formatter) { this.writer = writer; diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/directives/InflectDirective.java b/clformat/src/main/java/bjc/utils/ioutils/format/directives/InflectDirective.java index c4b2edb..937bd9d 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/directives/InflectDirective.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/directives/InflectDirective.java @@ -15,13 +15,13 @@ import bjc.utils.ioutils.format.*; public class InflectDirective implements Directive { @Override public Edict compile(CompileContext compCTX) { - List<Decree> body = new ArrayList<>(); + List<SimpleDecree> body = new ArrayList<>(); int nestLevel = 1; - Iterator<Decree> dirIter = compCTX.directives; + Iterator<SimpleDecree> dirIter = compCTX.directives; while (dirIter.hasNext()) { - Decree decr = dirIter.next(); + SimpleDecree decr = dirIter.next(); if (decr.isLiteral) { body.add(decr); @@ -62,7 +62,7 @@ public class InflectDirective implements Directive { class InflectEdict implements Edict { private CLString body; - public InflectEdict(List<Decree> body, CLFormatter fmt) { + public InflectEdict(List<SimpleDecree> body, CLFormatter fmt) { this.body = new CLString(fmt.compile(body)); } diff --git a/clformat/src/main/java/bjc/utils/ioutils/format/directives/IterationDirective.java b/clformat/src/main/java/bjc/utils/ioutils/format/directives/IterationDirective.java index 4b3b193..34f815d 100644 --- a/clformat/src/main/java/bjc/utils/ioutils/format/directives/IterationDirective.java +++ b/clformat/src/main/java/bjc/utils/ioutils/format/directives/IterationDirective.java @@ -16,12 +16,12 @@ public class IterationDirective implements Directive { public Edict compile(CompileContext compCTX) { IterationEdict.Mode mode; - List<Decree> body = new ArrayList<>(); + List<SimpleDecree> body = new ArrayList<>(); - Iterator<Decree> dirIter = compCTX.directives; + Iterator<SimpleDecree> dirIter = compCTX.directives; // :GroupDecree while (dirIter.hasNext()) { - Decree decr = dirIter.next(); + SimpleDecree decr = dirIter.next(); if (decr.isLiteral) { body.add(decr); } else { @@ -73,7 +73,7 @@ class IterationEdict implements Edict { private CLValue maxItrVal; - public IterationEdict(Mode mode, List<Decree> body, CLFormatter fmt, CLValue maxItr) { + public IterationEdict(Mode mode, List<SimpleDecree> body, CLFormatter fmt, CLValue maxItr) { this.mode = mode; this.body = new CLString(fmt.compile(body)); diff --git a/clformat/src/test/java/bjc/utils/test/ioutils/CLTokenizerTest.java b/clformat/src/test/java/bjc/utils/test/ioutils/CLTokenizerTest.java index 429c089..20d64b0 100644 --- a/clformat/src/test/java/bjc/utils/test/ioutils/CLTokenizerTest.java +++ b/clformat/src/test/java/bjc/utils/test/ioutils/CLTokenizerTest.java @@ -18,7 +18,7 @@ public class CLTokenizerTest { CLTokenizer tokenzer = new CLTokenizer(""); assertTrue("Empty tokenizer has a decree", tokenzer.hasNext()); - Decree dec = tokenzer.next(); + SimpleDecree dec = tokenzer.next(); assertFalse("Empty tokenizer has only one decree", tokenzer.hasNext()); assertTrue("Decree from empty tokenizer is a literal", dec.isLiteral); |
