mirror of
https://github.com/DanilaFe/abacus
synced 2026-01-25 08:05:19 +00:00
Compare commits
42 Commits
ui-touchup
...
loader
| Author | SHA1 | Date | |
|---|---|---|---|
| 1190ece7dd | |||
| f119f19c04 | |||
| 65772c8d57 | |||
| bbbb2e855e | |||
| 8a29019852 | |||
| 0d7a416446 | |||
| 167e13cfe1 | |||
| b0ae3f90fc | |||
| a7c2084254 | |||
|
|
bf6f48bf82 | ||
| f7da896fc0 | |||
| 6813643b15 | |||
| e6cb755ec9 | |||
| 2ca23fd427 | |||
| efbd6a4c20 | |||
| a211884499 | |||
| f2c280766d | |||
|
|
088a45cf4c | ||
|
|
557bc66e53 | ||
| e6559015b3 | |||
| f931b9f322 | |||
|
|
9666ef9019 | ||
|
|
ba30227b28 | ||
| 78e2d50f89 | |||
| 07dd9d0a1a | |||
| ee1de6dc17 | |||
| 077a34c618 | |||
| 79e85832ce | |||
|
|
ea5a7a9558 | ||
|
|
3e52a9d645 | ||
|
|
7a0fa31cad | ||
|
|
aec37b6720 | ||
| 189f8c6e15 | |||
| e8595510b8 | |||
| b09c9c3cb2 | |||
| b0a7c90aa1 | |||
| cf95ed7dc0 | |||
| bc72b4da8a | |||
| 15d7dbd30e | |||
| c8146954c3 | |||
| d18e27bdb4 | |||
| c4eb70999b |
@@ -25,6 +25,7 @@ public class Abacus {
|
||||
manager.addInstantiated(new StandardPlugin(manager));
|
||||
mainUi = new Window(manager);
|
||||
mainUi.setVisible(true);
|
||||
manager.load();
|
||||
}
|
||||
|
||||
public static void main(String[] args){
|
||||
|
||||
57
src/org/nwapw/abacus/function/Operator.java
Normal file
57
src/org/nwapw/abacus/function/Operator.java
Normal file
@@ -0,0 +1,57 @@
|
||||
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 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, int precedence, Function function){
|
||||
this.associativity = associativity;
|
||||
this.precedence = precedence;
|
||||
this.function = function;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the operator's associativity.
|
||||
* @return the associativity.
|
||||
*/
|
||||
public OperatorAssociativity getAssociativity() {
|
||||
return associativity;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package org.nwapw.abacus.tree;
|
||||
package org.nwapw.abacus.function;
|
||||
|
||||
/**
|
||||
* Enum to represent the associativity of an operator.
|
||||
@@ -5,9 +5,7 @@ import org.nwapw.abacus.lexing.pattern.Match;
|
||||
import org.nwapw.abacus.lexing.pattern.Pattern;
|
||||
import org.nwapw.abacus.lexing.pattern.PatternNode;
|
||||
|
||||
import java.util.ArrayList;
|
||||
import java.util.Comparator;
|
||||
import java.util.HashSet;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A lexer that can generate tokens of a given type given a list of regular expressions
|
||||
@@ -16,16 +14,53 @@ import java.util.HashSet;
|
||||
*/
|
||||
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 ArrayList<Pattern<T>> patterns;
|
||||
private HashMap<PatternEntry<T>, Pattern<T>> patterns;
|
||||
|
||||
/**
|
||||
* Creates a new lexer with no registered patterns.
|
||||
*/
|
||||
public Lexer(){
|
||||
patterns = new ArrayList<>();
|
||||
patterns = new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -35,7 +70,16 @@ public class Lexer<T> {
|
||||
*/
|
||||
public void register(String pattern, T id){
|
||||
Pattern<T> compiledPattern = new Pattern<>(pattern, id);
|
||||
if(compiledPattern.getHead() != null) patterns.add(compiledPattern);
|
||||
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));
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -50,7 +94,7 @@ public class Lexer<T> {
|
||||
HashSet<PatternNode<T>> currentSet = new HashSet<>();
|
||||
HashSet<PatternNode<T>> futureSet = new HashSet<>();
|
||||
int index = startAt;
|
||||
for(Pattern<T> pattern : patterns){
|
||||
for(Pattern<T> pattern : patterns.values()){
|
||||
pattern.getHead().addInto(currentSet);
|
||||
}
|
||||
while(!currentSet.isEmpty()){
|
||||
|
||||
@@ -235,4 +235,22 @@ public class Pattern<T> {
|
||||
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;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -29,7 +29,7 @@ public class NaiveNumber implements NumberInterface {
|
||||
|
||||
@Override
|
||||
public int precision() {
|
||||
return 15;
|
||||
return 18;
|
||||
}
|
||||
|
||||
@Override
|
||||
|
||||
@@ -49,8 +49,8 @@ public interface NumberInterface {
|
||||
|
||||
/**
|
||||
* Raises this number to an integer power.
|
||||
* @param exponent
|
||||
* @return
|
||||
* @param exponent the exponent to which to take the number.
|
||||
* @return the resulting value.
|
||||
*/
|
||||
NumberInterface intPow(int exponent);
|
||||
|
||||
|
||||
65
src/org/nwapw/abacus/plugin/ClassFinder.java
Normal file
65
src/org/nwapw/abacus/plugin/ClassFinder.java
Normal file
@@ -0,0 +1,65 @@
|
||||
package org.nwapw.abacus.plugin;
|
||||
|
||||
import java.io.BufferedInputStream;
|
||||
import java.io.File;
|
||||
import java.io.FileInputStream;
|
||||
import java.io.IOException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Enumeration;
|
||||
import java.util.HashMap;
|
||||
import java.util.jar.JarEntry;
|
||||
import java.util.jar.JarFile;
|
||||
import java.util.zip.ZipInputStream;
|
||||
|
||||
public class ClassFinder extends ClassLoader{
|
||||
|
||||
ArrayList<Class> classes;
|
||||
|
||||
public ClassFinder(){
|
||||
super(ClassFinder.class.getClassLoader());
|
||||
classes=new ArrayList();
|
||||
}
|
||||
public Class loadClass(String className) throws ClassNotFoundException{
|
||||
return findClass(className);
|
||||
}
|
||||
public ArrayList<String> loadClass(File jarLocation) throws ClassNotFoundException, IOException{
|
||||
return addJar(jarLocation);
|
||||
}
|
||||
public ArrayList<String> addJar(File jarLocation) throws IOException {
|
||||
JarFile jarFolder = new JarFile(jarLocation);
|
||||
Enumeration jarList = jarFolder.entries();
|
||||
HashMap classSize = new HashMap();
|
||||
HashMap classContent = new HashMap();
|
||||
ArrayList<String> classNames = new ArrayList();
|
||||
JarEntry tempJar;
|
||||
ZipInputStream zipStream = new ZipInputStream(new BufferedInputStream(new FileInputStream(jarLocation)));
|
||||
while(jarList.hasMoreElements()){
|
||||
tempJar = (JarEntry)jarList.nextElement();
|
||||
zipStream.getNextEntry();
|
||||
if(!tempJar.isDirectory()) {
|
||||
if (tempJar.getName().substring(tempJar.getName().indexOf('.')).equals(".class") && (tempJar.getName().length() < 9 || !tempJar.getName().substring(0, 9).equals("META-INF/"))) {
|
||||
int size = (int)tempJar.getSize();
|
||||
classSize.put(tempJar.getName(),new Integer((int)tempJar.getSize()));
|
||||
byte[] bytes = new byte[size];
|
||||
zipStream.read(bytes,0,size);
|
||||
classContent.put(tempJar.getName(),bytes);
|
||||
classNames.add(tempJar.getName());
|
||||
}
|
||||
}
|
||||
}
|
||||
jarFolder.close();
|
||||
for(String name:classNames) {
|
||||
classes.add(super.defineClass(name, (byte[]) classContent.get(name), 0, (int) classSize.get(name)));
|
||||
}
|
||||
return classNames;
|
||||
}
|
||||
public ArrayList<Class> getClasses(){
|
||||
return classes;
|
||||
}
|
||||
public Class getClass(int number){
|
||||
return classes.get(number);
|
||||
}
|
||||
public void delClasses(){
|
||||
classes=new ArrayList();
|
||||
}
|
||||
}
|
||||
@@ -1,8 +1,10 @@
|
||||
package org.nwapw.abacus.plugin;
|
||||
|
||||
import org.nwapw.abacus.function.Function;
|
||||
import org.nwapw.abacus.function.Operator;
|
||||
|
||||
import java.util.HashMap;
|
||||
import java.util.Set;
|
||||
|
||||
/**
|
||||
* A plugin class that can be externally implemented and loaded via the
|
||||
@@ -17,11 +19,19 @@ public abstract class Plugin {
|
||||
* A hash map of functions mapped to their string names.
|
||||
*/
|
||||
private HashMap<String, Function> functions;
|
||||
/**
|
||||
* A hash map of operators mapped to their string names.
|
||||
*/
|
||||
private HashMap<String, Operator> operators;
|
||||
/**
|
||||
* 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(){ }
|
||||
|
||||
@@ -32,15 +42,24 @@ public abstract class Plugin {
|
||||
public Plugin(PluginManager manager) {
|
||||
this.manager = manager;
|
||||
functions = new HashMap<>();
|
||||
operators = new HashMap<>();
|
||||
enabled = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Determines whether the current plugin provides the given function name.
|
||||
* @param functionName the name of the function provided.
|
||||
* @return true of the function exists, false if it doesn't.
|
||||
* Gets the list of functions provided by this plugin.
|
||||
* @return the list of registered functions.
|
||||
*/
|
||||
public final boolean hasFunction(String functionName) {
|
||||
return functions.containsKey(functionName);
|
||||
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();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -52,37 +71,91 @@ public abstract class Plugin {
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @return true if the function was registered successfully, false if not.
|
||||
*/
|
||||
protected final boolean registerFunction(String name, Function toRegister) {
|
||||
if(functionFor(name) == null){
|
||||
functions.put(name, toRegister);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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 then name for which to search
|
||||
* @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 load();
|
||||
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();
|
||||
|
||||
}
|
||||
|
||||
20
src/org/nwapw/abacus/plugin/PluginListener.java
Normal file
20
src/org/nwapw/abacus/plugin/PluginListener.java
Normal 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);
|
||||
|
||||
}
|
||||
106
src/org/nwapw/abacus/plugin/PluginLoader.java
Normal file
106
src/org/nwapw/abacus/plugin/PluginLoader.java
Normal file
@@ -0,0 +1,106 @@
|
||||
package org.nwapw.abacus.plugin;
|
||||
|
||||
import java.io.File;
|
||||
import java.io.IOException;
|
||||
import java.net.URL;
|
||||
import java.net.URLClassLoader;
|
||||
import java.util.ArrayList;
|
||||
import java.util.Properties;
|
||||
import java.util.jar.JarFile;
|
||||
|
||||
/**
|
||||
* A plugin loader, used to scan a directory for
|
||||
* plugins and load them into classes that can then be
|
||||
* used by the plugin manager.
|
||||
*/
|
||||
public class PluginLoader {
|
||||
|
||||
/**
|
||||
* An internal class that represents a Jar file that
|
||||
* has been founded, but not loaded.
|
||||
*/
|
||||
private static final class PluginEntry {
|
||||
String mainClass;
|
||||
File jarPath;
|
||||
}
|
||||
|
||||
/**
|
||||
* The path which to search for plugins.
|
||||
*/
|
||||
private File path;
|
||||
/**
|
||||
* The array of loaded plugin main classes.
|
||||
*/
|
||||
private ArrayList<Class<?>> foundMainClasses;
|
||||
|
||||
/**
|
||||
* Creates a new plugin loader at the given path.
|
||||
* @param path the path which to search for plugins.
|
||||
*/
|
||||
public PluginLoader(File path) {
|
||||
this.path = path;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads all the plugin classes that have been found.
|
||||
* @return the list of loaded classes.
|
||||
* @throws IOException thrown when loading classes from URL fails.
|
||||
* @throws ClassNotFoundException thrown when the class specified in plugin.properties is missing.
|
||||
*/
|
||||
private ArrayList<Class<?>> loadPluginClasses() throws IOException, ClassNotFoundException {
|
||||
ArrayList<Class<?>> foundMainClasses = new ArrayList<>();
|
||||
for(PluginEntry entry : findPlugins()){
|
||||
if(entry.mainClass == null) continue;
|
||||
ClassLoader loader = URLClassLoader.newInstance(
|
||||
new URL[]{ entry.jarPath.toURI().toURL() },
|
||||
getClass().getClassLoader());
|
||||
Class<?> loadedClass = loader.loadClass(entry.mainClass);
|
||||
if(!Plugin.class.isAssignableFrom(loadedClass)) continue;
|
||||
foundMainClasses.add(loadedClass);
|
||||
}
|
||||
return foundMainClasses;
|
||||
}
|
||||
|
||||
/**
|
||||
* Find all jars that have a plugin.properties file in the plugin folder.
|
||||
* @return the list of all plugin entries, with their main class names and the jars files.
|
||||
* @throws IOException thrown if reading the jar file fails
|
||||
*/
|
||||
private ArrayList<PluginEntry> findPlugins() throws IOException {
|
||||
ArrayList<PluginEntry> pluginEntries = new ArrayList<>();
|
||||
File[] childFiles = path.listFiles();
|
||||
|
||||
if(childFiles == null) return pluginEntries;
|
||||
for(File file : childFiles){
|
||||
if(!file.isFile() || !file.getName().endsWith(".jar")) continue;
|
||||
JarFile jarFile = new JarFile(file);
|
||||
if(jarFile.getEntry("plugin.properties") == null) continue;
|
||||
Properties properties = new Properties();
|
||||
properties.load(jarFile.getInputStream(jarFile.getEntry("plugin.properties")));
|
||||
|
||||
PluginEntry entry = new PluginEntry();
|
||||
entry.mainClass = properties.getProperty("mainClass");
|
||||
entry.jarPath = file;
|
||||
pluginEntries.add(entry);
|
||||
}
|
||||
return pluginEntries;
|
||||
}
|
||||
|
||||
/**
|
||||
* Loads all valid plugins and keeps track of them.
|
||||
* @throws IOException thrown if loading from jar files fails.
|
||||
* @throws ClassNotFoundException thrown if class specified in plugin.properties doesn't exist.
|
||||
*/
|
||||
public void loadValidPlugins() throws IOException, ClassNotFoundException {
|
||||
foundMainClasses = loadPluginClasses();
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets the list of all the plugins that have last been loaded.
|
||||
* @return the list of loaded class files.
|
||||
*/
|
||||
public ArrayList<Class<?>> getFoundMainClasses() {
|
||||
return foundMainClasses;
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,10 +1,10 @@
|
||||
package org.nwapw.abacus.plugin;
|
||||
|
||||
import org.nwapw.abacus.function.Function;
|
||||
import org.nwapw.abacus.function.Operator;
|
||||
|
||||
import java.lang.reflect.InvocationTargetException;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* A class that controls instances of plugins, allowing for them
|
||||
@@ -21,6 +21,23 @@ public class PluginManager {
|
||||
* that is, found in a plugin and returned.
|
||||
*/
|
||||
private HashMap<String, Function> cachedFunctions;
|
||||
/**
|
||||
* List of operators tha have been cached,
|
||||
* that is, found in a plugin and returned.
|
||||
*/
|
||||
private HashMap<String, Operator> cachedOperators;
|
||||
/**
|
||||
* List of all functions loaded by the plugins.
|
||||
*/
|
||||
private HashSet<String> allFunctions;
|
||||
/**
|
||||
* List of all operators loaded by the plugins.
|
||||
*/
|
||||
private HashSet<String> allOperators;
|
||||
/**
|
||||
* The list of plugin listeners attached to this instance.
|
||||
*/
|
||||
private HashSet<PluginListener> listeners;
|
||||
|
||||
/**
|
||||
* Creates a new plugin manager.
|
||||
@@ -28,27 +45,58 @@ public class PluginManager {
|
||||
public PluginManager(){
|
||||
plugins = new ArrayList<>();
|
||||
cachedFunctions = new HashMap<>();
|
||||
cachedOperators = new HashMap<>();
|
||||
allFunctions = new HashSet<>();
|
||||
allOperators = 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){
|
||||
if(cachedFunctions.containsKey(name)) {
|
||||
return cachedFunctions.get(name);
|
||||
}
|
||||
return searchCached(plugins, cachedFunctions, Plugin::providedFunctions, Plugin::getFunction, name);
|
||||
}
|
||||
|
||||
Function loadedFunction = null;
|
||||
for(Plugin plugin : plugins){
|
||||
if(plugin.hasFunction(name)){
|
||||
loadedFunction = plugin.getFunction(name);
|
||||
break;
|
||||
}
|
||||
}
|
||||
cachedFunctions.put(name, loadedFunction);
|
||||
return loadedFunction;
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -56,8 +104,6 @@ public class PluginManager {
|
||||
* @param plugin the plugin to add.
|
||||
*/
|
||||
public void addInstantiated(Plugin plugin){
|
||||
plugin.load();
|
||||
cachedFunctions.clear();
|
||||
plugins.add(plugin);
|
||||
}
|
||||
|
||||
@@ -75,4 +121,66 @@ public class PluginManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* 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());
|
||||
}
|
||||
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();
|
||||
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 HashSet<String> getAllFunctions() {
|
||||
return allFunctions;
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets all the operators loaded by the Plugin Manager.
|
||||
* @return the set of all operators that were loaded.
|
||||
*/
|
||||
public HashSet<String> getAllOperators() {
|
||||
return allOperators;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
}
|
||||
|
||||
@@ -1,9 +1,14 @@
|
||||
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.number.NaiveNumber;
|
||||
import org.nwapw.abacus.number.NumberInterface;
|
||||
|
||||
import javax.print.attribute.standard.MediaSize;
|
||||
import java.util.ArrayList;
|
||||
import java.util.HashMap;
|
||||
import java.util.function.BiFunction;
|
||||
|
||||
/**
|
||||
@@ -17,8 +22,8 @@ public class StandardPlugin extends Plugin {
|
||||
}
|
||||
|
||||
@Override
|
||||
public void load() {
|
||||
registerFunction("+", new Function() {
|
||||
public void onEnable() {
|
||||
registerOperator("+", new Operator(OperatorAssociativity.LEFT, 0, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length >= 1;
|
||||
@@ -32,9 +37,9 @@ public class StandardPlugin extends Plugin {
|
||||
}
|
||||
return sum;
|
||||
}
|
||||
});
|
||||
}));
|
||||
|
||||
registerFunction("-", new Function() {
|
||||
registerOperator("-", new Operator(OperatorAssociativity.LEFT, 0, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 2;
|
||||
@@ -44,9 +49,9 @@ public class StandardPlugin extends Plugin {
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
return params[0].subtract(params[1]);
|
||||
}
|
||||
});
|
||||
}));
|
||||
|
||||
registerFunction("*", new Function() {
|
||||
registerOperator("*", new Operator(OperatorAssociativity.LEFT, 1, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length >= 1;
|
||||
@@ -60,9 +65,9 @@ public class StandardPlugin extends Plugin {
|
||||
}
|
||||
return product;
|
||||
}
|
||||
});
|
||||
}));
|
||||
|
||||
registerFunction("/", new Function() {
|
||||
registerOperator("/", new Operator(OperatorAssociativity.LEFT, 1, new Function() {
|
||||
@Override
|
||||
protected boolean matchesParams(NumberInterface[] params) {
|
||||
return params.length == 2;
|
||||
@@ -72,9 +77,22 @@ public class StandardPlugin extends Plugin {
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
return params[0].divide(params[1]);
|
||||
}
|
||||
});
|
||||
}));
|
||||
|
||||
registerOperator("^", new Operator(OperatorAssociativity.RIGHT, 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]));
|
||||
}
|
||||
}));
|
||||
|
||||
registerFunction("!", 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;
|
||||
@@ -92,6 +110,23 @@ public class StandardPlugin extends Plugin {
|
||||
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()));
|
||||
}
|
||||
});
|
||||
|
||||
@@ -103,16 +138,114 @@ public class StandardPlugin extends Plugin {
|
||||
|
||||
@Override
|
||||
protected NumberInterface applyInternal(NumberInterface[] params) {
|
||||
return sumSeries(params[0], StandardPlugin.this::getExpSeriesTerm, getNTermsExp(getMaxError(params[0]), params[0]));
|
||||
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.getFunction("pow").apply(params[0], (new NaiveNumber(0.5)));
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@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
|
||||
* @return the nth term of the series.
|
||||
*/
|
||||
private NumberInterface getExpSeriesTerm(int n, NumberInterface x){
|
||||
return x.intPow(n).divide(this.getFunction("!").apply((new NaiveNumber(n)).promoteTo(x.getClass())));
|
||||
@@ -123,17 +256,18 @@ public class StandardPlugin extends Plugin {
|
||||
* 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
|
||||
* @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+2) <= (n+1)! * maxError
|
||||
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;
|
||||
NumberInterface LHS = x.intPow(2), RHS = maxError;
|
||||
while(LHS.compareTo(RHS) > 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).promoteTo(RHS.getClass()));
|
||||
RHS = RHS.multiply(new NaiveNumber(n + 1).promoteTo(RHS.getClass()));
|
||||
}
|
||||
return n;
|
||||
}
|
||||
@@ -157,7 +291,7 @@ public class StandardPlugin extends Plugin {
|
||||
/**
|
||||
* 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
|
||||
* @return the maximum error.
|
||||
*/
|
||||
private NumberInterface getMaxError(NumberInterface number){
|
||||
return (new NaiveNumber(10)).promoteTo(number.getClass()).intPow(-number.precision());
|
||||
|
||||
79
src/org/nwapw/abacus/tree/FunctionNode.java
Normal file
79
src/org/nwapw/abacus/tree/FunctionNode.java
Normal file
@@ -0,0 +1,79 @@
|
||||
package org.nwapw.abacus.tree;
|
||||
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* 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 ArrayList<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();
|
||||
}
|
||||
}
|
||||
@@ -1,12 +1,24 @@
|
||||
package org.nwapw.abacus.tree;
|
||||
|
||||
import org.nwapw.abacus.function.Function;
|
||||
import org.nwapw.abacus.number.NumberInterface;
|
||||
import org.nwapw.abacus.plugin.PluginManager;
|
||||
|
||||
/**
|
||||
* 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 PluginManager manager;
|
||||
|
||||
/**
|
||||
* Creates a new number reducer with the given plugin manager.
|
||||
* @param manager the plugin manager.
|
||||
*/
|
||||
public NumberReducer(PluginManager manager){
|
||||
this.manager = manager;
|
||||
}
|
||||
@@ -18,7 +30,17 @@ public class NumberReducer implements Reducer<NumberInterface> {
|
||||
} else if(node instanceof OpNode){
|
||||
NumberInterface left = (NumberInterface) children[0];
|
||||
NumberInterface right = (NumberInterface) children[1];
|
||||
return manager.functionFor(((OpNode) node).getOperation()).apply(left, right);
|
||||
Function function = manager.operatorFor(((OpNode) node).getOperation()).getFunction();
|
||||
if(function == null) return null;
|
||||
return function.apply(left, right);
|
||||
} 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 = manager.functionFor(((FunctionNode) node).getFunction());
|
||||
if(function == null) return null;
|
||||
return function.apply(convertedChildren);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -86,6 +86,7 @@ public class OpNode extends TreeNode {
|
||||
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);
|
||||
}
|
||||
|
||||
@@ -94,13 +95,6 @@ public class OpNode extends TreeNode {
|
||||
String leftString = left != null ? left.toString() : "null";
|
||||
String rightString = right != null ? right.toString() : "null";
|
||||
|
||||
if(right != null && right instanceof OpNode){
|
||||
if(TreeNode.precedenceMap.get(((OpNode) right).getOperation()) >
|
||||
TreeNode.precedenceMap.get(operation)) {
|
||||
rightString = "(" + rightString + ")";
|
||||
}
|
||||
}
|
||||
|
||||
return leftString + operation + rightString;
|
||||
return "(" + leftString + operation + rightString + ")";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -6,7 +6,8 @@ package org.nwapw.abacus.tree;
|
||||
*/
|
||||
public enum TokenType {
|
||||
|
||||
ANY(0), OP(1), NUM(2), WORD(3), OPEN_PARENTH(4), CLOSE_PARENTH(5);
|
||||
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.
|
||||
|
||||
183
src/org/nwapw/abacus/tree/TreeBuilder.java
Normal file
183
src/org/nwapw/abacus/tree/TreeBuilder.java
Normal file
@@ -0,0 +1,183 @@
|
||||
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 org.nwapw.abacus.lexing.pattern.Pattern;
|
||||
|
||||
import java.util.*;
|
||||
|
||||
/**
|
||||
* The builder responsible for turning strings into trees.
|
||||
*/
|
||||
public class TreeBuilder {
|
||||
|
||||
/**
|
||||
* The lexer used to get the input tokens.
|
||||
*/
|
||||
private Lexer<TokenType> lexer;
|
||||
/**
|
||||
* The map of operator precedences.
|
||||
*/
|
||||
private HashMap<String, Integer> precedenceMap;
|
||||
/**
|
||||
* The map of operator associativity.
|
||||
*/
|
||||
private HashMap<String, OperatorAssociativity> associativityMap;
|
||||
|
||||
/**
|
||||
* Comparator used to sort token types.
|
||||
*/
|
||||
protected static Comparator<TokenType> tokenSorter = Comparator.comparingInt(e -> e.priority);
|
||||
|
||||
/**
|
||||
* Creates a new TreeBuilder.
|
||||
*/
|
||||
public TreeBuilder(){
|
||||
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);
|
||||
}};
|
||||
precedenceMap = new HashMap<>();
|
||||
associativityMap = new HashMap<>();
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers a function with the TreeBuilder.
|
||||
* @param function the function to register.
|
||||
*/
|
||||
public void registerFunction(String function){
|
||||
lexer.register(Pattern.sanitize(function), TokenType.FUNCTION);
|
||||
}
|
||||
|
||||
/**
|
||||
* Registers an operator with the TreeBuilder.
|
||||
* @param operator the operator to register.
|
||||
* @param precedence the precedence of the operator.
|
||||
* @param associativity the associativity of the operator.
|
||||
*/
|
||||
public void registerOperator(String operator, int precedence, OperatorAssociativity associativity){
|
||||
lexer.register(Pattern.sanitize(operator), TokenType.OP);
|
||||
precedenceMap.put(operator, precedence);
|
||||
associativityMap.put(operator, associativity);
|
||||
}
|
||||
|
||||
/**
|
||||
* Tokenizes a string, converting it into matches
|
||||
* @param string the string to tokenize.
|
||||
* @return the list of tokens produced.
|
||||
*/
|
||||
public ArrayList<Match<TokenType>> tokenize(String string){
|
||||
return lexer.lexAll(string, 0, tokenSorter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rearranges tokens into a postfix list, using Shunting Yard.
|
||||
* @param source the source string.
|
||||
* @param from the tokens to be rearranged.
|
||||
* @return the resulting list of rearranged tokens.
|
||||
*/
|
||||
public ArrayList<Match<TokenType>> intoPostfix(String source, ArrayList<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<>(0, 0, TokenType.INTERNAL_FUNCTION_END));
|
||||
tokenStack.push(match);
|
||||
} else if(matchType == TokenType.OP){
|
||||
String tokenString = source.substring(match.getFrom(), match.getTo());
|
||||
int precedence = precedenceMap.get(tokenString);
|
||||
OperatorAssociativity associativity = associativityMap.get(tokenString);
|
||||
|
||||
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(source.substring(otherMatch.getFrom(), otherMatch.getTo()));
|
||||
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 source the source string.
|
||||
* @param matches the list of tokens from the source string.
|
||||
* @return the construct tree expression.
|
||||
*/
|
||||
public TreeNode fromStringRecursive(String source, ArrayList<Match<TokenType>> matches){
|
||||
if(matches.size() == 0) return null;
|
||||
Match<TokenType> match = matches.remove(0);
|
||||
TokenType matchType = match.getType();
|
||||
if(matchType == TokenType.OP){
|
||||
TreeNode right = fromStringRecursive(source, matches);
|
||||
TreeNode left = fromStringRecursive(source, matches);
|
||||
if(left == null || right == null) return null;
|
||||
else return new OpNode(source.substring(match.getFrom(), match.getTo()), left, right);
|
||||
} else if(matchType == TokenType.NUM){
|
||||
return new NumberNode(Double.parseDouble(source.substring(match.getFrom(), match.getTo())));
|
||||
} else if(matchType == TokenType.FUNCTION){
|
||||
String functionName = source.substring(match.getFrom(), match.getTo());
|
||||
FunctionNode node = new FunctionNode(functionName);
|
||||
while(!matches.isEmpty() && matches.get(0).getType() != TokenType.INTERNAL_FUNCTION_END){
|
||||
TreeNode argument = fromStringRecursive(source, matches);
|
||||
if(argument == null) return null;
|
||||
node.prependChild(argument);
|
||||
}
|
||||
if(matches.isEmpty()) return null;
|
||||
matches.remove(0);
|
||||
return node;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a tree node from a string.
|
||||
* @param string the string to create a node from.
|
||||
* @return the resulting tree.
|
||||
*/
|
||||
public TreeNode fromString(String string){
|
||||
ArrayList<Match<TokenType>> matches = tokenize(string);
|
||||
if(matches == null) return null;
|
||||
matches.removeIf(m -> m.getType() == TokenType.WHITESPACE);
|
||||
matches = intoPostfix(string, matches);
|
||||
if(matches == null) return null;
|
||||
|
||||
Collections.reverse(matches);
|
||||
return fromStringRecursive(string, matches);
|
||||
}
|
||||
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
package org.nwapw.abacus.tree;
|
||||
|
||||
import org.nwapw.abacus.function.OperatorAssociativity;
|
||||
import org.nwapw.abacus.lexing.Lexer;
|
||||
import org.nwapw.abacus.lexing.pattern.Match;
|
||||
|
||||
@@ -11,133 +12,11 @@ import java.util.*;
|
||||
public abstract class TreeNode {
|
||||
|
||||
/**
|
||||
* The lexer used to lex tokens.
|
||||
* 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.
|
||||
*/
|
||||
protected static Lexer<TokenType> lexer = new Lexer<TokenType>(){{
|
||||
register("\\+|-|\\*|/|^", TokenType.OP);
|
||||
register("[0-9]+(\\.[0-9]+)?", TokenType.NUM);
|
||||
register("[a-zA-Z]+", TokenType.WORD);
|
||||
register("\\(", TokenType.OPEN_PARENTH);
|
||||
register("\\)", TokenType.CLOSE_PARENTH);
|
||||
}};
|
||||
/**
|
||||
* A map that maps operations to their precedence.
|
||||
*/
|
||||
protected static HashMap<String, Integer> precedenceMap = new HashMap<String, Integer>(){{
|
||||
put("+", 0);
|
||||
put("-", 0);
|
||||
put("*", 1);
|
||||
put("/", 1);
|
||||
put("^", 2);
|
||||
}};
|
||||
/**
|
||||
* A map that maps operations to their associativity.
|
||||
*/
|
||||
protected static HashMap<String, OperatorAssociativity> associativityMap =
|
||||
new HashMap<String, OperatorAssociativity>() {{
|
||||
put("+", OperatorAssociativity.LEFT);
|
||||
put("-", OperatorAssociativity.LEFT);
|
||||
put("*", OperatorAssociativity.LEFT);
|
||||
put("/", OperatorAssociativity.LEFT);
|
||||
put("^", OperatorAssociativity.RIGHT);
|
||||
}};
|
||||
|
||||
/**
|
||||
* Comparator used to sort token types.
|
||||
*/
|
||||
protected static Comparator<TokenType> tokenSorter = Comparator.comparingInt(e -> e.priority);
|
||||
|
||||
/**
|
||||
* Tokenizes a string, converting it into matches
|
||||
* @param string the string to tokenize.
|
||||
* @return the list of tokens produced.
|
||||
*/
|
||||
public static ArrayList<Match<TokenType>> tokenize(String string){
|
||||
return lexer.lexAll(string, 0, tokenSorter);
|
||||
}
|
||||
|
||||
/**
|
||||
* Rearranges tokens into a postfix list, using Shunting Yard.
|
||||
* @param source the source string.
|
||||
* @param from the tokens to be rearranged.
|
||||
* @return the resulting list of rearranged tokens.
|
||||
*/
|
||||
public static ArrayList<Match<TokenType>> intoPostfix(String source, ArrayList<Match<TokenType>> from){
|
||||
ArrayList<Match<TokenType>> output = new ArrayList<>();
|
||||
Stack<Match<TokenType>> tokenStack = new Stack<>();
|
||||
while(!from.isEmpty()){
|
||||
Match<TokenType> match = from.remove(0);
|
||||
if(match.getType() == TokenType.NUM) {
|
||||
output.add(match);
|
||||
} else if(match.getType() == TokenType.OP){
|
||||
String tokenString = source.substring(match.getFrom(), match.getTo());
|
||||
int precedence = precedenceMap.get(tokenString);
|
||||
OperatorAssociativity associativity = associativityMap.get(tokenString);
|
||||
|
||||
while(!tokenStack.empty()) {
|
||||
Match<TokenType> otherMatch = tokenStack.peek();
|
||||
if(otherMatch.getType() != TokenType.OP) break;
|
||||
|
||||
int otherPrecdence = precedenceMap.get(source.substring(otherMatch.getFrom(), otherMatch.getTo()));
|
||||
if(otherPrecdence < precedence ||
|
||||
(associativity == OperatorAssociativity.RIGHT && otherPrecdence == precedence)) {
|
||||
break;
|
||||
}
|
||||
output.add(tokenStack.pop());
|
||||
}
|
||||
tokenStack.push(match);
|
||||
} else if(match.getType() == TokenType.OPEN_PARENTH){
|
||||
tokenStack.push(match);
|
||||
} else if(match.getType() == TokenType.CLOSE_PARENTH){
|
||||
while(!tokenStack.empty() && tokenStack.peek().getType() != TokenType.OPEN_PARENTH){
|
||||
output.add(tokenStack.pop());
|
||||
}
|
||||
if(tokenStack.empty()) return null;
|
||||
tokenStack.pop();
|
||||
}
|
||||
}
|
||||
while(!tokenStack.empty()){
|
||||
if(!(tokenStack.peek().getType() == TokenType.OP)) return null;
|
||||
output.add(tokenStack.pop());
|
||||
}
|
||||
return output;
|
||||
}
|
||||
|
||||
/**
|
||||
* Constructs a tree recursively from a list of tokens.
|
||||
* @param source the source string.
|
||||
* @param matches the list of tokens from the source string.
|
||||
* @return the construct tree expression.
|
||||
*/
|
||||
public static TreeNode fromStringRecursive(String source, ArrayList<Match<TokenType>> matches){
|
||||
if(matches.size() == 0) return null;
|
||||
Match<TokenType> match = matches.remove(0);
|
||||
if(match.getType() == TokenType.OP){
|
||||
TreeNode right = fromStringRecursive(source, matches);
|
||||
TreeNode left = fromStringRecursive(source, matches);
|
||||
if(left == null || right == null) return null;
|
||||
else return new OpNode(source.substring(match.getFrom(), match.getTo()), left, right);
|
||||
} else if(match.getType() == TokenType.NUM){
|
||||
return new NumberNode(Double.parseDouble(source.substring(match.getFrom(), match.getTo())));
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a tree node from a string.
|
||||
* @param string the string to create a node from.
|
||||
* @return the resulting tree.
|
||||
*/
|
||||
public static TreeNode fromString(String string){
|
||||
ArrayList<Match<TokenType>> matches = tokenize(string);
|
||||
if(matches == null) return null;
|
||||
matches = intoPostfix(string, matches);
|
||||
if(matches == null) return null;
|
||||
|
||||
Collections.reverse(matches);
|
||||
return fromStringRecursive(string, matches);
|
||||
}
|
||||
|
||||
public abstract <T> T reduce(Reducer<T> reducer);
|
||||
|
||||
}
|
||||
|
||||
@@ -7,20 +7,34 @@ import javax.swing.table.AbstractTableModel;
|
||||
import javax.swing.table.TableModel;
|
||||
import java.util.ArrayList;
|
||||
|
||||
/**
|
||||
* 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;
|
||||
@@ -40,17 +54,27 @@ public class HistoryTableModel extends AbstractTableModel {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The list of entries.
|
||||
*/
|
||||
ArrayList<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
|
||||
@Override
|
||||
public int getRowCount() {
|
||||
return entries.size();
|
||||
}
|
||||
@@ -80,18 +104,4 @@ public class HistoryTableModel extends AbstractTableModel {
|
||||
return entries.get(rowIndex).nthValue(columnIndex);
|
||||
}
|
||||
|
||||
@Override
|
||||
public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
|
||||
return;
|
||||
}
|
||||
|
||||
@Override
|
||||
public void addTableModelListener(TableModelListener l) {
|
||||
|
||||
}
|
||||
|
||||
@Override
|
||||
public void removeTableModelListener(TableModelListener l) {
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,11 @@
|
||||
package org.nwapw.abacus.window;
|
||||
|
||||
import org.nwapw.abacus.function.Operator;
|
||||
import org.nwapw.abacus.number.NumberInterface;
|
||||
import org.nwapw.abacus.plugin.PluginListener;
|
||||
import org.nwapw.abacus.plugin.PluginManager;
|
||||
import org.nwapw.abacus.tree.NumberReducer;
|
||||
import org.nwapw.abacus.tree.TreeBuilder;
|
||||
import org.nwapw.abacus.tree.TreeNode;
|
||||
|
||||
import javax.swing.*;
|
||||
@@ -14,20 +18,30 @@ import java.awt.event.MouseEvent;
|
||||
/**
|
||||
* The main UI window for the calculator.
|
||||
*/
|
||||
public class Window extends JFrame {
|
||||
public class Window extends JFrame implements PluginListener {
|
||||
|
||||
private static final String CALC_STRING = "Calculate";
|
||||
private static final String SELECT_STRING = "Select";
|
||||
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
|
||||
};
|
||||
|
||||
private static boolean[] BUTTON_ENABLED = {
|
||||
/**
|
||||
* 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
|
||||
};
|
||||
@@ -36,6 +50,10 @@ public class Window extends JFrame {
|
||||
* The plugin manager used to retrieve functions.
|
||||
*/
|
||||
private PluginManager manager;
|
||||
/**
|
||||
* The builder used to construct the parse trees.
|
||||
*/
|
||||
private TreeBuilder builder;
|
||||
/**
|
||||
* The reducer used to evaluate the tree.
|
||||
*/
|
||||
@@ -112,18 +130,28 @@ public class Window extends JFrame {
|
||||
* Action listener that causes the input to be evaluated.
|
||||
*/
|
||||
private ActionListener evaluateListener = (event) -> {
|
||||
TreeNode parsedExpression = TreeNode.fromString(inputField.getText());
|
||||
if(builder == null) return;
|
||||
TreeNode parsedExpression = builder.fromString(inputField.getText());
|
||||
if(parsedExpression == null){
|
||||
lastOutputArea.setText(SYNTAX_ERR_STRING);
|
||||
return;
|
||||
}
|
||||
lastOutput = parsedExpression.reduce(reducer).toString();
|
||||
NumberInterface numberInterface = parsedExpression.reduce(reducer);
|
||||
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
|
||||
@@ -136,6 +164,7 @@ public class Window extends JFrame {
|
||||
public Window(PluginManager manager){
|
||||
this();
|
||||
this.manager = manager;
|
||||
manager.addListener(this);
|
||||
reducer = new NumberReducer(manager);
|
||||
}
|
||||
|
||||
@@ -198,7 +227,7 @@ public class Window extends JFrame {
|
||||
pane.add("Settings", settingsPanel);
|
||||
pane.addChangeListener(e -> {
|
||||
int selectionIndex = pane.getSelectedIndex();
|
||||
boolean enabled = BUTTON_ENABLED[selectionIndex];
|
||||
boolean enabled = INPUT_ENABLED[selectionIndex];
|
||||
ActionListener listener = listeners[selectionIndex];
|
||||
inputEnterButton.setText(BUTTON_NAMES[selectionIndex]);
|
||||
inputField.setEnabled(enabled);
|
||||
@@ -231,4 +260,21 @@ public class Window extends JFrame {
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onLoad(PluginManager manager) {
|
||||
builder = new TreeBuilder();
|
||||
for(String function : manager.getAllFunctions()){
|
||||
builder.registerFunction(function);
|
||||
}
|
||||
for(String operator : manager.getAllOperators()){
|
||||
Operator operatorObject = manager.operatorFor(operator);
|
||||
builder.registerOperator(operator, operatorObject.getPrecedence(), operatorObject.getAssociativity());
|
||||
}
|
||||
}
|
||||
|
||||
@Override
|
||||
public void onUnload(PluginManager manager) {
|
||||
builder = null;
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user