1
0
mirror of https://github.com/DanilaFe/abacus synced 2026-01-12 10:05:18 +00:00

Move the source files into a new default directory.

This commit is contained in:
2017-07-29 23:44:21 -07:00
parent 92443bf0cf
commit bce469ec8d
41 changed files with 0 additions and 8 deletions

View File

@@ -0,0 +1,171 @@
package org.nwapw.abacus;
import org.nwapw.abacus.config.ConfigurationObject;
import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.parsing.LexerTokenizer;
import org.nwapw.abacus.parsing.ShuntingYardParser;
import org.nwapw.abacus.parsing.TreeBuilder;
import org.nwapw.abacus.plugin.ClassFinder;
import org.nwapw.abacus.plugin.PluginManager;
import org.nwapw.abacus.plugin.StandardPlugin;
import org.nwapw.abacus.tree.NumberReducer;
import org.nwapw.abacus.tree.TreeNode;
import org.nwapw.abacus.window.Window;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
/**
* The main calculator class. This is responsible
* for piecing together all of the components, allowing
* their interaction with each other.
*/
public class Abacus {
/**
* The default implementation to use for the number representation.
*/
public static final Class<? extends NumberInterface> DEFAULT_NUMBER = NaiveNumber.class;
/**
* The file used for saving and loading configuration.
*/
public static final File CONFIG_FILE = new File("config.toml");
/**
* The main Abacus UI.
*/
private Window mainUi;
/**
* The plugin manager responsible for
* loading and unloading plugins,
* and getting functions from them.
*/
private PluginManager pluginManager;
/**
* The reducer used to evaluate the tree.
*/
private NumberReducer numberReducer;
/**
* The configuration loaded from a file.
*/
private ConfigurationObject configuration;
/**
* The tree builder used to construct a tree
* from a string.
*/
private TreeBuilder treeBuilder;
/**
* Creates a new instance of the Abacus calculator.
*/
public Abacus(){
pluginManager = new PluginManager(this);
mainUi = new Window(this);
numberReducer = new NumberReducer(this);
configuration = new ConfigurationObject(CONFIG_FILE);
configuration.save(CONFIG_FILE);
LexerTokenizer lexerTokenizer = new LexerTokenizer();
ShuntingYardParser shuntingYardParser = new ShuntingYardParser(this);
treeBuilder = new TreeBuilder<>(lexerTokenizer, shuntingYardParser);
pluginManager.addListener(lexerTokenizer);
pluginManager.addListener(shuntingYardParser);
pluginManager.addInstantiated(new StandardPlugin(pluginManager));
try {
ClassFinder.loadJars("plugins")
.forEach(plugin -> pluginManager.addClass(plugin));
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
pluginManager.load();
mainUi.setVisible(true);
}
/**
* Gets the current tree builder.
* @return the main tree builder in this abacus instance.
*/
public TreeBuilder getTreeBuilder() {
return treeBuilder;
}
/**
* Gets the current plugin manager,
* @return the plugin manager in this abacus instance.
*/
public PluginManager getPluginManager() {
return pluginManager;
}
/**
* Gets the current UI.
* @return the UI window in this abacus instance.
*/
public Window getMainUi() {
return mainUi;
}
/**
* Get the reducer that is responsible for transforming
* an expression into a number.
* @return the number reducer in this abacus instance.
*/
public NumberReducer getNumberReducer() {
return numberReducer;
}
/**
* Gets the configuration object associated with this instance.
* @return the configuration object.
*/
public ConfigurationObject getConfiguration() {
return configuration;
}
/**
* Parses a string into a tree structure using the main
* tree builder.
* @param input the input string to parse
* @return the resulting tree, null if the tree builder or the produced tree are null.
*/
public TreeNode parseString(String input){
return treeBuilder.fromString(input);
}
/**
* Evaluates the given tree using the main
* number reducer.
* @param tree the tree to reduce, must not be null.
* @return the resulting number, or null of the reduction failed.
*/
public NumberInterface evaluateTree(TreeNode tree){
return tree.reduce(numberReducer);
}
public NumberInterface numberFromString(String numberString){
Class<? extends NumberInterface> toInstantiate =
pluginManager.numberFor(configuration.getNumberImplementation());
if(toInstantiate == null) toInstantiate = DEFAULT_NUMBER;
try {
return toInstantiate.getConstructor(String.class).newInstance(numberString);
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
return null;
}
public static void main(String[] args){
try {
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
} catch (ClassNotFoundException | InstantiationException | UnsupportedLookAndFeelException | IllegalAccessException e) {
e.printStackTrace();
}
new Abacus();
}
}

View File

@@ -0,0 +1,14 @@
package org.nwapw.abacus.config;
/**
* Serializable class that will be used to load TOML
* configurations.
*/
public class Configuration {
/**
* The type of number this calculator should use.
*/
public String numberType;
}

View File

@@ -0,0 +1,105 @@
package org.nwapw.abacus.config;
import com.moandjiezana.toml.Toml;
import com.moandjiezana.toml.TomlWriter;
import java.io.File;
import java.io.IOException;
/**
* A configuration object, which essentially
* manages saving, loading, and getting values
* from the configuration. While Configuration is
* the data model, this is the interface with it.
*/
public class ConfigurationObject {
/**
* The writer used to store the configuration.
*/
private static final TomlWriter TOML_WRITER = new TomlWriter();
/**
* The configuration instance being modeled.
*/
private Configuration configuration;
/**
* Sets up the ConfigurationObject.
* different constructors do different things,
* but they all lead here.
* @param configuration the configuration to set up with.
*/
private void setup(Configuration configuration){
this.configuration = configuration;
}
/**
* Creates a default configuration.
* @return the newly created default configuration.
*/
private Configuration getDefaultConfig(){
configuration = new Configuration();
configuration.numberType = "naive";
return configuration;
}
/**
* Returns the implementation the user has requested to
* represent their numbers.
* @return the implementation name.
*/
public String getNumberImplementation() {
return configuration.numberType;
}
/**
* Saves the ConfigurationObject to the given file.
* @param toFile the file to save ot.
* @return true if the save succeed, false if otherwise.
*/
public boolean save(File toFile){
if(toFile.getParentFile() != null) toFile.getParentFile().mkdirs();
try {
TOML_WRITER.write(configuration, toFile);
return true;
} catch (IOException e) {
e.printStackTrace();
}
return false;
}
/**
* Creates a new configuration object with the given config.
* @param config the config to use.
*/
public ConfigurationObject(Configuration config){
setup(config);
}
/**
* Create a configuration object by attempting to
* load a config from the given path, using the
* default configuration otherwise.
* @param path the path to attempt to load.
*/
public ConfigurationObject(File path){
Configuration config;
if(!path.exists()) {
config = getDefaultConfig();
} else {
Toml parse = new Toml();
parse.read(path);
config = parse.to(Configuration.class);
}
setup(config);
}
/**
* Creates a new configuration object with the
* default configuration.
*/
public ConfigurationObject(){
setup(getDefaultConfig());
}
}

View File

@@ -0,0 +1,49 @@
package org.nwapw.abacus.function;
import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.number.PreciseNumber;
import java.util.HashMap;
/**
* A function that operates on one or more
* inputs and returns a single number.
*/
public abstract class Function {
/**
* A map to correctly promote different number implementations to each other.
*/
private static final HashMap<Class<? extends NumberInterface>, Integer> priorityMap =
new HashMap<Class<? extends NumberInterface>, Integer>() {{
put(NaiveNumber.class, 0);
put(PreciseNumber.class, 1);
}};
/**
* Checks whether the given params will work for the given function.
* @param params the given params
* @return true if the params can be used with this function.
*/
protected abstract boolean matchesParams(NumberInterface[] params);
/**
* Internal apply implementation, which already receives appropriately promoted
* parameters that have bee run through matchesParams
* @param params the promoted parameters.
* @return the return value of the function.
*/
protected abstract NumberInterface applyInternal(NumberInterface[] params);
/**
* Function to check, promote arguments and run the function.
* @param params the raw input parameters.
* @return the return value of the function, or null if an error occurred.
*/
public NumberInterface apply(NumberInterface...params) {
if(!matchesParams(params)) return null;
return applyInternal(params);
}
}

View File

@@ -0,0 +1,70 @@
package org.nwapw.abacus.function;
/**
* A class that represents a single infix operator.
*/
public class Operator {
/**
* The associativity of the operator.
*/
private OperatorAssociativity associativity;
/**
* The type of this operator.
*/
private OperatorType type;
/**
* The precedence of the operator.
*/
private int precedence;
/**
* The function that is called by this operator.
*/
private Function function;
/**
* Creates a new operator with the given parameters.
* @param associativity the associativity of the operator.
* @param precedence the precedence of the operator.
* @param function the function that the operator calls.
*/
public Operator(OperatorAssociativity associativity, OperatorType operatorType, int precedence, Function function){
this.associativity = associativity;
this.type = operatorType;
this.precedence = precedence;
this.function = function;
}
/**
* Gets the operator's associativity.
* @return the associativity.
*/
public OperatorAssociativity getAssociativity() {
return associativity;
}
/**
* Gets the operator's type.
* @return the type.
*/
public OperatorType getType() {
return type;
}
/**
* Gets the operator's precedence.
* @return the precedence.
*/
public int getPrecedence() {
return precedence;
}
/**
* Gets the operator's function.
* @return the function.
*/
public Function getFunction() {
return function;
}
}

View File

@@ -0,0 +1,8 @@
package org.nwapw.abacus.function;
/**
* Enum to represent the associativity of an operator.
*/
public enum OperatorAssociativity {
LEFT, RIGHT
}

View File

@@ -0,0 +1,8 @@
package org.nwapw.abacus.function;
/**
* The type of an operator, describing how it should behave.
*/
public enum OperatorType {
BINARY_INFIX, UNARY_POSTFIX
}

View File

@@ -0,0 +1,144 @@
package org.nwapw.abacus.lexing;
import org.nwapw.abacus.lexing.pattern.EndNode;
import org.nwapw.abacus.lexing.pattern.Match;
import org.nwapw.abacus.lexing.pattern.Pattern;
import org.nwapw.abacus.lexing.pattern.PatternNode;
import java.util.*;
/**
* A lexer that can generate tokens of a given type given a list of regular expressions
* to operate on.
* @param <T> the type used to identify which match belongs to which pattern.
*/
public class Lexer<T> {
/**
* An entry that represents a pattern that has been registered with the lexer.
* @param <T> the type used to identify the pattern.
*/
private static class PatternEntry<T>{
/**
* The name of the entry.
*/
public String name;
/**
* The id of the entry.
*/
public T id;
/**
* Creates a new pattern entry with the given name and id.
* @param name the name of the pattern entry.
* @param id the id of the pattern entry.
*/
public PatternEntry(String name, T id){
this.name = name;
this.id = id;
}
@Override
public int hashCode() {
return Objects.hash(name, id);
}
@Override
public boolean equals(Object obj) {
return obj instanceof PatternEntry &&
((PatternEntry) obj).name.equals(name) &&
((PatternEntry) obj).id.equals(id);
}
}
/**
* The registered patterns.
*/
private Map<PatternEntry<T>, Pattern<T>> patterns;
/**
* Creates a new lexer with no registered patterns.
*/
public Lexer(){
patterns = new HashMap<>();
}
/**
* Registers a single pattern.
* @param pattern the pattern regex
* @param id the ID by which to identify the pattern.
*/
public void register(String pattern, T id){
Pattern<T> compiledPattern = new Pattern<>(pattern, id);
if(compiledPattern.getHead() != null) patterns.put(new PatternEntry<>(pattern, id), compiledPattern);
}
/**
* Unregisters a pattern.
* @param pattern the pattern to unregister
* @param id the ID by which to identify the pattern.
*/
public void unregister(String pattern, T id){
patterns.remove(new PatternEntry<>(pattern, id));
}
/**
* Reads one token from the given string.
* @param from the string to read from
* @param startAt the index to start at
* @param compare the comparator used to sort tokens by their ID.
* @return the best match.
*/
public Match<T> lexOne(String from, int startAt, Comparator<T> compare){
ArrayList<Match<T>> matches = new ArrayList<>();
HashSet<PatternNode<T>> currentSet = new HashSet<>();
HashSet<PatternNode<T>> futureSet = new HashSet<>();
int index = startAt;
for(Pattern<T> pattern : patterns.values()){
pattern.getHead().addInto(currentSet);
}
while(!currentSet.isEmpty()){
for(PatternNode<T> node : currentSet){
if(index < from.length() && node.matches(from.charAt(index))) {
node.addOutputsInto(futureSet);
} else if(node instanceof EndNode){
matches.add(new Match<>(from.substring(startAt, index), ((EndNode<T>) node).getPatternId()));
}
}
HashSet<PatternNode<T>> tmp = currentSet;
currentSet = futureSet;
futureSet = tmp;
futureSet.clear();
index++;
}
matches.sort((a, b) -> compare.compare(a.getType(), b.getType()));
if(compare != null) {
matches.sort(Comparator.comparingInt(a -> a.getContent().length()));
}
return matches.isEmpty() ? null : matches.get(matches.size() - 1);
}
/**
* Reads all tokens from a string.
* @param from the string to start from.
* @param startAt the index to start at.
* @param compare the comparator used to sort matches by their IDs.
* @return the resulting list of matches, in order, or null on error.
*/
public List<Match<T>> lexAll(String from, int startAt, Comparator<T> compare){
int index = startAt;
ArrayList<Match<T>> matches = new ArrayList<>();
Match<T> lastMatch = null;
while(index < from.length() && (lastMatch = lexOne(from, index, compare)) != null){
int length = lastMatch.getContent().length();
if(length == 0) return null;
matches.add(lastMatch);
index += length;
}
if(lastMatch == null) return null;
return matches;
}
}

View File

@@ -0,0 +1,14 @@
package org.nwapw.abacus.lexing.pattern;
/**
* A pattern node that matches any character.
* @param <T> the type that's used to tell which pattern this node belongs to.
*/
public class AnyNode<T> extends PatternNode<T> {
@Override
public boolean matches(char other) {
return true;
}
}

View File

@@ -0,0 +1,30 @@
package org.nwapw.abacus.lexing.pattern;
/**
* A node that represents a successful match.
* @param <T> the type that's used to tell which pattern this node belongs to.
*/
public class EndNode<T> extends PatternNode<T> {
/**
* The ID of the pattenr that has been matched.
*/
private T patternId;
/**
* Creates a new end node with the given ID.
* @param patternId the pattern ID.
*/
public EndNode(T patternId){
this.patternId = patternId;
}
/**
* Gets the pattern ID.
* @return the pattern ID.
*/
public T getPatternId(){
return patternId;
}
}

View File

@@ -0,0 +1,20 @@
package org.nwapw.abacus.lexing.pattern;
import java.util.ArrayList;
import java.util.Collection;
/**
* A node that is used as structural glue in pattern compilation.
* @param <T> the type that's used to tell which pattern this node belongs to.
*/
public class LinkNode<T> extends PatternNode<T> {
@Override
public void addInto(Collection<PatternNode<T>> into) {
if(!into.contains(this)) {
into.add(this);
addOutputsInto(into);
}
}
}

View File

@@ -0,0 +1,43 @@
package org.nwapw.abacus.lexing.pattern;
/**
* A match that has been generated by the lexer.
* @param <T> the type used to represent the ID of the pattern this match belongs to.
*/
public class Match<T> {
/**
* The content of this match.
*/
private String content;
/**
* The pattern type this match matched.
*/
private T type;
/**
* Creates a new match with the given parameters.
* @param content the content of this match.
* @param type the type of the match.
*/
public Match(String content, T type){
this.content = content;
this.type = type;
}
/**
* Gets the content of this match.
* @return the content.
*/
public String getContent() {
return content;
}
/**
* Gets the pattern type of the node.
* @return the ID of the pattern that this match matched.
*/
public T getType() {
return type;
}
}

View File

@@ -0,0 +1,257 @@
package org.nwapw.abacus.lexing.pattern;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.function.Function;
/**
* A pattern that can be compiled from a string and used in lexing.
* @param <T> the type that is used to identify and sort this pattern.
*/
public class Pattern<T> {
/**
* The ID of this pattern.
*/
private T id;
/**
* The head of this pattern.
*/
private PatternNode<T> head;
/**
* The source string of this pattern.
*/
private String source;
/**
* The index at which the compilation has stopped.
*/
private int index;
/**
* A map of regex operator to functions that modify a PatternChain
* with the appropriate operation.
*/
private Map<Character, Function<PatternChain<T>, PatternChain<T>>> operations =
new HashMap<Character, Function<PatternChain<T>, PatternChain<T>>>() {{
put('+', Pattern.this::transformPlus);
put('*', Pattern.this::transformStar);
put('?', Pattern.this::transformQuestion);
}};
/**
* A regex operator function that turns the chain
* into a one-or-more chain.
* @param chain the chain to transform.
* @return the modified chain.
*/
private PatternChain<T> transformPlus(PatternChain<T> chain){
chain.tail.outputStates.add(chain.head);
return chain;
}
/**
* A regex operator function that turns the chain
* into a zero-or-more chain.
* @param chain the chain to transform.
* @return the modified chain.
*/
private PatternChain<T> transformStar(PatternChain<T> chain){
LinkNode<T> newTail = new LinkNode<>();
LinkNode<T> newHead = new LinkNode<>();
newHead.outputStates.add(chain.head);
newHead.outputStates.add(newTail);
chain.tail.outputStates.add(newTail);
newTail.outputStates.add(newHead);
chain.head = newHead;
chain.tail = newTail;
return chain;
}
/**
* A regex operator function that turns the chain
* into a zero-or-one chain.
* @param chain the chain to transform.
* @return the modified chain.
*/
private PatternChain<T> transformQuestion(PatternChain<T> chain){
LinkNode<T> newTail = new LinkNode<>();
LinkNode<T> newHead = new LinkNode<>();
newHead.outputStates.add(chain.head);
newHead.outputStates.add(newTail);
chain.tail.outputStates.add(newTail);
chain.head = newHead;
chain.tail = newTail;
return chain;
}
/**
* Combines a collection of chains into one OR chain.
* @param collection the collection of chains to combine.
* @return the resulting OR chain.
*/
private PatternChain<T> combineChains(Collection<PatternChain<T>> collection){
LinkNode<T> head = new LinkNode<>();
LinkNode<T> tail = new LinkNode<>();
PatternChain<T> newChain = new PatternChain<>(head, tail);
for(PatternChain<T> chain : collection){
head.outputStates.add(chain.head);
chain.tail.outputStates.add(tail);
}
return newChain;
}
/**
* Parses a single value from the input into a chain.
* @return the resulting chain, or null on error.
*/
private PatternChain<T> parseValue(){
if(index >= source.length()) return null;
if(source.charAt(index) == '\\'){
if(++index >= source.length()) return null;
}
return new PatternChain<>(new ValueNode<>(source.charAt(index++)));
}
/**
* Parses a [] range from the input into a chain.
* @return the resulting chain, or null on error.
*/
private PatternChain<T> parseOr(){
Stack<PatternChain<T>> orStack = new Stack<>();
index++;
while(index < source.length() && source.charAt(index) != ']'){
if(source.charAt(index) == '-'){
index++;
if(orStack.empty() || orStack.peek().tail.range() == '\0') return null;
PatternChain<T> bottomRange = orStack.pop();
PatternChain<T> topRange = parseValue();
if(topRange == null || topRange.tail.range() == '\0') return null;
orStack.push(new PatternChain<>(new RangeNode<>(bottomRange.tail.range(), topRange.tail.range())));
} else {
PatternChain<T> newChain = parseValue();
if(newChain == null) return null;
orStack.push(newChain);
}
}
if(index++ >= source.length()) return null;
return (orStack.size() == 1) ? orStack.pop() : combineChains(orStack);
}
/**
* Parses a repeatable segment from the input into a chain
* @param isSubsegment whether the segment is a sub-expression "()", and therefore
* whether to expect a closing brace.
* @return the resulting chain, or null on error.
*/
private PatternChain<T> parseSegment(boolean isSubsegment){
if(index >= source.length() || ((source.charAt(index) != '(') && isSubsegment)) return null;
if(isSubsegment) index++;
Stack<PatternChain<T>> orChain = new Stack<>();
PatternChain<T> fullChain = new PatternChain<>();
PatternChain<T> currentChain = null;
while (index < source.length() && source.charAt(index) != ')'){
char currentChar = source.charAt(index);
if(operations.containsKey(currentChar)){
if(currentChain == null) return null;
currentChain = operations.get(currentChar).apply(currentChain);
fullChain.append(currentChain);
currentChain = null;
index++;
} else if(currentChar == '|'){
if(currentChain == null) return null;
fullChain.append(currentChain);
orChain.push(fullChain);
currentChain = null;
fullChain = new PatternChain<>();
if(++index >= source.length()) return null;
} else if(currentChar == '('){
if(currentChain != null) {
fullChain.append(currentChain);
}
currentChain = parseSegment(true);
if(currentChain == null) return null;
} else if(currentChar == '['){
if(currentChain != null){
fullChain.append(currentChain);
}
currentChain = parseOr();
if(currentChain == null) return null;
} else if(currentChar == '.'){
if(currentChain != null){
fullChain.append(currentChain);
}
currentChain = new PatternChain<>(new AnyNode<>());
index++;
} else {
if(currentChain != null){
fullChain.append(currentChain);
}
currentChain = parseValue();
if(currentChain == null) return null;
}
}
if(!(!isSubsegment || (index < source.length() && source.charAt(index) == ')'))) return null;
if(isSubsegment) index++;
if(currentChain != null) fullChain.append(currentChain);
if(!orChain.empty()){
orChain.push(fullChain);
fullChain = combineChains(orChain);
}
return fullChain;
}
/**
* Creates / compiles a new pattern with the given id from the given string.
* @param from the string to compile a pattern from.
* @param id the ID to use.
*/
public Pattern(String from, T id){
this.id = id;
index = 0;
source = from;
PatternChain<T> chain = parseSegment(false);
if(chain == null) {
head = null;
} else {
chain.append(new EndNode<>(id));
head = chain.head;
}
}
/**
* Gets the head PatternNode, for use in matching
* @return the pattern node.
*/
public PatternNode<T> getHead() {
return head;
}
/**
* Removes all characters that are considered "special" from
* the given string.
* @param from the string to sanitize.
* @return the resulting string.
*/
public static String sanitize(String from){
Pattern<Integer> pattern = new Pattern<>("", 0);
from = from.replace(".", "\\.");
from = from.replace("|", "\\|");
from = from.replace("(", "\\(");
from = from.replace(")", "\\)");
for(Character key : pattern.operations.keySet()){
from = from.replace("" + key, "\\" + key);
}
return from;
}
}

View File

@@ -0,0 +1,75 @@
package org.nwapw.abacus.lexing.pattern;
/**
* A chain of nodes that can be treated as a single unit.
* Used during pattern compilation.
* @param <T> the type used to identify which pattern has been matched.
*/
public class PatternChain<T> {
/**
* The head node of the chain.
*/
public PatternNode<T> head;
/**
* The tail node of the chain.
*/
public PatternNode<T> tail;
/**
* Creates a new chain with the given start and end.
* @param head the start of the chain.
* @param tail the end of the chain.
*/
public PatternChain(PatternNode<T> head, PatternNode<T> tail){
this.head = head;
this.tail = tail;
}
/**
* Creates a chain that starts and ends with the same node.
* @param node the node to use.
*/
public PatternChain(PatternNode<T> node){
this(node, node);
}
/**
* Creates an empty chain.
*/
public PatternChain(){
this(null);
}
/**
* Appends the other chain to this one. This modifies
* the nodes, as well.
* If this chain is empty, it is set to the other.
* @param other the other chain to append.
*/
public void append(PatternChain<T> other){
if(other.head == null || tail == null) {
this.head = other.head;
this.tail = other.tail;
} else {
tail.outputStates.add(other.head);
tail = other.tail;
}
}
/**
* Appends a single node to this chain. This modifies
* the nodes, as well.
* If this chain is empty, it is set to the node.
* @param node the node to append to this chain.
*/
public void append(PatternNode<T> node){
if(tail == null){
head = tail = node;
} else {
tail.outputStates.add(node);
tail = node;
}
}
}

View File

@@ -0,0 +1,64 @@
package org.nwapw.abacus.lexing.pattern;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
/**
* A base class for a pattern node. Provides all functions
* necessary for matching, and is constructed by a Pattern instance
* from a string.
* @param <T> the type that's used to tell which pattern this node belongs to.
*/
public class PatternNode<T> {
/**
* The set of states to which the lexer should continue
* should this node be correctly matched.
*/
protected Set<PatternNode<T>> outputStates;
/**
* Creates a new pattern node.
*/
public PatternNode(){
outputStates = new HashSet<>();
}
/**
* Determines whether the current input character can
* be matched by this node.
* @param other the character being matched.
* @return true if the character can be matched, false otherwise.
*/
public boolean matches(char other){
return false;
}
/**
* If this node can be used as part of a range, returns that value.
* @return a NULL terminator if this character cannot be converted
* into a range bound, or the appropriate range bound if it can.
*/
public char range(){
return '\0';
}
/**
* Adds this node in a collection of other nodes.
* @param into the collection to add into.
*/
public void addInto(Collection<PatternNode<T>> into){
into.add(this);
}
/**
* Adds the node's children into a collection of other nodes.
* @param into the collection to add into.
*/
public void addOutputsInto(Collection<PatternNode<T>> into){
outputStates.forEach(e -> e.addInto(into));
}
}

View File

@@ -0,0 +1,33 @@
package org.nwapw.abacus.lexing.pattern;
/**
* A node that matches a range of characters.
* @param <T> the type that's used to tell which pattern this node belongs to.
*/
public class RangeNode<T> extends PatternNode<T> {
/**
* The bottom bound of the range, inclusive.
*/
private char from;
/**
* The top bound of the range, inclusive.
*/
private char to;
/**
* Creates a new range node from the given range.
* @param from the bottom bound of the range.
* @param to the top bound of hte range.
*/
public RangeNode(char from, char to){
this.from = from;
this.to = to;
}
@Override
public boolean matches(char other) {
return other >= from && other <= to;
}
}

View File

@@ -0,0 +1,31 @@
package org.nwapw.abacus.lexing.pattern;
/**
* A node that matches a single value.
* @param <T> the type that's used to tell which pattern this node belongs to.
*/
public class ValueNode<T> extends PatternNode<T> {
/**
* The value this node matches.
*/
private char value;
/**
* Creates a new node that matches the given character.
* @param value
*/
public ValueNode(char value){
this.value = value;
}
@Override
public boolean matches(char other) {
return other == value;
}
@Override
public char range() {
return value;
}
}

View File

@@ -0,0 +1,110 @@
package org.nwapw.abacus.number;
/**
* An implementation of NumberInterface using a double.
*/
public class NaiveNumber implements NumberInterface {
/**
* The value of this number.
*/
private double value;
/**
* Creates a new NaiveNumber with the given string.
* @param value the value, which will be parsed as a double.
*/
public NaiveNumber(String value) {
this(Double.parseDouble(value));
}
/**
* Creates a new NaiveNumber with the given value.
* @param value the value to use.
*/
public NaiveNumber(double value) {
this.value = value;
}
/**
* The number zero.
*/
public static final NaiveNumber ZERO = new NaiveNumber(0);
/**
* The number one.
*/
public static final NaiveNumber ONE = new NaiveNumber(1);
@Override
public int getMaxPrecision() {
return 18;
}
@Override
public NumberInterface multiply(NumberInterface multiplier) {
return new NaiveNumber(value * ((NaiveNumber)multiplier).value);
}
@Override
public NumberInterface divide(NumberInterface divisor) {
return new NaiveNumber(value / ((NaiveNumber)divisor).value);
}
@Override
public NumberInterface add(NumberInterface summand) {
return new NaiveNumber(value + ((NaiveNumber)summand).value);
}
@Override
public NumberInterface subtract(NumberInterface subtrahend) {
return new NaiveNumber(value - ((NaiveNumber)subtrahend).value);
}
@Override
public NumberInterface negate() {
return new NaiveNumber(-value);
}
@Override
public NumberInterface intPow(int exponent) {
if(exponent == 0){
return NaiveNumber.ONE;
}
boolean takeReciprocal = exponent < 0;
exponent = Math.abs(exponent);
NumberInterface power = this;
for(int currentExponent = 1; currentExponent < exponent; currentExponent++){
power = power.multiply(this);
}
if(takeReciprocal){
power = NaiveNumber.ONE.divide(power);
}
return power;
}
@Override
public int compareTo(NumberInterface number) {
NaiveNumber num = (NaiveNumber) number;
return Double.compare(value, num.value);
}
@Override
public int signum() {
return this.compareTo(ZERO);
}
@Override
public NumberInterface promoteTo(Class<? extends NumberInterface> toClass) {
if(toClass == this.getClass()) return this;
else if(toClass == PreciseNumber.class){
return new PreciseNumber(Double.toString(value));
}
return null;
}
public String toString(){
double shiftBy = Math.pow(10, 10);
return Double.toString(Math.round(value * shiftBy) / shiftBy);
}
}

View File

@@ -0,0 +1,77 @@
package org.nwapw.abacus.number;
/**
* An interface used to represent a number.
*/
public interface NumberInterface {
/**
* The maximum precision to which this number operates.
* @return the precision.
*/
int getMaxPrecision();
/**
* Multiplies this number by another, returning
* a new number instance.
* @param multiplier the multiplier
* @return the result of the multiplication.
*/
NumberInterface multiply(NumberInterface multiplier);
/**
* Divides this number by another, returning
* a new number instance.
* @param divisor the divisor
* @return the result of the division.
*/
NumberInterface divide(NumberInterface divisor);
/**
* Adds this number to another, returning
* a new number instance.
* @param summand the summand
* @return the result of the summation.
*/
NumberInterface add(NumberInterface summand);
/**
* Subtracts another number from this number,
* a new number instance.
* @param subtrahend the subtrahend.
* @return the result of the subtraction.
*/
NumberInterface subtract(NumberInterface subtrahend);
/**
* Returns a new instance of this number with
* the sign flipped.
* @return the new instance.
*/
NumberInterface negate();
/**
* Raises this number to an integer power.
* @param exponent the exponent to which to take the number.
* @return the resulting value.
*/
NumberInterface intPow(int exponent);
/**
* Compares this number to another.
* @param number the number to compare to.
* @return same as Integer.compare();
*/
int compareTo(NumberInterface number);
/**
* Same as Math.signum().
* @return 1 if this number is positive, -1 if this number is negative, 0 if this number is 0.
*/
int signum();
/**
* Promotes this class to another number class.
* @param toClass the class to promote to.
* @return the resulting new instance.
*/
NumberInterface promoteTo(Class<? extends NumberInterface> toClass);
}

View File

@@ -0,0 +1,113 @@
package org.nwapw.abacus.number;
import java.math.BigDecimal;
import java.math.RoundingMode;
public class PreciseNumber implements NumberInterface{
/**
* The number one.
*/
static final PreciseNumber ONE = new PreciseNumber(BigDecimal.ONE);
/**
* The number zero.
*/
static final PreciseNumber ZERO = new PreciseNumber(BigDecimal.ZERO);
/**
* The number ten.
*/
static final PreciseNumber TEN = new PreciseNumber(BigDecimal.TEN);
/**
* The value of the PreciseNumber.
*/
BigDecimal value;
/**
* Constructs a precise number from the given string.
* @param string a string representation of the number meeting the same conditions
* as the BidDecimal(String) constructor.
*/
public PreciseNumber(String string){
value = new BigDecimal(string);
}
/**
* Constructs a precise number from the given BigDecimal.
* @param value a BigDecimal object representing the value of the number.
*/
public PreciseNumber(BigDecimal value){
this.value = value;
}
@Override
public int getMaxPrecision() {
return 54;
}
@Override
public NumberInterface multiply(NumberInterface multiplier) {
return new PreciseNumber(value.multiply(((PreciseNumber) multiplier).value));
}
@Override
public NumberInterface divide(NumberInterface divisor) {
return new PreciseNumber(value.divide(((PreciseNumber) divisor).value, this.getMaxPrecision(), RoundingMode.HALF_UP));
}
@Override
public NumberInterface add(NumberInterface summand) {
return new PreciseNumber(value.add(((PreciseNumber) summand).value));
}
@Override
public NumberInterface subtract(NumberInterface subtrahend) {
return new PreciseNumber(value.subtract(((PreciseNumber) subtrahend).value));
}
@Override
public NumberInterface intPow(int exponent) {
if(exponent == 0){
return PreciseNumber.ONE;
}
boolean takeReciprocal = exponent < 0;
exponent = Math.abs(exponent);
NumberInterface power = this;
for(int currentExponent = 1; currentExponent < exponent; currentExponent++){
power = power.multiply(this);
}
if(takeReciprocal){
power = PreciseNumber.ONE.divide(power);
}
return power;
}
@Override
public int compareTo(NumberInterface number) {
return value.compareTo(((PreciseNumber) number).value);
}
@Override
public int signum() {
return value.signum();
}
@Override
public NumberInterface negate(){
return new PreciseNumber(value.negate());
}
@Override
public NumberInterface promoteTo(Class<? extends NumberInterface> toClass) {
if(toClass == this.getClass()){
return this;
}
return null;
}
@Override
public String toString() {
BigDecimal rounded = value.setScale(getMaxPrecision() - 4, RoundingMode.HALF_UP);
return rounded.stripTrailingZeros().toPlainString();
}
}

View File

@@ -0,0 +1,67 @@
package org.nwapw.abacus.parsing;
import org.nwapw.abacus.lexing.Lexer;
import org.nwapw.abacus.lexing.pattern.Match;
import org.nwapw.abacus.lexing.pattern.Pattern;
import org.nwapw.abacus.plugin.PluginListener;
import org.nwapw.abacus.plugin.PluginManager;
import org.nwapw.abacus.tree.TokenType;
import java.util.Comparator;
import java.util.List;
/**
* A tokenzier that uses the lexer class and registered function and operator
* names to turn input into tokens in O(n) time.
*/
public class LexerTokenizer implements Tokenizer<Match<TokenType>>, PluginListener {
/**
* Comparator used to sort the tokens produced by the lexer.
*/
protected static final Comparator<TokenType> TOKEN_SORTER = Comparator.comparingInt(e -> e.priority);
/**
* The lexer instance used to turn strings into matches.
*/
private Lexer<TokenType> lexer;
/**
* Creates a new lexer tokenizer.
*/
public LexerTokenizer(){
lexer = new Lexer<TokenType>() {{
register(" ", TokenType.WHITESPACE);
register(",", TokenType.COMMA);
register("[0-9]*(\\.[0-9]+)?", TokenType.NUM);
register("\\(", TokenType.OPEN_PARENTH);
register("\\)", TokenType.CLOSE_PARENTH);
}};
}
@Override
public List<Match<TokenType>> tokenizeString(String string) {
return lexer.lexAll(string, 0, TOKEN_SORTER);
}
@Override
public void onLoad(PluginManager manager) {
for(String operator : manager.getAllOperators()){
lexer.register(Pattern.sanitize(operator), TokenType.OP);
}
for(String function : manager.getAllFunctions()){
lexer.register(Pattern.sanitize(function), TokenType.FUNCTION);
}
}
@Override
public void onUnload(PluginManager manager) {
for(String operator : manager.getAllOperators()){
lexer.unregister(Pattern.sanitize(operator), TokenType.OP);
}
for(String function : manager.getAllFunctions()){
lexer.unregister(Pattern.sanitize(function), TokenType.FUNCTION);
}
}
}

View File

@@ -0,0 +1,20 @@
package org.nwapw.abacus.parsing;
import org.nwapw.abacus.tree.TreeNode;
import java.util.List;
/**
* An itnerface that provides the ability to convert a list of tokens
* into a parse tree.
* @param <T> the type of tokens accepted by this parser.
*/
public interface Parser<T> {
/**
* Constructs a tree out of the given tokens.
* @param tokens the tokens to construct a tree from.
* @return the constructed tree, or null on error.
*/
public TreeNode constructTree(List<T> tokens);
}

View File

@@ -0,0 +1,173 @@
package org.nwapw.abacus.parsing;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.function.Operator;
import org.nwapw.abacus.function.OperatorAssociativity;
import org.nwapw.abacus.function.OperatorType;
import org.nwapw.abacus.lexing.pattern.Match;
import org.nwapw.abacus.plugin.PluginListener;
import org.nwapw.abacus.plugin.PluginManager;
import org.nwapw.abacus.tree.*;
import java.util.*;
/**
* A parser that uses shunting yard to rearranged matches into postfix
* and then convert them into a parse tree.
*/
public class ShuntingYardParser implements Parser<Match<TokenType>>, PluginListener {
/**
* The Abacus instance used to create number instances.
*/
private Abacus abacus;
/**
* Map of operator precedences, loaded from the plugin operators.
*/
private Map<String, Integer> precedenceMap;
/**
* Map of operator associativity, loaded from the plugin operators.
*/
private Map<String, OperatorAssociativity> associativityMap;
/**
* Map of operator types, loaded from plugin operators.
*/
private Map<String, OperatorType> typeMap;
/**
* Creates a new Shunting Yard parser with the given Abacus instance.
* @param abacus the abacus instance.
*/
public ShuntingYardParser(Abacus abacus){
this.abacus = abacus;
precedenceMap = new HashMap<>();
associativityMap = new HashMap<>();
typeMap = new HashMap<>();
}
/**
* Rearranges tokens into a postfix list, using Shunting Yard.
* @param from the tokens to be rearranged.
* @return the resulting list of rearranged tokens.
*/
public List<Match<TokenType>> intoPostfix(List<Match<TokenType>> from){
ArrayList<Match<TokenType>> output = new ArrayList<>();
Stack<Match<TokenType>> tokenStack = new Stack<>();
while(!from.isEmpty()){
Match<TokenType> match = from.remove(0);
TokenType matchType = match.getType();
if(matchType == TokenType.NUM) {
output.add(match);
} else if(matchType == TokenType.FUNCTION) {
output.add(new Match<>("" , TokenType.INTERNAL_FUNCTION_END));
tokenStack.push(match);
} else if(matchType == TokenType.OP){
String tokenString = match.getContent();
OperatorType type = typeMap.get(tokenString);
int precedence = precedenceMap.get(tokenString);
OperatorAssociativity associativity = associativityMap.get(tokenString);
if(type == OperatorType.UNARY_POSTFIX){
output.add(match);
continue;
}
while(!tokenStack.empty()) {
Match<TokenType> otherMatch = tokenStack.peek();
TokenType otherMatchType = otherMatch.getType();
if(!(otherMatchType == TokenType.OP || otherMatchType == TokenType.FUNCTION)) break;
if(otherMatchType == TokenType.OP){
int otherPrecedence = precedenceMap.get(match.getContent());
if(otherPrecedence < precedence ||
(associativity == OperatorAssociativity.RIGHT && otherPrecedence == precedence)) {
break;
}
}
output.add(tokenStack.pop());
}
tokenStack.push(match);
} else if(matchType == TokenType.OPEN_PARENTH){
tokenStack.push(match);
} else if(matchType == TokenType.CLOSE_PARENTH || matchType == TokenType.COMMA){
while(!tokenStack.empty() && tokenStack.peek().getType() != TokenType.OPEN_PARENTH){
output.add(tokenStack.pop());
}
if(tokenStack.empty()) return null;
if(matchType == TokenType.CLOSE_PARENTH){
tokenStack.pop();
}
}
}
while(!tokenStack.empty()){
Match<TokenType> match = tokenStack.peek();
TokenType matchType = match.getType();
if(!(matchType == TokenType.OP || matchType == TokenType.FUNCTION)) return null;
output.add(tokenStack.pop());
}
return output;
}
/**
* Constructs a tree recursively from a list of tokens.
* @param matches the list of tokens from the source string.
* @return the construct tree expression.
*/
public TreeNode constructRecursive(List<Match<TokenType>> matches){
if(matches.size() == 0) return null;
Match<TokenType> match = matches.remove(0);
TokenType matchType = match.getType();
if(matchType == TokenType.OP){
String operator = match.getContent();
OperatorType type = typeMap.get(operator);
if(type == OperatorType.BINARY_INFIX){
TreeNode right = constructRecursive(matches);
TreeNode left = constructRecursive(matches);
if(left == null || right == null) return null;
else return new BinaryInfixNode(operator, left, right);
} else {
TreeNode applyTo = constructRecursive(matches);
if(applyTo == null) return null;
else return new UnaryPrefixNode(operator, applyTo);
}
} else if(matchType == TokenType.NUM){
return new NumberNode(abacus.numberFromString(match.getContent()));
} else if(matchType == TokenType.FUNCTION){
String functionName = match.getContent();
FunctionNode node = new FunctionNode(functionName);
while(!matches.isEmpty() && matches.get(0).getType() != TokenType.INTERNAL_FUNCTION_END){
TreeNode argument = constructRecursive(matches);
if(argument == null) return null;
node.prependChild(argument);
}
if(matches.isEmpty()) return null;
matches.remove(0);
return node;
}
return null;
}
@Override
public TreeNode constructTree(List<Match<TokenType>> tokens) {
tokens = intoPostfix(new ArrayList<>(tokens));
Collections.reverse(tokens);
return constructRecursive(tokens);
}
@Override
public void onLoad(PluginManager manager) {
for(String operator : manager.getAllOperators()){
Operator operatorInstance = manager.operatorFor(operator);
precedenceMap.put(operator, operatorInstance.getPrecedence());
associativityMap.put(operator, operatorInstance.getAssociativity());
typeMap.put(operator, operatorInstance.getType());
}
}
@Override
public void onUnload(PluginManager manager) {
precedenceMap.clear();
associativityMap.clear();
typeMap.clear();
}
}

View File

@@ -0,0 +1,18 @@
package org.nwapw.abacus.parsing;
import java.util.List;
/**
* Interface that provides the ability to convert a string into a list of tokens.
* @param <T> the type of the tokens produced.
*/
public interface Tokenizer<T> {
/**
* Converts a string into tokens.
* @param string the string to convert.
* @return the list of tokens, or null on error.
*/
public List<T> tokenizeString(String string);
}

View File

@@ -0,0 +1,23 @@
package org.nwapw.abacus.parsing;
import org.nwapw.abacus.tree.TreeNode;
import java.util.List;
public class TreeBuilder<T> {
private Tokenizer<T> tokenizer;
private Parser<T> parser;
public TreeBuilder(Tokenizer<T> tokenizer, Parser<T> parser){
this.tokenizer = tokenizer;
this.parser = parser;
}
public TreeNode fromString(String input){
List<T> tokens = tokenizer.tokenizeString(input);
if(tokens == null) return null;
return parser.constructTree(tokens);
}
}

View File

@@ -0,0 +1,77 @@
package org.nwapw.abacus.plugin;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.stream.Collectors;
/**
* Class that loads plugin classes from their jars.
*/
public class ClassFinder {
/**
* Loads all the plugin classes from the given plugin folder.
* @param filePath the path for the plugin folder.
* @return the list of all loaded classes.
* @throws IOException thrown if an error occurred scanning the plugin folder.
* @throws ClassNotFoundException thrown if the class listed in the file doesn't get loaded.
*/
public static List<Class<?>> loadJars(String filePath) throws IOException, ClassNotFoundException {
return loadJars(new File(filePath));
}
/**
* Loads all the plugin classes from the given plugin folder.
* @param pluginFolderPath the folder in which to look for plugins.
* @return the list of all loaded classes.
* @throws IOException thrown if an error occurred scanning the plugin folder.
* @throws ClassNotFoundException thrown if the class listed in the file doesn't get loaded.
*/
public static List<Class<?>> loadJars(File pluginFolderPath) throws IOException, ClassNotFoundException {
ArrayList<Class<?>> toReturn = new ArrayList<>();
if(!pluginFolderPath.exists()) return toReturn;
ArrayList<File> files = Files.walk(pluginFolderPath.toPath())
.map(Path::toFile)
.filter(f -> f.getName().endsWith(".jar"))
.collect(Collectors.toCollection(ArrayList::new));
for (File file : files){
toReturn.addAll(loadJar(file));
}
return toReturn;
}
/**
* Loads the classes from a single path, given by the file.
* @param jarLocation the location of the jar to load.
* @return the list of loaded classes loaded from the jar.
* @throws IOException thrown if there was an error reading the file
* @throws ClassNotFoundException thrown if the class could not be loaded.
*/
public static List<Class<?>> loadJar(File jarLocation) throws IOException, ClassNotFoundException {
ArrayList<Class<?>> loadedClasses = new ArrayList<>();
String path = jarLocation.getPath();
URL[] urls = new URL[]{new URL("jar:file:" + path + "!/")};
URLClassLoader classLoader = URLClassLoader.newInstance(urls);
JarFile jarFolder = new JarFile(jarLocation);
Enumeration jarEntityList = jarFolder.entries();
while (jarEntityList.hasMoreElements()) {
JarEntry jarEntity = (JarEntry) jarEntityList.nextElement();
if (jarEntity.getName().endsWith(".class")) {
loadedClasses.add(classLoader.loadClass(jarEntity.getName().replace('/', '.').substring(0, jarEntity.getName().length() - 6)));
}
}
return loadedClasses;
}
}

View File

@@ -0,0 +1,197 @@
package org.nwapw.abacus.plugin;
import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.function.Operator;
import org.nwapw.abacus.number.NumberInterface;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
/**
* A plugin class that can be externally implemented and loaded via the
* plugin manager. Plugins provide functionality to the calculator
* with the "hasFunction" and "getFunction" functions,
* and can use "registerFunction" and "functionFor" for
* loading internally.
*/
public abstract class Plugin {
/**
* A hash map of functions mapped to their string names.
*/
private Map<String, Function> functions;
/**
* A hash map of operators mapped to their string names.
*/
private Map<String, Operator> operators;
/**
* A hash map of operators mapped to their string names.
*/
private Map<String, Class<? extends NumberInterface>> numbers;
/**
* The plugin manager in which to search for functions
* not inside this package,
*/
private PluginManager manager;
/**
* Whether this plugin has been loaded.
*/
private boolean enabled;
private Plugin(){ }
/**
* Creates a new plugin with the given PluginManager.
* @param manager the manager controlling this plugin.
*/
public Plugin(PluginManager manager) {
this.manager = manager;
functions = new HashMap<>();
operators = new HashMap<>();
numbers = new HashMap<>();
enabled = false;
}
/**
* Gets the list of functions provided by this plugin.
* @return the list of registered functions.
*/
public final Set<String> providedFunctions(){
return functions.keySet();
}
/**
* Gets the list of functions provided by this plugin.
* @return the list of registered functions.
*/
public final Set<String> providedOperators(){
return operators.keySet();
}
/**
* Gets the list of all numbers provided by this plugin.
* @return the list of registered numbers.
*/
public final Set<String> providedNumbers(){
return numbers.keySet();
}
/**
* Gets a function under the given function name.
* @param functionName the name of the function to get
* @return the function, or null if this plugin doesn't provide it.
*/
public final Function getFunction(String functionName) {
return functions.get(functionName);
}
/**
* Gets an operator under the given operator name.
* @param operatorName the name of the operator to get.
* @return the operator, or null if this plugin doesn't provide it.
*/
public final Operator getOperator(String operatorName) {
return operators.get(operatorName);
}
/**
* Gets the class under the given name.
* @param numberName the name of the class.
* @return the class, or null if the plugin doesn't provide it.
*/
public final Class<? extends NumberInterface> getNumber(String numberName){
return numbers.get(numberName);
}
/**
* Enables the function, loading the necessary instances
* of functions.
*/
public final void enable(){
if(enabled) return;
onEnable();
enabled = true;
}
/**
* Disables the plugin, clearing loaded data store by default
* and calling its disable() method.
*/
public final void disable(){
if(!enabled) return;
onDisable();
functions.clear();
operators.clear();
enabled = false;
}
/**
* To be used in load(). Registers a function abstract class with the
* plugin internally, which makes it accessible to the plugin manager.
* @param name the name to register by.
* @param toRegister the function implementation.
*/
protected final void registerFunction(String name, Function toRegister) {
functions.put(name, toRegister);
}
/**
* To be used in load(). Registers an operator abstract class
* with the plugin internally, which makes it accessible to
* the plugin manager.
* @param name the name of the operator.
* @param operator the operator to register.
*/
protected final void registerOperator(String name, Operator operator) {
operators.put(name, operator);
}
/**
* To be used in load(). Registers a number class
* with the plugin internally, which makes it possible
* for the user to select it as an "implementation" for the
* number that they would like to use.
* @param name the name to register it under.
* @param toRegister the class to register.
*/
protected final void registerNumber(String name, Class<? extends NumberInterface> toRegister){
numbers.put(name, toRegister);
}
/**
* Searches the PluginManager for the given function name.
* This can be used by the plugins internally in order to call functions
* they do not provide.
* @param name the name for which to search
* @return the resulting function, or null if none was found for that name.
*/
protected final Function functionFor(String name) {
return manager.functionFor(name);
}
/**
* Searches the PluginManager for the given operator name.
* This can be used by the plugins internally in order to call
* operations they do not provide.
* @param name the name for which to search
* @return the resulting operator, or null if none was found for that name.
*/
protected final Operator operatorFor(String name) {
return manager.operatorFor(name);
}
/**
* Abstract method to be overridden by plugin implementation, in which the plugins
* are supposed to register the functions they provide and do any other
* necessary setup.
*/
public abstract void onEnable();
/**
* Abstract method overridden by the plugin implementation, in which the plugins
* are supposed to dispose of loaded functions, operators, and macros.
*/
public abstract void onDisable();
}

View File

@@ -0,0 +1,20 @@
package org.nwapw.abacus.plugin;
/**
* A listener that responds to changes in the PluginManager.
*/
public interface PluginListener {
/**
* Called when the PluginManager loads plugins.
* @param manager the manager that fired the event.
*/
public void onLoad(PluginManager manager);
/**
* Called when the PluginManager unloads all its plugins.
* @param manager the manager that fired the event.
*/
public void onUnload(PluginManager manager);
}

View File

@@ -0,0 +1,231 @@
package org.nwapw.abacus.plugin;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.function.Operator;
import org.nwapw.abacus.number.NumberInterface;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
/**
* A class that controls instances of plugins, allowing for them
* to interact with each other and the calculator.
*/
public class PluginManager {
/**
* List of classes loaded by this manager.
*/
private Set<Class<?>> loadedPluginClasses;
/**
* A list of loaded plugins.
*/
private Set<Plugin> plugins;
/**
* List of functions that have been cached,
* that is, found in a plugin and returned.
*/
private Map<String, Function> cachedFunctions;
/**
* List of operators that have been cached,
* that is, found in a plugin and returned.
*/
private Map<String, Operator> cachedOperators;
/**
* List of registered number implementations that have
* been cached, that is, found in a plugin and returned.
*/
private Map<String, Class<? extends NumberInterface>> cachedNumbers;
/**
* List of all functions loaded by the plugins.
*/
private Set<String> allFunctions;
/**
* List of all operators loaded by the plugins.
*/
private Set<String> allOperators;
/**
* List of all numbers loaded by the plugins.
*/
private Set<String> allNumbers;
/**
* The list of plugin listeners attached to this instance.
*/
private Set<PluginListener> listeners;
/**
* The instance of Abacus that is used to interact with its other
* components.
*/
private Abacus abacus;
/**
* Creates a new plugin manager.
*/
public PluginManager(Abacus abacus){
this.abacus = abacus;
loadedPluginClasses = new HashSet<>();
plugins = new HashSet<>();
cachedFunctions = new HashMap<>();
cachedOperators = new HashMap<>();
cachedNumbers = new HashMap<>();
allFunctions = new HashSet<>();
allOperators = new HashSet<>();
allNumbers = new HashSet<>();
listeners = new HashSet<>();
}
/**
* Searches the plugin list for a certain value, retrieving the Plugin's
* list of items of the type using the setFunction and getting the value
* of it is available via getFunction. If the value is contained
* in the cache, it returns the cached value instead.
* @param plugins the plugin list to search.
* @param cache the cache to use
* @param setFunction the function to retrieve a set of available T's from the plugin
* @param getFunction the function to get the T value under the given name
* @param name the name to search for
* @param <T> the type of element being search
* @return the retrieved element, or null if it was not found.
*/
private static <T> T searchCached(Collection<Plugin> plugins, Map<String, T> cache,
java.util.function.Function<Plugin, Set<String>> setFunction,
java.util.function.BiFunction<Plugin, String, T> getFunction,
String name){
if(cache.containsKey(name)) return cache.get(name);
T loadedValue = null;
for(Plugin plugin : plugins){
if(setFunction.apply(plugin).contains(name)){
loadedValue = getFunction.apply(plugin, name);
break;
}
}
cache.put(name, loadedValue);
return loadedValue;
}
/**
* Gets a function under the given name.
* @param name the name of the function
* @return the function under the given name.
*/
public Function functionFor(String name){
return searchCached(plugins, cachedFunctions, Plugin::providedFunctions, Plugin::getFunction, name);
}
/**
* Gets an operator under the given name.
* @param name the name of the operator.
* @return the operator under the given name.
*/
public Operator operatorFor(String name){
return searchCached(plugins, cachedOperators, Plugin::providedOperators, Plugin::getOperator, name);
}
/**
* Gets a numer implementation under the given name.
* @param name the name of the implementation.
* @return the implementation class
*/
public Class<? extends NumberInterface> numberFor(String name){
return searchCached(plugins, cachedNumbers, Plugin::providedNumbers, Plugin::getNumber, name);
}
/**
* Adds an instance of Plugin that already has been instantiated.
* @param plugin the plugin to add.
*/
public void addInstantiated(Plugin plugin){
if(loadedPluginClasses.contains(plugin.getClass())) return;
plugins.add(plugin);
loadedPluginClasses.add(plugin.getClass());
}
/**
* Instantiates a class of plugin, and adds it to this
* plugin manager.
* @param newClass the new class to instantiate.
*/
public void addClass(Class<?> newClass){
if(!Plugin.class.isAssignableFrom(newClass) || newClass == Plugin.class) return;
try {
addInstantiated((Plugin) newClass.getConstructor(PluginManager.class).newInstance(this));
} catch (InstantiationException | IllegalAccessException | NoSuchMethodException | InvocationTargetException e) {
e.printStackTrace();
}
}
/**
* Loads all the plugins in the PluginManager.
*/
public void load(){
for(Plugin plugin : plugins) plugin.enable();
for(Plugin plugin : plugins){
allFunctions.addAll(plugin.providedFunctions());
allOperators.addAll(plugin.providedOperators());
allNumbers.addAll(plugin.providedNumbers());
}
listeners.forEach(e -> e.onLoad(this));
}
/**
* Unloads all the plugins in the PluginManager.
*/
public void unload(){
for(Plugin plugin : plugins) plugin.disable();
allFunctions.clear();
allOperators.clear();
allNumbers.clear();
listeners.forEach(e -> e.onUnload(this));
}
/**
* Reloads all the plugins in the PluginManager.
*/
public void reload(){
unload();
reload();
}
/**
* Gets all the functions loaded by the Plugin Manager.
* @return the set of all functions that were loaded.
*/
public Set<String> getAllFunctions() {
return allFunctions;
}
/**
* Gets all the operators loaded by the Plugin Manager.
* @return the set of all operators that were loaded.
*/
public Set<String> getAllOperators() {
return allOperators;
}
/**
* Gets all the number implementations loaded by the Plugin Manager
* @return the set of all implementations that were loaded
*/
public Set<String> getAllNumbers() {
return allNumbers;
}
/**
* Adds a plugin change listener to this plugin manager.
* @param listener the listener to add.
*/
public void addListener(PluginListener listener){
listeners.add(listener);
}
/**
* Remove the plugin change listener from this plugin manager.
* @param listener the listener to remove.
*/
public void removeListener(PluginListener listener){
listeners.remove(listener);
}
}

View File

@@ -0,0 +1,302 @@
package org.nwapw.abacus.plugin;
import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.function.Operator;
import org.nwapw.abacus.function.OperatorAssociativity;
import org.nwapw.abacus.function.OperatorType;
import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.number.PreciseNumber;
import java.util.function.BiFunction;
/**
* The plugin providing standard functions such as addition and subtraction to
* the calculator.
*/
public class StandardPlugin extends Plugin {
public StandardPlugin(PluginManager manager) {
super(manager);
}
@Override
public void onEnable() {
registerNumber("naive", NaiveNumber.class);
registerNumber("precise", PreciseNumber.class);
registerOperator("+", new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, 0, new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length >= 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface sum = params[0];
for(int i = 1; i < params.length; i++){
sum = sum.add(params[i]);
}
return sum;
}
}));
registerOperator("-", new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX, 0, new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return params[0].subtract(params[1]);
}
}));
registerOperator("*", new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX,1, new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length >= 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface product = params[0];
for(int i = 1; i < params.length; i++){
product = product.multiply(params[i]);
}
return product;
}
}));
registerOperator("/", new Operator(OperatorAssociativity.LEFT, OperatorType.BINARY_INFIX,1, new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return params[0].divide(params[1]);
}
}));
registerOperator("^", new Operator(OperatorAssociativity.RIGHT, OperatorType.BINARY_INFIX, 2, new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 2;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return StandardPlugin.this.getFunction("exp").apply(StandardPlugin.this.getFunction("ln").apply(params[0]).multiply(params[1]));
}
}));
registerOperator("!", new Operator(OperatorAssociativity.RIGHT, OperatorType.UNARY_POSTFIX, 0, new Function() {
//private HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>> storedList = new HashMap<Class<? extends NumberInterface>, ArrayList<NumberInterface>>();
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
if(params[0].signum() == 0){
return (new NaiveNumber(1)).promoteTo(params[0].getClass());
}
NumberInterface factorial = params[0];
NumberInterface multiplier = params[0];
//It is necessary to later prevent calls of factorial on anything but non-negative integers.
while((multiplier = multiplier.subtract(NaiveNumber.ONE.promoteTo(multiplier.getClass()))).signum() == 1){
factorial = factorial.multiply(multiplier);
}
return factorial;
/*if(!storedList.containsKey(params[0].getClass())){
storedList.put(params[0].getClass(), new ArrayList<NumberInterface>());
storedList.get(params[0].getClass()).add(NaiveNumber.ONE.promoteTo(params[0].getClass()));
storedList.get(params[0].getClass()).add(NaiveNumber.ONE.promoteTo(params[0].getClass()));
}*/
}
}));
registerFunction("abs", new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return params[0].multiply((new NaiveNumber(params[0].signum())).promoteTo(params[0].getClass()));
}
});
registerFunction("exp", new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
boolean takeReciprocal = params[0].signum() == -1;
params[0] = StandardPlugin.this.getFunction("abs").apply(params[0]);
NumberInterface sum = sumSeries(params[0], StandardPlugin.this::getExpSeriesTerm, getNTermsExp(getMaxError(params[0]), params[0]));
if(takeReciprocal){
sum = NaiveNumber.ONE.promoteTo(sum.getClass()).divide(sum);
}
return sum;
}
});
registerFunction("ln", new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
NumberInterface param = params[0];
int powersOf2 = 0;
while(StandardPlugin.this.getFunction("abs").apply(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass()))).compareTo((new NaiveNumber(0.1)).promoteTo(param.getClass())) >= 0){
if(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() == 1) {
param = param.divide(new NaiveNumber(2).promoteTo(param.getClass()));
powersOf2++;
if(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != 1) {
break;
//No infinite loop for you.
}
}
else {
param = param.multiply(new NaiveNumber(2).promoteTo(param.getClass()));
powersOf2--;
if(param.subtract(NaiveNumber.ONE.promoteTo(param.getClass())).signum() != 1) {
break;
//No infinite loop for you.
}
}
}
return getLog2(param).multiply((new NaiveNumber(powersOf2)).promoteTo(param.getClass())).add(getLogPartialSum(param));
}
/**
* Returns the partial sum of the Taylor series for logx (around x=1).
* Automatically determines the number of terms needed based on the precision of x.
* @param x value at which the series is evaluated. 0 < x < 2. (x=2 is convergent but impractical.)
* @return the partial sum.
*/
private NumberInterface getLogPartialSum(NumberInterface x){
NumberInterface maxError = StandardPlugin.this.getMaxError(x);
x = x.subtract(NaiveNumber.ONE.promoteTo(x.getClass())); //Terms used are for log(x+1).
NumberInterface currentTerm = x, sum = x;
int n = 1;
while(StandardPlugin.this.getFunction("abs").apply(currentTerm).compareTo(maxError) > 0){
n++;
currentTerm = currentTerm.multiply(x).multiply((new NaiveNumber(n-1)).promoteTo(x.getClass())).divide((new NaiveNumber(n)).promoteTo(x.getClass())).negate();
sum = sum.add(currentTerm);
}
return sum;
}
/**
* Returns natural log of 2 to the required precision of the class of number.
* @param number a number of the same type as the return type. (Used for precision.)
* @return the value of log(2) with the appropriate precision.
*/
private NumberInterface getLog2(NumberInterface number){
NumberInterface maxError = StandardPlugin.this.getMaxError(number);
//NumberInterface errorBound = (new NaiveNumber(1)).promoteTo(number.getClass());
//We'll use the series \sigma_{n >= 1) ((1/3^n + 1/4^n) * 1/n)
//In the following, a=1/3^n, b=1/4^n, c = 1/n.
//a is also an error bound.
NumberInterface a = (new NaiveNumber(1)).promoteTo(number.getClass()), b = a, c = a;
NumberInterface sum = NaiveNumber.ZERO.promoteTo(number.getClass());
int n = 0;
while(a.compareTo(maxError) >= 1){
n++;
a = a.divide((new NaiveNumber(3)).promoteTo(number.getClass()));
b = b.divide((new NaiveNumber(4)).promoteTo(number.getClass()));
c = NaiveNumber.ONE.promoteTo(number.getClass()).divide((new NaiveNumber(n)).promoteTo(number.getClass()));
sum = sum.add(a.add(b).multiply(c));
}
return sum;
}
});
registerFunction("sqrt", new Function() {
@Override
protected boolean matchesParams(NumberInterface[] params) {
return params.length == 1;
}
@Override
protected NumberInterface applyInternal(NumberInterface[] params) {
return StandardPlugin.this.getOperator("^").getFunction().apply(params[0], ((new NaiveNumber(0.5)).promoteTo(params[0].getClass())));
}
});
}
@Override
public void onDisable() {
}
/**
* Returns the nth term of the Taylor series (centered at 0) of e^x
* @param n the term required (n >= 0).
* @param x the real number at which the series is evaluated.
* @return the nth term of the series.
*/
private NumberInterface getExpSeriesTerm(int n, NumberInterface x){
return x.intPow(n).divide(this.getOperator("!").getFunction().apply((new NaiveNumber(n)).promoteTo(x.getClass())));
}
/**
* Returns the number of terms needed to evaluate the exponential function (at x)
* such that the error is at most maxError.
* @param maxError Maximum error permissible (This should probably be positive.)
* @param x where the function is evaluated.
* @return the number of terms needed to evaluated the exponential function.
*/
private int getNTermsExp(NumberInterface maxError, NumberInterface x) {
//We need n such that |x^(n+1)| <= (n+1)! * maxError
//The variables LHS and RHS refer to the above inequality.
int n = 0;
x = this.getFunction("abs").apply(x);
NumberInterface LHS = x, RHS = maxError;
while (LHS.compareTo(RHS) > 0) {
n++;
LHS = LHS.multiply(x);
RHS = RHS.multiply(new NaiveNumber(n + 1).promoteTo(RHS.getClass()));
}
return n;
}
/**
* Returns a partial sum of a series whose terms are given by the nthTermFunction, evaluated at x.
* @param x the value at which the series is evaluated.
* @param nthTermFunction the function that returns the nth term of the series, in the format term(x, n).
* @param n the number of terms in the partial sum.
* @return the value of the partial sum that has the same class as x.
*/
private NumberInterface sumSeries(NumberInterface x, BiFunction<Integer, NumberInterface, NumberInterface> nthTermFunction, int n){
NumberInterface sum = NaiveNumber.ZERO.promoteTo(x.getClass());
for(int i = 0; i <= n; i++){
sum = sum.add(nthTermFunction.apply(i, x));
}
return sum;
}
/**
* Returns the maximum error based on the precision of the class of number.
* @param number Any instance of the NumberInterface in question (should return an appropriate precision).
* @return the maximum error.
*/
private NumberInterface getMaxError(NumberInterface number){
return (new NaiveNumber(10)).promoteTo(number.getClass()).intPow(-number.getMaxPrecision());
}
}

View File

@@ -0,0 +1,100 @@
package org.nwapw.abacus.tree;
/**
* A tree node that represents an operation being applied to two operands.
*/
public class BinaryInfixNode extends TreeNode {
/**
* The operation being applied.
*/
private String operation;
/**
* The left node of the operation.
*/
private TreeNode left;
/**
* The right node of the operation.
*/
private TreeNode right;
private BinaryInfixNode() {}
/**
* Creates a new operation node with the given operation
* and no child nodes.
* @param operation the operation.
*/
public BinaryInfixNode(String operation){
this(operation, null, null);
}
/**
* Creates a new operation node with the given operation
* and child nodes.
* @param operation the operation.
* @param left the left node of the expression.
* @param right the right node of the expression.
*/
public BinaryInfixNode(String operation, TreeNode left, TreeNode right){
this.operation = operation;
this.left = left;
this.right = right;
}
/**
* Gets the operation in this node.
* @return the operation in this node.
*/
public String getOperation() {
return operation;
}
/**
* Gets the left sub-expression of this node.
* @return the left node.
*/
public TreeNode getLeft() {
return left;
}
/**
* Sets the left sub-expression of this node.
* @param left the sub-expression to apply.
*/
public void setLeft(TreeNode left) {
this.left = left;
}
/**
* Gets the right sub-expression of this node.
* @return the right node.
*/
public TreeNode getRight() {
return right;
}
/**
* Sets the right sub-expression of this node.
* @param right the sub-expression to apply.
*/
public void setRight(TreeNode right) {
this.right = right;
}
@Override
public <T> T reduce(Reducer<T> reducer) {
T leftReduce = left.reduce(reducer);
T rightReduce = right.reduce(reducer);
if(leftReduce == null || rightReduce == null) return null;
return reducer.reduceNode(this, leftReduce, rightReduce);
}
@Override
public String toString() {
String leftString = left != null ? left.toString() : "null";
String rightString = right != null ? right.toString() : "null";
return "(" + leftString + operation + rightString + ")";
}
}

View File

@@ -0,0 +1,80 @@
package org.nwapw.abacus.tree;
import java.util.ArrayList;
import java.util.List;
/**
* A node that represents a function call.
*/
public class FunctionNode extends TreeNode {
/**
* The name of the function being called
*/
private String function;
/**
* The list of arguments to the function.
*/
private List<TreeNode> children;
/**
* Creates a function node with no function.
*/
private FunctionNode() { }
/**
* Creates a new function node with the given function name.
* @param function the function name.
*/
public FunctionNode(String function){
this.function = function;
children = new ArrayList<>();
}
/**
* Gets the function name for this node.
* @return the function name.
*/
public String getFunction() {
return function;
}
/**
* Adds a child to the end of this node's child list.
* @param node the child to add.
*/
public void appendChild(TreeNode node){
children.add(node);
}
/**
* Adds a new child to the beginning of this node's child list.
* @param node the node to add.
*/
public void prependChild(TreeNode node) {
children.add(0, node);
}
@Override
public <T> T reduce(Reducer<T> reducer) {
Object[] reducedChildren = new Object[children.size()];
for(int i = 0; i < reducedChildren.length; i++){
reducedChildren[i] = children.get(i).reduce(reducer);
if(reducedChildren[i] == null) return null;
}
return reducer.reduceNode(this, reducedChildren);
}
@Override
public String toString() {
StringBuilder buffer = new StringBuilder();
buffer.append(function);
buffer.append("(");
for(int i = 0; i < children.size(); i++){
buffer.append(children.get(i));
buffer.append(i == children.size() - 1 ? "" : ", ");
}
buffer.append(")");
return buffer.toString();
}
}

View File

@@ -0,0 +1,48 @@
package org.nwapw.abacus.tree;
import org.nwapw.abacus.number.NaiveNumber;
import org.nwapw.abacus.number.NumberInterface;
/**
* A node implementation that represents a single number.
*/
public class NumberNode extends TreeNode {
/**
* The number that is represented by this number node.
*/
private NumberInterface number;
/**
* Creates a number node with no number.
*/
public NumberNode(){
number = null;
}
/**
* Creates a new number node with the given double value.
* @param newNumber the number for which to create a number node.
*/
public NumberNode(NumberInterface newNumber){
this.number = newNumber;
}
/**
* Gets the number value of this node.
* @return the number value of this node.
*/
public NumberInterface getNumber() {
return number;
}
@Override
public <T> T reduce(Reducer<T> reducer) {
return reducer.reduceNode(this);
}
@Override
public String toString() {
return number != null ? number.toString() : "null";
}
}

View File

@@ -0,0 +1,53 @@
package org.nwapw.abacus.tree;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.function.Function;
import org.nwapw.abacus.number.NumberInterface;
/**
* A reducer implementation that turns a tree into a single number.
* This is not always guaranteed to work.
*/
public class NumberReducer implements Reducer<NumberInterface> {
/**
* The plugin manager from which to draw the functions.
*/
private Abacus abacus;
/**
* Creates a new number reducer.
* @param abacus the calculator instance.
*/
public NumberReducer(Abacus abacus){
this.abacus = abacus;
}
@Override
public NumberInterface reduceNode(TreeNode node, Object... children) {
if(node instanceof NumberNode) {
return ((NumberNode) node).getNumber();
} else if(node instanceof BinaryInfixNode){
NumberInterface left = (NumberInterface) children[0];
NumberInterface right = (NumberInterface) children[1];
Function function = abacus.getPluginManager().operatorFor(((BinaryInfixNode) node).getOperation()).getFunction();
if(function == null) return null;
return function.apply(left, right);
} else if(node instanceof UnaryPrefixNode) {
NumberInterface child = (NumberInterface) children[0];
Function functionn = abacus.getPluginManager().operatorFor(((UnaryPrefixNode) node).getOperation()).getFunction();
if(functionn == null) return null;
return functionn.apply(child);
} else if(node instanceof FunctionNode){
NumberInterface[] convertedChildren = new NumberInterface[children.length];
for(int i = 0; i < convertedChildren.length; i++){
convertedChildren[i] = (NumberInterface) children[i];
}
Function function = abacus.getPluginManager().functionFor(((FunctionNode) node).getFunction());
if(function == null) return null;
return function.apply(convertedChildren);
}
return null;
}
}

View File

@@ -0,0 +1,17 @@
package org.nwapw.abacus.tree;
/**
* Interface used to reduce a tree into a single value.
* @param <T> the value to reduce into.
*/
public interface Reducer<T> {
/**
* Reduces the given tree into a single value of type T.
* @param node the node being passed in to be reduced.
* @param children the already-reduced children of this node.
* @return the resulting value from the reduce.
*/
public T reduceNode(TreeNode node, Object...children);
}

View File

@@ -0,0 +1,25 @@
package org.nwapw.abacus.tree;
/**
* Enum to represent the type of the token that has been matched
* by the lexer.
*/
public enum TokenType {
INTERNAL_FUNCTION_END(-1),
ANY(0), WHITESPACE(1), COMMA(2), OP(3), NUM(4), FUNCTION(5), OPEN_PARENTH(6), CLOSE_PARENTH(7);
/**
* The priority by which this token gets sorted.
*/
public final int priority;
/**
* Creates a new token type with the given priority.
* @param priority the priority of this token type.
*/
TokenType(int priority){
this.priority = priority;
}
}

View File

@@ -0,0 +1,22 @@
package org.nwapw.abacus.tree;
import org.nwapw.abacus.function.OperatorAssociativity;
import org.nwapw.abacus.lexing.Lexer;
import org.nwapw.abacus.lexing.pattern.Match;
import java.util.*;
/**
* An abstract class that represents an expression tree node.
*/
public abstract class TreeNode {
/**
* The function that reduces a tree to a single vale.
* @param reducer the reducer used to reduce the tree.
* @param <T> the type the reducer produces.
* @return the result of the reduction, or null on error.
*/
public abstract <T> T reduce(Reducer<T> reducer);
}

View File

@@ -0,0 +1,59 @@
package org.nwapw.abacus.tree;
public class UnaryPrefixNode extends TreeNode {
/**
* The operation this node will apply.
*/
private String operation;
/**
* The tree node to apply the operation to.
*/
private TreeNode applyTo;
/**
* Creates a new node with the given operation and no child.
* @param operation the operation for this node.
*/
public UnaryPrefixNode(String operation){
this(operation, null);
}
/**
* Creates a new node with the given operation and child.
* @param operation the operation for this node.
* @param applyTo the node to apply the function to.
*/
public UnaryPrefixNode(String operation, TreeNode applyTo){
this.operation = operation;
this.applyTo = applyTo;
}
@Override
public <T> T reduce(Reducer<T> reducer) {
Object reducedChild = applyTo.reduce(reducer);
if(reducedChild == null) return null;
return reducer.reduceNode(this, reducedChild);
}
/**
* Gets the operation of this node.
* @return the operation this node performs.
*/
public String getOperation() {
return operation;
}
/**
* Gets the node to which this node's operation applies.
* @return the tree node to which the operation will be applied.
*/
public TreeNode getApplyTo() {
return applyTo;
}
@Override
public String toString() {
return "(" + (applyTo == null ? "null" : applyTo.toString()) + ")" + operation;
}
}

View File

@@ -0,0 +1,108 @@
package org.nwapw.abacus.window;
import org.nwapw.abacus.tree.TreeNode;
import javax.swing.event.TableModelListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableModel;
import java.util.ArrayList;
import java.util.List;
/**
* A table model to store data about the history of inputs
* in the calculator.
*/
public class HistoryTableModel extends AbstractTableModel {
/**
* Static array used to get the column names.
*/
public static final String[] COLUMN_NAMES = {
"Input",
"Parsed Input",
"Output"
};
/**
* Static array used to get the class of each column.
*/
public static final Class[] CLASS_TYPES = {
String.class,
TreeNode.class,
String.class
};
/**
* Class used specifically to hold data about
* the previous entries into the calculator.
*/
public static class HistoryEntry {
public String input;
public TreeNode parsedInput;
public String output;
public HistoryEntry(String input, TreeNode parsedInput, String output){
this.input = input;
this.parsedInput = parsedInput;
this.output = output;
}
Object nthValue(int n){
if(n == 0) return input;
if(n == 1) return parsedInput;
if(n == 2) return output;
return null;
}
}
/**
* The list of entries.
*/
List<HistoryEntry> entries;
/**
* Creates a new empty history table model
*/
public HistoryTableModel() {
entries = new ArrayList<>();
}
/**
* Adds an entry to the model.
* @param entry the entry to add.
*/
public void addEntry(HistoryEntry entry){
entries.add(entry);
}
@Override
public int getRowCount() {
return entries.size();
}
@Override
public int getColumnCount() {
return 3;
}
@Override
public String getColumnName(int columnIndex) {
return COLUMN_NAMES[columnIndex];
}
@Override
public Class<?> getColumnClass(int columnIndex) {
return CLASS_TYPES[columnIndex];
}
@Override
public boolean isCellEditable(int rowIndex, int columnIndex) {
return false;
}
@Override
public Object getValueAt(int rowIndex, int columnIndex) {
return entries.get(rowIndex).nthValue(columnIndex);
}
}

View File

@@ -0,0 +1,249 @@
package org.nwapw.abacus.window;
import org.nwapw.abacus.Abacus;
import org.nwapw.abacus.number.NumberInterface;
import org.nwapw.abacus.tree.TreeNode;
import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.StringSelection;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
/**
* The main UI window for the calculator.
*/
public class Window extends JFrame {
private static final String CALC_STRING = "Calculate";
private static final String SYNTAX_ERR_STRING = "Syntax Error";
private static final String EVAL_ERR_STRING = "Evaluation Error";
private static final String NUMBER_SYSTEM_LABEL = "Number Type:";
private static final String FUNCTION_LABEL = "Functions:";
/**
* Array of Strings to which the "calculate" button's text
* changes. For instance, in the graph tab, the name will
* be "Graph" and not "Calculate".
*/
private static final String[] BUTTON_NAMES = {
CALC_STRING,
CALC_STRING
};
/**
* Array of booleans that determine whether the input
* field and the input button are enabled at a particular
* index.
*/
private static boolean[] INPUT_ENABLED = {
true,
false
};
/**
* The instance of the Abacus class, used
* for interaction with plugins and configuration.
*/
private Abacus abacus;
/**
* The last output by the calculator.
*/
private String lastOutput;
/**
* The tabbed pane that separates calculator contexts.
*/
private JTabbedPane pane;
/**
* The panel where the output occurs.
*/
private JPanel calculationPanel;
/**
* The text area reserved for the last output.
*/
private JTextArea lastOutputArea;
/**
* The table used for storing history results.
*/
private JTable historyTable;
/**
* The table model used for managing history.
*/
private HistoryTableModel historyModel;
/**
* The scroll pane for the history area.
*/
private JScrollPane historyScroll;
/**
* The panel where the input occurs.
*/
private JPanel inputPanel;
/**
* The input text field.
*/
private JTextField inputField;
/**
* The "submit" button.
*/
private JButton inputEnterButton;
/**
* The side panel for separate configuration.
*/
private JPanel settingsPanel;
/**
* Panel for elements relating to number
* system selection.
*/
private JPanel numberSystemPanel;
/**
* The possible list of number systems.
*/
private JComboBox<String> numberSystemList;
/**
* The panel for elements relating to
* function selection.
*/
private JPanel functionSelectPanel;
/**
* The list of functions available to the user.
*/
private JComboBox<String> functionList;
/**
* Action listener that causes the input to be evaluated.
*/
private ActionListener evaluateListener = (event) -> {
TreeNode parsedExpression = abacus.parseString(inputField.getText());
if(parsedExpression == null){
lastOutputArea.setText(SYNTAX_ERR_STRING);
return;
}
NumberInterface numberInterface = abacus.evaluateTree(parsedExpression);
if(numberInterface == null) {
lastOutputArea.setText(EVAL_ERR_STRING);
return;
}
lastOutput = numberInterface.toString();
historyModel.addEntry(new HistoryTableModel.HistoryEntry(inputField.getText(), parsedExpression, lastOutput));
historyTable.invalidate();
lastOutputArea.setText(lastOutput);
inputField.setText("");
};
/**
* Array of listeners that tell the input button how to behave
* at a given input tab.
*/
private ActionListener[] listeners = {
evaluateListener,
null
};
/**
* Creates a new window with the given manager.
* @param abacus the calculator instance to interact with other components.
*/
public Window(Abacus abacus){
this();
this.abacus = abacus;
}
/**
* Creates a new window.
*/
private Window() {
super();
lastOutput = "";
setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
setSize(320, 480);
inputField = new JTextField();
inputEnterButton = new JButton(CALC_STRING);
inputPanel = new JPanel();
inputPanel.setLayout(new BorderLayout());
inputPanel.add(inputField, BorderLayout.CENTER);
inputPanel.add(inputEnterButton, BorderLayout.SOUTH);
historyModel = new HistoryTableModel();
historyTable = new JTable(historyModel);
historyScroll = new JScrollPane(historyTable);
lastOutputArea = new JTextArea(lastOutput);
lastOutputArea.setEditable(false);
calculationPanel = new JPanel();
calculationPanel.setLayout(new BorderLayout());
calculationPanel.add(historyScroll, BorderLayout.CENTER);
calculationPanel.add(lastOutputArea, BorderLayout.SOUTH);
numberSystemList = new JComboBox<>();
numberSystemPanel = new JPanel();
numberSystemPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
numberSystemPanel.setLayout(new FlowLayout());
numberSystemPanel.add(new JLabel(NUMBER_SYSTEM_LABEL));
numberSystemPanel.add(numberSystemList);
numberSystemPanel.setMaximumSize(numberSystemPanel.getPreferredSize());
functionList = new JComboBox<>();
functionSelectPanel = new JPanel();
functionSelectPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
functionSelectPanel.setLayout(new FlowLayout());
functionSelectPanel.add(new JLabel(FUNCTION_LABEL));
functionSelectPanel.add(functionList);
functionSelectPanel.setMaximumSize(functionSelectPanel.getPreferredSize());
settingsPanel = new JPanel();
settingsPanel.setAlignmentX(Component.LEFT_ALIGNMENT);
settingsPanel.setLayout(new BoxLayout(settingsPanel, BoxLayout.PAGE_AXIS));
settingsPanel.add(numberSystemPanel);
settingsPanel.add(functionSelectPanel);
pane = new JTabbedPane();
pane.add("Calculator", calculationPanel);
pane.add("Settings", settingsPanel);
pane.addChangeListener(e -> {
int selectionIndex = pane.getSelectedIndex();
boolean enabled = INPUT_ENABLED[selectionIndex];
ActionListener listener = listeners[selectionIndex];
inputEnterButton.setText(BUTTON_NAMES[selectionIndex]);
inputField.setEnabled(enabled);
inputEnterButton.setEnabled(enabled);
for(ActionListener removingListener : inputEnterButton.getActionListeners()){
inputEnterButton.removeActionListener(removingListener);
inputField.removeActionListener(removingListener);
}
if(listener != null){
inputEnterButton.addActionListener(listener);
inputField.addActionListener(listener);
}
});
add(pane, BorderLayout.CENTER);
add(inputPanel, BorderLayout.SOUTH);
inputEnterButton.addActionListener(evaluateListener);
inputField.addActionListener(evaluateListener);
historyTable.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e) {
Point clickPoint = e.getPoint();
if(e.getClickCount() == 2){
int row = historyTable.rowAtPoint(clickPoint);
int column = historyTable.columnAtPoint(clickPoint);
String toCopy = historyTable.getValueAt(row, column).toString();
Toolkit.getDefaultToolkit().getSystemClipboard().setContents(new StringSelection(toCopy), null);
}
}
});
}
}