- Added documentation to some classes

- Created script provider system
- Did some refactoring to improve the API
This commit is contained in:
Stan Hebben committed 2014-06-10 21:12:55 +02:00
1 parent 38b78ce305
commit 97c7f42400
50 files changed
+1311 -318

No files matched your search

@@ -0,0 +1,21 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime;
import minetweaker.MineTweakerAPI;
/**
*
* @author Stan
*/
public class GlobalFunctions {
private GlobalFunctions() {}
public static void print(String message) {
MineTweakerAPI.logger.logInfo(message);
}
}
@@ -0,0 +1,296 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import minetweaker.IBracketHandler;
import minetweaker.IRecipeRemover;
import minetweaker.MineTweakerAPI;
import minetweaker.minecraft.item.IIngredient;
import stanhebben.zenscript.IZenErrorLogger;
import stanhebben.zenscript.TypeExpansion;
import stanhebben.zenscript.annotations.ZenExpansion;
import stanhebben.zenscript.compiler.ClassNameGenerator;
import stanhebben.zenscript.compiler.IEnvironmentGlobal;
import stanhebben.zenscript.compiler.TypeRegistry;
import stanhebben.zenscript.expression.partial.IPartialExpression;
import stanhebben.zenscript.parser.Token;
import stanhebben.zenscript.symbols.IZenCompileEnvironment;
import stanhebben.zenscript.symbols.IZenSymbol;
import stanhebben.zenscript.symbols.SymbolJavaStaticField;
import stanhebben.zenscript.symbols.SymbolJavaStaticMethod;
import stanhebben.zenscript.symbols.SymbolPackage;
import stanhebben.zenscript.type.ZenType;
import stanhebben.zenscript.type.ZenTypeNative;
import stanhebben.zenscript.type.natives.JavaMethod;
import stanhebben.zenscript.util.ZenPosition;
/**
*
* @author Stan
*/
public class GlobalRegistry {
private static final Map<String, IZenSymbol> globals = new HashMap<String, IZenSymbol>();
private static final List<IRecipeRemover> removers = new ArrayList<IRecipeRemover>();
private static final List<IBracketHandler> bracketHandlers = new ArrayList<IBracketHandler>();
private static final TypeRegistry types = new TypeRegistry();
private static final SymbolPackage root = new SymbolPackage();
private static final IZenErrorLogger errors = new MyErrorLogger();
private static final IZenCompileEnvironment environment = new MyCompileEnvironment();
private static final Map<String, TypeExpansion> expansions = new HashMap<String, TypeExpansion>();
static {
registerGlobal("print", getStaticFunction(GlobalFunctions.class, "print", String.class));
registerGlobal("max", getStaticFunction(Math.class, "max", int.class, int.class));
registerGlobal("min", getStaticFunction(Math.class, "min", int.class, int.class));
registerGlobal("logger", getStaticField(MineTweakerAPI.class, "logger"));
registerGlobal("minetweaker", getStaticField(MineTweakerAPI.class, "tweaker"));
registerGlobal("recipes", getStaticField(MineTweakerAPI.class, "recipes"));
registerGlobal("furnace", getStaticField(MineTweakerAPI.class, "furnace"));
registerGlobal("oreDict", getStaticField(MineTweakerAPI.class, "oreDict"));
/*registerExpansion(ExpandAnyArray.class);
registerExpansion(ExpandAnyDict.class);
registerExpansion(ExpandBool.class);
registerExpansion(ExpandByte.class);
registerExpansion(ExpandDouble.class);
registerExpansion(ExpandFloat.class);
registerExpansion(ExpandInt.class);
registerExpansion(ExpandLong.class);
registerExpansion(ExpandShort.class);
registerExpansion(ExpandString.class);*/
/*registerNativeClass(IData.class);
registerNativeClass(IIngredient.class);
registerNativeClass(IItemCondition.class);
registerNativeClass(IItemDefinition.class);
registerNativeClass(IItemStack.class);
registerNativeClass(IItemTransformer.class);
registerNativeClass(Condition.class);
registerNativeClass(Transform.class);
registerNativeClass(ILiquidDefinition.class);
registerNativeClass(ILiquidStack.class);
registerNativeClass(IOreDict.class);
registerNativeClass(IOreDictEntry.class);
registerNativeClass(ICraftingInventory.class);
registerNativeClass(IFurnaceManager.class);
registerNativeClass(IRecipeFunction.class);*/
}
private GlobalRegistry() {}
public static void registerGlobal(String name, IZenSymbol symbol) {
if (globals.containsKey(name)) {
throw new IllegalArgumentException("symbol already exists: " + name);
}
globals.put(name, symbol);
}
public static void registerExpansion(Class cls) {
for (Annotation annotation : cls.getAnnotationsByType(ZenExpansion.class)) {
ZenExpansion eAnnotation = (ZenExpansion) annotation;
if (!expansions.containsKey(eAnnotation.value())) {
expansions.put(eAnnotation.value(), new TypeExpansion());
}
expansions.get(eAnnotation.value()).expand(cls, types);
}
}
public static void registerRemover(IRecipeRemover remover) {
removers.add(remover);
}
public static void registerBracketHandler(IBracketHandler handler) {
bracketHandlers.add(handler);
}
public static void registerNativeClass(Class cls) {
ZenTypeNative type = new ZenTypeNative(cls);
type.complete(types);
root.put(type.getName(), root, errors);
}
public static TypeRegistry getTypeRegistry() {
return types;
}
public static void remove(IIngredient ingredient) {
for (IRecipeRemover remover : removers) {
remover.remove(ingredient);
}
}
public static IZenSymbol resolveBracket(List<Token> tokens) {
for (IBracketHandler handler : bracketHandlers) {
IZenSymbol symbol = handler.resolve(tokens);
if (symbol != null) {
return symbol;
}
}
return null;
}
public static IZenSymbol getStaticFunction(Class cls, String name, Class... arguments) {
JavaMethod method = JavaMethod.get(types, cls, name, arguments);
if (method == null) return null;
return new SymbolJavaStaticMethod(method);
}
public static IZenSymbol getStaticField(Class cls, String name) {
try {
Field field = cls.getDeclaredField(name);
return new SymbolJavaStaticField(cls, field, types);
} catch (NoSuchFieldException ex) {
Logger.getLogger(GlobalRegistry.class.getName()).log(Level.SEVERE, null, ex);
return null;
} catch (SecurityException ex) {
Logger.getLogger(GlobalRegistry.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
public static IEnvironmentGlobal makeGlobalEnvironment(Map<String, byte[]> classes) {
return new MyGlobalEnvironment(classes);
}
private static class MyErrorLogger implements IZenErrorLogger {
@Override
public void error(ZenPosition position, String message) {
MineTweakerAPI.logger.logError(position.toString() + ": " + message);
}
@Override
public void warning(ZenPosition position, String message) {
MineTweakerAPI.logger.logWarning(position.toString() + ": " + message);
}
}
private static class MyCompileEnvironment implements IZenCompileEnvironment {
@Override
public IZenErrorLogger getErrorLogger() {
return errors;
}
@Override
public IZenSymbol getGlobal(String name) {
if (globals.containsKey(name)) {
return globals.get(name);
} else {
return root.get(name);
}
}
@Override
public IZenSymbol getDollar(String name) {
return null;
}
@Override
public IZenSymbol getBracketed(List<Token> tokens) {
return resolveBracket(tokens);
}
@Override
public TypeRegistry getTypeRegistry() {
return types;
}
@Override
public TypeExpansion getExpansion(String type) {
return expansions.get(type);
}
}
private static class MyGlobalEnvironment implements IEnvironmentGlobal {
private final Map<String, byte[]> classes;
private final Map<String, IZenSymbol> symbols;
private final ClassNameGenerator generator;
public MyGlobalEnvironment(Map<String, byte[]> classes) {
this.classes = classes;
symbols = new HashMap<String, IZenSymbol>();
generator = new ClassNameGenerator();
}
@Override
public IZenCompileEnvironment getEnvironment() {
return environment;
}
@Override
public TypeExpansion getExpansion(String name) {
return expansions.get(name);
}
@Override
public String makeClassName() {
return generator.generate();
}
@Override
public boolean containsClass(String name) {
return classes.containsKey(name);
}
@Override
public void putClass(String name, byte[] data) {
classes.put(name, data);
}
@Override
public IPartialExpression getValue(String name, ZenPosition position) {
if (symbols.containsKey(name)) {
return symbols.get(name).instance(position);
} else if (globals.containsKey(name)) {
return globals.get(name).instance(position);
} else {
IZenSymbol pkg = root.get(name);
if (pkg == null) {
return null;
} else {
return pkg.instance(position);
}
}
}
@Override
public void putValue(String name, IZenSymbol value) {
symbols.put(name, value);
}
@Override
public ZenType getType(Type type) {
return types.getType(type);
}
@Override
public void error(ZenPosition position, String message) {
MineTweakerAPI.logger.logError("[" + position.getFile() + ":" + position.getLine() + "] Error: " + message);
}
@Override
public void warning(ZenPosition position, String message) {
MineTweakerAPI.logger.logWarning("[" + position.getFile() + ":" + position.getLine() + "] Warning: " + message);
}
}
}
@@ -0,0 +1,24 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime;
import stanhebben.zenscript.annotations.ZenMethod;
/**
*
* @author Stan
*/
public interface ILogger {
@ZenMethod
public void logInfo(String message);
@ZenMethod
public void logWarning(String message);
@ZenMethod
public void logError(String message);
}
@@ -0,0 +1,56 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime;
import java.io.Closeable;
import java.util.List;
import minetweaker.IUndoableAction;
import minetweaker.minecraft.item.IIngredient;
import stanhebben.zenscript.annotations.ZenClass;
import stanhebben.zenscript.annotations.ZenMethod;
/**
*
* @author Stan
*/
@ZenClass("minetweaker.MineTweaker")
public interface IMineTweaker {
/**
* Executes a specified MineTweaker action. Will print a log message and
* adds the action to the undo list.
*
* @param action action to execute
*/
public void apply(IUndoableAction action);
/**
* Removes a specific item from all known recipes handlers.
*
* @param items items to remove
*/
@ZenMethod
public void remove(IIngredient items);
/**
* Rolls back all actions performed by MineTweaker. Returns the list of
* actions that could not be rolled back (the "stuck" ones that are not
* undoable).
*
* @return stuck action list
*/
public List<IUndoableAction> rollback();
/**
* Registers a script provider.
*
* @param provider
* @return
*/
public Closeable registerScriptProvider(IScriptProvider provider);
public void load();
}
@@ -0,0 +1,24 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author Stan
*/
public interface IScriptIterator {
public String getGroupName();
public boolean next();
public String getName();
public InputStream open() throws IOException;
}
@@ -0,0 +1,17 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime;
import java.util.Iterator;
/**
*
* @author Stan
*/
public interface IScriptProvider {
public Iterator<IScriptIterator> getScripts();
}
@@ -0,0 +1,125 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime;
import java.io.BufferedInputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import minetweaker.IUndoableAction;
import minetweaker.MineTweakerAPI;
import minetweaker.minecraft.item.IIngredient;
import minetweaker.minecraft.util.CloseablePriorityList;
import stanhebben.zenscript.ZenModule;
import static stanhebben.zenscript.ZenModule.compileScripts;
import static stanhebben.zenscript.ZenModule.extractClassName;
import stanhebben.zenscript.ZenParsedFile;
import stanhebben.zenscript.ZenTokener;
import stanhebben.zenscript.compiler.IEnvironmentGlobal;
/**
*
*
* @author Stan Hebben
*/
public class Tweaker implements IMineTweaker {
private final CloseablePriorityList<IScriptProvider> scriptProviders = new CloseablePriorityList<IScriptProvider>();
private final List<IUndoableAction> actions = new ArrayList<IUndoableAction>();
private final Set<IUndoableAction> wereStuck = new HashSet<IUndoableAction>();
@Override
public void apply(IUndoableAction action) {
MineTweakerAPI.logger.logInfo(action.describe());
action.apply();
}
@Override
public void remove(IIngredient items) {
GlobalRegistry.remove(items);
}
@Override
public List<IUndoableAction> rollback() {
List<IUndoableAction> stuck = new ArrayList<IUndoableAction>();
for (int i = actions.size() - 1; i >= 0; i--) {
IUndoableAction action = actions.get(i);
if (action.canUndo()) {
MineTweakerAPI.logger.logInfo(action.describeUndo());
action.undo();
} else {
stuck.add(0, action);
wereStuck.add(action);
}
}
actions.clear();
return stuck;
}
@Override
public Closeable registerScriptProvider(IScriptProvider provider) {
return scriptProviders.add(provider);
}
@Override
public void load() {
Set<String> executed = new HashSet<String>();
for (IScriptProvider provider : scriptProviders) {
Iterator<IScriptIterator> scripts = provider.getScripts();
while (scripts.hasNext()) {
IScriptIterator script = scripts.next();
if (!executed.contains(script.getGroupName())) {
executed.add(script.getGroupName());
Map<String, byte[]> classes = new HashMap<String, byte[]>();
IEnvironmentGlobal environmentGlobal = GlobalRegistry.makeGlobalEnvironment(classes);
List<ZenParsedFile> files = new ArrayList<ZenParsedFile>();
while (script.next()) {
try {
String filename = script.getName();
String className = extractClassName(filename);
Reader reader = new InputStreamReader(new BufferedInputStream(script.open()));
ZenTokener parser = new ZenTokener(reader, environmentGlobal.getEnvironment());
ZenParsedFile pfile = new ZenParsedFile(filename, className, parser, environmentGlobal);
files.add(pfile);
reader.close();
} catch (IOException ex) {
MineTweakerAPI.logger.logError("Could not load script " + script.getName() + ": " + ex.getMessage());
}
}
String filename = script.getGroupName();
compileScripts(filename, files, environmentGlobal);
// execute scripts
ZenModule module = new ZenModule(classes);
module.getMain().run();
}
}
}
if (wereStuck.size() > 0) {
MineTweakerAPI.logger.logWarning(Integer.toString(wereStuck.size()) + " modifications were stuck");
for (IUndoableAction action : wereStuck) {
MineTweakerAPI.logger.logInfo("Stuck: " + action.describe());
}
}
}
}
@@ -0,0 +1,73 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime.providers;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import minetweaker.runtime.IScriptIterator;
/**
*
* @author Stan
*/
public class ScriptIteratorDirectory implements IScriptIterator {
private final File directory;
private Iterator<File> contents;
private File current;
public ScriptIteratorDirectory(File directory) {
this.directory = directory;
File scriptDir = new File(directory, "scripts");
List<File> contentsList = new ArrayList<File>();
if (scriptDir.exists()) {
iterate(scriptDir, contentsList);
}
contents = contentsList.iterator();
}
@Override
public String getGroupName() {
return directory.getName();
}
@Override
public boolean next() {
if (contents.hasNext()) {
current = contents.next();
return true;
} else {
return false;
}
}
@Override
public String getName() {
return current.getAbsolutePath().substring(directory.getAbsolutePath().length());
}
@Override
public InputStream open() throws IOException {
return new BufferedInputStream(new FileInputStream(current));
}
private static void iterate(File directory, List<File> contentsList) {
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
iterate(file, contentsList);
} else if (file.isFile() && file.getName().endsWith(".zs")) {
contentsList.add(file);
}
}
}
}
@@ -0,0 +1,52 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime.providers;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import minetweaker.runtime.IScriptIterator;
/**
*
* @author Stan
*/
public class ScriptIteratorSingle implements IScriptIterator {
private final File file;
private boolean first = true;
public ScriptIteratorSingle(File file) {
this.file = file;
}
@Override
public String getGroupName() {
return file.getName();
}
@Override
public boolean next() {
if (first) {
first = false;
return true;
} else {
return false;
}
}
@Override
public String getName() {
return file.getName();
}
@Override
public InputStream open() throws IOException {
return new BufferedInputStream(new FileInputStream(file));
}
}
@@ -0,0 +1,70 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime.providers;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import minetweaker.runtime.IScriptIterator;
/**
*
* @author Stan
*/
public class ScriptIteratorZip implements IScriptIterator {
private final File file;
private final ZipFile zipFile;
private final Iterator<ZipEntry> entries;
private ZipEntry current;
public ScriptIteratorZip(File file) throws IOException {
this.file = file;
zipFile = new ZipFile(file);
List<ZipEntry> entriesList = new ArrayList<ZipEntry>();
Enumeration<? extends ZipEntry> original = zipFile.entries();
while (original.hasMoreElements()) {
ZipEntry entry = original.nextElement();
if (entry.getName().startsWith("scripts/") && entry.getName().endsWith(".zs")) {
entriesList.add(entry);
}
}
entries = entriesList.iterator();
}
@Override
public String getGroupName() {
return file.getName().substring(0, file.getName().lastIndexOf('.'));
}
@Override
public boolean next() {
if (entries.hasNext()) {
current = entries.next();
return true;
} else {
return false;
}
}
@Override
public String getName() {
return current.getName().substring("scripts/".length());
}
@Override
public InputStream open() throws IOException {
return zipFile.getInputStream(current);
}
}
@@ -0,0 +1,47 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime.providers;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import minetweaker.MineTweakerAPI;
import minetweaker.runtime.IScriptIterator;
import minetweaker.runtime.IScriptProvider;
/**
*
* @author Stan
*/
public class ScriptProviderDirectory implements IScriptProvider {
private final File directory;
public ScriptProviderDirectory(File directory) {
this.directory = directory;
}
@Override
public Iterator<IScriptIterator> getScripts() {
List<IScriptIterator> scripts = new ArrayList<IScriptIterator>();
for (File file : directory.listFiles()) {
if (file.isDirectory()) {
scripts.add(new ScriptIteratorDirectory(file));
} else if (file.getName().endsWith(".zs")) {
scripts.add(new ScriptIteratorSingle(file));
} else if (file.getName().endsWith(".zip")) {
try {
scripts.add(new ScriptIteratorZip(file));
} catch (IOException ex) {
MineTweakerAPI.logger.logError("Could not load " + file.getName() + ": " + ex.getMessage());
}
}
}
return scripts.iterator();
}
}
@@ -0,0 +1,106 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package minetweaker.runtime.providers;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.zip.DeflaterOutputStream;
import java.util.zip.InflaterInputStream;
import minetweaker.MineTweakerAPI;
import minetweaker.minecraft.util.FileUtil;
import minetweaker.runtime.IScriptIterator;
import minetweaker.runtime.IScriptProvider;
/**
*
* @author Stan
*/
public class ScriptProviderMemory {
public static byte[] collect(Iterable<IScriptProvider> providers) {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
DeflaterOutputStream deflater = new DeflaterOutputStream(output);
DataOutputStream deflaterData = new DataOutputStream(deflater);
Set<String> executed = new HashSet<String>();
for (IScriptProvider provider : providers) {
Iterator<IScriptIterator> scripts = provider.getScripts();
while (scripts.hasNext()) {
IScriptIterator script = scripts.next();
if (!executed.contains(script.getGroupName())) {
executed.add(script.getGroupName());
deflaterData.writeUTF(script.getGroupName());
while (script.next()) {
String name = script.getName();
byte[] data = FileUtil.read(script.open());
deflaterData.writeUTF(name);
deflaterData.writeInt(data.length);
deflaterData.write(data);
}
deflaterData.writeUTF("");
}
}
}
deflaterData.writeUTF("");
deflater.close();
} catch (IOException ex) {
MineTweakerAPI.logger.logError("Could not collect scripts: " + ex.getMessage());
}
return output.toByteArray();
}
public ScriptProviderMemory(byte[] scripts) {
try {
InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(scripts));
DataInputStream inflaterData = new DataInputStream(inflater);
String moduleName = inflaterData.readUTF();
while (moduleName.length() > 0) {
List<MemoryFile> files = new ArrayList<MemoryFile>();
String fileName = inflaterData.readUTF();
while (fileName.length() > 0) {
byte[] data = new byte[inflaterData.readInt()];
inflaterData.readFully(data);
files.add(new MemoryFile(fileName, data));
fileName = inflaterData.readUTF();
}
moduleName = inflaterData.readUTF();
}
inflaterData.close();
} catch (IOException ex) {
MineTweakerAPI.logger.logError("Could not load transmitted scripts: " + ex.getMessage());
}
}
private class MemoryFile {
private final String name;
private final byte[] data;
public MemoryFile(String name, byte[] data) {
this.name = name;
this.data = data;
}
}
}