diff --git a/MineTweaker3-API/src/main/java/minetweaker/IBracketHandler.java b/MineTweaker3-API/src/main/java/minetweaker/IBracketHandler.java index 616449e..a61fe75 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/IBracketHandler.java +++ b/MineTweaker3-API/src/main/java/minetweaker/IBracketHandler.java @@ -8,9 +8,9 @@ import stanhebben.zenscript.symbols.IZenSymbol; /** * Bracket handlers enable processing of the bracket syntax. * - * Inside brackets, any kind of token is acceptable except the closing bracket. (>) - * Bracket handlers (multiple handlers can be registered) will resolve these - * tokens into actual values. Values have to be ZenScript symbols and will + * Inside brackets, any kind of token is acceptable except the closing bracket. + * (>) Bracket handlers (multiple handlers can be registered) will resolve + * these tokens into actual values. Values have to be ZenScript symbols and will * resolve at compile-time. * * These may of course return an expression that are executed on run-time, but diff --git a/MineTweaker3-API/src/main/java/minetweaker/IPlatformFunctions.java b/MineTweaker3-API/src/main/java/minetweaker/IPlatformFunctions.java index 08b1f8f..9836999 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/IPlatformFunctions.java +++ b/MineTweaker3-API/src/main/java/minetweaker/IPlatformFunctions.java @@ -4,8 +4,8 @@ import minetweaker.api.chat.IChatMessage; import minetweaker.api.item.IItemDefinition; /** - * Platform functions are a set of internal functions implemented by the platform - * intended to communicate between API and implementation. + * Platform functions are a set of internal functions implemented by the + * platform intended to communicate between API and implementation. * * @author Stan Hebben */ @@ -17,7 +17,7 @@ public interface IPlatformFunctions { * @return chat message */ public IChatMessage getMessage(String message); - + /** * Distributes the given script data to all connected clients. Automatically * reloads the scripts from this data. @@ -25,7 +25,7 @@ public interface IPlatformFunctions { * @param data data to be distributed */ public void distributeScripts(byte[] data); - + /** * Finds the item definition with the given ID. * diff --git a/MineTweaker3-API/src/main/java/minetweaker/IRecipeRemover.java b/MineTweaker3-API/src/main/java/minetweaker/IRecipeRemover.java index 059bcef..cfb0654 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/IRecipeRemover.java +++ b/MineTweaker3-API/src/main/java/minetweaker/IRecipeRemover.java @@ -3,8 +3,8 @@ package minetweaker; import minetweaker.api.item.IIngredient; /** - * Used to register removable mod recipes for mod machines. Once registered, - * it will be called when minetweaker.remove() is called. + * Used to register removable mod recipes for mod machines. Once registered, it + * will be called when minetweaker.remove() is called. * * @author Stan Hebben */ diff --git a/MineTweaker3-API/src/main/java/minetweaker/IUndoableAction.java b/MineTweaker3-API/src/main/java/minetweaker/IUndoableAction.java index 72daf66..f860dfc 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/IUndoableAction.java +++ b/MineTweaker3-API/src/main/java/minetweaker/IUndoableAction.java @@ -27,48 +27,48 @@ public interface IUndoableAction { * again if undo() has been called in between. */ public void apply(); - + /** - * Checks if this action can be undone. If this method returns true, it - * must implement undo() properly. If this method returns false, the action - * is considered permanent, undo() will never be called, and the action - * cannot be executed as part of a server script. Additionally, the - * minetweaker.clear() function will not work and minetweaker.canClear - * will return false. + * Checks if this action can be undone. If this method returns true, it must + * implement undo() properly. If this method returns false, the action is + * considered permanent, undo() will never be called, and the action cannot + * be executed as part of a server script. Additionally, the + * minetweaker.clear() function will not work and minetweaker.canClear will + * return false. * * @return undoable status */ public boolean canUndo(); - + /** * Undoes the action. Will only be called after apply() has been executed. * After an undo, apply may be called again. They could be done multiple * times in certain scenarios. */ public void undo(); - + /** * Describes, in a single human-readable sentence, what this specific action * is doing. Used in logging messages, lists, ... * * Try to be as descriptive as possible without being too verbose. * - * Examples: - * - Adding Peach planks to the woodPlanks ore dictionary entry - * - Removing a recipe for Iron Ore + * Examples: - Adding Peach planks to the woodPlanks ore dictionary entry - + * Removing a recipe for Iron Ore * * @return the description of this action */ public String describe(); - + /** - * Describes what this action does if it is undone. Similar to the describe() - * method. No implementation is needed if the action cannot be undone. + * Describes what this action does if it is undone. Similar to the + * describe() method. No implementation is needed if the action cannot be + * undone. * * @return the description of this action, when undone */ public String describeUndo(); - + /** * Returns the override key. Two actions are considered to override each * other if their override key is equal. You can return null to indicate @@ -77,7 +77,8 @@ public interface IUndoableAction { * This value only makes sense for recipes that are not undoable. For * undoable recipes, you should return null. * - * @return override key (null for actions that are undoable or which can never be overridden by another action) + * @return override key (null for actions that are undoable or which can + * never be overridden by another action) */ public Object getOverrideKey(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/MineTweakerAPI.java b/MineTweaker3-API/src/main/java/minetweaker/MineTweakerAPI.java index 5b79455..11617cd 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/MineTweakerAPI.java +++ b/MineTweaker3-API/src/main/java/minetweaker/MineTweakerAPI.java @@ -38,50 +38,45 @@ import stanhebben.zenscript.type.natives.JavaMethod; /** * Provides access to the MineTweaker API. * - * An implementing platform needs to do the following: - * - Set a logger - * - Set the ore dictionary - * - Set the recipe manager - * - Set the furnace manager - * - Set event manager - * - Set resource manager + * An implementing platform needs to do the following: - Set a logger - Set the + * ore dictionary - Set the recipe manager - Set the furnace manager - Set event + * manager - Set resource manager * * - Register additional global symbols to the GlobalRegistry (recipes, - * minetweaker, oreDict, logger, as well as the official set of functions) - * - Register native classes using the GlobalRegistry - * - Register bracket handlers to resolve block/item/... references using the - * bracket syntax + * minetweaker, oreDict, logger, as well as the official set of functions) - + * Register native classes using the GlobalRegistry - Register bracket handlers + * to resolve block/item/... references using the bracket syntax * * @author Stan Hebben */ public class MineTweakerAPI { public static final String[] COLOR_NAMES = { - "White", - "Orange", - "Magenta", - "Light Blue", - "Yellow", - "Lime", - "Pink", - "Gray", - "Light Gray", - "Cyan", - "Purple", - "Blue", - "Brown", - "Green", - "Red", - "Black" + "White", + "Orange", + "Magenta", + "Light Blue", + "Yellow", + "Lime", + "Pink", + "Gray", + "Light Gray", + "Cyan", + "Purple", + "Blue", + "Brown", + "Green", + "Red", + "Black" }; - + static { List apiClasses = new ArrayList(); ClassRegistry.getClasses(apiClasses); - + for (Class cls : apiClasses) { registerClass(cls); } - + registerGlobalSymbol("logger", getJavaStaticGetterSymbol(MineTweakerAPI.class, "getLogger")); registerGlobalSymbol("recipes", getJavaStaticFieldSymbol(MineTweakerAPI.class, "recipes")); registerGlobalSymbol("furnace", getJavaStaticFieldSymbol(MineTweakerAPI.class, "furnace")); @@ -94,26 +89,27 @@ public class MineTweakerAPI { registerGlobalSymbol("format", getJavaStaticFieldSymbol(MineTweakerAPI.class, "format")); registerGlobalSymbol("vanilla", getJavaStaticFieldSymbol(MineTweakerAPI.class, "vanilla")); } - - private MineTweakerAPI() {} - + + private MineTweakerAPI() { + } + /** * The Tweaker is where you apply undoable actions. Any kind of action that * reloads with the scripts should always be submitted to the tweaker. */ @Deprecated public static final ITweaker tweaker = new MTTweaker(); - + /** * The logger can be used to write logging messages to the client. Error and * warning messages should be relayed to admins for further handling. * - * @return + * @return */ public static final ILogger getLogger() { return MineTweakerImplementationAPI.logger; } - + /** * Access point to the ore dictionary. */ @@ -123,47 +119,47 @@ public class MineTweakerAPI { * Access point to the recipe manager. */ public static IRecipeManager recipes = null; - + /** * Access point to the furnace manager. */ public static IFurnaceManager furnace = null; - + /** * Access point to the events manager. */ public static final IEventManager events = MineTweakerImplementationAPI.events; - + /** * Access point to the server, if any. */ public static IServer server = null; - + /** * Access point to the client, if any. */ public static IClient client = null; - + /** * Access point to general game data, such as items. */ public static IGame game = null; - + /** * Access point to mods list. */ public static ILoadedMods loadedMods = null; - + /** * Access point to the text formatter. */ public static IFormatter format = null; - + /** * Access point to the vanilla functions and data. */ public static IVanilla vanilla = null; - + /** * Applies this given action. * @@ -172,7 +168,7 @@ public class MineTweakerAPI { public static void apply(IUndoableAction action) { tweaker.apply(action); } - + /** * Logs a command message. Commands messages are those generated as output * in response to a command. @@ -182,7 +178,7 @@ public class MineTweakerAPI { public static void logCommand(String message) { getLogger().logCommand(message); } - + /** * Logs an info message. Info messages have low priority and will only be * displayed in the log files, but not directly to players in-game. @@ -192,7 +188,7 @@ public class MineTweakerAPI { public static void logInfo(String message) { getLogger().logInfo(message); } - + /** * Logs a warning message. Warning messages are displayed to admins and * indicate that there is an issue. However, the issue is not a large @@ -204,24 +200,24 @@ public class MineTweakerAPI { public static void logWarning(String message) { getLogger().logWarning(message); } - + /** * Logs an error message. Error messages indicate a real problem and - * indicate that things won't run properly. The scripting system will - * still make a best-effort attempt at executing the rest of the scripts, - * but that might cause additional errors and issues. + * indicate that things won't run properly. The scripting system will still + * make a best-effort attempt at executing the rest of the scripts, but that + * might cause additional errors and issues. * * @param message error message */ public static void logError(String message) { getLogger().logError(message); } - + /** * Logs an error message. Error messages indicate a real problem and - * indicate that things won't run properly. The scripting system will - * still make a best-effort attempt at executing the rest of the scripts, - * but that might cause additional errors and issues. + * indicate that things won't run properly. The scripting system will still + * make a best-effort attempt at executing the rest of the scripts, but that + * might cause additional errors and issues. * * @param message error message * @param exception exception that was caught related to the error @@ -229,29 +225,29 @@ public class MineTweakerAPI { public static void logError(String message, Throwable exception) { getLogger().logError(message, exception); } - + // ################################### // ### Plugin registration methods ### // ################################### - + /** * Register a class registry class. Such class must have (at least) a public - * static method called "getClasses" with accepts a List of classes and which - * stores its classes into that list. + * static method called "getClasses" with accepts a List of classes and + * which stores its classes into that list. * - * @param registryClass + * @param registryClass */ public static void registerClassRegistry(Class registryClass) { registerClassRegistry(registryClass, null); } - + /** * Register a class registry class. Such class must have (at least) a public - * static method called "getClasses" with accepts a List of classes and which - * stores its classes into that list. + * static method called "getClasses" with accepts a List of classes and + * which stores its classes into that list. * - * @param registryClass - * @param description + * @param registryClass + * @param description */ public static void registerClassRegistry(Class registryClass, String description) { try { @@ -261,26 +257,26 @@ public class MineTweakerAPI { } else { List classes = new ArrayList(); method.invoke(null, classes); - + outer: for (Class cls : classes) { for (Annotation annotation : cls.getAnnotations()) { if (annotation instanceof ModOnly) { String[] value = ((ModOnly) annotation).value(); String version = ((ModOnly) annotation).version(); - + for (String mod : value) { if (!loadedMods.contains(mod)) continue outer; - + if (!loadedMods.get(mod).getVersion().startsWith(version)) continue outer; } } } - + MineTweakerAPI.registerClass(cls); } - + if (description != null) System.out.println("Loaded class registry: " + description); } @@ -292,10 +288,10 @@ public class MineTweakerAPI { } } - + /** - * Registers a class registry. Will attempt to resolve the given class - * name. Does nothing if the class could not be loaded. + * Registers a class registry. Will attempt to resolve the given class name. + * Does nothing if the class could not be loaded. * * @param className class name to be loaded * @return true if registration was successful @@ -303,10 +299,10 @@ public class MineTweakerAPI { public static boolean registerClassRegistry(String className) { return registerClassRegistry(className, null); } - + /** - * Registers a class registry. Will attempt to resolve the given class - * name. Does nothing if the class could not be loaded. + * Registers a class registry. Will attempt to resolve the given class name. + * Does nothing if the class could not be loaded. * * @param className class name to be loaded * @param description @@ -320,26 +316,26 @@ public class MineTweakerAPI { return false; } } - + /** * Registers an annotated class. A class is annotated with either @ZenClass * or @ZenExpansion. Classes not annotated with either of these will be * ignored. * - * @param annotatedClass + * @param annotatedClass */ public static void registerClass(Class annotatedClass) { - //System.out.println("Registering " + annotatedClass.getName()); - + // System.out.println("Registering " + annotatedClass.getName()); + for (Annotation annotation : annotatedClass.getAnnotations()) { if (annotation instanceof ZenExpansion) { GlobalRegistry.registerExpansion(annotatedClass); } - + if (annotation instanceof ZenClass) { GlobalRegistry.registerNativeClass(annotatedClass); } - + if ((annotation instanceof BracketHandler) && IBracketHandler.class.isAssignableFrom(annotatedClass)) { try { IBracketHandler bracketHandler = (IBracketHandler) annotatedClass.newInstance(); @@ -352,7 +348,7 @@ public class MineTweakerAPI { } } } - + /** * Registers a global symbol. Global symbols are immediately accessible from * anywhere in the scripts. @@ -363,7 +359,7 @@ public class MineTweakerAPI { public static void registerGlobalSymbol(String name, IZenSymbol symbol) { GlobalRegistry.registerGlobal(name, symbol); } - + /** * Registers a recipe remover. Removers are called when the global * minetweaker.remove() function is called. @@ -373,18 +369,18 @@ public class MineTweakerAPI { public static void registerRemover(IRecipeRemover remover) { GlobalRegistry.registerRemover(remover); } - + /** * Registers a bracket handler. Is capable of converting the bracket syntax - * to an actual value. This new handler will be added last - it can thus - * not intercept values that are already handled by the system. + * to an actual value. This new handler will be added last - it can thus not + * intercept values that are already handled by the system. * * @param handler bracket handler to be added */ public static void registerBracketHandler(IBracketHandler handler) { GlobalRegistry.registerBracketHandler(handler); } - + /** * Creates a symbol that refers to a java method. * @@ -397,11 +393,11 @@ public class MineTweakerAPI { IJavaMethod method = JavaMethod.get(GlobalRegistry.getTypeRegistry(), cls, name, arguments); return new SymbolJavaStaticMethod(method); } - + /** - * Creates a symbol that refers to a java getter. The getter must be a method - * with no arguments. The given symbol will act as a variable of which the - * value can be retrieved but not set. + * Creates a symbol that refers to a java getter. The getter must be a + * method with no arguments. The given symbol will act as a variable of + * which the value can be retrieved but not set. * * @param cls class that contains the getter method * @param name name of the method @@ -411,7 +407,7 @@ public class MineTweakerAPI { IJavaMethod method = JavaMethod.get(GlobalRegistry.getTypeRegistry(), cls, name); return new SymbolJavaStaticGetter(method); } - + /** * Creates a symbol that refers to a static field. The field must be an * existing public field in the given class. The field will act as a @@ -431,7 +427,7 @@ public class MineTweakerAPI { return null; } } - + /** * Loads a Java method from an existing class. * diff --git a/MineTweaker3-API/src/main/java/minetweaker/MineTweakerImplementation.java b/MineTweaker3-API/src/main/java/minetweaker/MineTweakerImplementation.java index d5bb018..2f63b5c 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/MineTweakerImplementation.java +++ b/MineTweaker3-API/src/main/java/minetweaker/MineTweakerImplementation.java @@ -11,5 +11,5 @@ package minetweaker; * @author Stan */ public class MineTweakerImplementation { - + } diff --git a/MineTweaker3-API/src/main/java/minetweaker/OneWayAction.java b/MineTweaker3-API/src/main/java/minetweaker/OneWayAction.java index 720028e..d10a30b 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/OneWayAction.java +++ b/MineTweaker3-API/src/main/java/minetweaker/OneWayAction.java @@ -12,7 +12,8 @@ public abstract class OneWayAction implements IUndoableAction { } @Override - public void undo() {} + public void undo() { + } @Override public String describeUndo() { diff --git a/MineTweaker3-API/src/main/java/minetweaker/annotations/BracketHandler.java b/MineTweaker3-API/src/main/java/minetweaker/annotations/BracketHandler.java index 5fbeaed..5c1ddfb 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/annotations/BracketHandler.java +++ b/MineTweaker3-API/src/main/java/minetweaker/annotations/BracketHandler.java @@ -6,20 +6,20 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Marks a bracket handler. Bracket handlers are automatically registered. - * The marked class should have an empty constructor. + * Marks a bracket handler. Bracket handlers are automatically registered. The + * marked class should have an empty constructor. * * @author Stan Hebben */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE}) +@Target({ ElementType.TYPE }) public @interface BracketHandler { /** - * Indicates priority. A lower value means a higher priority. Only change - * if you have issues, default value is 10. Internal minetweaker handlers - * have priorities up to 100. + * Indicates priority. A lower value means a higher priority. Only change if + * you have issues, default value is 10. Internal minetweaker handlers have + * priorities up to 100. * - * @return + * @return */ public int priority() default 10; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/annotations/ModOnly.java b/MineTweaker3-API/src/main/java/minetweaker/annotations/ModOnly.java index 8d49b19..8d0494c 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/annotations/ModOnly.java +++ b/MineTweaker3-API/src/main/java/minetweaker/annotations/ModOnly.java @@ -6,14 +6,15 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Indicates that a certain class is only available when a specific mod is + * Indicates that a certain class is only available when a specific mod is * available. Multiple mods can be specified. * * @author Stan Hebben */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) public @interface ModOnly { public String[] value(); + public String version() default ""; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/annotations/OnRegister.java b/MineTweaker3-API/src/main/java/minetweaker/annotations/OnRegister.java index cbb9795..45c591b 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/annotations/OnRegister.java +++ b/MineTweaker3-API/src/main/java/minetweaker/annotations/OnRegister.java @@ -16,7 +16,7 @@ import java.lang.annotation.Target; * @author Stan */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.METHOD}) +@Target({ ElementType.METHOD }) public @interface OnRegister { - + } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/block/BlockPatternOr.java b/MineTweaker3-API/src/main/java/minetweaker/api/block/BlockPatternOr.java index e50f187..955f3b3 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/block/BlockPatternOr.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/block/BlockPatternOr.java @@ -16,13 +16,13 @@ import minetweaker.util.ArrayUtil; */ public class BlockPatternOr implements IBlockPattern { private final IBlockPattern[] elements; - + public BlockPatternOr(IBlockPattern[] elements) { this.elements = elements; } - + public BlockPatternOr(IBlockPattern a, IBlockPattern b) { - this.elements = new IBlockPattern[] {a, b}; + this.elements = new IBlockPattern[] { a, b }; } @Override @@ -40,7 +40,7 @@ public class BlockPatternOr implements IBlockPattern { if (pattern.matches(block)) return true; } - + return false; } @@ -54,10 +54,10 @@ public class BlockPatternOr implements IBlockPattern { } else { result.append(" | "); } - + result.append(pattern.getDisplayName()); } - + return result.toString(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlock.java b/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlock.java index 938277f..aa8edf9 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlock.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlock.java @@ -18,10 +18,10 @@ public interface IBlock extends IBlockPattern { */ @ZenGetter("definition") public IBlockDefinition getDefinition(); - + @ZenGetter("meta") public int getMeta(); - + @ZenGetter("data") public IData getTileData(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlockDefinition.java b/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlockDefinition.java index f6fa0dc..6439b9d 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlockDefinition.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlockDefinition.java @@ -12,7 +12,7 @@ import stanhebben.zenscript.annotations.ZenGetter; public interface IBlockDefinition { @ZenGetter("id") public String getId(); - + @ZenGetter("displayName") public String getDisplayName(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlockPattern.java b/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlockPattern.java index 41af7b1..1e7c970 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlockPattern.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/block/IBlockPattern.java @@ -21,14 +21,14 @@ import stanhebben.zenscript.annotations.ZenOperator; public interface IBlockPattern { @ZenMethod("blocks") public List getBlocks(); - + @ZenOperator(OperatorType.CONTAINS) public boolean matches(IBlock block); - + @ZenOperator(OperatorType.OR) public IBlockPattern or(IBlockPattern pattern); - + @ZenGetter("displayName") public String getDisplayName(); - + } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/chat/IChatMessage.java b/MineTweaker3-API/src/main/java/minetweaker/api/chat/IChatMessage.java index f771140..57af335 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/chat/IChatMessage.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/chat/IChatMessage.java @@ -5,8 +5,8 @@ import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenOperator; /** - * Represents a chat message. Strings can be converted into chat messages, - * and chat messages can be colored and concatenated. + * Represents a chat message. Strings can be converted into chat messages, and + * chat messages can be colored and concatenated. * * @author Stan Hebben */ @@ -20,10 +20,10 @@ public interface IChatMessage { */ @ZenOperator(OperatorType.ADD) public IChatMessage add(IChatMessage other); - + /** - * Retrieves the internal object backing this object. Must be generated by the - * implementing platform. + * Retrieves the internal object backing this object. Must be generated by + * the implementing platform. * * @return internal object */ diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/client/IClient.java b/MineTweaker3-API/src/main/java/minetweaker/api/client/IClient.java index 1fb8888..621e424 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/client/IClient.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/client/IClient.java @@ -18,7 +18,7 @@ public interface IClient { */ @ZenGetter("player") public IPlayer getPlayer(); - + @ZenGetter("language") public String getLanguage(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/container/IContainer.java b/MineTweaker3-API/src/main/java/minetweaker/api/container/IContainer.java index 89c28b3..267fc6f 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/container/IContainer.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/container/IContainer.java @@ -19,7 +19,7 @@ public interface IContainer extends Iterable { */ @ZenGetter("containerSize") public int getContainerSize(); - + /** * Gets the item stack at the given position. Returns null if there is no * stack at that position. @@ -29,7 +29,7 @@ public interface IContainer extends Iterable { */ @ZenMethod public IItemStack getStack(int i); - + /** * Sets the item stack at the given position. * diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/damage/IDamageSource.java b/MineTweaker3-API/src/main/java/minetweaker/api/damage/IDamageSource.java index 6093899..8f8b494 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/damage/IDamageSource.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/damage/IDamageSource.java @@ -5,5 +5,5 @@ package minetweaker.api.damage; * @author Stan Hebben */ public interface IDamageSource { - + } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataBool.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataBool.java index 45a4a82..c1e849a 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataBool.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataBool.java @@ -10,7 +10,7 @@ import java.util.Map; */ public class DataBool implements IData { private final boolean value; - + public DataBool(boolean value) { this.value = value; } @@ -54,12 +54,12 @@ public class DataBool implements IData { public String asString() { return Boolean.toString(value); } - + @Override public List asList() { return null; } - + @Override public Map asMap() { return null; @@ -104,12 +104,12 @@ public class DataBool implements IData { public boolean contains(IData data) { return data.asBool() == value; } - + @Override public boolean equals(IData other) { return value == other.asBool(); } - + @Override public int compareTo(IData other) { throw new UnsupportedOperationException("Cannot compare bool values"); @@ -179,7 +179,7 @@ public class DataBool implements IData { public IData not() { return new DataBool(!value); } - + @Override public String toString() { return asString(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataByte.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataByte.java index 7d4eac2..9a50ac7 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataByte.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataByte.java @@ -10,7 +10,7 @@ import java.util.Map; */ public class DataByte implements IData { private final byte value; - + public DataByte(byte value) { this.value = value; } @@ -54,12 +54,12 @@ public class DataByte implements IData { public String asString() { return Byte.toString(value); } - + @Override public List asList() { return null; } - + @Override public Map asMap() { return null; @@ -104,12 +104,12 @@ public class DataByte implements IData { public boolean contains(IData data) { return data.asByte() == value; } - + @Override public boolean equals(IData data) { return value == data.asByte(); } - + @Override public int compareTo(IData data) { return Byte.compare(value, data.asByte()); @@ -172,14 +172,14 @@ public class DataByte implements IData { @Override public IData neg() { - return new DataByte((byte) (- value)); + return new DataByte((byte) (-value)); } @Override public IData not() { - return new DataByte((byte) (~ value)); + return new DataByte((byte) (~value)); } - + @Override public String toString() { return asString() + " as byte"; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataByteArray.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataByteArray.java index 406b024..bc49a7c 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataByteArray.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataByteArray.java @@ -13,7 +13,7 @@ import java.util.Map; public class DataByteArray implements IData { private final byte[] data; private final boolean immutable; - + public DataByteArray(byte[] data, boolean immutable) { this.data = data; this.immutable = immutable; @@ -117,7 +117,7 @@ public class DataByteArray implements IData { first = false; else result.append(", "); - + result.append(value); } result.append("] as byte[]"); @@ -214,7 +214,7 @@ public class DataByteArray implements IData { public T convert(IDataConverter converter) { return converter.fromByteArray(this.data); } - + @Override public String toString() { return asString() + " as byte[]"; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataDouble.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataDouble.java index 8c44a84..aac5619 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataDouble.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataDouble.java @@ -10,7 +10,7 @@ import java.util.Map; */ public class DataDouble implements IData { private final double value; - + public DataDouble(double value) { this.value = value; } @@ -54,12 +54,12 @@ public class DataDouble implements IData { public String asString() { return Double.toString(value); } - + @Override public List asList() { return null; } - + @Override public Map asMap() { return null; @@ -104,12 +104,12 @@ public class DataDouble implements IData { public boolean contains(IData data) { return data.asDouble() == value; } - + @Override public boolean equals(IData other) { return value == other.asDouble(); } - + @Override public int compareTo(IData other) { return Double.compare(value, other.asDouble()); @@ -172,14 +172,14 @@ public class DataDouble implements IData { @Override public IData neg() { - return new DataDouble(- value); + return new DataDouble(-value); } @Override public IData not() { throw new UnsupportedOperationException("Cannot perform bitwise operations on double"); } - + @Override public String toString() { return asString(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataFloat.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataFloat.java index 6dd9677..bc0b2f9 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataFloat.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataFloat.java @@ -10,7 +10,7 @@ import java.util.Map; */ public class DataFloat implements IData { private final float value; - + public DataFloat(float value) { this.value = value; } @@ -54,12 +54,12 @@ public class DataFloat implements IData { public String asString() { return Float.toString(value); } - + @Override public List asList() { return null; } - + @Override public Map asMap() { return null; @@ -104,12 +104,12 @@ public class DataFloat implements IData { public boolean contains(IData data) { return data.asFloat() == value; } - + @Override public boolean equals(IData data) { return value == data.asFloat(); } - + @Override public int compareTo(IData data) { return Float.compare(value, data.asFloat()); @@ -172,14 +172,14 @@ public class DataFloat implements IData { @Override public IData neg() { - return new DataFloat(- value); + return new DataFloat(-value); } @Override public IData not() { throw new UnsupportedOperationException("Cannot perform bitwise operations on float"); } - + @Override public String toString() { return asString() + " as float"; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataInt.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataInt.java index 927757c..fdced16 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataInt.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataInt.java @@ -10,7 +10,7 @@ import java.util.Map; */ public class DataInt implements IData { private final int value; - + public DataInt(int value) { this.value = value; } @@ -54,12 +54,12 @@ public class DataInt implements IData { public String asString() { return Integer.toString(value); } - + @Override public List asList() { return null; } - + @Override public Map asMap() { return null; @@ -104,12 +104,12 @@ public class DataInt implements IData { public boolean contains(IData data) { return data.asInt() == value; } - + @Override public boolean equals(IData data) { return value == data.asInt(); } - + @Override public int compareTo(IData data) { return Integer.compare(value, data.asInt()); @@ -172,14 +172,14 @@ public class DataInt implements IData { @Override public IData neg() { - return new DataInt(- value); + return new DataInt(-value); } @Override public IData not() { - return new DataInt(~ value); + return new DataInt(~value); } - + @Override public String toString() { return asString(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataIntArray.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataIntArray.java index b71356e..7fedeef 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataIntArray.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataIntArray.java @@ -13,7 +13,7 @@ import java.util.Map; public class DataIntArray implements IData { private final int[] data; private final boolean immutable; - + public DataIntArray(int[] data, boolean immutable) { this.data = data; this.immutable = immutable; @@ -214,7 +214,7 @@ public class DataIntArray implements IData { public T convert(IDataConverter converter) { return converter.fromIntArray(this.data); } - + @Override public String toString() { return asString() + " as int[]"; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataList.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataList.java index ed6aff2..4653101 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataList.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataList.java @@ -13,7 +13,7 @@ import java.util.Map; public class DataList implements IData { private final List values; private final boolean immutable; - + public DataList(List values, boolean immutable) { this.values = values; this.immutable = immutable; @@ -53,7 +53,7 @@ public class DataList implements IData { public double asDouble() { throw new IllegalDataException("Cannot convert a list to a double"); } - + @Override public List asList() { if (immutable) { @@ -62,7 +62,7 @@ public class DataList implements IData { return values; } } - + @Override public Map asMap() { return null; @@ -145,15 +145,15 @@ public class DataList implements IData { List dataValues = data.asList(); if (dataValues != null && containsList(dataValues)) return true; - + for (IData value : values) { if (value.contains(data)) return true; } - + return false; } - + private boolean containsList(List dataValues) { outer: for (IData dataValue : dataValues) { for (IData value : values) { @@ -163,22 +163,24 @@ public class DataList implements IData { return false; } - + return true; } - + @Override public boolean equals(IData data) { List otherValues = data.asList(); - if (otherValues.size() != values.size()) return false; - + if (otherValues.size() != values.size()) + return false; + for (int i = 0; i < values.size(); i++) { - if (!values.get(i).equals(otherValues.get(i))) return false; + if (!values.get(i).equals(otherValues.get(i))) + return false; } - + return true; } - + @Override public int compareTo(IData data) { throw new UnsupportedOperationException("Cannot compare with a list"); @@ -199,8 +201,9 @@ public class DataList implements IData { @Override public IData update(IData data) { - if (immutable) data = data.immutable(); - + if (immutable) + data = data.immutable(); + List result = new ArrayList(); result.addAll(values); result.addAll(data.asList()); @@ -261,7 +264,7 @@ public class DataList implements IData { public IData not() { throw new UnsupportedOperationException("Lists don't support bitwise operators"); } - + @Override public String toString() { return asString(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataLong.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataLong.java index c3c16b0..b34f592 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataLong.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataLong.java @@ -10,7 +10,7 @@ import java.util.Map; */ public class DataLong implements IData { private final long value; - + public DataLong(long value) { this.value = value; } @@ -54,12 +54,12 @@ public class DataLong implements IData { public String asString() { return Long.toString(value); } - + @Override public List asList() { return null; } - + @Override public Map asMap() { return null; @@ -104,12 +104,12 @@ public class DataLong implements IData { public boolean contains(IData data) { return data.asLong() == value; } - + @Override public boolean equals(IData data) { return value == data.asLong(); } - + @Override public int compareTo(IData data) { return Long.compare(value, data.asLong()); @@ -172,14 +172,14 @@ public class DataLong implements IData { @Override public IData neg() { - return new DataLong(- value); + return new DataLong(-value); } @Override public IData not() { - return new DataLong(~ value); + return new DataLong(~value); } - + @Override public String toString() { return asString() + " as long"; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataMap.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataMap.java index fb970d5..4f442e6 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataMap.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataMap.java @@ -12,10 +12,10 @@ import java.util.Map; */ public class DataMap implements IData { public static final DataMap EMPTY = new DataMap(new HashMap(), true); - + private final Map data; private final boolean immutable; - + public DataMap(Map data, boolean immutable) { this.data = data; this.immutable = immutable; @@ -25,14 +25,14 @@ public class DataMap implements IData { public IData add(IData other) { Map result = new HashMap(); Map otherMap = other.asMap(); - + for (Map.Entry entry : data.entrySet()) { result.put(entry.getKey(), entry.getValue()); } for (Map.Entry entry : otherMap.entrySet()) { result.put(entry.getKey(), entry.getValue()); } - + return new DataMap(result, immutable); } @@ -40,14 +40,14 @@ public class DataMap implements IData { public IData sub(IData other) { Map result = new HashMap(); Map otherMap = other.asMap(); - + for (Map.Entry entry : data.entrySet()) { result.put(entry.getKey(), entry.getValue()); } for (String key : otherMap.keySet()) { result.remove(key); } - + return new DataMap(result, immutable); } @@ -137,13 +137,13 @@ public class DataMap implements IData { } else { result.append(", "); } - + if (isValidIdentifier(entry.getKey())) { result.append(entry.getKey()); } else { result.append("\"").append(entry.getKey()).append("\""); } - + result.append(": "); result.append(entry.getValue().toString()); } @@ -209,11 +209,11 @@ public class DataMap implements IData { if (data instanceof DataString) { return this.data.containsKey(data.asString()); } - + Map dataMap = data.asMap(); if (dataMap == null) return false; - + for (Map.Entry dataEntry : dataMap.entrySet()) { if (!this.data.containsKey(dataEntry.getKey())) { return false; @@ -221,7 +221,7 @@ public class DataMap implements IData { return false; } } - + return true; } @@ -232,11 +232,13 @@ public class DataMap implements IData { @Override public boolean equals(IData data) { - if (this == data) return true; - + if (this == data) + return true; + Map dataMap = data.asMap(); - if (dataMap.size() != this.data.size()) return false; - + if (dataMap.size() != this.data.size()) + return false; + for (Map.Entry dataEntry : this.data.entrySet()) { if (!dataMap.containsKey(dataEntry.getKey())) { return false; @@ -244,7 +246,7 @@ public class DataMap implements IData { return false; } } - + return true; } @@ -263,8 +265,9 @@ public class DataMap implements IData { @Override public IData update(IData data) { - if (immutable) data = data.immutable(); - + if (immutable) + data = data.immutable(); + Map result = new HashMap(); for (Map.Entry entry : this.data.entrySet()) { result.put(entry.getKey(), entry.getValue()); @@ -279,21 +282,21 @@ public class DataMap implements IData { public T convert(IDataConverter converter) { return converter.fromMap(data); } - + @Override public String toString() { return asString(); } - + private boolean isValidIdentifier(String str) { if (!Character.isJavaIdentifierStart(str.charAt(0))) return false; - + for (int i = 1; i < str.length(); i++) { if (!Character.isJavaIdentifierPart(str.charAt(i))) return false; } - + return true; } } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataShort.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataShort.java index 231985f..a46901e 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataShort.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataShort.java @@ -10,7 +10,7 @@ import java.util.Map; */ public class DataShort implements IData { private final short value; - + public DataShort(short value) { this.value = value; } @@ -54,12 +54,12 @@ public class DataShort implements IData { public String asString() { return Short.toString(value); } - + @Override public List asList() { return null; } - + @Override public Map asMap() { return null; @@ -104,12 +104,12 @@ public class DataShort implements IData { public boolean contains(IData data) { return data.asShort() == value; } - + @Override public boolean equals(IData data) { return value == data.asShort(); } - + @Override public int compareTo(IData data) { return Short.compare(value, data.asShort()); @@ -172,14 +172,14 @@ public class DataShort implements IData { @Override public IData neg() { - return new DataShort((short) (- value)); + return new DataShort((short) (-value)); } @Override public IData not() { - return new DataShort((short) (~ value)); + return new DataShort((short) (~value)); } - + @Override public String toString() { return asString() + " as short"; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataString.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataString.java index af972e4..87c46c1 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/DataString.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/DataString.java @@ -10,7 +10,7 @@ import java.util.Map; */ public class DataString implements IData { private final String value; - + public DataString(String value) { this.value = value; } @@ -54,12 +54,12 @@ public class DataString implements IData { public String asString() { return value; } - + @Override public List asList() { return null; } - + @Override public Map asMap() { return null; @@ -108,12 +108,12 @@ public class DataString implements IData { public boolean contains(IData data) { return data.asString().equals(value); } - + @Override public boolean equals(IData data) { return value.equals(data.asString()); } - + @Override public int compareTo(IData data) { return value.compareTo(data.asString()); @@ -183,7 +183,7 @@ public class DataString implements IData { public IData not() { throw new UnsupportedOperationException("Cannot perform bitwise arithmetic on a string"); } - + @Override public String toString() { return '\"' + value.replace("\"", "\\\"") + "\""; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/IData.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/IData.java index 9972065..dc0e5c1 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/IData.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/IData.java @@ -13,8 +13,8 @@ import stanhebben.zenscript.annotations.ZenMethod; /** * Generic data interface. A data element may contain any kind of basic data - * element (bool, byte, short, int, long, float, double, string, list, map, - * int array or byte array). Used to store data with stacks, blocks, world, ... + * element (bool, byte, short, int, long, float, double, string, list, map, int + * array or byte array). Used to store data with stacks, blocks, world, ... * * @author Stan Hebben */ @@ -22,58 +22,58 @@ import stanhebben.zenscript.annotations.ZenMethod; public interface IData { @ZenOperator(OperatorType.ADD) public IData add(IData other); - + @ZenOperator(OperatorType.SUB) public IData sub(IData other); - + @ZenOperator(OperatorType.MUL) public IData mul(IData other); - + @ZenOperator(OperatorType.DIV) public IData div(IData other); - + @ZenOperator(OperatorType.MOD) public IData mod(IData other); - + @ZenOperator(OperatorType.AND) public IData and(IData other); - + @ZenOperator(OperatorType.OR) public IData or(IData other); - + @ZenOperator(OperatorType.XOR) public IData xor(IData other); - + @ZenOperator(OperatorType.NEG) public IData neg(); - + @ZenOperator(OperatorType.NOT) public IData not(); - - @ZenCaster - public boolean asBool(); - - @ZenCaster - public byte asByte(); - - @ZenCaster - public short asShort(); - - @ZenCaster - public int asInt(); - - @ZenCaster - public long asLong(); - - @ZenCaster - public float asFloat(); - - @ZenCaster - public double asDouble(); - - @ZenCaster - public String asString(); - + + @ZenCaster + public boolean asBool(); + + @ZenCaster + public byte asByte(); + + @ZenCaster + public short asShort(); + + @ZenCaster + public int asInt(); + + @ZenCaster + public long asLong(); + + @ZenCaster + public float asFloat(); + + @ZenCaster + public double asDouble(); + + @ZenCaster + public String asString(); + /** * Attempts to convert this value to a List. Returns null if this value * cannot be converted to a list. @@ -82,7 +82,7 @@ public interface IData { */ @ZenCaster public List asList(); - + /** * Attempts to convert this value to a Map. Returns null if this value * cannot be converted to a map. @@ -91,57 +91,57 @@ public interface IData { */ @ZenCaster public Map asMap(); - + /** * Attempts to convert this value to a byte array. Returns null if this * value cannot be converted to a byte array. * * @return byte array data of this value, if any */ - @ZenCaster - public byte[] asByteArray(); - + @ZenCaster + public byte[] asByteArray(); + /** * Attempts to convert this value to an int array. Returns null if this * value cannot be converted to an int array. * * @return int array data of this value, if any */ - @ZenCaster - public int[] asIntArray(); - - @ZenOperator(OperatorType.INDEXGET) - public IData getAt(int i); - - @ZenOperator(OperatorType.INDEXSET) - public void setAt(int i, IData value); - - @ZenMemberGetter - public IData memberGet(String name); - - @ZenMemberSetter - public void memberSet(String name, IData data); - + @ZenCaster + public int[] asIntArray(); + + @ZenOperator(OperatorType.INDEXGET) + public IData getAt(int i); + + @ZenOperator(OperatorType.INDEXSET) + public void setAt(int i, IData value); + + @ZenMemberGetter + public IData memberGet(String name); + + @ZenMemberSetter + public void memberSet(String name, IData data); + @ZenGetter public int length(); - + @ZenOperator(OperatorType.CONTAINS) public boolean contains(IData data); - + @ZenOperator(OperatorType.COMPARE) public int compareTo(IData data); - + @ZenOperator(OperatorType.EQUALS) public boolean equals(IData data); - + @ZenGetter public IData immutable(); - + @ZenMethod public IData update(IData data); - + public T convert(IDataConverter converter); - + @Override public String toString(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/data/IDataConverter.java b/MineTweaker3-API/src/main/java/minetweaker/api/data/IDataConverter.java index 2e9a2ef..543178f 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/data/IDataConverter.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/data/IDataConverter.java @@ -11,26 +11,26 @@ import java.util.Map; */ public interface IDataConverter { public T fromBool(boolean value); - + public T fromByte(byte value); - + public T fromShort(short value); - + public T fromInt(int value); - + public T fromLong(long value); - + public T fromFloat(float value); - + public T fromDouble(double value); - + public T fromString(String value); - + public T fromList(List values); - + public T fromMap(Map values); - + public T fromByteArray(byte[] value); - + public T fromIntArray(int[] value); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/entity/IEntity.java b/MineTweaker3-API/src/main/java/minetweaker/api/entity/IEntity.java index 5237c8a..5c7668c 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/entity/IEntity.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/entity/IEntity.java @@ -7,9 +7,9 @@ import stanhebben.zenscript.annotations.ZenGetter; import stanhebben.zenscript.annotations.ZenSetter; /** - * Entity interface. Used to obtain information about entities, and modify - * their data. Entities are any item that is freely movable in the world, - * such as players, monsters, items on the ground, ... + * Entity interface. Used to obtain information about entities, and modify their + * data. Entities are any item that is freely movable in the world, such as + * players, monsters, items on the ground, ... * * @author Stan Hebben */ @@ -22,7 +22,7 @@ public interface IEntity { */ @ZenGetter("dimension") public IDimension getDimension(); - + /** * Retrieves the x position of this entity. * @@ -30,7 +30,7 @@ public interface IEntity { */ @ZenGetter("x") public float getX(); - + /** * Retrieves the y position of this entity. * @@ -38,7 +38,7 @@ public interface IEntity { */ @ZenGetter("y") public float getY(); - + /** * Retrieves the z position of this entity. * @@ -46,7 +46,7 @@ public interface IEntity { */ @ZenGetter("z") public float getZ(); - + /** * Retrieves the position of this entity. * @@ -54,7 +54,7 @@ public interface IEntity { */ @ZenGetter("position") public Position3f getPosition(); - + /** * Sets the position of this entity. Instantly moves (teleports) the entity * to that position. diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/entity/IEntityDefinition.java b/MineTweaker3-API/src/main/java/minetweaker/api/entity/IEntityDefinition.java index 9bffc8b..715f341 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/entity/IEntityDefinition.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/entity/IEntityDefinition.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.annotations.ZenGetter; public interface IEntityDefinition { @ZenGetter("id") public String getId(); - + @ZenGetter("name") public String getName(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/IEventManager.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/IEventManager.java index fb1b655..bc601d7 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/IEventManager.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/IEventManager.java @@ -12,77 +12,85 @@ import minetweaker.util.IEventHandler; public interface IEventManager { // implemented public IEventHandle onPlayerCrafted(IEventHandler ev); - + // implemented public IEventHandle onPlayerSmelted(IEventHandler ev); - + public IEventHandle onPlayerChangedDimension(IEventHandler ev); - + public IEventHandle onPlayerRespawn(IEventHandler ev); - + public IEventHandle onPlayerAttackEntity(IEventHandler ev); - + public IEventHandle onPlayerBonemeal(IEventHandler ev); - + public IEventHandle onPlayerInteractEntity(IEventHandler ev); - + public IEventHandle onPlayerPickup(IEventHandler ev); - + public IEventHandle onPlayerPickupItem(IEventHandler ev); - + public IEventHandle onPlayerFillBucket(IEventHandler ev); - + public IEventHandle onPlayerDeathDrops(IEventHandler ev); - + public IEventHandle onPlayerInteract(IEventHandler ev); - + public IEventHandle onPlayerOpenContainer(IEventHandler ev); - + public IEventHandle onPlayerPickupXp(IEventHandler ev); - + public IEventHandle onPlayerSleepInBed(IEventHandler ev); - + public IEventHandle onPlayerUseHoe(IEventHandler ev); - + public IEventHandle onPlayerUseItemStart(IEventHandler ev); - + public IEventHandle onPlayerUseItemTick(IEventHandler ev); - - /*public IEventHandle onPlayerUseItemStop(IEventHandler ev); - - public IEventHandle onPlayerUseItemFinish(IPlayerUserItemFinishEventHandler ev); - - public IEventHandle onPlayerChat(IPlayerChatEventHandler ev); - - public IEventHandle onTimerSingle(int millis, ITimerEventHandler ev); - - public IEventHandle onTimerRepeat(int millis, ITimerEventHandler ev); - - public IEventHandle onEntityJoinWorld(IEntityJoinWorldEventHandler ev); - - public IEventHandle onEntityStruckByLightning(IEntityStruckByLightningEventHandler ev); - - public IEventHandle onLivingEnderTeleport(ILivingEnderTeleportEventHandler ev); - - public IEventHandle onLivingAttackEvent(ILivingAttackEventHandler ev); - - public IEventHandle onLivingDeathEvent(ILivingDeathEventHandler ev); - - public IEventHandle onLivingJumpEvent(ILivingJumpEventHandler ev); - - public IEventHandle onLivingFallEvent(ILivingFallEventHandler ev); - - public IEventHandle onLivingHurtEvent(ILivingHurtEventHandler ev); - - public IEventHandle onLivingDeathDropsEvent(ILivingDeathDropsEventHandler ev); - - public IEventHandle onItemTossed(IItemTossedEventHandler ev); - - public IEventHandle onItemExpired(IItemExpiredEventHandler ev); - - public IEventHandle onMinecartCollision(IMinecartCollisionEventHandler ev); - - public IEventHandle onMinecartInteract(IMinecartInteractEventHandler ev); - - public IEventHandle onCommand(ICommandEventHandler ev);*/ + + /* + * public IEventHandle + * onPlayerUseItemStop(IEventHandler ev); + * + * public IEventHandle + * onPlayerUseItemFinish(IPlayerUserItemFinishEventHandler ev); + * + * public IEventHandle onPlayerChat(IPlayerChatEventHandler ev); + * + * public IEventHandle onTimerSingle(int millis, ITimerEventHandler ev); + * + * public IEventHandle onTimerRepeat(int millis, ITimerEventHandler ev); + * + * public IEventHandle onEntityJoinWorld(IEntityJoinWorldEventHandler ev); + * + * public IEventHandle + * onEntityStruckByLightning(IEntityStruckByLightningEventHandler ev); + * + * public IEventHandle + * onLivingEnderTeleport(ILivingEnderTeleportEventHandler ev); + * + * public IEventHandle onLivingAttackEvent(ILivingAttackEventHandler ev); + * + * public IEventHandle onLivingDeathEvent(ILivingDeathEventHandler ev); + * + * public IEventHandle onLivingJumpEvent(ILivingJumpEventHandler ev); + * + * public IEventHandle onLivingFallEvent(ILivingFallEventHandler ev); + * + * public IEventHandle onLivingHurtEvent(ILivingHurtEventHandler ev); + * + * public IEventHandle onLivingDeathDropsEvent(ILivingDeathDropsEventHandler + * ev); + * + * public IEventHandle onItemTossed(IItemTossedEventHandler ev); + * + * public IEventHandle onItemExpired(IItemExpiredEventHandler ev); + * + * public IEventHandle onMinecartCollision(IMinecartCollisionEventHandler + * ev); + * + * public IEventHandle onMinecartInteract(IMinecartInteractEventHandler ev); + * + * public IEventHandle onCommand(ICommandEventHandler ev); + */ } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/MTEventManager.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/MTEventManager.java index be35be0..87c7936 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/MTEventManager.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/MTEventManager.java @@ -36,37 +36,37 @@ public class MTEventManager implements IEventManager { elPlayerUseItemStart.clear(); elPlayerUseItemTick.clear(); } - + // ########################## // ### PlayerCraftedEvent ### // ########################## - + private final EventList elPlayerCrafted = new EventList(); - + @Override public IEventHandle onPlayerCrafted(IEventHandler ev) { return elPlayerCrafted.add(ev); } - + public boolean hasPlayerCrafted() { return elPlayerCrafted.hasHandlers(); } - + public void publishPlayerCrafted(PlayerCraftedEvent event) { elPlayerCrafted.publish(event); } - + // ########################## // ### PlayerSmeltedEvent ### // ########################## - + private final EventList elPlayerSmelted = new EventList(); - + @Override public IEventHandle onPlayerSmelted(IEventHandler ev) { return elPlayerSmelted.add(ev); } - + public boolean hasPlayerSmelted() { return elPlayerSmelted.hasHandlers(); } @@ -74,54 +74,54 @@ public class MTEventManager implements IEventManager { public void publishPlayerSmelted(PlayerSmeltedEvent event) { elPlayerSmelted.publish(event); } - + // ################################### // ### PlayerChangedDimensionEvent ### // ################################### - + private final EventList elPlayerChangedDimension = new EventList(); - + @Override public IEventHandle onPlayerChangedDimension(IEventHandler ev) { return elPlayerChangedDimension.add(ev); } - + public boolean hasPlayerChangedDimension() { return elPlayerChangedDimension.hasHandlers(); } - + public void publishPlayerChangedDimension(PlayerChangedDimensionEvent event) { elPlayerChangedDimension.publish(event); } - + // ########################### // ### PlayerLoggedInEvent ### // ########################### private final EventList elPlayerLoggedIn = new EventList(); - + public IEventHandle onPlayerLoggedIn(IEventHandler ev) { return elPlayerLoggedIn.add(ev); } - + public boolean hasPlayerLoggedIn() { return elPlayerLoggedIn.hasHandlers(); } - + public void publishPlayerLoggedIn(PlayerLoggedInEvent event) { elPlayerLoggedIn.publish(event); } - + // ############################ // ### PlayerLoggedOutEvent ### // ############################ - + private final EventList elPlayerLoggedOut = new EventList(); - + public IEventHandle onPlayerLoggedOut(IEventHandler ev) { return elPlayerLoggedOut.add(ev); } - + public boolean hasPlayerLoggedOut() { return elPlayerLoggedOut.hasHandlers(); } @@ -129,18 +129,18 @@ public class MTEventManager implements IEventManager { public void publishPlayerLoggedOut(PlayerLoggedOutEvent event) { elPlayerLoggedOut.publish(event); } - + // ########################## // ### PlayerRespawnEvent ### // ########################## - + private final EventList elPlayerRespawn = new EventList(); - + @Override public IEventHandle onPlayerRespawn(IEventHandler ev) { return elPlayerRespawn.add(ev); } - + public boolean hasPlayerRespawn() { return elPlayerRespawn.hasHandlers(); } @@ -148,18 +148,18 @@ public class MTEventManager implements IEventManager { public void publishPlayerRespawn(PlayerRespawnEvent event) { elPlayerRespawn.publish(event); } - + // ############################### // ### PlayerAttackEntityEvent ### // ############################### - + private final EventList elPlayerAttackEntity = new EventList(); - + @Override public IEventHandle onPlayerAttackEntity(IEventHandler ev) { return elPlayerAttackEntity.add(ev); } - + public boolean hasPlayerAttackEntity() { return elPlayerAttackEntity.hasHandlers(); } @@ -167,231 +167,231 @@ public class MTEventManager implements IEventManager { public void publishPlayerAttackEntity(PlayerAttackEntityEvent event) { elPlayerAttackEntity.publish(event); } - + // ########################### // ### PlayerBonemealEvent ### // ########################### - + private final EventList elPlayerBonemeal = new EventList(); - + @Override public IEventHandle onPlayerBonemeal(IEventHandler ev) { return elPlayerBonemeal.add(ev); } - + public boolean hasPlayerBonemeal() { return elPlayerBonemeal.hasHandlers(); } - + public void publishPlayerBonemeal(PlayerBonemealEvent event) { elPlayerBonemeal.publish(event); } - + // ################################# // ### PlayerInteractEntityEvent ### // ################################# private final EventList elPlayerInteractEntity = new EventList(); - + @Override public IEventHandle onPlayerInteractEntity(IEventHandler ev) { return elPlayerInteractEntity.add(ev); } - + public boolean hasPlayerInteractEntity() { return elPlayerInteractEntity.hasHandlers(); } - + public void publishPlayerInteractEntity(PlayerInteractEntityEvent event) { elPlayerInteractEntity.publish(event); } - + // ######################### // ### PlayerPickupEvent ### // ######################### private final EventList elPlayerPickup = new EventList(); - + @Override public IEventHandle onPlayerPickup(IEventHandler ev) { return elPlayerPickup.add(ev); } - + public boolean hasPlayerPickup() { return elPlayerPickup.hasHandlers(); } - + public void publishPlayerPickup(PlayerPickupEvent event) { elPlayerPickup.publish(event); } - + // ############################# // ### PlayerPickupItemEvent ### // ############################# private final EventList elPlayerPickupItem = new EventList(); - + @Override public IEventHandle onPlayerPickupItem(IEventHandler ev) { return elPlayerPickupItem.add(ev); } - + public boolean hasPlayerPickupItem() { return elPlayerPickupItem.hasHandlers(); } - + public void publishPlayerPickupItem(PlayerPickupItemEvent event) { elPlayerPickupItem.publish(event); } - + // ############################# // ### PlayerFillBucketEvent ### // ############################# private final EventList elPlayerFillBucket = new EventList(); - + @Override public IEventHandle onPlayerFillBucket(IEventHandler ev) { return elPlayerFillBucket.add(ev); } - + public boolean hasPlayerFillBucket() { return elPlayerFillBucket.hasHandlers(); } - + public void publishPlayerFillBucket(PlayerFillBucketEvent event) { elPlayerFillBucket.publish(event); } - + // ############################# // ### PlayerDeathDropsEvent ### // ############################# private final EventList elPlayerDeathDrops = new EventList(); - + @Override public IEventHandle onPlayerDeathDrops(IEventHandler ev) { return elPlayerDeathDrops.add(ev); } - + public boolean hasPlayerDeathDrops() { return elPlayerDeathDrops.hasHandlers(); } - + public void publishPlayerDeathDrops(PlayerDeathDropsEvent event) { elPlayerDeathDrops.publish(event); } - + // ########################### // ### PlayerInteractEvent ### // ########################### private final EventList elPlayerInteract = new EventList(); - + @Override public IEventHandle onPlayerInteract(IEventHandler ev) { return elPlayerInteract.add(ev); } - + public boolean hasPlayerInteract() { return elPlayerInteract.hasHandlers(); } - + public void publishPlayerInteract(PlayerInteractEvent event) { elPlayerInteract.publish(event); } - + // ################################ // ### PlayerOpenContainerEvent ### // ################################ private final EventList elPlayerOpenContainer = new EventList(); - + @Override public IEventHandle onPlayerOpenContainer(IEventHandler ev) { return elPlayerOpenContainer.add(ev); } - + public boolean hasPlayerOpenContainer() { return elPlayerOpenContainer.hasHandlers(); } - + public void publishPlayerOpenContainer(PlayerOpenContainerEvent event) { elPlayerOpenContainer.publish(event); } - + // ########################### // ### PlayerPickupXpEvent ### // ########################### private final EventList elPlayerPickupXp = new EventList(); - + @Override public IEventHandle onPlayerPickupXp(IEventHandler ev) { return elPlayerPickupXp.add(ev); } - + public boolean hasPlayerPickupXp() { return elPlayerPickupXp.hasHandlers(); } - + public void publishPlayerPickup(PlayerPickupXpEvent event) { elPlayerPickupXp.publish(event); } - + // ############################# // ### PlayerSleepInBedEvent ### // ############################# - + private final EventList elPlayerSleepInBed = new EventList(); - + @Override public IEventHandle onPlayerSleepInBed(IEventHandler ev) { return elPlayerSleepInBed.add(ev); } - + public boolean hasPlayerSleepInBed() { return elPlayerSleepInBed.hasHandlers(); } - + public void publishPlayerSleepInBed(PlayerSleepInBedEvent event) { elPlayerSleepInBed.publish(event); } - + // ######################### // ### PlayerUseHoeEvent ### // ######################### - + private final EventList elPlayerUseHoe = new EventList(); @Override public IEventHandle onPlayerUseHoe(IEventHandler ev) { return elPlayerUseHoe.add(ev); } - + public boolean hasPlayerUseHoe() { return elPlayerUseHoe.hasHandlers(); } - + public void publishPlayerUseHoe(PlayerUseHoeEvent event) { elPlayerUseHoe.publish(event); } - + // ############################### // ### PlayerUseItemStartEvent ### // ############################### - + private final EventList elPlayerUseItemStart = new EventList(); - + @Override public IEventHandle onPlayerUseItemStart(IEventHandler ev) { return elPlayerUseItemStart.add(ev); } - + public boolean hasPlayerUseItemStart() { return elPlayerUseItemStart.hasHandlers(); } - + public void publishPlayerUseItemStart(PlayerUseItemStartEvent event) { elPlayerUseItemStart.publish(event); } @@ -399,18 +399,18 @@ public class MTEventManager implements IEventManager { // ############################## // ### PlayerUseItemTickEvent ### // ############################## - + private final EventList elPlayerUseItemTick = new EventList(); - + @Override public IEventHandle onPlayerUseItemTick(IEventHandler ev) { return elPlayerUseItemTick.add(ev); } - + public boolean hasPlayerUseItemTick() { return elPlayerUseItemTick.hasHandlers(); } - + public void publishPlayerUseItemTick(PlayerUseItemTickEvent event) { elPlayerUseItemTick.publish(event); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerAttackEntityEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerAttackEntityEvent.java index 13981c9..07ff5fe 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerAttackEntityEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerAttackEntityEvent.java @@ -21,28 +21,28 @@ public class PlayerAttackEntityEvent { private final IPlayer player; private final IEntity entity; private boolean canceled; - + public PlayerAttackEntityEvent(IPlayer player, IEntity entity) { this.player = player; this.entity = entity; canceled = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("entity") public IEntity getEntity() { return entity; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerBonemealEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerBonemealEvent.java index af61f07..4987bff 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerBonemealEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerBonemealEvent.java @@ -27,68 +27,68 @@ public class PlayerBonemealEvent { private final int z; private boolean canceled; private boolean processed; - + public PlayerBonemealEvent(IPlayer player, IBlockGroup blocks, int x, int y, int z) { this.player = player; this.blocks = blocks; this.x = x; this.y = y; this.z = z; - + canceled = false; processed = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenMethod public void process() { processed = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("processed") public boolean isProcessed() { return processed; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("blocks") public IBlockGroup getBlocks() { return blocks; } - + @ZenGetter("x") public int getX() { return x; } - + @ZenGetter("y") public int getY() { return y; } - + @ZenGetter("z") public int getZ() { return z; } - + @ZenGetter("block") public IBlock getBlock() { return blocks.getBlock(x, y, z); } - + @ZenGetter("dimension") public IDimension getDimension() { return blocks.getDimension(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerChangedDimensionEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerChangedDimensionEvent.java index 0912b6e..b663ac5 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerChangedDimensionEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerChangedDimensionEvent.java @@ -20,23 +20,23 @@ public class PlayerChangedDimensionEvent { private final IPlayer player; private final IDimension from; private final IDimension to; - + public PlayerChangedDimensionEvent(IPlayer player, IDimension from, IDimension to) { this.player = player; this.from = from; this.to = to; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("from") public IDimension getFrom() { return from; } - + @ZenGetter("to") public IDimension getTo() { return to; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerCraftedEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerCraftedEvent.java index 8709ccd..8bf3da6 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerCraftedEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerCraftedEvent.java @@ -21,23 +21,23 @@ public class PlayerCraftedEvent { private final IPlayer player; private final IItemStack output; private final ICraftingInventory inventory; - + public PlayerCraftedEvent(IPlayer player, IItemStack output, ICraftingInventory inventory) { this.player = player; this.output = output; this.inventory = inventory; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("output") public IItemStack getOutput() { return output; } - + @ZenGetter("inventory") public ICraftingInventory getInventory() { return inventory; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerDeathDropsEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerDeathDropsEvent.java index dcad378..f5e6f83 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerDeathDropsEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerDeathDropsEvent.java @@ -22,23 +22,23 @@ public class PlayerDeathDropsEvent { private final IPlayer player; private final List items; private final IDamageSource damageSource; - + public PlayerDeathDropsEvent(IPlayer player, List items, IDamageSource damageSource) { this.player = player; this.items = items; this.damageSource = damageSource; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("items") public List getItems() { return items; } - + @ZenGetter("damageSource") public IDamageSource getDamageSource() { return damageSource; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerFillBucketEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerFillBucketEvent.java index b91091c..3682994 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerFillBucketEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerFillBucketEvent.java @@ -29,28 +29,28 @@ public class PlayerFillBucketEvent { private final int z; private boolean canceled; private IItemStack result; - + public PlayerFillBucketEvent(IPlayer player, IBlockGroup blocks, int x, int y, int z) { this.player = player; this.blocks = blocks; this.x = x; this.y = y; this.z = z; - + canceled = false; result = null; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + /** * Sets the resulting item. Automatically processes the event, too. * @@ -60,42 +60,42 @@ public class PlayerFillBucketEvent { public void setResult(IItemStack result) { this.result = result; } - + @ZenGetter("result") public IItemStack getResult() { return result; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("blocks") public IBlockGroup getBlocks() { return blocks; } - + @ZenGetter("x") public int getX() { return x; } - + @ZenGetter("y") public int getY() { return y; } - + @ZenGetter("z") public int getZ() { return z; } - + @ZenGetter("block") public IBlock getBlock() { return blocks.getBlock(x, y, z); } - + @ZenGetter("dimension") public IDimension getDimension() { return blocks.getDimension(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerInteractEntityEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerInteractEntityEvent.java index 9af68fe..b3702c2 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerInteractEntityEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerInteractEntityEvent.java @@ -21,28 +21,28 @@ public class PlayerInteractEntityEvent { private final IPlayer player; private final IEntity entity; private boolean canceled; - + public PlayerInteractEntityEvent(IPlayer player, IEntity entity) { this.player = player; this.entity = entity; canceled = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("entity") public IEntity getEntity() { return entity; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerInteractEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerInteractEvent.java index 9dcd682..dfda3e5 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerInteractEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerInteractEvent.java @@ -25,83 +25,83 @@ public class PlayerInteractEvent { private final int x; private final int y; private final int z; - + private boolean canceled; private boolean useBlock; private boolean useItem; - + public PlayerInteractEvent(IPlayer player, IBlockGroup blocks, int x, int y, int z) { this.player = player; this.blocks = blocks; this.x = x; this.y = y; this.z = z; - + canceled = false; useBlock = false; useItem = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenMethod public void useBlock() { useBlock = true; } - + @ZenMethod public void useItem() { useItem = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("usingBlock") public boolean isUsingBlock() { return useBlock; } - + @ZenGetter("usingItem") public boolean isUsingItem() { return useItem; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("blocks") public IBlockGroup getBlocks() { return blocks; } - + @ZenGetter("x") public int getX() { return x; } - + @ZenGetter("y") public int getY() { return y; } - + @ZenGetter("z") public int getZ() { return z; } - + @ZenGetter("block") public IBlock getBlock() { return blocks.getBlock(x, y, z); } - + @ZenGetter("dimension") public IDimension getDimension() { return blocks.getDimension(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerLoggedInEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerLoggedInEvent.java index eaa2795..9c06710 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerLoggedInEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerLoggedInEvent.java @@ -17,11 +17,11 @@ import stanhebben.zenscript.annotations.ZenGetter; @ZenClass("minetweaker.event.PlayerLoggedInEvent") public class PlayerLoggedInEvent { private final IPlayer player; - + public PlayerLoggedInEvent(IPlayer player) { this.player = player; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerLoggedOutEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerLoggedOutEvent.java index ecd959b..4322955 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerLoggedOutEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerLoggedOutEvent.java @@ -17,11 +17,11 @@ import stanhebben.zenscript.annotations.ZenGetter; @ZenClass("minetweaker.event.PlayerLoggedOutEvent") public class PlayerLoggedOutEvent { private final IPlayer player; - + public PlayerLoggedOutEvent(IPlayer player) { this.player = player; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerOpenContainerEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerOpenContainerEvent.java index d308ed2..c3bf4a0 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerOpenContainerEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerOpenContainerEvent.java @@ -21,29 +21,29 @@ public class PlayerOpenContainerEvent { private final IPlayer player; private final IContainer container; private boolean canceled; - + public PlayerOpenContainerEvent(IPlayer player, IContainer container) { this.player = player; this.container = container; - + canceled = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("container") public IContainer getContainer() { return container; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupEvent.java index 1776a7d..6ac3862 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupEvent.java @@ -22,20 +22,20 @@ public class PlayerPickupEvent { private final IEntity entity; private boolean canceled; private boolean processed; - + public PlayerPickupEvent(IPlayer player, IEntity entity) { this.player = player; this.entity = entity; - + canceled = false; processed = false; } - + @ZenMethod public void cancel() { canceled = true; } - + /** * Processes the event (picks up the entity). */ @@ -43,22 +43,22 @@ public class PlayerPickupEvent { public void process() { processed = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("processed") public boolean isProcessed() { return processed; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("entity") public IEntity getEntity() { return entity; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupItemEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupItemEvent.java index 5c556e8..fa87ccf 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupItemEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupItemEvent.java @@ -19,17 +19,17 @@ import stanhebben.zenscript.annotations.ZenGetter; public class PlayerPickupItemEvent { private final IPlayer player; private final IItemStack item; - + public PlayerPickupItemEvent(IPlayer player, IItemStack item) { this.player = player; this.item = item; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("item") public IItemStack getItem() { return item; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupXpEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupXpEvent.java index f7c341a..79ac113 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupXpEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerPickupXpEvent.java @@ -21,34 +21,34 @@ public class PlayerPickupXpEvent { private final IPlayer player; private final IEntityXp xp; private boolean canceled; - + public PlayerPickupXpEvent(IPlayer player, IEntityXp xp) { this.player = player; this.xp = xp; - + canceled = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("entity") public IEntityXp getEntity() { return xp; } - + @ZenGetter("xp") public float getXp() { return xp.getXp(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerRespawnEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerRespawnEvent.java index da6eb73..2bc2dd7 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerRespawnEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerRespawnEvent.java @@ -17,11 +17,11 @@ import stanhebben.zenscript.annotations.ZenGetter; @ZenClass("minetweaker.event.PlayerRespawnEvent") public class PlayerRespawnEvent { private final IPlayer player; - + public PlayerRespawnEvent(IPlayer player) { this.player = player; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerSleepInBedEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerSleepInBedEvent.java index 5294ba7..af0ba06 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerSleepInBedEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerSleepInBedEvent.java @@ -20,29 +20,29 @@ public class PlayerSleepInBedEvent { private final int x; private final int y; private final int z; - + public PlayerSleepInBedEvent(IPlayer player, int x, int y, int z) { this.player = player; this.x = x; this.y = y; this.z = z; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("x") public int getX() { return x; } - + @ZenGetter("y") public int getY() { return y; } - + @ZenGetter("z") public int getZ() { return z; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerSmeltedEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerSmeltedEvent.java index 62d5743..b3b0ff7 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerSmeltedEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerSmeltedEvent.java @@ -17,17 +17,17 @@ import stanhebben.zenscript.annotations.ZenGetter; public class PlayerSmeltedEvent { private final IPlayer player; private final IItemStack output; - + public PlayerSmeltedEvent(IPlayer player, IItemStack output) { this.player = player; this.output = output; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("output") public IItemStack getOutput() { return output; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseHoeEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseHoeEvent.java index a6fe85d..8bced4b 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseHoeEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseHoeEvent.java @@ -29,7 +29,7 @@ public class PlayerUseHoeEvent { private final int z; private boolean canceled; private boolean processed; - + public PlayerUseHoeEvent(IPlayer player, IItemStack item, IBlockGroup blocks, int x, int y, int z) { this.player = player; this.item = item; @@ -37,66 +37,66 @@ public class PlayerUseHoeEvent { this.x = x; this.y = y; this.z = z; - + canceled = false; processed = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenMethod public void process() { processed = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("processed") public boolean isProcessed() { return processed; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("item") public IItemStack getItem() { return item; } - + @ZenGetter("blocks") public IBlockGroup getBlocks() { return blocks; } - + @ZenGetter("x") public int getX() { return x; } - + @ZenGetter("y") public int getY() { return y; } - + @ZenGetter("z") public int getZ() { return z; } - + @ZenGetter("dimension") public IDimension getDimension() { return blocks.getDimension(); } - + @ZenGetter("block") public IBlock getBlock() { return blocks.getBlock(x, y, z); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseItemStartEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseItemStartEvent.java index 37ac12f..6628913 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseItemStartEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseItemStartEvent.java @@ -21,29 +21,29 @@ public class PlayerUseItemStartEvent { private final IPlayer player; private final IItemStack item; private boolean canceled; - + public PlayerUseItemStartEvent(IPlayer player, IItemStack item) { this.player = player; this.item = item; - + canceled = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("item") public IItemStack getItem() { return item; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseItemTickEvent.java b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseItemTickEvent.java index 0595e80..1445af7 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseItemTickEvent.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/event/PlayerUseItemTickEvent.java @@ -22,35 +22,35 @@ public class PlayerUseItemTickEvent { private final IItemStack item; private final int duration; private boolean canceled; - + public PlayerUseItemTickEvent(IPlayer player, IItemStack item, int duration) { this.player = player; this.item = item; this.duration = duration; - + canceled = false; } - + @ZenMethod public void cancel() { canceled = true; } - + @ZenGetter("canceled") public boolean isCanceled() { return canceled; } - + @ZenGetter("player") public IPlayer getPlayer() { return player; } - + @ZenGetter("item") public IItemStack getItem() { return item; } - + @ZenGetter("duration") public int getDuration() { return duration; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/formatting/IFormattedText.java b/MineTweaker3-API/src/main/java/minetweaker/api/formatting/IFormattedText.java index e96c466..469e65a 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/formatting/IFormattedText.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/formatting/IFormattedText.java @@ -18,7 +18,7 @@ import stanhebben.zenscript.annotations.ZenOperator; public interface IFormattedText { @ZenOperator(OperatorType.ADD) public IFormattedText add(IFormattedText other); - + @ZenOperator(OperatorType.CAT) public IFormattedText cat(IFormattedText other); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/formatting/IFormatter.java b/MineTweaker3-API/src/main/java/minetweaker/api/formatting/IFormatter.java index 15d5d70..0989cae 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/formatting/IFormatter.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/formatting/IFormatter.java @@ -14,67 +14,67 @@ import stanhebben.zenscript.annotations.ZenMethod; */ public interface IFormatter { public IFormattedText string(String text); - + @ZenMethod public IFormattedText black(IFormattedText text); - + @ZenMethod public IFormattedText darkBlue(IFormattedText text); - + @ZenMethod public IFormattedText darkGreen(IFormattedText text); - + @ZenMethod public IFormattedText darkAqua(IFormattedText text); - + @ZenMethod public IFormattedText darkRed(IFormattedText text); - + @ZenMethod public IFormattedText darkPurple(IFormattedText text); - + @ZenMethod public IFormattedText gold(IFormattedText text); - + @ZenMethod public IFormattedText gray(IFormattedText text); - + @ZenMethod public IFormattedText darkGray(IFormattedText text); - + @ZenMethod public IFormattedText blue(IFormattedText text); - + @ZenMethod public IFormattedText green(IFormattedText text); - + @ZenMethod public IFormattedText aqua(IFormattedText text); - + @ZenMethod public IFormattedText red(IFormattedText text); - + @ZenMethod public IFormattedText lightPurple(IFormattedText text); - + @ZenMethod public IFormattedText yellow(IFormattedText text); - + @ZenMethod public IFormattedText white(IFormattedText text); - + @ZenMethod public IFormattedText obfuscated(IFormattedText text); - + @ZenMethod public IFormattedText bold(IFormattedText text); - + @ZenMethod public IFormattedText strikethrough(IFormattedText text); - + @ZenMethod public IFormattedText underline(IFormattedText text); - + @ZenMethod public IFormattedText italic(IFormattedText text); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/game/IGame.java b/MineTweaker3-API/src/main/java/minetweaker/api/game/IGame.java index c027219..e3673ce 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/game/IGame.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/game/IGame.java @@ -24,7 +24,7 @@ public interface IGame { */ @ZenGetter("items") public List getItems(); - + /** * Retrieves the block definitions in this game. * @@ -32,7 +32,7 @@ public interface IGame { */ @ZenGetter("blocks") public List getBlocks(); - + /** * Retrieves the liquids in this game. * @@ -40,7 +40,7 @@ public interface IGame { */ @ZenGetter("liquids") public List getLiquids(); - + /** * Retrieves the biomes in this game. * @@ -48,7 +48,7 @@ public interface IGame { */ @ZenGetter("biomes") public List getBiomes(); - + /** * Retrieves the entities in this game. * @@ -56,7 +56,7 @@ public interface IGame { */ @ZenGetter("entities") public List getEntities(); - + /** * Sets a localization value. * @@ -65,17 +65,17 @@ public interface IGame { */ @ZenMethod public void setLocalization(String key, String value); - + /** * Sets a localization value. * * @param lang language * @param key localization key - * @param value localization value + * @param value localization value */ @ZenMethod public void setLocalization(String lang, String key, String value); - + /** * Gets a localized string. * @@ -84,7 +84,7 @@ public interface IGame { */ @ZenMethod public String localize(String key); - + /** * Gets a localized string. * @@ -94,7 +94,7 @@ public interface IGame { */ @ZenMethod public String localize(String key, String lang); - + /** * Lock the game and disable reload. Recommended for distributed versions. * @@ -103,7 +103,7 @@ public interface IGame { */ @ZenMethod public void lock(); - + /** * Returns the lock state. True if locked. * @@ -111,7 +111,7 @@ public interface IGame { */ @ZenGetter("locked") public boolean isLocked(); - + /** * Signals a modified script while in locked mode. */ diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IIngredient.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IIngredient.java index 99e9994..38e575c 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IIngredient.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IIngredient.java @@ -11,8 +11,8 @@ import stanhebben.zenscript.annotations.ZenOperator; /** * Represents a recipe ingredient. An ingredient can be an item, an ore - * dictionary entry, an item stack, an ore dictionary entry multiplied with - * an amount, or other kinds of ingredients as offered by the API. + * dictionary entry, an item stack, an ore dictionary entry multiplied with an + * amount, or other kinds of ingredients as offered by the API. * * There is no guarantee that every mod will respect the conditions or * transformations, or that every mod will support every kind of ingredient. @@ -22,14 +22,14 @@ import stanhebben.zenscript.annotations.ZenOperator; @ZenClass("minetweaker.item.IIngredient") public interface IIngredient { /** - * Gets the mark of the ingredient. Ingredients can be marked so they can - * be used in crafting functions. + * Gets the mark of the ingredient. Ingredients can be marked so they can be + * used in crafting functions. * * @return ingredient mark */ @ZenGetter("mark") public String getMark(); - + /** * Gets the amount. * @@ -40,7 +40,7 @@ public interface IIngredient { */ @ZenGetter("amount") public int getAmount(); - + /** * Gets all possible items for this ingredient. * @@ -51,18 +51,18 @@ public interface IIngredient { */ @ZenGetter("items") public List getItems(); - + /** * Gets all possible liquids for this ingredient. * - * If there is no liquid list (for example, it is the <*&ft; wildcard item) - * null should be returned. + * If there is no liquid list (for example, it is the <*&ft; wildcard + * item) null should be returned. * * @return the liquids for this ingredient, or null */ @ZenGetter("liquids") public List getLiquids(); - + /** * Returns a new ingredient with the given stack size. * @@ -72,7 +72,7 @@ public interface IIngredient { @ZenOperator(OperatorType.MUL) @ZenMethod public IIngredient amount(int amount); - + /** * Combines multiple ingredients into a single one. Note that ore dictionary * entries are preferred to or statements. @@ -83,7 +83,7 @@ public interface IIngredient { @ZenOperator(OperatorType.OR) @ZenMethod public IIngredient or(IIngredient ingredient); - + /** * Returns a new ingredient with the given transform added to it. * @@ -92,7 +92,7 @@ public interface IIngredient { */ @ZenMethod public IIngredient transform(IItemTransformer transformer); - + /** * Returns a new ingredient with the given condition added to it. * @@ -101,7 +101,7 @@ public interface IIngredient { */ @ZenMethod public IIngredient only(IItemCondition condition); - + /** * Returns a new ingredient marked with the given name. * @@ -110,26 +110,26 @@ public interface IIngredient { */ @ZenMethod public IIngredient marked(String mark); - + /** - * Checks if this ingredient matches the given item. For liquids, will - * match the item if it is a valid container. + * Checks if this ingredient matches the given item. For liquids, will match + * the item if it is a valid container. * * @param item item to check * @return true if the item matches */ @ZenMethod public boolean matches(IItemStack item); - + /** * Checks if this ingredient matches the given liquid. * * @param liquid - * @return + * @return */ @ZenMethod public boolean matches(ILiquidStack liquid); - + /** * Check if this ingredient contains all possible values for the given * ingredient. @@ -139,7 +139,7 @@ public interface IIngredient { */ @ZenOperator(OperatorType.CONTAINS) public boolean contains(IIngredient ingredient); - + /** * Applies transformations after crafting, if any, to the given item. * @@ -149,24 +149,25 @@ public interface IIngredient { */ @ZenMethod public IItemStack applyTransform(IItemStack item, IPlayer byPlayer); - + /** * Checks if this ingredient has (or could have) any transformatiosns. * - * @return true if there are (or could be) any transformations false otherwise. + * @return true if there are (or could be) any transformations false + * otherwise. */ @ZenGetter("hasTransformations") public boolean hasTransformers(); - + /** * Gets the internal item backing this ingredient. * - * The value is implementation-dependent and should only be handled by - * the internal code. Don't use this value - instead, use the version-specific + * The value is implementation-dependent and should only be handled by the + * internal code. Don't use this value - instead, use the version-specific * helper methods. * * @return internal item */ public Object getInternal(); - + } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemCondition.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemCondition.java index 0e3e73e..3c12508 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemCondition.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemCondition.java @@ -6,7 +6,8 @@ import stanhebben.zenscript.annotations.ZenClass; * Item conditions apply additional conditions on item stacks. * * They may, for instance, require specific damage ranges or NBT tags. Custom - * implementations of this functional interface may contain any kind of condition. + * implementations of this functional interface may contain any kind of + * condition. * * @author Stan Hebben */ diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemDefinition.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemDefinition.java index 5ef5f61..459538a 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemDefinition.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemDefinition.java @@ -25,7 +25,7 @@ public interface IItemDefinition { */ @ZenGetter("id") public String getId(); - + /** * Gets the unlocalized item name. * @@ -33,7 +33,7 @@ public interface IItemDefinition { */ @ZenGetter("name") public String getName(); - + /** * Makes an item stack from this definition. * @@ -42,12 +42,12 @@ public interface IItemDefinition { */ @ZenMethod public IItemStack makeStack(@Optional int meta); - + /** * Returns all ore entries containing this item. Also contains ore entries * that refer to a specific sub-item. * - * @return + * @return */ @ZenGetter("ores") public List getOres(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemTransformer.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemTransformer.java index ab4986f..0767f43 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemTransformer.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IItemTransformer.java @@ -5,17 +5,17 @@ import stanhebben.zenscript.annotations.ZenClass; import stanhebben.zenscript.annotations.ZenMethod; /** - * An item transformer modifies an item stack after crafting. Used to apply damage, - * grab multiple items, change NBT tags, replace the item with something else - or whatever - * else you'd want to happen to the input stack. + * An item transformer modifies an item stack after crafting. Used to apply + * damage, grab multiple items, change NBT tags, replace the item with something + * else - or whatever else you'd want to happen to the input stack. * * @author Stan Hebben */ @ZenClass("minetweaker.item.IItemTransformer") public interface IItemTransformer { /** - * Transforms the specified item. May modify this item (and return it) - * or return an entirely new one. + * Transforms the specified item. May modify this item (and return it) or + * return an entirely new one. * * @param item input item * @param byPlayer player that performs the crafting diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientAny.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientAny.java index 69b500e..69f3057 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientAny.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientAny.java @@ -12,10 +12,12 @@ import minetweaker.util.ArrayUtil; */ public class IngredientAny implements IIngredient { public static final IngredientAny INSTANCE = new IngredientAny(); - - public static Object INTERNAL_ANY = null; // platforms supporting an "any" item should fill it here - - private IngredientAny() {} + + public static Object INTERNAL_ANY = null; // platforms supporting an "any" + // item should fill it here + + private IngredientAny() { + } @Override public String getMark() { @@ -31,7 +33,7 @@ public class IngredientAny implements IIngredient { public List getItems() { return null; } - + @Override public List getLiquids() { return null; @@ -66,7 +68,7 @@ public class IngredientAny implements IIngredient { public boolean matches(IItemStack item) { return true; } - + @Override public boolean matches(ILiquidStack liquid) { return true; @@ -91,7 +93,7 @@ public class IngredientAny implements IIngredient { public Object getInternal() { return INTERNAL_ANY; } - + @Override public String toString() { return "<*>"; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientAnyAdvanced.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientAnyAdvanced.java index 7790c7d..0b5a9bd 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientAnyAdvanced.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientAnyAdvanced.java @@ -15,7 +15,7 @@ public class IngredientAnyAdvanced implements IIngredient { private final String mark; private final IItemCondition[] conditions; private final IItemTransformer[] transformers; - + public IngredientAnyAdvanced(String mark, IItemCondition[] conditions, IItemTransformer[] transformers) { this.mark = mark; this.conditions = conditions; @@ -36,7 +36,7 @@ public class IngredientAnyAdvanced implements IIngredient { public List getItems() { return null; } - + @Override public List getLiquids() { return null; @@ -70,15 +70,17 @@ public class IngredientAnyAdvanced implements IIngredient { @Override public boolean matches(IItemStack item) { // TODO: what is the point of this? - if (!item.matches(item)) return false; - + if (!item.matches(item)) + return false; + for (IItemCondition condition : conditions) { - if (!condition.matches(item)) return false; + if (!condition.matches(item)) + return false; } - + return true; } - + @Override public boolean matches(ILiquidStack liquid) { // TODO: conditions on liquids? @@ -89,9 +91,10 @@ public class IngredientAnyAdvanced implements IIngredient { public boolean contains(IIngredient ingredient) { List iitems = ingredient.getItems(); for (IItemStack iitem : iitems) { - if (!matches(iitem)) return false; + if (!matches(iitem)) + return false; } - + return true; } @@ -100,7 +103,7 @@ public class IngredientAnyAdvanced implements IIngredient { for (IItemTransformer transform : transformers) { item = transform.transform(item, byPlayer); } - + return item; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientCondition.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientCondition.java index 12421d5..c69945f 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientCondition.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientCondition.java @@ -28,7 +28,7 @@ public class IngredientCondition { } }); } - + /** * Requires the item to be damaged with at least a specified amount. * @@ -45,7 +45,7 @@ public class IngredientCondition { } }); } - + /** * Requires the item to be damaged with at most a specified amount. An * undamaged item is accepted. @@ -63,7 +63,7 @@ public class IngredientCondition { } }); } - + /** * Requires the item damage value to be between two values. * @@ -81,7 +81,7 @@ public class IngredientCondition { } }); } - + /** * Requires the item to contain at least the given tags. It is OK for the * item to contain more data, as remaining data is ignored. @@ -99,7 +99,7 @@ public class IngredientCondition { } }); } - + /** * Requires the input stack to contain at least the given number of items. * Used in combination with stack consuming recipes. diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientItem.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientItem.java index e273c69..8f69103 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientItem.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientItem.java @@ -17,13 +17,13 @@ public class IngredientItem implements IIngredient { private final IItemCondition[] conditions; private final IItemTransformer[] transformers; private final List items; - + public IngredientItem(IItemStack item, String mark, IItemCondition[] conditions, IItemTransformer[] transformers) { this.item = item; this.mark = mark; this.conditions = conditions; this.transformers = transformers; - + items = Collections.singletonList(item); } @@ -41,7 +41,7 @@ public class IngredientItem implements IIngredient { public List getItems() { return items; } - + @Override public List getLiquids() { return Collections.emptyList(); @@ -74,15 +74,17 @@ public class IngredientItem implements IIngredient { @Override public boolean matches(IItemStack item) { - if (!this.item.matches(item)) return false; - + if (!this.item.matches(item)) + return false; + for (IItemCondition condition : conditions) { - if (!condition.matches(item)) return false; + if (!condition.matches(item)) + return false; } - + return true; } - + @Override public boolean matches(ILiquidStack liquid) { return false; @@ -92,9 +94,10 @@ public class IngredientItem implements IIngredient { public boolean contains(IIngredient ingredient) { List iitems = ingredient.getItems(); for (IItemStack iitem : iitems) { - if (!matches(iitem)) return false; + if (!matches(iitem)) + return false; } - + return true; } @@ -103,7 +106,7 @@ public class IngredientItem implements IIngredient { for (IItemTransformer transform : transformers) { item = transform.transform(item, byPlayer); } - + return item; } @@ -116,11 +119,11 @@ public class IngredientItem implements IIngredient { public Object getInternal() { return item.getInternal(); } - + // ############################# // ### Object implementation ### // ############################# - + @Override public String toString() { return "(Ingredient) " + item.toString(); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientOr.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientOr.java index fc06a90..ef5636f 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientOr.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientOr.java @@ -21,18 +21,18 @@ public class IngredientOr implements IIngredient { private final String mark; private final IItemCondition[] conditions; private final IItemTransformer[] transformers; - + public IngredientOr(IIngredient[] elements) { this.elements = elements; mark = null; conditions = ArrayUtil.EMPTY_CONDITIONS; transformers = ArrayUtil.EMPTY_TRANSFORMERS; } - + public IngredientOr(IIngredient a, IIngredient b) { - this(new IIngredient[] {a, b}); + this(new IIngredient[] { a, b }); } - + private IngredientOr(IIngredient[] elements, String mark, IItemCondition[] conditions, IItemTransformer[] transformers) { this.elements = elements; this.mark = mark; @@ -58,7 +58,7 @@ public class IngredientOr implements IIngredient { } return result; } - + @Override public List getLiquids() { List result = new ArrayList(); @@ -103,17 +103,17 @@ public class IngredientOr implements IIngredient { if (ingredient.matches(item)) return true; } - + return false; } - + @Override public boolean matches(ILiquidStack liquid) { for (IIngredient ingredient : elements) { if (ingredient.matches(liquid)) return true; } - + return false; } @@ -124,7 +124,7 @@ public class IngredientOr implements IIngredient { if (!matches(item)) return false; } - + return true; } @@ -133,7 +133,7 @@ public class IngredientOr implements IIngredient { for (IItemTransformer transformer : transformers) { item = transformer.transform(item, byPlayer); } - + return item; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientStack.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientStack.java index d7ccc70..c57c96b 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientStack.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientStack.java @@ -14,7 +14,7 @@ import minetweaker.api.player.IPlayer; public class IngredientStack implements IIngredient { private final IIngredient ingredient; private final int amount; - + public IngredientStack(IIngredient ingredient, int amount) { this.ingredient = ingredient; this.amount = amount; @@ -34,7 +34,7 @@ public class IngredientStack implements IIngredient { public List getItems() { return ingredient.getItems(); } - + @Override public List getLiquids() { return Collections.emptyList(); @@ -69,7 +69,7 @@ public class IngredientStack implements IIngredient { public boolean matches(IItemStack item) { return item.getAmount() == amount && ingredient.matches(item); } - + @Override public boolean matches(ILiquidStack liquid) { return false; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientTransform.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientTransform.java index dd60cbe..999a23d 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientTransform.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientTransform.java @@ -7,7 +7,8 @@ import stanhebben.zenscript.annotations.ZenMethod; /** * Transformations can be used to modify an ingredient after it is used in a - * crafting recipe. It could reuse the item, damage it or consume multiple items. + * crafting recipe. It could reuse the item, damage it or consume multiple + * items. * * @author Stan Hebben */ @@ -28,10 +29,10 @@ public class IngredientTransform { } }); } - + /** - * Damages the item. Also makes the item reusable. Will damage the item - * for 1 point upon crafting and consume it when broken. + * Damages the item. Also makes the item reusable. Will damage the item for + * 1 point upon crafting and consume it when broken. * * @param ingredient target value * @return damage transformer @@ -50,12 +51,12 @@ public class IngredientTransform { } }); } - + /** * Damages the item for a specific amount. Also makes the item reusable. - * Upon reaching maximum damage, the item will be consumed. Take care to - * set the proper condition such that an almost-broken item becomes - * invalid for crafting. + * Upon reaching maximum damage, the item will be consumed. Take care to set + * the proper condition such that an almost-broken item becomes invalid for + * crafting. * * @param ingredient target value * @param damage damage to be applied @@ -76,7 +77,7 @@ public class IngredientTransform { } }); } - + /** * Causes the item to be replaced upon crafting. Can be used, for instance, * to return empty bottles or buckets. @@ -99,10 +100,10 @@ public class IngredientTransform { } }); } - + /** - * Causes multiple items to be consumed. Take care to set a condition for - * a minimum stack size too, as otherwise smaller stacks would still be + * Causes multiple items to be consumed. Take care to set a condition for a + * minimum stack size too, as otherwise smaller stacks would still be * accepted for input. * * @param ingredient target value @@ -118,12 +119,12 @@ public class IngredientTransform { } }); } - + /** * Makes sure there is no return value. * * @param ingredient - * @return + * @return */ @ZenMethod public static IIngredient noReturn(IIngredient ingredient) { @@ -134,13 +135,14 @@ public class IngredientTransform { } }); } - + /** - * Gives an item back to the player. Also clears the inventory slot at that position. + * Gives an item back to the player. Also clears the inventory slot at that + * position. * * @param ingredient * @param givenItem - * @return + * @return */ @ZenMethod public static IIngredient giveBack(IIngredient ingredient, @Optional final IItemStack givenItem) { diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientUnknown.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientUnknown.java index 539cdcd..908235d 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientUnknown.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/IngredientUnknown.java @@ -18,9 +18,9 @@ import minetweaker.api.player.IPlayer; public class IngredientUnknown implements IIngredient { public static final IngredientUnknown INSTANCE = new IngredientUnknown(1); - + private final int size; - + public IngredientUnknown(int size) { this.size = size; @@ -43,7 +43,7 @@ public class IngredientUnknown implements IIngredient { return Collections.emptyList(); } - + @Override public List getLiquids() { @@ -85,7 +85,7 @@ public class IngredientUnknown implements IIngredient { return false; } - + @Override public boolean matches(ILiquidStack liquid) { diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/item/WeightedItemStack.java b/MineTweaker3-API/src/main/java/minetweaker/api/item/WeightedItemStack.java index a5e6f0a..9ec2d29 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/item/WeightedItemStack.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/item/WeightedItemStack.java @@ -16,43 +16,43 @@ import stanhebben.zenscript.annotations.ZenGetter; public final class WeightedItemStack { public static List pickRandomDrops(Random random, WeightedItemStack[] items) { ArrayList result = new ArrayList(); - + for (WeightedItemStack item : items) { if (random.nextFloat() <= item.getChance()) { result.add(item.getStack()); } } - + return result; } - + private final IItemStack stack; private final float p; - + public WeightedItemStack(IItemStack stack, float p) { this.stack = stack; this.p = p; } - + @ZenGetter("stack") public IItemStack getStack() { return stack; } - + @ZenGetter("chance") public float getChance() { return p; } - + @ZenGetter("percent") public float getPercent() { return p * 100; } - + // ############################# // ### Object implementation ### // ############################# - + @Override public int hashCode() { int hash = 7; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/liquid/ILiquidDefinition.java b/MineTweaker3-API/src/main/java/minetweaker/api/liquid/ILiquidDefinition.java index 9472168..e2a4b65 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/liquid/ILiquidDefinition.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/liquid/ILiquidDefinition.java @@ -10,8 +10,8 @@ import stanhebben.zenscript.annotations.ZenMethod; import stanhebben.zenscript.annotations.ZenSetter; /** - * Contains a liquid definition. Liquid definitions provide additional information - * about liquids. + * Contains a liquid definition. Liquid definitions provide additional + * information about liquids. * * @author Stan Hebben */ @@ -25,7 +25,7 @@ public interface ILiquidDefinition { */ @ZenOperator(OperatorType.MUL) public ILiquidStack asStack(int millibuckets); - + /** * Gets the unlocalized name of this item. * @@ -33,46 +33,46 @@ public interface ILiquidDefinition { */ @ZenGetter("name") public String getName(); - + @ZenGetter("displayName") public String getDisplayName(); - + @ZenGetter("luminosity") public int getLuminosity(); - + @ZenSetter("luminosity") public void setLuminosity(int value); - + @ZenGetter("density") public int getDensity(); - + @ZenSetter("density") public void setDensity(int density); - + @ZenGetter("temperature") public int getTemperature(); - + @ZenSetter("temperature") public void setTemperature(int temperature); - + @ZenGetter("viscosity") public int getViscosity(); - + @ZenSetter("viscosity") public void setViscosity(int viscosity); - + @ZenGetter("gaseous") public boolean isGaseous(); - + @ZenSetter("gaseous") public void setGaseous(boolean gaseous); - + @ZenGetter("containers") public List getContainers(); - + @ZenMethod public void addContainer(IItemStack filled, IItemStack empty, int amount); - + @ZenMethod public void removeContainer(IItemStack filled); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/liquid/ILiquidStack.java b/MineTweaker3-API/src/main/java/minetweaker/api/liquid/ILiquidStack.java index bf003ff..9d04a45 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/liquid/ILiquidStack.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/liquid/ILiquidStack.java @@ -22,40 +22,40 @@ import stanhebben.zenscript.annotations.ZenOperator; public interface ILiquidStack extends IIngredient { @ZenGetter("definition") public ILiquidDefinition getDefinition(); - + @ZenGetter("name") public String getName(); - + @ZenGetter("displayName") public String getDisplayName(); - + @ZenGetter("amount") public int getAmount(); - + @ZenGetter("luminosity") public int getLuminosity(); - + @ZenGetter("density") public int getDensity(); - + @ZenGetter("temperature") public int getTemperature(); - + @ZenGetter("viscosity") public int getViscosity(); - + @ZenGetter("gaseous") public boolean isGaseous(); - + @ZenGetter("tag") public IData getTag(); - + @ZenMethod public ILiquidStack withTag(IData data); - + @ZenOperator(OperatorType.MUL) @ZenMethod public ILiquidStack withAmount(int amount); - + public Object getInternal(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/liquid/WeightedLiquidStack.java b/MineTweaker3-API/src/main/java/minetweaker/api/liquid/WeightedLiquidStack.java index 871c9f5..d3ccbea 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/liquid/WeightedLiquidStack.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/liquid/WeightedLiquidStack.java @@ -16,43 +16,43 @@ import stanhebben.zenscript.annotations.ZenGetter; public final class WeightedLiquidStack { public static List pickRandomDrops(Random random, WeightedLiquidStack[] items) { ArrayList result = new ArrayList(); - + for (WeightedLiquidStack item : items) { if (random.nextFloat() <= item.getChance()) { result.add(item.getStack()); } } - + return result; } - + private final ILiquidStack stack; private final float p; - + public WeightedLiquidStack(ILiquidStack stack, float p) { this.stack = stack; this.p = p; } - + @ZenGetter("stack") public ILiquidStack getStack() { return stack; } - + @ZenGetter("chance") public float getChance() { return p; } - + @ZenGetter("percent") public float getPercent() { return p * 100; } - + // ############################# // ### Object implementation ### // ############################# - + @Override public int hashCode() { int hash = 17; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/logger/FileLogger.java b/MineTweaker3-API/src/main/java/minetweaker/api/logger/FileLogger.java index b9770fb..5a76a2f 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/logger/FileLogger.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/logger/FileLogger.java @@ -23,7 +23,7 @@ import minetweaker.runtime.ILogger; public class FileLogger implements ILogger { private final Writer writer; private final PrintWriter printWriter; - + public FileLogger(File output) { try { writer = new OutputStreamWriter(new FileOutputStream(output), "utf-8"); @@ -69,7 +69,7 @@ public class FileLogger implements ILogger { public void logError(String message) { logError(message, null); } - + @Override public void logError(String message, Throwable exception) { try { diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/logger/MTLogger.java b/MineTweaker3-API/src/main/java/minetweaker/api/logger/MTLogger.java index 392a303..5f2b511 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/logger/MTLogger.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/logger/MTLogger.java @@ -19,29 +19,29 @@ public class MTLogger implements ILogger { private final List loggers = new ArrayList(); private final List players = new ArrayList(); private final List unprocessed = new ArrayList(); - + public void addLogger(ILogger logger) { loggers.add(logger); } - + public void removeLogger(ILogger logger) { loggers.remove(logger); } - + public void addPlayer(IPlayer player) { players.add(player); - + if (!unprocessed.isEmpty()) { for (String message : unprocessed) { player.sendChat(message); } } } - + public void removePlayer(IPlayer player) { players.remove(player); } - + public void clear() { unprocessed.clear(); } @@ -65,9 +65,9 @@ public class MTLogger implements ILogger { for (ILogger logger : loggers) { logger.logWarning(message); } - + String message2 = "WARNING: " + message; - + if (players.isEmpty()) { unprocessed.add(message2); } else { @@ -76,7 +76,7 @@ public class MTLogger implements ILogger { } } } - + @Override public void logError(String message) { logError(message, null); @@ -87,9 +87,9 @@ public class MTLogger implements ILogger { for (ILogger logger : loggers) { logger.logError(message, exception); } - + String message2 = "ERROR: " + message; - + if (players.isEmpty()) { unprocessed.add(message2); } else { diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/mods/ILoadedMods.java b/MineTweaker3-API/src/main/java/minetweaker/api/mods/ILoadedMods.java index 39971e5..c5c2e54 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/mods/ILoadedMods.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/mods/ILoadedMods.java @@ -20,7 +20,7 @@ import stanhebben.zenscript.annotations.ZenOperator; public interface ILoadedMods extends Iterable { @ZenOperator(OperatorType.CONTAINS) public boolean contains(String name); - + @ZenOperator(OperatorType.INDEXGET) public IMod get(String name); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/mods/IMod.java b/MineTweaker3-API/src/main/java/minetweaker/api/mods/IMod.java index e7c447e..ad59d6d 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/mods/IMod.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/mods/IMod.java @@ -10,13 +10,13 @@ import stanhebben.zenscript.annotations.ZenGetter; public interface IMod { @ZenGetter("id") public String getId(); - + @ZenGetter("name") public String getName(); - + @ZenGetter("version") public String getVersion(); - + @ZenGetter("decription") public String getDescription(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IOreDict.java b/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IOreDict.java index d8766c1..31da298 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IOreDict.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IOreDict.java @@ -19,7 +19,7 @@ import stanhebben.zenscript.annotations.ZenMemberGetter; public interface IOreDict { @ZenMemberGetter public IOreDictEntry get(String name); - + @ZenGetter("entries") public List getEntries(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IOreDictEntry.java b/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IOreDictEntry.java index 2f9c89b..136f3ff 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IOreDictEntry.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IOreDictEntry.java @@ -22,22 +22,22 @@ import stanhebben.zenscript.annotations.ZenOperator; public interface IOreDictEntry extends IIngredient { @ZenGetter("name") public String getName(); - + @ZenGetter("empty") public boolean isEmpty(); - + @ZenMethod public void add(IItemStack item); - + @ZenMethod public void addAll(IOreDictEntry entry); - + @ZenMethod public void remove(IItemStack item); - + @ZenOperator(OperatorType.CONTAINS) public boolean contains(IItemStack item); - + @ZenMethod public void mirror(IOreDictEntry other); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IngredientOreDict.java b/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IngredientOreDict.java index 04dea14..2312bee 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IngredientOreDict.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/oredict/IngredientOreDict.java @@ -27,7 +27,7 @@ public class IngredientOreDict implements IIngredient { private final String mark; private final IItemCondition[] conditions; private final IItemTransformer[] transformers; - + public IngredientOreDict( IOreDictEntry entry, String mark, @@ -53,7 +53,7 @@ public class IngredientOreDict implements IIngredient { public List getItems() { return entry.getItems(); } - + @Override public List getLiquids() { return Collections.emptyList(); @@ -86,15 +86,17 @@ public class IngredientOreDict implements IIngredient { @Override public boolean matches(IItemStack item) { - if (!entry.matches(item)) return false; - + if (!entry.matches(item)) + return false; + for (IItemCondition condition : conditions) { - if (!condition.matches(item)) return false; + if (!condition.matches(item)) + return false; } - + return true; } - + @Override public boolean matches(ILiquidStack liquid) { return false; @@ -110,7 +112,7 @@ public class IngredientOreDict implements IIngredient { for (IItemTransformer transformer : transformers) { item = transformer.transform(item, byPlayer); } - + return item; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/player/IPlayer.java b/MineTweaker3-API/src/main/java/minetweaker/api/player/IPlayer.java index 9251f06..9b1084e 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/player/IPlayer.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/player/IPlayer.java @@ -21,49 +21,49 @@ import stanhebben.zenscript.annotations.ZenMethod; public interface IPlayer { @ZenGetter("id") public String getId(); - + @ZenGetter("name") public String getName(); - + @ZenGetter("data") public IData getData(); - + @ZenMethod public void update(IData data); - + @ZenMethod public void sendChat(IChatMessage message); - + @ZenMethod public void sendChat(String message); - + @ZenGetter("hotbarSize") public int getHotbarSize(); - + @ZenMethod public IItemStack getHotbarStack(int i); - + @ZenGetter("inventorySize") public int getInventorySize(); - + @ZenMethod public IItemStack getInventoryStack(int i); - + @ZenGetter("currentItem") public IItemStack getCurrentItem(); - + @ZenGetter("creative") public boolean isCreative(); - + @ZenGetter("adventure") public boolean isAdventure(); - + @ZenMethod public void give(IItemStack stack); - + // not an exposed method. risks abuse public void openBrowser(String url); - + // not an exposed method, so far. would it be useful? public void copyToClipboard(String value); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/CraftingInfo.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/CraftingInfo.java index 160a565..fd83dac 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/CraftingInfo.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/CraftingInfo.java @@ -16,7 +16,7 @@ import minetweaker.api.world.IDimension; public class CraftingInfo implements ICraftingInfo { private final ICraftingInventory inventory; private final IDimension dimension; - + public CraftingInfo(ICraftingInventory inventory, IDimension dimension) { this.inventory = inventory; this.dimension = dimension; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingInfo.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingInfo.java index 52f3926..8fd7e26 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingInfo.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingInfo.java @@ -19,10 +19,10 @@ import stanhebben.zenscript.annotations.ZenGetter; public interface ICraftingInfo { @ZenGetter("inventory") public ICraftingInventory getInventory(); - + @ZenGetter("player") public IPlayer getPlayer(); - + @ZenGetter("dimension") public IDimension getDimension(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingInventory.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingInventory.java index 3796818..233b265 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingInventory.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingInventory.java @@ -27,7 +27,7 @@ public interface ICraftingInventory { */ @ZenGetter("player") public IPlayer getPlayer(); - + /** * Gets the size of this inventory. * @@ -35,7 +35,7 @@ public interface ICraftingInventory { */ @ZenGetter("size") public int getSize(); - + /** * Gets the width of this inventory. * @@ -43,7 +43,7 @@ public interface ICraftingInventory { */ @ZenGetter("width") public int getWidth(); - + /** * Gets the height of this inventory. * @@ -51,7 +51,7 @@ public interface ICraftingInventory { */ @ZenGetter("height") public int getHeight(); - + /** * Gets the number of stacks that are actually filled in. * @@ -59,7 +59,7 @@ public interface ICraftingInventory { */ @ZenGetter("stackCount") public int getStackCount(); - + /** * Gets the stack at the given location. * @@ -68,9 +68,10 @@ public interface ICraftingInventory { */ @ZenMethod public IItemStack getStack(int i); - + /** - * Gets the stack at the given position. The top left stack is position (0, 0). + * Gets the stack at the given position. The top left stack is position (0, + * 0). * * @param x stack x position * @param y stack y position @@ -78,22 +79,25 @@ public interface ICraftingInventory { */ @ZenMethod public IItemStack getStack(int x, int y); - + /** - * Sets the stack at the given position. The top left stack is position (0, 0). + * Sets the stack at the given position. The top left stack is position (0, + * 0). * * @param x stack x position * @param y stack y position - * @param stack item stack to be set, or null to clear the stack at that position + * @param stack item stack to be set, or null to clear the stack at that + * position */ @ZenMethod public void setStack(int x, int y, IItemStack stack); - + /** * Sets the stack at the given index. * * @param i stack index - * @param stack item stack to be set, or null to clear the stack at that index + * @param stack item stack to be set, or null to clear the stack at that + * index */ @ZenMethod public void setStack(int i, IItemStack stack); diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingRecipe.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingRecipe.java index b579c65..37e2e5e 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingRecipe.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ICraftingRecipe.java @@ -17,12 +17,12 @@ import stanhebben.zenscript.annotations.ZenClass; @ZenClass("minetweaker.recipes.ICraftingRecipe") public interface ICraftingRecipe { public boolean matches(ICraftingInventory inventory); - + public IItemStack getCraftingResult(ICraftingInventory inventory); - + public boolean hasTransformers(); - + public void applyTransformers(ICraftingInventory inventory, IPlayer byPlayer); - + public String toCommandString(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/IFurnaceManager.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/IFurnaceManager.java index a460e28..d20b386 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/IFurnaceManager.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/IFurnaceManager.java @@ -20,13 +20,13 @@ import stanhebben.zenscript.annotations.ZenMethod; public interface IFurnaceManager { @ZenMethod public void remove(IIngredient output, @Optional IIngredient input); - + @ZenMethod public void addRecipe(IItemStack output, IIngredient input, @Optional double xp); - + @ZenMethod public void setFuel(IIngredient item, int fuel); - + @ZenMethod public int getFuel(IItemStack item); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/IRecipeManager.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/IRecipeManager.java index b2fb32a..7154bb1 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/IRecipeManager.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/IRecipeManager.java @@ -23,7 +23,7 @@ public interface IRecipeManager { */ @ZenGetter("all") public List getAll(); - + /** * Returns all crafting recipes resulting in the given ingredient. * @@ -32,7 +32,7 @@ public interface IRecipeManager { */ @ZenMethod public List getRecipesFor(IIngredient ingredient); - + /** * Removes all crafting recipes crafting the specified item. * @@ -41,7 +41,7 @@ public interface IRecipeManager { */ @ZenMethod public int remove(IIngredient output); - + /** * Adds a shaped recipe. * @@ -54,7 +54,7 @@ public interface IRecipeManager { IItemStack output, IIngredient[][] ingredients, @Optional IRecipeFunction function); - + /** * Adds a mirrored shaped recipe. * @@ -67,7 +67,7 @@ public interface IRecipeManager { IItemStack output, IIngredient[][] ingredients, @Optional IRecipeFunction function); - + /** * Adds a shapeless recipe. * @@ -80,7 +80,7 @@ public interface IRecipeManager { IItemStack output, IIngredient[] ingredients, @Optional IRecipeFunction function); - + /** * Removes shaped recipes. * @@ -92,13 +92,14 @@ public interface IRecipeManager { public int removeShaped( IIngredient output, @Optional IIngredient[][] ingredients); - + /** * Removes shapeless recipes. * * @param output recipe output * @param ingredients recipe ingredients - * @param wildcard if the recipe may contain other ingredients too, besides the ones specified + * @param wildcard if the recipe may contain other ingredients too, besides + * the ones specified * @return number of removed recipes */ @ZenMethod @@ -106,7 +107,7 @@ public interface IRecipeManager { IIngredient output, @Optional IIngredient[] ingredients, @Optional boolean wildcard); - + /** * Performs a crafting with the specified ingredients. Returns null if no * crafting recipe exists. diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ShapedRecipe.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ShapedRecipe.java index 7a18115..996540f 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ShapedRecipe.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ShapedRecipe.java @@ -23,10 +23,10 @@ public class ShapedRecipe implements ICraftingRecipe { private final byte[] posy; private final boolean mirrored; private final IRecipeFunction function; - + private final IItemStack output; private final IIngredient[] ingredients; - + public ShapedRecipe(IItemStack output, IIngredient[][] ingredients, IRecipeFunction function, boolean mirrored) { int numIngredients = 0; for (IIngredient[] row : ingredients) { @@ -36,21 +36,21 @@ public class ShapedRecipe implements ICraftingRecipe { } } } - + this.posx = new byte[numIngredients]; this.posy = new byte[numIngredients]; this.output = output; this.ingredients = new IIngredient[numIngredients]; this.function = function; - + int width1 = 0; int height1 = ingredients.length; - + int ix = 0; for (int j = 0; j < ingredients.length; j++) { IIngredient[] row = ingredients[j]; width1 = Math.max(width1, row.length); - + for (int i = 0; i < row.length; i++) { if (row[i] != null) { this.posx[ix] = (byte) i; @@ -60,103 +60,111 @@ public class ShapedRecipe implements ICraftingRecipe { } } } - + this.width = width1; this.height = height1; this.mirrored = mirrored; } - + public int getWidth() { return width; } - + public int getHeight() { return height; } - + public boolean isMirrored() { return mirrored; } - + public IIngredient[] getIngredients() { return ingredients; } - + public byte[] getIngredientsX() { return posx; } - + public byte[] getIngredientsY() { return posy; } - + public IItemStack getOutput() { return output; } - + @Override public boolean matches(ICraftingInventory inventory) { if (inventory.getStackCount() != ingredients.length) { return false; } - + for (int i = 0; i <= inventory.getWidth() - width; i++) { out: for (int j = 0; j <= inventory.getHeight() - height; j++) { for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(posx[k] + i, posy[k] + j); - if (item == null) continue out; - - if (!ingredients[k].matches(item)) continue out; + if (item == null) + continue out; + + if (!ingredients[k].matches(item)) + continue out; } - + return true; } } - + if (mirrored) { for (int i = 0; i <= inventory.getWidth() - width; i++) { out: for (int j = 0; j <= inventory.getHeight() - height; j++) { for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(inventory.getWidth() - (posx[k] + i) - 1, posy[k] + j); - if (item == null) continue out; - - if (!ingredients[k].matches(item)) continue out; + if (item == null) + continue out; + + if (!ingredients[k].matches(item)) + continue out; } return true; } } } - + return false; } - + @Override public IItemStack getCraftingResult(ICraftingInventory inventory) { IItemStack[] stacks = new IItemStack[ingredients.length]; - + for (int i = 0; i <= inventory.getWidth() - width; i++) { out: for (int j = 0; j <= inventory.getHeight() - height; j++) { for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(posx[k] + i, posy[k] + j); - if (item == null) continue out; - - if (!ingredients[k].matches(item)) continue out; + if (item == null) + continue out; + + if (!ingredients[k].matches(item)) + continue out; stacks[k] = item; } - + return doRecipe(inventory, stacks, i, j, output, false); } } - + if (mirrored) { for (int i = 0; i <= inventory.getWidth() - width; i++) { out: for (int j = 0; j <= inventory.getHeight() - height; j++) { for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(inventory.getWidth() - (posx[k] + i) - 1, posy[k] + j); - if (item == null) continue out; - - if (!ingredients[k].matches(item)) continue out; + if (item == null) + continue out; + + if (!ingredients[k].matches(item)) + continue out; stacks[k] = item; } @@ -164,10 +172,10 @@ public class ShapedRecipe implements ICraftingRecipe { } } } - + return null; } - + @Override public boolean hasTransformers() { for (IIngredient ingredient : ingredients) { @@ -175,38 +183,41 @@ public class ShapedRecipe implements ICraftingRecipe { return true; } } - + return false; } - + @Override public void applyTransformers(ICraftingInventory inventory, IPlayer byPlayer) { IItemStack[] stacks = new IItemStack[ingredients.length]; - + for (int i = 0; i <= inventory.getWidth() - width; i++) { out: for (int j = 0; j <= inventory.getHeight() - height; j++) { for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(posx[k] + i, posy[k] + j); - if (item == null) continue out; - + if (item == null) + continue out; + if (!ingredients[k].matches(item)) continue out; stacks[k] = item; } - + doRecipeTransformers(inventory, stacks, i, j, false, byPlayer); return; } } - + if (mirrored) { for (int i = 0; i <= inventory.getWidth() - width; i++) { out: for (int j = 0; j <= inventory.getHeight() - height; j++) { for (int k = 0; k < ingredients.length; k++) { IItemStack item = inventory.getStack(inventory.getWidth() - (posx[k] + i) - 1, posy[k] + j); - if (item == null) continue out; - - if (!ingredients[k].matches(item)) continue out; + if (item == null) + continue out; + + if (!ingredients[k].matches(item)) + continue out; stacks[k] = item; } @@ -216,40 +227,40 @@ public class ShapedRecipe implements ICraftingRecipe { } } } - + @Override public String toCommandString() { StringBuilder result = new StringBuilder(); result.append("recipes.addShaped("); result.append(output); result.append(", ["); - + IIngredient[][] ingredientsArray = new IIngredient[height][width]; for (int i = 0; i < ingredients.length; i++) { ingredientsArray[posy[i]][posx[i]] = ingredients[i]; } - + for (int i = 0; i < ingredientsArray.length; i++) { if (i > 0) { result.append(", "); } - + result.append("["); - + for (int j = 0; j < ingredientsArray[i].length; j++) { if (j > 0) result.append(", "); - + result.append(ingredientsArray[i][j]); } - + result.append("]"); } - + result.append("]);"); return result.toString(); } - + private IItemStack doRecipe( ICraftingInventory inventory, IItemStack[] stacks, @@ -257,7 +268,7 @@ public class ShapedRecipe implements ICraftingRecipe { IItemStack output, boolean mirrored) { // determine output and apply transformations - + if (function != null) { Map tagged = new HashMap(); for (int k = 0; k < ingredients.length; k++) { @@ -270,28 +281,20 @@ public class ShapedRecipe implements ICraftingRecipe { output = function.process(output, tagged, new CraftingInfo(inventory, null)); System.out.println("Ouput: " + output); } - + if (output == null) { return null; } - - /*for (int i = 0; i < ingredients.length; i++) { - IItemStack transformed = ingredients[i].applyTransform(stacks[i]); - if (transformed != stacks[i]) { - if (mirrored) { - inventory.setStack( - inventory.getWidth() - (offx + posx[i]) - 1, - offy + posy[i], - transformed); - } else { - inventory.setStack( - offx + posx[i], - offy + posy[i], - transformed); - } - } - }*/ - + + /* + * for (int i = 0; i < ingredients.length; i++) { IItemStack transformed + * = ingredients[i].applyTransform(stacks[i]); if (transformed != + * stacks[i]) { if (mirrored) { inventory.setStack( inventory.getWidth() + * - (offx + posx[i]) - 1, offy + posy[i], transformed); } else { + * inventory.setStack( offx + posx[i], offy + posy[i], transformed); } } + * } + */ + return output; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ShapelessRecipe.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ShapelessRecipe.java index 6de1c27..6fe3666 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ShapelessRecipe.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/ShapelessRecipe.java @@ -20,34 +20,34 @@ public class ShapelessRecipe implements ICraftingRecipe { private final IItemStack output; private final IRecipeFunction function; private final IIngredient[] ingredients; - + public ShapelessRecipe(IItemStack output, IIngredient[] ingredients, IRecipeFunction function) { this.output = output; this.function = function; this.ingredients = ingredients; } - + public int getSize() { return ingredients.length; } - + public IIngredient[] getIngredients() { return ingredients; } - + public IItemStack getOutput() { return output; } - + @Override public boolean matches(ICraftingInventory inventory) { return matchShapeless(ingredients, inventory) != null; } - + @Override public IItemStack getCraftingResult(ICraftingInventory inventory) { RecipeMatching matching = matchShapeless(ingredients, inventory); - + IItemStack actualOutput = output; if (function != null) { Map map = new HashMap(); @@ -56,21 +56,21 @@ public class ShapelessRecipe implements ICraftingRecipe { map.put(ingredients[i].getMark(), matching.inputs[i]); } } - + actualOutput = function.process(actualOutput, map, new CraftingInfo(inventory, null)); } - + if (actualOutput == null) { return null; } - + return actualOutput; } - + @Override public void applyTransformers(ICraftingInventory inventory, IPlayer byPlayer) { RecipeMatching matching = matchShapeless(ingredients, inventory); - + for (int i = 0; i < ingredients.length; i++) { IIngredient ingredient = ingredients[i]; IItemStack transformed = ingredient.applyTransform(matching.inputs[i], byPlayer); @@ -79,27 +79,27 @@ public class ShapelessRecipe implements ICraftingRecipe { } } } - + @Override public String toCommandString() { StringBuilder result = new StringBuilder(); - + result.append("recipes.addShapeless("); result.append(output); result.append(", ["); - + for (int i = 0; i < ingredients.length; i++) { if (i > 0) result.append(", "); - + result.append(ingredients[i]); } - + result.append("]);"); - + return result.toString(); } - + /** * Reorders ingredients to match the given shapeless recipe. * @@ -116,34 +116,36 @@ public class ShapelessRecipe implements ICraftingRecipe { numItems++; } } - + if (numItems != recipe.length) { return null; } - + IItemStack[] matched = new IItemStack[recipe.length]; int[] indices = new int[recipe.length]; - + outer: for (int i = 0; i < ingredients.getSize(); i++) { IItemStack ingredient = ingredients.getStack(i); - if (ingredient == null) continue; - + if (ingredient == null) + continue; + for (int j = 0; j < recipe.length; j++) { - if (matched[j] != null) continue; - + if (matched[j] != null) + continue; + if (recipe[j].matches(ingredient)) { matched[j] = ingredient; indices[j] = i; continue outer; } } - + return null; } - + return new RecipeMatching(matched, indices); } - + @Override public boolean hasTransformers() { for (IIngredient ingredient : ingredients) { @@ -151,10 +153,10 @@ public class ShapelessRecipe implements ICraftingRecipe { return true; } } - + return false; } - + private static class RecipeMatching { public final IItemStack[] inputs; public final int[] indices; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/UnknownRecipe.java b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/UnknownRecipe.java index dfe818c..3d0ccdb 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/recipes/UnknownRecipe.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/recipes/UnknownRecipe.java @@ -15,7 +15,7 @@ import minetweaker.api.player.IPlayer; */ public class UnknownRecipe implements ICraftingRecipe { private final IItemStack output; - + public UnknownRecipe(IItemStack output) { this.output = output; } @@ -37,7 +37,7 @@ public class UnknownRecipe implements ICraftingRecipe { @Override public void applyTransformers(ICraftingInventory inventory, IPlayer byPlayer) { - + } @Override diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/resource/IResourceManager.java b/MineTweaker3-API/src/main/java/minetweaker/api/resource/IResourceManager.java index 86cfd12..c70e33d 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/resource/IResourceManager.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/resource/IResourceManager.java @@ -16,7 +16,7 @@ public interface IResourceManager { * * @param module * @param name - * @return + * @return */ public IResourceFile getResource(String module, String name); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/server/AbstractServer.java b/MineTweaker3-API/src/main/java/minetweaker/api/server/AbstractServer.java index cec52f5..8defe83 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/server/AbstractServer.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/server/AbstractServer.java @@ -7,8 +7,8 @@ import minetweaker.api.event.PlayerLoggedOutEvent; import minetweaker.util.IEventHandler; /** - * Abstract server implementation. Implements call of which the implementation is - * already fixed by the API. + * Abstract server implementation. Implements call of which the implementation + * is already fixed by the API. * * @author Stan Hebben */ diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/server/CommandValidators.java b/MineTweaker3-API/src/main/java/minetweaker/api/server/CommandValidators.java index 70be81d..97f719f 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/server/CommandValidators.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/server/CommandValidators.java @@ -23,7 +23,7 @@ public class CommandValidators { return MineTweakerAPI.server.isOp(player); } }; - + @ZenGetter public static ICommandValidator isOp() { return ISOP; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/server/IServer.java b/MineTweaker3-API/src/main/java/minetweaker/api/server/IServer.java index 58c643b..68eef56 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/server/IServer.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/server/IServer.java @@ -29,19 +29,19 @@ public interface IServer { ICommandFunction function, @Optional ICommandValidator validator, @Optional ICommandTabCompletion completion); - + @ZenMethod public void removeCommand(String name); - + @ZenMethod public void addMineTweakerCommand(String name, String[] usage, ICommandFunction function); - + @ZenMethod public boolean isOp(IPlayer player); - + @ZenMethod public IEventHandle onPlayerLoggedIn(IEventHandler ev); - + @ZenMethod public IEventHandle onPlayerLoggedOut(IEventHandler ev); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/tooltip/IngredientTooltips.java b/MineTweaker3-API/src/main/java/minetweaker/api/tooltip/IngredientTooltips.java index 1708a7c..e72765d 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/tooltip/IngredientTooltips.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/tooltip/IngredientTooltips.java @@ -25,36 +25,36 @@ import stanhebben.zenscript.annotations.ZenMethod; public class IngredientTooltips { private static final IngredientMap TOOLTIPS = new IngredientMap(); private static final IngredientMap SHIFT_TOOLTIPS = new IngredientMap(); - + @ZenMethod public static void addTooltip(IIngredient ingredient, IFormattedText tooltip) { MineTweakerAPI.apply(new AddTooltipAction(ingredient, tooltip, false)); } - + @ZenMethod public static void addShiftTooltip(IIngredient ingredient, IFormattedText tooltip) { MineTweakerAPI.apply(new AddTooltipAction(ingredient, tooltip, true)); } - + public static List getTooltips(IItemStack item) { return TOOLTIPS.getEntries(item); } - + public static List getShiftTooltips(IItemStack item) { return SHIFT_TOOLTIPS.getEntries(item); } - + // ###################### // ### Action classes ### // ###################### - + private static class AddTooltipAction implements IUndoableAction { private final IIngredient ingredient; private final IFormattedText tooltip; private final boolean shift; - + private IngredientMapEntry entry; - + public AddTooltipAction(IIngredient ingredient, IFormattedText tooltip, boolean shift) { this.ingredient = ingredient; this.tooltip = tooltip; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/util/IngredientMap.java b/MineTweaker3-API/src/main/java/minetweaker/api/util/IngredientMap.java index 070eddd..1e01b32 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/util/IngredientMap.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/util/IngredientMap.java @@ -22,53 +22,53 @@ import minetweaker.api.item.IItemStack; */ public class IngredientMap { private final HashMap>> entries; - + public IngredientMap() { entries = new HashMap>>(); } - + public IngredientMapEntry register(IIngredient ingredient, T entry) { Set items = new HashSet(); for (IItemStack item : ingredient.getItems()) { items.add(item.getDefinition()); } - + IngredientMapEntry actualEntry = new IngredientMapEntry(ingredient, entry); - + for (IItemDefinition item : items) { if (!entries.containsKey(item)) { entries.put(item, new ArrayList>()); } - + entries.get(item).add(actualEntry); } - + return actualEntry; } - + public void unregister(IngredientMapEntry entry) { Set items = new HashSet(); for (IItemStack item : entry.ingredient.getItems()) { items.add(item.getDefinition()); } - + for (IItemDefinition item : items) { if (entries.containsKey(item)) { entries.get(item).remove(entry); } } } - + public T getFirstEntry(IItemStack item) { for (IngredientMapEntry entry : entries.get(item.getDefinition())) { if (entry.ingredient.matches(item)) { return entry.entry; } } - + return null; } - + public List getEntries(IItemStack item) { List> entries = this.entries.get(item.getDefinition()); if (entries != null) { @@ -83,11 +83,11 @@ public class IngredientMap { return Collections.EMPTY_LIST; } } - + public static class IngredientMapEntry { private final IIngredient ingredient; private final T entry; - + public IngredientMapEntry(IIngredient ingredient, T entry) { this.ingredient = ingredient; this.entry = entry; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/util/Position3f.java b/MineTweaker3-API/src/main/java/minetweaker/api/util/Position3f.java index 516b6ca..14337bd 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/util/Position3f.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/util/Position3f.java @@ -18,23 +18,23 @@ public class Position3f { private final float x; private final float y; private final float z; - + public Position3f(float x, float y, float z) { this.x = x; this.y = y; this.z = z; } - + @ZenGetter("x") public float getX() { return x; } - + @ZenGetter("y") public float getY() { return y; } - + @ZenGetter("z") public float getZ() { return z; diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/ILootRegistry.java b/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/ILootRegistry.java index 78b74d1..b2e2e92 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/ILootRegistry.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/ILootRegistry.java @@ -21,16 +21,16 @@ import stanhebben.zenscript.annotations.ZenMethod; public interface ILootRegistry { @ZenMethod public void addChestLoot(String name, WeightedItemStack item); - + @ZenMethod public void addChestLoot(String name, WeightedItemStack item, int min, int max); - + @ZenMethod public void removeChestLoot(String name, IIngredient ingredient); - + @ZenMethod public List getLoot(String name); - + @ZenGetter("lootTypes") public List getLootTypes(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/ISeedRegistry.java b/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/ISeedRegistry.java index c39396b..68e8588 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/ISeedRegistry.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/ISeedRegistry.java @@ -21,10 +21,10 @@ import stanhebben.zenscript.annotations.ZenMethod; public interface ISeedRegistry { @ZenMethod public void addSeed(WeightedItemStack item); - + @ZenMethod public void removeSeed(IIngredient item); - + @ZenGetter("seeds") public List getSeeds(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/IVanilla.java b/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/IVanilla.java index b091548..e8a82ba 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/IVanilla.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/IVanilla.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.annotations.ZenGetter; public interface IVanilla { @ZenGetter("loot") public ILootRegistry getLoot(); - + @ZenGetter("seeds") public ISeedRegistry getSeeds(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/LootEntry.java b/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/LootEntry.java index b78ef07..e423c2f 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/LootEntry.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/vanilla/LootEntry.java @@ -19,7 +19,7 @@ public class LootEntry { private final WeightedItemStack item; private final int minAmount; private final int maxAmount; - + public LootEntry(WeightedItemStack item, int minAmount, int maxAmount) { this.item = item; this.minAmount = minAmount; @@ -35,12 +35,12 @@ public class LootEntry { public int getMinAmount() { return minAmount; } - + @ZenGetter("maxAmount") public int getMaxAmount() { return maxAmount; } - + @Override public String toString() { StringBuilder message = new StringBuilder(); @@ -54,7 +54,7 @@ public class LootEntry { message.append(getMaxAmount()); } message.append(")"); - + return message.toString(); } } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/world/IBlockGroup.java b/MineTweaker3-API/src/main/java/minetweaker/api/world/IBlockGroup.java index 61d13a1..73e0e96 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/world/IBlockGroup.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/world/IBlockGroup.java @@ -19,7 +19,7 @@ import stanhebben.zenscript.annotations.ZenMethod; public interface IBlockGroup { @ZenGetter("dimension") public IDimension getDimension(); - + @ZenMethod public IBlock getBlock(int x, int y, int z); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/api/world/IDimension.java b/MineTweaker3-API/src/main/java/minetweaker/api/world/IDimension.java index 800c4a4..e367254 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/api/world/IDimension.java +++ b/MineTweaker3-API/src/main/java/minetweaker/api/world/IDimension.java @@ -18,7 +18,7 @@ import stanhebben.zenscript.annotations.ZenMethod; public interface IDimension extends IBlockGroup { @ZenGetter public boolean isDay(); - + @ZenMethod public int getBrightness(int x, int y, int z); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/expand/ExpandString.java b/MineTweaker3-API/src/main/java/minetweaker/expand/ExpandString.java index 3fd2f7b..8eccedf 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/expand/ExpandString.java +++ b/MineTweaker3-API/src/main/java/minetweaker/expand/ExpandString.java @@ -31,62 +31,64 @@ public class ExpandString { public static IFormattedText add(String str, IFormattedText formattedText) { return MineTweakerAPI.format.string(str).add(formattedText); } - + @ZenOperator(OperatorType.CAT) public static IFormattedText cat(String str, IFormattedText formattedText) { return add(str, formattedText); } - + @ZenCaster public static IData asData(String value) { return new DataString(value); } - + @ZenCaster public static IChatMessage asChatMessage(String value) { return MineTweakerImplementationAPI.platform.getMessage(value); } - + @ZenCaster public static IFormattedText asFormattedText(String value) { return MineTweakerAPI.format.string(value); } - + @ZenMethod public static List split(String value, String separator, @Optional int maximum) { List result = new ArrayList(); int minIndex = 0; int numSplits = 0; - + while (minIndex + separator.length() <= value.length()) { int index = value.indexOf(separator, minIndex); - if (index < 0) break; + if (index < 0) + break; result.add(value.substring(minIndex, index)); minIndex = index + separator.length(); - + numSplits++; - if (maximum > 0 && numSplits >= maximum) break; + if (maximum > 0 && numSplits >= maximum) + break; } - + result.add(value.substring(minIndex)); return result; } - + @ZenMethod public static int indexOf(String value, String needle) { return value.indexOf(needle); } - + @ZenMethod public static int indexOf(String value, String needle, int fromIndex) { return value.indexOf(needle, fromIndex); } - + @ZenMethod public static int lastIndexOf(String value, String needle) { return value.lastIndexOf(needle); } - + @ZenMethod public static int lastIndexOf(String value, String needle, int fromIndex) { return value.lastIndexOf(value, fromIndex); diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/GlobalFunctions.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/GlobalFunctions.java index f3ef224..67e19ca 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/GlobalFunctions.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/GlobalFunctions.java @@ -13,8 +13,9 @@ import minetweaker.MineTweakerAPI; * @author Stan */ public class GlobalFunctions { - private GlobalFunctions() {} - + private GlobalFunctions() { + } + public static void print(String message) { MineTweakerAPI.logInfo(message); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/GlobalRegistry.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/GlobalRegistry.java index d380272..6e81955 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/GlobalRegistry.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/GlobalRegistry.java @@ -53,23 +53,24 @@ public class GlobalRegistry { private static final IZenErrorLogger errors = new MyErrorLogger(); private static final IZenCompileEnvironment environment = new MyCompileEnvironment(); private static final Map expansions = new HashMap(); - + 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)); } - - private GlobalRegistry() {} - + + 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) { try { for (Annotation annotation : cls.getAnnotations()) { @@ -85,15 +86,15 @@ public class GlobalRegistry { ex.printStackTrace(); } } - + public static void registerRemover(IRecipeRemover remover) { removers.add(remover); } - + public static void registerBracketHandler(IBracketHandler handler) { bracketHandlers.add(handler); } - + public static void registerNativeClass(Class cls) { try { ZenTypeNative type = new ZenTypeNative(cls); @@ -104,17 +105,17 @@ public class GlobalRegistry { ex.printStackTrace(); } } - + public static TypeRegistry getTypeRegistry() { return types; } - + public static void remove(IIngredient ingredient) { for (IRecipeRemover remover : removers) { remover.remove(ingredient); } } - + public static IZenSymbol resolveBracket(IEnvironmentGlobal environment, List tokens) { for (IBracketHandler handler : bracketHandlers) { IZenSymbol symbol = handler.resolve(environment, tokens); @@ -122,16 +123,17 @@ public class GlobalRegistry { return symbol; } } - + return null; } - + public static IZenSymbol getStaticFunction(Class cls, String name, Class... arguments) { IJavaMethod method = JavaMethod.get(types, cls, name, arguments); - if (method == null) return null; + if (method == null) + return null; return new SymbolJavaStaticMethod(method); } - + public static IZenSymbol getStaticField(Class cls, String name) { try { Field field = cls.getDeclaredField(name); @@ -144,11 +146,11 @@ public class GlobalRegistry { return null; } } - + public static IEnvironmentGlobal makeGlobalEnvironment(Map classes) { return new MyGlobalEnvironment(classes); } - + private static class MyErrorLogger implements IZenErrorLogger { @Override public void error(ZenPosition position, String message) { @@ -168,7 +170,7 @@ public class GlobalRegistry { } } } - + private static class MyCompileEnvironment implements IZenCompileEnvironment { @Override public IZenErrorLogger getErrorLogger() { @@ -204,18 +206,18 @@ public class GlobalRegistry { return expansions.get(type); } } - + private static class MyGlobalEnvironment implements IEnvironmentGlobal { private final Map classes; private final Map symbols; private final ClassNameGenerator generator; - + public MyGlobalEnvironment(Map classes) { this.classes = classes; symbols = new HashMap(); generator = new ClassNameGenerator(); } - + @Override public IZenCompileEnvironment getEnvironment() { return environment; diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/ILogger.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/ILogger.java index 7cd3934..281fd3c 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/ILogger.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/ILogger.java @@ -15,16 +15,16 @@ import stanhebben.zenscript.annotations.ZenMethod; public interface ILogger { @ZenMethod public void logCommand(String message); - + @ZenMethod public void logInfo(String message); - + @ZenMethod public void logWarning(String message); - + @ZenMethod public void logError(String message); - + @ZenMethod public void logError(String message, Throwable exception); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/IScriptIterator.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/IScriptIterator.java index 6dac8a0..4df6685 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/IScriptIterator.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/IScriptIterator.java @@ -15,10 +15,10 @@ import java.io.InputStream; */ public interface IScriptIterator { public String getGroupName(); - + public boolean next(); - + public String getName(); - + public InputStream open() throws IOException; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/ITweaker.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/ITweaker.java index aedd35f..e18fd0a 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/ITweaker.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/ITweaker.java @@ -21,10 +21,10 @@ public interface ITweaker { /** * Retrieves the script data to be loaded. * - * @return + * @return */ public byte[] getStagedScriptData(); - + /** * Executes a specified MineTweaker action. Will print a log message and * adds the action to the undo list. @@ -32,7 +32,7 @@ public interface ITweaker { * @param action action to execute */ public void apply(IUndoableAction action); - + /** * Removes a specific item from all known recipes handlers. * @@ -40,7 +40,7 @@ public interface ITweaker { */ @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 @@ -49,20 +49,20 @@ public interface ITweaker { * @return stuck action list */ public List rollback(); - + /** * Sets the script provider. * * @param provider - * @return + * @return */ public void setScriptProvider(IScriptProvider provider); - + /** * Executes all scripts provided by the script provider. */ public void load(); - + /** * Retrieves the data from the scripts that were loaded last. * diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/MTTweaker.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/MTTweaker.java index ce80aa9..324c138 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/MTTweaker.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/MTTweaker.java @@ -37,27 +37,27 @@ import stanhebben.zenscript.parser.ParseException; */ public class MTTweaker implements ITweaker { private static final boolean DEBUG = false; - + private final List actions = new ArrayList(); private final Set wereStuck = new LinkedHashSet(); private final Map stuckOverridable = new HashMap(); - + private IScriptProvider scriptProvider; private byte[] scriptData; - + @Override public byte[] getStagedScriptData() { return ScriptProviderMemory.collect(scriptProvider); } - + @Override public void apply(IUndoableAction action) { MineTweakerAPI.logInfo(action.describe()); - + Object overrideKey = action.getOverrideKey(); if (wereStuck.contains(action)) { wereStuck.remove(action); - + if (overrideKey != null) { stuckOverridable.remove(overrideKey); } @@ -66,10 +66,10 @@ public class MTTweaker implements ITweaker { wereStuck.remove(stuckOverridable.get(overrideKey)); stuckOverridable.remove(overrideKey); } - + action.apply(); } - + actions.add(action); } @@ -90,7 +90,7 @@ public class MTTweaker implements ITweaker { MineTweakerAPI.logInfo("[Stuck] " + action.describe()); stuck.add(0, action); wereStuck.add(action); - + Object overrideKey = action.getOverrideKey(); if (overrideKey != null) { stuckOverridable.put(overrideKey, action); @@ -109,7 +109,7 @@ public class MTTweaker implements ITweaker { @Override public void load() { System.out.println("Loading scripts"); - + scriptData = ScriptProviderMemory.collect(scriptProvider); Set executed = new HashSet(); @@ -129,26 +129,27 @@ public class MTTweaker implements ITweaker { Reader reader = null; try { reader = new InputStreamReader(new BufferedInputStream(script.open())); - + String filename = script.getName(); String className = extractClassName(filename); - + ZenTokener parser = new ZenTokener(reader, environmentGlobal.getEnvironment()); ZenParsedFile pfile = new ZenParsedFile(filename, className, parser, environmentGlobal); files.add(pfile); } catch (IOException ex) { MineTweakerAPI.logError("Could not load script " + script.getName() + ": " + ex.getMessage()); } catch (ParseException ex) { - //ex.printStackTrace(); + // ex.printStackTrace(); MineTweakerAPI.logError("Error parsing " + ex.getFile().getFileName() + ":" + ex.getLine() + " -- " + ex.getExplanation()); } catch (Exception ex) { MineTweakerAPI.logError("Error loading " + script.getName() + ": " + ex.toString(), ex); } - + if (reader != null) { try { reader.close(); - } catch (IOException ex) {} + } catch (IOException ex) { + } } } @@ -165,7 +166,7 @@ public class MTTweaker implements ITweaker { } } } - + if (wereStuck.size() > 0) { MineTweakerAPI.logWarning(Integer.toString(wereStuck.size()) + " modifications were stuck"); for (IUndoableAction action : wereStuck) { diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorDirectory.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorDirectory.java index ba8db00..b57bd7a 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorDirectory.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorDirectory.java @@ -24,10 +24,10 @@ public class ScriptIteratorDirectory implements IScriptIterator { private final File directory; private Iterator contents; private File current; - + public ScriptIteratorDirectory(File directory) { this.directory = directory; - + File scriptDir = new File(directory, "scripts"); List contentsList = new ArrayList(); if (scriptDir.exists()) { @@ -60,7 +60,7 @@ public class ScriptIteratorDirectory implements IScriptIterator { public InputStream open() throws IOException { return new BufferedInputStream(new FileInputStream(current)); } - + private static void iterate(File directory, List contentsList) { for (File file : directory.listFiles()) { if (file.isDirectory()) { diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorSingle.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorSingle.java index 75e9089..086b44e 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorSingle.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorSingle.java @@ -20,7 +20,7 @@ import minetweaker.runtime.IScriptIterator; public class ScriptIteratorSingle implements IScriptIterator { private final File file; private boolean first = true; - + public ScriptIteratorSingle(File file) { this.file = file; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorZip.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorZip.java index 13feb4a..9cb87be 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorZip.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptIteratorZip.java @@ -26,10 +26,10 @@ public class ScriptIteratorZip implements IScriptIterator { private final ZipFile zipFile; private final Iterator entries; private ZipEntry current; - + public ScriptIteratorZip(File file) throws IOException { this.file = file; - + zipFile = new ZipFile(file); List entriesList = new ArrayList(); Enumeration original = zipFile.entries(); @@ -39,7 +39,7 @@ public class ScriptIteratorZip implements IScriptIterator { entriesList.add(entry); } } - + entries = entriesList.iterator(); } diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderCascade.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderCascade.java index 8d2b368..4d530be 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderCascade.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderCascade.java @@ -18,30 +18,30 @@ import minetweaker.runtime.IScriptProvider; */ public class ScriptProviderCascade implements IScriptProvider { private final IScriptProvider[] providers; - + public ScriptProviderCascade(IScriptProvider... providers) { this.providers = providers; } - + @Override public Iterator getScripts() { return new MyScripterator(); } - + private class MyScripterator implements Iterator { private final Set executed = new HashSet(); - + private int currentIndex = providers.length - 1; private Iterator current; private IScriptIterator currentValue; - + public MyScripterator() { currentIndex = providers.length - 1; current = providers[currentIndex].getScripts(); - + advance(); } - + @Override public boolean hasNext() { return currentIndex >= 0; @@ -51,29 +51,40 @@ public class ScriptProviderCascade implements IScriptProvider { public IScriptIterator next() { IScriptIterator result = currentValue; executed.add(result.getGroupName()); - + advance(); - + return result; } - + private void advance() { do { while (!current.hasNext()) { currentIndex--; - if (currentIndex < 0) return; - + if (currentIndex < 0) + return; + current = providers[currentIndex].getScripts(); } - if (currentIndex < 0) break; - + if (currentIndex < 0) + break; + currentValue = current.next(); } while (executed.contains(currentValue.getGroupName()) && hasNext()); } @Override public void remove() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. } } } diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderCustom.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderCustom.java index 1315236..78d0891 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderCustom.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderCustom.java @@ -25,42 +25,42 @@ import minetweaker.runtime.IScriptProvider; */ public class ScriptProviderCustom implements IScriptProvider { private static final Charset UTF8 = Charset.forName("UTF-8"); - + private final String moduleName; private final List scripts; - + public ScriptProviderCustom(String moduleName) { this.moduleName = moduleName; scripts = new ArrayList(); } - + public void add(String name, byte[] content) { scripts.add(new CustomScript(name, content)); } - + public void add(String name, String content) { add(name, content.getBytes(UTF8)); } - + @Override public Iterator getScripts() { return Collections.singleton(new CustomScriptIterator()).iterator(); } - + private class CustomScript { private final String name; private final byte[] content; - + public CustomScript(String name, byte[] content) { this.name = name; this.content = content; } } - + private class CustomScriptIterator implements IScriptIterator { private CustomScript current; private final Iterator iterator = scripts.iterator(); - + @Override public String getGroupName() { return moduleName; diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderDirectory.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderDirectory.java index 969ea78..be1c5c5 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderDirectory.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderDirectory.java @@ -21,10 +21,11 @@ import minetweaker.runtime.IScriptProvider; */ public class ScriptProviderDirectory implements IScriptProvider { private final File directory; - + public ScriptProviderDirectory(File directory) { - if (directory == null) throw new IllegalArgumentException("directory cannot be null"); - + if (directory == null) + throw new IllegalArgumentException("directory cannot be null"); + this.directory = directory; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderMemory.java b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderMemory.java index 21f5937..bff4ad1 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderMemory.java +++ b/MineTweaker3-API/src/main/java/minetweaker/runtime/providers/ScriptProviderMemory.java @@ -37,7 +37,7 @@ public class ScriptProviderMemory implements IScriptProvider { DeflaterOutputStream deflater = new DeflaterOutputStream(output); DataOutputStream deflaterData = new DataOutputStream(deflater); Set executed = new HashSet(); - + Iterator scripts = provider.getScripts(); while (scripts.hasNext()) { IScriptIterator script = scripts.next(); @@ -50,8 +50,9 @@ public class ScriptProviderMemory implements IScriptProvider { while (script.next()) { String name = script.getName(); byte[] data = FileUtil.read(script.open()); - if (data.length == 0) continue; // skip empty files - + if (data.length == 0) + continue; // skip empty files + deflaterData.writeUTF(name); deflaterData.writeInt(data.length); deflaterData.write(data); @@ -60,21 +61,21 @@ public class ScriptProviderMemory implements IScriptProvider { deflaterData.writeUTF(""); } } - + deflaterData.writeUTF(""); - + deflater.close(); } catch (IOException ex) { MineTweakerAPI.logError("Could not collect scripts: " + ex.getMessage()); } return output.toByteArray(); } - + private final Map modules; - + public ScriptProviderMemory(byte[] scripts) { modules = new HashMap(); - + try { InflaterInputStream inflater = new InflaterInputStream(new ByteArrayInputStream(scripts)); DataInputStream inflaterData = new DataInputStream(inflater); @@ -82,20 +83,20 @@ public class ScriptProviderMemory implements IScriptProvider { String moduleName = inflaterData.readUTF(); while (moduleName.length() > 0) { List files = new ArrayList(); - + 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(); } modules.put(moduleName, new MemoryModule(moduleName, files)); - + moduleName = inflaterData.readUTF(); } - + inflaterData.close(); } catch (IOException ex) { MineTweakerAPI.logError("Could not load transmitted scripts: " + ex.getMessage()); @@ -106,10 +107,10 @@ public class ScriptProviderMemory implements IScriptProvider { public Iterator getScripts() { return new ProviderIterator(); } - + private class ProviderIterator implements Iterator { private final Iterator baseIterator = modules.values().iterator(); - + @Override public boolean hasNext() { return baseIterator.hasNext(); @@ -122,21 +123,30 @@ public class ScriptProviderMemory implements IScriptProvider { @Override public void remove() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. } } - + private class ScriptIterator implements IScriptIterator { private final MemoryModule module; private final Iterator files; private MemoryFile current; - + public ScriptIterator(MemoryModule module) { this.module = module; files = module.data.iterator(); current = null; } - + @Override public String getGroupName() { return module.name; @@ -162,21 +172,21 @@ public class ScriptProviderMemory implements IScriptProvider { return new ByteArrayInputStream(current.data); } } - + private class MemoryModule { private final String name; private final List data; - + public MemoryModule(String name, List data) { this.name = name; this.data = data; } } - + private class MemoryFile { private final String name; private final byte[] data; - + public MemoryFile(String name, byte[] data) { this.name = name; this.data = data; diff --git a/MineTweaker3-API/src/main/java/minetweaker/util/ArrayUtil.java b/MineTweaker3-API/src/main/java/minetweaker/util/ArrayUtil.java index ea2f742..618d3ce 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/util/ArrayUtil.java +++ b/MineTweaker3-API/src/main/java/minetweaker/util/ArrayUtil.java @@ -19,25 +19,25 @@ import minetweaker.api.item.IItemTransformer; public class ArrayUtil { public static final IItemCondition[] EMPTY_CONDITIONS = new IItemCondition[0]; public static final IItemTransformer[] EMPTY_TRANSFORMERS = new IItemTransformer[0]; - + public static IItemCondition[] append(IItemCondition[] values, IItemCondition value) { IItemCondition[] result = Arrays.copyOf(values, values.length + 1); result[values.length] = value; return result; } - + public static IItemTransformer[] append(IItemTransformer[] values, IItemTransformer value) { IItemTransformer[] result = Arrays.copyOf(values, values.length + 1); result[values.length] = value; return result; } - + public static IIngredient[] append(IIngredient[] values, IIngredient value) { IIngredient[] result = Arrays.copyOf(values, values.length + 1); result[values.length] = value; return result; } - + public static IBlockPattern[] append(IBlockPattern[] values, IBlockPattern value) { IBlockPattern[] result = Arrays.copyOf(values, values.length + 1); result[values.length] = value; diff --git a/MineTweaker3-API/src/main/java/minetweaker/util/CloseablePriorityList.java b/MineTweaker3-API/src/main/java/minetweaker/util/CloseablePriorityList.java index cfe7e61..1d1b5cc 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/util/CloseablePriorityList.java +++ b/MineTweaker3-API/src/main/java/minetweaker/util/CloseablePriorityList.java @@ -16,13 +16,13 @@ import java.util.Iterator; */ public class CloseablePriorityList implements Iterable { private CloseableEntry first; - + /** * Adds a new item to the list. The new item will be inserted at the head of * the list. * * @param value - * @return + * @return */ public Closeable add(T value) { if (first == null) { @@ -33,18 +33,18 @@ public class CloseablePriorityList implements Iterable { first.prev = entry; first = entry; } - + return first; } - + @Override public Iterator iterator() { return new MyIterator(); } - + private class MyIterator implements Iterator { private CloseableEntry current = null; - + @Override public boolean hasNext() { return current == null || current.next != null; @@ -58,15 +58,24 @@ public class CloseablePriorityList implements Iterable { @Override public void remove() { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. } } - + private class CloseableEntry implements Closeable { private final T value; private CloseableEntry next; private CloseableEntry prev; - + public CloseableEntry(T value) { this.value = value; } diff --git a/MineTweaker3-API/src/main/java/minetweaker/util/EventList.java b/MineTweaker3-API/src/main/java/minetweaker/util/EventList.java index 4e87612..4e3e62b 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/util/EventList.java +++ b/MineTweaker3-API/src/main/java/minetweaker/util/EventList.java @@ -15,15 +15,15 @@ import minetweaker.api.event.IEventHandle; public class EventList { private EventNode first = null; private EventNode last = null; - + public void clear() { first = last = null; } - + public IEventHandle add(IEventHandler handler) { EventNode node = new EventNode(handler, last, null); - - synchronized(this) { + + synchronized (this) { if (first == null) { first = node; } @@ -32,45 +32,45 @@ public class EventList { } last = node; } - + return node; } - + public boolean hasHandlers() { return first != null; } - + public boolean isEmpty() { return first == null; } - + public void publish(T event) { EventNode current = null; - - synchronized(this) { + + synchronized (this) { current = first; } - + while (current != null) { current.handler.handle(event); - - synchronized(this) { + + synchronized (this) { current = current.next; } } } - + private class EventNode implements IEventHandle { private final IEventHandler handler; private EventNode next; private EventNode prev; - + public EventNode(IEventHandler handler, EventNode prev, EventNode next) { this.handler = handler; this.prev = prev; this.next = next; } - + @Override public void close() { synchronized (EventList.this) { diff --git a/MineTweaker3-API/src/main/java/minetweaker/util/StringUtil.java b/MineTweaker3-API/src/main/java/minetweaker/util/StringUtil.java index 25a61ad..61295e1 100644 --- a/MineTweaker3-API/src/main/java/minetweaker/util/StringUtil.java +++ b/MineTweaker3-API/src/main/java/minetweaker/util/StringUtil.java @@ -16,14 +16,15 @@ import java.nio.charset.Charset; public class StringUtil { private static final Charset UTF8 = Charset.forName("UTF-8"); - - private StringUtil() {} - + + private StringUtil() { + } + public static String decodeUTF8(byte[] data) { return UTF8.decode(ByteBuffer.wrap(data)).toString().trim(); } - + public static byte[] encodeUTF8(String data) { return UTF8.encode(data).array(); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/api/minecraft/MineTweakerMC.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/api/minecraft/MineTweakerMC.java index e1a565b..b48cf2c 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/api/minecraft/MineTweakerMC.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/api/minecraft/MineTweakerMC.java @@ -45,7 +45,7 @@ import net.minecraftforge.oredict.OreDictionary; public class MineTweakerMC { private static final Map blockDefinitions = new HashMap(); public static final IBiome[] biomes; - + static { biomes = new IBiome[BiomeGenBase.getBiomeGenArray().length]; for (int i = 0; i < BiomeGenBase.getBiomeGenArray().length; i++) { @@ -53,9 +53,10 @@ public class MineTweakerMC { biomes[i] = new MCBiome(BiomeGenBase.getBiomeGenArray()[i]); } } - - private MineTweakerMC() {} - + + private MineTweakerMC() { + } + /** * Returns the Minecraft item for this MineTweaker item. * @@ -63,15 +64,16 @@ public class MineTweakerMC { * @return minecraft item stack */ public static ItemStack getItemStack(IItemStack item) { - if (item == null) return null; - + if (item == null) + return null; + Object internal = item.getInternal(); if (internal == null || !(internal instanceof ItemStack)) { MineTweakerAPI.logError("Not a valid item stack: " + item); } return (ItemStack) internal; } - + /** * Returns the Minecraft ingredient for this ingredient. This method is only * useful for ingredients that represent a single item stack. @@ -80,27 +82,29 @@ public class MineTweakerMC { * @return minecraft item stack */ public static ItemStack getItemStack(IIngredient ingredient) { - if (ingredient == null) return null; - + if (ingredient == null) + return null; + List items = ingredient.getItems(); if (items.size() != 1) { MineTweakerAPI.logError("Not an ingredient with a single item: " + ingredient); } return getItemStack(items.get(0)); } - + /** * Returns the MineTweaker item stack for this item. * * @param item minecraft item stack - * @return minetweaker item stack + * @return minetweaker item stack */ public static IItemStack getIItemStack(ItemStack item) { - if (item == null) return null; - + if (item == null) + return null; + return new MCItemStack(item); } - + /** * Constructs an item stack with wildcard size. * @@ -108,11 +112,12 @@ public class MineTweakerMC { * @return minetweaker stack */ public static IItemStack getIItemStackWildcardSize(ItemStack item) { - if (item == null) return null; - + if (item == null) + return null; + return new MCItemStack(item, true); } - + /** * Constructs an item stack with wildcard size. * @@ -121,11 +126,12 @@ public class MineTweakerMC { * @return minetweaker stack */ public static IItemStack getIItemStackWildcardSize(Item item, int meta) { - if (item == null) return null; - + if (item == null) + return null; + return new MCItemStack(new ItemStack(item, 1, meta), true); } - + /** * Constructs an item stack with wildcard damage. * @@ -134,11 +140,12 @@ public class MineTweakerMC { * @return minetweaker item stack */ public static IItemStack getIItemStackWildcard(Item item, int amount) { - if (item == null) return null; - + if (item == null) + return null; + return new MCItemStack(new ItemStack(item, 1, OreDictionary.WILDCARD_VALUE)); } - + public static ItemStack[] getExamples(IIngredient ingredient) { List examples = ingredient.getItems(); ItemStack[] result = new ItemStack[examples.size()]; @@ -147,7 +154,7 @@ public class MineTweakerMC { } return result; } - + /** * Constructs an item stack with given item, damage and amount. * @@ -157,11 +164,12 @@ public class MineTweakerMC { * @return minetweaker item stack */ public static IItemStack getItemStack(Item item, int amount, int damage) { - if (item == null) return null; - + if (item == null) + return null; + return new MCItemStack(new ItemStack(item, amount, damage)); } - + /** * Converts an array of minetweaker item stacks into an array of minecraft * item stacks. @@ -170,8 +178,9 @@ public class MineTweakerMC { * @return minecraft item stacks */ public static ItemStack[] getItemStacks(IItemStack... items) { - if (items == null) return null; - + if (items == null) + return null; + ItemStack[] output = new ItemStack[items.length]; for (int i = 0; i < items.length; i++) { Object internal = items[i].getInternal(); @@ -181,7 +190,7 @@ public class MineTweakerMC { } return output; } - + /** * Converts a list of minetweaker item stacks into an array of minecraft * item stacks. @@ -190,8 +199,9 @@ public class MineTweakerMC { * @return minecraft items */ public static ItemStack[] getItemStacks(List items) { - if (items == null) return null; - + if (items == null) + return null; + ItemStack[] output = new ItemStack[items.size()]; for (int i = 0; i < items.size(); i++) { Object internal = items.get(i).getInternal(); @@ -203,7 +213,7 @@ public class MineTweakerMC { } return output; } - + /** * Converts an array of minecraft item stacks into an array of minetweaker * item stacks. @@ -212,15 +222,16 @@ public class MineTweakerMC { * @return minetweaker item stacks */ public static IItemStack[] getIItemStacks(ItemStack... items) { - if (items == null) return null; - + if (items == null) + return null; + IItemStack[] result = new IItemStack[items.length]; for (int i = 0; i < items.length; i++) { result[i] = new MCItemStack(items[i]); } return result; } - + /** * Converts a list of minecraft item stacks into an array of minetweaker * item stacks. @@ -229,15 +240,16 @@ public class MineTweakerMC { * @return minetweaker item stacks */ public static IItemStack[] getIItemStacks(List items) { - if (items == null) return null; - + if (items == null) + return null; + IItemStack[] result = new IItemStack[items.size()]; for (int i = 0; i < result.length; i++) { result[i] = new MCItemStack(items.get(i)); } return result; } - + /** * Gets the ore dictionary entry with the given name. If the entry didn't * exist yet, it will create it and return an empty entry. @@ -248,7 +260,7 @@ public class MineTweakerMC { public static IOreDictEntry getOreDict(String name) { return new MCOreDictEntry(name); } - + /** * Converts a Minecraft player into a MineTweaker player. * @@ -256,11 +268,12 @@ public class MineTweakerMC { * @return minetweaker player */ public static IPlayer getIPlayer(EntityPlayer player) { - if (player == null) return null; - + if (player == null) + return null; + return new MCPlayer(player); } - + /** * Converts a MineTweaker player into a Minecraft player. * @@ -268,15 +281,16 @@ public class MineTweakerMC { * @return minecraft player */ public static EntityPlayer getPlayer(IPlayer player) { - if (player == null) return null; - + if (player == null) + return null; + if (!(player instanceof MCPlayer)) { MineTweakerAPI.logError("Invalid player: " + player); } - + return ((MCPlayer) player).getInternal(); } - + /** * Converts a Minecraft NBT to an IData instance. The IData instance is * immutable (not modifyiable). @@ -285,11 +299,12 @@ public class MineTweakerMC { * @return IData value */ public static IData getIData(NBTBase nbt) { - if (nbt == null) return null; - + if (nbt == null) + return null; + return NBTConverter.from(nbt, true); } - + /** * Converts a Minecraft NBT to a modifyable IData instance. * @@ -297,11 +312,12 @@ public class MineTweakerMC { * @return mutable IData value */ public static IData getIDataModifyable(NBTBase nbt) { - if (nbt == null) return null; - + if (nbt == null) + return null; + return NBTConverter.from(nbt, false); } - + /** * Converts an IData instance to an NBT value. * @@ -309,11 +325,12 @@ public class MineTweakerMC { * @return nbt data */ public static NBTBase getNBT(IData data) { - if (data == null) return null; - + if (data == null) + return null; + return NBTConverter.from(data); } - + /** * Converts an IData instance to an NBT Tag compound. * @@ -321,11 +338,12 @@ public class MineTweakerMC { * @return nbt compound data */ public static NBTTagCompound getNBTCompound(IData data) { - if (data == null) return null; - + if (data == null) + return null; + return (NBTTagCompound) NBTConverter.from(data); } - + /** * Retrieves the block at the given position. * @@ -338,7 +356,7 @@ public class MineTweakerMC { public static IBlock getBlock(IBlockAccess blocks, int x, int y, int z) { return new MCWorldBlock(blocks, x, y, z); } - + /** * Retrieves the block definition for the given block. * @@ -351,7 +369,7 @@ public class MineTweakerMC { } return blockDefinitions.get(block); } - + /** * Retrieves the dimension instance for a given world. * @@ -359,11 +377,12 @@ public class MineTweakerMC { * @return dimension */ public static IDimension getDimension(World world) { - if (world == null) return null; - + if (world == null) + return null; + return new MCDimension(world); } - + /** * Returns an instance of the given block. * @@ -373,7 +392,7 @@ public class MineTweakerMC { public static IBlock getBlockAnyMeta(Block block) { return new MCSpecificBlock(block, OreDictionary.WILDCARD_VALUE); } - + /** * Returns an instance of the given block. * @@ -384,21 +403,21 @@ public class MineTweakerMC { public static IBlock getBlock(Block block, int meta) { return new MCSpecificBlock(block, meta); } - + /** * Retrieves the block from an item stack. * * @param itemStack - * @return + * @return */ public static Block getBlock(IItemStack itemStack) { return ((MCBlockDefinition) itemStack.asBlock().getDefinition()).getInternalBlock(); } - + public static Block getBlock(IBlock block) { return ((MCBlockDefinition) block.getDefinition()).getInternalBlock(); } - + /** * Retrieves the internal fluid stack of the given stack. * @@ -408,29 +427,30 @@ public class MineTweakerMC { public static FluidStack getLiquidStack(ILiquidStack stack) { if (stack == null) return null; - + return (FluidStack) stack.getInternal(); } - + /** * Converts an array of MT liquid stacks into an array of MCF fluid stacks * */ public static FluidStack[] getLiquidStacks(ILiquidStack[] stacks) { - if(stacks == null) { + if (stacks == null) { return null; } - + FluidStack[] res = new FluidStack[stacks.length]; - + for (int i = 0; i < stacks.length; i++) { ILiquidStack liquidStack = stacks[i]; res[i] = getLiquidStack(liquidStack); } return res; } - + private static final HashMap oreDictArrays = new HashMap(); + public static IOreDictEntry getOreDictEntryFromArray(List array) { if (!oreDictArrays.containsKey(array)) { for (String ore : OreDictionary.getOreNames()) { @@ -439,10 +459,10 @@ public class MineTweakerMC { } } } - + return oreDictArrays.get(array); } - + /** * Converts a Minecraft ingredient to a MineTweaker ingredient. * @@ -460,11 +480,11 @@ public class MineTweakerMC { return getIItemStack((ItemStack) ingredient); } else if (ingredient instanceof List) { IOreDictEntry entry = getOreDictEntryFromArray((List) ingredient); - + if (entry == null) { return IngredientUnknown.INSTANCE; } - + return entry; } else if (ingredient instanceof FluidStack) { return new MCLiquidStack((FluidStack) ingredient); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/ForgeEventHandler.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/ForgeEventHandler.java index a0047b2..657effb 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/ForgeEventHandler.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/ForgeEventHandler.java @@ -28,18 +28,18 @@ public class ForgeEventHandler { MineTweakerMC.getIPlayer(ev.entityPlayer), MineTweakerMC.getDimension(ev.world), ev.x, ev.y, ev.z - ); - + ); + MineTweakerImplementationAPI.events.publishPlayerInteract(event); } - + @SubscribeEvent public void onItemTooltip(ItemTooltipEvent ev) { IItemStack itemStack = MineTweakerMC.getIItemStack(ev.itemStack); for (IFormattedText tooltip : IngredientTooltips.getTooltips(itemStack)) { ev.toolTip.add(((IMCFormattedString) tooltip).getTooltipString()); } - + if (Keyboard.isKeyDown(Keyboard.KEY_LSHIFT) || Keyboard.isKeyDown(Keyboard.KEY_RSHIFT)) { for (IFormattedText tooltip : IngredientTooltips.getShiftTooltips(itemStack)) { ev.toolTip.add(((IMCFormattedString) tooltip).getTooltipString()); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/GuiCannotRemodify.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/GuiCannotRemodify.java index e9d7a96..452526b 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/GuiCannotRemodify.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/GuiCannotRemodify.java @@ -5,8 +5,8 @@ import net.minecraft.client.gui.GuiScreen; /** * This screen is shown when a client has been modified with a permanent - * modification and the player logs into a game with a different script. It - * asks the player to restart the game. + * modification and the player logs into a game with a different script. It asks + * the player to restart the game. * * @author Stan Hebben */ @@ -14,19 +14,19 @@ public class GuiCannotRemodify extends GuiScreen { private final String message1; private final String message2; private final String message3; - + public GuiCannotRemodify(String message1, String message2, String message3) { this.message1 = message1; this.message2 = message2; this.message3 = message3; } - + @Override public void initGui() { - this.buttonList.clear(); - this.buttonList.add( - new GuiButton(0, this.width / 2 - 100, this.height / 4 + 120 + 12, "Close") - ); + this.buttonList.clear(); + this.buttonList.add( + new GuiButton(0, this.width / 2 - 100, this.height / 4 + 120 + 12, "Close") + ); } @Override @@ -47,14 +47,14 @@ public class GuiCannotRemodify extends GuiScreen { message3, this.width / 2, this.height / 2 - 0, 11184810); - + super.drawScreen(par1, par2, par3); } - + @Override protected void actionPerformed(GuiButton par1GuiButton) { - if (par1GuiButton.id == 0) { - System.exit(0); - } - } + if (par1GuiButton.id == 0) { + System.exit(0); + } + } } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/MCPlatformFunctions.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/MCPlatformFunctions.java index 2a0ed32..6534b2a 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/MCPlatformFunctions.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/MCPlatformFunctions.java @@ -21,9 +21,10 @@ import net.minecraft.item.Item; */ public class MCPlatformFunctions implements IPlatformFunctions { public static final MCPlatformFunctions INSTANCE = new MCPlatformFunctions(); - - private MCPlatformFunctions() {} - + + private MCPlatformFunctions() { + } + @Override public IChatMessage getMessage(String message) { return new MCChatMessage(message); @@ -37,7 +38,8 @@ public class MCPlatformFunctions implements IPlatformFunctions { @Override public IItemDefinition getItemDefinition(int id) { Item item = Item.getItemById(id); - if (item == null) return null; + if (item == null) + return null; String sid = Item.itemRegistry.getNameForObject(item); return new MCItemDefinition(sid, item); } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/MineTweakerMod.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/MineTweakerMod.java index b4b0072..9060444 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/MineTweakerMod.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/MineTweakerMod.java @@ -60,37 +60,37 @@ import net.minecraftforge.common.MinecraftForge; public class MineTweakerMod { public static final String MODID = "MineTweaker3"; public static final String MCVERSION = "1.7.10"; - + public static final SimpleNetworkWrapper NETWORK = NetworkRegistry.INSTANCE.newSimpleChannel(MODID); - + private static final String[] REGISTRIES = { - "minetweaker.mods.ic2.ClassRegistry", - "minetweaker.mods.nei.ClassRegistry", - "minetweaker.mods.mfr.ClassRegistry", - "minetweaker.mods.gregtech.ClassRegistry", - "minetweaker.mods.buildcraft.ClassRegistry" + "minetweaker.mods.ic2.ClassRegistry", + "minetweaker.mods.nei.ClassRegistry", + "minetweaker.mods.mfr.ClassRegistry", + "minetweaker.mods.gregtech.ClassRegistry", + "minetweaker.mods.buildcraft.ClassRegistry" }; private static final String[] REGISTRY_DESCRIPTIONS = { - "IC2 mod support", - "NEI mod support", - "MFR mod support", - "GregTech mod support", - "Buildcraft mod support" + "IC2 mod support", + "NEI mod support", + "MFR mod support", + "GregTech mod support", + "Buildcraft mod support" }; - + static { NETWORK.registerMessage(MineTweakerLoadScriptsHandler.class, MineTweakerLoadScriptsPacket.class, 0, Side.CLIENT); NETWORK.registerMessage(MineTweakerOpenBrowserHandler.class, MineTweakerOpenBrowserPacket.class, 1, Side.CLIENT); NETWORK.registerMessage(MineTweakerCopyClipboardHandler.class, MineTweakerCopyClipboardPacket.class, 2, Side.CLIENT); } - + @Mod.Instance(MODID) public static MineTweakerMod INSTANCE; - + public final MCRecipeManager recipes; private final IScriptProvider scriptsGlobal; private final ScriptProviderCustom scriptsIMC; - + public MineTweakerMod() { MineTweakerImplementationAPI.init( new MCOreDict(), @@ -100,80 +100,80 @@ public class MineTweakerMod { new MCLoadedMods(), new MCFormatter(), new MCVanilla()); - + MineTweakerImplementationAPI.logger.addLogger(new FileLogger(new File("minetweaker.log"))); MineTweakerImplementationAPI.platform = MCPlatformFunctions.INSTANCE; - + File globalDir = new File("scripts"); if (!globalDir.exists()) globalDir.mkdirs(); - + scriptsIMC = new ScriptProviderCustom("intermod"); scriptsGlobal = new ScriptProviderDirectory(globalDir); MineTweakerImplementationAPI.setScriptProvider(scriptsGlobal); } - + // ########################## // ### FML Event Handlers ### // ########################## - + @EventHandler - public void onIMCEvent(FMLInterModComms.IMCEvent event) { - for (final FMLInterModComms.IMCMessage imcMessage : event.getMessages()) { - if (imcMessage.key.equalsIgnoreCase("addMineTweakerScript")) { + public void onIMCEvent(FMLInterModComms.IMCEvent event) { + for (final FMLInterModComms.IMCMessage imcMessage : event.getMessages()) { + if (imcMessage.key.equalsIgnoreCase("addMineTweakerScript")) { if (imcMessage.isStringMessage()) { scriptsIMC.add(imcMessage.getSender() + "::imc", imcMessage.getStringValue()); } else if (imcMessage.isNBTMessage()) { NBTTagCompound message = imcMessage.getNBTValue(); scriptsIMC.add(imcMessage.getSender() + "::" + message.getString("name"), message.getString("content")); } - } - } - } - + } + } + } + @EventHandler public void onLoad(FMLPreInitializationEvent ev) { MinecraftForge.EVENT_BUS.register(new ForgeEventHandler()); FMLCommonHandler.instance().bus().register(new FMLEventHandler()); } - + @EventHandler public void onPostInit(FMLPostInitializationEvent ev) { MineTweakerAPI.registerClassRegistry(MineTweakerRegistry.class); - + for (int i = 0; i < REGISTRIES.length; i++) { MineTweakerAPI.registerClassRegistry(REGISTRIES[i], REGISTRY_DESCRIPTIONS[i]); } - + FuelTweaker.INSTANCE.register(); } - + @EventHandler public void onServerAboutToStart(FMLServerAboutToStartEvent ev) { // starts before loading worlds // perfect place to start MineTweaker! - + if (MineTweakerPlatformUtils.isClient()) { MineTweakerAPI.client = new MCClient(); } - + File scriptsDir = new File(MineTweakerHacks.getWorldDirectory(ev.getServer()), "scripts"); if (!scriptsDir.exists()) { scriptsDir.mkdir(); } - + IScriptProvider scriptsLocal = new ScriptProviderDirectory(scriptsDir); IScriptProvider cascaded = new ScriptProviderCascade(scriptsIMC, scriptsGlobal, scriptsLocal); - + MineTweakerImplementationAPI.setScriptProvider(cascaded); MineTweakerImplementationAPI.onServerStart(new MCServer(ev.getServer())); } - + @EventHandler public void onServerStarting(FMLServerStartingEvent ev) { - + } - + @EventHandler public void onServerStopped(FMLServerStoppedEvent ev) { MineTweakerImplementationAPI.onServerStop(); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/actions/SetTranslationAction.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/actions/SetTranslationAction.java index e43844a..e5cb073 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/actions/SetTranslationAction.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/actions/SetTranslationAction.java @@ -19,11 +19,11 @@ import net.minecraft.util.StringTranslate; public class SetTranslationAction implements IUndoableAction { private static final StringTranslate INSTANCE = MineTweakerHacks.getStringTranslateInstance(); private static final Charset UTF8 = Charset.forName("utf-8"); - + private final String key; private final String newValue; private final String oldValue; - + public SetTranslationAction(String key, String value) { this.key = key; newValue = value; @@ -54,7 +54,7 @@ public class SetTranslationAction implements IUndoableAction { public String describeUndo() { return "Reverting " + key + " to " + oldValue; } - + private static void set(String key, String value) { StringTranslate.inject(new ByteArrayInputStream((key + "=" + value).getBytes(UTF8))); } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCBlockDefinition.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCBlockDefinition.java index fcd2d26..d300b98 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCBlockDefinition.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCBlockDefinition.java @@ -15,11 +15,11 @@ import net.minecraft.block.Block; */ public class MCBlockDefinition implements IBlockDefinition { private final Block block; - + public MCBlockDefinition(Block block) { this.block = block; } - + public Block getInternalBlock() { return block; } @@ -28,7 +28,7 @@ public class MCBlockDefinition implements IBlockDefinition { public String getId() { return Block.blockRegistry.getNameForObject(block); } - + @Override public String getDisplayName() { return block.getLocalizedName(); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCItemBlock.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCItemBlock.java index e41f9f5..1cd153e 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCItemBlock.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCItemBlock.java @@ -24,7 +24,7 @@ import net.minecraftforge.oredict.OreDictionary; */ public class MCItemBlock implements IBlock { private final ItemStack item; - + public MCItemBlock(ItemStack item) { this.item = item; } @@ -43,7 +43,7 @@ public class MCItemBlock implements IBlock { public IData getTileData() { if (item.stackTagCompound == null) return null; - + return MineTweakerMC.getIData(item.stackTagCompound); } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCSpecificBlock.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCSpecificBlock.java index d7895c2..352101c 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCSpecificBlock.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCSpecificBlock.java @@ -24,12 +24,12 @@ import net.minecraftforge.oredict.OreDictionary; public class MCSpecificBlock implements IBlock { private final Block block; private final int meta; - + public MCSpecificBlock(Block block, int meta) { this.block = block; this.meta = meta; } - + @Override public IBlockDefinition getDefinition() { return MineTweakerMC.getBlockDefinition(block); @@ -65,12 +65,12 @@ public class MCSpecificBlock implements IBlock { public String getDisplayName() { return block.getLocalizedName(); } - + @Override public String toString() { return ""; } - + private static String getBlockId(Block block) { return Block.blockRegistry.getNameForObject(block); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCWorldBlock.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCWorldBlock.java index 09cac4d..70d659d 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCWorldBlock.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/block/MCWorldBlock.java @@ -31,7 +31,7 @@ public class MCWorldBlock implements IBlock { private final int x; private final int y; private final int z; - + public MCWorldBlock(IBlockAccess blocks, int x, int y, int z) { this.blocks = blocks; this.x = x; @@ -52,10 +52,10 @@ public class MCWorldBlock implements IBlock { @Override public IData getTileData() { TileEntity tileEntity = blocks.getTileEntity(x, y, z); - + if (tileEntity == null) return null; - + NBTTagCompound nbt = new NBTTagCompound(); tileEntity.writeToNBT(nbt); return MineTweakerMC.getIData(nbt); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/ItemBracketHandler.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/ItemBracketHandler.java index 7d2525a..8924329 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/ItemBracketHandler.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/ItemBracketHandler.java @@ -34,19 +34,19 @@ import stanhebben.zenscript.util.ZenPosition; * * @author Stan */ -@BracketHandler(priority=100) +@BracketHandler(priority = 100) public class ItemBracketHandler implements IBracketHandler { private static final Map itemNames; - + static { itemNames = new HashMap(); for (String itemName : (Set) Item.itemRegistry.getKeys()) { itemNames.put(itemName.replace(" ", ""), (Item) Item.itemRegistry.getObject(itemName)); } } - + public static IItemStack getItem(String name, int meta) { - //Item item = (Item) Item.itemRegistry.getObject(name); + // Item item = (Item) Item.itemRegistry.getObject(name); Item item = itemNames.get(name); if (item != null) { return getIItemStackWildcardSize(item, meta); @@ -54,10 +54,10 @@ public class ItemBracketHandler implements IBracketHandler { return null; } } - + private final IZenSymbol symbolAny; private final IJavaMethod method; - + public ItemBracketHandler() { symbolAny = MineTweakerAPI.getJavaStaticFieldSymbol(IngredientAny.class, "INSTANCE"); method = MineTweakerAPI.getJavaMethod( @@ -72,15 +72,15 @@ public class ItemBracketHandler implements IBracketHandler { if (tokens.size() == 1 && tokens.get(0).getValue().equals("*")) { return symbolAny; } - + // detect special cases: - // item: at the start means item-specific syntax - // :xxx with xxx an integer means sub-item syntax - // :* means any-subitem-syntax + // item: at the start means item-specific syntax + // :xxx with xxx an integer means sub-item syntax + // :* means any-subitem-syntax int fromIndex = 0; int toIndex = tokens.size(); int meta = 0; - + if (tokens.size() > 2) { if (tokens.get(0).getValue().equals("item") && tokens.get(1).getValue().equals(":")) { fromIndex = 2; @@ -95,36 +95,36 @@ public class ItemBracketHandler implements IBracketHandler { meta = OreDictionary.WILDCARD_VALUE; } } - + return find(environment, tokens, fromIndex, toIndex, meta); } - + private IZenSymbol find(IEnvironmentGlobal environment, List tokens, int startIndex, int endIndex, int meta) { StringBuilder valueBuilder = new StringBuilder(); for (int i = startIndex; i < endIndex; i++) { Token token = tokens.get(i); valueBuilder.append(token.getValue()); } - + String itemName = valueBuilder.toString(); if (itemNames.containsKey(itemName)) { return new ItemReferenceSymbol(environment, itemName, meta); } - + return null; } - + private class ItemReferenceSymbol implements IZenSymbol { private final IEnvironmentGlobal environment; private final String name; private final int meta; - + public ItemReferenceSymbol(IEnvironmentGlobal environment, String name, int meta) { this.environment = environment; this.name = name; this.meta = meta; } - + @Override public IPartialExpression instance(ZenPosition position) { return new ExpressionCallStatic( diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/LiquidBracketHandler.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/LiquidBracketHandler.java index 421d0cb..5499c70 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/LiquidBracketHandler.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/LiquidBracketHandler.java @@ -41,34 +41,34 @@ public class LiquidBracketHandler implements IBracketHandler { return find(environment, tokens, 2, tokens.size()); } } - + return null; } - + private IZenSymbol find(IEnvironmentGlobal environment, List tokens, int startIndex, int endIndex) { StringBuilder valueBuilder = new StringBuilder(); for (int i = startIndex; i < endIndex; i++) { Token token = tokens.get(i); valueBuilder.append(token.getValue()); } - + Fluid fluid = FluidRegistry.getFluid(valueBuilder.toString()); if (fluid != null) { return new LiquidReferenceSymbol(environment, valueBuilder.toString()); } - + return null; } - + private class LiquidReferenceSymbol implements IZenSymbol { private final IEnvironmentGlobal environment; private final String name; - + public LiquidReferenceSymbol(IEnvironmentGlobal environment, String name) { this.environment = environment; this.name = name; } - + @Override public IPartialExpression instance(ZenPosition position) { IJavaMethod method = JavaMethod.get( @@ -76,7 +76,7 @@ public class LiquidBracketHandler implements IBracketHandler { LiquidBracketHandler.class, "getLiquid", String.class); - + return new ExpressionCallStatic( position, environment, diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/OreBracketHandler.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/OreBracketHandler.java index ad5c021..e275493 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/OreBracketHandler.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/brackets/OreBracketHandler.java @@ -31,7 +31,7 @@ public class OreBracketHandler implements IBracketHandler { public static IOreDictEntry getOre(String name) { return new MCOreDictEntry(name); } - + @Override public IZenSymbol resolve(IEnvironmentGlobal environment, List tokens) { if (tokens.size() > 2) { @@ -39,29 +39,29 @@ public class OreBracketHandler implements IBracketHandler { return find(environment, tokens, 2, tokens.size()); } } - + return null; } - + private IZenSymbol find(IEnvironmentGlobal environment, List tokens, int startIndex, int endIndex) { StringBuilder valueBuilder = new StringBuilder(); for (int i = startIndex; i < endIndex; i++) { Token token = tokens.get(i); valueBuilder.append(token.getValue()); } - + return new OreReferenceSymbol(environment, valueBuilder.toString()); } - + private class OreReferenceSymbol implements IZenSymbol { private final IEnvironmentGlobal environment; private final String name; - + public OreReferenceSymbol(IEnvironmentGlobal environment, String name) { this.environment = environment; this.name = name; } - + @Override public IPartialExpression instance(ZenPosition position) { IJavaMethod method = JavaMethod.get( @@ -69,7 +69,7 @@ public class OreBracketHandler implements IBracketHandler { OreBracketHandler.class, "getOre", String.class); - + return new ExpressionCallStatic( position, environment, diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/chat/MCChatMessage.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/chat/MCChatMessage.java index 26ff668..1085d92 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/chat/MCChatMessage.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/chat/MCChatMessage.java @@ -16,11 +16,11 @@ import net.minecraft.util.IChatComponent; */ public class MCChatMessage implements IChatMessage { private final IChatComponent data; - + public MCChatMessage(String message) { data = new ChatComponentText(message); } - + public MCChatMessage(IChatComponent data) { this.data = data; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/data/NBTConverter.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/data/NBTConverter.java index 3eee34e..0fc6199 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/data/NBTConverter.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/data/NBTConverter.java @@ -44,14 +44,15 @@ import net.minecraft.nbt.NBTTagString; */ public class NBTConverter implements IDataConverter { private static final NBTConverter INSTANCE = new NBTConverter(); - + public static NBTBase from(IData data) { return data.convert(INSTANCE); } - + public static IData from(NBTBase nbt, boolean immutable) { - if (nbt == null) return null; - + if (nbt == null) + return null; + switch (nbt.getId()) { case 1: // byte return new DataByte(((NBTBase.NBTPrimitive) nbt).func_150290_f()); @@ -80,7 +81,7 @@ public class NBTConverter implements IDataConverter { case 10: { // compound Map values = new HashMap(); NBTTagCompound original = (NBTTagCompound) nbt; - for (String key : (Set)original.func_150296_c()) { + for (String key : (Set) original.func_150296_c()) { values.put(key, from(original.getTag(key), immutable)); } return new DataMap(values, immutable); @@ -96,9 +97,10 @@ public class NBTConverter implements IDataConverter { NBTUpdater updater = new NBTUpdater(nbt); data.convert(updater); } - - public NBTConverter() {} - + + public NBTConverter() { + } + @Override public NBTBase fromBool(boolean value) { return new NBTTagInt(value ? 1 : 0); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/data/NBTUpdater.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/data/NBTUpdater.java index 316d103..84d0070 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/data/NBTUpdater.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/data/NBTUpdater.java @@ -18,11 +18,11 @@ import net.minecraft.nbt.NBTTagCompound; */ public class NBTUpdater extends NBTConverter implements IDataConverter { private final NBTTagCompound nbt; - + public NBTUpdater(NBTTagCompound compound) { this.nbt = compound; } - + @Override public NBTBase fromMap(Map map) { for (Map.Entry entry : map.entrySet()) { @@ -41,7 +41,7 @@ public class NBTUpdater extends NBTConverter implements IDataConverter nbt.setTag(entry.getKey(), from(entry.getValue())); } } - + return nbt; } } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/entity/MCEntityDefinition.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/entity/MCEntityDefinition.java index a6df0e1..758a0c8 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/entity/MCEntityDefinition.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/entity/MCEntityDefinition.java @@ -15,7 +15,7 @@ import minetweaker.api.entity.IEntityDefinition; */ public class MCEntityDefinition implements IEntityDefinition { private final EntityRegistry.EntityRegistration registration; - + public MCEntityDefinition(EntityRegistry.EntityRegistration registration) { this.registration = registration; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedMarkupString.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedMarkupString.java index d5de784..312ad6f 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedMarkupString.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedMarkupString.java @@ -16,7 +16,7 @@ import net.minecraft.util.EnumChatFormatting; public class FormattedMarkupString implements IMCFormattedString { private final EnumChatFormatting markup; private final IMCFormattedString contents; - + public FormattedMarkupString(EnumChatFormatting markup, IMCFormattedString contents) { this.markup = markup; this.contents = contents; diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedString.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedString.java index 160106f..6920aea 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedString.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedString.java @@ -14,11 +14,11 @@ import minetweaker.api.formatting.IFormattedText; */ public class FormattedString implements IMCFormattedString { private final String value; - + public FormattedString(String value) { this.value = value; } - + @Override public String getTooltipString() { return value; diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedStringJoin.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedStringJoin.java index f788ceb..62fc90c 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedStringJoin.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/FormattedStringJoin.java @@ -16,11 +16,11 @@ import net.minecraft.util.EnumChatFormatting; */ public class FormattedStringJoin implements IMCFormattedString { private final IMCFormattedString[] values; - + public FormattedStringJoin(IMCFormattedString first, IMCFormattedString second) { values = new IMCFormattedString[] { first, second }; } - + public FormattedStringJoin(IMCFormattedString[] values) { this.values = values; } @@ -37,7 +37,7 @@ public class FormattedStringJoin implements IMCFormattedString { @Override public String getTooltipString(String context) { boolean first = true; - + StringBuilder result = new StringBuilder(); for (IMCFormattedString value : values) { if (first) { @@ -45,11 +45,11 @@ public class FormattedStringJoin implements IMCFormattedString { } else { result.append(context); } - + result.append(value.getTooltipString()); result.append(EnumChatFormatting.RESET); } - + return result.toString(); } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/IMCFormattedString.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/IMCFormattedString.java index aed14a6..36912d6 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/IMCFormattedString.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/formatting/IMCFormattedString.java @@ -14,6 +14,6 @@ import minetweaker.api.formatting.IFormattedText; */ public interface IMCFormattedString extends IFormattedText { public String getTooltipString(); - + public String getTooltipString(String context); } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/FuelTweaker.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/FuelTweaker.java index afbb5dd..a05f20e 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/FuelTweaker.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/FuelTweaker.java @@ -20,11 +20,12 @@ import net.minecraft.item.ItemStack; public class FuelTweaker { public static final FuelTweaker INSTANCE = new FuelTweaker(); - + private List original; private final HashMap> quickList = new HashMap>(); - - private FuelTweaker() {} + + private FuelTweaker() { + } public void register() { try { @@ -42,14 +43,14 @@ public class FuelTweaker { System.out.println("[MineTweaker] Error: could not alter GameRegistry fuel handlers field. Cannot use custom fuel values."); } } - + public void addFuelPattern(SetFuelPattern pattern) { List items = pattern.getPattern().getItems(); if (items == null) { MineTweakerAPI.logError("Cannot set fuel for <*>"); return; } - + for (IItemStack item : pattern.getPattern().getItems()) { ItemStack itemStack = MineTweakerMC.getItemStack(item); Item mcItem = itemStack.getItem(); @@ -59,7 +60,7 @@ public class FuelTweaker { quickList.get(mcItem).add(pattern); } } - + public void removeFuelPattern(SetFuelPattern pattern) { for (IItemStack item : pattern.getPattern().getItems()) { ItemStack itemStack = MineTweakerMC.getItemStack(item); @@ -69,20 +70,20 @@ public class FuelTweaker { } } } - + private class OverridingFuelHandler implements IFuelHandler { @Override public int getBurnTime(ItemStack fuel) { if (quickList.containsKey(fuel.getItem())) { IItemStack stack = MineTweakerMC.getIItemStack(fuel); - + for (SetFuelPattern override : quickList.get(fuel.getItem())) { if (override.getPattern().matches(stack)) { return override.getValue(); } } } - + int max = 0; for (IFuelHandler handler : original) { max = Math.max(max, handler.getBurnTime(fuel)); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/MCFurnaceManager.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/MCFurnaceManager.java index 7be0296..ff42961 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/MCFurnaceManager.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/MCFurnaceManager.java @@ -27,15 +27,16 @@ import net.minecraft.item.crafting.FurnaceRecipes; */ public class MCFurnaceManager implements IFurnaceManager { public MCFurnaceManager() { - + } - + @Override public void remove(IIngredient output, IIngredient input) { - if (output == null) throw new IllegalArgumentException("output cannot be null"); - + if (output == null) + throw new IllegalArgumentException("output cannot be null"); + Map smeltingList = FurnaceRecipes.smelting().getSmeltingList(); - + List toRemove = new ArrayList(); List toRemoveValues = new ArrayList(); for (Map.Entry entry : smeltingList.entrySet()) { @@ -45,7 +46,7 @@ public class MCFurnaceManager implements IFurnaceManager { toRemoveValues.add(entry.getValue()); } } - + if (toRemove.isEmpty()) { MineTweakerAPI.logWarning("No furnace recipes for " + output.toString()); } else { @@ -59,7 +60,7 @@ public class MCFurnaceManager implements IFurnaceManager { if (items == null) { MineTweakerAPI.logError("Cannot turn " + input.toString() + " into a furnace recipe"); } - + ItemStack[] items2 = getItemStacks(items); ItemStack output2 = getItemStack(output); MineTweakerAPI.apply(new AddRecipeAction(input, items2, output2, xp)); @@ -74,20 +75,20 @@ public class MCFurnaceManager implements IFurnaceManager { public int getFuel(IItemStack item) { return GameRegistry.getFuelValue(getItemStack(item)); } - + // ###################### // ### Action classes ### // ###################### - + private static class RemoveAction implements IUndoableAction { private final List items; private final List values; - + public RemoveAction(List items, List values) { this.items = items; this.values = values; } - + @Override public void apply() { for (ItemStack item : items) { @@ -122,13 +123,13 @@ public class MCFurnaceManager implements IFurnaceManager { return null; } } - + private static class AddRecipeAction implements IUndoableAction { private final IIngredient ingredient; private final ItemStack[] input; private final ItemStack output; private final double xp; - + public AddRecipeAction(IIngredient ingredient, ItemStack[] input, ItemStack output, double xp) { this.ingredient = ingredient; this.input = input; @@ -170,14 +171,14 @@ public class MCFurnaceManager implements IFurnaceManager { return null; } } - + private static class SetFuelAction implements IUndoableAction { private final SetFuelPattern pattern; - + public SetFuelAction(SetFuelPattern pattern) { this.pattern = pattern; } - + @Override public void apply() { FuelTweaker.INSTANCE.addFuelPattern(pattern); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/SetFuelPattern.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/SetFuelPattern.java index 96313c6..61e724d 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/SetFuelPattern.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/furnace/SetFuelPattern.java @@ -5,16 +5,16 @@ import minetweaker.api.item.IIngredient; public class SetFuelPattern { private final IIngredient pattern; private final int value; - + public SetFuelPattern(IIngredient pattern, int value) { this.pattern = pattern; this.value = value; } - + public IIngredient getPattern() { return pattern; } - + public int getValue() { return value; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/game/MCGame.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/game/MCGame.java index 67e167d..2a8517b 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/game/MCGame.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/game/MCGame.java @@ -40,17 +40,18 @@ import net.minecraftforge.fluids.FluidRegistry; */ public class MCGame implements IGame { private static final Map TRANSLATIONS = MineTweakerHacks.getTranslations(); - + public static final MCGame INSTANCE = new MCGame(); - + private boolean locked = false; - - private MCGame() {} + + private MCGame() { + } @Override public List getItems() { List result = new ArrayList(); - for (String item : (Set)Item.itemRegistry.getKeys()) { + for (String item : (Set) Item.itemRegistry.getKeys()) { result.add(new MCItemDefinition(item, (Item) Item.itemRegistry.getObject(item))); } return result; @@ -59,10 +60,10 @@ public class MCGame implements IGame { @Override public List getBlocks() { List result = new ArrayList(); - for (String block : (Set)Block.blockRegistry.getKeys()) { + for (String block : (Set) Block.blockRegistry.getKeys()) { result.add(MineTweakerMC.getBlockDefinition((Block) Block.blockRegistry.getObject(block))); } - + return result; } @@ -85,15 +86,15 @@ public class MCGame implements IGame { } return result; } - + @Override public List getEntities() { List result = new ArrayList(); - + for (EntityRegistry.EntityRegistration entityRegistration : MineTweakerHacks.getEntityClassRegistrations().values()) { result.add(new MCEntityDefinition(entityRegistration)); } - + return result; } @@ -133,18 +134,18 @@ public class MCGame implements IGame { public void signalLockError() { MineTweakerAPI.getLogger().logError("Reload of scripts blocked (script lock)"); - + if (Minecraft.isGuiEnabled()) { // Commented out due to unresolved import - /** Minecraft.getMinecraft().displayGuiScreen( - new GuiCannotRemodify( - "Minecraft has been tweaked for another server", - "with modifications that cannot be rolled back.", - "Please restart your game.")); - **/ + /** + * Minecraft.getMinecraft().displayGuiScreen( new GuiCannotRemodify( + * "Minecraft has been tweaked for another server", + * "with modifications that cannot be rolled back.", + * "Please restart your game.")); + **/ } } - + // ###################### // ### Action classes ### // ###################### @@ -154,37 +155,37 @@ public class MCGame implements IGame { * * @author Joshiejack */ - private static class SetTranslation implements IUndoableAction { - private String original; - private final String lang; - private final String key; - private final String text; + private static class SetTranslation implements IUndoableAction { + private String original; + private final String lang; + private final String key; + private final String text; private boolean added; - public SetTranslation(String lang, String key, String text) { - this.lang = lang; - this.key = key; - this.text = text; - } + public SetTranslation(String lang, String key, String text) { + this.lang = lang; + this.key = key; + this.text = text; + } - @Override - public void apply() { - if (lang == null || MineTweakerPlatformUtils.isLanguageActive(lang)) { - original = TRANSLATIONS.get(key); - TRANSLATIONS.put(key, text); + @Override + public void apply() { + if (lang == null || MineTweakerPlatformUtils.isLanguageActive(lang)) { + original = TRANSLATIONS.get(key); + TRANSLATIONS.put(key, text); added = true; - } else { + } else { added = false; } - } + } - @Override - public boolean canUndo() { - return TRANSLATIONS != null; - } + @Override + public boolean canUndo() { + return TRANSLATIONS != null; + } - @Override - public void undo() { + @Override + public void undo() { if (added) { if (original == null) { TRANSLATIONS.remove(key); @@ -192,21 +193,21 @@ public class MCGame implements IGame { TRANSLATIONS.put(key, original); } } - } + } - @Override - public String describe() { - return "Setting localization for the key: " + key + " to " + text; - } + @Override + public String describe() { + return "Setting localization for the key: " + key + " to " + text; + } - @Override - public String describeUndo() { - return "Setting localization for the key: " + key + " to " + original; - } + @Override + public String describeUndo() { + return "Setting localization for the key: " + key + " to " + original; + } - @Override - public Object getOverrideKey() { - return null; - } - } + @Override + public Object getOverrideKey() { + return null; + } + } } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/item/MCItemDefinition.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/item/MCItemDefinition.java index e69a2b9..892cd37 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/item/MCItemDefinition.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/item/MCItemDefinition.java @@ -24,7 +24,7 @@ import net.minecraftforge.oredict.OreDictionary; public class MCItemDefinition implements IItemDefinition { private final String id; private final Item item; - + public MCItemDefinition(String id, Item item) { this.id = id; this.item = item; @@ -48,7 +48,7 @@ public class MCItemDefinition implements IItemDefinition { @Override public List getOres() { List result = new ArrayList(); - + for (String key : OreDictionary.getOreNames()) { for (ItemStack is : OreDictionary.getOres(key)) { if (is.getItem() == item) { @@ -57,10 +57,10 @@ public class MCItemDefinition implements IItemDefinition { } } } - + return result; } - + // ############################# // ### Object implementation ### // ############################# diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/liquid/MCLiquidDefinition.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/liquid/MCLiquidDefinition.java index 03e3999..fb52167 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/liquid/MCLiquidDefinition.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/liquid/MCLiquidDefinition.java @@ -24,16 +24,16 @@ import net.minecraftforge.fluids.FluidStack; */ public class MCLiquidDefinition implements ILiquidDefinition { private final Fluid fluid; - + public MCLiquidDefinition(Fluid fluid) { this.fluid = fluid; } - + @Override public String getName() { return fluid.getName(); } - + @Override public String getDisplayName() { return fluid.getLocalizedName(); @@ -112,44 +112,50 @@ public class MCLiquidDefinition implements ILiquidDefinition { @Override public void removeContainer(IItemStack filled) { - //MineTweakerAPI.apply(new RemoveContainerAction(filled)); + // MineTweakerAPI.apply(new RemoveContainerAction(filled)); MineTweakerAPI.logError("Cannot remove container items in MineCraft 1.7.X"); } - + // ####################### // ### Private methods ### // ####################### - - /*private void removeContainerInner(IItemStack filled) { - ItemStack filledItem = MineTweakerMC.getItemStack(filled); - FluidContainerRegistry.FluidContainerData data = filledContainerMap.get(Arrays.asList(filledItem.itemID, filledItem.getItemDamage())); - if (data != null) { - filledContainerMap.remove(Arrays.asList(filledItem.itemID, filledItem.getItemDamage())); - containerFluidMap.remove(Arrays.asList(data.emptyContainer.itemID, data.emptyContainer.getItemDamage())); - - // rebuild empty containers set - emptyContainers.clear(); - for (FluidContainerRegistry.FluidContainerData fdata : filledContainerMap.values()) { - emptyContainers.add(Arrays.asList(fdata.emptyContainer.itemID, fdata.emptyContainer.getItemDamage())); - } - } - MineTweakerAPI.logError("Removal of containers is not possible in 1.7.X"); - }*/ - - /*private FluidContainerRegistry.FluidContainerData getData(IItemStack filled) { - ItemStack filledStack = MineTweakerMC.getItemStack(filled); - return filledContainerMap.get(Arrays.asList(filledStack.itemID, filledStack.getItemDamage())); - }*/ - + + /* + * private void removeContainerInner(IItemStack filled) { ItemStack + * filledItem = MineTweakerMC.getItemStack(filled); + * FluidContainerRegistry.FluidContainerData data = + * filledContainerMap.get(Arrays.asList(filledItem.itemID, + * filledItem.getItemDamage())); if (data != null) { + * filledContainerMap.remove(Arrays.asList(filledItem.itemID, + * filledItem.getItemDamage())); + * containerFluidMap.remove(Arrays.asList(data.emptyContainer.itemID, + * data.emptyContainer.getItemDamage())); + * + * // rebuild empty containers set emptyContainers.clear(); for + * (FluidContainerRegistry.FluidContainerData fdata : + * filledContainerMap.values()) { + * emptyContainers.add(Arrays.asList(fdata.emptyContainer.itemID, + * fdata.emptyContainer.getItemDamage())); } } + * MineTweakerAPI.logError("Removal of containers is not possible in 1.7.X" + * ); } + */ + + /* + * private FluidContainerRegistry.FluidContainerData getData(IItemStack + * filled) { ItemStack filledStack = MineTweakerMC.getItemStack(filled); + * return filledContainerMap.get(Arrays.asList(filledStack.itemID, + * filledStack.getItemDamage())); } + */ + // ###################### // ### Action classes ### // ###################### - + private class AddContainerAction implements IUndoableAction { private final IItemStack filled; private final IItemStack empty; private final int amount; - + public AddContainerAction(IItemStack filled, IItemStack empty, int amount) { this.filled = filled; this.empty = empty; @@ -164,12 +170,12 @@ public class MCLiquidDefinition implements ILiquidDefinition { @Override public boolean canUndo() { return false; - //return true; + // return true; } @Override public void undo() { - //removeContainerInner(filled); + // removeContainerInner(filled); } @Override @@ -187,60 +193,43 @@ public class MCLiquidDefinition implements ILiquidDefinition { return null; } } - - /*private class RemoveContainerAction implements IUndoableAction { - private final IItemStack filled; - private final IItemStack empty; - private final FluidStack amount; - - public RemoveContainerAction(IItemStack filled) { - this.filled = filled; - - FluidContainerRegistry.FluidContainerData data = getData(filled); - empty = MineTweakerMC.getIItemStack(data.emptyContainer); - amount = data.fluid; - } - @Override - public void apply() { - removeContainerInner(filled); - } + /* + * private class RemoveContainerAction implements IUndoableAction { private + * final IItemStack filled; private final IItemStack empty; private final + * FluidStack amount; + * + * public RemoveContainerAction(IItemStack filled) { this.filled = filled; + * + * FluidContainerRegistry.FluidContainerData data = getData(filled); empty = + * MineTweakerMC.getIItemStack(data.emptyContainer); amount = data.fluid; } + * + * @Override public void apply() { removeContainerInner(filled); } + * + * @Override public boolean canUndo() { return true; } + * + * @Override public void undo() { + * FluidContainerRegistry.registerFluidContainer(amount, + * MineTweakerMC.getItemStack(filled), MineTweakerMC.getItemStack(empty)); } + * + * @Override public String describe() { return "Removing liquid container " + * + filled; } + * + * @Override public String describeUndo() { return + * "Restoring liquid container " + filled; } + * + * @Override public Object getOverrideKey() { return null; } } + */ - @Override - public boolean canUndo() { - return true; - } - - @Override - public void undo() { - FluidContainerRegistry.registerFluidContainer(amount, MineTweakerMC.getItemStack(filled), MineTweakerMC.getItemStack(empty)); - } - - @Override - public String describe() { - return "Removing liquid container " + filled; - } - - @Override - public String describeUndo() { - return "Restoring liquid container " + filled; - } - - @Override - public Object getOverrideKey() { - return null; - } - }*/ - private class ActionSetLuminosity implements IUndoableAction { private final int oldValue; private final int newValue; - + public ActionSetLuminosity(int newValue) { oldValue = getLuminosity(); this.newValue = newValue; } - + @Override public void apply() { fluid.setLuminosity(newValue); @@ -271,16 +260,16 @@ public class MCLiquidDefinition implements ILiquidDefinition { return null; } } - + private class ActionSetDensity implements IUndoableAction { private final int oldValue; private final int newValue; - + public ActionSetDensity(int newValue) { oldValue = getDensity(); this.newValue = newValue; } - + @Override public void apply() { fluid.setDensity(newValue); @@ -311,16 +300,16 @@ public class MCLiquidDefinition implements ILiquidDefinition { return null; } } - + private class ActionSetTemperature implements IUndoableAction { private final int oldValue; private final int newValue; - + public ActionSetTemperature(int newValue) { oldValue = getTemperature(); this.newValue = newValue; } - + @Override public void apply() { fluid.setTemperature(newValue); @@ -351,16 +340,16 @@ public class MCLiquidDefinition implements ILiquidDefinition { return null; } } - + private class ActionSetViscosity implements IUndoableAction { private final int oldValue; private final int newValue; - + public ActionSetViscosity(int newValue) { oldValue = getViscosity(); this.newValue = newValue; } - + @Override public void apply() { fluid.setViscosity(newValue); @@ -391,16 +380,16 @@ public class MCLiquidDefinition implements ILiquidDefinition { return null; } } - + private class ActionSetGaseous implements IUndoableAction { private final boolean oldValue; private final boolean newValue; - + public ActionSetGaseous(boolean newValue) { oldValue = isGaseous(); this.newValue = newValue; } - + @Override public void apply() { fluid.setGaseous(newValue); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/liquid/MCLiquidStack.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/liquid/MCLiquidStack.java index b6108d7..8df2d3e 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/liquid/MCLiquidStack.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/liquid/MCLiquidStack.java @@ -28,11 +28,11 @@ import net.minecraftforge.fluids.FluidStack; public class MCLiquidStack implements ILiquidStack { private final FluidStack stack; private IData tag = null; - + public MCLiquidStack(FluidStack stack) { this.stack = stack; } - + private MCLiquidStack(FluidStack stack, IData tag) { this.stack = stack; this.tag = tag; @@ -42,12 +42,12 @@ public class MCLiquidStack implements ILiquidStack { public ILiquidDefinition getDefinition() { return new MCLiquidDefinition(stack.getFluid()); } - + @Override public String getName() { return stack.getFluid().getName(); } - + @Override public String getDisplayName() { return stack.getFluid().getLocalizedName(); @@ -64,10 +64,10 @@ public class MCLiquidStack implements ILiquidStack { if (stack.tag == null) { return null; } - + tag = NBTConverter.from(stack.tag, true); } - + return tag; } @@ -114,11 +114,11 @@ public class MCLiquidStack implements ILiquidStack { public Object getInternal() { return stack; } - + // ################################## // ### IIngredient implementation ### // ################################## - + @Override public String getMark() { @@ -130,7 +130,7 @@ public class MCLiquidStack implements ILiquidStack { { return Collections.emptyList(); } - + @Override public List getLiquids() { @@ -185,13 +185,13 @@ public class MCLiquidStack implements ILiquidStack { { if (!ingredient.getItems().isEmpty()) return false; - + for (ILiquidStack liquid : ingredient.getLiquids()) { if (!matches(liquid)) return false; } - + return false; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/mods/MCLoadedMods.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/mods/MCLoadedMods.java index 221cf82..e9517bc 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/mods/MCLoadedMods.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/mods/MCLoadedMods.java @@ -13,13 +13,14 @@ import stanhebben.zenscript.util.MappingIterator; * @author Stan */ public class MCLoadedMods implements ILoadedMods { - public MCLoadedMods() {} + public MCLoadedMods() { + } @Override public boolean contains(String name) { return Loader.isModLoaded(name); } - + @Override public IMod get(String name) { for (ModContainer mod : Loader.instance().getActiveModList()) { @@ -27,7 +28,7 @@ public class MCLoadedMods implements ILoadedMods { return new MCMod(mod); } } - + return null; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/mods/MCMod.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/mods/MCMod.java index 7983e38..3ec189a 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/mods/MCMod.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/mods/MCMod.java @@ -15,7 +15,7 @@ import minetweaker.api.mods.IMod; */ public class MCMod implements IMod { private final ModContainer mod; - + public MCMod(ModContainer mod) { this.mod = mod; } @@ -29,7 +29,7 @@ public class MCMod implements IMod { public String getName() { return mod.getName(); } - + @Override public String getVersion() { return mod.getVersion(); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardHandler.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardHandler.java index 0a7bda2..8db755e 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardHandler.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/network/MineTweakerCopyClipboardHandler.java @@ -26,7 +26,7 @@ public class MineTweakerCopyClipboardHandler implements IMessageHandler { @Override public IMessage onMessage(MineTweakerOpenBrowserPacket message, MessageContext ctx) { - if(Desktop.isDesktopSupported()){ + if (Desktop.isDesktopSupported()) { Desktop desktop = Desktop.getDesktop(); try { desktop.browse(new URI(message.getUrl())); @@ -31,7 +31,7 @@ public class MineTweakerOpenBrowserHandler implements IMessageHandler> OREDICT_CONTENTS = MineTweakerHacks.getOreIdStacks(); private static final List> OREDICT_CONTENTS_UN = MineTweakerHacks.getOreIdStacksUn(); - + private final int id; - + public MCOreDictEntry(Integer id) { this.id = id; } - + public MCOreDictEntry(String id) { this.id = OreDictionary.getOreID(id); } - + // #################################### // ### IOreDictEntry implementation ### // #################################### - + @Override public String getName() { return OreDictionary.getOreName(id); } - + @Override public boolean isEmpty() { return OreDictionary.getOres(id).isEmpty(); @@ -86,7 +86,7 @@ public class MCOreDictEntry implements IOreDictEntry { break; } } - + if (result != null) { MineTweakerAPI.apply(new ActionRemoveItem(id, result)); } @@ -99,7 +99,7 @@ public class MCOreDictEntry implements IOreDictEntry { return true; } } - + return false; } @@ -130,7 +130,7 @@ public class MCOreDictEntry implements IOreDictEntry { } return result; } - + @Override public List getLiquids() { return Collections.emptyList(); @@ -155,7 +155,7 @@ public class MCOreDictEntry implements IOreDictEntry { public IIngredient marked(String mark) { return new IngredientOreDict(this, mark, ArrayUtil.EMPTY_CONDITIONS, ArrayUtil.EMPTY_TRANSFORMERS); } - + @Override public IIngredient or(IIngredient ingredient) { return new IngredientOr(this, ingredient); @@ -165,7 +165,7 @@ public class MCOreDictEntry implements IOreDictEntry { public boolean matches(IItemStack item) { return contains(item); } - + @Override public boolean matches(ILiquidStack liquid) { return false; @@ -175,9 +175,10 @@ public class MCOreDictEntry implements IOreDictEntry { public boolean contains(IIngredient ingredient) { List items = ingredient.getItems(); for (IItemStack item : items) { - if (!matches(item)) return false; + if (!matches(item)) + return false; } - + return true; } @@ -195,40 +196,41 @@ public class MCOreDictEntry implements IOreDictEntry { public Object getInternal() { return OreDictionary.getOreName(id); } - + // ############################# // ### Object implementation ### // ############################# - + @Override public String toString() { return ""; } - + @Override public int hashCode() { return id; } - + @Override public boolean equals(Object other) { - if (!(other instanceof MCOreDictEntry)) return false; + if (!(other instanceof MCOreDictEntry)) + return false; return ((MCOreDictEntry) other).id == id; } - + // ###################### // ### Action classes ### // ###################### - + private static class ActionAddItem implements IUndoableAction { private final Integer id; private final ItemStack item; - + public ActionAddItem(Integer id, ItemStack item) { this.id = id; this.item = item; } - + @Override public void apply() { OreDictionary.registerOre(id, item); @@ -259,18 +261,18 @@ public class MCOreDictEntry implements IOreDictEntry { return null; } } - + private static class ActionMirror implements IUndoableAction { private final Integer idTarget; private final Integer idSource; - + private final ArrayList targetCopy; private final ArrayList targetCopyUn; - + public ActionMirror(Integer idTarget, Integer idSource) { this.idTarget = idTarget; this.idSource = idSource; - + targetCopy = OREDICT_CONTENTS.get(idTarget); targetCopyUn = OREDICT_CONTENTS_UN.get(idTarget); } @@ -307,16 +309,16 @@ public class MCOreDictEntry implements IOreDictEntry { return null; } } - + private static class ActionRemoveItem implements IUndoableAction { private final Integer id; private final ItemStack item; - + public ActionRemoveItem(Integer id, ItemStack item) { this.id = id; this.item = item; } - + @Override public void apply() { OREDICT_CONTENTS.get(id).remove(item); @@ -347,11 +349,11 @@ public class MCOreDictEntry implements IOreDictEntry { return null; } } - + private static class ActionAddAll implements IUndoableAction { private final Integer idTarget; private final Integer idSource; - + public ActionAddAll(Integer idTarget, Integer idSource) { this.idTarget = idTarget; this.idSource = idSource; diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/player/MCPlayer.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/player/MCPlayer.java index 50767ea..3339b58 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/player/MCPlayer.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/player/MCPlayer.java @@ -27,11 +27,11 @@ import net.minecraft.util.IChatComponent; */ public class MCPlayer implements IPlayer { private final EntityPlayer player; - + public MCPlayer(EntityPlayer player) { this.player = player; } - + public EntityPlayer getInternal() { return player; } @@ -40,7 +40,7 @@ public class MCPlayer implements IPlayer { public String getId() { return null; // TODO: we should be having this for MC 1.7.10, right? } - + @Override public String getName() { return player.getCommandSenderName(); @@ -50,7 +50,7 @@ public class MCPlayer implements IPlayer { public IData getData() { return NBTConverter.from(player.getEntityData(), true); } - + @Override public void update(IData data) { NBTConverter.updateMap(player.getEntityData(), data); @@ -114,7 +114,7 @@ public class MCPlayer implements IPlayer { (EntityPlayerMP) player); } } - + @Override public void copyToClipboard(String value) { if (player instanceof EntityPlayerMP) { @@ -123,12 +123,12 @@ public class MCPlayer implements IPlayer { (EntityPlayerMP) player); } } - + @Override public boolean equals(Object other) { if (other.getClass() != this.getClass()) return false; - + return ((MCPlayer) other).player == player; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/MCCraftingInventory.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/MCCraftingInventory.java index 8344cfd..6ed425f 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/MCCraftingInventory.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/MCCraftingInventory.java @@ -31,7 +31,7 @@ import net.minecraft.item.ItemStack; public class MCCraftingInventory implements ICraftingInventory { private static final ThreadLocal cache = new ThreadLocal(); private static final ThreadLocal cache2 = new ThreadLocal(); - + public static MCCraftingInventory get(InventoryCrafting inventory) { if (cache.get() == null || cache.get().inventory != inventory) { MCCraftingInventory result = new MCCraftingInventory(inventory); @@ -43,7 +43,7 @@ public class MCCraftingInventory implements ICraftingInventory { return result; } } - + public static MCCraftingInventory get(IInventory inventory, EntityPlayer player) { if (cache2.get() == null || cache2.get().inventory != inventory || cache2.get().player != player) { MCCraftingInventory result = new MCCraftingInventory(inventory, player); @@ -55,7 +55,7 @@ public class MCCraftingInventory implements ICraftingInventory { return result; } } - + private int width; private int height; private final IInventory inventory; @@ -64,7 +64,7 @@ public class MCCraftingInventory implements ICraftingInventory { private int stackCount; private final IPlayer player; private final EntityPlayer playerOrig; - + private MCCraftingInventory(InventoryCrafting inventory) { this.inventory = inventory; width = height = (int) Math.sqrt(inventory.getSizeInventory()); @@ -72,7 +72,7 @@ public class MCCraftingInventory implements ICraftingInventory { original = new ItemStack[stacks.length]; stackCount = 0; update(); - + Container container = MineTweakerHacks.getCraftingContainer(inventory); if (container != null) { List slots = container.inventorySlots; @@ -89,7 +89,7 @@ public class MCCraftingInventory implements ICraftingInventory { player = null; } } - + public MCCraftingInventory(IInventory inventory, EntityPlayer player) { this.inventory = inventory; width = height = (int) Math.sqrt(inventory.getSizeInventory()); @@ -97,11 +97,11 @@ public class MCCraftingInventory implements ICraftingInventory { original = new ItemStack[stacks.length]; stackCount = 0; update(); - + playerOrig = player; this.player = player == null ? null : new MCPlayer(player); } - + private void update() { if (inventory.getSizeInventory() != original.length) { width = height = (int) Math.sqrt(inventory.getSizeInventory()); @@ -109,23 +109,25 @@ public class MCCraftingInventory implements ICraftingInventory { original = new ItemStack[stacks.length]; stackCount = 0; } - + for (int i = 0; i < inventory.getSizeInventory(); i++) { if (changed(i)) { - //System.out.println("Slot " + i + " changed"); + // System.out.println("Slot " + i + " changed"); original[i] = inventory.getStackInSlot(i); if (inventory.getStackInSlot(i) != null) { - if (stacks[i] == null) stackCount++; + if (stacks[i] == null) + stackCount++; stacks[i] = getIItemStack(original[i]); } else { - if (stacks[i] != null) stackCount--; + if (stacks[i] != null) + stackCount--; stacks[i] = null; } } } - //System.out.println("Num stack count: " + stackCount); + // System.out.println("Num stack count: " + stackCount); } - + @Override public IPlayer getPlayer() { return player; @@ -145,7 +147,7 @@ public class MCCraftingInventory implements ICraftingInventory { public int getHeight() { return height; } - + @Override public int getStackCount() { return stackCount; @@ -163,8 +165,8 @@ public class MCCraftingInventory implements ICraftingInventory { @Override public void setStack(int x, int y, IItemStack stack) { - //System.out.println("SetStack(" + x + ", " + y + ") " + stack); - + // System.out.println("SetStack(" + x + ", " + y + ") " + stack); + int ix = y * width + x; if (stack != stacks[ix]) { if (stack == null) { @@ -172,7 +174,7 @@ public class MCCraftingInventory implements ICraftingInventory { inventory.setInventorySlotContents(ix, null); } else { inventory.setInventorySlotContents(ix, getItemStack(stack)); - + if (stacks[ix] == null) { stackCount++; } @@ -183,15 +185,15 @@ public class MCCraftingInventory implements ICraftingInventory { @Override public void setStack(int i, IItemStack stack) { - //System.out.println("SetStack(" + i + ") " + stack); - + // System.out.println("SetStack(" + i + ") " + stack); + if (stack != stacks[i]) { if (stack == null) { stackCount--; inventory.setInventorySlotContents(i, null); } else { inventory.setInventorySlotContents(i, getItemStack(stack)); - + if (stacks[i] == null) { stackCount++; } @@ -199,11 +201,13 @@ public class MCCraftingInventory implements ICraftingInventory { stacks[i] = stack; } } - + private boolean changed(int i) { - if (original[i] != inventory.getStackInSlot(i)) return true; - if (original[i] != null && stacks[i].getAmount() != original[i].stackSize) return true; - + if (original[i] != inventory.getStackInSlot(i)) + return true; + if (original[i] != null && stacks[i].getAmount() != original[i].stackSize) + return true; + return false; } } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/RecipeConverter.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/RecipeConverter.java index 5023e06..9afa4da 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/RecipeConverter.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/RecipeConverter.java @@ -28,12 +28,13 @@ import net.minecraftforge.oredict.ShapelessOreRecipe; * @author Stan */ public class RecipeConverter { - private RecipeConverter() {} - + private RecipeConverter() { + } + public static final int TYPE_ADVANCED = 0; public static final int TYPE_ORE = 1; public static final int TYPE_BASIC = 2; - + private static int getIngredientType(IIngredient pattern) { Object internal = pattern.getInternal(); if (internal == null) { @@ -44,7 +45,7 @@ public class RecipeConverter { return TYPE_ORE; } } - + private static int getRecipeType(IIngredient[] ingredients) { int type = TYPE_BASIC; for (IIngredient ingredient : ingredients) { @@ -52,11 +53,11 @@ public class RecipeConverter { } return type; } - + public static IRecipe convert(ShapelessRecipe recipe) { IIngredient[] ingredients = recipe.getIngredients(); int type = getRecipeType(ingredients); - + if (type == TYPE_BASIC) { ItemStack[] items = new ItemStack[ingredients.length]; for (int i = 0; i < ingredients.length; i++) { @@ -73,33 +74,33 @@ public class RecipeConverter { return new ShapelessRecipeAdvanced(recipe); } } - + public static IRecipe convert(ShapedRecipe recipe) { IIngredient[] ingredients = recipe.getIngredients(); byte[] posx = recipe.getIngredientsX(); byte[] posy = recipe.getIngredientsY(); - + // determine recipe type int type = getRecipeType(ingredients); - + // construct recipe if (type == TYPE_BASIC) { ItemStack[] basicIngredients = new ItemStack[recipe.getHeight() * recipe.getWidth()]; for (int i = 0; i < ingredients.length; i++) { basicIngredients[posx[i] + posy[i] * recipe.getWidth()] = getItemStack(ingredients[i]); } - + return new ShapedRecipeBasic(basicIngredients, recipe); } else if (type == TYPE_ORE) { Object[] converted = new Object[recipe.getHeight() * recipe.getWidth()]; for (int i = 0; i < ingredients.length; i++) { converted[posx[i] + posy[i] * recipe.getWidth()] = ingredients[i].getInternal(); } - + // arguments contents: // 1) recipe patterns // 2) characters + ingredients - + int counter = 0; String[] parts = new String[recipe.getHeight()]; ArrayList rarguments = new ArrayList(); @@ -118,60 +119,60 @@ public class RecipeConverter { } parts[i] = new String(pattern); } - + rarguments.addAll(0, Arrays.asList(parts)); - + return new ShapedRecipeOre(rarguments.toArray(), recipe); } else { return new ShapedRecipeAdvanced(recipe); } } - + public static ICraftingRecipe toCraftingRecipe(IRecipe recipe) { IItemStack output = MineTweakerMC.getIItemStack(recipe.getRecipeOutput()); - + if (recipe instanceof ShapelessRecipes) { ShapelessRecipes shapeless = (ShapelessRecipes) recipe; - + IIngredient[] ingredients = new IIngredient[shapeless.recipeItems.size()]; for (int i = 0; i < ingredients.length; i++) { ingredients[i] = MineTweakerMC.getIIngredient(shapeless.recipeItems.get(i)); } - + return new ShapelessRecipe(output, ingredients, null); } else if (recipe instanceof ShapedRecipes) { ShapedRecipes shaped = (ShapedRecipes) recipe; - + IIngredient[][] ingredients = new IIngredient[shaped.recipeHeight][shaped.recipeWidth]; for (int i = 0; i < shaped.recipeHeight; i++) { for (int j = 0; j < shaped.recipeWidth; j++) { ingredients[i][j] = MineTweakerMC.getIItemStack(shaped.recipeItems[i * shaped.recipeWidth + j]); } } - + return new ShapedRecipe(output, ingredients, null, false); } else if (recipe instanceof ShapedOreRecipe) { ShapedOreRecipe shaped = (ShapedOreRecipe) recipe; - + int width = (int) Math.sqrt(recipe.getRecipeSize()); int height = recipe.getRecipeSize() / width; - + IIngredient[][] recipeIngredients = new IIngredient[height][width]; for (int i = 0; i < height; i++) { for (int j = 0; j < width; j++) { recipeIngredients[i][j] = MineTweakerMC.getIIngredient(shaped.getInput()[i * width + j]); } } - + return new ShapedRecipe(output, recipeIngredients, null, false); } else if (recipe instanceof ShapelessOreRecipe) { ShapelessOreRecipe shapeless = (ShapelessOreRecipe) recipe; - + IIngredient[] ingredients = new IIngredient[shapeless.getRecipeSize()]; for (int i = 0; i < ingredients.length; i++) { ingredients[i] = MineTweakerMC.getIIngredient(shapeless.getInput().get(i)); } - + return new ShapelessRecipe(output, ingredients, null); } else { return new UnknownRecipe(output); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeAdvanced.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeAdvanced.java index 613a52c..34196ae 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeAdvanced.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeAdvanced.java @@ -20,7 +20,7 @@ import net.minecraft.world.World; */ public class ShapedRecipeAdvanced implements IRecipe { private final ShapedRecipe recipe; - + public ShapedRecipeAdvanced(ShapedRecipe recipe) { this.recipe = recipe; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeBasic.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeBasic.java index 841b5dd..8910351 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeBasic.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeBasic.java @@ -20,20 +20,20 @@ import net.minecraft.world.World; */ public class ShapedRecipeBasic extends ShapedRecipes { private final ShapedRecipe recipe; - + public ShapedRecipeBasic(ItemStack[] basicInputs, ShapedRecipe recipe) { super(recipe.getWidth(), recipe.getHeight(), basicInputs, getItemStack(recipe.getOutput())); - + this.recipe = recipe; } - + @Override - public boolean matches(InventoryCrafting inventory, World world) { + public boolean matches(InventoryCrafting inventory, World world) { return recipe.matches(MCCraftingInventory.get(inventory)); } - @Override - public ItemStack getCraftingResult(InventoryCrafting inventory) { + @Override + public ItemStack getCraftingResult(InventoryCrafting inventory) { IItemStack result = recipe.getCraftingResult(MCCraftingInventory.get(inventory)); if (result == null) { return null; diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeOre.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeOre.java index 7ddc811..58fb6dd 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeOre.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapedRecipeOre.java @@ -19,20 +19,20 @@ import net.minecraftforge.oredict.ShapedOreRecipe; */ public class ShapedRecipeOre extends ShapedOreRecipe { private final ShapedRecipe recipe; - + public ShapedRecipeOre(Object[] contents, ShapedRecipe recipe) { super(getItemStack(recipe.getOutput()), contents); - + this.recipe = recipe; } - + @Override - public boolean matches(InventoryCrafting inventory, World world) { + public boolean matches(InventoryCrafting inventory, World world) { return recipe.matches(MCCraftingInventory.get(inventory)); } - + @Override - public ItemStack getCraftingResult(InventoryCrafting inventory) { + public ItemStack getCraftingResult(InventoryCrafting inventory) { return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); } } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeAdvanced.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeAdvanced.java index 91de672..e2a9850 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeAdvanced.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeAdvanced.java @@ -19,7 +19,7 @@ import net.minecraft.world.World; */ public class ShapelessRecipeAdvanced implements IRecipe { private final ShapelessRecipe recipe; - + public ShapelessRecipeAdvanced(ShapelessRecipe recipe) { this.recipe = recipe; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeBasic.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeBasic.java index f422221..6997da1 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeBasic.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeBasic.java @@ -20,18 +20,18 @@ import net.minecraft.world.World; */ public class ShapelessRecipeBasic extends ShapelessRecipes { private final ShapelessRecipe recipe; - + public ShapelessRecipeBasic(ItemStack[] ingredients, ShapelessRecipe recipe) { super(getItemStack(recipe.getOutput()), Arrays.asList(ingredients)); - + this.recipe = recipe; } - + @Override public boolean matches(InventoryCrafting inventory, World world) { return recipe.matches(MCCraftingInventory.get(inventory)); } - + @Override public ItemStack getCraftingResult(InventoryCrafting inventory) { return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeOre.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeOre.java index f86a44b..3a8bd43 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeOre.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/recipes/ShapelessRecipeOre.java @@ -19,18 +19,18 @@ import net.minecraftforge.oredict.ShapelessOreRecipe; */ public class ShapelessRecipeOre extends ShapelessOreRecipe { private final ShapelessRecipe recipe; - + public ShapelessRecipeOre(Object[] ingredients, ShapelessRecipe recipe) { super(getItemStack(recipe.getOutput()), ingredients); - + this.recipe = recipe; } - + @Override public boolean matches(InventoryCrafting inventory, World world) { return recipe.matches(MCCraftingInventory.get(inventory)); } - + @Override public ItemStack getCraftingResult(InventoryCrafting inventory) { return getItemStack(recipe.getCraftingResult(MCCraftingInventory.get(inventory))).copy(); diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/server/MCServer.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/server/MCServer.java index 0450c78..10fadfe 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/server/MCServer.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/server/MCServer.java @@ -30,20 +30,20 @@ import net.minecraft.server.management.UserListOps; */ public class MCServer extends AbstractServer { private final MinecraftServer server; - + public MCServer(MinecraftServer server) { this.server = server; } - + @Override public void addCommand(String name, String usage, String[] aliases, ICommandFunction function, ICommandValidator validator, ICommandTabCompletion completion) { ICommand command = new MCCommand(name, usage, aliases, function, validator, completion); MineTweakerAPI.apply(new AddCommandAction(command)); } - + @Override public void removeCommand(String name) { - ICommand command = (ICommand)((CommandHandler) server.getCommandManager()).getCommands().get(name); + ICommand command = (ICommand) ((CommandHandler) server.getCommandManager()).getCommands().get(name); if (command == null) { MineTweakerAPI.logWarning("No such command: " + name); } else { @@ -55,7 +55,7 @@ public class MCServer extends AbstractServer { public boolean isOp(IPlayer player) { if (player == ServerPlayer.INSTANCE) return true; - + UserListOps ops = MinecraftServer.getServer().getConfigurationManager().func_152603_m(); if (server.isDedicatedServer()) { return ops.func_152690_d() || ops.func_152700_a(player.getName()) != null; @@ -63,7 +63,7 @@ public class MCServer extends AbstractServer { return true; } } - + private static IPlayer getPlayer(ICommandSender commandSender) { if (commandSender instanceof EntityPlayer) { return MineTweakerMC.getIPlayer((EntityPlayer) commandSender); @@ -75,18 +75,18 @@ public class MCServer extends AbstractServer { return null; } } - + private static void removeCommand(ICommand command) { CommandHandler ch = (CommandHandler) MinecraftServer.getServer().getCommandManager(); ch.getCommands().remove(command.getCommandName()); if (command.getCommandAliases() != null) { - for (String alias : (List)command.getCommandAliases()) { + for (String alias : (List) command.getCommandAliases()) { ch.getCommands().remove(alias); } } } - + private class MCCommand implements ICommand { private final String name; private final String usage; @@ -94,7 +94,7 @@ public class MCServer extends AbstractServer { private final ICommandFunction function; private final ICommandValidator validator; private final ICommandTabCompletion completion; - + public MCCommand(String name, String usage, String[] aliases, ICommandFunction function, ICommandValidator validator, ICommandTabCompletion completion) { this.name = name; this.usage = usage; @@ -103,7 +103,7 @@ public class MCServer extends AbstractServer { this.validator = validator; this.completion = completion; } - + @Override public String getCommandName() { return name; @@ -152,10 +152,10 @@ public class MCServer extends AbstractServer { return 0; } } - + private class AddCommandAction implements IUndoableAction { private final ICommand command; - + public AddCommandAction(ICommand command) { this.command = command; } @@ -191,10 +191,10 @@ public class MCServer extends AbstractServer { return null; } } - + private class RemoveCommandAction implements IUndoableAction { private final ICommand command; - + public RemoveCommandAction(ICommand command) { this.command = command; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/server/ServerPlayer.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/server/ServerPlayer.java index 68b1834..b3a3a52 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/server/ServerPlayer.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/server/ServerPlayer.java @@ -28,9 +28,9 @@ import net.minecraft.util.IChatComponent; */ public class ServerPlayer implements IPlayer { public static final ServerPlayer INSTANCE = new ServerPlayer(); - + private ServerPlayer() { - + } @Override @@ -109,7 +109,7 @@ public class ServerPlayer implements IPlayer { } } } - + @Override public void copyToClipboard(String value) { if (Desktop.isDesktopSupported()) { @@ -121,6 +121,6 @@ public class ServerPlayer implements IPlayer { @Override public void give(IItemStack stack) { - + } } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerHacks.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerHacks.java index 04eb669..243eb50 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerHacks.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerHacks.java @@ -24,7 +24,8 @@ import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; import net.minecraft.inventory.InventoryCrafting; -import net.minecraft.inventory.SlotCrafting;import net.minecraft.item.ItemStack; +import net.minecraft.inventory.SlotCrafting; +import net.minecraft.item.ItemStack; import net.minecraft.nbt.NBTBase; import net.minecraft.nbt.NBTTagList; import net.minecraft.server.MinecraftServer; @@ -51,31 +52,32 @@ public class MineTweakerHacks { private static final Field SHAPEDORERECIPE_WIDTH; private static final Field INVENTORYCRAFTING_EVENTHANDLER; private static final Field SLOTCRAFTING_PLAYER; - + private static final Field ENTITYREGISTRY_CLASSREGISTRATIONS; private static final Field SEEDENTRY_SEED; private static final Constructor SEEDENTRY_CONSTRUCTOR; - + static { NBTTAGLIST_TAGLIST = getField(NBTTagList.class, MineTweakerObfuscation.NBTTAGLIST_TAGLIST); OREDICTIONARY_IDTOSTACK = getField(OreDictionary.class, MineTweakerObfuscation.OREDICTIONARY_IDTOSTACK); OREDICTIONARY_IDTOSTACKUN = getField(OreDictionary.class, MineTweakerObfuscation.OREDICTIONARY_IDTOSTACKUN); MINECRAFTSERVER_ANVILFILE = getField(MinecraftServer.class, MineTweakerObfuscation.MINECRAFTSERVER_ANVILFILE); - SHAPEDORERECIPE_WIDTH = getField(ShapedOreRecipe.class, new String[] {"width"}); + SHAPEDORERECIPE_WIDTH = getField(ShapedOreRecipe.class, new String[] { "width" }); INVENTORYCRAFTING_EVENTHANDLER = getField(InventoryCrafting.class, MineTweakerObfuscation.INVENTORYCRAFTING_EVENTHANDLER); SLOTCRAFTING_PLAYER = getField(SlotCrafting.class, MineTweakerObfuscation.SLOTCRAFTING_PLAYER); - - ENTITYREGISTRY_CLASSREGISTRATIONS = getField(EntityRegistry.class, new String[] {"entityClassRegistrations"}); - + + ENTITYREGISTRY_CLASSREGISTRATIONS = getField(EntityRegistry.class, new String[] { "entityClassRegistrations" }); + Class forgeSeedEntry = null; try { forgeSeedEntry = (Class) Class.forName("net.minecraftforge.common.ForgeHooks$SeedEntry"); - } catch (ClassNotFoundException ex) {} - + } catch (ClassNotFoundException ex) { + } + SEEDENTRY_SEED = getField(forgeSeedEntry, "seed"); - + Constructor seedEntryConstructor = null; - + try { seedEntryConstructor = forgeSeedEntry.getConstructor(ItemStack.class, int.class); seedEntryConstructor.setAccessible(true); @@ -84,12 +86,13 @@ public class MineTweakerHacks { } catch (SecurityException ex) { Logger.getLogger(MineTweakerHacks.class.getName()).log(Level.SEVERE, null, ex); } - + SEEDENTRY_CONSTRUCTOR = seedEntryConstructor; } - - private MineTweakerHacks() {} - + + private MineTweakerHacks() { + } + public static BiMap, EntityRegistry.EntityRegistration> getEntityClassRegistrations() { try { return (BiMap, EntityRegistry.EntityRegistration>) ENTITYREGISTRY_CLASSREGISTRATIONS.get(EntityRegistry.instance()); @@ -99,7 +102,7 @@ public class MineTweakerHacks { return null; } } - + public static List getTagList(NBTTagList list) { if (NBTTAGLIST_TAGLIST == null) { return null; @@ -112,22 +115,22 @@ public class MineTweakerHacks { return null; } } - + public static List getSeeds() { return getPrivateStaticObject(ForgeHooks.class, "seedList"); } - + public static Map getChestLoot() { return getPrivateStaticObject(ChestGenHooks.class, "chestInfo"); } - + public static Map getTranslations() { return getPrivateObject( - getPrivateStaticObject(StatCollector.class, "localizedName", "field_74839_a"), - "languageList", - "field_74816_c"); + getPrivateStaticObject(StatCollector.class, "localizedName", "field_74839_a"), + "languageList", + "field_74816_c"); } - + public static List> getOreIdStacks() { try { return (List>) OREDICTIONARY_IDTOSTACK.get(null); @@ -136,7 +139,7 @@ public class MineTweakerHacks { return null; } } - + public static List> getOreIdStacksUn() { try { return (List>) OREDICTIONARY_IDTOSTACKUN.get(null); @@ -145,7 +148,7 @@ public class MineTweakerHacks { return null; } } - + public static File getAnvilFile(MinecraftServer server) { try { return (File) MINECRAFTSERVER_ANVILFILE.get(server); @@ -154,18 +157,19 @@ public class MineTweakerHacks { return null; } } - + public static File getWorldDirectory(MinecraftServer server) { if (server.isDedicatedServer()) { return server.getFile("world"); } else { File worldsDir = getAnvilFile(server); - if (worldsDir == null) return null; - - return new File(worldsDir, server.getFolderName()); + if (worldsDir == null) + return null; + + return new File(worldsDir, server.getFolderName()); } } - + public static int getShapedOreRecipeWidth(ShapedOreRecipe recipe) { try { return SHAPEDORERECIPE_WIDTH.getInt(recipe); @@ -174,7 +178,7 @@ public class MineTweakerHacks { return 3; } } - + public static Container getCraftingContainer(InventoryCrafting inventory) { try { return (Container) INVENTORYCRAFTING_EVENTHANDLER.get(inventory); @@ -183,7 +187,7 @@ public class MineTweakerHacks { return null; } } - + public static EntityPlayer getCraftingSlotPlayer(SlotCrafting slot) { try { return (EntityPlayer) SLOTCRAFTING_PLAYER.get(slot); @@ -192,7 +196,7 @@ public class MineTweakerHacks { return null; } } - + public static StringTranslate getStringTranslateInstance() { try { Field field = getField(StringTranslate.class, MineTweakerObfuscation.STRINGTRANSLATE_INSTANCE); @@ -202,7 +206,7 @@ public class MineTweakerHacks { return null; } } - + public static ItemStack getSeedEntrySeed(Object entry) { try { return (ItemStack) SEEDENTRY_SEED.get(entry); @@ -211,7 +215,7 @@ public class MineTweakerHacks { return null; } } - + public static WeightedRandom.Item constructSeedEntry(WeightedItemStack stack) { try { return SEEDENTRY_CONSTRUCTOR.newInstance(MineTweakerMC.getItemStack(stack.getStack()), (int) stack.getChance()); @@ -224,10 +228,10 @@ public class MineTweakerHacks { } catch (InvocationTargetException ex) { MineTweakerAPI.logError("could not construct SeedEntry"); } - + return null; } - + public static T getPrivateStaticObject(Class cls, String... names) { for (String name : names) { try { @@ -242,10 +246,10 @@ public class MineTweakerHacks { } } - + return null; } - + public static T getPrivateObject(Object object, String... names) { Class cls = object.getClass(); for (String name : names) { @@ -261,15 +265,14 @@ public class MineTweakerHacks { } } - + return null; } - - + // ####################### // ### Private Methods ### // ####################### - + private static Field getField(Class cls, String... names) { for (String name : names) { try { @@ -280,7 +283,7 @@ public class MineTweakerHacks { } catch (SecurityException ex) { } } - + return null; } } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerObfuscation.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerObfuscation.java index 9c67978..0c7eb62 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerObfuscation.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerObfuscation.java @@ -11,14 +11,15 @@ package minetweaker.mc1710.util; * @author Stanneke */ public class MineTweakerObfuscation { - private MineTweakerObfuscation() {} - - public static final String[] NBTTAGLIST_TAGLIST = {"tagList", "field_74747_a"}; - public static final String[] CRAFTINGMANAGER_RECIPES = {"recipes", "field_77597_b"}; - public static final String[] OREDICTIONARY_IDTOSTACK = {"idToStack"}; - public static final String[] OREDICTIONARY_IDTOSTACKUN = {"idToStackUn"}; - public static final String[] MINECRAFTSERVER_ANVILFILE = {"anvilFile", "field_71308_o"}; - public static final String[] INVENTORYCRAFTING_EVENTHANDLER = {"eventHandler", "field_70465_c"}; - public static final String[] SLOTCRAFTING_PLAYER = {"thePlayer", "field_75238_b"}; - public static final String[] STRINGTRANSLATE_INSTANCE = {"instance", "field_74817_a"}; + private MineTweakerObfuscation() { + } + + public static final String[] NBTTAGLIST_TAGLIST = { "tagList", "field_74747_a" }; + public static final String[] CRAFTINGMANAGER_RECIPES = { "recipes", "field_77597_b" }; + public static final String[] OREDICTIONARY_IDTOSTACK = { "idToStack" }; + public static final String[] OREDICTIONARY_IDTOSTACKUN = { "idToStackUn" }; + public static final String[] MINECRAFTSERVER_ANVILFILE = { "anvilFile", "field_71308_o" }; + public static final String[] INVENTORYCRAFTING_EVENTHANDLER = { "eventHandler", "field_70465_c" }; + public static final String[] SLOTCRAFTING_PLAYER = { "thePlayer", "field_75238_b" }; + public static final String[] STRINGTRANSLATE_INSTANCE = { "instance", "field_74817_a" }; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerPlatformUtils.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerPlatformUtils.java index 2ced44a..036f90c 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerPlatformUtils.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/util/MineTweakerPlatformUtils.java @@ -16,8 +16,9 @@ import net.minecraft.entity.EntityLivingBase; * @author Stan */ public class MineTweakerPlatformUtils { - private MineTweakerPlatformUtils() {} - + private MineTweakerPlatformUtils() { + } + public static Class getLivingEntityClass(String entityClassName) { try { Class entityClass = Class.forName(entityClassName); @@ -29,16 +30,16 @@ public class MineTweakerPlatformUtils { throw new RuntimeException("entity class not found: " + entityClassName); } } - + public static String getLanguage() { return FMLCommonHandler.instance().getSide() == Side.SERVER ? null : FMLClientHandler.instance().getCurrentLanguage(); } - + public static boolean isLanguageActive(String lang) { String current = getLanguage(); return current != null && current.equals(lang); } - + public static boolean isClient() { return FMLCommonHandler.instance().getSide() == Side.CLIENT; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCLootRegistry.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCLootRegistry.java index 5305678..95ea083 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCLootRegistry.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCLootRegistry.java @@ -27,7 +27,7 @@ import net.minecraftforge.common.ChestGenHooks; */ public class MCLootRegistry implements ILootRegistry { private static final Map LOOT = MineTweakerHacks.getChestLoot(); - + @Override public void addChestLoot(String type, WeightedItemStack item) { WeightedRandomChestContent content = new WeightedRandomChestContent( @@ -52,23 +52,23 @@ public class MCLootRegistry implements ILootRegistry { public void removeChestLoot(String type, IIngredient pattern) { MineTweakerAPI.apply(new RemoveLootAction(type, pattern)); } - + @Override public List getLoot(String type) { ChestGenHooks recipe = LOOT.get(type); List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - + List results = new ArrayList(); for (WeightedRandomChestContent content : contents) { results.add(new LootEntry(new WeightedItemStack( MineTweakerMC.getIItemStack(content.theItemId), content.itemWeight), - content.theMinimumChanceToGenerateItem, - content.theMaximumChanceToGenerateItem)); + content.theMinimumChanceToGenerateItem, + content.theMaximumChanceToGenerateItem)); } return results; } - + @Override public List getLootTypes() { Set keys = LOOT.keySet(); @@ -76,49 +76,49 @@ public class MCLootRegistry implements ILootRegistry { keyList.addAll(keys); return keyList; } - + // ###################### // ### Action Classes ### // ###################### - + /** * Ported from ModTweaker. * * @author JoshieJack */ - private static class AddLootAction implements IUndoableAction { + private static class AddLootAction implements IUndoableAction { private final String chest; - private final WeightedRandomChestContent content; + private final WeightedRandomChestContent content; - public AddLootAction(String chest, WeightedRandomChestContent content) { + public AddLootAction(String chest, WeightedRandomChestContent content) { this.chest = chest; - this.content = content; - } + this.content = content; + } - @Override - public void apply() { - ChestGenHooks recipe = LOOT.get(chest); + @Override + public void apply() { + ChestGenHooks recipe = LOOT.get(chest); List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - + contents.add(content); - } + } - @Override - public boolean canUndo() { - return true; - } + @Override + public boolean canUndo() { + return true; + } - @Override - public void undo() { - ChestGenHooks recipe = LOOT.get(chest); + @Override + public void undo() { + ChestGenHooks recipe = LOOT.get(chest); List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - - contents.remove(content); - } - public String getRecipeInfo() { - return content.theItemId.getDisplayName(); - } + contents.remove(content); + } + + public String getRecipeInfo() { + return content.theItemId.getDisplayName(); + } @Override public String describe() { @@ -134,29 +134,29 @@ public class MCLootRegistry implements ILootRegistry { public Object getOverrideKey() { return null; } - } - + } + /** * Ported from ModTweaker. * * @author JoshieJack */ - private static class RemoveLootAction implements IUndoableAction { + private static class RemoveLootAction implements IUndoableAction { private final String chest; private final IIngredient pattern; - private final List removed; + private final List removed; - public RemoveLootAction(String chest, IIngredient pattern) { + public RemoveLootAction(String chest, IIngredient pattern) { this.chest = chest; this.pattern = pattern; removed = new ArrayList(); - } + } - @Override - public void apply() { + @Override + public void apply() { removed.clear(); - - ChestGenHooks recipe = LOOT.get(chest); + + ChestGenHooks recipe = LOOT.get(chest); List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); for (WeightedRandomChestContent r : contents) { @@ -164,26 +164,26 @@ public class MCLootRegistry implements ILootRegistry { removed.add(r); } } - + for (WeightedRandomChestContent r : removed) { contents.remove(r); } - } + } - @Override - public boolean canUndo() { + @Override + public boolean canUndo() { return true; - } + } - @Override - public void undo() { - ChestGenHooks recipe = LOOT.get(chest); + @Override + public void undo() { + ChestGenHooks recipe = LOOT.get(chest); List contents = MineTweakerHacks.getPrivateObject(recipe, "contents"); - + for (WeightedRandomChestContent entry : removed) { contents.add(entry); } - } + } @Override public String describe() { @@ -199,5 +199,5 @@ public class MCLootRegistry implements ILootRegistry { public Object getOverrideKey() { return null; } - } + } } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCSeedRegistry.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCSeedRegistry.java index 8ef2926..0340b52 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCSeedRegistry.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCSeedRegistry.java @@ -25,7 +25,7 @@ import net.minecraft.util.WeightedRandom; */ public class MCSeedRegistry implements ISeedRegistry { private static final List SEEDS = MineTweakerHacks.getSeeds(); - + @Override public void addSeed(WeightedItemStack item) { MineTweakerAPI.apply(new AddSeedAction(item)); @@ -35,34 +35,34 @@ public class MCSeedRegistry implements ISeedRegistry { public void removeSeed(IIngredient pattern) { MineTweakerAPI.apply(new RemoveSeedAction(pattern)); } - + @Override public List getSeeds() { List entries = (List) SEEDS; - + List results = new ArrayList(); for (WeightedRandom.Item entry : entries) { results.add(new WeightedItemStack( MineTweakerMC.getIItemStack(MineTweakerHacks.getSeedEntrySeed(entry)), entry.itemWeight - )); + )); } return results; } - + // ###################### // ### Action classes ### // ###################### - + private static class AddSeedAction implements IUndoableAction { private final IItemStack item; private final WeightedRandom.Item entry; - + public AddSeedAction(WeightedItemStack item) { this.item = item.getStack(); entry = MineTweakerHacks.constructSeedEntry(item); } - + @Override public void apply() { SEEDS.add(entry); @@ -93,11 +93,11 @@ public class MCSeedRegistry implements ISeedRegistry { return null; } } - + private static class RemoveSeedAction implements IUndoableAction { private final IIngredient pattern; private final List removed; - + public RemoveSeedAction(IIngredient ingredient) { this.pattern = ingredient; removed = new ArrayList(); @@ -106,14 +106,14 @@ public class MCSeedRegistry implements ISeedRegistry { @Override public void apply() { removed.clear(); - + for (Object entry : SEEDS) { ItemStack itemStack = MineTweakerHacks.getSeedEntrySeed(entry); if (pattern.matches(MineTweakerMC.getIItemStack(itemStack))) { removed.add(entry); } } - + for (Object entry : removed) { SEEDS.remove(entry); } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCVanilla.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCVanilla.java index 6ae1d9a..f906614 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCVanilla.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/vanilla/MCVanilla.java @@ -17,7 +17,7 @@ import minetweaker.api.vanilla.IVanilla; public class MCVanilla implements IVanilla { private final MCLootRegistry lootRegistry = new MCLootRegistry(); private final MCSeedRegistry seedRegistry = new MCSeedRegistry(); - + @Override public ILootRegistry getLoot() { return lootRegistry; diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/world/MCBiome.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/world/MCBiome.java index 25266b3..f355077 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/world/MCBiome.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/world/MCBiome.java @@ -15,7 +15,7 @@ import net.minecraft.world.biome.BiomeGenBase; */ public class MCBiome implements IBiome { private final BiomeGenBase biome; - + public MCBiome(BiomeGenBase biome) { this.biome = biome; } diff --git a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/world/MCDimension.java b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/world/MCDimension.java index c83d25f..8c28ddb 100644 --- a/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/world/MCDimension.java +++ b/MineTweaker3-MC1710-Main/src/main/java/minetweaker/mc1710/world/MCDimension.java @@ -17,7 +17,7 @@ import net.minecraft.world.World; */ public class MCDimension implements IDimension { private final World world; - + public MCDimension(World world) { this.world = world; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/IZenCompileEnvironment.java b/ZenScript/src/main/java/stanhebben/zenscript/IZenCompileEnvironment.java index 2035011..c05eb9a 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/IZenCompileEnvironment.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/IZenCompileEnvironment.java @@ -18,14 +18,14 @@ import stanhebben.zenscript.symbols.IZenSymbol; */ public interface IZenCompileEnvironment { public IZenErrorLogger getErrorLogger(); - + public IZenSymbol getGlobal(String name); - + public IZenSymbol getDollar(String name); - + public IZenSymbol getBracketed(IEnvironmentGlobal environment, List tokens); - + public TypeRegistry getTypeRegistry(); - + public TypeExpansion getExpansion(String type); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/IZenErrorLogger.java b/ZenScript/src/main/java/stanhebben/zenscript/IZenErrorLogger.java index 9fbe5e6..e511b03 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/IZenErrorLogger.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/IZenErrorLogger.java @@ -16,7 +16,7 @@ public interface IZenErrorLogger { * @param message error message */ public void error(ZenPosition position, String message); - + /** * Called when a warning is generated during compilation. * diff --git a/ZenScript/src/main/java/stanhebben/zenscript/TypeExpansion.java b/ZenScript/src/main/java/stanhebben/zenscript/TypeExpansion.java index 28a4e80..404de5c 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/TypeExpansion.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/TypeExpansion.java @@ -34,8 +34,8 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; import stanhebben.zenscript.value.IAny; /** - * Type expansions provide additional members for existing types. They can - * add members, casters or operators and these will be available to all compiling + * Type expansions provide additional members for existing types. They can add + * members, casters or operators and these will be available to all compiling * scripts. * * @author Stan Hebben @@ -48,7 +48,7 @@ public class TypeExpansion { private final List trinaryOperators; private final List binaryOperators; private final List unaryOperators; - + /** * Creates an empty type expansion. Use the expand method to register the * actual expansions. @@ -57,7 +57,7 @@ public class TypeExpansion { */ public TypeExpansion(String type) { this.type = type; - + members = new HashMap(); staticMembers = new HashMap(); casters = new ArrayList(); @@ -65,7 +65,7 @@ public class TypeExpansion { binaryOperators = new ArrayList(); unaryOperators = new ArrayList(); } - + /** * Added a native type expansion. The provided class must contain the proper * annotations for the required expansions, else nothing will happen. Each @@ -78,7 +78,7 @@ public class TypeExpansion { public void expand(Class cls, ITypeRegistry types) { for (Method method : cls.getMethods()) { String methodName = method.getName(); - + for (Annotation annotation : method.getAnnotations()) { if (annotation instanceof ZenCaster) { checkStatic(method); @@ -87,7 +87,7 @@ public class TypeExpansion { checkStatic(method); ZenGetter getterAnnotation = (ZenGetter) annotation; String name = getterAnnotation.value().length() == 0 ? method.getName() : getterAnnotation.value(); - + if (!members.containsKey(name)) { members.put(name, new ZenExpandMember(type, name)); } @@ -96,7 +96,7 @@ public class TypeExpansion { checkStatic(method); ZenSetter setterAnnotation = (ZenSetter) annotation; String name = setterAnnotation.value().length() == 0 ? method.getName() : setterAnnotation.value(); - + if (!members.containsKey(name)) { members.put(name, new ZenExpandMember(type, name)); } @@ -174,7 +174,7 @@ public class TypeExpansion { } } } - + /** * Registers all casting rules to the given delegate. * @@ -186,7 +186,7 @@ public class TypeExpansion { caster.constructCastingRules(environment, rules); } } - + /** * Retrieves a caster from this expansion. May return null if no suitable * caster was available. @@ -203,18 +203,18 @@ public class TypeExpansion { return caster; } } - + for (ZenExpandCaster caster : casters) { if (caster.getTarget().canCastImplicit(type, environment)) { return caster; } } - + return null; } - + /** - * Retrieves a unary operator from this expansion. May return null if no + * Retrieves a unary operator from this expansion. May return null if no * suitable operator was available. * * @param position calling position @@ -233,10 +233,10 @@ public class TypeExpansion { return new ExpressionCallStatic(position, environment, op.getMethod(), value); } } - + return null; } - + /** * Retrieves a binary operator from this expansion. May return null if no * suitable operator was available. @@ -259,10 +259,10 @@ public class TypeExpansion { return new ExpressionCallStatic(position, environment, op.getMethod(), left, right); } } - + return null; } - + /** * Retrieves a ternary operator from this expansion. May return null if no * suitable operator was available. @@ -287,10 +287,10 @@ public class TypeExpansion { return new ExpressionCallStatic(position, environment, op.getMethod(), first, second, third); } } - + return null; } - + /** * Retrieves an instance member from this expansion. May return null if no * suitable member was available. @@ -299,7 +299,8 @@ public class TypeExpansion { * @param environment compile environment * @param value instance value * @param member member name - * @return resulting member expression, or null if no such member was available + * @return resulting member expression, or null if no such member was + * available */ public IPartialExpression instanceMember( ZenPosition position, @@ -309,10 +310,10 @@ public class TypeExpansion { if (members.containsKey(member)) { return members.get(member).instance(position, environment, value); } - + return null; } - + /** * Retrieves a static member from this expansion. May return null if no * suitable member was available. @@ -320,25 +321,26 @@ public class TypeExpansion { * @param position calling position * @param environment compile environment * @param member member name - * @return resulting static member expression, or null if no such member was available + * @return resulting static member expression, or null if no such member was + * available */ public IPartialExpression staticMember(ZenPosition position, IEnvironmentGlobal environment, String member) { if (staticMembers.containsKey(member)) { return staticMembers.get(member).instance(position, environment); } - + return null; } - + public void compileAnyCast(ZenType type, MethodOutput output, IEnvironmentGlobal environment, int localValue, int localClass) { if (type == null) throw new IllegalArgumentException("type cannot be null"); - + Type asmType = type.toASMType(); if (asmType == null) { throw new RuntimeException("type has no asm type"); } - + for (ZenExpandCaster caster : casters) { Label skip = new Label(); output.loadObject(localClass); @@ -349,13 +351,13 @@ public class TypeExpansion { output.returnType(caster.getTarget().toASMType()); output.label(skip); } - + for (ZenExpandCaster caster : casters) { String casterAny = caster.getTarget().getAnyClassName(environment); if (casterAny == null) // TODO: make sure this isn't necessary continue; - + Label skip = new Label(); output.loadObject(localClass); output.invokeStatic(casterAny, "rtCanCastImplicit", "(Ljava/lang/Class;)Z"); @@ -368,7 +370,7 @@ public class TypeExpansion { output.label(skip); } } - + public void compileAnyCanCastImplicit(ZenType type, MethodOutput output, IEnvironmentGlobal environment, int localClass) { for (ZenExpandCaster caster : casters) { Label skip = new Label(); @@ -379,14 +381,14 @@ public class TypeExpansion { output.returnInt(); output.label(skip); } - + for (ZenExpandCaster caster : casters) { String casterAny = caster.getTarget().getAnyClassName(environment); if (casterAny == null) { // TODO: make sure no type ever does this continue; } - + Label skip = new Label(); output.loadObject(localClass); output.invokeStatic(casterAny, "rtCanCastImplicit", "(Ljava/lang/Class;)Z"); @@ -396,12 +398,12 @@ public class TypeExpansion { output.label(skip); } } - + public boolean compileAnyUnary(MethodOutput output, OperatorType type, IEnvironmentMethod environment) { for (ZenNativeOperator operator : unaryOperators) { if (operator.getOperator() == type) { ZenType returnType = operator.getMethod().getReturnType(); - + output.loadObject(0); operator.getMethod().invokeStatic(output); output.invokeStatic( @@ -412,14 +414,14 @@ public class TypeExpansion { return true; } } - + return false; } - + // ####################### // ### Private methods ### // ####################### - + /** * Checks if the given method is static. Throws an exception if not. * diff --git a/ZenScript/src/main/java/stanhebben/zenscript/ZenParsedFile.java b/ZenScript/src/main/java/stanhebben/zenscript/ZenParsedFile.java index afa6dfb..d06cee2 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/ZenParsedFile.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/ZenParsedFile.java @@ -26,8 +26,8 @@ import stanhebben.zenscript.type.ZenType; *
  • A set of statuments
  • * * - * This parsed file cannot be executed by itself, but it can be compiled into - * a module, possibly together with other files. + * This parsed file cannot be executed by itself, but it can be compiled into a + * module, possibly together with other files. * * @author Stan Hebben */ @@ -38,7 +38,7 @@ public class ZenParsedFile { private final Map functions; private final List statements; private final IEnvironmentGlobal environmentScript; - + /** * Constructs and parses a given file. * @@ -50,43 +50,43 @@ public class ZenParsedFile { public ZenParsedFile(String filename, String classname, ZenTokener tokener, IEnvironmentGlobal environment) { this.filename = filename; this.classname = classname; - + imports = new ArrayList(); functions = new HashMap(); statements = new ArrayList(); environmentScript = new EnvironmentScript(environment); - + tokener.setFile(this); - + while (tokener.peek() != null && tokener.peek().getType() == T_IMPORT) { Token start = tokener.next(); - + List importName = new ArrayList(); Token tName = tokener.required(T_ID, "identifier expected"); importName.add(tName.getValue()); - + while (tokener.optional(T_DOT) != null) { Token tNamePart = tokener.required(T_ID, "identifier expected"); importName.add(tNamePart.getValue()); } - + String rename = null; if (tokener.optional(T_AS) != null) { Token tRename = tokener.required(T_ID, "identifier expected"); rename = tRename.getValue(); } - + tokener.required(T_SEMICOLON, "; expected"); - + imports.add(new Import(start.getPosition(), importName, rename)); } - + for (Import imprt : imports) { List name = imprt.getName(); IPartialExpression type = null; - + StringBuilder nameSoFar = new StringBuilder(); - + for (String part : name) { if (type == null) { nameSoFar.append(part); @@ -104,7 +104,7 @@ public class ZenParsedFile { } } } - + if (type != null) { IZenSymbol symbol = type.toSymbol(); if (symbol == null) { @@ -116,7 +116,7 @@ public class ZenParsedFile { environmentScript.putValue(imprt.getRename(), new SymbolType(ZenType.ANY), imprt.getPosition()); } } - + while (tokener.hasNext()) { Token next = tokener.peek(); if (next.getType() == T_FUNCTION) { @@ -130,11 +130,11 @@ public class ZenParsedFile { } } } - + public IEnvironmentGlobal getEnvironment() { return environmentScript; } - + /** * Gets the output classname for this file. * @@ -143,7 +143,7 @@ public class ZenParsedFile { public String getClassName() { return classname; } - + /** * Gets the input filename for this file. * @@ -152,7 +152,7 @@ public class ZenParsedFile { public String getFileName() { return filename; } - + /** * Gets the imports list. * @@ -161,7 +161,7 @@ public class ZenParsedFile { public List getImports() { return imports; } - + /** * Gets this file's script statements. * @@ -170,7 +170,7 @@ public class ZenParsedFile { public List getStatements() { return statements; } - + /** * Gets the functions defined inside this file. * @@ -179,7 +179,7 @@ public class ZenParsedFile { public Map getFunctions() { return functions; } - + @Override public String toString() { return filename; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/ZenRuntimeException.java b/ZenScript/src/main/java/stanhebben/zenscript/ZenRuntimeException.java index 4703aeb..1ff13de 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/ZenRuntimeException.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/ZenRuntimeException.java @@ -2,8 +2,8 @@ package stanhebben.zenscript; /** * ZenRuntimeExceptions are thrown when an internal error occurs during - * execution of scripts. Since ZenScript is only partially typesafe, errors - * may occur at runtime due to impossible operations being executed. + * execution of scripts. Since ZenScript is only partially typesafe, errors may + * occur at runtime due to impossible operations being executed. * * @author Stan Hebben */ diff --git a/ZenScript/src/main/java/stanhebben/zenscript/ZenTokener.java b/ZenScript/src/main/java/stanhebben/zenscript/ZenTokener.java index 150ef97..e143163 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/ZenTokener.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/ZenTokener.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.parser.TokenStream; */ public class ZenTokener extends TokenStream { private static final HashMap KEYWORDS; - + public static final int T_ID = 1; public static final int T_INTVALUE = 2; public static final int T_FLOATVALUE = 3; @@ -63,7 +63,7 @@ public class ZenTokener extends TokenStream { public static final int T_NOTEQ = 42; public static final int T_NOT = 43; public static final int T_DOLLAR = 44; - + public static final int T_ANY = 99; public static final int T_BOOL = 100; public static final int T_BYTE = 101; @@ -76,7 +76,7 @@ public class ZenTokener extends TokenStream { public static final int T_FUNCTION = 108; public static final int T_IN = 109; public static final int T_VOID = 110; - + public static final int T_AS = 120; public static final int T_VERSION = 121; public static final int T_IF = 122; @@ -85,119 +85,119 @@ public class ZenTokener extends TokenStream { public static final int T_RETURN = 125; public static final int T_VAR = 126; public static final int T_VAL = 127; - + public static final int T_NULL = 140; public static final int T_TRUE = 141; public static final int T_FALSE = 142; - + public static final int T_IMPORT = 160; - + private static final String[] REGEXPS = { - "#[^\n]*[\n\\e]", - "//[^\n]*[\n\\e]", - "/\\*[^\\*]*(\\*[^/]*)*\\*/", - "[ \t\r\n]*", - "[a-zA-Z_][a-zA-Z_0-9]*", - "\\-?(0|[1-9][0-9]*)\\.[0-9]+([eE][\\+\\-]?[0-9]+)?", - "\\-?(0|[1-9][0-9]*)", - "\"([^\"\\\\]|\\\\([\'\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"", - "\'([^\'\\\\]|\\\\([\'\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\'", - "\\{", - "\\}", - "\\[", - "\\]", - "\\.\\.", - "\\.", - ",", - "\\+=", - "\\+", - "\\-=", - "\\-", - "\\*=", - "\\*", - "/=", - "/", - "%=", - "%", - "\\|=", - "\\|\\|", - "\\|", - "&=", - "&&", - "&", - "\\^=", - "\\^", - "\\?", - ":", - "\\(", - "\\)", - "~=", - "~", - ";", - "<=", - "<", - ">=", - ">", - "==", - "=", - "!=", - "!", - "$" + "#[^\n]*[\n\\e]", + "//[^\n]*[\n\\e]", + "/\\*[^\\*]*(\\*[^/]*)*\\*/", + "[ \t\r\n]*", + "[a-zA-Z_][a-zA-Z_0-9]*", + "\\-?(0|[1-9][0-9]*)\\.[0-9]+([eE][\\+\\-]?[0-9]+)?", + "\\-?(0|[1-9][0-9]*)", + "\"([^\"\\\\]|\\\\([\'\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\"", + "\'([^\'\\\\]|\\\\([\'\"\\\\/bfnrt]|u[0-9a-fA-F]{4}))*\'", + "\\{", + "\\}", + "\\[", + "\\]", + "\\.\\.", + "\\.", + ",", + "\\+=", + "\\+", + "\\-=", + "\\-", + "\\*=", + "\\*", + "/=", + "/", + "%=", + "%", + "\\|=", + "\\|\\|", + "\\|", + "&=", + "&&", + "&", + "\\^=", + "\\^", + "\\?", + ":", + "\\(", + "\\)", + "~=", + "~", + ";", + "<=", + "<", + ">=", + ">", + "==", + "=", + "!=", + "!", + "$" }; private static final int[] FINALS = { - -1, - -1, - -1, - -1, - T_ID, - T_FLOATVALUE, - T_INTVALUE, - T_STRINGVALUE, - T_STRINGVALUE, - T_AOPEN, - T_ACLOSE, - T_SQBROPEN, - T_SQBRCLOSE, - T_DOT2, - T_DOT, - T_COMMA, - T_PLUSASSIGN, - T_PLUS, - T_MINUSASSIGN, - T_MINUS, - T_MULASSIGN, - T_MUL, - T_DIVASSIGN, - T_DIV, - T_MODASSIGN, - T_MOD, - T_ORASSIGN, - T_OR2, - T_OR, - T_ANDASSIGN, - T_AND2, - T_AND, - T_XORASSIGN, - T_XOR, - T_QUEST, - T_COLON, - T_BROPEN, - T_BRCLOSE, - T_TILDEASSIGN, - T_TILDE, - T_SEMICOLON, - T_LTEQ, - T_LT, - T_GTEQ, - T_GT, - T_EQ, - T_ASSIGN, - T_NOTEQ, - T_NOT, - T_DOLLAR + -1, + -1, + -1, + -1, + T_ID, + T_FLOATVALUE, + T_INTVALUE, + T_STRINGVALUE, + T_STRINGVALUE, + T_AOPEN, + T_ACLOSE, + T_SQBROPEN, + T_SQBRCLOSE, + T_DOT2, + T_DOT, + T_COMMA, + T_PLUSASSIGN, + T_PLUS, + T_MINUSASSIGN, + T_MINUS, + T_MULASSIGN, + T_MUL, + T_DIVASSIGN, + T_DIV, + T_MODASSIGN, + T_MOD, + T_ORASSIGN, + T_OR2, + T_OR, + T_ANDASSIGN, + T_AND2, + T_AND, + T_XORASSIGN, + T_XOR, + T_QUEST, + T_COLON, + T_BROPEN, + T_BRCLOSE, + T_TILDEASSIGN, + T_TILDE, + T_SEMICOLON, + T_LTEQ, + T_LT, + T_GTEQ, + T_GT, + T_EQ, + T_ASSIGN, + T_NOTEQ, + T_NOT, + T_DOLLAR }; private static final CompiledDFA DFA = new NFA(REGEXPS, FINALS).toDFA().optimize().compile(); - + static { KEYWORDS = new HashMap(); KEYWORDS.put("any", T_ANY); @@ -212,7 +212,7 @@ public class ZenTokener extends TokenStream { KEYWORDS.put("function", T_FUNCTION); KEYWORDS.put("in", T_IN); KEYWORDS.put("void", T_VOID); - + KEYWORDS.put("as", T_AS); KEYWORDS.put("version", T_VERSION); KEYWORDS.put("if", T_IF); @@ -221,16 +221,16 @@ public class ZenTokener extends TokenStream { KEYWORDS.put("return", T_RETURN); KEYWORDS.put("var", T_VAR); KEYWORDS.put("val", T_VAL); - + KEYWORDS.put("null", T_NULL); KEYWORDS.put("true", T_TRUE); KEYWORDS.put("false", T_FALSE); - + KEYWORDS.put("import", T_IMPORT); } - + private final IZenCompileEnvironment environment; - + /** * Constructs a tokener from the given reader. * @@ -240,10 +240,10 @@ public class ZenTokener extends TokenStream { */ public ZenTokener(Reader contents, IZenCompileEnvironment environment) throws IOException { super(contents, DFA); - + this.environment = environment; } - + /** * Constructs a tokener from the given string. * @@ -253,10 +253,10 @@ public class ZenTokener extends TokenStream { */ public ZenTokener(String contents, IZenCompileEnvironment environment) throws IOException { super(new StringReader(contents), DFA); - + this.environment = environment; } - + /** * Retrieves the compile environment of this tokener. * @@ -265,11 +265,11 @@ public class ZenTokener extends TokenStream { public IZenCompileEnvironment getEnvironment() { return environment; } - + // ################################## // ### TokenStream implementation ### // ################################## - + @Override public Token process(Token token) { if (token.getType() == T_ID) { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/IterableList.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/IterableList.java index ceca76b..1f6b7a7 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/IterableList.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/IterableList.java @@ -6,7 +6,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Makes a class implementing List expose itself as iterable over keys and values. + * Makes a class implementing List expose itself as iterable over keys and + * values. * * @author Stan Hebben */ diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/IterableMap.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/IterableMap.java index 732581a..d698c59 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/IterableMap.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/IterableMap.java @@ -6,7 +6,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Makes a class implementing Map expose itself as iterable over keys and values. + * Makes a class implementing Map expose itself as iterable over keys and + * values. * * @author Stan Hebben */ @@ -14,5 +15,6 @@ import java.lang.annotation.Target; @Target(ElementType.TYPE) public @interface IterableMap { String key(); + String value(); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/NotNull.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/NotNull.java index 6ce9999..c6216de 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/NotNull.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/NotNull.java @@ -13,5 +13,5 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface NotNull { - + } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/Optional.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/Optional.java index 1e02ad6..4d55501 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/Optional.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/Optional.java @@ -15,5 +15,5 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.PARAMETER) public @interface Optional { - + } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenCaster.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenCaster.java index 6c77c5d..e0cf133 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenCaster.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenCaster.java @@ -17,5 +17,5 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ZenCaster { - + } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenClass.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenClass.java index c9efe12..5790614 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenClass.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenClass.java @@ -12,13 +12,13 @@ import java.lang.annotation.Target; * @author Stan Hebben */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) public @interface ZenClass { /** * Contains the class' package and name. If omitted, the java package and * name will be used. * - * @return + * @return */ String value() default ""; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenExpansion.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenExpansion.java index 8fab394..9824998 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenExpansion.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenExpansion.java @@ -6,16 +6,17 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Indicates that the given class contains an expansion for a certain type. - * The expansions themselves are given through annotated static methods. + * Indicates that the given class contains an expansion for a certain type. The + * expansions themselves are given through annotated static methods. * * @author Stan Hebben */ @Retention(RetentionPolicy.RUNTIME) -@Target({ElementType.TYPE, ElementType.METHOD}) +@Target({ ElementType.TYPE, ElementType.METHOD }) public @interface ZenExpansion { /** - * Contains the type of the annotated class. May be any kind of ZenScript type. + * Contains the type of the annotated class. May be any kind of ZenScript + * type. * * Examples: *
      diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMemberGetter.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMemberGetter.java index 72f6073..5a1a77a 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMemberGetter.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMemberGetter.java @@ -6,9 +6,9 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Indicates a member getter. A member getter is a special kind of operator which - * is a fallback if a member could not be resolved. Can be used to make contents - * available as if they were members. + * Indicates a member getter. A member getter is a special kind of operator + * which is a fallback if a member could not be resolved. Can be used to make + * contents available as if they were members. * * If this method is a native class, it accepts a single string parameter with * the member name. If this method is an expansion method, it accepts the source @@ -19,5 +19,5 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ZenMemberGetter { - + } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMemberSetter.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMemberSetter.java index ceb2f1b..07c491c 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMemberSetter.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMemberSetter.java @@ -9,8 +9,8 @@ import java.lang.annotation.Target; * Used to indicate a member setter. Companion to member getters, but allow * setting contents of this object as if they were members. * - * If this method is a native class, it accepts a string parameter with - * the member name and a second parameter with the value. If this method is an + * If this method is a native class, it accepts a string parameter with the + * member name and a second parameter with the value. If this method is an * expansion method, it accepts the source value, the member name and the value * to be assigned. * @@ -19,5 +19,5 @@ import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface ZenMemberSetter { - + } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMethod.java index 1d1425f..5e2c0de 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMethod.java @@ -8,9 +8,9 @@ import java.lang.annotation.Target; /** * Used to indicate an exposed method. * - * If this method is part of a native class, it will simply accept the parameters - * as provided. If it is part of an expansion method, it will also accept the - * instance value as first parameter. + * If this method is part of a native class, it will simply accept the + * parameters as provided. If it is part of an expansion method, it will also + * accept the instance value as first parameter. * * @author Stan Hebben */ diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMethodStatic.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMethodStatic.java index 7c1b0fa..2737847 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMethodStatic.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenMethodStatic.java @@ -12,8 +12,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Used to indicate static methods for expansions. For native classes, use ZenMethod - * instead on a static method. + * Used to indicate static methods for expansions. For native classes, use + * ZenMethod instead on a static method. * * @author Stan Hebben */ diff --git a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenSetter.java b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenSetter.java index 875e2f4..ef70314 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenSetter.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/annotations/ZenSetter.java @@ -6,8 +6,8 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** - * Used to annotate setters. Will make the given method accessible as setter, that is, - * it's called when value.name is being assinged a value. + * Used to annotate setters. Will make the given method accessible as setter, + * that is, it's called when value.name is being assinged a value. * * For a native class, a single argument with the assinged value is provided. * For an expansion, the target object and assigned value are provided. diff --git a/ZenScript/src/main/java/stanhebben/zenscript/compiler/ClassNameGenerator.java b/ZenScript/src/main/java/stanhebben/zenscript/compiler/ClassNameGenerator.java index 7252b00..7eb4609 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/compiler/ClassNameGenerator.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/compiler/ClassNameGenerator.java @@ -12,15 +12,15 @@ package stanhebben.zenscript.compiler; */ public class ClassNameGenerator { private int counter = 0; - + public ClassNameGenerator() { - + } - + public String generate() { return "ZenClass" + counter++; } - + public String generate(String prefix) { return prefix + (counter++); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentClass.java b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentClass.java index 3ac0b7c..25f94d0 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentClass.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentClass.java @@ -26,7 +26,7 @@ public class EnvironmentClass implements IEnvironmentClass { private final ClassVisitor output; private final IEnvironmentGlobal global; private final Map local; - + public EnvironmentClass(ClassVisitor output, IEnvironmentGlobal global) { this.output = output; this.global = global; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentGlobal.java b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentGlobal.java index ba7f4ea..3928542 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentGlobal.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentGlobal.java @@ -29,7 +29,7 @@ public class EnvironmentGlobal implements IEnvironmentGlobal { private final Map local; private final ClassNameGenerator nameGen; private final TypeRegistry types; - + public EnvironmentGlobal( IZenCompileEnvironment environment, Map classes, @@ -41,31 +41,31 @@ public class EnvironmentGlobal implements IEnvironmentGlobal { this.types = environment.getTypeRegistry(); this.local = new HashMap(); } - + public IZenCompileEnvironment getCompileEnvironment() { return environment; } - + @Override public ZenType getType(Type type) { return types.getType(type); } - + @Override public boolean containsClass(String name) { return classes.containsKey(name); } - + @Override public void putClass(String name, byte[] data) { classes.put(name, data); } - + @Override public String makeClassName() { return nameGen.generate(); } - + @Override public TypeExpansion getExpansion(String type) { return environment.getExpansion(type); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentMethod.java index 3834bc0..cd4f7ff 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentMethod.java @@ -29,24 +29,24 @@ public class EnvironmentMethod implements IEnvironmentMethod { private final HashMap locals; private final IEnvironmentClass environment; private final Map local; - + public EnvironmentMethod(MethodOutput output, IEnvironmentClass environment) { this.output = output; this.locals = new HashMap(); this.environment = environment; this.local = new HashMap(); } - + @Override public MethodOutput getOutput() { return output; } - + @Override public ClassVisitor getClassOutput() { return environment.getClassOutput(); } - + @Override public int getLocal(SymbolLocal variable) { if (!locals.containsKey(variable)) { @@ -54,7 +54,7 @@ public class EnvironmentMethod implements IEnvironmentMethod { } return locals.get(variable); } - + @Override public ZenType getType(Type type) { return environment.getType(type); @@ -79,7 +79,7 @@ public class EnvironmentMethod implements IEnvironmentMethod { public TypeExpansion getExpansion(String name) { return environment.getExpansion(name); } - + @Override public String makeClassName() { return environment.makeClassName(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentScope.java b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentScope.java index c6c8853..ac06eba 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentScope.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentScope.java @@ -28,7 +28,7 @@ public class EnvironmentScope implements IEnvironmentMethod { private final IEnvironmentMethod outer; private final Map local; private final Map locals; - + public EnvironmentScope(IEnvironmentMethod outer) { this.outer = outer; this.local = new HashMap(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentScript.java b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentScript.java index 6ecb5ff..3adcab5 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentScript.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/compiler/EnvironmentScript.java @@ -24,7 +24,7 @@ import stanhebben.zenscript.util.ZenPosition; public class EnvironmentScript implements IEnvironmentGlobal { private final IEnvironmentGlobal parent; private final Map imports; - + public EnvironmentScript(IEnvironmentGlobal parent) { this.parent = parent; imports = new HashMap(); @@ -59,7 +59,8 @@ public class EnvironmentScript implements IEnvironmentGlobal { public IPartialExpression getValue(String name, ZenPosition position) { if (imports.containsKey(name)) { IZenSymbol imprt = imports.get(name); - if (imprt == null) throw new RuntimeException("How could this happen?"); + if (imprt == null) + throw new RuntimeException("How could this happen?"); return imprt.instance(position); } else { return parent.getValue(name, position); @@ -68,8 +69,9 @@ public class EnvironmentScript implements IEnvironmentGlobal { @Override public void putValue(String name, IZenSymbol value, ZenPosition position) { - if (value == null) throw new IllegalArgumentException("value cannot be null"); - + if (value == null) + throw new IllegalArgumentException("value cannot be null"); + if (imports.containsKey(name)) { error(position, "Value already defined in this scope: " + name); } else { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/compiler/IEnvironmentGlobal.java b/ZenScript/src/main/java/stanhebben/zenscript/compiler/IEnvironmentGlobal.java index e64fc5e..d03e1ee 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/compiler/IEnvironmentGlobal.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/compiler/IEnvironmentGlobal.java @@ -20,20 +20,20 @@ import stanhebben.zenscript.util.ZenPosition; */ public interface IEnvironmentGlobal extends ITypeRegistry, IZenErrorLogger { public IZenCompileEnvironment getEnvironment(); - + public TypeExpansion getExpansion(String name); - + public String makeClassName(); - + public boolean containsClass(String name); - + public Set getClassNames(); - + public byte[] getClass(String name); - + public void putClass(String name, byte[] data); - + public IPartialExpression getValue(String name, ZenPosition position); - + public void putValue(String name, IZenSymbol value, ZenPosition position); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/compiler/IEnvironmentMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/compiler/IEnvironmentMethod.java index 158a4a9..d10ece4 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/compiler/IEnvironmentMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/compiler/IEnvironmentMethod.java @@ -15,6 +15,6 @@ import stanhebben.zenscript.util.MethodOutput; */ public interface IEnvironmentMethod extends IEnvironmentClass { public MethodOutput getOutput(); - + public int getLocal(SymbolLocal variable); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/definitions/Import.java b/ZenScript/src/main/java/stanhebben/zenscript/definitions/Import.java index 75af0e0..66d601e 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/definitions/Import.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/definitions/Import.java @@ -17,21 +17,21 @@ public class Import { private final ZenPosition position; private final List name; private final String rename; - + public Import(ZenPosition position, List name, String rename) { this.position = position; this.name = name; this.rename = rename; } - + public ZenPosition getPosition() { return position; } - + public List getName() { return name; } - + public String getRename() { return rename == null ? name.get(name.size() - 1) : rename; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/definitions/ParsedFunction.java b/ZenScript/src/main/java/stanhebben/zenscript/definitions/ParsedFunction.java index 56ef89c..a34dc64 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/definitions/ParsedFunction.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/definitions/ParsedFunction.java @@ -27,7 +27,8 @@ public class ParsedFunction { parser.next(); Token tName = parser.required(ZenTokener.T_ID, "identifier expected"); - // function (argname [as type], argname [as type], ...) [as type] { ...contents... } + // function (argname [as type], argname [as type], ...) [as type] { + // ...contents... } parser.required(T_BROPEN, "( expected"); List arguments = new ArrayList(); @@ -37,7 +38,7 @@ public class ParsedFunction { if (parser.optional(T_AS) != null) { type = ZenType.read(parser, environment); } - + arguments.add(new ParsedFunctionArgument(argName.getValue(), type)); while (parser.optional(T_COMMA) != null) { @@ -46,20 +47,20 @@ public class ParsedFunction { if (parser.optional(T_AS) != null) { type2 = ZenType.read(parser, environment); } - + arguments.add(new ParsedFunctionArgument(argName2.getValue(), type2)); } - + parser.required(T_BRCLOSE, ") expected"); } - + ZenType type = ZenTypeAny.INSTANCE; if (parser.optional(T_AS) != null) { type = ZenType.read(parser, environment); } - + parser.required(T_AOPEN, "{ expected"); - + Statement[] statements; if (parser.optional(T_ACLOSE) != null) { statements = new Statement[0]; @@ -71,25 +72,25 @@ public class ParsedFunction { } statements = statementsAL.toArray(new Statement[statementsAL.size()]); } - + return new ParsedFunction(tName.getPosition(), tName.getValue(), arguments, type, statements); } - + private final ZenPosition position; private final String name; private final List arguments; private final ZenType returnType; private final Statement[] statements; - + private final String signature; - + private ParsedFunction(ZenPosition position, String name, List arguments, ZenType returnType, Statement[] statements) { this.position = position; this.name = name; this.arguments = arguments; this.returnType = returnType; this.statements = statements; - + StringBuilder sig = new StringBuilder(); sig.append("("); for (ParsedFunctionArgument argument : arguments) { @@ -99,27 +100,27 @@ public class ParsedFunction { sig.append(returnType.getSignature()); signature = sig.toString(); } - + public ZenPosition getPosition() { return position; } - + public String getName() { return name; } - + public String getSignature() { return signature; } - + public ZenType getReturnType() { return returnType; } - + public List getArguments() { return arguments; } - + public ZenType[] getArgumentTypes() { ZenType[] result = new ZenType[arguments.size()]; for (int i = 0; i < arguments.size(); i++) { @@ -127,7 +128,7 @@ public class ParsedFunction { } return result; } - + public Statement[] getStatements() { return statements; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/definitions/ParsedFunctionArgument.java b/ZenScript/src/main/java/stanhebben/zenscript/definitions/ParsedFunctionArgument.java index bdf89de..fd943f1 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/definitions/ParsedFunctionArgument.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/definitions/ParsedFunctionArgument.java @@ -9,16 +9,16 @@ import stanhebben.zenscript.type.ZenType; public class ParsedFunctionArgument { private final String name; private final ZenType type; - + public ParsedFunctionArgument(String name, ZenType type) { this.name = name; this.type = type; } - + public String getName() { return name; } - + public ZenType getType() { return type; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/Expression.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/Expression.java index f76e776..9332fdc 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/Expression.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/Expression.java @@ -11,23 +11,23 @@ import stanhebben.zenscript.type.ZenType; import stanhebben.zenscript.type.casting.ICastingRule; import stanhebben.zenscript.util.ZenPosition; -public abstract class Expression implements IPartialExpression { +public abstract class Expression implements IPartialExpression { public static final Expression parse(ZenTokener parser, IEnvironmentMethod environment, ZenType predictedType) { return ParsedExpression.read(parser, environment) - .compile(environment, predictedType) - .eval(environment); + .compile(environment, predictedType) + .eval(environment); } - + private final ZenPosition position; - + public Expression(ZenPosition position) { this.position = position; } - + public ZenPosition getPosition() { return position; } - + public Expression cast(ZenPosition position, IEnvironmentGlobal environment, ZenType type) { if (getType().equals(type)) { return this; @@ -41,9 +41,9 @@ public abstract class Expression implements IPartialExpression { } } } - + public abstract void compile(boolean result, IEnvironmentMethod environment); - + public void compileIf(Label onElse, IEnvironmentMethod environment) { if (getType() == ZenType.BOOL) { compile(true, environment); @@ -55,42 +55,42 @@ public abstract class Expression implements IPartialExpression { throw new RuntimeException("cannot compile non-pointer non-boolean value to if condition"); } } - + // ######################################### // ### IPartialExpression implementation ### // ######################################### - + @Override public Expression eval(IEnvironmentGlobal environment) { return this; } - + @Override public Expression assign(ZenPosition position, IEnvironmentGlobal environment, Expression other) { environment.error(position, "not a valid lvalue"); return new ExpressionInvalid(position, getType()); } - + @Override public IPartialExpression getMember(ZenPosition position, IEnvironmentGlobal environment, String name) { return getType().getMember(position, environment, this, name); } - + @Override public Expression call(ZenPosition position, IEnvironmentMethod environment, Expression... values) { return getType().call(position, environment, this, values); } - + @Override public ZenType[] predictCallTypes(int numArguments) { return getType().predictCallTypes(numArguments); } - + @Override public IZenSymbol toSymbol() { return null; } - + @Override public ZenType toType(IEnvironmentGlobal environment) { environment.error(position, "not a valid type"); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionAndAnd.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionAndAnd.java index 474f441..0d2ee84 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionAndAnd.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionAndAnd.java @@ -9,10 +9,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionAndAnd extends Expression { private final Expression a; private final Expression b; - + public ExpressionAndAnd(ZenPosition position, Expression a, Expression b) { super(position); - + this.a = a; this.b = b; } @@ -27,9 +27,9 @@ public class ExpressionAndAnd extends Expression { // if not a: return false // if not b: return false // return true - + MethodOutput output = environment.getOutput(); - + Label skip = new Label(); a.compile(true, environment); output.ifEQ(skip); @@ -37,7 +37,7 @@ public class ExpressionAndAnd extends Expression { output.ifEQ(skip); output.iConst1(); output.label(skip); - + if (!result) { output.pop(); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArgument.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArgument.java index 78e8846..4c5f940 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArgument.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArgument.java @@ -17,10 +17,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionArgument extends Expression { private final int id; private final ZenType type; - + public ExpressionArgument(ZenPosition position, int id, ZenType type) { super(position); - + this.id = id; this.type = type; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticBinary.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticBinary.java index 0a779d8..929fd94 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticBinary.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticBinary.java @@ -27,10 +27,10 @@ public class ExpressionArithmeticBinary extends Expression { private final OperatorType operator; private final Expression a; private final Expression b; - + public ExpressionArithmeticBinary(ZenPosition position, OperatorType operator, Expression a, Expression b) { super(position); - + this.operator = operator; this.a = a; this.b = b; @@ -46,10 +46,10 @@ public class ExpressionArithmeticBinary extends Expression { if (result) { a.compile(result, environment); b.compile(result, environment); - + ZenType type = a.getType(); MethodOutput output = environment.getOutput(); - + if (type == ZenType.BOOL) { switch (operator) { case AND: diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticCompare.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticCompare.java index 9c75cea..1381e9c 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticCompare.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticCompare.java @@ -18,10 +18,10 @@ public class ExpressionArithmeticCompare extends Expression { private final Expression a; private final Expression b; private final CompareType type; - + public ExpressionArithmeticCompare(ZenPosition position, CompareType type, Expression a, Expression b) { super(position); - + this.a = a; this.b = b; this.type = type; @@ -36,14 +36,14 @@ public class ExpressionArithmeticCompare extends Expression { public void compile(boolean result, IEnvironmentMethod environment) { a.compile(result, environment); b.compile(result, environment); - + if (result) { MethodOutput output = environment.getOutput(); if (a.getType() == ZenType.BOOL) { if (type == CompareType.EQ) { Label onThen = new Label(); Label onEnd = new Label(); - + output.ifICmpEQ(onThen); output.iConst0(); output.goTo(onEnd); @@ -53,7 +53,7 @@ public class ExpressionArithmeticCompare extends Expression { } else if (type == CompareType.NE) { Label onThen = new Label(); Label onEnd = new Label(); - + output.ifICmpNE(onThen); output.iConst0(); output.goTo(onEnd); @@ -66,7 +66,7 @@ public class ExpressionArithmeticCompare extends Expression { } else { Label onThen = new Label(); Label onEnd = new Label(); - + if (a.getType() == ZenTypeLong.INSTANCE) { output.lCmp(); } else if (a.getType() == ZenTypeFloat.INSTANCE) { @@ -80,19 +80,31 @@ public class ExpressionArithmeticCompare extends Expression { } else { throw new RuntimeException("Unsupported type for arithmetic compare"); } - + switch (type) { - case EQ: output.ifICmpEQ(onThen); break; - case NE: output.ifICmpNE(onThen); break; - case LE: output.ifICmpLE(onThen); break; - case GE: output.ifICmpGE(onThen); break; - case LT: output.ifICmpLT(onThen); break; - case GT: output.ifICmpGT(onThen); break; + case EQ: + output.ifICmpEQ(onThen); + break; + case NE: + output.ifICmpNE(onThen); + break; + case LE: + output.ifICmpLE(onThen); + break; + case GE: + output.ifICmpGE(onThen); + break; + case LT: + output.ifICmpLT(onThen); + break; + case GT: + output.ifICmpGT(onThen); + break; default: environment.error(getPosition(), "this kind of comparison is not supported on int values"); return; } - + output.iConst0(); output.goTo(onEnd); output.label(onThen); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticUnary.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticUnary.java index eba3ea7..0f7098d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticUnary.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArithmeticUnary.java @@ -16,10 +16,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionArithmeticUnary extends Expression { private final Expression base; private final OperatorType operator; - + public ExpressionArithmeticUnary(ZenPosition position, OperatorType operator, Expression base) { super(position); - + this.base = base; this.operator = operator; } @@ -32,7 +32,7 @@ public class ExpressionArithmeticUnary extends Expression { @Override public void compile(boolean result, IEnvironmentMethod environment) { base.compile(result, environment); - + MethodOutput output = environment.getOutput(); if (result) { ZenType type = base.getType(); @@ -69,7 +69,7 @@ public class ExpressionArithmeticUnary extends Expression { } } } - + environment.error(getPosition(), "Invalid operation"); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArray.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArray.java index a51f0ca..d1f4c31 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArray.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArray.java @@ -13,10 +13,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionArray extends Expression { private final Expression[] contents; private final ZenTypeArrayBasic type; - + public ExpressionArray(ZenPosition position, ZenTypeArrayBasic type, Expression... contents) { super(position); - + this.contents = contents; this.type = type; } @@ -26,14 +26,14 @@ public class ExpressionArray extends Expression { if (this.type.equals(type)) { return this; } - + if (type instanceof ZenTypeArrayBasic) { ZenTypeArrayBasic arrayType = (ZenTypeArrayBasic) type; Expression[] newContents = new Expression[contents.length]; for (int i = 0; i < contents.length; i++) { newContents[i] = contents[i].cast(position, environment, arrayType.getBaseType()); } - + return new ExpressionArray(getPosition(), arrayType, newContents); } else { ICastingRule castingRule = this.type.getCastingRule(type, environment); @@ -55,11 +55,11 @@ public class ExpressionArray extends Expression { public void compile(boolean result, IEnvironmentMethod environment) { ZenType baseType = type.getBaseType(); Type asmBaseType = type.getBaseType().toASMType(); - + MethodOutput output = environment.getOutput(); output.constant(contents.length); output.newArray(asmBaseType); - + for (int i = 0; i < contents.length; i++) { output.dup(); output.constant(i); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArrayGet.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArrayGet.java index 60f9fd7..694928f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArrayGet.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArrayGet.java @@ -19,10 +19,10 @@ public class ExpressionArrayGet extends Expression { private final Expression array; private final Expression index; private final ZenType baseType; - + public ExpressionArrayGet(ZenPosition position, Expression array, Expression index) { super(position); - + this.array = array; this.index = index; this.baseType = ((ZenTypeArray) array.getType()).getBaseType(); @@ -37,7 +37,7 @@ public class ExpressionArrayGet extends Expression { public void compile(boolean result, IEnvironmentMethod environment) { array.compile(result, environment); index.compile(result, environment); - + if (result) { environment.getOutput().arrayLoad(baseType.toASMType()); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArrayLength.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArrayLength.java index e77c8d3..7cbb0a0 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArrayLength.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArrayLength.java @@ -17,10 +17,10 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ExpressionArrayLength extends Expression { private final Expression value; - + public ExpressionArrayLength(ZenPosition position, Expression value) { super(position); - + this.value = value; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArraySet.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArraySet.java index c50f816..f152da4 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArraySet.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionArraySet.java @@ -18,15 +18,15 @@ public class ExpressionArraySet extends Expression { private final Expression array; private final Expression index; private final Expression value; - + public ExpressionArraySet(ZenPosition position, Expression array, Expression index, Expression value) { super(position); - + this.array = array; this.index = index; this.value = value; } - + @Override public ZenType getType() { return ZenType.VOID; @@ -37,7 +37,7 @@ public class ExpressionArraySet extends Expression { array.compile(result, environment); index.compile(result, environment); value.compile(result, environment); - + if (result) { environment.getOutput().arrayStore(value.getType().toASMType()); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionAs.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionAs.java index 7bb989b..3b2477f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionAs.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionAs.java @@ -9,28 +9,24 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionAs extends Expression { private final Expression value; private final ICastingRule castingRule; - + public ExpressionAs(ZenPosition position, Expression value, ICastingRule castingRule) { super(position); - + this.value = value; this.castingRule = castingRule; } - /*@Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, ZenType type) { - if (castingRule.getResultingType().equals(type)) { - return this; - } - - ICastingRule newCastingRule = type.getCastingRule(type, environment); - if (newCastingRule == null) { - environment.error(position, "Cannot cast " + getType() + " to " + type); - return new ExpressionInvalid(position, type); - } else { - return new ExpressionAs(position, this, newCastingRule); - } - }*/ + /* + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, ZenType type) { if + * (castingRule.getResultingType().equals(type)) { return this; } + * + * ICastingRule newCastingRule = type.getCastingRule(type, environment); if + * (newCastingRule == null) { environment.error(position, "Cannot cast " + + * getType() + " to " + type); return new ExpressionInvalid(position, type); + * } else { return new ExpressionAs(position, this, newCastingRule); } } + */ @Override public ZenType getType() { @@ -40,7 +36,7 @@ public class ExpressionAs extends Expression { @Override public void compile(boolean result, IEnvironmentMethod environment) { value.compile(result, environment); - + if (result) { castingRule.compile(environment); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionBool.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionBool.java index 278a32f..57f1e75 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionBool.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionBool.java @@ -18,13 +18,13 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ExpressionBool extends Expression { private final boolean value; - + public ExpressionBool(ZenPosition position, boolean value) { super(position); - + this.value = value; } - + @Override public Expression cast(ZenPosition position, IEnvironmentGlobal environment, ZenType type) { if (type == ZenType.BOOL) { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCallStatic.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCallStatic.java index 84e2b2a..8919b2f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCallStatic.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCallStatic.java @@ -21,14 +21,14 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionCallStatic extends Expression { private final IJavaMethod method; private final Expression[] arguments; - + public ExpressionCallStatic( ZenPosition position, IEnvironmentGlobal environment, IJavaMethod method, Expression... arguments) { super(position); - + this.method = method; this.arguments = JavaMethod.rematch(position, method, environment, arguments); } @@ -40,14 +40,14 @@ public class ExpressionCallStatic extends Expression { @Override public void compile(boolean result, IEnvironmentMethod environment) { - MethodOutput output = environment.getOutput(); - + MethodOutput output = environment.getOutput(); + for (Expression argument : arguments) { argument.compile(true, environment); } - + method.invokeStatic(output); - + if (method.getReturnType() != ZenType.VOID && !result) { output.pop(method.getReturnType().isLarge()); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCallVirtual.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCallVirtual.java index caf818d..515af0a 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCallVirtual.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCallVirtual.java @@ -19,10 +19,10 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ExpressionCallVirtual extends Expression { private final IJavaMethod method; - + private final Expression receiver; private final Expression[] arguments; - + public ExpressionCallVirtual( ZenPosition position, IEnvironmentGlobal environment, @@ -30,9 +30,9 @@ public class ExpressionCallVirtual extends Expression { Expression receiver, Expression... arguments) { super(position); - + this.method = method; - + this.receiver = receiver; this.arguments = JavaMethod.rematch(position, method, environment, arguments); } @@ -45,11 +45,11 @@ public class ExpressionCallVirtual extends Expression { @Override public void compile(boolean result, IEnvironmentMethod environment) { receiver.compile(true, environment); - + for (Expression argument : arguments) { argument.compile(true, environment); } - + method.invokeVirtual(environment.getOutput()); if (method.getReturnType() != ZenType.VOID && !result) { environment.getOutput().pop(method.getReturnType().isLarge()); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCompareGeneric.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCompareGeneric.java index 6ff2972..9db42d2 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCompareGeneric.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionCompareGeneric.java @@ -21,10 +21,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionCompareGeneric extends Expression { private final Expression value; // should return a compareTo value (<=>0) private final CompareType type; - + public ExpressionCompareGeneric(ZenPosition position, Expression value, CompareType type) { super(position); - + this.value = value; this.type = type; } @@ -35,24 +35,37 @@ public class ExpressionCompareGeneric extends Expression { } @Override - public void compile(boolean result, IEnvironmentMethod environment) {; + public void compile(boolean result, IEnvironmentMethod environment) { + ; value.compile(result, environment); if (result) { MethodOutput output = environment.getOutput(); Label lblThen = new Label(); Label lblEnd = new Label(); - + switch (type) { - case LT: output.ifLT(lblThen); break; - case GT: output.ifGT(lblThen); break; - case LE: output.ifLE(lblThen); break; - case GE: output.ifGE(lblThen); break; - case NE: output.ifNE(lblThen); break; - case EQ: output.ifEQ(lblThen); break; + case LT: + output.ifLT(lblThen); + break; + case GT: + output.ifGT(lblThen); + break; + case LE: + output.ifLE(lblThen); + break; + case GE: + output.ifGE(lblThen); + break; + case NE: + output.ifNE(lblThen); + break; + case EQ: + output.ifEQ(lblThen); + break; default: throw new RuntimeException(); } - + output.iConst0(); output.goTo(lblEnd); output.label(lblThen); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionConditional.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionConditional.java index 132e400..1f34788 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionConditional.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionConditional.java @@ -9,10 +9,10 @@ public class ExpressionConditional extends Expression { private final Expression condition; private final Expression onIf; private final Expression onElse; - + public ExpressionConditional(ZenPosition position, Expression condition, Expression onIf, Expression onElse) { super(position); - + this.condition = condition; this.onIf = onIf; this.onElse = onElse; @@ -27,7 +27,7 @@ public class ExpressionConditional extends Expression { public void compile(boolean result, IEnvironmentMethod environment) { Label lblElse = new Label(); Label lblExit = new Label(); - + condition.compileIf(lblElse, environment); onIf.compile(result, environment); environment.getOutput().goTo(lblExit); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionFloat.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionFloat.java index b11fe7f..9720542 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionFloat.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionFloat.java @@ -19,10 +19,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionFloat extends Expression { private final double value; private final ZenType type; - + public ExpressionFloat(ZenPosition position, double value, ZenType type) { super(position); - + this.value = value; this.type = type; } @@ -34,8 +34,9 @@ public class ExpressionFloat extends Expression { @Override public void compile(boolean result, IEnvironmentMethod environment) { - if (!result) return; - + if (!result) + return; + if (type == ZenTypeFloat.INSTANCE) { environment.getOutput().constant((float) value); } else if (type == ZenTypeDouble.INSTANCE) { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionFunction.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionFunction.java index 4da10b4..487282c 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionFunction.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionFunction.java @@ -26,18 +26,18 @@ public class ExpressionFunction extends Expression { private final List arguments; private final ZenType returnType; private final List statements; - + private final ZenTypeFunction functionType; - + public ExpressionFunction(ZenPosition position, List arguments, ZenType returnType, List statements) { super(position); - + System.out.println("Function expression: " + arguments.size() + " arguments"); - + this.arguments = arguments; this.returnType = returnType; this.statements = statements; - + ZenType[] argumentTypes = new ZenType[arguments.size()]; for (int i = 0; i < arguments.size(); i++) { argumentTypes[i] = arguments.get(i).getType(); @@ -70,7 +70,7 @@ public class ExpressionFunction extends Expression { return new ExpressionInvalid(position); } } - + return new ExpressionJavaLambda( position, nativeClass, diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionInt.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionInt.java index f03d1da..e8ad3ff 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionInt.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionInt.java @@ -23,18 +23,19 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionInt extends Expression { private final long value; private final ZenType type; - + public ExpressionInt(ZenPosition position, long value, ZenType type) { super(position); - + this.value = value; this.type = type; } @Override public Expression cast(ZenPosition position, IEnvironmentGlobal environment, ZenType type) { - if (type == this.type) return this; - + if (type == this.type) + return this; + switch (type.getNumberType()) { case ZenType.NUM_BYTE: case ZenType.NUM_SHORT: @@ -45,7 +46,7 @@ public class ExpressionInt extends Expression { case ZenType.NUM_DOUBLE: return new ExpressionFloat(getPosition(), value, type); } - + return super.cast(position, environment, type); } @@ -56,8 +57,9 @@ public class ExpressionInt extends Expression { @Override public void compile(boolean result, IEnvironmentMethod environment) { - if (!result) return; - + if (!result) + return; + MethodOutput output = environment.getOutput(); if (type == ZenTypeByte.INSTANCE) { output.biPush((byte) value); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionIntegerRange.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionIntegerRange.java index 7fc03c9..ce87b47 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionIntegerRange.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionIntegerRange.java @@ -18,7 +18,7 @@ public class ExpressionIntegerRange extends Expression { public ExpressionIntegerRange(ZenPosition position, Expression from, Expression to) { super(position); - + this.from = from; this.to = to; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionInvalid.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionInvalid.java index 9d25606..ab0a6d6 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionInvalid.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionInvalid.java @@ -19,22 +19,22 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ExpressionInvalid extends Expression { private final ZenType type; - + public ExpressionInvalid(ZenPosition position) { super(position); - + type = ZenTypeAny.INSTANCE; } - + public ExpressionInvalid(ZenPosition position, ZenType type) { super(position); - + this.type = type; - + // XXX: remove before release - //throw new RuntimeException("Constructing invalid expression"); + // throw new RuntimeException("Constructing invalid expression"); } - + @Override public Expression getMember(ZenPosition position, IEnvironmentGlobal errors, String name) { return new ExpressionInvalid(position); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaLambda.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaLambda.java index 48d03a1..2b23f87 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaLambda.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaLambda.java @@ -31,9 +31,9 @@ public class ExpressionJavaLambda extends Expression { private final Class interfaceClass; private final List arguments; private final List statements; - + private final ZenType type; - + public ExpressionJavaLambda( ZenPosition position, Class interfaceClass, @@ -41,11 +41,11 @@ public class ExpressionJavaLambda extends Expression { List statements, ZenType type) { super(position); - + this.interfaceClass = interfaceClass; this.arguments = arguments; this.statements = statements; - + this.type = type; } @@ -56,43 +56,44 @@ public class ExpressionJavaLambda extends Expression { @Override public void compile(boolean result, IEnvironmentMethod environment) { - if (!result) return; - + if (!result) + return; + Method method = interfaceClass.getMethods()[0]; - + // generate class String clsName = environment.makeClassName(); - + ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_FRAMES); cw.visit(Opcodes.V1_6, Opcodes.ACC_PUBLIC, clsName, null, "java/lang/Object", new String[] { internal(interfaceClass) }); - + MethodOutput constructor = new MethodOutput(cw, Opcodes.ACC_PUBLIC, "", "()V", null, null); constructor.start(); constructor.loadObject(0); constructor.invokeSpecial("java/lang/Object", "", "()V"); constructor.ret(); constructor.end(); - + MethodOutput output = new MethodOutput(cw, Opcodes.ACC_PUBLIC, method.getName(), descriptor(method), null, null); - + IEnvironmentClass environmentClass = new EnvironmentClass(cw, environment); IEnvironmentMethod environmentMethod = new EnvironmentMethod(output, environmentClass); - + for (int i = 0; i < arguments.size(); i++) { environmentMethod.putValue( arguments.get(i).getName(), new SymbolArgument(i + 1, environment.getType(method.getGenericParameterTypes()[i])), getPosition()); } - + output.start(); for (Statement statement : statements) { statement.compile(environmentMethod); } output.end(); - + environment.putClass(clsName, cw.toByteArray()); - + // make class instance environment.getOutput().newObject(clsName); environment.getOutput().dup(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaMethodCurled.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaMethodCurled.java index cb05ca4..c53b5ca 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaMethodCurled.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaMethodCurled.java @@ -24,22 +24,22 @@ public class ExpressionJavaMethodCurled extends Expression { private final JavaMethod method; private final ZenType type; private final Expression receiver; - + public ExpressionJavaMethodCurled( ZenPosition position, JavaMethod method, IEnvironmentGlobal environment, Expression receiver) { super(position); - + this.method = method; this.receiver = receiver; - + List arguments = new ArrayList(); for (int i = 0; i < method.getMethod().getParameterTypes().length; i++) { arguments.add(new ParsedFunctionArgument("p" + i, environment.getType(method.getMethod().getGenericParameterTypes()[i]))); } - + this.type = new ZenTypeFunction(environment.getType(method.getMethod().getGenericReturnType()), arguments); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaMethodStatic.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaMethodStatic.java index 5e317d5..2f16fa8 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaMethodStatic.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionJavaMethodStatic.java @@ -23,17 +23,17 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionJavaMethodStatic extends Expression { private final JavaMethod method; private final ZenType type; - + public ExpressionJavaMethodStatic(ZenPosition position, JavaMethod method, IEnvironmentGlobal environment) { super(position); - + this.method = method; - + List arguments = new ArrayList(); for (int i = 0; i < method.getParameterTypes().length; i++) { arguments.add(new ParsedFunctionArgument("p" + i, environment.getType(method.getMethod().getGenericParameterTypes()[i]))); } - + this.type = new ZenTypeFunction(environment.getType(method.getMethod().getGenericReturnType()), arguments); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionLocalGet.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionLocalGet.java index 6f9bdd9..f95e88b 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionLocalGet.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionLocalGet.java @@ -17,13 +17,13 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ExpressionLocalGet extends Expression { private final SymbolLocal variable; - + public ExpressionLocalGet(ZenPosition position, SymbolLocal variable) { super(position); - + this.variable = variable; } - + @Override public ZenType getType() { return variable.getType(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionLocalSet.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionLocalSet.java index 3be4259..7cd482f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionLocalSet.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionLocalSet.java @@ -18,14 +18,14 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionLocalSet extends Expression { private final SymbolLocal variable; private final Expression value; - + public ExpressionLocalSet(ZenPosition position, SymbolLocal variable, Expression value) { super(position); - + this.variable = variable; this.value = value; } - + @Override public ZenType getType() { return variable.getType(); @@ -34,7 +34,7 @@ public class ExpressionLocalSet extends Expression { @Override public void compile(boolean result, IEnvironmentMethod environment) { int local = environment.getLocal(variable); - + value.compile(true, environment); if (result) { environment.getOutput().dup(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMap.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMap.java index b2abbd2..08e966c 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMap.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMap.java @@ -16,13 +16,13 @@ public class ExpressionMap extends Expression { private final Expression[] keys; private final Expression[] values; private final ZenTypeAssociative type; - + public ExpressionMap(ZenPosition position, Expression[] keys, Expression[] values, ZenTypeAssociative type) { super(position); - + this.keys = keys; this.values = values; - + this.type = type; } @@ -36,12 +36,12 @@ public class ExpressionMap extends Expression { if (result) { ZenType keyType = type.getKeyType(); ZenType valueType = type.getValueType(); - + MethodOutput output = environment.getOutput(); output.newObject(HashMap.class); output.dup(); output.invokeSpecial(internal(HashMap.class), "", "()V"); - + for (int i = 0; i < keys.length; i++) { output.dup(); keys[i].cast(getPosition(), environment, keyType).compile(true, environment); @@ -58,23 +58,23 @@ public class ExpressionMap extends Expression { } } } - + @Override public Expression cast(ZenPosition position, IEnvironmentGlobal environment, ZenType type) { if (this.type.equals(type)) { return this; } - + if (type instanceof ZenTypeAssociative) { ZenTypeAssociative associativeType = (ZenTypeAssociative) type; Expression[] newKeys = new Expression[keys.length]; Expression[] newValues = new Expression[values.length]; - + for (int i = 0; i < keys.length; i++) { newKeys[i] = keys[i].cast(position, environment, associativeType.getKeyType()); newValues[i] = values[i].cast(position, environment, associativeType.getValueType()); } - + return new ExpressionMap(getPosition(), newKeys, newValues, associativeType); } else { ICastingRule castingRule = this.type.getCastingRule(type, environment); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapContains.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapContains.java index 97ce1f7..6f4afda 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapContains.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapContains.java @@ -20,10 +20,10 @@ import static stanhebben.zenscript.util.ZenTypeUtil.internal; public class ExpressionMapContains extends Expression { private final Expression map; private final Expression key; - + public ExpressionMapContains(ZenPosition position, Expression map, Expression key) { super(position); - + this.map = map; this.key = key; } @@ -38,7 +38,7 @@ public class ExpressionMapContains extends Expression { if (result) { map.compile(result, environment); key.compile(result, environment); - + environment.getOutput().invokeInterface(internal(Map.class), "containsKey", "()Ljava/lang/Object;"); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapIndexGet.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapIndexGet.java index 757c7f1..d2f463d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapIndexGet.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapIndexGet.java @@ -20,15 +20,15 @@ import static stanhebben.zenscript.util.ZenTypeUtil.internal; public class ExpressionMapIndexGet extends Expression { private final Expression map; private final Expression index; - + private final ZenType type; - + public ExpressionMapIndexGet(ZenPosition position, Expression map, Expression index) { super(position); - + this.map = map; this.index = index; - + type = ((ZenTypeAssociative) map.getType()).getValueType(); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapIndexSet.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapIndexSet.java index 3818245..e3b86dc 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapIndexSet.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapIndexSet.java @@ -21,16 +21,16 @@ public class ExpressionMapIndexSet extends Expression { private final Expression map; private final Expression index; private final Expression value; - + private final ZenType type; - + public ExpressionMapIndexSet(ZenPosition position, Expression map, Expression index, Expression value) { super(position); - + this.map = map; this.index = index; this.value = value; - + type = ZenTypeVoid.INSTANCE; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapSize.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapSize.java index 72d1b4d..49dbefd 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapSize.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionMapSize.java @@ -19,10 +19,10 @@ import static stanhebben.zenscript.util.ZenTypeUtil.internal; */ public class ExpressionMapSize extends Expression { private final Expression map; - + public ExpressionMapSize(ZenPosition position, Expression map) { super(position); - + this.map = map; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionNull.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionNull.java index f6d72b1..7b41c26 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionNull.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionNull.java @@ -21,7 +21,7 @@ public class ExpressionNull extends Expression { public ExpressionNull(ZenPosition position) { super(position); } - + @Override public Expression cast(ZenPosition position, IEnvironmentGlobal environment, ZenType type) { if (type.isPointer()) { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionOrOr.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionOrOr.java index 4af7522..0d94801 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionOrOr.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionOrOr.java @@ -7,10 +7,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionOrOr extends Expression { private final Expression a; private final Expression b; - + public ExpressionOrOr(ZenPosition position, Expression a, Expression b) { super(position); - + this.a = a; this.b = b; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionString.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionString.java index a5ef50e..1253d3f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionString.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionString.java @@ -17,10 +17,10 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ExpressionString extends Expression { private final String value; - + public ExpressionString(ZenPosition position, String value) { super(position); - + this.value = value; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringConcat.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringConcat.java index 5bc92e9..97c992b 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringConcat.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringConcat.java @@ -19,13 +19,13 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ExpressionStringConcat extends Expression { private final List values; - + public ExpressionStringConcat(ZenPosition position, List values) { super(position); - + this.values = values; } - + public void add(Expression value) { values.add(value); } @@ -39,18 +39,18 @@ public class ExpressionStringConcat extends Expression { public void compile(boolean result, IEnvironmentMethod environment) { if (result) { MethodOutput output = environment.getOutput(); - + // Step 1: construct StringBuilder output.newObject(StringBuilder.class); output.dup(); output.construct(StringBuilder.class); - + // Step 2: concatenate Strings for (Expression value : values) { value.compile(true, environment); output.invoke(StringBuilder.class, "append", StringBuilder.class, String.class); } - + // Step 3: return String output.invoke(StringBuilder.class, "toString", String.class); } else { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringContains.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringContains.java index ad1c1b9..3ced428 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringContains.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringContains.java @@ -17,14 +17,14 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionStringContains extends Expression { private final Expression haystack; private final Expression needle; - + public ExpressionStringContains(ZenPosition position, Expression haystack, Expression needle) { super(position); - + this.haystack = haystack; this.needle = needle; } - + @Override public ZenType getType() { return ZenType.STRING; @@ -34,7 +34,7 @@ public class ExpressionStringContains extends Expression { public void compile(boolean result, IEnvironmentMethod environment) { haystack.compile(result, environment); needle.compile(result, environment); - + if (result) { environment.getOutput().invokeVirtual(String.class, "contains", CharSequence.class); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringIndex.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringIndex.java index c7dd845..ccfb2b9 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringIndex.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/ExpressionStringIndex.java @@ -17,14 +17,14 @@ import stanhebben.zenscript.util.ZenPosition; public class ExpressionStringIndex extends Expression { private final Expression source; private final Expression index; - + public ExpressionStringIndex(ZenPosition position, Expression source, Expression index) { super(position); - + this.source = source; this.index = index; } - + @Override public ZenType getType() { return ZenType.STRING; @@ -34,7 +34,7 @@ public class ExpressionStringIndex extends Expression { public void compile(boolean result, IEnvironmentMethod environment) { source.compile(result, environment); index.compile(result, environment); - + if (result) { environment.getOutput().dup(); environment.getOutput().iConst1(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/ExpressionJavaStaticField.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/ExpressionJavaStaticField.java index 73d7a04..0a57b63 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/ExpressionJavaStaticField.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/ExpressionJavaStaticField.java @@ -21,10 +21,10 @@ public class ExpressionJavaStaticField extends Expression { private final Class cls; private final Field field; private final ITypeRegistry types; - + public ExpressionJavaStaticField(ZenPosition position, Class cls, Field field, ITypeRegistry types) { super(position); - + this.cls = cls; this.field = field; this.types = types; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/IPartialExpression.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/IPartialExpression.java index b258cba..185313a 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/IPartialExpression.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/IPartialExpression.java @@ -19,18 +19,18 @@ import stanhebben.zenscript.util.ZenPosition; */ public interface IPartialExpression { public Expression eval(IEnvironmentGlobal environment); - + public Expression assign(ZenPosition position, IEnvironmentGlobal environment, Expression other); - + public IPartialExpression getMember(ZenPosition position, IEnvironmentGlobal environment, String name); - + public Expression call(ZenPosition position, IEnvironmentMethod environment, Expression... values); - + public ZenType[] predictCallTypes(int numArguments); - + public IZenSymbol toSymbol(); - + public ZenType getType(); - + public ZenType toType(IEnvironmentGlobal environment); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialJavaClass.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialJavaClass.java index 468a727..1417ece 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialJavaClass.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialJavaClass.java @@ -23,7 +23,7 @@ import stanhebben.zenscript.util.ZenPosition; public class PartialJavaClass implements IPartialExpression { private final ZenPosition position; private final Type cls; - + public PartialJavaClass(ZenPosition position, Type cls) { this.position = position; this.cls = cls; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialLocal.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialLocal.java index 65d2af0..91c56af 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialLocal.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialLocal.java @@ -24,7 +24,7 @@ import stanhebben.zenscript.util.ZenPosition; public class PartialLocal implements IPartialExpression { private final ZenPosition position; private final SymbolLocal variable; - + public PartialLocal(ZenPosition position, SymbolLocal variable) { this.position = position; this.variable = variable; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialPackage.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialPackage.java index 93d7141..e7d3a8f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialPackage.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialPackage.java @@ -22,7 +22,7 @@ import stanhebben.zenscript.util.ZenPosition; public class PartialPackage implements IPartialExpression { private final ZenPosition position; private final SymbolPackage contents; - + public PartialPackage(ZenPosition position, SymbolPackage contents) { this.position = position; this.contents = contents; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticGenerated.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticGenerated.java index 05fb62f..1609d7e 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticGenerated.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticGenerated.java @@ -29,7 +29,7 @@ public class PartialStaticGenerated implements IPartialExpression { private final String signature; private final ZenType[] argumentTypes; private final ZenType returnType; - + public PartialStaticGenerated(ZenPosition position, String owner, String method, String signature, ZenType[] argumentTypes, ZenType returnType) { this.position = position; this.owner = owner; @@ -38,7 +38,7 @@ public class PartialStaticGenerated implements IPartialExpression { this.argumentTypes = argumentTypes; this.returnType = returnType; } - + @Override public Expression eval(IEnvironmentGlobal environment) { environment.error(position, "cannot use a function as value"); @@ -63,12 +63,12 @@ public class PartialStaticGenerated implements IPartialExpression { environment.error(position, "invalid number of arguments"); return new ExpressionInvalid(position); } - + Expression[] arguments = new Expression[argumentTypes.length]; for (int i = 0; i < arguments.length; i++) { arguments[i] = values[i].cast(position, environment, argumentTypes[i]); } - + return new ExpressionCallStatic(position, environment, JavaMethod.getStatic(owner, method, returnType, argumentTypes), arguments); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticGetter.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticGetter.java index d517e0f..d3b6202 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticGetter.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticGetter.java @@ -24,7 +24,7 @@ import stanhebben.zenscript.util.ZenPosition; public class PartialStaticGetter implements IPartialExpression { private final ZenPosition position; private final IJavaMethod method; - + public PartialStaticGetter(ZenPosition position, IJavaMethod method) { this.position = position; this.method = method; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticMethod.java index 9ca831a..6813b31 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialStaticMethod.java @@ -25,7 +25,7 @@ import stanhebben.zenscript.util.ZenPosition; public class PartialStaticMethod implements IPartialExpression { private final ZenPosition position; private final IJavaMethod method; - + public PartialStaticMethod(ZenPosition position, IJavaMethod method) { this.position = position; this.method = method; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialType.java b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialType.java index 9ee7061..d1ff7f9 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialType.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/expression/partial/PartialType.java @@ -22,7 +22,7 @@ import stanhebben.zenscript.util.ZenPosition; public class PartialType implements IPartialExpression { private final ZenPosition position; private final ZenType type; - + public PartialType(ZenPosition position, ZenType type) { this.position = position; this.type = type; @@ -55,7 +55,7 @@ public class PartialType implements IPartialExpression { public IZenSymbol toSymbol() { return new SymbolType(type); } - + @Override public ZenType getType() { return null; // not an expression diff --git a/ZenScript/src/main/java/stanhebben/zenscript/package-info.java b/ZenScript/src/main/java/stanhebben/zenscript/package-info.java index 3536640..4101a28 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/package-info.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/package-info.java @@ -38,3 +38,4 @@ */ package stanhebben.zenscript; + diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/ArrayListI.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/ArrayListI.java index b200ee4..e203f7b 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/ArrayListI.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/ArrayListI.java @@ -11,62 +11,64 @@ package stanhebben.zenscript.parser; * @author Stan Hebben */ public class ArrayListI { - private int[] data; - private int size; + private int[] data; + private int size; - /** - * Creates a new, empty ArrayList of integers. - */ - public ArrayListI() { - data = new int[8]; - } + /** + * Creates a new, empty ArrayList of integers. + */ + public ArrayListI() { + data = new int[8]; + } - /** - * Adds a value. - * - * @param value integer value - */ - public void add(int value) { - if (size == data.length) expand(); - data[size++] = value; - } + /** + * Adds a value. + * + * @param value integer value + */ + public void add(int value) { + if (size == data.length) + expand(); + data[size++] = value; + } - /** - * Gets the value at the specified position. - * - * @param index position - * @return value at this position - */ - public int get(int index) { - if (index >= size) throw new ArrayIndexOutOfBoundsException(); - return data[index]; - } + /** + * Gets the value at the specified position. + * + * @param index position + * @return value at this position + */ + public int get(int index) { + if (index >= size) + throw new ArrayIndexOutOfBoundsException(); + return data[index]; + } - /** - * Gets the size of this ArrayList. - * - * @return size - */ - public int size() { - return size; - } + /** + * Gets the size of this ArrayList. + * + * @return size + */ + public int size() { + return size; + } - //////////////////// - // Private methods - //////////////////// + // ////////////////// + // Private methods + // ////////////////// - /** - * Doubles the size of this array. - */ - private void expand() { - int[] newdata = new int[data.length * 2]; - System.arraycopy(data, 0, newdata, 0, size); - data = newdata; - } + /** + * Doubles the size of this array. + */ + private void expand() { + int[] newdata = new int[data.length * 2]; + System.arraycopy(data, 0, newdata, 0, size); + data = newdata; + } - public int[] toArray() { - int[] result = new int[size]; - System.arraycopy(data, 0, result, 0, size); - return result; - } + public int[] toArray() { + int[] result = new int[size]; + System.arraycopy(data, 0, result, 0, size); + return result; + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/CharStream.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/CharStream.java index 1e230dd..3cf8abc 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/CharStream.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/CharStream.java @@ -13,107 +13,111 @@ package stanhebben.zenscript.parser; * @author Stan Hebben */ public class CharStream { - private char[] data; - private int index; + private char[] data; + private int index; - /** - * Constructs a character stream from a data string. - * - * @param data data string - */ - public CharStream(String data) { - this.data = data.toCharArray(); - index = 0; - } + /** + * Constructs a character stream from a data string. + * + * @param data data string + */ + public CharStream(String data) { + this.data = data.toCharArray(); + index = 0; + } - /** - * Checks if the next character in the stream equals the specified character. - * - * @param ch checked character - * @return true if the next character equals the specified character - */ - public boolean peek(char ch) { - if (index == data.length) return false; - return data[index] == ch; - } + /** + * Checks if the next character in the stream equals the specified + * character. + * + * @param ch checked character + * @return true if the next character equals the specified character + */ + public boolean peek(char ch) { + if (index == data.length) + return false; + return data[index] == ch; + } - /** - * Processes an optional character. If the next character does not equal - * the specified character, nothing will happen. - * - * @param ch checked character - * @return true if the next character equals the specified character - */ - public boolean optional(char ch) { - if (index == data.length) return false; - if (data[index] == ch) { - index++; - return true; - } else { - return false; - } - } + /** + * Processes an optional character. If the next character does not equal the + * specified character, nothing will happen. + * + * @param ch checked character + * @return true if the next character equals the specified character + */ + public boolean optional(char ch) { + if (index == data.length) + return false; + if (data[index] == ch) { + index++; + return true; + } else { + return false; + } + } - /** - * Processes an optional range of characters. If the next character is not - * within the specified bounds, nothing will happen. - * - * @param from lower character value bound, inclusive - * @param to upper character value bound, inclusive - * @return the processed character - */ - public char optional(char from, char to) { - if (index == data.length) return 0; - if (data[index] >= from && data[index] <= to) { - return data[index++]; - } else { - return 0; - } - } + /** + * Processes an optional range of characters. If the next character is not + * within the specified bounds, nothing will happen. + * + * @param from lower character value bound, inclusive + * @param to upper character value bound, inclusive + * @return the processed character + */ + public char optional(char from, char to) { + if (index == data.length) + return 0; + if (data[index] >= from && data[index] <= to) { + return data[index++]; + } else { + return 0; + } + } - /** - * Processes a required character. If the next character does not equal the - * specified character, an IllegalArgumentException is thrown. - * - * @param ch required character - */ - public void required(char ch) { - if (data[index] != ch) { - throw new IllegalArgumentException("Unexpected character: " + data[index]); - } - index++; - } + /** + * Processes a required character. If the next character does not equal the + * specified character, an IllegalArgumentException is thrown. + * + * @param ch required character + */ + public void required(char ch) { + if (data[index] != ch) { + throw new IllegalArgumentException("Unexpected character: " + data[index]); + } + index++; + } - /** - * Processes a required character range. If the next character is not within - * the specified bounds, an IllegalArgumentException is thrown. - * - * @param from lower character value bound, inclusive - * @param to upper character value bound, inclusive - * @return the processed character - */ - public char required(char from, char to) { - if (data[index] < from || data[index] > to) { - throw new IllegalArgumentException("Unexpected character: " + data[index]); - } - return data[index++]; - } + /** + * Processes a required character range. If the next character is not within + * the specified bounds, an IllegalArgumentException is thrown. + * + * @param from lower character value bound, inclusive + * @param to upper character value bound, inclusive + * @return the processed character + */ + public char required(char from, char to) { + if (data[index] < from || data[index] > to) { + throw new IllegalArgumentException("Unexpected character: " + data[index]); + } + return data[index++]; + } - /** - * Returns the next character in the stream. - * - * @return the next character - */ - public char next() { - return data[index++]; - } + /** + * Returns the next character in the stream. + * + * @return the next character + */ + public char next() { + return data[index++]; + } - /** - * Checks if the end of the stream has been reached. - * - * @return true if there are more characters in the stream - */ - public boolean hasMore() { - return index < data.length; - } + /** + * Checks if the end of the stream has been reached. + * + * @return true if there are more characters in the stream + */ + public boolean hasMore() { + return index < data.length; + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/CompiledDFA.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/CompiledDFA.java index 5e614b3..f055d7e 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/CompiledDFA.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/CompiledDFA.java @@ -8,8 +8,8 @@ package stanhebben.zenscript.parser; import static java.util.Arrays.sort; /** - * Represents a compiled DFA. A compiled DFA has a compact representation and - * is immediately usable for efficient processing. + * Represents a compiled DFA. A compiled DFA has a compact representation and is + * immediately usable for efficient processing. * * A compiled DFA can be converted to a compact integer array. This array can * then be hardcoded in an application. @@ -17,136 +17,137 @@ import static java.util.Arrays.sort; * @author Stan Hebben */ public class CompiledDFA { - public static final int NOFINAL = Integer.MIN_VALUE; + public static final int NOFINAL = Integer.MIN_VALUE; - public HashMapII[] transitions; - public int[] finals; + public HashMapII[] transitions; + public int[] finals; - /** - * Constructs a compiled DFA from the specified transition graph and finals - * arrays. - * - * The transition array specifies all transitions for each state. The finals - * array specifies the final class index of each state, or NOFINAL if the state - * is not a final. There can multiple final classes, which can, for example, - * be used to distinguish token types. - * - * @param transitions transitions graph - * @param finals finals - */ - public CompiledDFA(HashMapII[] transitions, int[] finals) { - this.transitions = transitions; - this.finals = finals; - } + /** + * Constructs a compiled DFA from the specified transition graph and finals + * arrays. + * + * The transition array specifies all transitions for each state. The finals + * array specifies the final class index of each state, or NOFINAL if the + * state is not a final. There can multiple final classes, which can, for + * example, be used to distinguish token types. + * + * @param transitions transitions graph + * @param finals finals + */ + public CompiledDFA(HashMapII[] transitions, int[] finals) { + this.transitions = transitions; + this.finals = finals; + } - /** - * Converts an integer array with a DFA definition (generated by toArray()) - * to a CompiledDFA. - * - * @param definition definition array - */ - public CompiledDFA(int[] definition) { - int ix = 0; - int numStates = definition[ix++]; - transitions = new HashMapII[numStates]; - finals = new int[numStates]; + /** + * Converts an integer array with a DFA definition (generated by toArray()) + * to a CompiledDFA. + * + * @param definition definition array + */ + public CompiledDFA(int[] definition) { + int ix = 0; + int numStates = definition[ix++]; + transitions = new HashMapII[numStates]; + finals = new int[numStates]; - for (int i = 0; i < numStates; i++) { - transitions[i] = new HashMapII(); - finals[i] = definition[ix++]; + for (int i = 0; i < numStates; i++) { + transitions[i] = new HashMapII(); + finals[i] = definition[ix++]; - int numRanges = definition[ix++]; - for (int j = 0; j < numRanges; j++) { - int from = definition[ix++]; - int to = definition[ix++]; - int state = definition[ix++]; - for (int k = from; k <= to; k++) { - transitions[i].put(k, state); - } - } + int numRanges = definition[ix++]; + for (int j = 0; j < numRanges; j++) { + int from = definition[ix++]; + int to = definition[ix++]; + int state = definition[ix++]; + for (int k = from; k <= to; k++) { + transitions[i].put(k, state); + } + } - int numSingles = definition[ix++]; - for (int j = 0; j < numSingles; j++) { - int label = definition[ix++]; - int state = definition[ix++]; - transitions[i].put(label, state); - } - } - } + int numSingles = definition[ix++]; + for (int j = 0; j < numSingles; j++) { + int label = definition[ix++]; + int state = definition[ix++]; + transitions[i].put(label, state); + } + } + } - /** - * Converts the DFA to an integer array. - * - * @return an integer array representation of the DFA - */ - public int[] toArray() { - ArrayListI result = new ArrayListI(); - result.add(finals.length); + /** + * Converts the DFA to an integer array. + * + * @return an integer array representation of the DFA + */ + public int[] toArray() { + ArrayListI result = new ArrayListI(); + result.add(finals.length); - for (int i = 0; i < finals.length; i++) { - result.add(finals[i]); + for (int i = 0; i < finals.length; i++) { + result.add(finals[i]); - ArrayListI singles = new ArrayListI(); - ArrayListI rangeFrom = new ArrayListI(); - ArrayListI rangeTo = new ArrayListI(); + ArrayListI singles = new ArrayListI(); + ArrayListI rangeFrom = new ArrayListI(); + ArrayListI rangeTo = new ArrayListI(); - int[] keys = transitions[i].keysArray(); - sort(keys); - for (int j = 0; j < keys.length; j++) { - int from = j; - int state = transitions[i].get(j); - while (j + 1 < keys.length && keys[j + 1] == keys[j] + 1 && transitions[i].get(j + 1) == state) j++; - if (j == from) { - singles.add(keys[j]); - } else { - rangeFrom.add(keys[from]); - rangeTo.add(keys[j]); - } - } + int[] keys = transitions[i].keysArray(); + sort(keys); + for (int j = 0; j < keys.length; j++) { + int from = j; + int state = transitions[i].get(j); + while (j + 1 < keys.length && keys[j + 1] == keys[j] + 1 && transitions[i].get(j + 1) == state) + j++; + if (j == from) { + singles.add(keys[j]); + } else { + rangeFrom.add(keys[from]); + rangeTo.add(keys[j]); + } + } - result.add(rangeFrom.size()); - for (int j = 0; j < rangeFrom.size(); j++) { - result.add(rangeFrom.get(j)); - result.add(rangeTo.get(j)); - result.add(transitions[i].get(rangeFrom.get(j))); - } - result.add(singles.size()); - for (int j = 0; j < singles.size(); j++) { - result.add(singles.get(j)); - result.add(transitions[i].get(singles.get(j))); - } - } - return result.toArray(); - } + result.add(rangeFrom.size()); + for (int j = 0; j < rangeFrom.size(); j++) { + result.add(rangeFrom.get(j)); + result.add(rangeTo.get(j)); + result.add(transitions[i].get(rangeFrom.get(j))); + } + result.add(singles.size()); + for (int j = 0; j < singles.size(); j++) { + result.add(singles.get(j)); + result.add(transitions[i].get(singles.get(j))); + } + } + return result.toArray(); + } - /* Used for debugging */ - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - for (int i = 0; i < transitions.length; i++) { - HashMapII map = transitions[i]; + /* Used for debugging */ + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + for (int i = 0; i < transitions.length; i++) { + HashMapII map = transitions[i]; - IteratorI it = map.keys(); - while (it.hasNext()) { - int v = it.next(); - result.append("edge("); - result.append(i); - result.append(", "); - result.append(v); - result.append("): "); - result.append(map.get(v)); - result.append("\r\n"); - } - } - for (int i = 0; i < finals.length; i++) { - if (finals[i] != DFA.NOFINAL) { - result.append("final("); - result.append(i); - result.append("): "); - result.append(finals[i]); - result.append("\r\n"); - } - } - return result.toString(); - } + IteratorI it = map.keys(); + while (it.hasNext()) { + int v = it.next(); + result.append("edge("); + result.append(i); + result.append(", "); + result.append(v); + result.append("): "); + result.append(map.get(v)); + result.append("\r\n"); + } + } + for (int i = 0; i < finals.length; i++) { + if (finals[i] != DFA.NOFINAL) { + result.append("final("); + result.append(i); + result.append("): "); + result.append(finals[i]); + result.append("\r\n"); + } + } + return result.toString(); + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/DFA.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/DFA.java index 604699a..43d22e3 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/DFA.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/DFA.java @@ -16,234 +16,235 @@ import java.util.Queue; * @author Stan Hebben */ public class DFA { - public static final int NOFINAL = Integer.MIN_VALUE; + public static final int NOFINAL = Integer.MIN_VALUE; - private DFAState initial; + private DFAState initial; - /** - * Constructs a new DFA with the specified initial state. - * - * @param initial - */ - public DFA(DFAState initial) { - this.initial = initial; - } + /** + * Constructs a new DFA with the specified initial state. + * + * @param initial + */ + public DFA(DFAState initial) { + this.initial = initial; + } - /** - * Compiles this DFA into a more efficient structure. - * - * @return the compiled DFA - */ - public CompiledDFA compile() { - ArrayList nodeList = new ArrayList(); - HashMap nodes = new HashMap(); - nodes.put(initial, 0); - nodeList.add(initial); + /** + * Compiles this DFA into a more efficient structure. + * + * @return the compiled DFA + */ + public CompiledDFA compile() { + ArrayList nodeList = new ArrayList(); + HashMap nodes = new HashMap(); + nodes.put(initial, 0); + nodeList.add(initial); - /* Find all reachable nodes in the dfs */ - int counter = 1; - Queue todo = new LinkedList(); - todo.add(initial); + /* Find all reachable nodes in the dfs */ + int counter = 1; + Queue todo = new LinkedList(); + todo.add(initial); - while (!todo.isEmpty()) { - DFAState current = todo.poll(); + while (!todo.isEmpty()) { + DFAState current = todo.poll(); - IteratorI it = current.transitions.keys(); - while (it.hasNext()) { - int k = it.next(); - DFAState next = current.transitions.get(k); - if (!nodes.containsKey(next)) { - todo.add(next); - nodes.put(next, counter++); - nodeList.add(next); - } - } - } + IteratorI it = current.transitions.keys(); + while (it.hasNext()) { + int k = it.next(); + DFAState next = current.transitions.get(k); + if (!nodes.containsKey(next)) { + todo.add(next); + nodes.put(next, counter++); + nodeList.add(next); + } + } + } - /* Compile */ - HashMapII[] transitions = new HashMapII[counter]; - int[] finals2 = new int[counter]; + /* Compile */ + HashMapII[] transitions = new HashMapII[counter]; + int[] finals2 = new int[counter]; - for (DFAState node : nodeList) { - int index = nodes.get(node); - finals2[index] = node.finalCode; + for (DFAState node : nodeList) { + int index = nodes.get(node); + finals2[index] = node.finalCode; - transitions[index] = new HashMapII(); - IteratorI it = node.transitions.keys(); - while (it.hasNext()) { - int k = it.next(); - DFAState next = node.transitions.get(k); - transitions[index].put(k, nodes.get(next)); - } - } + transitions[index] = new HashMapII(); + IteratorI it = node.transitions.keys(); + while (it.hasNext()) { + int k = it.next(); + DFAState next = node.transitions.get(k); + transitions[index].put(k, nodes.get(next)); + } + } - return new CompiledDFA(transitions, finals2); - } + return new CompiledDFA(transitions, finals2); + } - /** - * Generates the minimal version of this DFA. - * - * @return the minimal DFA - */ - public DFA optimize() { - CompiledDFA compiled = compile(); - HashMapII[] transitions = compiled.transitions; - int size = transitions.length; + /** + * Generates the minimal version of this DFA. + * + * @return the minimal DFA + */ + public DFA optimize() { + CompiledDFA compiled = compile(); + HashMapII[] transitions = compiled.transitions; + int size = transitions.length; - /* Collect all edges and determine alphabet */ - HashSetI alphabet = new HashSetI(); - for (int i = 0; i < size; i++) { - IteratorI it = transitions[i].keys(); - while (it.hasNext()) { - int k = it.next(); - alphabet.add(k); - } - } + /* Collect all edges and determine alphabet */ + HashSetI alphabet = new HashSetI(); + for (int i = 0; i < size; i++) { + IteratorI it = transitions[i].keys(); + while (it.hasNext()) { + int k = it.next(); + alphabet.add(k); + } + } - /* Initialize distinguishing array */ - boolean[][] distinguishable = new boolean[size + 1][size + 1]; - for (int i = 0; i < size; i++) { - for (int j = 0; j < size; j++) { - distinguishable[i][j] = compiled.finals[i] != compiled.finals[j]; - } - } - for (int i = 0; i < size; i++) { - distinguishable[i][size] = true; - distinguishable[size][i] = true; - } + /* Initialize distinguishing array */ + boolean[][] distinguishable = new boolean[size + 1][size + 1]; + for (int i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + distinguishable[i][j] = compiled.finals[i] != compiled.finals[j]; + } + } + for (int i = 0; i < size; i++) { + distinguishable[i][size] = true; + distinguishable[size][i] = true; + } - /* Minimization algorithm implementation */ - boolean changed; - do { - changed = false; - IteratorI ita = alphabet.iterator(); - while (ita.hasNext()) { - int x = ita.next(); - for (int i = 0; i < size; i++) { - int ti = transitions[i].get(x, size); - for (int j = 0; j < size; j++) { - if (distinguishable[i][j]) continue; + /* Minimization algorithm implementation */ + boolean changed; + do { + changed = false; + IteratorI ita = alphabet.iterator(); + while (ita.hasNext()) { + int x = ita.next(); + for (int i = 0; i < size; i++) { + int ti = transitions[i].get(x, size); + for (int j = 0; j < size; j++) { + if (distinguishable[i][j]) + continue; - int tj = transitions[j].get(x, size); - if (distinguishable[ti][tj]) { - distinguishable[i][j] = true; - changed = true; - } - } - } - } - } while (changed); + int tj = transitions[j].get(x, size); + if (distinguishable[ti][tj]) { + distinguishable[i][j] = true; + changed = true; + } + } + } + } + } while (changed); - /* Group nodes */ - HashMapI nodeMap = new HashMapI(); - outer: for (int i = 0; i < size; i++) { - for (int j = 0; j < size; j++) { - if (!distinguishable[i][j] && nodeMap.containsKey(j)) { - nodeMap.put(i, nodeMap.get(j)); - if (compiled.finals[i] != NOFINAL) { - if (nodeMap.get(j).getFinal() != NOFINAL && nodeMap.get(j).getFinal() != compiled.finals[i]) { - throw new RuntimeException("Eh?"); - } - } - continue outer; - } - } - DFAState node = new DFAState(); - node.setFinal(compiled.finals[i]); - nodeMap.put(i, node); - } + /* Group nodes */ + HashMapI nodeMap = new HashMapI(); + outer: for (int i = 0; i < size; i++) { + for (int j = 0; j < size; j++) { + if (!distinguishable[i][j] && nodeMap.containsKey(j)) { + nodeMap.put(i, nodeMap.get(j)); + if (compiled.finals[i] != NOFINAL) { + if (nodeMap.get(j).getFinal() != NOFINAL && nodeMap.get(j).getFinal() != compiled.finals[i]) { + throw new RuntimeException("Eh?"); + } + } + continue outer; + } + } + DFAState node = new DFAState(); + node.setFinal(compiled.finals[i]); + nodeMap.put(i, node); + } - for (int i = 0; i < compiled.transitions.length; i++) { - IteratorI iter = transitions[i].keys(); - while (iter.hasNext()) { - int k = iter.next(); + for (int i = 0; i < compiled.transitions.length; i++) { + IteratorI iter = transitions[i].keys(); + while (iter.hasNext()) { + int k = iter.next(); - nodeMap.get(i).addTransition(k, nodeMap.get(transitions[i].get(k))); - } - } - - DFA result = new DFA(nodeMap.get(0)); - return result; - } + nodeMap.get(i).addTransition(k, nodeMap.get(transitions[i].get(k))); + } + } - @Override - public String toString() { - StringBuilder result = new StringBuilder(); - CompiledDFA dfs = compile(); - for (int i = 0; i < dfs.transitions.length; i++) { - HashMapII map = dfs.transitions[i]; - - IteratorI it = map.keys(); - while (it.hasNext()) { - int v = it.next(); - result.append("edge("); - result.append(i); - result.append(", "); - result.append(v); - result.append("): "); - result.append(map.get(v)); - result.append("\r\n"); - } - } - for (int i = 0; i < dfs.finals.length; i++) { - if (dfs.finals[i] != NOFINAL) { - result.append("final("); - result.append(i); - result.append("): "); - result.append(dfs.finals[i]); - result.append("\r\n"); - } - } - return result.toString(); - } + DFA result = new DFA(nodeMap.get(0)); + return result; + } - ///////////////////////// - // Public inner classes - ///////////////////////// + @Override + public String toString() { + StringBuilder result = new StringBuilder(); + CompiledDFA dfs = compile(); + for (int i = 0; i < dfs.transitions.length; i++) { + HashMapII map = dfs.transitions[i]; - /** - * Represents a state in a DFA. - */ - public static class DFAState { - private HashMapI transitions; - private int finalCode = NOFINAL; + IteratorI it = map.keys(); + while (it.hasNext()) { + int v = it.next(); + result.append("edge("); + result.append(i); + result.append(", "); + result.append(v); + result.append("): "); + result.append(map.get(v)); + result.append("\r\n"); + } + } + for (int i = 0; i < dfs.finals.length; i++) { + if (dfs.finals[i] != NOFINAL) { + result.append("final("); + result.append(i); + result.append("): "); + result.append(dfs.finals[i]); + result.append("\r\n"); + } + } + return result.toString(); + } - /** - * Creates a new DFA state. - */ - public DFAState() { - transitions = new HashMapI(); - } + // /////////////////////// + // Public inner classes + // /////////////////////// - /** - * Adds a transition. - * - * @param label transition edge label - * @param next next state - */ - public void addTransition(int label, DFAState next) { - transitions.put(label, next); - } + /** + * Represents a state in a DFA. + */ + public static class DFAState { + private HashMapI transitions; + private int finalCode = NOFINAL; - /** - * Sets the final class of this state. Finals can be divided in multiple - * class, in which case each class gets its own index. Class NOFINAL is - * used to indicate nonfinals. - * - * @param finalCode final index - */ - public void setFinal(int finalCode) { - this.finalCode = finalCode; - } + /** + * Creates a new DFA state. + */ + public DFAState() { + transitions = new HashMapI(); + } - /** - * Gets the final class of this state. Equals NOFINAL if this state is - * not a final. - * - * @return final index - */ - public int getFinal() { - return finalCode; - } - } + /** + * Adds a transition. + * + * @param label transition edge label + * @param next next state + */ + public void addTransition(int label, DFAState next) { + transitions.put(label, next); + } + + /** + * Sets the final class of this state. Finals can be divided in multiple + * class, in which case each class gets its own index. Class NOFINAL is + * used to indicate nonfinals. + * + * @param finalCode final index + */ + public void setFinal(int finalCode) { + this.finalCode = finalCode; + } + + /** + * Gets the final class of this state. Equals NOFINAL if this state is + * not a final. + * + * @return final index + */ + public int getFinal() { + return finalCode; + } + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/HashMapI.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/HashMapI.java index f4e56e0..2a896c3 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/HashMapI.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/HashMapI.java @@ -11,206 +11,211 @@ package stanhebben.zenscript.parser; * @param */ public class HashMapI { - private int[] keys; - private T[] values; - private int[] next; - private int mask; - private int size; + private int[] keys; + private T[] values; + private int[] next; + private int mask; + private int size; - /** - * Creates a new HashMap for integer keys. - */ - public HashMapI() { - keys = new int[16]; - values = (T[])new Object[16]; - next = new int[16]; - mask = 15; - size = 0; + /** + * Creates a new HashMap for integer keys. + */ + public HashMapI() { + keys = new int[16]; + values = (T[]) new Object[16]; + next = new int[16]; + mask = 15; + size = 0; - for (int i = 0; i < keys.length; i++) { - keys[i] = Integer.MIN_VALUE; - } - } + for (int i = 0; i < keys.length; i++) { + keys[i] = Integer.MIN_VALUE; + } + } - /** - * Associates the specified value with the specified key in this map. If the - * map previously contained a mapping for the key, the old value is replaced. - * - * @param key key with which the specified value is to be associated - * @param value value to be associated with the specified key - */ - public void put(int key, T value) { - if (size > (keys.length * 3) >> 2) { - expand(); - } + /** + * Associates the specified value with the specified key in this map. If the + * map previously contained a mapping for the key, the old value is + * replaced. + * + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + */ + public void put(int key, T value) { + if (size > (keys.length * 3) >> 2) { + expand(); + } - int index = key & mask; + int index = key & mask; - if (keys[index] == Integer.MIN_VALUE) { - keys[index] = key; - values[index] = value; - } else { - if (keys[index] == key) { - values[index] = value; - return; - } - while (next[index] != 0) { - index = next[index] - 1; - if (keys[index] == key) { - values[index] = value; - return; - } - } - int ref = index; - while (keys[index] != Integer.MIN_VALUE) { - index++; - if (index == keys.length) index = 0; - } - next[ref] = index + 1; + if (keys[index] == Integer.MIN_VALUE) { + keys[index] = key; + values[index] = value; + } else { + if (keys[index] == key) { + values[index] = value; + return; + } + while (next[index] != 0) { + index = next[index] - 1; + if (keys[index] == key) { + values[index] = value; + return; + } + } + int ref = index; + while (keys[index] != Integer.MIN_VALUE) { + index++; + if (index == keys.length) + index = 0; + } + next[ref] = index + 1; - keys[index] = key; - values[index] = value; - } + keys[index] = key; + values[index] = value; + } - size++; - } + size++; + } - /** - * Returns the value to which the specified key is mapped, or null if this - * map contains no mapping for the key. - * - * @param key the key whose associated value is to be returned - * @return the value to which the specified key is mapped, or null if this map contains no mapping for the key - */ - public T get(int key) { - int index = key & mask; - while (keys[index] != key) { - if (next[index] == 0) { - return null; - } - index = next[index] - 1; - } - return values[index]; - } + /** + * Returns the value to which the specified key is mapped, or null if this + * map contains no mapping for the key. + * + * @param key the key whose associated value is to be returned + * @return the value to which the specified key is mapped, or null if this + * map contains no mapping for the key + */ + public T get(int key) { + int index = key & mask; + while (keys[index] != key) { + if (next[index] == 0) { + return null; + } + index = next[index] - 1; + } + return values[index]; + } - /** - * Returns true if this map contains a mapping for the specified key. - * - * @param key The key whose presence in this map is to be tested - * @return true if this map contains a mapping for the specified key. - */ - public boolean containsKey(int key) { - int index = key & mask; - while (keys[index] != key) { - if (next[index] == 0) { - return false; - } - index = next[index] - 1; - } - return true; - } + /** + * Returns true if this map contains a mapping for the specified key. + * + * @param key The key whose presence in this map is to be tested + * @return true if this map contains a mapping for the specified key. + */ + public boolean containsKey(int key) { + int index = key & mask; + while (keys[index] != key) { + if (next[index] == 0) { + return false; + } + index = next[index] - 1; + } + return true; + } - /** - * Returns an iterator over the keys in this HashMap. The elements are - * returned in no particular order. - * - * @return an iterator over the keys in this HashMap - */ - public IteratorI keys() { - return new KeyIterator(); - } + /** + * Returns an iterator over the keys in this HashMap. The elements are + * returned in no particular order. + * + * @return an iterator over the keys in this HashMap + */ + public IteratorI keys() { + return new KeyIterator(); + } - /** - * Returns an array with all keys in this HashMap. The elements are returned - * in no particular order. - * - * @return an array with all keys in this HashMap - */ - public int[] keysArray() { - int[] result = new int[size]; - int ix = 0; - for (int i = 0; i < keys.length; i++) { - if (keys[i] != Integer.MIN_VALUE) result[ix++] = keys[i]; - } - return result; - } + /** + * Returns an array with all keys in this HashMap. The elements are returned + * in no particular order. + * + * @return an array with all keys in this HashMap + */ + public int[] keysArray() { + int[] result = new int[size]; + int ix = 0; + for (int i = 0; i < keys.length; i++) { + if (keys[i] != Integer.MIN_VALUE) + result[ix++] = keys[i]; + } + return result; + } - //////////////////// - // Private methods - //////////////////// + // ////////////////// + // Private methods + // ////////////////// - /** - * Expands the size of this array. (it doubles the size) - */ - private void expand() { - int[] newKeys = new int[keys.length * 2]; - T[] newValues = (T[])new Object[values.length * 2]; - int[] newNext = new int[next.length * 2]; - int newMask = newKeys.length - 1; + /** + * Expands the size of this array. (it doubles the size) + */ + private void expand() { + int[] newKeys = new int[keys.length * 2]; + T[] newValues = (T[]) new Object[values.length * 2]; + int[] newNext = new int[next.length * 2]; + int newMask = newKeys.length - 1; - for (int i = 0; i < newKeys.length; i++) { - newKeys[i] = Integer.MIN_VALUE; - } + for (int i = 0; i < newKeys.length; i++) { + newKeys[i] = Integer.MIN_VALUE; + } - for (int i = 0; i < keys.length; i++) { - if (keys[i] == Integer.MIN_VALUE) { - continue; - } + for (int i = 0; i < keys.length; i++) { + if (keys[i] == Integer.MIN_VALUE) { + continue; + } - int key = keys[i]; - T value = values[i]; - int index = key & newMask; + int key = keys[i]; + T value = values[i]; + int index = key & newMask; - if (newKeys[index] == Integer.MIN_VALUE) { - newKeys[index] = key; - newValues[index] = value; - } else { - while (newNext[index] != 0) { - index = newNext[index] - 1; - } - int ref = index; - while (newKeys[index] != Integer.MIN_VALUE) { - index = (index + 1) & newMask; - } - newNext[ref] = index + 1; + if (newKeys[index] == Integer.MIN_VALUE) { + newKeys[index] = key; + newValues[index] = value; + } else { + while (newNext[index] != 0) { + index = newNext[index] - 1; + } + int ref = index; + while (newKeys[index] != Integer.MIN_VALUE) { + index = (index + 1) & newMask; + } + newNext[ref] = index + 1; - newKeys[index] = key; - newValues[index] = value; - } - } + newKeys[index] = key; + newValues[index] = value; + } + } - keys = newKeys; - values = newValues; - next = newNext; - mask = newMask; - } + keys = newKeys; + values = newValues; + next = newNext; + mask = newMask; + } - ////////////////////////// - // Private inner classes - ////////////////////////// + // //////////////////////// + // Private inner classes + // //////////////////////// - private class KeyIterator implements IteratorI { - private int i; + private class KeyIterator implements IteratorI { + private int i; - public KeyIterator() { - i = 0; - skip(); - } + public KeyIterator() { + i = 0; + skip(); + } @Override - public boolean hasNext() { - return i < keys.length; - } + public boolean hasNext() { + return i < keys.length; + } @Override - public int next() { - int result = keys[i++]; - skip(); - return result; - } + public int next() { + int result = keys[i++]; + skip(); + return result; + } - private void skip() { - while (i < keys.length && keys[i] == Integer.MIN_VALUE) i++; - } - } + private void skip() { + while (i < keys.length && keys[i] == Integer.MIN_VALUE) + i++; + } + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/HashMapII.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/HashMapII.java index fd63096..309819f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/HashMapII.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/HashMapII.java @@ -5,233 +5,240 @@ package stanhebben.zenscript.parser; /** - * A HashMap implementation which is optimized to associate integers with integers. + * A HashMap implementation which is optimized to associate integers with + * integers. * * @author Stan Hebben */ public class HashMapII { - private int[] keys; - private int[] values; - private int[] next; - private int mask; - private int size; + private int[] keys; + private int[] values; + private int[] next; + private int mask; + private int size; - /** - * Creates a new HashMap for integer keys and values. - */ - public HashMapII() { - keys = new int[16]; - values = new int[16]; - next = new int[16]; - mask = 15; - size = 0; + /** + * Creates a new HashMap for integer keys and values. + */ + public HashMapII() { + keys = new int[16]; + values = new int[16]; + next = new int[16]; + mask = 15; + size = 0; - for (int i = 0; i < keys.length; i++) { - keys[i] = Integer.MIN_VALUE; - } - } - - /** - * Returns the number of key/value pairs in the hashmap. - * - * @return hashmap size - */ - public int size() { - return size; - } + for (int i = 0; i < keys.length; i++) { + keys[i] = Integer.MIN_VALUE; + } + } - /** - * Associates the specified value with the specified key in this map. If the - * map previously contained a mapping for the key, the old value is replaced. - * - * @param key key with which the specified value is to be associated - * @param value value to be associated with the specified key - */ - public void put(int key, int value) { - if (size > (keys.length * 3) >> 2) { - expand(); - } + /** + * Returns the number of key/value pairs in the hashmap. + * + * @return hashmap size + */ + public int size() { + return size; + } - int index = key & mask; + /** + * Associates the specified value with the specified key in this map. If the + * map previously contained a mapping for the key, the old value is + * replaced. + * + * @param key key with which the specified value is to be associated + * @param value value to be associated with the specified key + */ + public void put(int key, int value) { + if (size > (keys.length * 3) >> 2) { + expand(); + } - if (keys[index] == Integer.MIN_VALUE) { - keys[index] = key; - values[index] = value; - } else { - while (next[index] != 0) { - index = next[index] - 1; - if (keys[index] == key) { - values[index] = value; - return; - } - } - int ref = index; - while (keys[index] != Integer.MIN_VALUE) { - index++; - if (index == keys.length) index = 0; - } - next[ref] = index + 1; + int index = key & mask; - keys[index] = key; - values[index] = value; - } + if (keys[index] == Integer.MIN_VALUE) { + keys[index] = key; + values[index] = value; + } else { + while (next[index] != 0) { + index = next[index] - 1; + if (keys[index] == key) { + values[index] = value; + return; + } + } + int ref = index; + while (keys[index] != Integer.MIN_VALUE) { + index++; + if (index == keys.length) + index = 0; + } + next[ref] = index + 1; - size++; - } + keys[index] = key; + values[index] = value; + } - /** - * Returns the value to which the specified key is mapped, or null if this - * map contains no mapping for the key. - * - * @param key the key whose associated value is to be returned - * @return the value to which the specified key is mapped, or Integer.MIN_VALUE if this map contains no mapping for the key - */ - public int get(int key) { - int index = key & mask; - while (keys[index] != key) { - if (next[index] == 0) { - return Integer.MIN_VALUE; - } - index = next[index] - 1; - } - return values[index]; - } + size++; + } - /** - * Returns the value to which the specified key is mapped, or null if this - * map contains no mapping for the key. - * - * @param key the key whose associated value is to be returned - * @param def the default key value - * @return the value to which the specified key is mapped, or the default value if this map contains no mapping for the key - */ - public int get(int key, int def) { - int index = key & mask; - while (keys[index] != key) { - if (next[index] == 0) { - return def; - } - index = next[index] - 1; - } - return values[index]; - } + /** + * Returns the value to which the specified key is mapped, or null if this + * map contains no mapping for the key. + * + * @param key the key whose associated value is to be returned + * @return the value to which the specified key is mapped, or + * Integer.MIN_VALUE if this map contains no mapping for the key + */ + public int get(int key) { + int index = key & mask; + while (keys[index] != key) { + if (next[index] == 0) { + return Integer.MIN_VALUE; + } + index = next[index] - 1; + } + return values[index]; + } - /** - * Returns true if this map contains a mapping for the specified key. - * - * @param key The key whose presence in this map is to be tested - * @return true if this map contains a mapping for the specified key. - */ - public boolean containsKey(int key) { - int index = key & mask; - while (keys[index] != key) { - if (next[index] == 0) { - return false; - } - index = next[index] - 1; - } - return true; - } + /** + * Returns the value to which the specified key is mapped, or null if this + * map contains no mapping for the key. + * + * @param key the key whose associated value is to be returned + * @param def the default key value + * @return the value to which the specified key is mapped, or the default + * value if this map contains no mapping for the key + */ + public int get(int key, int def) { + int index = key & mask; + while (keys[index] != key) { + if (next[index] == 0) { + return def; + } + index = next[index] - 1; + } + return values[index]; + } - /** - * Returns an iterator over the keys in this HashMap. The elements are - * returned in no particular order. - * - * @return an iterator over the keys in this HashMap - */ - public IteratorI keys() { - return new KeyIterator(); - } + /** + * Returns true if this map contains a mapping for the specified key. + * + * @param key The key whose presence in this map is to be tested + * @return true if this map contains a mapping for the specified key. + */ + public boolean containsKey(int key) { + int index = key & mask; + while (keys[index] != key) { + if (next[index] == 0) { + return false; + } + index = next[index] - 1; + } + return true; + } - /** - * Returns an array with all keys in this HashMap. The elements are returned - * in no particular order. - * - * @return an array with all keys in this HashMap - */ - public int[] keysArray() { - int[] result = new int[size]; - int ix = 0; - for (int i = 0; i < keys.length; i++) { - if (keys[i] != Integer.MIN_VALUE) result[ix++] = keys[i]; - } - return result; - } + /** + * Returns an iterator over the keys in this HashMap. The elements are + * returned in no particular order. + * + * @return an iterator over the keys in this HashMap + */ + public IteratorI keys() { + return new KeyIterator(); + } - //////////////////// - // Private methods - //////////////////// + /** + * Returns an array with all keys in this HashMap. The elements are returned + * in no particular order. + * + * @return an array with all keys in this HashMap + */ + public int[] keysArray() { + int[] result = new int[size]; + int ix = 0; + for (int i = 0; i < keys.length; i++) { + if (keys[i] != Integer.MIN_VALUE) + result[ix++] = keys[i]; + } + return result; + } - /** - * Expands the size of this array. (it doubles the size) - */ - private void expand() { - int[] newKeys = new int[keys.length * 2]; - int[] newValues = new int[values.length * 2]; - int[] newNext = new int[next.length * 2]; - int newMask = newKeys.length - 1; + // ////////////////// + // Private methods + // ////////////////// - for (int i = 0; i < newKeys.length; i++) { - newKeys[i] = Integer.MIN_VALUE; - } + /** + * Expands the size of this array. (it doubles the size) + */ + private void expand() { + int[] newKeys = new int[keys.length * 2]; + int[] newValues = new int[values.length * 2]; + int[] newNext = new int[next.length * 2]; + int newMask = newKeys.length - 1; - for (int i = 0; i < keys.length; i++) { - if (keys[i] == Integer.MIN_VALUE) { - continue; - } + for (int i = 0; i < newKeys.length; i++) { + newKeys[i] = Integer.MIN_VALUE; + } - int key = keys[i]; - int value = values[i]; - int index = key & newMask; + for (int i = 0; i < keys.length; i++) { + if (keys[i] == Integer.MIN_VALUE) { + continue; + } - if (newKeys[index] == Integer.MIN_VALUE) { - newKeys[index] = key; - newValues[index] = value; - } else { - while (newNext[index] != 0) { - index = newNext[index] - 1; - } - int ref = index; - while (newKeys[index] != Integer.MIN_VALUE) { - index = (index + 1) & newMask; - } - newNext[ref] = index + 1; + int key = keys[i]; + int value = values[i]; + int index = key & newMask; - newKeys[index] = key; - newValues[index] = value; - } - } + if (newKeys[index] == Integer.MIN_VALUE) { + newKeys[index] = key; + newValues[index] = value; + } else { + while (newNext[index] != 0) { + index = newNext[index] - 1; + } + int ref = index; + while (newKeys[index] != Integer.MIN_VALUE) { + index = (index + 1) & newMask; + } + newNext[ref] = index + 1; - keys = newKeys; - values = newValues; - next = newNext; - mask = newMask; - } + newKeys[index] = key; + newValues[index] = value; + } + } - ////////////////////////// - // Private inner classes - ////////////////////////// + keys = newKeys; + values = newValues; + next = newNext; + mask = newMask; + } - private class KeyIterator implements IteratorI { - private int i; + // //////////////////////// + // Private inner classes + // //////////////////////// - public KeyIterator() { - i = 0; - skip(); - } + private class KeyIterator implements IteratorI { + private int i; - public boolean hasNext() { - return i < keys.length; - } + public KeyIterator() { + i = 0; + skip(); + } - public int next() { - int result = keys[i++]; - skip(); - return result; - } + public boolean hasNext() { + return i < keys.length; + } - private void skip() { - while (i < keys.length && keys[i] == Integer.MIN_VALUE) i++; - } - } + public int next() { + int result = keys[i++]; + skip(); + return result; + } + + private void skip() { + while (i < keys.length && keys[i] == Integer.MIN_VALUE) + i++; + } + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/HashSetI.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/HashSetI.java index dc1af8e..083562f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/HashSetI.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/HashSetI.java @@ -12,185 +12,187 @@ import java.util.Arrays; * @author Stan Hebben */ public class HashSetI { - private int[] values; - private int[] next; - private int mask; - private int size; + private int[] values; + private int[] next; + private int mask; + private int size; - /** - * Creates a new HashSet for integer values. - */ - public HashSetI() { - values = new int[16]; - next = new int[16]; - mask = 15; - size = 0; + /** + * Creates a new HashSet for integer values. + */ + public HashSetI() { + values = new int[16]; + next = new int[16]; + mask = 15; + size = 0; - for (int i = 0; i < values.length; i++) { - values[i] = Integer.MIN_VALUE; - } - } + for (int i = 0; i < values.length; i++) { + values[i] = Integer.MIN_VALUE; + } + } - public HashSetI(HashSetI original) { - values = Arrays.copyOf(original.values, original.values.length); - next = Arrays.copyOf(original.next, original.next.length); - mask = original.mask; - size = original.size; - } + public HashSetI(HashSetI original) { + values = Arrays.copyOf(original.values, original.values.length); + next = Arrays.copyOf(original.next, original.next.length); + mask = original.mask; + size = original.size; + } - /** - * Adds the specified value to this HashSet. If this value is already in this - * HashSet, nothing happens. - * - * @param value value to be added to the HashSet - */ - public void add(int value) { - if (size > (values.length * 3) >> 2) { - expand(); - } + /** + * Adds the specified value to this HashSet. If this value is already in + * this HashSet, nothing happens. + * + * @param value value to be added to the HashSet + */ + public void add(int value) { + if (size > (values.length * 3) >> 2) { + expand(); + } - int index = value & mask; + int index = value & mask; - if (values[index] == Integer.MIN_VALUE) { - values[index] = value; - } else { - if (values[index] == value) { - return; - } - while (next[index] != 0) { - index = next[index] - 1; - if (values[index] == value) { - return; - } - } - int ref = index; - while (values[index] != Integer.MIN_VALUE) { - index++; - if (index == values.length) index = 0; - } - next[ref] = index + 1; + if (values[index] == Integer.MIN_VALUE) { + values[index] = value; + } else { + if (values[index] == value) { + return; + } + while (next[index] != 0) { + index = next[index] - 1; + if (values[index] == value) { + return; + } + } + int ref = index; + while (values[index] != Integer.MIN_VALUE) { + index++; + if (index == values.length) + index = 0; + } + next[ref] = index + 1; - values[index] = value; - } + values[index] = value; + } - size++; - } + size++; + } - /** - * Checks if this HashSet contains the specified value. - * - * @param value integer value to add - * @return true if this HashSet contains the specified value - */ - public boolean contains(int value) { - int index = value & mask; - while (values[index] != value) { - if (next[index] == 0) { - return false; - } - index = next[index] - 1; - } - return true; - } + /** + * Checks if this HashSet contains the specified value. + * + * @param value integer value to add + * @return true if this HashSet contains the specified value + */ + public boolean contains(int value) { + int index = value & mask; + while (values[index] != value) { + if (next[index] == 0) { + return false; + } + index = next[index] - 1; + } + return true; + } - /** - * Returns an iterator over this HashSet. The elements are returned in no - * particular order. - * - * @return an iterator over this HashSet - */ - public IteratorI iterator() { - return new KeyIterator(); - } + /** + * Returns an iterator over this HashSet. The elements are returned in no + * particular order. + * + * @return an iterator over this HashSet + */ + public IteratorI iterator() { + return new KeyIterator(); + } - /** - * Converts the contents of this HashSet to an integer array. The order of - * the elements is unspecified. - * - * @return this HashSet as integer array - */ - public int[] toArray() { - int[] result = new int[size]; - int ix = 0; - for (int i = 0; i < values.length; i++) { - if (values[i] != Integer.MIN_VALUE) { - result[ix++] = values[i]; - } - } - return result; - } + /** + * Converts the contents of this HashSet to an integer array. The order of + * the elements is unspecified. + * + * @return this HashSet as integer array + */ + public int[] toArray() { + int[] result = new int[size]; + int ix = 0; + for (int i = 0; i < values.length; i++) { + if (values[i] != Integer.MIN_VALUE) { + result[ix++] = values[i]; + } + } + return result; + } - ////////////////////////// - // Private inner methods - ////////////////////////// + // //////////////////////// + // Private inner methods + // //////////////////////// - /** - * Expands the capacity of this HashSet. (double it) - */ - private void expand() { - int[] newKeys = new int[values.length * 2]; - int[] newNext = new int[next.length * 2]; - int newMask = newKeys.length - 1; + /** + * Expands the capacity of this HashSet. (double it) + */ + private void expand() { + int[] newKeys = new int[values.length * 2]; + int[] newNext = new int[next.length * 2]; + int newMask = newKeys.length - 1; - for (int i = 0; i < newKeys.length; i++) { - newKeys[i] = Integer.MIN_VALUE; - } + for (int i = 0; i < newKeys.length; i++) { + newKeys[i] = Integer.MIN_VALUE; + } - for (int i = 0; i < values.length; i++) { - if (values[i] == Integer.MIN_VALUE) { - continue; - } + for (int i = 0; i < values.length; i++) { + if (values[i] == Integer.MIN_VALUE) { + continue; + } - int key = values[i]; - int index = key & newMask; + int key = values[i]; + int index = key & newMask; - if (newKeys[index] == Integer.MIN_VALUE) { - newKeys[index] = key; - } else { - while (newNext[index] != 0) { - index = newNext[index] - 1; - } - int ref = index; - while (newKeys[index] != Integer.MIN_VALUE) { - index = (index + 1) & newMask; - } - newNext[ref] = index + 1; + if (newKeys[index] == Integer.MIN_VALUE) { + newKeys[index] = key; + } else { + while (newNext[index] != 0) { + index = newNext[index] - 1; + } + int ref = index; + while (newKeys[index] != Integer.MIN_VALUE) { + index = (index + 1) & newMask; + } + newNext[ref] = index + 1; - newKeys[index] = key; - } - } + newKeys[index] = key; + } + } - values = newKeys; - next = newNext; - mask = newMask; - } + values = newKeys; + next = newNext; + mask = newMask; + } - ////////////////////////// - // Private inner classes - ////////////////////////// + // //////////////////////// + // Private inner classes + // //////////////////////// - private class KeyIterator implements IteratorI { - private int i; + private class KeyIterator implements IteratorI { + private int i; - public KeyIterator() { - i = 0; - skip(); - } + public KeyIterator() { + i = 0; + skip(); + } @Override - public boolean hasNext() { - return i < values.length; - } + public boolean hasNext() { + return i < values.length; + } @Override - public int next() { - int result = values[i++]; - skip(); - return result; - } + public int next() { + int result = values[i++]; + skip(); + return result; + } - private void skip() { - while (i < values.length && values[i] == Integer.MIN_VALUE) i++; - } - } + private void skip() { + while (i < values.length && values[i] == Integer.MIN_VALUE) + i++; + } + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/IteratorI.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/IteratorI.java index fde349b..3c168b6 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/IteratorI.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/IteratorI.java @@ -1,4 +1,4 @@ - /* +/* * This file is subject to the license.txt file in the main folder * of this project. */ @@ -11,17 +11,17 @@ package stanhebben.zenscript.parser; * @author Stan Hebben */ public interface IteratorI { - /** - * Returns true if the iteration has more elements. - * - * @return true if the iteration has more elements - */ - public boolean hasNext(); + /** + * Returns true if the iteration has more elements. + * + * @return true if the iteration has more elements + */ + public boolean hasNext(); - /** - * Returns the next element in this iteration. - * - * @return the next element in this iteration - */ - public int next(); + /** + * Returns the next element in this iteration. + * + * @return the next element in this iteration + */ + public int next(); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/NFA.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/NFA.java index e05ad6c..8cf6ef9 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/NFA.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/NFA.java @@ -18,555 +18,593 @@ import java.util.Queue; * @author Stan Hebben */ public class NFA { - public static final int NOFINAL = Integer.MIN_VALUE; - public static final int EPSILON = Integer.MIN_VALUE + 1; + public static final int NOFINAL = Integer.MIN_VALUE; + public static final int EPSILON = Integer.MIN_VALUE + 1; - private final NFAState initial; + private final NFAState initial; - private HashMap converted; + private HashMap converted; - /** - * Creates a new NFA with the specified initial state. - * - * @param initial initial state - */ - public NFA(NFAState initial) { - this.initial = initial; - } + /** + * Creates a new NFA with the specified initial state. + * + * @param initial initial state + */ + public NFA(NFAState initial) { + this.initial = initial; + } - /** - * Creates a new NFA from the specified regular expression. - * - * Note: the regular expression implementation is not complete. Shorthand - * character classes (\s, \w, \d), hexadecimal and unicode escape sequences and - * unicode properties are not implemented. - * - * Anchors, lazy plus operators, lookbehind and lookforward are not implemented - * since they cannot be implemented in an NFA. - * - * @param regexp regular expression - */ - public NFA(String regexp) { - Partial main = processRegExp(new CharStream(regexp)); - initial = new NFAState(); - initial.addTransition(main.tailLabel, main.tail); - main.head.setFinal(1); - } + /** + * Creates a new NFA from the specified regular expression. + * + * Note: the regular expression implementation is not complete. Shorthand + * character classes (\s, \w, \d), hexadecimal and unicode escape sequences + * and unicode properties are not implemented. + * + * Anchors, lazy plus operators, lookbehind and lookforward are not + * implemented since they cannot be implemented in an NFA. + * + * @param regexp regular expression + */ + public NFA(String regexp) { + Partial main = processRegExp(new CharStream(regexp)); + initial = new NFAState(); + initial.addTransition(main.tailLabel, main.tail); + main.head.setFinal(1); + } - /** - * Converts an array of regular expressions to an NFA. Each regular expression - * can have its own final class. The length of both arrays must match. - * - * @param regexp regular expression array - * @param finals final classes - */ - public NFA(String[] regexp, int[] finals) { - initial = new NFAState(); + /** + * Converts an array of regular expressions to an NFA. Each regular + * expression can have its own final class. The length of both arrays must + * match. + * + * @param regexp regular expression array + * @param finals final classes + */ + public NFA(String[] regexp, int[] finals) { + initial = new NFAState(); - Partial[] partials = new Partial[regexp.length]; - for (int i = 0; i < regexp.length; i++) { - partials[i] = processRegExp(new CharStream(regexp[i])); - partials[i].head.setFinal(finals[i]); - initial.addTransition(partials[i].tailLabel, partials[i].tail); - } - } + Partial[] partials = new Partial[regexp.length]; + for (int i = 0; i < regexp.length; i++) { + partials[i] = processRegExp(new CharStream(regexp[i])); + partials[i].head.setFinal(finals[i]); + initial.addTransition(partials[i].tailLabel, partials[i].tail); + } + } - /** - * Converts this NFA to a DFA. The resulting DFA is not optimal. If the - * NFA is ambiguous, the token with lowest value will receive preference. - * - * @return this NFA as DFA - */ - public DFA toDFA() { - converted = new HashMap(); - HashSet closure = new HashSet(); - this.initial.closure(closure); - DFA.DFAState init = convert(new NodeSet(closure)); + /** + * Converts this NFA to a DFA. The resulting DFA is not optimal. If the NFA + * is ambiguous, the token with lowest value will receive preference. + * + * @return this NFA as DFA + */ + public DFA toDFA() { + converted = new HashMap(); + HashSet closure = new HashSet(); + this.initial.closure(closure); + DFA.DFAState init = convert(new NodeSet(closure)); - DFA dfs = new DFA(init); - return dfs; - } + DFA dfs = new DFA(init); + return dfs; + } - //////////////////// - // Private methods - //////////////////// + // ////////////////// + // Private methods + // ////////////////// - /* Converts a set of possible states to a DFA state. */ - private DFA.DFAState convert(NodeSet nodes) { - if (!converted.containsKey(nodes)) { - DFA.DFAState node = new DFA.DFAState(); - converted.put(nodes, node); + /* Converts a set of possible states to a DFA state. */ + private DFA.DFAState convert(NodeSet nodes) { + if (!converted.containsKey(nodes)) { + DFA.DFAState node = new DFA.DFAState(); + converted.put(nodes, node); - HashSet edgeSet = new HashSet(); - for (NFAState n : nodes.nodes) { - n.alphabet(edgeSet); - } - for (int i : edgeSet) { - HashSet edge = new HashSet(); - for (NFAState n : nodes.nodes) { + HashSet edgeSet = new HashSet(); + for (NFAState n : nodes.nodes) { + n.alphabet(edgeSet); + } + for (int i : edgeSet) { + HashSet edge = new HashSet(); + for (NFAState n : nodes.nodes) { n.edge(i, edge); } - NodeSet set = new NodeSet(edge); - node.addTransition(i, convert(set)); - } - int finalCode = DFA.NOFINAL; - for (NFAState n : nodes.nodes) { - if (n.finalCode != NOFINAL) { - if (finalCode != DFA.NOFINAL) { - finalCode = Math.min(n.finalCode, finalCode); - } else { - finalCode = n.finalCode; - } - } - } - node.setFinal(finalCode); - - return node; - } - return converted.get(nodes); - } + NodeSet set = new NodeSet(edge); + node.addTransition(i, convert(set)); + } + int finalCode = DFA.NOFINAL; + for (NFAState n : nodes.nodes) { + if (n.finalCode != NOFINAL) { + if (finalCode != DFA.NOFINAL) { + finalCode = Math.min(n.finalCode, finalCode); + } else { + finalCode = n.finalCode; + } + } + } + node.setFinal(finalCode); - /* Processes a regular expression */ - private Partial processRegExp(CharStream stream) { - Partial partial = processRegExp0(stream); - if (stream.optional('|')) { - ArrayList partials = new ArrayList(); - partials.add(partial); - partials.add(processRegExp0(stream)); - while (stream.optional('|')) { - partials.add(processRegExp0(stream)); - } - NFAState head = new NFAState(); - NFAState tail = new NFAState(); - for (Partial p : partials) { - tail.addTransition(p.tailLabel, p.tail); - p.head.addTransition(EPSILON, head); - } - return new Partial(EPSILON, tail, head); - } else { - return partial; - } - } + return node; + } + return converted.get(nodes); + } - /* Processes an element of an alternation clause */ - private Partial processRegExp0(CharStream stream) { - Partial partial = processRegExp1(stream); - while (!stream.peek(')') && !stream.peek('|') && stream.hasMore()) { - Partial partial2 = processRegExp1(stream); - partial.head.addTransition(partial2.tailLabel, partial2.tail); - partial = new Partial(partial.tailLabel, partial.tail, partial2.head); - } - return partial; - } + /* Processes a regular expression */ + private Partial processRegExp(CharStream stream) { + Partial partial = processRegExp0(stream); + if (stream.optional('|')) { + ArrayList partials = new ArrayList(); + partials.add(partial); + partials.add(processRegExp0(stream)); + while (stream.optional('|')) { + partials.add(processRegExp0(stream)); + } + NFAState head = new NFAState(); + NFAState tail = new NFAState(); + for (Partial p : partials) { + tail.addTransition(p.tailLabel, p.tail); + p.head.addTransition(EPSILON, head); + } + return new Partial(EPSILON, tail, head); + } else { + return partial; + } + } - /* Processes a partial with optional repetition */ - private Partial processRegExp1(CharStream stream) { - Partial partial = processPartial(stream); - if (stream.optional('*')) { - NFAState node = new NFAState(); - partial.head.addTransition(EPSILON, node); - node.addTransition(partial.tailLabel, partial.tail); - return new Partial(EPSILON, node, node); - } else if (stream.optional('+')) { - NFAState node = new NFAState(); - partial.head.addTransition(EPSILON, node); - node.addTransition(partial.tailLabel, partial.tail); - return new Partial(partial.tailLabel, partial.tail, node); - } else if (stream.optional('?')) { - NFAState node = new NFAState(); - node.addTransition(EPSILON, partial.head); - node.addTransition(partial.tailLabel, partial.tail); - return new Partial(EPSILON, node, partial.head); - } else if (stream.optional('{')) { - int amount = processInt(stream); - if (amount < 0) throw new IllegalArgumentException("Repitition count expected"); - if (stream.optional(',')) { - int amount2 = processInt(stream); - stream.required('}'); - if (amount2 < 0) { - // unbounded - Partial[] duplicates = new Partial[amount]; - for (int i = 0; i < duplicates.length - 1; i++) { - duplicates[i] = partial.duplicate(); - } - duplicates[amount - 1] = partial; - for (int i = 0; i < duplicates.length - 1; i++) { - duplicates[i].head.addTransition(duplicates[i + 1].tailLabel, duplicates[i + 1].tail); - } - duplicates[amount - 1].head.addTransition(duplicates[amount - 1].tailLabel, duplicates[amount - 1].tail); - return new Partial(duplicates[0].tailLabel, duplicates[0].tail, duplicates[amount - 1].head); - } else { - Partial[] duplicates = new Partial[amount2]; - for (int i = 0; i < duplicates.length - 1; i++) { - duplicates[i] = partial.duplicate(); - } - duplicates[amount2 - 1] = partial; - for (int i = 0; i < duplicates.length - 1; i++) { - duplicates[i].head.addTransition(duplicates[i + 1].tailLabel, duplicates[i + 1].tail); - } - for (int i = amount; i < amount2; i++) { - if (i == 0) { - /* insert additional node before the chain because minimal repeat is 0 */ - NFAState additional = new NFAState(); - additional.addTransition(duplicates[0].tailLabel, duplicates[0].tail); - additional.addTransition(EPSILON, duplicates[amount2 - 1].head); - duplicates[0].tailLabel = EPSILON; - duplicates[0].tail = additional; - } else { - duplicates[i - 1].head.addTransition(EPSILON, duplicates[amount2 - 1].head); - } - } - return new Partial(duplicates[0].tailLabel, duplicates[0].tail, duplicates[amount2 - 1].head); - } - } else { - stream.required('}'); - - Partial[] duplicates = new Partial[amount]; - for (int i = 0; i < duplicates.length - 1; i++) { - duplicates[i] = partial.duplicate(); - } - duplicates[amount - 1] = partial; - for (int i = 0; i < duplicates.length - 1; i++) { - duplicates[i].head.addTransition(duplicates[i + 1].tailLabel, duplicates[i + 1].tail); - } - return new Partial(duplicates[0].tailLabel, duplicates[0].tail, duplicates[amount - 1].head); - } - } else { - return partial; - } - } + /* Processes an element of an alternation clause */ + private Partial processRegExp0(CharStream stream) { + Partial partial = processRegExp1(stream); + while (!stream.peek(')') && !stream.peek('|') && stream.hasMore()) { + Partial partial2 = processRegExp1(stream); + partial.head.addTransition(partial2.tailLabel, partial2.tail); + partial = new Partial(partial.tailLabel, partial.tail, partial2.head); + } + return partial; + } - /* Processes a part of a regular expression, which can be a character, - * expression between brackets, a dot or a character list */ - private Partial processPartial(CharStream stream) { - if (stream.optional('(')) { - Partial result = processRegExp(stream); - stream.required(')'); - return result; - } else if (stream.optional('[')) { - NFAState head = new NFAState(); - NFAState tail = new NFAState(); + /* Processes a partial with optional repetition */ + private Partial processRegExp1(CharStream stream) { + Partial partial = processPartial(stream); + if (stream.optional('*')) { + NFAState node = new NFAState(); + partial.head.addTransition(EPSILON, node); + node.addTransition(partial.tailLabel, partial.tail); + return new Partial(EPSILON, node, node); + } else if (stream.optional('+')) { + NFAState node = new NFAState(); + partial.head.addTransition(EPSILON, node); + node.addTransition(partial.tailLabel, partial.tail); + return new Partial(partial.tailLabel, partial.tail, node); + } else if (stream.optional('?')) { + NFAState node = new NFAState(); + node.addTransition(EPSILON, partial.head); + node.addTransition(partial.tailLabel, partial.tail); + return new Partial(EPSILON, node, partial.head); + } else if (stream.optional('{')) { + int amount = processInt(stream); + if (amount < 0) + throw new IllegalArgumentException("Repitition count expected"); + if (stream.optional(',')) { + int amount2 = processInt(stream); + stream.required('}'); + if (amount2 < 0) { + // unbounded + Partial[] duplicates = new Partial[amount]; + for (int i = 0; i < duplicates.length - 1; i++) { + duplicates[i] = partial.duplicate(); + } + duplicates[amount - 1] = partial; + for (int i = 0; i < duplicates.length - 1; i++) { + duplicates[i].head.addTransition(duplicates[i + 1].tailLabel, duplicates[i + 1].tail); + } + duplicates[amount - 1].head.addTransition(duplicates[amount - 1].tailLabel, duplicates[amount - 1].tail); + return new Partial(duplicates[0].tailLabel, duplicates[0].tail, duplicates[amount - 1].head); + } else { + Partial[] duplicates = new Partial[amount2]; + for (int i = 0; i < duplicates.length - 1; i++) { + duplicates[i] = partial.duplicate(); + } + duplicates[amount2 - 1] = partial; + for (int i = 0; i < duplicates.length - 1; i++) { + duplicates[i].head.addTransition(duplicates[i + 1].tailLabel, duplicates[i + 1].tail); + } + for (int i = amount; i < amount2; i++) { + if (i == 0) { + /* + * insert additional node before the chain because + * minimal repeat is 0 + */ + NFAState additional = new NFAState(); + additional.addTransition(duplicates[0].tailLabel, duplicates[0].tail); + additional.addTransition(EPSILON, duplicates[amount2 - 1].head); + duplicates[0].tailLabel = EPSILON; + duplicates[0].tail = additional; + } else { + duplicates[i - 1].head.addTransition(EPSILON, duplicates[amount2 - 1].head); + } + } + return new Partial(duplicates[0].tailLabel, duplicates[0].tail, duplicates[amount2 - 1].head); + } + } else { + stream.required('}'); - IteratorI iter = processCharList(stream).iterator(); - while (iter.hasNext()) { - tail.addTransition(iter.next(), head); - } - stream.required(']'); - return new Partial(EPSILON, tail, head); - } else if (stream.optional('.')) { - NFAState head = new NFAState(); - NFAState tail = new NFAState(); + Partial[] duplicates = new Partial[amount]; + for (int i = 0; i < duplicates.length - 1; i++) { + duplicates[i] = partial.duplicate(); + } + duplicates[amount - 1] = partial; + for (int i = 0; i < duplicates.length - 1; i++) { + duplicates[i].head.addTransition(duplicates[i + 1].tailLabel, duplicates[i + 1].tail); + } + return new Partial(duplicates[0].tailLabel, duplicates[0].tail, duplicates[amount - 1].head); + } + } else { + return partial; + } + } - for (int i = 0; i <= 256; i++) { - tail.addTransition(i, head); - } - return new Partial(EPSILON, tail, head); - } else { - NFAState node = new NFAState(); - return new Partial(processChar(stream), node, node); - } - } + /* + * Processes a part of a regular expression, which can be a character, + * expression between brackets, a dot or a character list + */ + private Partial processPartial(CharStream stream) { + if (stream.optional('(')) { + Partial result = processRegExp(stream); + stream.required(')'); + return result; + } else if (stream.optional('[')) { + NFAState head = new NFAState(); + NFAState tail = new NFAState(); - /* Processes a character list */ - private HashSetI processCharList(CharStream stream) { - boolean invert = stream.optional('^'); - HashSetI base = new HashSetI(); - do { - processCharPartial(base, stream); - } while (!stream.peek(']')); - if (invert) { - HashSetI result = new HashSetI(); - for (int i = 0; i <= 256; i++) { - if (!base.contains(i)) result.add(i); - } - return result; - } else { - return base; - } - } + IteratorI iter = processCharList(stream).iterator(); + while (iter.hasNext()) { + tail.addTransition(iter.next(), head); + } + stream.required(']'); + return new Partial(EPSILON, tail, head); + } else if (stream.optional('.')) { + NFAState head = new NFAState(); + NFAState tail = new NFAState(); - /* Processes a character partial, which can be a single character or a range - * of characters. */ - private void processCharPartial(HashSetI out, CharStream stream) { - if (stream.optional('.')) { - for (int i = 0; i <= 256; i++) { - out.add(i); - } - } else { - int from = processChar(stream); - if (stream.optional('-')) { - int to = processChar(stream); - for (int i = from; i <= to; i++) { - out.add(i); - } - } else { - out.add(from); - } - } - } + for (int i = 0; i <= 256; i++) { + tail.addTransition(i, head); + } + return new Partial(EPSILON, tail, head); + } else { + NFAState node = new NFAState(); + return new Partial(processChar(stream), node, node); + } + } - /* Processes a single character */ - private int processChar(CharStream stream) { - if (stream.optional('\\')) { - if (stream.optional('e')) return -1; - if (stream.optional('r')) return '\r'; - if (stream.optional('n')) return '\n'; - if (stream.optional('t')) return '\t'; - if (stream.optional('[')) return '['; - if (stream.optional(']')) return ']'; - if (stream.optional('(')) return '('; - if (stream.optional(')')) return ')'; - if (stream.optional('.')) return '.'; - if (stream.optional('+')) return '+'; - if (stream.optional('-')) return '-'; - if (stream.optional('\\')) return '\\'; - if (stream.optional('{')) return '{'; - if (stream.optional('}')) return '}'; - if (stream.optional('?')) return '?'; - if (stream.optional('*')) return '*'; - if (stream.optional('~')) return '~'; - if (stream.optional('|')) return '|'; - if (stream.optional('^')) return '^'; - throw new IllegalArgumentException("Invalid character: " + stream.next()); - } else { - if (stream.peek('[') - || stream.peek(']') - || stream.peek('(') - || stream.peek(')') - || stream.peek('{') - || stream.peek('}') - || stream.peek('.') - || stream.peek('-') - || stream.peek('+') - || stream.peek('?') - || stream.peek('*')) { - throw new IllegalArgumentException("Invalid character: " + stream.next()); - } else { - return stream.next(); - } - } - } + /* Processes a character list */ + private HashSetI processCharList(CharStream stream) { + boolean invert = stream.optional('^'); + HashSetI base = new HashSetI(); + do { + processCharPartial(base, stream); + } while (!stream.peek(']')); + if (invert) { + HashSetI result = new HashSetI(); + for (int i = 0; i <= 256; i++) { + if (!base.contains(i)) + result.add(i); + } + return result; + } else { + return base; + } + } - /* Processes an optional integer, returns -1 if the next character do not - * represent an integer */ - private int processInt(CharStream stream) { - int data = stream.optional('0', '9') - '0'; - if (data < 0) return -1; - char ch = stream.optional('0', '9'); - while (ch != 0) { - data = data * 10 + (ch - '0'); - ch = stream.optional('0', '9'); - } - return data; - } + /* + * Processes a character partial, which can be a single character or a range + * of characters. + */ + private void processCharPartial(HashSetI out, CharStream stream) { + if (stream.optional('.')) { + for (int i = 0; i <= 256; i++) { + out.add(i); + } + } else { + int from = processChar(stream); + if (stream.optional('-')) { + int to = processChar(stream); + for (int i = from; i <= to; i++) { + out.add(i); + } + } else { + out.add(from); + } + } + } - ///////////////////////// - // Public inner classes - ///////////////////////// + /* Processes a single character */ + private int processChar(CharStream stream) { + if (stream.optional('\\')) { + if (stream.optional('e')) + return -1; + if (stream.optional('r')) + return '\r'; + if (stream.optional('n')) + return '\n'; + if (stream.optional('t')) + return '\t'; + if (stream.optional('[')) + return '['; + if (stream.optional(']')) + return ']'; + if (stream.optional('(')) + return '('; + if (stream.optional(')')) + return ')'; + if (stream.optional('.')) + return '.'; + if (stream.optional('+')) + return '+'; + if (stream.optional('-')) + return '-'; + if (stream.optional('\\')) + return '\\'; + if (stream.optional('{')) + return '{'; + if (stream.optional('}')) + return '}'; + if (stream.optional('?')) + return '?'; + if (stream.optional('*')) + return '*'; + if (stream.optional('~')) + return '~'; + if (stream.optional('|')) + return '|'; + if (stream.optional('^')) + return '^'; + throw new IllegalArgumentException("Invalid character: " + stream.next()); + } else { + if (stream.peek('[') + || stream.peek(']') + || stream.peek('(') + || stream.peek(')') + || stream.peek('{') + || stream.peek('}') + || stream.peek('.') + || stream.peek('-') + || stream.peek('+') + || stream.peek('?') + || stream.peek('*')) { + throw new IllegalArgumentException("Invalid character: " + stream.next()); + } else { + return stream.next(); + } + } + } - /** - * Represents an NFA state. - */ - public static class NFAState { - private static int counter = 1; + /* + * Processes an optional integer, returns -1 if the next character do not + * represent an integer + */ + private int processInt(CharStream stream) { + int data = stream.optional('0', '9') - '0'; + if (data < 0) + return -1; + char ch = stream.optional('0', '9'); + while (ch != 0) { + data = data * 10 + (ch - '0'); + ch = stream.optional('0', '9'); + } + return data; + } - private ArrayList transitions; - private ArrayList closure; - private int index; - private int finalCode = NOFINAL; + // /////////////////////// + // Public inner classes + // /////////////////////// - /** - * Creates a new state. - */ - public NFAState() { - transitions = new ArrayList(); - index = counter++; - } + /** + * Represents an NFA state. + */ + public static class NFAState { + private static int counter = 1; - /** - * Adds a transition. - * - * @param label transition label - * @param next next state - */ - public void addTransition(int label, NFAState next) { - transitions.add(new Transition(label, next)); - } + private ArrayList transitions; + private ArrayList closure; + private int index; + private int finalCode = NOFINAL; - /** - * Sets the final state of this state. - * - * @param finalCode - */ - public void setFinal(int finalCode) { - if (this.finalCode == finalCode) return; - this.finalCode = finalCode; + /** + * Creates a new state. + */ + public NFAState() { + transitions = new ArrayList(); + index = counter++; + } - for (Transition t : transitions) { - if (t.label == EPSILON) { - t.next.setFinal(finalCode); - } - } - } + /** + * Adds a transition. + * + * @param label transition label + * @param next next state + */ + public void addTransition(int label, NFAState next) { + transitions.add(new Transition(label, next)); + } - //////////////////// - // Private methods - //////////////////// + /** + * Sets the final state of this state. + * + * @param finalCode + */ + public void setFinal(int finalCode) { + if (this.finalCode == finalCode) + return; + this.finalCode = finalCode; - /** - * Determines the (partial) closure of this state. - * - * @param output output to store the closure in - */ - private void closure(HashSet output) { - for (NFAState node : closure()) output.add(node); - } + for (Transition t : transitions) { + if (t.label == EPSILON) { + t.next.setFinal(finalCode); + } + } + } - /** - * Calculates the (full) closure of this state. - * - * @return this state's closure - */ - private ArrayList closure() { - if (closure == null) { - HashSet tmp = new HashSet(); - tmp.add(this); - for (Transition transition : transitions) { - if (transition.label == EPSILON) { - if (!tmp.contains(transition.next)) { - tmp.add(transition.next); - transition.next.closure(tmp); - } - } - } - closure = new ArrayList(); - for (NFAState node : tmp) closure.add(node); - } - return closure; - } + // ////////////////// + // Private methods + // ////////////////// - /** - * Calculates the possible set of states after a transition with the - * specified value - * - * @param label transition label - * @param output possible set of states (out) - */ - private void edge(int label, HashSet output) { - for (Transition transition : transitions) { - if (transition.label == label) { - if (!output.contains(transition.next)) { - output.add(transition.next); - transition.next.closure(output); - } - } - } - } + /** + * Determines the (partial) closure of this state. + * + * @param output output to store the closure in + */ + private void closure(HashSet output) { + for (NFAState node : closure()) + output.add(node); + } - /** - * Calculates the alphabet of this state. - * - * @param output alphabet (out) - */ - private void alphabet(HashSet output) { - for (NFAState node : closure()) { - for (Transition t : node.transitions) { - if (t.label != EPSILON) { - output.add(t.label); - } - } - } - } + /** + * Calculates the (full) closure of this state. + * + * @return this state's closure + */ + private ArrayList closure() { + if (closure == null) { + HashSet tmp = new HashSet(); + tmp.add(this); + for (Transition transition : transitions) { + if (transition.label == EPSILON) { + if (!tmp.contains(transition.next)) { + tmp.add(transition.next); + transition.next.closure(tmp); + } + } + } + closure = new ArrayList(); + for (NFAState node : tmp) + closure.add(node); + } + return closure; + } - //////////////// - // Inner class - //////////////// + /** + * Calculates the possible set of states after a transition with the + * specified value + * + * @param label transition label + * @param output possible set of states (out) + */ + private void edge(int label, HashSet output) { + for (Transition transition : transitions) { + if (transition.label == label) { + if (!output.contains(transition.next)) { + output.add(transition.next); + transition.next.closure(output); + } + } + } + } - /* Represents a transition */ - private class Transition { - private int label; - private NFAState next; + /** + * Calculates the alphabet of this state. + * + * @param output alphabet (out) + */ + private void alphabet(HashSet output) { + for (NFAState node : closure()) { + for (Transition t : node.transitions) { + if (t.label != EPSILON) { + output.add(t.label); + } + } + } + } - public Transition(int input, NFAState next) { - this.label = input; - this.next = next; - } - } - } + // ////////////// + // Inner class + // ////////////// - /* Hashable set of nodes */ - private class NodeSet { - private NFAState[] nodes; + /* Represents a transition */ + private class Transition { + private int label; + private NFAState next; - public NodeSet(HashSet nodes) { - this.nodes = new NFAState[nodes.size()]; - int i = 0; - for (NFAState node : nodes) this.nodes[i++] = node; - Arrays.sort(this.nodes, new Comparator() { - public int compare(NFAState o1, NFAState o2) { - return o1.index - o2.index; - } - }); - } + public Transition(int input, NFAState next) { + this.label = input; + this.next = next; + } + } + } - @Override - public int hashCode() { - return Arrays.hashCode(nodes); - } + /* Hashable set of nodes */ + private class NodeSet { + private NFAState[] nodes; - @Override - public boolean equals(Object other) { - if (other.getClass() != NodeSet.class) return false; - return Arrays.equals(nodes, ((NodeSet)other).nodes); - } - } + public NodeSet(HashSet nodes) { + this.nodes = new NFAState[nodes.size()]; + int i = 0; + for (NFAState node : nodes) + this.nodes[i++] = node; + Arrays.sort(this.nodes, new Comparator() { + public int compare(NFAState o1, NFAState o2) { + return o1.index - o2.index; + } + }); + } - /** - * Contains a partially parsed regular expression. Has a head and a tail. - * - * The tail is a transition and thus has a label and a next node. The head - * is the 'final' state of the partial. - */ - private static class Partial { - private int tailLabel; - private NFAState tail; - private NFAState head; + @Override + public int hashCode() { + return Arrays.hashCode(nodes); + } - /** - * Creates a new partial - * @param tailLabel tail label - * @param tail tail node - * @param head head node - */ - public Partial(int tailLabel, NFAState tail, NFAState head) { - this.tailLabel = tailLabel; - this.tail = tail; - this.head = head; - } + @Override + public boolean equals(Object other) { + if (other.getClass() != NodeSet.class) + return false; + return Arrays.equals(nodes, ((NodeSet) other).nodes); + } + } - /** - * Duplicates the NFA of this partial. - * - * @return a duplicate of this partial - */ - public Partial duplicate() { - HashMap nodes = new HashMap(); + /** + * Contains a partially parsed regular expression. Has a head and a tail. + * + * The tail is a transition and thus has a label and a next node. The head + * is the 'final' state of the partial. + */ + private static class Partial { + private int tailLabel; + private NFAState tail; + private NFAState head; - Queue todo = new LinkedList(); - todo.add(tail); - nodes.put(tail, new NFAState()); - while (!todo.isEmpty()) { - NFAState node = todo.poll(); - for (NFAState.Transition t : node.transitions) { - if (!nodes.containsKey(t.next)) { - nodes.put(t.next, new NFAState()); - todo.add(t.next); - } - nodes.get(node).addTransition(t.label, nodes.get(t.next)); - } - } + /** + * Creates a new partial + * + * @param tailLabel tail label + * @param tail tail node + * @param head head node + */ + public Partial(int tailLabel, NFAState tail, NFAState head) { + this.tailLabel = tailLabel; + this.tail = tail; + this.head = head; + } - return new Partial(tailLabel, nodes.get(tail), nodes.get(head)); - } - } + /** + * Duplicates the NFA of this partial. + * + * @return a duplicate of this partial + */ + public Partial duplicate() { + HashMap nodes = new HashMap(); + + Queue todo = new LinkedList(); + todo.add(tail); + nodes.put(tail, new NFAState()); + while (!todo.isEmpty()) { + NFAState node = todo.poll(); + for (NFAState.Transition t : node.transitions) { + if (!nodes.containsKey(t.next)) { + nodes.put(t.next, new NFAState()); + todo.add(t.next); + } + nodes.get(node).addTransition(t.label, nodes.get(t.next)); + } + } + + return new Partial(tailLabel, nodes.get(tail), nodes.get(head)); + } + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/ParseException.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/ParseException.java index 74ffa00..2429c37 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/ParseException.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/ParseException.java @@ -15,43 +15,43 @@ public class ParseException extends RuntimeException { private final ZenParsedFile file; private final int line; private final int lineOffset; - + private final Token token; private final String message; - - public ParseException(Token token, String error) { - super("Error parsing line " + token.getPosition().getLine() + ":" + token.getPosition().getLineOffset() + " - " + error + " (last token: " + token.getValue() + ")"); - + + public ParseException(Token token, String error) { + super("Error parsing line " + token.getPosition().getLine() + ":" + token.getPosition().getLineOffset() + " - " + error + " (last token: " + token.getValue() + ")"); + this.file = token.getPosition().getFile(); this.line = token.getPosition().getLine(); this.lineOffset = token.getPosition().getLineOffset(); - - this.token = token; - this.message = error; - } - + + this.token = token; + this.message = error; + } + public ParseException(ZenParsedFile file, int line, int lineOffset, String error) { this.file = file; this.line = line; this.lineOffset = lineOffset; - + token = null; message = error; } - - public ZenParsedFile getFile() { - return file; - } - - public int getLine() { - return line; - } - - public int getLineOffset() { - return lineOffset; - } - - public String getExplanation() { - return message; - } + + public ZenParsedFile getFile() { + return file; + } + + public int getLine() { + return line; + } + + public int getLineOffset() { + return lineOffset; + } + + public String getExplanation() { + return message; + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/Token.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/Token.java index 519d846..7e91300 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/Token.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/Token.java @@ -14,46 +14,46 @@ import stanhebben.zenscript.util.ZenPosition; */ public class Token { private final ZenPosition position; - private final String value; - private final int type; + private final String value; + private final int type; - /** - * Constructs a new token. - * - * @param value token string value - * @param type token type + /** + * Constructs a new token. + * + * @param value token string value + * @param type token type * @param position token position - */ - public Token(String value, int type, ZenPosition position) { - this.value = value; - this.type = type; + */ + public Token(String value, int type, ZenPosition position) { + this.value = value; + this.type = type; this.position = position; - } - - public ZenPosition getPosition() { - return position; - } + } - /** - * Returns the string value of this token. - * - * @return token value - */ - public String getValue() { - return value; - } + public ZenPosition getPosition() { + return position; + } - /** - * Returns the token type of this token. - * - * @return token type - */ - public int getType() { - return type; - } + /** + * Returns the string value of this token. + * + * @return token value + */ + public String getValue() { + return value; + } - @Override - public String toString() { - return position.getLine() + ":" + position.getLineOffset() + " (" + type + ") " + value; - } + /** + * Returns the token type of this token. + * + * @return token type + */ + public int getType() { + return type; + } + + @Override + public String toString() { + return position.getLine() + ":" + position.getLineOffset() + " (" + type + ") " + value; + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/TokenException.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/TokenException.java index 06c08d0..9bd7170 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/TokenException.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/TokenException.java @@ -13,9 +13,10 @@ import stanhebben.zenscript.ZenParsedFile; * @author Stan Hebben */ public class TokenException extends RuntimeException { - public TokenException(ZenParsedFile file, int line, int lineOffset, char value) { - super("Invalid character at " + file + ":" + line + " - " + value); - - if (line < 0) throw new IllegalArgumentException("Line cannot be negative"); - } + public TokenException(ZenParsedFile file, int line, int lineOffset, char value) { + super("Invalid character at " + file + ":" + line + " - " + value); + + if (line < 0) + throw new IllegalArgumentException("Line cannot be negative"); + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/TokenStream.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/TokenStream.java index 1984416..ca3ca1a 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/TokenStream.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/TokenStream.java @@ -24,251 +24,252 @@ import stanhebben.zenscript.util.ZenPosition; */ public class TokenStream implements Iterator { private ZenParsedFile file; - - private CountingReader reader; - private CompiledDFA dfa; - private Token next; - private int nextChar; - private int line; - private int lineOffset; - private int tokenMemoryOffset; - private LinkedList tokenMemory; - private Stack marks; - private int tokenMemoryCurrent; - - /** - * Creates a token stream using the specified reader and DFA. - * - * @param reader reader to read characters from - * @param dfa DFA to tokenize the stream - * @throws IOException - */ - public TokenStream(Reader reader, CompiledDFA dfa) throws IOException { - tokenMemoryOffset = 0; - tokenMemoryCurrent = 0; - tokenMemory = new LinkedList(); - marks = new Stack(); - - this.reader = new CountingReader(reader); - this.dfa = dfa; - nextChar = this.reader.read(); - line = 1; - lineOffset = 1; - advance(); - } + private CountingReader reader; + private CompiledDFA dfa; + private Token next; + private int nextChar; + private int line; + private int lineOffset; + + private int tokenMemoryOffset; + private LinkedList tokenMemory; + private Stack marks; + private int tokenMemoryCurrent; + + /** + * Creates a token stream using the specified reader and DFA. + * + * @param reader reader to read characters from + * @param dfa DFA to tokenize the stream + * @throws IOException + */ + public TokenStream(Reader reader, CompiledDFA dfa) throws IOException { + tokenMemoryOffset = 0; + tokenMemoryCurrent = 0; + tokenMemory = new LinkedList(); + marks = new Stack(); + + this.reader = new CountingReader(reader); + this.dfa = dfa; + nextChar = this.reader.read(); + line = 1; + lineOffset = 1; + advance(); + } + + /** + * Creates a token stream which reads data from the specified string. + * + * @param data data to read + * @param dfa DFA to tokenize the stream + * @throws IOException + */ + public TokenStream(String data, CompiledDFA dfa) throws IOException { + this(new StringReader(data), dfa); + } - /** - * Creates a token stream which reads data from the specified string. - * - * @param data data to read - * @param dfa DFA to tokenize the stream - * @throws IOException - */ - public TokenStream(String data, CompiledDFA dfa) throws IOException { - this(new StringReader(data), dfa); - } - public void setFile(ZenParsedFile file) { this.file = file; } - + public ZenParsedFile getFile() { return file; } - + public int getLine() { return line; } - + public int getLineOffset() { return lineOffset; } - - public Token peek() { - if (tokenMemoryCurrent < tokenMemoryOffset + tokenMemory.size()) { - return tokenMemory.get((tokenMemoryCurrent) - tokenMemoryOffset); - } else { - return next; - } - } - public boolean isNext(int type) { - return peek().getType() == type; - } + public Token peek() { + if (tokenMemoryCurrent < tokenMemoryOffset + tokenMemory.size()) { + return tokenMemory.get((tokenMemoryCurrent) - tokenMemoryOffset); + } else { + return next; + } + } - public Token optional(int type) { - if (peek() != null && peek().getType() == type) { - return next(); - } else { - return null; - } - } + public boolean isNext(int type) { + return peek().getType() == type; + } - public Token required(int type, String error) { + public Token optional(int type) { + if (peek() != null && peek().getType() == type) { + return next(); + } else { + return null; + } + } + + public Token required(int type, String error) { Token t = peek(); - if (t != null && t.getType() == type) { - return next(); - } else { - throw new ParseException(file, line, lineOffset, error); - } - } + if (t != null && t.getType() == type) { + return next(); + } else { + throw new ParseException(file, line, lineOffset, error); + } + } - // LL(*) ability + // LL(*) ability - /** - * Pushes a mark on the mark stack. - */ - public void pushMark() { - marks.push(tokenMemoryCurrent); - } + /** + * Pushes a mark on the mark stack. + */ + public void pushMark() { + marks.push(tokenMemoryCurrent); + } - /** - * Pops a mark from the mark stack without reset. - */ - public void popMark() { - marks.pop(); + /** + * Pops a mark from the mark stack without reset. + */ + public void popMark() { + marks.pop(); - if (marks.isEmpty()) { - tokenMemoryOffset = tokenMemoryCurrent; - tokenMemory.clear(); - } - } + if (marks.isEmpty()) { + tokenMemoryOffset = tokenMemoryCurrent; + tokenMemory.clear(); + } + } - /** - * Pops a mark from the mark stack and resets the stream's position to it - */ - public void reset() { - tokenMemoryCurrent = marks.pop(); - } + /** + * Pops a mark from the mark stack and resets the stream's position to it + */ + public void reset() { + tokenMemoryCurrent = marks.pop(); + } + // ////////////////////////// + // Iterator implementation + // ////////////////////////// - //////////////////////////// - // Iterator implementation - //////////////////////////// + public boolean hasNext() { + return next != null; + } - public boolean hasNext() { - return next != null; - } + public Token next() { + if (tokenMemoryCurrent < tokenMemoryOffset + tokenMemory.size()) { + return tokenMemory.get((tokenMemoryCurrent++) - tokenMemoryOffset); + } else { + Token result = next; - public Token next() { - if (tokenMemoryCurrent < tokenMemoryOffset + tokenMemory.size()) { - return tokenMemory.get((tokenMemoryCurrent++) - tokenMemoryOffset); - } else { - Token result = next; + if (marks.isEmpty()) { + tokenMemoryOffset++; + } else { + tokenMemory.add(result); + } + tokenMemoryCurrent++; - if (marks.isEmpty()) { - tokenMemoryOffset++; - } else { - tokenMemory.add(result); - } - tokenMemoryCurrent++; + advance(); + return result; + } + } - advance(); - return result; - } - } + public void remove() { + throw new UnsupportedOperationException("Not supported."); + } - public void remove() { - throw new UnsupportedOperationException("Not supported."); - } + // //////////////////// + // Protected methods + // //////////////////// - ////////////////////// - // Protected methods - ////////////////////// + /** + * Can be implemented by subclasses to post-process tokens. + * + * @param token + * @return processed token + */ + protected Token process(Token token) { + return token; + } - /** - * Can be implemented by subclasses to post-process tokens. - * - * @param token - * @return processed token - */ - protected Token process(Token token) { - return token; - } + // ////////////////// + // Private methods + // ////////////////// - //////////////////// - // Private methods - //////////////////// + /** + * Advances to the next non - whitespace token. + */ + private void advance() { + do { + advanceToken(); + } while (next != null && next.getType() < 0); + } - /** - * Advances to the next non - whitespace token. - */ - private void advance() { - do { - advanceToken(); - } while (next != null && next.getType() < 0); - } + /** + * Advances to the next token. + */ + private void advanceToken() { + if (nextChar < 0) { + next = null; + return; + } + try { + int state = 0; + StringBuilder value = new StringBuilder(); + int tLine = line; + int tLineOffset = lineOffset; + while (dfa.transitions[state].containsKey(nextChar)) { + value.append((char) nextChar); + state = dfa.transitions[state].get(nextChar); + line = reader.line; + lineOffset = reader.lineOffset; + nextChar = reader.read(); + } - /** - * Advances to the next token. - */ - private void advanceToken() { - if (nextChar < 0) { - next = null; - return; - } - try { - int state = 0; - StringBuilder value = new StringBuilder(); - int tLine = line; - int tLineOffset = lineOffset; - while (dfa.transitions[state].containsKey(nextChar)) { - value.append((char)nextChar); - state = dfa.transitions[state].get(nextChar); - line = reader.line; - lineOffset = reader.lineOffset; - nextChar = reader.read(); - } - - if (line < 0) throw new IllegalStateException("Line cannot be negative"); - - if (dfa.finals[state] != CompiledDFA.NOFINAL) { - if (state == 0) throw new TokenException(file, line, lineOffset, (char)nextChar); - next = process(new Token(value.toString(), dfa.finals[state], new ZenPosition(file, tLine, tLineOffset))); - } else { + if (line < 0) + throw new IllegalStateException("Line cannot be negative"); + + if (dfa.finals[state] != CompiledDFA.NOFINAL) { + if (state == 0) + throw new TokenException(file, line, lineOffset, (char) nextChar); + next = process(new Token(value.toString(), dfa.finals[state], new ZenPosition(file, tLine, tLineOffset))); + } else { if (nextChar < 0 && value.length() == 0) { return; // happens on comments at the end of files } - throw new TokenException(file, line, lineOffset, (char)nextChar); - } - } catch (IOException ex) { - ex.printStackTrace(); - } - } + throw new TokenException(file, line, lineOffset, (char) nextChar); + } + } catch (IOException ex) { + ex.printStackTrace(); + } + } - ////////////////////////// - // Private inner classes - ////////////////////////// + // //////////////////////// + // Private inner classes + // //////////////////////// - /** - * Keeps a line and line offset count. - */ - private class CountingReader { - private int line; - private int lineOffset; - private Reader reader; - private boolean eof; + /** + * Keeps a line and line offset count. + */ + private class CountingReader { + private int line; + private int lineOffset; + private Reader reader; + private boolean eof; - public CountingReader(Reader reader) { - this.reader = reader; - line = 1; - lineOffset = 1; - } + public CountingReader(Reader reader) { + this.reader = reader; + line = 1; + lineOffset = 1; + } - public int read() throws IOException { - int ch = reader.read(); - if (ch == -1) { - eof = true; - return ch; - } - if (ch == '\n') { - line++; - lineOffset = 1; - } else { - lineOffset++; - } - return ch; - } - } + public int read() throws IOException { + int ch = reader.read(); + if (ch == -1) { + eof = true; + return ch; + } + if (ch == '\n') { + line++; + lineOffset = 1; + } else { + lineOffset++; + } + return ch; + } + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpression.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpression.java index e457db1..caa1b12 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpression.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpression.java @@ -39,7 +39,7 @@ public abstract class ParsedExpression { public static ParsedExpression read(ZenTokener parser, IEnvironmentGlobal environment) { return readAssignExpression(parser, environment); } - + private static ParsedExpression readAssignExpression(ZenTokener parser, IEnvironmentGlobal environment) { Token token = parser.peek(); if (token == null) { @@ -47,17 +47,17 @@ public abstract class ParsedExpression { environment.error(position, "unexpected end of file; expression expected"); return new ParsedExpressionInvalid(position); } - + ZenPosition position = token.getPosition(); - + ParsedExpression left = readConditionalExpression(position, parser, environment); - + if (parser.peek() == null) { ZenPosition position2 = new ZenPosition(parser.getFile(), parser.getLine(), parser.getLineOffset()); environment.error(position2, "unexpected end of file - ; expected"); return new ParsedExpressionInvalid(position2); } - + switch (parser.peek().getType()) { case T_ASSIGN: parser.next(); @@ -90,76 +90,76 @@ public abstract class ParsedExpression { parser.next(); return new ParsedExpressionOpAssign(position, left, readAssignExpression(parser, environment), OperatorType.XOR); } - + return left; } - + private static ParsedExpression readConditionalExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readOrOrExpression(position, parser, environment); - + if (parser.optional(T_QUEST) != null) { ParsedExpression onIf = readOrOrExpression(parser.peek().getPosition(), parser, environment); parser.required(T_COLON, ": expected"); ParsedExpression onElse = readConditionalExpression(parser.peek().getPosition(), parser, environment); return new ParsedExpressionConditional(position, left, onIf, onElse); } - + return left; } - + private static ParsedExpression readOrOrExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readAndAndExpression(position, parser, environment); - + while (parser.optional(T_OR2) != null) { ParsedExpression right = readAndAndExpression(parser.peek().getPosition(), parser, environment); left = new ParsedExpressionOrOr(position, left, right); } return left; } - + private static ParsedExpression readAndAndExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readOrExpression(position, parser, environment); - + while (parser.optional(T_AND2) != null) { ParsedExpression right = readOrExpression(parser.peek().getPosition(), parser, environment); left = new ParsedExpressionAndAnd(position, left, right); } return left; } - + private static ParsedExpression readOrExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readXorExpression(position, parser, environment); - + while (parser.optional(T_OR) != null) { ParsedExpression right = readXorExpression(parser.peek().getPosition(), parser, environment); left = new ParsedExpressionBinary(position, left, right, OperatorType.OR); } return left; } - + private static ParsedExpression readXorExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readAndExpression(position, parser, environment); - + while (parser.optional(T_XOR) != null) { ParsedExpression right = readAndExpression(parser.peek().getPosition(), parser, environment); left = new ParsedExpressionBinary(position, left, right, OperatorType.XOR); } return left; } - + private static ParsedExpression readAndExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readCompareExpression(position, parser, environment); - + while (parser.optional(T_AND) != null) { ParsedExpression right = readCompareExpression(parser.peek().getPosition(), parser, environment); left = new ParsedExpressionBinary(position, left, right, OperatorType.AND); } return left; } - + private static ParsedExpression readCompareExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readAddExpression(position, parser, environment); - + switch (parser.peek() == null ? -1 : parser.peek().getType()) { case T_EQ: { parser.next(); @@ -197,13 +197,13 @@ public abstract class ParsedExpression { return new ParsedExpressionBinary(position, left, right, OperatorType.CONTAINS); } } - + return left; } - + private static ParsedExpression readAddExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readMulExpression(position, parser, environment); - + while (true) { if (parser.optional(T_PLUS) != null) { ParsedExpression right = readMulExpression(parser.peek().getPosition(), parser, environment); @@ -220,10 +220,10 @@ public abstract class ParsedExpression { } return left; } - + private static ParsedExpression readMulExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression left = readUnaryExpression(position, parser, environment); - + while (true) { if (parser.optional(T_MUL) != null) { ParsedExpression right = readUnaryExpression(parser.peek().getPosition(), parser, environment); @@ -238,10 +238,10 @@ public abstract class ParsedExpression { break; } } - + return left; } - + private static ParsedExpression readUnaryExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { switch (parser.peek().getType()) { case T_NOT: @@ -260,10 +260,10 @@ public abstract class ParsedExpression { return readPostfixExpression(position, parser, environment); } } - + private static ParsedExpression readPostfixExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { ParsedExpression base = readPrimaryExpression(position, parser, environment); - + while (true) { if (parser.optional(T_DOT) != null) { Token indexString = parser.optional(T_ID); @@ -279,8 +279,8 @@ public abstract class ParsedExpression { } } } else if (parser.optional(T_DOT2) != null) { - //ParsedExpression to = readAssignExpression(parser, errors); - //base = base.range(position, errors, to); + // ParsedExpression to = readAssignExpression(parser, errors); + // base = base.range(position, errors, to); throw new RuntimeException("not yet supported"); } else if (parser.optional(T_SQBROPEN) != null) { ParsedExpression index = readAssignExpression(parser, environment); @@ -303,10 +303,10 @@ public abstract class ParsedExpression { break; } } - + return base; } - + private static ParsedExpression readPrimaryExpression(ZenPosition position, ZenTokener parser, IEnvironmentGlobal environment) { switch (parser.peek().getType()) { case T_INTVALUE: @@ -321,20 +321,19 @@ public abstract class ParsedExpression { return new ParsedExpressionValue( position, new ExpressionString(position, unescapeString(parser.next().getValue()))); - /*case T_DOLLAR: { - Expression result = new ExpressionDollar(position); - if (parser.isNext(T_STRINGVALUE)) { - return new ExpressionIndexString(position, result, unescapeString(parser.next().getValue())); - } - return result; - }*/ + /* + * case T_DOLLAR: { Expression result = new + * ExpressionDollar(position); if (parser.isNext(T_STRINGVALUE)) + * { return new ExpressionIndexString(position, result, + * unescapeString(parser.next().getValue())); } return result; } + */ case T_ID: return new ParsedExpressionVariable(position, parser.next().getValue()); case T_FUNCTION: // function (argname, argname, ...) { ...contents... } parser.next(); parser.required(T_BROPEN, "( expected"); - + List arguments = new ArrayList(); if (parser.optional(T_BRCLOSE) == null) { do { @@ -344,27 +343,27 @@ public abstract class ParsedExpression { if (parser.optional(T_AS) != null) { type = ZenType.read(parser, environment); } - + arguments.add(new ParsedFunctionArgument(name, type)); } while (parser.optional(T_COMMA) != null); - + parser.required(T_BRCLOSE, ") expected"); } - + ZenType returnType = ZenTypeAny.INSTANCE; if (parser.optional(T_AS) != null) { returnType = ZenType.read(parser, environment); } - + parser.required(T_AOPEN, "{ expected"); - + List statements = new ArrayList(); if (parser.optional(T_ACLOSE) == null) { while (parser.optional(T_ACLOSE) == null) { statements.add(Statement.read(parser, environment, returnType)); } } - + return new ParsedExpressionFunction(position, returnType, arguments, statements); case T_LT: { Token start = parser.next(); @@ -380,12 +379,13 @@ public abstract class ParsedExpression { builder.append('<'); Token last = null; for (Token token : tokens) { - if (last != null) builder.append(' '); + if (last != null) + builder.append(' '); builder.append(token.getValue()); last = token; } builder.append('>'); - + parser.getEnvironment().getErrorLogger().error(start.getPosition(), "Could not resolve " + builder.toString()); return new ParsedExpressionInvalid(start.getPosition()); } else { @@ -410,7 +410,7 @@ public abstract class ParsedExpression { } case T_AOPEN: { parser.next(); - + List keys = new ArrayList(); List values = new ArrayList(); if (parser.optional(T_ACLOSE) == null) { @@ -418,13 +418,13 @@ public abstract class ParsedExpression { keys.add(readAssignExpression(parser, environment)); parser.required(T_COLON, ": expected"); values.add(readAssignExpression(parser, environment)); - + if (parser.optional(T_COMMA) == null) { parser.required(T_ACLOSE, "} or , expected"); break; } } - + return new ParsedExpressionMap(position, keys, values); } } @@ -447,18 +447,19 @@ public abstract class ParsedExpression { throw new ParseException(last, "Invalid expression, last token: " + last.getValue()); } } + private final ZenPosition position; - + public ParsedExpression(ZenPosition position) { this.position = position; } - + public ZenPosition getPosition() { return position; } - + public abstract IPartialExpression compile(IEnvironmentMethod environment, ZenType predictedType); - + public Expression compileKey(IEnvironmentMethod environment, ZenType predictedType) { return compile(environment, predictedType).eval(environment); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionAndAnd.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionAndAnd.java index e235946..1e2c784 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionAndAnd.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionAndAnd.java @@ -19,10 +19,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionAndAnd extends ParsedExpression { private final ParsedExpression left; private final ParsedExpression right; - + public ParsedExpressionAndAnd(ZenPosition position, ParsedExpression left, ParsedExpression right) { super(position); - + this.left = left; this.right = right; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionArray.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionArray.java index aad6ebe..791eccc 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionArray.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionArray.java @@ -25,10 +25,10 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ParsedExpressionArray extends ParsedExpression { private final List contents; - + public ParsedExpressionArray(ZenPosition position, List contents) { super(position); - + this.contents = contents; } @@ -37,7 +37,7 @@ public class ParsedExpressionArray extends ParsedExpression { ZenType predictedBaseType = null; ZenTypeArrayBasic arrayType = ZenType.ANYARRAY; ICastingRule castingRule = null; - + if (predictedType instanceof ZenTypeArray) { predictedBaseType = ((ZenTypeArray) predictedType).getBaseType(); if (predictedType instanceof ZenTypeArrayBasic) { @@ -60,7 +60,7 @@ public class ParsedExpressionArray extends ParsedExpression { } } } - + Expression[] cContents = new Expression[contents.size()]; for (int i = 0; i < contents.size(); i++) { cContents[i] = contents.get(i).compile(environment, predictedBaseType).eval(environment); @@ -72,7 +72,7 @@ public class ParsedExpressionArray extends ParsedExpression { return result; } } - + @Override public Expression compileKey(IEnvironmentMethod environment, ZenType predictedType) { if (contents.size() == 1 && contents.get(0) instanceof ParsedExpressionVariable) { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionAssign.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionAssign.java index 31e9478..1a2e400 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionAssign.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionAssign.java @@ -18,19 +18,19 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionAssign extends ParsedExpression { private final ParsedExpression left; private final ParsedExpression right; - + public ParsedExpressionAssign(ZenPosition position, ParsedExpression left, ParsedExpression right) { super(position); - + this.left = left; this.right = right; } - + @Override public IPartialExpression compile(IEnvironmentMethod environment, ZenType predictedType) { IPartialExpression cLeft = left.compile(environment, predictedType); return cLeft - .assign(getPosition(), environment, - right.compile(environment, cLeft.getType()).eval(environment)); + .assign(getPosition(), environment, + right.compile(environment, cLeft.getType()).eval(environment)); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionBinary.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionBinary.java index d79dd02..6d9519a 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionBinary.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionBinary.java @@ -21,10 +21,10 @@ public class ParsedExpressionBinary extends ParsedExpression { private final ParsedExpression left; private final ParsedExpression right; private final OperatorType operator; - + public ParsedExpressionBinary(ZenPosition position, ParsedExpression left, ParsedExpression right, OperatorType operator) { super(position); - + this.left = left; this.right = right; this.operator = operator; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionBool.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionBool.java index 3f9d425..0cec3db 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionBool.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionBool.java @@ -18,10 +18,10 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ParsedExpressionBool extends ParsedExpression { private final boolean value; - + public ParsedExpressionBool(ZenPosition position, boolean value) { super(position); - + this.value = value; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCall.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCall.java index 21bd875..5e4443f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCall.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCall.java @@ -20,25 +20,25 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionCall extends ParsedExpression { private final ParsedExpression receiver; private final List arguments; - + public ParsedExpressionCall(ZenPosition position, ParsedExpression receiver, List arguments) { super(position); - + this.receiver = receiver; this.arguments = arguments; } - + @Override public IPartialExpression compile(IEnvironmentMethod environment, ZenType predictedType) { IPartialExpression cReceiver = receiver.compile(environment, null); ZenType[] predictedTypes = cReceiver.predictCallTypes(arguments.size()); - + Expression[] cArguments = new Expression[arguments.size()]; for (int i = 0; i < cArguments.length; i++) { IPartialExpression cArgument = arguments.get(i).compile(environment, predictedTypes[i]); cArguments[i] = cArgument.eval(environment); } - + return cReceiver.call(getPosition(), environment, cArguments); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCast.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCast.java index b779110..98f3432 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCast.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCast.java @@ -18,10 +18,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionCast extends ParsedExpression { private final ParsedExpression value; private final ZenType type; - + public ParsedExpressionCast(ZenPosition position, ParsedExpression value, ZenType type) { super(position); - + this.value = value; this.type = type; } @@ -29,8 +29,8 @@ public class ParsedExpressionCast extends ParsedExpression { @Override public IPartialExpression compile(IEnvironmentMethod environment, ZenType predictedType) { return value - .compile(environment, type) - .eval(environment) - .cast(getPosition(), environment, type); + .compile(environment, type) + .eval(environment) + .cast(getPosition(), environment, type); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCompare.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCompare.java index 6a4ce97..ea484ed 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCompare.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionCompare.java @@ -21,14 +21,14 @@ public class ParsedExpressionCompare extends ParsedExpression { private final ParsedExpression left; private final ParsedExpression right; private final CompareType type; - + public ParsedExpressionCompare( ZenPosition position, ParsedExpression left, ParsedExpression right, CompareType type) { super(position); - + this.left = left; this.right = right; this.type = type; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionConditional.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionConditional.java index dffb03d..2e7e778 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionConditional.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionConditional.java @@ -20,10 +20,10 @@ public class ParsedExpressionConditional extends ParsedExpression { private final ParsedExpression condition; private final ParsedExpression ifThen; private final ParsedExpression ifElse; - + public ParsedExpressionConditional(ZenPosition position, ParsedExpression condition, ParsedExpression ifThen, ParsedExpression ifElse) { super(position); - + this.condition = condition; this.ifThen = ifThen; this.ifElse = ifElse; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionFunction.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionFunction.java index 4183170..41ad7e4 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionFunction.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionFunction.java @@ -28,10 +28,10 @@ public class ParsedExpressionFunction extends ParsedExpression { private final ZenType returnType; private final List arguments; private final List statements; - + public ParsedExpressionFunction(ZenPosition position, ZenType returnType, List arguments, List statements) { super(position); - + this.returnType = returnType; this.arguments = arguments; this.statements = statements; @@ -41,7 +41,7 @@ public class ParsedExpressionFunction extends ParsedExpression { public IPartialExpression compile(IEnvironmentMethod environment, ZenType predictedType) { if (predictedType != null && predictedType instanceof ZenTypeNative) { System.out.println("Known predicted function type: " + predictedType); - + ZenTypeNative nativeType = (ZenTypeNative) predictedType; Class nativeClass = nativeType.getNativeClass(); if (nativeClass.isInterface() && nativeClass.getMethods().length == 1) { @@ -64,7 +64,7 @@ public class ParsedExpressionFunction extends ParsedExpression { return new ExpressionInvalid(getPosition()); } } - + return new ExpressionJavaLambda( getPosition(), nativeClass, diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionIndex.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionIndex.java index a61463c..c98728e 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionIndex.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionIndex.java @@ -20,10 +20,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionIndex extends ParsedExpression { private final ParsedExpression value; private final ParsedExpression index; - + public ParsedExpressionIndex(ZenPosition position, ParsedExpression value, ParsedExpression index) { super(position); - + this.value = value; this.index = index; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionIndexSet.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionIndexSet.java index 0a27e99..52e222a 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionIndexSet.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionIndexSet.java @@ -21,10 +21,10 @@ public class ParsedExpressionIndexSet extends ParsedExpression { private final ParsedExpression value; private final ParsedExpression index; private final ParsedExpression setValue; - + public ParsedExpressionIndexSet(ZenPosition position, ParsedExpression value, ParsedExpression index, ParsedExpression setValue) { super(position); - + this.value = value; this.index = index; this.setValue = setValue; @@ -36,6 +36,6 @@ public class ParsedExpressionIndexSet extends ParsedExpression { Expression cValue = value.compile(environment, null).eval(environment); Expression cIndex = index.compile(environment, null).eval(environment); Expression cSetValue = setValue.compile(environment, null).eval(environment); - return cValue.getType().trinary(getPosition(), environment, cValue, cIndex, cSetValue,OperatorType.INDEXSET); - } + return cValue.getType().trinary(getPosition(), environment, cValue, cIndex, cSetValue, OperatorType.INDEXSET); + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionMap.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionMap.java index c119e9d..375c614 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionMap.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionMap.java @@ -24,13 +24,13 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionMap extends ParsedExpression { private final List keys; private final List values; - + public ParsedExpressionMap( ZenPosition position, List keys, List values) { super(position); - + this.keys = keys; this.values = values; } @@ -41,7 +41,7 @@ public class ParsedExpressionMap extends ParsedExpression { ZenType predictedValueType = null; ICastingRule castingRule = null; ZenTypeAssociative mapType = ZenType.ANYMAP; - + if (predictedType instanceof ZenTypeAssociative) { ZenTypeAssociative inputType = (ZenTypeAssociative) predictedType; predictedKeyType = inputType.getKeyType(); @@ -60,15 +60,15 @@ public class ParsedExpressionMap extends ParsedExpression { } } } - + Expression[] cKeys = new Expression[keys.size()]; Expression[] cValues = new Expression[values.size()]; - + for (int i = 0; i < keys.size(); i++) { cKeys[i] = keys.get(i).compileKey(environment, predictedKeyType); cValues[i] = values.get(i).compile(environment, predictedValueType).eval(environment); } - + Expression result = new ExpressionMap(getPosition(), cKeys, cValues, mapType); if (castingRule != null) { return new ExpressionAs(getPosition(), result, castingRule); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionMember.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionMember.java index 2924128..614c1ab 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionMember.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionMember.java @@ -18,10 +18,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionMember extends ParsedExpression { private final ParsedExpression value; private final String member; - + public ParsedExpressionMember(ZenPosition position, ParsedExpression value, String member) { super(position); - + this.value = value; this.member = member; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionOpAssign.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionOpAssign.java index 49b2ae0..f0d4092 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionOpAssign.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionOpAssign.java @@ -21,23 +21,23 @@ public class ParsedExpressionOpAssign extends ParsedExpression { private final ParsedExpression left; private final ParsedExpression right; private final OperatorType operator; - + public ParsedExpressionOpAssign(ZenPosition position, ParsedExpression left, ParsedExpression right, OperatorType operator) { super(position); - + this.left = left; this.right = right; this.operator = operator; } - + @Override public IPartialExpression compile(IEnvironmentMethod environment, ZenType predictedType) { // TODO: validate if the prediction rules are sound Expression cLeft = left.compile(environment, predictedType).eval(environment); Expression cRight = right.compile(environment, cLeft.getType()).eval(environment); - + Expression value = cLeft.getType().binary(getPosition(), environment, cLeft, cRight, operator); - + return left.compile(environment, predictedType).assign(getPosition(), environment, value); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionOrOr.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionOrOr.java index 3a49767..1241aec 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionOrOr.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionOrOr.java @@ -20,10 +20,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionOrOr extends ParsedExpression { private final ParsedExpression left; private final ParsedExpression right; - + public ParsedExpressionOrOr(ZenPosition position, ParsedExpression left, ParsedExpression right) { super(position); - + this.left = left; this.right = right; } @@ -32,7 +32,7 @@ public class ParsedExpressionOrOr extends ParsedExpression { public IPartialExpression compile(IEnvironmentMethod environment, ZenType predictedType) { Expression cLeft = left.compile(environment, predictedType).eval(environment); Expression cRight = right.compile(environment, predictedType).eval(environment); - + ZenType type; if (cRight.getType().canCastImplicit(cLeft.getType(), environment)) { type = cLeft.getType(); @@ -42,7 +42,7 @@ public class ParsedExpressionOrOr extends ParsedExpression { environment.error(getPosition(), "These types could not be unified: " + cLeft.getType() + " and " + cRight.getType()); type = ZenType.ANY; } - + return new ExpressionOrOr( getPosition(), cLeft.cast(getPosition(), environment, type), diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionUnary.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionUnary.java index 2aa4448..9e80c55 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionUnary.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionUnary.java @@ -20,10 +20,10 @@ import stanhebben.zenscript.util.ZenPosition; public class ParsedExpressionUnary extends ParsedExpression { private final ParsedExpression value; private final OperatorType operator; - + public ParsedExpressionUnary(ZenPosition position, ParsedExpression value, OperatorType operator) { super(position); - + this.value = value; this.operator = operator; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionValue.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionValue.java index 6ac458c..2bc5bad 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionValue.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionValue.java @@ -17,12 +17,13 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ParsedExpressionValue extends ParsedExpression { private final IPartialExpression value; - + public ParsedExpressionValue(ZenPosition position, IPartialExpression value) { super(position); - - if (value == null) throw new IllegalArgumentException("value cannot be null"); - + + if (value == null) + throw new IllegalArgumentException("value cannot be null"); + this.value = value; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionVariable.java b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionVariable.java index 267b704..bca98ee 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionVariable.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/parser/expression/ParsedExpressionVariable.java @@ -20,10 +20,10 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ParsedExpressionVariable extends ParsedExpression { private final String name; - + public ParsedExpressionVariable(ZenPosition position, String name) { super(position); - + this.name = name; } @@ -35,8 +35,9 @@ public class ParsedExpressionVariable extends ParsedExpression { environment.error(getPosition(), "could not find " + name); return new ExpressionInvalid(getPosition()); } - - // enable usage of static members of the same type as the predicted type (eg. enum values) + + // enable usage of static members of the same type as the predicted + // type (eg. enum values) IPartialExpression member = predictedType.getStaticMember(getPosition(), environment, name); if (member == null || member.getType().getCastingRule(predictedType, environment) == null) { environment.error(getPosition(), "could not find " + name); @@ -48,7 +49,7 @@ public class ParsedExpressionVariable extends ParsedExpression { return result; } } - + @Override public Expression compileKey(IEnvironmentMethod environment, ZenType predictedType) { return new ExpressionString(getPosition(), name); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/statements/Statement.java b/ZenScript/src/main/java/stanhebben/zenscript/statements/Statement.java index c1415e4..4ab266c 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/statements/Statement.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/statements/Statement.java @@ -34,7 +34,7 @@ public abstract class Statement { case T_VAL: { Token start = parser.next(); String name = parser.required(T_ID, "identifier expected").getValue(); - + ZenType type = null; ParsedExpression initializer = null; if (parser.optional(T_AS) != null) { @@ -61,11 +61,11 @@ public abstract class Statement { String name = parser.required(T_ID, "identifier expected").getValue(); List names = new ArrayList(); names.add(name); - + while (parser.optional(T_COMMA) != null) { names.add(parser.required(T_ID, "identifier expected").getValue()); } - + parser.required(T_IN, "in expected"); ParsedExpression source = ParsedExpression.read(parser, environment); Statement content = read(parser, environment, null); @@ -78,33 +78,33 @@ public abstract class Statement { case T_VERSION: { Token t = parser.next(); parser.required(T_INTVALUE, "integer expected"); - - //MineTweaker.logWarning("The version statement is no longer necessary"); - + + // MineTweaker.logWarning("The version statement is no longer necessary"); + parser.required(T_SEMICOLON, "; expected"); return new StatementNull(t.getPosition()); } } - + ZenPosition position = parser.peek().getPosition(); StatementExpression result = new StatementExpression(position, ParsedExpression.read(parser, environment)); parser.required(T_SEMICOLON, "; expected"); return result; } - + private final ZenPosition position; - + public Statement(ZenPosition position) { this.position = position; } - + public ZenPosition getPosition() { return position; } - + public boolean isReturn() { return false; } - + public abstract void compile(IEnvironmentMethod environment); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementBlock.java b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementBlock.java index babcd58..4878c58 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementBlock.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementBlock.java @@ -7,10 +7,10 @@ import stanhebben.zenscript.util.ZenPosition; public class StatementBlock extends Statement { private final List statements; - + public StatementBlock(ZenPosition position, List statements) { super(position); - + this.statements = statements; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementForeach.java b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementForeach.java index 33edfda..7fbbd66 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementForeach.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementForeach.java @@ -15,10 +15,10 @@ public class StatementForeach extends Statement { private final String[] varnames; private final ParsedExpression list; private final Statement body; - + public StatementForeach(ZenPosition position, String[] varnames, ParsedExpression list, Statement body) { super(position); - + this.varnames = varnames; this.list = list; this.body = body; @@ -28,16 +28,16 @@ public class StatementForeach extends Statement { public void compile(IEnvironmentMethod environment) { Expression cList = list.compile(environment, ZenType.ANYARRAY).eval(environment); ZenType listType = cList.getType(); - + IZenIterator iterator = listType.makeIterator(varnames.length, environment); if (iterator == null) { environment.error(getPosition(), "No iterator with " + varnames.length + " variables"); return; } - + MethodOutput methodOutput = environment.getOutput(); environment.getOutput().position(getPosition()); - + IEnvironmentMethod local = new EnvironmentScope(environment); int[] localVariables = new int[varnames.length]; for (int i = 0; i < localVariables.length; i++) { @@ -45,13 +45,13 @@ public class StatementForeach extends Statement { local.putValue(varnames[i], localVar, getPosition()); localVariables[i] = local.getLocal(localVar); } - + cList.compile(true, environment); iterator.compileStart(localVariables); - + Label repeat = new Label(); Label exit = new Label(); - + methodOutput.label(repeat); iterator.compilePreIterate(localVariables, exit); body.compile(local); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementIf.java b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementIf.java index 94c42e7..2cccf76 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementIf.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementIf.java @@ -12,10 +12,10 @@ public class StatementIf extends Statement { private final ParsedExpression condition; private final Statement onThen; private final Statement onElse; - + public StatementIf(ZenPosition position, ParsedExpression condition, Statement onThen, Statement onElse) { super(position); - + this.condition = condition; this.onThen = onThen; this.onElse = onElse; @@ -24,26 +24,26 @@ public class StatementIf extends Statement { @Override public void compile(IEnvironmentMethod environment) { environment.getOutput().position(getPosition()); - + Expression cCondition = condition.compile(environment, ZenType.BOOL) - .eval(environment) - .cast(getPosition(), environment, ZenType.BOOL); - + .eval(environment) + .cast(getPosition(), environment, ZenType.BOOL); + ZenType expressionType = cCondition.getType(); if (expressionType.canCastImplicit(ZenType.BOOL, environment)) { Label labelEnd = new Label(); Label labelElse = onElse == null ? labelEnd : new Label(); - + cCondition.compileIf(labelElse, environment); onThen.compile(environment); - + MethodOutput methodOutput = environment.getOutput(); if (onElse != null) { methodOutput.goTo(labelEnd); methodOutput.label(labelElse); onElse.compile(environment); } - + methodOutput.label(labelEnd); } else { environment.error(getPosition(), "condition is not a boolean"); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementNull.java b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementNull.java index c6e6eb3..cd11d0c 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementNull.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementNull.java @@ -20,6 +20,6 @@ public class StatementNull extends Statement { @Override public void compile(IEnvironmentMethod environment) { - + } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementReturn.java b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementReturn.java index a56aacb..f4b222d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementReturn.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementReturn.java @@ -10,18 +10,18 @@ import stanhebben.zenscript.util.ZenPosition; public class StatementReturn extends Statement { private final ZenType returnType; private final ParsedExpression expression; - + public StatementReturn(ZenPosition position, ZenType returnType, ParsedExpression expression) { super(position); - + this.returnType = returnType; this.expression = expression; } - + public ParsedExpression getExpression() { return expression; } - + @Override public boolean isReturn() { return false; @@ -30,13 +30,13 @@ public class StatementReturn extends Statement { @Override public void compile(IEnvironmentMethod environment) { environment.getOutput().position(getPosition()); - + if (expression == null) { environment.getOutput().ret(); } else { Expression cExpression = expression.compile(environment, returnType).eval(environment); cExpression.compile(true, environment); - + Type returnType = cExpression.getType().toASMType(); environment.getOutput().returnType(returnType); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementVar.java b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementVar.java index 8974e61..4e9e645 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementVar.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/statements/StatementVar.java @@ -23,10 +23,10 @@ public class StatementVar extends Statement { private final ZenType type; private final ParsedExpression initializer; private final boolean isFinal; - + public StatementVar(ZenPosition position, String name, ZenType type, ParsedExpression initializer, boolean isFinal) { super(position); - + this.name = name; this.type = type; this.initializer = initializer; @@ -36,15 +36,15 @@ public class StatementVar extends Statement { @Override public void compile(IEnvironmentMethod environment) { environment.getOutput().position(getPosition()); - + Expression cInitializer = initializer == null ? null : initializer.compile(environment, type).eval(environment); ZenType cType = type == null ? (cInitializer == null ? ZenTypeAny.INSTANCE : cInitializer.getType()) : type; SymbolLocal symbol = new SymbolLocal(cType, isFinal); - + environment.putValue(name, symbol, getPosition()); - + if (cInitializer != null) { cInitializer.compile(true, environment); environment.getOutput().store(symbol.getType().toASMType(), environment.getLocal(symbol)); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolArgument.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolArgument.java index f7d7bd5..cbadadf 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolArgument.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolArgument.java @@ -18,7 +18,7 @@ import stanhebben.zenscript.util.ZenPosition; public class SymbolArgument implements IZenSymbol { private final int id; private final ZenType type; - + public SymbolArgument(int id, ZenType type) { this.id = id; this.type = type; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaClass.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaClass.java index 516210b..dce6bdb 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaClass.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaClass.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.util.ZenPosition; */ public class SymbolJavaClass implements IZenSymbol { private final Type cls; - + public SymbolJavaClass(Type cls) { this.cls = cls; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticField.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticField.java index 14f2a5e..4308d44 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticField.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticField.java @@ -20,13 +20,13 @@ public class SymbolJavaStaticField implements IZenSymbol { private final Class cls; private final Field field; private final ITypeRegistry types; - + public SymbolJavaStaticField(Class cls, Field field, ITypeRegistry types) { this.cls = cls; this.field = field; this.types = types; } - + @Override public IPartialExpression instance(ZenPosition position) { return new ExpressionJavaStaticField(position, cls, field, types); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticGetter.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticGetter.java index e213f55..70d5bf6 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticGetter.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticGetter.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.util.ZenPosition; */ public class SymbolJavaStaticGetter implements IZenSymbol { private final IJavaMethod method; - + public SymbolJavaStaticGetter(IJavaMethod method) { this.method = method; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticMethod.java index 7e9285d..464c937 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolJavaStaticMethod.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.util.ZenPosition; */ public class SymbolJavaStaticMethod implements IZenSymbol { private final IJavaMethod method; - + public SymbolJavaStaticMethod(IJavaMethod method) { this.method = method; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolLocal.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolLocal.java index 39d37e3..f3064a8 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolLocal.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolLocal.java @@ -18,16 +18,16 @@ import stanhebben.zenscript.util.ZenPosition; public class SymbolLocal implements IZenSymbol { private final ZenType type; private final boolean isFinal; - + public SymbolLocal(ZenType type, boolean isFinal) { this.type = type; this.isFinal = isFinal; } - + public ZenType getType() { return type; } - + public boolean isFinal() { return isFinal; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolPackage.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolPackage.java index 1ed79a4..ef4c667 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolPackage.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolPackage.java @@ -21,26 +21,26 @@ import stanhebben.zenscript.util.ZenPosition; */ public class SymbolPackage implements IZenSymbol { private final HashMap members; - + private final String name; - + public SymbolPackage(String name) { this.name = name; members = new HashMap(); } - + public String getName() { return name; } - + public Map getPackages() { return members; } - + public IZenSymbol get(String name) { return members.get(name); } - + public void put(String name, IZenSymbol symbol, IZenErrorLogger errors) { String[] parts = StringUtil.split(name, '.'); String[] pkgParts = Arrays.copyOf(parts, parts.length - 1); @@ -52,7 +52,7 @@ public class SymbolPackage implements IZenSymbol { } else { pkgName = pkgName + '.' + part; } - + if (pkgCurrent.members.containsKey(part)) { IZenSymbol member = pkgCurrent.members.get(part); if (member instanceof SymbolPackage) { @@ -67,15 +67,16 @@ public class SymbolPackage implements IZenSymbol { pkgCurrent = child; } } - - //System.out.println("Adding " + parts[parts.length - 1] + " to package " + pkgCurrent.getName() + "(" + symbol + ")"); + + // System.out.println("Adding " + parts[parts.length - 1] + + // " to package " + pkgCurrent.getName() + "(" + symbol + ")"); if (pkgCurrent.members.containsKey(parts[parts.length - 1])) { errors.error(null, parts[parts.length - 1] + " is already defined in that package"); } else { pkgCurrent.members.put(parts[parts.length - 1], symbol); } } - + @Override public IPartialExpression instance(ZenPosition position) { return new PartialPackage(position, this); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolType.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolType.java index aa1ded6..47f5d65 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolType.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolType.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.util.ZenPosition; */ public class SymbolType implements IZenSymbol { private final ZenType type; - + public SymbolType(ZenType type) { this.type = type; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolZenStaticMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolZenStaticMethod.java index 2ebf058..a11f7e3 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolZenStaticMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/symbols/SymbolZenStaticMethod.java @@ -21,7 +21,7 @@ public class SymbolZenStaticMethod implements IZenSymbol { private final String signature; private final ZenType[] argumentTypes; private final ZenType returnType; - + public SymbolZenStaticMethod(String className, String methodName, String signature, ZenType[] argumentTypes, ZenType returnType) { this.className = className; this.methodName = methodName; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/IZenIterator.java b/ZenScript/src/main/java/stanhebben/zenscript/type/IZenIterator.java index ab78fbd..60ecdd8 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/IZenIterator.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/IZenIterator.java @@ -14,35 +14,36 @@ import org.objectweb.asm.Label; */ public interface IZenIterator { /** - * Compiles the header before the iteration. The list is on the top of the stack. + * Compiles the header before the iteration. The list is on the top of the + * stack. * * @param locals */ public void compileStart(int[] locals); - + /** - * Compiles the start of an iteration. The stack is unmodified from the + * Compiles the start of an iteration. The stack is unmodified from the * previous iteration and from the iteration start. * * @param locals - * @param exit + * @param exit */ public void compilePreIterate(int[] locals, Label exit); - + /** * Compiles the end of an iteration. The stack is the same as it was after * preIterate. * * @param locals * @param exit - * @param repeat + * @param repeat */ public void compilePostIterate(int[] locals, Label exit, Label repeat); - + /** * Compiles the end of the whole iteration. */ public void compileEnd(); - + public ZenType getType(int i); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenType.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenType.java index 8a1beea..9373141 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenType.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenType.java @@ -42,17 +42,17 @@ public abstract class ZenType { public static final ZenTypeString STRING = ZenTypeString.INSTANCE; public static final ZenTypeVoid VOID = ZenTypeVoid.INSTANCE; public static final ZenTypeNull NULL = ZenTypeNull.INSTANCE; - + public static final ZenTypeArrayBasic ANYARRAY = new ZenTypeArrayBasic(ANY); public static final ZenTypeAssociative ANYMAP = new ZenTypeAssociative(ANY, ANY); - + public static final int NUM_BYTE = 1; public static final int NUM_SHORT = 2; public static final int NUM_INT = 3; public static final int NUM_LONG = 4; public static final int NUM_FLOAT = 5; public static final int NUM_DOUBLE = 6; - + protected static final IJavaMethod BOOL_VALUEOF = JavaMethod.get(EMPTY_REGISTRY, Boolean.class, "valueOf", boolean.class); protected static final IJavaMethod BYTE_VALUEOF = JavaMethod.get(EMPTY_REGISTRY, Byte.class, "valueOf", byte.class); protected static final IJavaMethod SHORT_VALUEOF = JavaMethod.get(EMPTY_REGISTRY, Short.class, "valueOf", short.class); @@ -60,7 +60,7 @@ public abstract class ZenType { protected static final IJavaMethod LONG_VALUEOF = JavaMethod.get(EMPTY_REGISTRY, Long.class, "valueOf", long.class); protected static final IJavaMethod FLOAT_VALUEOF = JavaMethod.get(EMPTY_REGISTRY, Float.class, "valueOf", float.class); protected static final IJavaMethod DOUBLE_VALUEOF = JavaMethod.get(EMPTY_REGISTRY, Double.class, "valueOf", double.class); - + protected static final IJavaMethod BOOL_VALUE = JavaMethod.get(EMPTY_REGISTRY, Boolean.class, "booleanValue"); protected static final IJavaMethod BYTE_VALUE = JavaMethod.get(EMPTY_REGISTRY, Number.class, "byteValue"); protected static final IJavaMethod SHORT_VALUE = JavaMethod.get(EMPTY_REGISTRY, Number.class, "shortValue"); @@ -68,7 +68,7 @@ public abstract class ZenType { protected static final IJavaMethod LONG_VALUE = JavaMethod.get(EMPTY_REGISTRY, Number.class, "longValue"); protected static final IJavaMethod FLOAT_VALUE = JavaMethod.get(EMPTY_REGISTRY, Number.class, "floatValue"); protected static final IJavaMethod DOUBLE_VALUE = JavaMethod.get(EMPTY_REGISTRY, Number.class, "doubleValue"); - + protected static final IJavaMethod BOOL_TOSTRING_STATIC = JavaMethod.get(EMPTY_REGISTRY, Boolean.class, "toString", boolean.class); protected static final IJavaMethod BYTE_TOSTRING_STATIC = JavaMethod.get(EMPTY_REGISTRY, Byte.class, "toString", byte.class); protected static final IJavaMethod SHORT_TOSTRING_STATIC = JavaMethod.get(EMPTY_REGISTRY, Short.class, "toString", short.class); @@ -76,7 +76,7 @@ public abstract class ZenType { protected static final IJavaMethod LONG_TOSTRING_STATIC = JavaMethod.get(EMPTY_REGISTRY, Long.class, "toString", long.class); protected static final IJavaMethod FLOAT_TOSTRING_STATIC = JavaMethod.get(EMPTY_REGISTRY, Float.class, "toString", float.class); protected static final IJavaMethod DOUBLE_TOSTRING_STATIC = JavaMethod.get(EMPTY_REGISTRY, Double.class, "toString", double.class); - + protected static final IJavaMethod BOOL_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Boolean.class, "toString"); protected static final IJavaMethod BYTE_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Byte.class, "toString"); protected static final IJavaMethod SHORT_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Short.class, "toString"); @@ -84,7 +84,7 @@ public abstract class ZenType { protected static final IJavaMethod LONG_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Long.class, "toString"); protected static final IJavaMethod FLOAT_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Float.class, "toString"); protected static final IJavaMethod DOUBLE_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Double.class, "toString"); - + protected static final IJavaMethod PARSE_BOOL = JavaMethod.get(EMPTY_REGISTRY, Boolean.class, "parseBoolean", String.class); protected static final IJavaMethod PARSE_BYTE = JavaMethod.get(EMPTY_REGISTRY, Byte.class, "parseByte", String.class); protected static final IJavaMethod PARSE_SHORT = JavaMethod.get(EMPTY_REGISTRY, Short.class, "parseShort", String.class); @@ -92,7 +92,7 @@ public abstract class ZenType { protected static final IJavaMethod PARSE_LONG = JavaMethod.get(EMPTY_REGISTRY, Long.class, "parseLong", String.class); protected static final IJavaMethod PARSE_FLOAT = JavaMethod.get(EMPTY_REGISTRY, Float.class, "parseFloat", String.class); protected static final IJavaMethod PARSE_DOUBLE = JavaMethod.get(EMPTY_REGISTRY, Double.class, "parseDouble", String.class); - + protected static final IJavaMethod PARSE_BOOL_OBJECT = JavaMethod.get(EMPTY_REGISTRY, Boolean.class, "valueOf", String.class); protected static final IJavaMethod PARSE_BYTE_OBJECT = JavaMethod.get(EMPTY_REGISTRY, Byte.class, "valueOf", String.class); protected static final IJavaMethod PARSE_SHORT_OBJECT = JavaMethod.get(EMPTY_REGISTRY, Short.class, "valueOf", String.class); @@ -100,7 +100,7 @@ public abstract class ZenType { protected static final IJavaMethod PARSE_LONG_OBJECT = JavaMethod.get(EMPTY_REGISTRY, Long.class, "valueOf", String.class); protected static final IJavaMethod PARSE_FLOAT_OBJECT = JavaMethod.get(EMPTY_REGISTRY, Float.class, "valueOf", String.class); protected static final IJavaMethod PARSE_DOUBLE_OBJECT = JavaMethod.get(EMPTY_REGISTRY, Double.class, "valueOf", String.class); - + public static ZenType parse(String type, IEnvironmentGlobal environment) { try { ZenTokener parser = new ZenTokener(type, environment.getEnvironment()); @@ -109,10 +109,10 @@ public abstract class ZenType { return null; } } - + public static ZenType read(ZenTokener parser, IEnvironmentGlobal environment) { ZenType base; - + Token next = parser.next(); switch (next.getType()) { case ZenTokener.T_ANY: @@ -147,17 +147,17 @@ public abstract class ZenType { break; case ZenTokener.T_ID: base = ANY; - + StringBuilder typeName = new StringBuilder(); typeName.append(next.getValue()); IPartialExpression partial = environment.getValue(next.getValue(), next.getPosition()); while (parser.optional(ZenTokener.T_DOT) != null) { typeName.append('.'); - + Token member = parser.required(ZenTokener.T_ID, "identifier expected"); typeName.append(member.getValue()); partial = partial.getMember(member.getPosition(), environment, member.getValue()); - + if (partial == null) { environment.error(member.getPosition(), "could not find type " + typeName); break; @@ -170,7 +170,7 @@ public abstract class ZenType { default: throw new ParseException(next, "Unknown type: " + next.getValue()); } - + while (parser.optional(ZenTokener.T_SQBROPEN) != null) { if (parser.optional(ZenTokener.T_SQBRCLOSE) == null) { base = new ZenTypeAssociative(base, read(parser, environment)); @@ -179,25 +179,25 @@ public abstract class ZenType { base = new ZenTypeArrayBasic(base); } } - + return base; } - + private Map castingRules = null; - + public abstract Expression unary( ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator); - + public abstract Expression binary( ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, OperatorType operator); - + public abstract Expression trinary( ZenPosition position, IEnvironmentGlobal environment, @@ -205,75 +205,75 @@ public abstract class ZenType { Expression second, Expression third, OperatorType operator); - + public abstract Expression compare( ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type); - + public abstract IPartialExpression getMember( ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value, String name); - + public abstract IPartialExpression getStaticMember( ZenPosition position, IEnvironmentGlobal environment, String name); - + public abstract Expression call( ZenPosition position, IEnvironmentGlobal environment, Expression receiver, Expression... arguments); - + public ZenType[] predictCallTypes(int numArguments) { return new ZenType[numArguments]; } - + public abstract void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters); - + public abstract IZenIterator makeIterator( int numValues, IEnvironmentMethod methodOutput); - + public ICastingRule getCastingRule(ZenType type, IEnvironmentGlobal environment) { if (castingRules == null) { castingRules = new HashMap(); constructCastingRules(environment, new CastingRuleDelegateMap(this, castingRules), true); } - + return castingRules.get(type); } - + public final boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { if (equals(type)) return true; - + return getCastingRule(type, environment) != null; } public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { return canCastImplicit(type, environment); } - + public abstract Class toJavaClass(); - + public abstract Type toASMType(); - + public abstract int getNumberType(); - + public abstract String getSignature(); - + public abstract boolean isPointer(); - + public final void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { if (equals(type)) return; - + ICastingRule castingRule = getCastingRule(type, environment); if (castingRule != null) { castingRule.compile(environment); @@ -281,22 +281,22 @@ public abstract class ZenType { throw new RuntimeException("Cannot cast " + getName() + " to " + type.getName()); } } - + public abstract String getAnyClassName(IEnvironmentGlobal environment); - + public abstract String getName(); - + public abstract Expression defaultValue(ZenPosition position); - + public boolean isLarge() { return false; } - + @Override public String toString() { return getName(); } - + protected Expression unaryExpansion(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { @@ -304,7 +304,7 @@ public abstract class ZenType { } return null; } - + protected Expression binaryExpansion( ZenPosition position, IEnvironmentGlobal environment, @@ -317,7 +317,7 @@ public abstract class ZenType { } return null; } - + protected Expression trinaryExpansion( ZenPosition position, IEnvironmentGlobal environment, @@ -331,7 +331,7 @@ public abstract class ZenType { } return null; } - + protected IPartialExpression memberExpansion(ZenPosition position, IEnvironmentGlobal environment, Expression value, String member) { TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { @@ -339,7 +339,7 @@ public abstract class ZenType { } return null; } - + protected IPartialExpression staticMemberExpansion(ZenPosition position, IEnvironmentGlobal environment, String member) { TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { @@ -347,14 +347,14 @@ public abstract class ZenType { } return null; } - + protected void constructExpansionCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules) { TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.constructCastingRules(environment, rules); } } - + protected Expression castExpansion( ZenPosition position, IEnvironmentGlobal environment, @@ -369,7 +369,7 @@ public abstract class ZenType { } return null; } - + protected boolean canCastExpansion(IEnvironmentGlobal environment, ZenType toType) { String name = getName(); TypeExpansion expansion = environment.getExpansion(name); @@ -382,7 +382,7 @@ public abstract class ZenType { return false; } - + protected boolean compileCastExpansion(ZenPosition position, IEnvironmentMethod environment, ZenType toType) { TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { @@ -395,12 +395,12 @@ public abstract class ZenType { return false; } - + @Override public int hashCode() { return getName().hashCode(); } - + @Override public boolean equals(Object other) { if (other instanceof ZenType) { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeAny.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeAny.java index 0a15feb..1c9febd 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeAny.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeAny.java @@ -35,9 +35,10 @@ import stanhebben.zenscript.value.IAny; */ public class ZenTypeAny extends ZenType { public static final ZenTypeAny INSTANCE = new ZenTypeAny(); - - private ZenTypeAny() {} - + + private ZenTypeAny() { + } + @Override public IPartialExpression getMember(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value, String name) { environment.error(position, "any values not yet supported"); @@ -54,7 +55,7 @@ public class ZenTypeAny extends ZenType { public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { return null; // TODO: handle iteration on any-values } - + @Override public ICastingRule getCastingRule(ZenType type, IEnvironmentGlobal environment) { ICastingRule base = super.getCastingRule(type, environment); @@ -64,7 +65,7 @@ public class ZenTypeAny extends ZenType { return base; } } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { rules.registerCastingRule(BOOL, CastingAnyBool.INSTANCE); @@ -82,17 +83,17 @@ public class ZenTypeAny extends ZenType { rules.registerCastingRule(DOUBLE, CastingAnyDouble.INSTANCE); rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleNullableStaticMethod(DOUBLE_VALUEOF, CastingAnyDouble.INSTANCE)); rules.registerCastingRule(STRING, CastingAnyString.INSTANCE); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - + @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { return true; } - + @Override public Class toJavaClass() { return IAny.class; @@ -117,7 +118,7 @@ public class ZenTypeAny extends ZenType { public boolean isPointer() { return true; } - + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { switch (operator) { @@ -186,7 +187,7 @@ public class ZenTypeAny extends ZenType { JavaMethod.get(environment, IAny.class, "compareTo", IAny.class), left, right); - + return new ExpressionCompareGeneric( position, comparator, @@ -202,7 +203,7 @@ public class ZenTypeAny extends ZenType { receiver, arguments); } - + @Override public ZenType[] predictCallTypes(int numArguments) { ZenType[] result = new ZenType[numArguments]; @@ -216,7 +217,7 @@ public class ZenTypeAny extends ZenType { public String getName() { return "any"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { throw new UnsupportedOperationException("Cannot get any class name from the any type. That's like trying to stuff a freezer into a freezer."); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArray.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArray.java index 2f03025..715b5e1 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArray.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArray.java @@ -23,22 +23,22 @@ import stanhebben.zenscript.util.ZenPosition; public abstract class ZenTypeArray extends ZenType { private final ZenType base; private final String name; - + public ZenTypeArray(ZenType base) { this.base = base; name = base + "[]"; } - + public ZenType getBaseType() { return base; } - + public abstract IPartialExpression getMemberLength(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value); public abstract Expression indexGet(ZenPosition position, IEnvironmentGlobal environment, Expression array, Expression index); - + public abstract Expression indexSet(ZenPosition position, IEnvironmentGlobal environment, Expression array, Expression index, Expression value); - + @Override public final String getName() { return name; @@ -48,7 +48,7 @@ public abstract class ZenTypeArray extends ZenType { public final boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { return equals(type) || canCastExpansion(environment, type); } - + @Override public final int getNumberType() { return 0; @@ -84,7 +84,7 @@ public abstract class ZenTypeArray extends ZenType { public final boolean isPointer() { return true; } - + @Override public final Expression unary( ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { @@ -147,7 +147,7 @@ public abstract class ZenTypeArray extends ZenType { environment.error(position, "Cannot call an array"); return new ExpressionInvalid(position); } - + @Override public Expression defaultValue(ZenPosition position) { return new ExpressionNull(position); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArrayBasic.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArrayBasic.java index 8df9d0e..def2487 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArrayBasic.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArrayBasic.java @@ -19,20 +19,20 @@ import stanhebben.zenscript.util.ZenPosition; public class ZenTypeArrayBasic extends ZenTypeArray { private final Type asmType; - + public ZenTypeArrayBasic(ZenType base) { super(base); - + asmType = Type.getType("[" + base.toASMType().getDescriptor()); } - + @Override public boolean equals(Object other) { if (other instanceof ZenTypeArrayBasic) { ZenTypeArrayBasic o = (ZenTypeArrayBasic) other; return o.getBaseType().equals(getBaseType()); } - + return false; } @@ -42,12 +42,12 @@ public class ZenTypeArrayBasic extends ZenTypeArray { hash = 23 * hash + (this.getBaseType() != null ? this.getBaseType().hashCode() : 0); return hash; } - + @Override public ICastingRule getCastingRule(ZenType type, IEnvironmentGlobal environment) { ICastingRule base = super.getCastingRule(type, environment); if (base == null && getBaseType() == ANY && type instanceof ZenTypeArray) { - ZenType toBaseType = ((ZenTypeArray)type).getBaseType(); + ZenType toBaseType = ((ZenTypeArray) type).getBaseType(); if (type instanceof ZenTypeArrayBasic) { return new CastingRuleArrayArray(ANY.getCastingRule(toBaseType, environment), this, (ZenTypeArrayBasic) type); } else if (type instanceof ZenTypeArrayList) { @@ -59,17 +59,17 @@ public class ZenTypeArrayBasic extends ZenTypeArray { return base; } } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { ICastingRuleDelegate arrayRules = new CastingRuleDelegateArray(rules, this); getBaseType().constructCastingRules(environment, arrayRules, followCasters); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - + @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { if (numValues == 1) { @@ -80,7 +80,7 @@ public class ZenTypeArrayBasic extends ZenTypeArray { return null; } } - + @Override public String getAnyClassName(IEnvironmentGlobal global) { return null; @@ -104,7 +104,7 @@ public class ZenTypeArrayBasic extends ZenTypeArray { public String getSignature() { return "[" + getBaseType().getSignature(); } - + @Override public IPartialExpression getMemberLength(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value) { return new ExpressionArrayLength(position, value.eval(environment)); @@ -126,11 +126,11 @@ public class ZenTypeArrayBasic extends ZenTypeArray { index.cast(position, environment, INT), value.cast(position, environment, getBaseType())); } - + private class ValueIterator implements IZenIterator { private final MethodOutput methodOutput; private int index; - + public ValueIterator(MethodOutput methodOutput) { this.methodOutput = methodOutput; } @@ -148,19 +148,19 @@ public class ZenTypeArrayBasic extends ZenTypeArray { methodOutput.arrayLength(); methodOutput.loadInt(index); methodOutput.ifICmpLE(exit); - + methodOutput.dup(); methodOutput.loadInt(index); methodOutput.arrayLoad(getBaseType().toASMType()); methodOutput.store(getBaseType().toASMType(), locals[0]); } - + @Override public void compilePostIterate(int[] locals, Label exit, Label repeat) { methodOutput.iinc(index, 1); methodOutput.goTo(repeat); } - + @Override public void compileEnd() { // pop the array @@ -172,10 +172,10 @@ public class ZenTypeArrayBasic extends ZenTypeArray { return getBaseType(); } } - + private class IndexValueIterator implements IZenIterator { private final MethodOutput methodOutput; - + public IndexValueIterator(MethodOutput methodOutput) { this.methodOutput = methodOutput; } @@ -192,19 +192,19 @@ public class ZenTypeArrayBasic extends ZenTypeArray { methodOutput.arrayLength(); methodOutput.loadInt(locals[0]); methodOutput.ifICmpLE(exit); - + methodOutput.dup(); methodOutput.loadInt(locals[0]); methodOutput.arrayLoad(getBaseType().toASMType()); methodOutput.store(getBaseType().toASMType(), locals[1]); } - + @Override public void compilePostIterate(int[] locals, Label exit, Label repeat) { methodOutput.iinc(locals[0]); methodOutput.goTo(repeat); } - + @Override public void compileEnd() { // pop the array diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArrayList.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArrayList.java index 9e90de9..f0d85e0 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArrayList.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeArrayList.java @@ -25,10 +25,10 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; */ public class ZenTypeArrayList extends ZenTypeArray { private final Type type; - + public ZenTypeArrayList(ZenType baseType) { super(baseType); - + type = Type.getType(List.class); } @@ -36,17 +36,17 @@ public class ZenTypeArrayList extends ZenTypeArray { public IPartialExpression getMemberLength(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value) { return new ExpressionListLength(position, value.eval(environment)); } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { ICastingRuleDelegate arrayRules = new CastingRuleDelegateList(rules, this); getBaseType().constructCastingRules(environment, arrayRules, followCasters); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - + @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { if (numValues == 1) { @@ -62,7 +62,7 @@ public class ZenTypeArrayList extends ZenTypeArray { public Class toJavaClass() { return List.class; } - + @Override public String getAnyClassName(IEnvironmentGlobal global) { return null; @@ -77,25 +77,43 @@ public class ZenTypeArrayList extends ZenTypeArray { public String getSignature() { return signature(List.class); } - + @Override public Expression indexGet(ZenPosition position, IEnvironmentGlobal environment, Expression array, Expression index) { // TODO: implement - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. } @Override public Expression indexSet(ZenPosition position, IEnvironmentGlobal environment, Expression array, Expression index, Expression value) { // TODO: implement - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. } - + private class ExpressionListLength extends Expression { private final Expression value; - + public ExpressionListLength(ZenPosition position, Expression value) { super(position); - + this.value = value; } @@ -107,7 +125,7 @@ public class ZenTypeArrayList extends ZenTypeArray { @Override public void compile(boolean result, IEnvironmentMethod environment) { value.compile(result, environment); - + if (result) { environment.getOutput().invokeInterface(List.class, "size", int.class); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeAssociative.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeAssociative.java index 9615d46..493b8c7 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeAssociative.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeAssociative.java @@ -37,24 +37,24 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; public class ZenTypeAssociative extends ZenType { private final ZenType valueType; private final ZenType keyType; - + private final String name; - + public ZenTypeAssociative(ZenType valueType, ZenType keyType) { this.valueType = valueType; this.keyType = keyType; - + name = valueType.getName() + "[" + keyType.getName() + "]"; } - + public ZenType getValueType() { return valueType; } - + public ZenType getKeyType() { return keyType; } - + @Override public ICastingRule getCastingRule(ZenType type, IEnvironmentGlobal environment) { ICastingRule base = super.getCastingRule(type, environment); @@ -69,7 +69,7 @@ public class ZenTypeAssociative extends ZenType { return base; } } - + @Override public String getAnyClassName(IEnvironmentGlobal global) { return null; @@ -169,14 +169,14 @@ public class ZenTypeAssociative extends ZenType { environment.error(position, "cannot call associative arrays"); return new ExpressionInvalid(position); } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { if (followCasters) { constructExpansionCastingRules(environment, rules); } } - + @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { if (numValues == 1) { @@ -227,12 +227,12 @@ public class ZenTypeAssociative extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionNull(position); } - + private boolean canCastAssociative(ZenType type, IEnvironmentGlobal global) { if (!(type instanceof ZenTypeAssociative)) { return false; } - + ZenTypeAssociative atype = (ZenTypeAssociative) type; return getKeyType().canCastImplicit(atype.getKeyType(), global) && getValueType().canCastImplicit(atype.getValueType(), global); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeBool.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeBool.java index f1ac3e3..0b95b9d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeBool.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeBool.java @@ -38,48 +38,49 @@ public class ZenTypeBool extends ZenType { private static final String ANY_NAME = "any/AnyBool"; private static final String ANY_NAME_2 = "any.AnyBool"; private static final String ANY_NAME_DESC = "Lany/AnyBool;"; - - public ZenTypeBool() {} + + public ZenTypeBool() { + } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { return null; } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { rules.registerCastingRule(STRING, new CastingRuleStaticMethod(BOOL_TOSTRING_STATIC)); rules.registerCastingRule(BOOLOBJECT, new CastingRuleStaticMethod(BOOL_VALUEOF)); rules.registerCastingRule(ANY, new CastingRuleStaticMethod(JavaMethod.getStatic( getAnyClassName(environment), "valueOf", ANY, BOOL - ))); - + ))); + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return type == BOOL || type == ANY || type == ZenTypeString.INSTANCE || canCastExpansion(environment, type); - }*/ + + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return type == BOOL || type == ANY || type == + * ZenTypeString.INSTANCE || canCastExpansion(environment, type); } + */ @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { return canCastImplicit(type, environment); } - - /*@Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type == BOOL || type == ZenTypeBoolObject.INSTANCE || type == STRING || type == ANY) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ - + + /* + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type == BOOL || type + * == ZenTypeBoolObject.INSTANCE || type == STRING || type == ANY) { return + * new ExpressionAs(position, value, type); } else if + * (canCastExpansion(environment, type)) { return castExpansion(position, + * environment, value, type); } else { return new ExpressionAs(position, + * value, type); } } + */ + @Override public Class toJavaClass() { return boolean.class; @@ -94,12 +95,12 @@ public class ZenTypeBool extends ZenType { public int getNumberType() { return 0; } - + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return new ExpressionArithmeticUnary(position, operator, value); } - + @Override public Expression binary(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, OperatorType operator) { if (operator == OperatorType.CAT) { @@ -109,7 +110,7 @@ public class ZenTypeBool extends ZenType { left.cast(position, environment, STRING), right.cast(position, environment, STRING), OperatorType.CAT); } - + if (right.getType().canCastImplicit(BOOL, environment)) { switch (operator) { case AND: @@ -118,7 +119,7 @@ public class ZenTypeBool extends ZenType { if (right.getType() != BOOL) { right = right.cast(position, environment, BOOL); } - + return new ExpressionArithmeticBinary(position, operator, left, right); default: environment.error(position, "unsupported bool operator: " + operator); @@ -129,14 +130,14 @@ public class ZenTypeBool extends ZenType { return new ExpressionInvalid(position, BOOL); } } - + @Override public Expression trinary( ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "operation not supported on a bool value"); return new ExpressionInvalid(position, BOOL); } - + @Override public Expression compare( ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { @@ -147,14 +148,14 @@ public class ZenTypeBool extends ZenType { return new ExpressionInvalid(position, BOOL); } } - + @Override public Expression call( ZenPosition position, IEnvironmentGlobal environment, Expression receiver, Expression... arguments) { environment.error(position, "cannot call a boolean value"); return new ExpressionInvalid(position, ZenTypeAny.INSTANCE); } - + @Override public IPartialExpression getMember(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value, String name) { IPartialExpression result = memberExpansion(position, environment, value.eval(environment), name); @@ -182,33 +183,32 @@ public class ZenTypeBool extends ZenType { return false; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else if (type == ZenTypeBoolObject.INSTANCE) { - environment.getOutput().invokeStatic(Boolean.class, "valueOf", Boolean.class, boolean.class); - } else if (type == STRING) { - environment.getOutput().invokeStatic(Boolean.TYPE, "toString", String.class, boolean.class); - } else if (type == ANY) { - environment.getOutput().invokeStatic(getAnyClassName(environment), "valueOf", "(Z)" + signature(IAny.class)); - } else if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "Cannot compile bool to " + type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else if (type == ZenTypeBoolObject.INSTANCE) { + * environment.getOutput().invokeStatic(Boolean.class, "valueOf", + * Boolean.class, boolean.class); } else if (type == STRING) { + * environment.getOutput().invokeStatic(Boolean.TYPE, "toString", + * String.class, boolean.class); } else if (type == ANY) { + * environment.getOutput().invokeStatic(getAnyClassName(environment), + * "valueOf", "(Z)" + signature(IAny.class)); } else if + * (!compileCastExpansion(position, environment, type)) { + * environment.error(position, "Cannot compile bool to " + type); } } + */ @Override public String getName() { return "bool"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { if (!environment.containsClass(ANY_NAME_2)) { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionBool(environment), ANY_NAME, Type.BOOLEAN_TYPE)); } - + return ANY_NAME; } @@ -216,10 +216,10 @@ public class ZenTypeBool extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionBool(position, false); } - + private class AnyDefinitionBool implements IAnyDefinition { private final IEnvironmentGlobal environment; - + public AnyDefinitionBool(IEnvironmentGlobal environment) { this.environment = environment; } @@ -228,9 +228,9 @@ public class ZenTypeBool extends ZenType { public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, "TRUE", ANY_NAME_DESC, null, null); output.visitField(Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC | Opcodes.ACC_FINAL, "FALSE", ANY_NAME_DESC, null, null); - + output.visitField(Opcodes.ACC_PRIVATE, "value", "Z", null, null); - + MethodOutput clinit = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "", "()V", null, null); clinit.start(); clinit.newObject(ANY_NAME); @@ -245,7 +245,7 @@ public class ZenTypeBool extends ZenType { clinit.putStaticField(ANY_NAME, "TRUE", ANY_NAME_DESC); clinit.returnType(Type.VOID_TYPE); clinit.end(); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(Z)" + signature(IAny.class), null, null); Label lblFalse = new Label(); valueOf.start(); @@ -257,7 +257,7 @@ public class ZenTypeBool extends ZenType { valueOf.getStaticField(ANY_NAME, "FALSE", ANY_NAME_DESC); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(Z)V", null, null); constructor.start(); constructor.loadObject(0); @@ -268,23 +268,23 @@ public class ZenTypeBool extends ZenType { constructor.returnType(Type.VOID_TYPE); constructor.end(); } - + @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblCan = new Label(); - + output.constant(Type.BOOLEAN_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(BOOL, output, environment, 0); } - + output.iConst0(); output.returnInt(); - + output.label(lblCan); output.iConst1(); output.returnInt(); @@ -296,7 +296,7 @@ public class ZenTypeBool extends ZenType { if (expansion != null) { expansion.compileAnyCast(BOOL, output, environment, 0, 1); } - + throwCastException(output, "bool", 1); } @@ -492,21 +492,21 @@ public class ZenTypeBool extends ZenType { @Override public void defineAs(MethodOutput output) { int localValue = output.local(Type.BYTE_TYPE); - + getValue(output); output.store(Type.BYTE_TYPE, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(BYTE, output, environment, localValue, 1); } - + throwCastException(output, "bool", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); - + output.loadObject(1); output.constant(Type.BOOLEAN_TYPE); output.ifACmpEq(lblEq); @@ -516,7 +516,7 @@ public class ZenTypeBool extends ZenType { output.iConst1(); output.returnInt(); } - + @Override public void defineGetNumberType(MethodOutput output) { output.iConst0(); @@ -538,12 +538,12 @@ public class ZenTypeBool extends ZenType { Label lblEqual = new Label(); output.loadObject(0); output.loadObject(1); - + output.ifACmpEq(lblEqual); - + output.iConst0(); output.returnInt(); - + output.label(lblEqual); output.iConst1(); output.returnInt(); @@ -553,12 +553,12 @@ public class ZenTypeBool extends ZenType { public void defineHashCode(MethodOutput output) { output.invokeSpecial("java/lang/Object", "hashCode", "()I"); } - + private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "Z"); } - + private void valueOf(MethodOutput output) { output.invokeStatic(ANY_NAME, "valueOf", "(Z)" + signature(IAny.class)); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeBoolObject.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeBoolObject.java index 0afcdbf..f288431 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeBoolObject.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeBoolObject.java @@ -29,8 +29,9 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; */ public class ZenTypeBoolObject extends ZenType { public static final ZenTypeBoolObject INSTANCE = new ZenTypeBoolObject(); - - private ZenTypeBoolObject() {} + + private ZenTypeBoolObject() { + } @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { @@ -66,12 +67,12 @@ public class ZenTypeBoolObject extends ZenType { public Expression call(ZenPosition position, IEnvironmentGlobal environment, Expression receiver, Expression... arguments) { return BOOL.call(position, environment, receiver.cast(position, environment, BOOL), arguments); } - + @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { return BOOL.makeIterator(numValues, methodOutput); } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { rules.registerCastingRule(BOOL, new CastingRuleVirtualMethod(BOOL_VALUE)); @@ -81,13 +82,13 @@ public class ZenTypeBoolObject extends ZenType { "valueOf", ANY, BOOL - ), new CastingRuleVirtualMethod(BOOL_VALUE))); + ), new CastingRuleVirtualMethod(BOOL_VALUE))); } - - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return BOOL.canCastImplicit(type, environment); - }*/ + + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return BOOL.canCastImplicit(type, environment); } + */ @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { @@ -119,56 +120,50 @@ public class ZenTypeBoolObject extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else if (type == BOOL) { - environment.getOutput().invokeVirtual(Boolean.class, "booleanValue", boolean.class); - } else if (type == STRING) { - environment.getOutput().invokeVirtual(Boolean.class, "toString", String.class); - } else if (type == ANY) { - MethodOutput output = environment.getOutput(); - - Label lblNotNull = new Label(); - Label lblAfter = new Label(); - - output.dup(); - output.ifNonNull(lblNotNull); - output.aConstNull(); - output.goTo(lblAfter); - - output.label(lblNotNull); - output.invokeVirtual(Boolean.class, "booleanValue", boolean.class); - output.invokeStatic(BOOL.getAnyClassName(environment), "valueOf", "(Z)" + signature(IAny.class)); - - output.label(lblAfter); - } else { - environment.getOutput().invokeVirtual(Boolean.class, "booleanValue", boolean.class); - BOOL.compileCast(position, environment, type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else if (type == BOOL) { + * environment.getOutput().invokeVirtual(Boolean.class, "booleanValue", + * boolean.class); } else if (type == STRING) { + * environment.getOutput().invokeVirtual(Boolean.class, "toString", + * String.class); } else if (type == ANY) { MethodOutput output = + * environment.getOutput(); + * + * Label lblNotNull = new Label(); Label lblAfter = new Label(); + * + * output.dup(); output.ifNonNull(lblNotNull); output.aConstNull(); + * output.goTo(lblAfter); + * + * output.label(lblNotNull); output.invokeVirtual(Boolean.class, + * "booleanValue", boolean.class); + * output.invokeStatic(BOOL.getAnyClassName(environment), "valueOf", "(Z)" + + * signature(IAny.class)); + * + * output.label(lblAfter); } else { + * environment.getOutput().invokeVirtual(Boolean.class, "booleanValue", + * boolean.class); BOOL.compileCast(position, environment, type); } } + */ @Override public String getName() { return "bool?"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { return BOOL.getAnyClassName(environment); } - /*@Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type == BOOL || type == ZenTypeBoolObject.INSTANCE || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type == BOOL || type + * == ZenTypeBoolObject.INSTANCE || type == STRING) { return new + * ExpressionAs(position, value, type); } else if + * (canCastExpansion(environment, type)) { return castExpansion(position, + * environment, value, type); } else { return new ExpressionAs(position, + * value, type); } } + */ @Override public Expression defaultValue(ZenPosition position) { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeByte.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeByte.java index e39fc59..fc53947 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeByte.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeByte.java @@ -38,11 +38,12 @@ import stanhebben.zenscript.value.IAny; public class ZenTypeByte extends ZenType { public static final ZenTypeByte INSTANCE = new ZenTypeByte(); - + private static final String ANY_NAME = "any/AnyByte"; private static final String ANY_NAME_2 = "any.AnyByte"; - - private ZenTypeByte() {} + + private ZenTypeByte() { + } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { @@ -62,43 +63,32 @@ public class ZenTypeByte extends ZenType { rules.registerCastingRule(FLOATOBJECT, new CastingRuleStaticMethod(FLOAT_VALUEOF, new CastingRuleI2F(null))); rules.registerCastingRule(DOUBLE, new CastingRuleI2D(null)); rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleStaticMethod(DOUBLE_VALUEOF, new CastingRuleI2D(null))); - + rules.registerCastingRule(STRING, new CastingRuleStaticMethod(BYTE_TOSTRING_STATIC)); rules.registerCastingRule(ANY, new CastingRuleStaticMethod(JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, BYTE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - int itype = type.getNumberType(); - return itype != 0 - || type == STRING - || type == ANY - || canCastExpansion(environment, type); - } - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return type.getNumberType() != 0 - || type == STRING - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING || type == ANY) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ - + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { int itype = type.getNumberType(); return itype != 0 || + * type == STRING || type == ANY || canCastExpansion(environment, type); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return type.getNumberType() != 0 || type == STRING || type + * == ANY || canCastExpansion(environment, type); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING || type == ANY) { return new ExpressionAs(position, + * value, type); } else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ + @Override public Class toJavaClass() { return byte.class; @@ -140,46 +130,35 @@ public class ZenTypeByte extends ZenType { return false; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - MethodOutput output = environment.getOutput(); - - if (type == BYTE) { - // nothing to do - } else if (type == ZenTypeByteObject.INSTANCE) { - output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); - } else if (type == SHORT) { - // nothing to do - } else if (type == ZenTypeShortObject.INSTANCE) { - output.invokeStatic(Short.class, "valueOf", Short.class, short.class); - } else if (type == INT) { - // nothing to do - } else if (type == ZenTypeIntObject.INSTANCE) { - output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); - } else if (type == LONG) { - output.i2l(); - } else if (type == ZenTypeLongObject.INSTANCE) { - output.i2l(); - output.invokeStatic(Long.class, "valueOf", Long.class, long.class); - } else if (type == FLOAT) { - output.i2f(); - } else if (type == ZenTypeFloatObject.INSTANCE) { - output.i2f(); - output.invokeStatic(Float.class, "valueOf", Float.class, float.class); - } else if (type == DOUBLE) { - output.i2d(); - } else if (type == ZenTypeDoubleObject.INSTANCE) { - output.i2d(); - output.invokeStatic(Double.class, "valueOf", Double.class, double.class); - } else if (type == STRING) { - output.invokeStatic(Byte.class, "toString", String.class, byte.class); - } else if (type == ANY) { - output.invokeStatic(getAnyClassName(environment), "valueOf", "(B)" + signature(IAny.class)); - } else if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "cannot cast " + this + " to " + type); - } - }*/ - + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { MethodOutput output = + * environment.getOutput(); + * + * if (type == BYTE) { // nothing to do } else if (type == + * ZenTypeByteObject.INSTANCE) { output.invokeStatic(Byte.class, "valueOf", + * Byte.class, byte.class); } else if (type == SHORT) { // nothing to do } + * else if (type == ZenTypeShortObject.INSTANCE) { + * output.invokeStatic(Short.class, "valueOf", Short.class, short.class); } + * else if (type == INT) { // nothing to do } else if (type == + * ZenTypeIntObject.INSTANCE) { output.invokeStatic(Integer.class, + * "valueOf", Integer.class, int.class); } else if (type == LONG) { + * output.i2l(); } else if (type == ZenTypeLongObject.INSTANCE) { + * output.i2l(); output.invokeStatic(Long.class, "valueOf", Long.class, + * long.class); } else if (type == FLOAT) { output.i2f(); } else if (type == + * ZenTypeFloatObject.INSTANCE) { output.i2f(); + * output.invokeStatic(Float.class, "valueOf", Float.class, float.class); } + * else if (type == DOUBLE) { output.i2d(); } else if (type == + * ZenTypeDoubleObject.INSTANCE) { output.i2d(); + * output.invokeStatic(Double.class, "valueOf", Double.class, double.class); + * } else if (type == STRING) { output.invokeStatic(Byte.class, "toString", + * String.class, byte.class); } else if (type == ANY) { + * output.invokeStatic(getAnyClassName(environment), "valueOf", "(B)" + + * signature(IAny.class)); } else if (!compileCastExpansion(position, + * environment, type)) { environment.error(position, "cannot cast " + this + + * " to " + type); } } + */ + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return new ExpressionArithmeticUnary(position, operator, value); @@ -194,16 +173,16 @@ public class ZenTypeByte extends ZenType { left.cast(position, environment, STRING), right.cast(position, environment, STRING), OperatorType.CAT); } - + return new ExpressionArithmeticBinary(position, operator, left, right.cast(position, environment, this)); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "byte doesn't support this operation"); return new ExpressionInvalid(position); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { return new ExpressionArithmeticCompare(position, type, left, right.cast(position, environment, this)); @@ -220,14 +199,14 @@ public class ZenTypeByte extends ZenType { public String getName() { return "byte"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { if (!environment.containsClass(ANY_NAME_2)) { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionByte(environment), ANY_NAME, Type.BYTE_TYPE)); } - + return ANY_NAME; } @@ -235,10 +214,10 @@ public class ZenTypeByte extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionInt(position, 0, ZenType.BYTE); } - + private class AnyDefinitionByte implements IAnyDefinition { private final IEnvironmentGlobal environment; - + public AnyDefinitionByte(IEnvironmentGlobal environment) { this.environment = environment; } @@ -246,7 +225,7 @@ public class ZenTypeByte extends ZenType { @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "B", null, null); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(B)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(ANY_NAME); @@ -255,7 +234,7 @@ public class ZenTypeByte extends ZenType { valueOf.construct(ANY_NAME, "B"); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(B)V", null, null); constructor.start(); constructor.loadObject(0); @@ -266,43 +245,43 @@ public class ZenTypeByte extends ZenType { constructor.returnType(Type.VOID_TYPE); constructor.end(); } - + @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblCan = new Label(); - + output.constant(Type.BYTE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.SHORT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.INT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.LONG_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.FLOAT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.DOUBLE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(BYTE, output, environment, 0); } - + output.iConst0(); output.returnInt(); - + output.label(lblCan); output.iConst1(); output.returnInt(); @@ -314,7 +293,7 @@ public class ZenTypeByte extends ZenType { if (expansion != null) { expansion.compileAnyCast(BYTE, output, environment, 0, 1); } - + throwCastException(output, "byte", 1); } @@ -563,21 +542,21 @@ public class ZenTypeByte extends ZenType { @Override public void defineAs(MethodOutput output) { int localValue = output.local(Type.BYTE_TYPE); - + getValue(output); output.store(Type.BYTE_TYPE, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(BYTE, output, environment, localValue, 1); } - + throwCastException(output, "byte", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); - + output.loadObject(1); output.constant(Type.BYTE_TYPE); output.ifACmpEq(lblEq); @@ -587,7 +566,7 @@ public class ZenTypeByte extends ZenType { output.iConst1(); output.returnInt(); } - + @Override public void defineGetNumberType(MethodOutput output) { output.constant(IAny.NUM_BYTE); @@ -607,19 +586,19 @@ public class ZenTypeByte extends ZenType { @Override public void defineEquals(MethodOutput output) { Label lblNope = new Label(); - + output.loadObject(1); output.instanceOf(IAny.NAME); output.ifEQ(lblNope); - + getValue(output); output.loadObject(1); METHOD_ASBYTE.invokeVirtual(output); output.ifICmpNE(lblNope); - + output.iConst1(); output.returnInt(); - + output.label(lblNope); output.iConst0(); output.returnInt(); @@ -630,7 +609,7 @@ public class ZenTypeByte extends ZenType { getValue(output); output.returnInt(); } - + private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "B"); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeByteObject.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeByteObject.java index 3b90bce..ec8f838 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeByteObject.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeByteObject.java @@ -29,9 +29,10 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; */ public class ZenTypeByteObject extends ZenType { public static final ZenTypeByteObject INSTANCE = new ZenTypeByteObject(); - - private ZenTypeByteObject() {} - + + private ZenTypeByteObject() { + } + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return BYTE.unary(position, environment, value.cast(position, environment, BYTE), operator); @@ -95,37 +96,31 @@ public class ZenTypeByteObject extends ZenType { rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleNullableStaticMethod( DOUBLE_VALUEOF, new CastingRuleVirtualMethod(DOUBLE_VALUE))); - + rules.registerCastingRule(STRING, new CastingRuleNullableVirtualMethod(BYTEOBJECT, BYTE_TOSTRING)); rules.registerCastingRule(ANY, new CastingRuleNullableStaticMethod( JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, BYTE), new CastingRuleVirtualMethod(BYTE_VALUE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return BYTE.canCastImplicit(type, environment); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - } - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return BYTE.canCastExplicit(type, environment); - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return BYTE.canCastImplicit(type, environment); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return BYTE.canCastExplicit(type, environment); } + */ @Override public Class toJavaClass() { @@ -152,41 +147,35 @@ public class ZenTypeByteObject extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else if (type == BYTE) { - environment.getOutput().invokeVirtual(Byte.class, "byteValue", byte.class); - } else if (type == STRING) { - environment.getOutput().invokeVirtual(Byte.class, "toString", String.class); - } else if (type == ANY) { - MethodOutput output = environment.getOutput(); - - Label lblNotNull = new Label(); - Label lblAfter = new Label(); - - output.dup(); - output.ifNonNull(lblNotNull); - output.aConstNull(); - output.goTo(lblAfter); - - output.label(lblNotNull); - output.invokeVirtual(Byte.class, "byteValue", byte.class); - output.invokeStatic(BYTE.getAnyClassName(environment), "valueOf", "(B)" + signature(IAny.class)); - - output.label(lblAfter); - } else { - environment.getOutput().invokeVirtual(Byte.class, "byteValue", byte.class); - BYTE.compileCast(position, environment, type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else if (type == BYTE) { + * environment.getOutput().invokeVirtual(Byte.class, "byteValue", + * byte.class); } else if (type == STRING) { + * environment.getOutput().invokeVirtual(Byte.class, "toString", + * String.class); } else if (type == ANY) { MethodOutput output = + * environment.getOutput(); + * + * Label lblNotNull = new Label(); Label lblAfter = new Label(); + * + * output.dup(); output.ifNonNull(lblNotNull); output.aConstNull(); + * output.goTo(lblAfter); + * + * output.label(lblNotNull); output.invokeVirtual(Byte.class, "byteValue", + * byte.class); output.invokeStatic(BYTE.getAnyClassName(environment), + * "valueOf", "(B)" + signature(IAny.class)); + * + * output.label(lblAfter); } else { + * environment.getOutput().invokeVirtual(Byte.class, "byteValue", + * byte.class); BYTE.compileCast(position, environment, type); } } + */ @Override public String getName() { return "byte?"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { return BYTE.getAnyClassName(environment); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeDouble.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeDouble.java index 1a8600b..1c56d5e 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeDouble.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeDouble.java @@ -44,12 +44,14 @@ import stanhebben.zenscript.value.IAny; public class ZenTypeDouble extends ZenType { public static final ZenTypeDouble INSTANCE = new ZenTypeDouble(); - - //private static final JavaMethod DOUBLE_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Double.class, "toString", double.class); + + // private static final JavaMethod DOUBLE_TOSTRING = + // JavaMethod.get(EMPTY_REGISTRY, Double.class, "toString", double.class); private static final String ANY_NAME = "any/AnyDouble"; private static final String ANY_NAME_2 = "any.AnyDouble"; - - private ZenTypeDouble() {} + + private ZenTypeDouble() { + } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { @@ -69,47 +71,38 @@ public class ZenTypeDouble extends ZenType { rules.registerCastingRule(FLOAT, new CastingRuleD2F(null)); rules.registerCastingRule(FLOATOBJECT, new CastingRuleStaticMethod(FLOAT_VALUEOF, new CastingRuleD2F(null))); rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleStaticMethod(DOUBLE_VALUEOF)); - + rules.registerCastingRule(STRING, new CastingRuleStaticMethod(DOUBLE_TOSTRING_STATIC)); rules.registerCastingRule(ANY, new CastingRuleStaticMethod(JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, DOUBLE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return (type.getNumberType() != 0 && type.getNumberType() >= NUM_FLOAT) - || type == STRING - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return type.getNumberType() != 0 - || type == STRING - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return (type.getNumberType() != 0 && type.getNumberType() + * >= NUM_FLOAT) || type == STRING || type == ANY || + * canCastExpansion(environment, type); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return type.getNumberType() != 0 || type == STRING || type + * == ANY || canCastExpansion(environment, type); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Type toASMType() { return Type.DOUBLE_TYPE; } - + @Override public Class toJavaClass() { return double.class; @@ -146,52 +139,37 @@ public class ZenTypeDouble extends ZenType { return false; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - MethodOutput output = environment.getOutput(); - - if (type == BYTE) { - output.d2i(); - output.i2b(); - } else if (type == ZenTypeByteObject.INSTANCE) { - output.d2i(); - output.i2b(); - output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); - } else if (type == SHORT) { - output.d2i(); - output.i2s(); - } else if (type == ZenTypeShortObject.INSTANCE) { - output.d2i(); - output.i2s(); - output.invokeStatic(Short.class, "valueOf", Short.class, short.class); - } else if (type == INT) { - output.d2i(); - } else if (type == ZenTypeIntObject.INSTANCE) { - output.d2i(); - output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); - } else if (type == LONG) { - output.d2l(); - } else if (type == ZenTypeLongObject.INSTANCE) { - output.d2l(); - output.invokeStatic(Long.class, "valueOf", Long.class, long.class); - } else if (type == FLOAT) { - output.d2f(); - } else if (type == ZenTypeFloatObject.INSTANCE) { - output.d2f(); - output.invokeStatic(Float.class, "valueOf", Float.class, float.class); - } else if (type == DOUBLE) { - // nothing to do - } else if (type == ZenTypeDoubleObject.INSTANCE) { - output.invokeStatic(Double.class, "valueOf", Double.class, double.class); - } else if (type == STRING) { - output.invokeStatic(Double.class, "toString", String.class, double.class); - } else if (type == ANY) { - output.invokeStatic(getAnyClassName(environment), "valueOf", "(D)" + signature(IAny.class)); - } else if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "cannot cast " + this + " to " + type); - } - }*/ - + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { MethodOutput output = + * environment.getOutput(); + * + * if (type == BYTE) { output.d2i(); output.i2b(); } else if (type == + * ZenTypeByteObject.INSTANCE) { output.d2i(); output.i2b(); + * output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); } + * else if (type == SHORT) { output.d2i(); output.i2s(); } else if (type == + * ZenTypeShortObject.INSTANCE) { output.d2i(); output.i2s(); + * output.invokeStatic(Short.class, "valueOf", Short.class, short.class); } + * else if (type == INT) { output.d2i(); } else if (type == + * ZenTypeIntObject.INSTANCE) { output.d2i(); + * output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); + * } else if (type == LONG) { output.d2l(); } else if (type == + * ZenTypeLongObject.INSTANCE) { output.d2l(); + * output.invokeStatic(Long.class, "valueOf", Long.class, long.class); } + * else if (type == FLOAT) { output.d2f(); } else if (type == + * ZenTypeFloatObject.INSTANCE) { output.d2f(); + * output.invokeStatic(Float.class, "valueOf", Float.class, float.class); } + * else if (type == DOUBLE) { // nothing to do } else if (type == + * ZenTypeDoubleObject.INSTANCE) { output.invokeStatic(Double.class, + * "valueOf", Double.class, double.class); } else if (type == STRING) { + * output.invokeStatic(Double.class, "toString", String.class, + * double.class); } else if (type == ANY) { + * output.invokeStatic(getAnyClassName(environment), "valueOf", "(D)" + + * signature(IAny.class)); } else if (!compileCastExpansion(position, + * environment, type)) { environment.error(position, "cannot cast " + this + + * " to " + type); } } + */ + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return new ExpressionArithmeticUnary(position, operator, value); @@ -206,16 +184,16 @@ public class ZenTypeDouble extends ZenType { left.cast(position, environment, STRING), right.cast(position, environment, STRING), OperatorType.CAT); } - + return new ExpressionArithmeticBinary(position, operator, left, right.cast(position, environment, this)); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "double doesn't support this operation"); return new ExpressionInvalid(position); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { return new ExpressionArithmeticCompare(position, type, left, right.cast(position, environment, this)); @@ -232,17 +210,17 @@ public class ZenTypeDouble extends ZenType { public String getName() { return "double"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { if (!environment.containsClass(ANY_NAME_2)) { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionDouble(environment), ANY_NAME, Type.DOUBLE_TYPE)); } - + return ANY_NAME; } - + @Override public boolean isLarge() { return true; @@ -252,10 +230,10 @@ public class ZenTypeDouble extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionFloat(position, 0.0, DOUBLE); } - + private class AnyDefinitionDouble implements IAnyDefinition { private final IEnvironmentGlobal environment; - + public AnyDefinitionDouble(IEnvironmentGlobal environment) { this.environment = environment; } @@ -263,7 +241,7 @@ public class ZenTypeDouble extends ZenType { @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "D", null, null); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(D)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(ANY_NAME); @@ -272,7 +250,7 @@ public class ZenTypeDouble extends ZenType { valueOf.construct(ANY_NAME, "D"); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(D)V", null, null); constructor.start(); constructor.loadObject(0); @@ -283,43 +261,43 @@ public class ZenTypeDouble extends ZenType { constructor.returnType(Type.VOID_TYPE); constructor.end(); } - + @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblCan = new Label(); - + output.constant(Type.BYTE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.SHORT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.INT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.LONG_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.FLOAT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.DOUBLE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(FLOAT, output, environment, 0); } - + output.iConst0(); output.returnInt(); - + output.label(lblCan); output.iConst1(); output.returnInt(); @@ -331,7 +309,7 @@ public class ZenTypeDouble extends ZenType { if (expansion != null) { expansion.compileAnyCast(DOUBLE, output, environment, 0, 1); } - + throwCastException(output, "double", 1); } @@ -557,21 +535,21 @@ public class ZenTypeDouble extends ZenType { @Override public void defineAs(MethodOutput output) { int localValue = output.local(Type.DOUBLE_TYPE); - + getValue(output); output.store(Type.DOUBLE_TYPE, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(DOUBLE, output, environment, localValue, 1); } - + throwCastException(output, "double", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); - + output.loadObject(1); output.constant(Type.DOUBLE_TYPE); output.ifACmpEq(lblEq); @@ -581,7 +559,7 @@ public class ZenTypeDouble extends ZenType { output.iConst1(); output.returnInt(); } - + @Override public void defineGetNumberType(MethodOutput output) { output.constant(IAny.NUM_DOUBLE); @@ -597,7 +575,7 @@ public class ZenTypeDouble extends ZenType { public void defineIteratorMulti(MethodOutput output) { throwUnsupportedException(output, "double", "iterator"); } - + private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "D"); @@ -606,20 +584,20 @@ public class ZenTypeDouble extends ZenType { @Override public void defineEquals(MethodOutput output) { Label lblNope = new Label(); - + output.loadObject(1); output.instanceOf(IAny.NAME); output.ifEQ(lblNope); - + getValue(output); output.loadObject(1); METHOD_ASDOUBLE.invokeVirtual(output); output.dCmp(); output.ifNE(lblNope); - + output.iConst1(); output.returnInt(); - + output.label(lblNope); output.iConst0(); output.returnInt(); @@ -632,7 +610,7 @@ public class ZenTypeDouble extends ZenType { int bits = output.local(Type.LONG_TYPE); output.invokeStatic(Double.class, "doubleToLongBits", double.class, long.class); output.store(Type.LONG_TYPE, bits); - + output.load(Type.LONG_TYPE, bits); output.l2i(); output.load(Type.LONG_TYPE, bits); @@ -640,7 +618,7 @@ public class ZenTypeDouble extends ZenType { output.lShr(); output.l2i(); output.iXor(); - + output.returnInt(); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeDoubleObject.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeDoubleObject.java index 5b74a08..d9beadf 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeDoubleObject.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeDoubleObject.java @@ -32,8 +32,9 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; */ public class ZenTypeDoubleObject extends ZenType { public static final ZenTypeDoubleObject INSTANCE = new ZenTypeDoubleObject(); - - private ZenTypeDoubleObject() {} + + private ZenTypeDoubleObject() { + } @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { @@ -101,37 +102,31 @@ public class ZenTypeDoubleObject extends ZenType { rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleNullableStaticMethod( DOUBLE_VALUEOF, new CastingRuleVirtualMethod(DOUBLE_VALUE))); - + rules.registerCastingRule(STRING, new CastingRuleNullableVirtualMethod(DOUBLEOBJECT, DOUBLE_TOSTRING)); rules.registerCastingRule(ANY, new CastingRuleNullableStaticMethod( JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, DOUBLE), new CastingRuleVirtualMethod(DOUBLE_VALUE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return DOUBLE.canCastImplicit(type, environment); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return DOUBLE.canCastExplicit(type, environment); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return DOUBLE.canCastImplicit(type, environment); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return DOUBLE.canCastExplicit(type, environment); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Class toJavaClass() { @@ -158,41 +153,36 @@ public class ZenTypeDoubleObject extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else if (type == DOUBLE) { - environment.getOutput().invokeVirtual(Double.class, "doubleValue", double.class); - } else if (type == STRING) { - environment.getOutput().invokeVirtual(Double.class, "toString", String.class); - } else if (type == ANY) { - MethodOutput output = environment.getOutput(); - - Label lblNotNull = new Label(); - Label lblAfter = new Label(); - - output.dup(); - output.ifNonNull(lblNotNull); - output.aConstNull(); - output.goTo(lblAfter); - - output.label(lblNotNull); - output.invokeVirtual(Double.class, "doubleValue", double.class); - output.invokeStatic(DOUBLE.getAnyClassName(environment), "valueOf", "(D)" + signature(IAny.class)); - - output.label(lblAfter); - } else { - environment.getOutput().invokeVirtual(Double.class, "doubleValue", double.class); - DOUBLE.compileCast(position, environment, type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else if (type == DOUBLE) { + * environment.getOutput().invokeVirtual(Double.class, "doubleValue", + * double.class); } else if (type == STRING) { + * environment.getOutput().invokeVirtual(Double.class, "toString", + * String.class); } else if (type == ANY) { MethodOutput output = + * environment.getOutput(); + * + * Label lblNotNull = new Label(); Label lblAfter = new Label(); + * + * output.dup(); output.ifNonNull(lblNotNull); output.aConstNull(); + * output.goTo(lblAfter); + * + * output.label(lblNotNull); output.invokeVirtual(Double.class, + * "doubleValue", double.class); + * output.invokeStatic(DOUBLE.getAnyClassName(environment), "valueOf", "(D)" + * + signature(IAny.class)); + * + * output.label(lblAfter); } else { + * environment.getOutput().invokeVirtual(Double.class, "doubleValue", + * double.class); DOUBLE.compileCast(position, environment, type); } } + */ @Override public String getName() { return "double?"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { return DOUBLE.getAnyClassName(environment); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFloat.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFloat.java index 0f26f95..e65eca6 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFloat.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFloat.java @@ -44,12 +44,14 @@ import stanhebben.zenscript.value.IAny; public class ZenTypeFloat extends ZenType { public static final ZenTypeFloat INSTANCE = new ZenTypeFloat(); - - //private static final JavaMethod FLOAT_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Float.class, "toString", float.class); + + // private static final JavaMethod FLOAT_TOSTRING = + // JavaMethod.get(EMPTY_REGISTRY, Float.class, "toString", float.class); private static final String ANY_NAME = "any/AnyFloat"; private static final String ANY_NAME_2 = "any.AnyFloat"; - - private ZenTypeFloat() {} + + private ZenTypeFloat() { + } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { @@ -69,41 +71,33 @@ public class ZenTypeFloat extends ZenType { rules.registerCastingRule(FLOATOBJECT, new CastingRuleStaticMethod(FLOAT_VALUEOF)); rules.registerCastingRule(DOUBLE, new CastingRuleF2D(null)); rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleStaticMethod(DOUBLE_VALUEOF, new CastingRuleF2D(null))); - + rules.registerCastingRule(STRING, new CastingRuleStaticMethod(FLOAT_TOSTRING_STATIC)); rules.registerCastingRule(ANY, new CastingRuleStaticMethod(JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, FLOAT))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return (type.getNumberType() != 0) - || type == ZenTypeString.INSTANCE - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return type.getNumberType() != 0 - || type == ZenTypeString.INSTANCE - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return (type.getNumberType() != 0) || type == + * ZenTypeString.INSTANCE || type == ANY || canCastExpansion(environment, + * type); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return type.getNumberType() != 0 || type == + * ZenTypeString.INSTANCE || type == ANY || canCastExpansion(environment, + * type); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Type toASMType() { @@ -141,52 +135,37 @@ public class ZenTypeFloat extends ZenType { return false; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - MethodOutput output = environment.getOutput(); - - if (type == BYTE) { - output.f2i(); - output.i2b(); - } else if (type == ZenTypeByteObject.INSTANCE) { - output.f2i(); - output.i2b(); - output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); - } else if (type == SHORT) { - output.f2i(); - output.i2s(); - } else if (type == ZenTypeShortObject.INSTANCE) { - output.f2i(); - output.i2s(); - output.invokeStatic(Short.class, "valueOf", Short.class, short.class); - } else if (type == INT) { - output.f2i(); - } else if (type == ZenTypeIntObject.INSTANCE) { - output.f2i(); - output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); - } else if (type == LONG) { - output.f2l(); - } else if (type == ZenTypeLongObject.INSTANCE) { - output.f2l(); - output.invokeStatic(Long.class, "valueOf", Long.class, long.class); - } else if (type == FLOAT) { - // nothing to do - } else if (type == ZenTypeFloatObject.INSTANCE) { - output.invokeStatic(Float.class, "valueOf", Float.class, float.class); - } else if (type == DOUBLE) { - output.f2d(); - } else if (type == ZenTypeDoubleObject.INSTANCE) { - output.f2d(); - output.invokeStatic(Double.class, "valueOf", Double.class, double.class); - } else if (type == STRING) { - output.invokeStatic(Float.class, "toString", String.class, float.class); - } else if (type == ANY) { - output.invokeStatic(getAnyClassName(environment), "valueOf", "(F)" + signature(IAny.class)); - } else if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "cannot cast " + this + " to " + type); - } - }*/ - + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { MethodOutput output = + * environment.getOutput(); + * + * if (type == BYTE) { output.f2i(); output.i2b(); } else if (type == + * ZenTypeByteObject.INSTANCE) { output.f2i(); output.i2b(); + * output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); } + * else if (type == SHORT) { output.f2i(); output.i2s(); } else if (type == + * ZenTypeShortObject.INSTANCE) { output.f2i(); output.i2s(); + * output.invokeStatic(Short.class, "valueOf", Short.class, short.class); } + * else if (type == INT) { output.f2i(); } else if (type == + * ZenTypeIntObject.INSTANCE) { output.f2i(); + * output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); + * } else if (type == LONG) { output.f2l(); } else if (type == + * ZenTypeLongObject.INSTANCE) { output.f2l(); + * output.invokeStatic(Long.class, "valueOf", Long.class, long.class); } + * else if (type == FLOAT) { // nothing to do } else if (type == + * ZenTypeFloatObject.INSTANCE) { output.invokeStatic(Float.class, + * "valueOf", Float.class, float.class); } else if (type == DOUBLE) { + * output.f2d(); } else if (type == ZenTypeDoubleObject.INSTANCE) { + * output.f2d(); output.invokeStatic(Double.class, "valueOf", Double.class, + * double.class); } else if (type == STRING) { + * output.invokeStatic(Float.class, "toString", String.class, float.class); + * } else if (type == ANY) { + * output.invokeStatic(getAnyClassName(environment), "valueOf", "(F)" + + * signature(IAny.class)); } else if (!compileCastExpansion(position, + * environment, type)) { environment.error(position, "cannot cast " + this + + * " to " + type); } } + */ + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return new ExpressionArithmeticUnary(position, operator, value); @@ -201,16 +180,16 @@ public class ZenTypeFloat extends ZenType { left.cast(position, environment, STRING), right.cast(position, environment, STRING), OperatorType.CAT); } - + return new ExpressionArithmeticBinary(position, operator, left, right.cast(position, environment, this)); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "float doesn't support this operation"); return new ExpressionInvalid(position); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { return new ExpressionArithmeticCompare(position, type, left, right.cast(position, environment, this)); @@ -232,14 +211,14 @@ public class ZenTypeFloat extends ZenType { public String getName() { return "float"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { if (!environment.containsClass(ANY_NAME_2)) { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionFloat(environment), ANY_NAME, Type.FLOAT_TYPE)); } - + return ANY_NAME; } @@ -247,10 +226,10 @@ public class ZenTypeFloat extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionFloat(position, 0.0, FLOAT); } - + private class AnyDefinitionFloat implements IAnyDefinition { private final IEnvironmentGlobal environment; - + public AnyDefinitionFloat(IEnvironmentGlobal environment) { this.environment = environment; } @@ -258,7 +237,7 @@ public class ZenTypeFloat extends ZenType { @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "F", null, null); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(F)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(ANY_NAME); @@ -267,7 +246,7 @@ public class ZenTypeFloat extends ZenType { valueOf.construct(ANY_NAME, "F"); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(F)V", null, null); constructor.start(); constructor.loadObject(0); @@ -278,43 +257,43 @@ public class ZenTypeFloat extends ZenType { constructor.returnType(Type.VOID_TYPE); constructor.end(); } - + @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblCan = new Label(); - + output.constant(Type.BYTE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.SHORT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.INT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.LONG_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.FLOAT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.DOUBLE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(FLOAT, output, environment, 0); } - + output.iConst0(); output.returnInt(); - + output.label(lblCan); output.iConst1(); output.returnInt(); @@ -326,7 +305,7 @@ public class ZenTypeFloat extends ZenType { if (expansion != null) { expansion.compileAnyCast(FLOAT, output, environment, 0, 1); } - + throwCastException(output, "float", 1); } @@ -552,21 +531,21 @@ public class ZenTypeFloat extends ZenType { @Override public void defineAs(MethodOutput output) { int localValue = output.local(Type.FLOAT_TYPE); - + getValue(output); output.store(Type.FLOAT_TYPE, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(FLOAT, output, environment, localValue, 1); } - + throwCastException(output, "float", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); - + output.loadObject(1); output.constant(Type.FLOAT_TYPE); output.ifACmpEq(lblEq); @@ -576,7 +555,7 @@ public class ZenTypeFloat extends ZenType { output.iConst1(); output.returnInt(); } - + @Override public void defineGetNumberType(MethodOutput output) { output.constant(IAny.NUM_FLOAT); @@ -592,7 +571,7 @@ public class ZenTypeFloat extends ZenType { public void defineIteratorMulti(MethodOutput output) { throwUnsupportedException(output, "float", "iterator"); } - + private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "F"); @@ -601,20 +580,20 @@ public class ZenTypeFloat extends ZenType { @Override public void defineEquals(MethodOutput output) { Label lblNope = new Label(); - + output.loadObject(1); output.instanceOf(IAny.NAME); output.ifEQ(lblNope); - + getValue(output); output.loadObject(1); METHOD_ASFLOAT.invokeVirtual(output); output.fCmp(); output.ifICmpNE(lblNope); - + output.iConst1(); output.returnInt(); - + output.label(lblNope); output.iConst0(); output.returnInt(); @@ -622,7 +601,7 @@ public class ZenTypeFloat extends ZenType { @Override public void defineHashCode(MethodOutput output) { - //return Float.floatToIntBits(value); + // return Float.floatToIntBits(value); getValue(output); output.invokeStatic(Float.class, "floatToIntBits", float.class, int.class); output.returnInt(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFloatObject.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFloatObject.java index 924a3a2..363299d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFloatObject.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFloatObject.java @@ -32,8 +32,9 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; */ public class ZenTypeFloatObject extends ZenType { public static final ZenTypeFloatObject INSTANCE = new ZenTypeFloatObject(); - - private ZenTypeFloatObject() {} + + private ZenTypeFloatObject() { + } @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { @@ -101,37 +102,31 @@ public class ZenTypeFloatObject extends ZenType { rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleNullableStaticMethod( DOUBLE_VALUEOF, new CastingRuleVirtualMethod(DOUBLE_VALUE))); - + rules.registerCastingRule(STRING, new CastingRuleNullableVirtualMethod(FLOATOBJECT, FLOAT_TOSTRING)); rules.registerCastingRule(ANY, new CastingRuleNullableStaticMethod( JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, FLOAT), new CastingRuleVirtualMethod(FLOAT_VALUE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return FLOAT.canCastImplicit(type, environment); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return FLOAT.canCastExplicit(type, environment); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return FLOAT.canCastImplicit(type, environment); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return FLOAT.canCastExplicit(type, environment); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Class toJavaClass() { @@ -158,41 +153,35 @@ public class ZenTypeFloatObject extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else if (type == FLOAT) { - environment.getOutput().invokeVirtual(Float.class, "floatValue", float.class); - } else if (type == STRING) { - environment.getOutput().invokeVirtual(Float.class, "toString", String.class); - } else if (type == ANY) { - MethodOutput output = environment.getOutput(); - - Label lblNotNull = new Label(); - Label lblAfter = new Label(); - - output.dup(); - output.ifNonNull(lblNotNull); - output.aConstNull(); - output.goTo(lblAfter); - - output.label(lblNotNull); - output.invokeVirtual(Float.class, "floatValue", float.class); - output.invokeStatic(FLOAT.getAnyClassName(environment), "valueOf", "(F)" + signature(IAny.class)); - - output.label(lblAfter); - } else { - environment.getOutput().invokeVirtual(Float.class, "floatValue", float.class); - FLOAT.compileCast(position, environment, type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else if (type == FLOAT) { + * environment.getOutput().invokeVirtual(Float.class, "floatValue", + * float.class); } else if (type == STRING) { + * environment.getOutput().invokeVirtual(Float.class, "toString", + * String.class); } else if (type == ANY) { MethodOutput output = + * environment.getOutput(); + * + * Label lblNotNull = new Label(); Label lblAfter = new Label(); + * + * output.dup(); output.ifNonNull(lblNotNull); output.aConstNull(); + * output.goTo(lblAfter); + * + * output.label(lblNotNull); output.invokeVirtual(Float.class, "floatValue", + * float.class); output.invokeStatic(FLOAT.getAnyClassName(environment), + * "valueOf", "(F)" + signature(IAny.class)); + * + * output.label(lblAfter); } else { + * environment.getOutput().invokeVirtual(Float.class, "floatValue", + * float.class); FLOAT.compileCast(position, environment, type); } } + */ @Override public String getName() { return "float?"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { return FLOAT.getAnyClassName(environment); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFunction.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFunction.java index 0af4649..41a3011 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFunction.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeFunction.java @@ -35,14 +35,14 @@ public class ZenTypeFunction extends ZenType { private final ZenType[] argumentTypes; private final String name; private final Map implementedInterfaces = new HashMap(); - + public ZenTypeFunction(ZenType returnType, List arguments) { this.returnType = returnType; argumentTypes = new ZenType[arguments.size()]; for (int i = 0; i < argumentTypes.length; i++) { argumentTypes[i] = arguments.get(i).getType(); } - + StringBuilder nameBuilder = new StringBuilder(); nameBuilder.append("function("); boolean first = true; @@ -57,11 +57,11 @@ public class ZenTypeFunction extends ZenType { nameBuilder.append(returnType.getName()); name = nameBuilder.toString(); } - + public ZenTypeFunction(ZenType returnType, ZenType[] argumentTypes) { this.returnType = returnType; this.argumentTypes = argumentTypes; - + StringBuilder nameBuilder = new StringBuilder(); nameBuilder.append("function("); for (ZenType type : argumentTypes) { @@ -71,7 +71,7 @@ public class ZenTypeFunction extends ZenType { nameBuilder.append(returnType.getName()); name = nameBuilder.toString(); } - + @Override public String getAnyClassName(IEnvironmentGlobal global) { throw new UnsupportedOperationException("functions cannot yet be used as any value"); @@ -93,24 +93,24 @@ public class ZenTypeFunction extends ZenType { public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { return null; } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { if (followCasters) { constructExpansionCastingRules(environment, rules); } } - + @Override public ICastingRule getCastingRule(ZenType type, IEnvironmentGlobal environment) { if (implementedInterfaces.containsKey(type)) { return implementedInterfaces.get(type); } - + Class cls = type.toJavaClass(); - + System.out.println("Can cast this function to " + cls.getName() + "?"); - + if (cls.isInterface() && cls.getMethods().length == 1) { // this is a functional interface // do the method signatures match? @@ -124,13 +124,13 @@ public class ZenTypeFunction extends ZenType { return null; } } - + java.lang.reflect.Type[] methodParameters = method.getGenericParameterTypes(); if (methodParameters.length < argumentTypes.length) { System.out.println("Argument count doesn't match"); return null; } - + ICastingRule[] argumentCastingRules = new ICastingRule[argumentTypes.length]; for (int i = 0; i < argumentCastingRules.length; i++) { ZenType argumentType = environment.getType(methodParameters[i]); @@ -143,13 +143,13 @@ public class ZenTypeFunction extends ZenType { } } } - + CastingRuleMatchedFunction castingRule = new CastingRuleMatchedFunction(this, type, returnCastingRule, argumentCastingRules); implementedInterfaces.put(type, castingRule); System.out.println("Can cast this function"); return castingRule; } - + return null; } @@ -172,7 +172,7 @@ public class ZenTypeFunction extends ZenType { public boolean isPointer() { return true; } - + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { environment.error(position, "cannot apply operators on a function"); @@ -184,13 +184,13 @@ public class ZenTypeFunction extends ZenType { environment.error(position, "cannot apply operators on a function"); return new ExpressionInvalid(position, ZenTypeAny.INSTANCE); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "cannot apply operators on a function"); return new ExpressionInvalid(position, ZenTypeAny.INSTANCE); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { environment.error(position, "cannot apply operators on a function"); @@ -202,7 +202,7 @@ public class ZenTypeFunction extends ZenType { ZenPosition position, IEnvironmentGlobal environment, Expression receiver, Expression... arguments) { return null; // TODO: complete } - + @Override public ZenType[] predictCallTypes(int numArguments) { return Arrays.copyOf(argumentTypes, numArguments); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeInt.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeInt.java index 3a6c200..282541b 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeInt.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeInt.java @@ -43,18 +43,20 @@ import stanhebben.zenscript.value.IAny; public class ZenTypeInt extends ZenType { public static final ZenTypeInt INSTANCE = new ZenTypeInt(); - - //private static final JavaMethod INT_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Integer.class, "toString", byte.class); + + // private static final JavaMethod INT_TOSTRING = + // JavaMethod.get(EMPTY_REGISTRY, Integer.class, "toString", byte.class); private static final String ANY_NAME = "any/AnyInt"; private static final String ANY_NAME_2 = "any.AnyInt"; - - private ZenTypeInt() {} + + private ZenTypeInt() { + } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { return null; } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { rules.registerCastingRule(BYTE, new CastingRuleI2B(null)); @@ -68,41 +70,33 @@ public class ZenTypeInt extends ZenType { rules.registerCastingRule(FLOATOBJECT, new CastingRuleStaticMethod(FLOAT_VALUEOF, new CastingRuleI2F(null))); rules.registerCastingRule(DOUBLE, new CastingRuleI2D(null)); rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleStaticMethod(DOUBLE_VALUEOF, new CastingRuleI2D(null))); - + rules.registerCastingRule(STRING, new CastingRuleStaticMethod(INT_TOSTRING_STATIC)); rules.registerCastingRule(ANY, new CastingRuleStaticMethod(JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, INT))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return (type.getNumberType() != 0 && type.getNumberType() >= NUM_INT) - || type == ZenTypeString.INSTANCE - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return type.getNumberType() != 0 - || type == ZenTypeString.INSTANCE - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return (type.getNumberType() != 0 && type.getNumberType() + * >= NUM_INT) || type == ZenTypeString.INSTANCE || type == ANY || + * canCastExpansion(environment, type); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return type.getNumberType() != 0 || type == + * ZenTypeString.INSTANCE || type == ANY || canCastExpansion(environment, + * type); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Type toASMType() { @@ -140,48 +134,36 @@ public class ZenTypeInt extends ZenType { return false; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - MethodOutput output = environment.getOutput(); - - if (type == BYTE) { - output.i2b(); - } else if (type == ZenTypeByteObject.INSTANCE) { - output.i2b(); - output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); - } else if (type == SHORT) { - output.i2s(); - } else if (type == ZenTypeShortObject.INSTANCE) { - output.i2s(); - output.invokeStatic(Short.class, "valueOf", Short.class, short.class); - } else if (type == INT) { - // nothing to do - } else if (type == ZenTypeIntObject.INSTANCE) { - output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); - } else if (type == LONG) { - output.i2l(); - } else if (type == ZenTypeLongObject.INSTANCE) { - output.i2l(); - output.invokeStatic(Long.class, "valueOf", Long.class, long.class); - } else if (type == FLOAT) { - output.i2f(); - } else if (type == ZenTypeFloatObject.INSTANCE) { - output.i2f(); - output.invokeStatic(Float.class, "valueOf", Float.class, float.class); - } else if (type == DOUBLE) { - output.i2d(); - } else if (type == ZenTypeDoubleObject.INSTANCE) { - output.i2d(); - output.invokeStatic(Double.class, "valueOf", Double.class, double.class); - } else if (type == STRING) { - output.invokeStatic(Integer.class, "toString", String.class, int.class); - } else if (type == ANY) { - output.invokeStatic(getAnyClassName(environment), "valueOf", "(I)" + signature(IAny.class)); - } else if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "cannot cast " + this + " to " + type); - } - }*/ - + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { MethodOutput output = + * environment.getOutput(); + * + * if (type == BYTE) { output.i2b(); } else if (type == + * ZenTypeByteObject.INSTANCE) { output.i2b(); + * output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); } + * else if (type == SHORT) { output.i2s(); } else if (type == + * ZenTypeShortObject.INSTANCE) { output.i2s(); + * output.invokeStatic(Short.class, "valueOf", Short.class, short.class); } + * else if (type == INT) { // nothing to do } else if (type == + * ZenTypeIntObject.INSTANCE) { output.invokeStatic(Integer.class, + * "valueOf", Integer.class, int.class); } else if (type == LONG) { + * output.i2l(); } else if (type == ZenTypeLongObject.INSTANCE) { + * output.i2l(); output.invokeStatic(Long.class, "valueOf", Long.class, + * long.class); } else if (type == FLOAT) { output.i2f(); } else if (type == + * ZenTypeFloatObject.INSTANCE) { output.i2f(); + * output.invokeStatic(Float.class, "valueOf", Float.class, float.class); } + * else if (type == DOUBLE) { output.i2d(); } else if (type == + * ZenTypeDoubleObject.INSTANCE) { output.i2d(); + * output.invokeStatic(Double.class, "valueOf", Double.class, double.class); + * } else if (type == STRING) { output.invokeStatic(Integer.class, + * "toString", String.class, int.class); } else if (type == ANY) { + * output.invokeStatic(getAnyClassName(environment), "valueOf", "(I)" + + * signature(IAny.class)); } else if (!compileCastExpansion(position, + * environment, type)) { environment.error(position, "cannot cast " + this + + * " to " + type); } } + */ + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return new ExpressionArithmeticUnary(position, operator, value); @@ -196,16 +178,16 @@ public class ZenTypeInt extends ZenType { left.cast(position, environment, STRING), right.cast(position, environment, STRING), OperatorType.CAT); } - + return new ExpressionArithmeticBinary(position, operator, left, right.cast(position, environment, this)); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "int doesn't support this operation"); return new ExpressionInvalid(position); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { return new ExpressionArithmeticCompare(position, type, left, right.cast(position, environment, this)); @@ -227,14 +209,14 @@ public class ZenTypeInt extends ZenType { public String getName() { return "int"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { if (!environment.containsClass(ANY_NAME_2)) { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionInt(environment), ANY_NAME, Type.INT_TYPE)); } - + return ANY_NAME; } @@ -242,10 +224,10 @@ public class ZenTypeInt extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionInt(position, 0, INT); } - + private class AnyDefinitionInt implements IAnyDefinition { private final IEnvironmentGlobal environment; - + public AnyDefinitionInt(IEnvironmentGlobal environment) { this.environment = environment; } @@ -253,7 +235,7 @@ public class ZenTypeInt extends ZenType { @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "I", null, null); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(I)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(ANY_NAME); @@ -262,7 +244,7 @@ public class ZenTypeInt extends ZenType { valueOf.construct(ANY_NAME, "I"); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(I)V", null, null); constructor.start(); constructor.loadObject(0); @@ -273,43 +255,43 @@ public class ZenTypeInt extends ZenType { constructor.returnType(Type.VOID_TYPE); constructor.end(); } - + @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblCan = new Label(); - + output.constant(Type.BYTE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.SHORT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.INT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.LONG_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.FLOAT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.DOUBLE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(INT, output, environment, 0); } - + output.iConst0(); output.returnInt(); - + output.label(lblCan); output.iConst1(); output.returnInt(); @@ -321,7 +303,7 @@ public class ZenTypeInt extends ZenType { if (expansion != null) { expansion.compileAnyCast(INT, output, environment, 0, 1); } - + throwCastException(output, "int", 1); } @@ -572,21 +554,21 @@ public class ZenTypeInt extends ZenType { @Override public void defineAs(MethodOutput output) { int localValue = output.local(Type.INT_TYPE); - + getValue(output); output.store(Type.INT_TYPE, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(INT, output, environment, localValue, 1); } - + throwCastException(output, "int", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); - + output.loadObject(1); output.constant(Type.INT_TYPE); output.ifACmpEq(lblEq); @@ -596,7 +578,7 @@ public class ZenTypeInt extends ZenType { output.iConst1(); output.returnInt(); } - + @Override public void defineGetNumberType(MethodOutput output) { output.constant(IAny.NUM_INT); @@ -612,7 +594,7 @@ public class ZenTypeInt extends ZenType { public void defineIteratorMulti(MethodOutput output) { throwUnsupportedException(output, "int", "iterator"); } - + private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "I"); @@ -621,19 +603,19 @@ public class ZenTypeInt extends ZenType { @Override public void defineEquals(MethodOutput output) { Label lblNope = new Label(); - + output.loadObject(1); output.instanceOf(IAny.NAME); output.ifEQ(lblNope); - + getValue(output); output.loadObject(1); METHOD_ASINT.invokeVirtual(output); output.ifICmpNE(lblNope); - + output.iConst1(); output.returnInt(); - + output.label(lblNope); output.iConst0(); output.returnInt(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntObject.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntObject.java index 3538259..5fec927 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntObject.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntObject.java @@ -32,8 +32,9 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; */ public class ZenTypeIntObject extends ZenType { public static final ZenTypeIntObject INSTANCE = new ZenTypeIntObject(); - - private ZenTypeIntObject() {} + + private ZenTypeIntObject() { + } @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { @@ -101,37 +102,31 @@ public class ZenTypeIntObject extends ZenType { rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleNullableStaticMethod( DOUBLE_VALUEOF, new CastingRuleVirtualMethod(DOUBLE_VALUE))); - + rules.registerCastingRule(STRING, new CastingRuleNullableVirtualMethod(INTOBJECT, INT_TOSTRING)); rules.registerCastingRule(ANY, new CastingRuleNullableStaticMethod( JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, INT), new CastingRuleVirtualMethod(DOUBLE_VALUE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return INT.canCastImplicit(type, environment); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return INT.canCastExplicit(type, environment); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return INT.canCastImplicit(type, environment); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return INT.canCastExplicit(type, environment); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Class toJavaClass() { @@ -158,41 +153,35 @@ public class ZenTypeIntObject extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else if (type == INT) { - environment.getOutput().invokeVirtual(Integer.class, "intValue", int.class); - } else if (type == STRING) { - environment.getOutput().invokeVirtual(Integer.class, "toString", String.class); - } else if (type == ANY) { - MethodOutput output = environment.getOutput(); - - Label lblNotNull = new Label(); - Label lblAfter = new Label(); - - output.dup(); - output.ifNonNull(lblNotNull); - output.aConstNull(); - output.goTo(lblAfter); - - output.label(lblNotNull); - output.invokeVirtual(Integer.class, "intValue", int.class); - output.invokeStatic(INT.getAnyClassName(environment), "valueOf", "(I)" + signature(IAny.class)); - - output.label(lblAfter); - } else { - environment.getOutput().invokeVirtual(Integer.class, "intValue", int.class); - INT.compileCast(position, environment, type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else if (type == INT) { + * environment.getOutput().invokeVirtual(Integer.class, "intValue", + * int.class); } else if (type == STRING) { + * environment.getOutput().invokeVirtual(Integer.class, "toString", + * String.class); } else if (type == ANY) { MethodOutput output = + * environment.getOutput(); + * + * Label lblNotNull = new Label(); Label lblAfter = new Label(); + * + * output.dup(); output.ifNonNull(lblNotNull); output.aConstNull(); + * output.goTo(lblAfter); + * + * output.label(lblNotNull); output.invokeVirtual(Integer.class, "intValue", + * int.class); output.invokeStatic(INT.getAnyClassName(environment), + * "valueOf", "(I)" + signature(IAny.class)); + * + * output.label(lblAfter); } else { + * environment.getOutput().invokeVirtual(Integer.class, "intValue", + * int.class); INT.compileCast(position, environment, type); } } + */ @Override public String getName() { return "int?"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { return INT.getAnyClassName(environment); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntRange.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntRange.java index 4aac285..cdf022d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntRange.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeIntRange.java @@ -33,21 +33,21 @@ import stanhebben.zenscript.value.IntRange; */ public class ZenTypeIntRange extends ZenType { public static final ZenTypeIntRange INSTANCE = new ZenTypeIntRange(); - + private final IJavaMethod methodFrom; private final IJavaMethod methodTo; - + private ZenTypeIntRange() { ITypeRegistry dummy = new TypeRegistry(); methodFrom = JavaMethod.get(dummy, IntRange.class, "getFrom"); methodTo = JavaMethod.get(dummy, IntRange.class, "getTo"); } - + @Override public String getAnyClassName(IEnvironmentGlobal global) { throw new UnsupportedOperationException("range values cannot yet be used as any value"); } - + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { environment.error(position, "cannot apply unary operators on int ranges"); @@ -95,21 +95,20 @@ public class ZenTypeIntRange extends ZenType { environment.error(position, "int ranges cannot be called"); return new ExpressionInvalid(position); } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { - + } - /*@Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type == this) { - return value; - } - - environment.error(position, "cannot cast int ranges to any other type"); - return new ExpressionInvalid(position); - }*/ + /* + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type == this) { return + * value; } + * + * environment.error(position, "cannot cast int ranges to any other type"); + * return new ExpressionInvalid(position); } + */ @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { @@ -120,15 +119,13 @@ public class ZenTypeIntRange extends ZenType { } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return type == this; - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return type == this; - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return type == this; } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return type == this; } + */ @Override public Class toJavaClass() { @@ -155,10 +152,12 @@ public class ZenTypeIntRange extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { throw new + * UnsupportedOperationException("Not supported yet."); //To change body of + * generated methods, choose Tools | Templates. } + */ @Override public String getName() { @@ -169,10 +168,10 @@ public class ZenTypeIntRange extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionNull(position); } - + private class IntRangeIterator implements IZenIterator { private final IEnvironmentMethod method; - + public IntRangeIterator(IEnvironmentMethod methodOutput) { this.method = methodOutput; } @@ -180,7 +179,7 @@ public class ZenTypeIntRange extends ZenType { @Override public void compileStart(int[] locals) { MethodOutput output = method.getOutput(); - + output.dup(); // copy IntRange reference methodFrom.invokeVirtual(output); output.storeInt(locals[0]); @@ -188,21 +187,21 @@ public class ZenTypeIntRange extends ZenType { @Override public void compilePreIterate(int[] locals, Label exit) { - + } @Override public void compilePostIterate(int[] locals, Label exit, Label repeat) { MethodOutput output = method.getOutput(); - + output.dup(); // copy IntRange reference methodTo.invokeVirtual(output); - + output.loadInt(locals[0]); output.iinc(locals[0]); output.dup(); output.storeInt(locals[0]); - + output.ifICmpGT(repeat); output.goTo(exit); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeLong.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeLong.java index 67066a1..0c0c714 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeLong.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeLong.java @@ -45,12 +45,14 @@ import stanhebben.zenscript.value.IAny; public class ZenTypeLong extends ZenType { public static final ZenTypeLong INSTANCE = new ZenTypeLong(); - - //private static final JavaMethod LONG_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Long.class, "toString", long.class); + + // private static final JavaMethod LONG_TOSTRING = + // JavaMethod.get(EMPTY_REGISTRY, Long.class, "toString", long.class); private static final String ANY_NAME = "any/AnyLong"; private static final String ANY_NAME_2 = "any.AnyLong"; - - private ZenTypeLong() {} + + private ZenTypeLong() { + } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { @@ -70,41 +72,33 @@ public class ZenTypeLong extends ZenType { rules.registerCastingRule(FLOATOBJECT, new CastingRuleStaticMethod(FLOAT_VALUEOF, new CastingRuleI2F(null))); rules.registerCastingRule(DOUBLE, new CastingRuleI2D(null)); rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleStaticMethod(DOUBLE_VALUEOF, new CastingRuleI2D(null))); - + rules.registerCastingRule(STRING, new CastingRuleStaticMethod(LONG_TOSTRING_STATIC)); rules.registerCastingRule(ANY, new CastingRuleStaticMethod(JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, LONG))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return (type.getNumberType() != 0 && type.getNumberType() >= NUM_LONG) - || type == ZenTypeString.INSTANCE - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return type.getNumberType() != 0 - || type == ZenTypeString.INSTANCE - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return (type.getNumberType() != 0 && type.getNumberType() + * >= NUM_LONG) || type == ZenTypeString.INSTANCE || type == ANY || + * canCastExpansion(environment, type); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return type.getNumberType() != 0 || type == + * ZenTypeString.INSTANCE || type == ANY || canCastExpansion(environment, + * type); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Type toASMType() { @@ -142,52 +136,36 @@ public class ZenTypeLong extends ZenType { return false; } - /*@Override - public void compileCast(stanhebben.zenscript.util.ZenPosition position, IEnvironmentMethod environment, ZenType type) { - MethodOutput output = environment.getOutput(); - - if (type == BYTE) { - output.l2i(); - output.i2b(); - } else if (type == ZenTypeByteObject.INSTANCE) { - output.l2i(); - output.i2b(); - output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); - } else if (type == SHORT) { - output.l2i(); - output.i2s(); - } else if (type == ZenTypeShortObject.INSTANCE) { - output.l2i(); - output.i2s(); - output.invokeStatic(Short.class, "valueOf", Short.class, short.class); - } else if (type == INT) { - output.l2i(); - } else if (type == ZenTypeIntObject.INSTANCE) { - output.l2i(); - output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); - } else if (type == LONG) { - // nothing to do - } else if (type == ZenTypeLongObject.INSTANCE) { - output.invokeStatic(Long.class, "valueOf", Long.class, long.class); - } else if (type == FLOAT) { - output.l2f(); - } else if (type == ZenTypeFloatObject.INSTANCE) { - output.l2f(); - output.invokeStatic(Float.class, "valueOf", Float.class, float.class); - } else if (type == DOUBLE) { - output.l2d(); - } else if (type == ZenTypeDoubleObject.INSTANCE) { - output.l2d(); - output.invokeStatic(Double.class, "valueOf", Double.class, double.class); - } else if (type == STRING) { - output.invokeStatic(Long.class, "toString", String.class, long.class); - } else if (type == ANY) { - output.invokeStatic(getAnyClassName(environment), "valueOf", "(J)" + signature(IAny.class)); - } else if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "cannot cast " + this + " to " + type); - } - }*/ - + /* + * @Override public void compileCast(stanhebben.zenscript.util.ZenPosition + * position, IEnvironmentMethod environment, ZenType type) { MethodOutput + * output = environment.getOutput(); + * + * if (type == BYTE) { output.l2i(); output.i2b(); } else if (type == + * ZenTypeByteObject.INSTANCE) { output.l2i(); output.i2b(); + * output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); } + * else if (type == SHORT) { output.l2i(); output.i2s(); } else if (type == + * ZenTypeShortObject.INSTANCE) { output.l2i(); output.i2s(); + * output.invokeStatic(Short.class, "valueOf", Short.class, short.class); } + * else if (type == INT) { output.l2i(); } else if (type == + * ZenTypeIntObject.INSTANCE) { output.l2i(); + * output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); + * } else if (type == LONG) { // nothing to do } else if (type == + * ZenTypeLongObject.INSTANCE) { output.invokeStatic(Long.class, "valueOf", + * Long.class, long.class); } else if (type == FLOAT) { output.l2f(); } else + * if (type == ZenTypeFloatObject.INSTANCE) { output.l2f(); + * output.invokeStatic(Float.class, "valueOf", Float.class, float.class); } + * else if (type == DOUBLE) { output.l2d(); } else if (type == + * ZenTypeDoubleObject.INSTANCE) { output.l2d(); + * output.invokeStatic(Double.class, "valueOf", Double.class, double.class); + * } else if (type == STRING) { output.invokeStatic(Long.class, "toString", + * String.class, long.class); } else if (type == ANY) { + * output.invokeStatic(getAnyClassName(environment), "valueOf", "(J)" + + * signature(IAny.class)); } else if (!compileCastExpansion(position, + * environment, type)) { environment.error(position, "cannot cast " + this + + * " to " + type); } } + */ + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return new ExpressionArithmeticUnary(position, operator, value); @@ -202,16 +180,16 @@ public class ZenTypeLong extends ZenType { left.cast(position, environment, STRING), right.cast(position, environment, STRING), OperatorType.CAT); } - + return new ExpressionArithmeticBinary(position, operator, left, right.cast(position, environment, this)); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "long doesn't support this operation"); return new ExpressionInvalid(position); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { return new ExpressionArithmeticCompare(position, type, left, right.cast(position, environment, this)); @@ -233,17 +211,17 @@ public class ZenTypeLong extends ZenType { public String getName() { return "long"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { if (!environment.containsClass(ANY_NAME_2)) { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionLong(environment), ANY_NAME, Type.LONG_TYPE)); } - + return ANY_NAME; } - + @Override public boolean isLarge() { return true; @@ -253,10 +231,10 @@ public class ZenTypeLong extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionInt(position, 0, LONG); } - + private class AnyDefinitionLong implements IAnyDefinition { private final IEnvironmentGlobal environment; - + public AnyDefinitionLong(IEnvironmentGlobal environment) { this.environment = environment; } @@ -264,7 +242,7 @@ public class ZenTypeLong extends ZenType { @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "J", null, null); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(J)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(ANY_NAME); @@ -273,7 +251,7 @@ public class ZenTypeLong extends ZenType { valueOf.construct(ANY_NAME, "J"); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(J)V", null, null); constructor.start(); constructor.loadObject(0); @@ -284,43 +262,43 @@ public class ZenTypeLong extends ZenType { constructor.returnType(Type.VOID_TYPE); constructor.end(); } - + @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblCan = new Label(); - + output.constant(Type.BYTE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.SHORT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.INT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.LONG_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.FLOAT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.DOUBLE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(LONG, output, environment, 0); } - + output.iConst0(); output.returnInt(); - + output.label(lblCan); output.iConst1(); output.returnInt(); @@ -332,7 +310,7 @@ public class ZenTypeLong extends ZenType { if (expansion != null) { expansion.compileAnyCast(LONG, output, environment, 0, 1); } - + throwCastException(output, "long", 1); } @@ -586,21 +564,21 @@ public class ZenTypeLong extends ZenType { @Override public void defineAs(MethodOutput output) { int localValue = output.local(Type.LONG_TYPE); - + getValue(output); output.store(Type.LONG_TYPE, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(LONG, output, environment, localValue, 1); } - + throwCastException(output, "long", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); - + output.loadObject(1); output.constant(Type.LONG_TYPE); output.ifACmpEq(lblEq); @@ -610,7 +588,7 @@ public class ZenTypeLong extends ZenType { output.iConst1(); output.returnInt(); } - + @Override public void defineGetNumberType(MethodOutput output) { output.constant(IAny.NUM_LONG); @@ -626,7 +604,7 @@ public class ZenTypeLong extends ZenType { public void defineIteratorMulti(MethodOutput output) { throwUnsupportedException(output, "long", "iterator"); } - + private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "J"); @@ -635,20 +613,20 @@ public class ZenTypeLong extends ZenType { @Override public void defineEquals(MethodOutput output) { Label lblNope = new Label(); - + output.loadObject(0); output.instanceOf(IAny.NAME); output.ifEQ(lblNope); - + getValue(output); output.loadObject(1); METHOD_ASLONG.invokeVirtual(output); output.lCmp(); output.ifICmpNE(lblNope); - + output.iConst1(); output.returnInt(); - + output.label(lblNope); output.iConst0(); output.returnInt(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeLongObject.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeLongObject.java index 3367ac3..bf9d6fd 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeLongObject.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeLongObject.java @@ -32,8 +32,9 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; */ public class ZenTypeLongObject extends ZenType { public static final ZenTypeLongObject INSTANCE = new ZenTypeLongObject(); - - private ZenTypeLongObject() {} + + private ZenTypeLongObject() { + } @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { @@ -101,37 +102,31 @@ public class ZenTypeLongObject extends ZenType { rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleNullableStaticMethod( DOUBLE_VALUEOF, new CastingRuleVirtualMethod(DOUBLE_VALUE))); - + rules.registerCastingRule(STRING, new CastingRuleNullableVirtualMethod(LONGOBJECT, LONG_TOSTRING)); rules.registerCastingRule(ANY, new CastingRuleNullableStaticMethod( JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, LONG), new CastingRuleVirtualMethod(LONG_VALUE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return LONG.canCastImplicit(type, environment); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return LONG.canCastExplicit(type, environment); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return LONG.canCastImplicit(type, environment); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return LONG.canCastExplicit(type, environment); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Class toJavaClass() { @@ -158,41 +153,35 @@ public class ZenTypeLongObject extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else if (type == LONG) { - environment.getOutput().invokeVirtual(Long.class, "longValue", long.class); - } else if (type == STRING) { - environment.getOutput().invokeVirtual(Long.class, "toString", String.class); - } else if (type == ANY) { - MethodOutput output = environment.getOutput(); - - Label lblNotNull = new Label(); - Label lblAfter = new Label(); - - output.dup(); - output.ifNonNull(lblNotNull); - output.aConstNull(); - output.goTo(lblAfter); - - output.label(lblNotNull); - output.invokeVirtual(Long.class, "longValue", long.class); - output.invokeStatic(LONG.getAnyClassName(environment), "valueOf", "(J)" + signature(IAny.class)); - - output.label(lblAfter); - } else { - environment.getOutput().invokeVirtual(Long.class, "longValue", long.class); - LONG.compileCast(position, environment, type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else if (type == LONG) { + * environment.getOutput().invokeVirtual(Long.class, "longValue", + * long.class); } else if (type == STRING) { + * environment.getOutput().invokeVirtual(Long.class, "toString", + * String.class); } else if (type == ANY) { MethodOutput output = + * environment.getOutput(); + * + * Label lblNotNull = new Label(); Label lblAfter = new Label(); + * + * output.dup(); output.ifNonNull(lblNotNull); output.aConstNull(); + * output.goTo(lblAfter); + * + * output.label(lblNotNull); output.invokeVirtual(Long.class, "longValue", + * long.class); output.invokeStatic(LONG.getAnyClassName(environment), + * "valueOf", "(J)" + signature(IAny.class)); + * + * output.label(lblAfter); } else { + * environment.getOutput().invokeVirtual(Long.class, "longValue", + * long.class); LONG.compileCast(position, environment, type); } } + */ @Override public String getName() { return "long"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { return LONG.getAnyClassName(environment); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeNative.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeNative.java index 62e5ef2..d56ace4 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeNative.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeNative.java @@ -74,7 +74,7 @@ public class ZenTypeNative extends ZenType { private static final int ITERATOR_ITERABLE = 1; private static final int ITERATOR_LIST = 2; private static final int ITERATOR_MAP = 3; - + private final Class cls; private final String anyName; private final String anyName2; @@ -85,14 +85,14 @@ public class ZenTypeNative extends ZenType { private final List trinaryOperators; private final List binaryOperators; private final List unaryOperators; - + private int iteratorType; private String classPkg; private String className; private Annotation iteratorAnnotation; private ZenType iteratorKeyType; private ZenType iteratorValueType; - + public ZenTypeNative(Class cls) { this.cls = cls; members = new HashMap(); @@ -102,22 +102,22 @@ public class ZenTypeNative extends ZenType { binaryOperators = new ArrayList(); unaryOperators = new ArrayList(); implementing = new ArrayList(); - + anyName2 = cls.getName() + "Any"; anyName = anyName2.replace('.', '/'); } - + public void complete(ITypeRegistry types) { int iterator = ITERATOR_NONE; Annotation _iteratorAnnotation = null; String _classPkg = cls.getPackage().getName().replace('/', '.'); String _className = cls.getSimpleName(); boolean fully = false; - + Queue todo = new LinkedList(); todo.add(this); addSubtypes(todo, types); - + Annotation[] clsAnnotations = cls.getAnnotations(); for (Annotation annotation : clsAnnotations) { if (annotation instanceof ZenClass) { @@ -153,11 +153,11 @@ public class ZenTypeNative extends ZenType { } } } - + for (Method method : cls.getMethods()) { boolean isMethod = fully; String methodName = method.getName(); - + for (Annotation annotation : method.getAnnotations()) { if (annotation instanceof ZenCaster) { casters.add(new ZenNativeCaster(JavaMethod.get(types, method))); @@ -165,7 +165,7 @@ public class ZenTypeNative extends ZenType { } else if (annotation instanceof ZenGetter) { ZenGetter getterAnnotation = (ZenGetter) annotation; String name = getterAnnotation.value().length() == 0 ? method.getName() : getterAnnotation.value(); - + if (!members.containsKey(name)) { members.put(name, new ZenNativeMember()); } @@ -174,7 +174,7 @@ public class ZenTypeNative extends ZenType { } else if (annotation instanceof ZenSetter) { ZenSetter setterAnnotation = (ZenSetter) annotation; String name = setterAnnotation.value().length() == 0 ? method.getName() : setterAnnotation.value(); - + if (!members.containsKey(name)) { members.put(name, new ZenNativeMember()); } @@ -231,14 +231,14 @@ public class ZenTypeNative extends ZenType { isMethod = false; } else if (annotation instanceof ZenMethod) { isMethod = true; - + ZenMethod methodAnnotation = (ZenMethod) annotation; if (methodAnnotation.value().length() > 0) { methodName = methodAnnotation.value(); } } } - + if (isMethod) { if ((method.getModifiers() & Modifier.STATIC) > 0) { if (!staticMembers.containsKey(methodName)) { @@ -253,17 +253,17 @@ public class ZenTypeNative extends ZenType { } } } - + this.iteratorType = iterator; this.iteratorAnnotation = _iteratorAnnotation; this.classPkg = _classPkg; this.className = _className; } - + public Class getNativeClass() { return cls; } - + public void complete(IEnvironmentGlobal environment) { if (iteratorAnnotation instanceof IterableSimple) { IterableSimple annotation = (IterableSimple) iteratorAnnotation; @@ -280,14 +280,15 @@ public class ZenTypeNative extends ZenType { iteratorValueType = ZenType.parse(annotation.value(), environment); } } - + @Override public String getAnyClassName(IEnvironmentGlobal global) { if (!global.containsClass(anyName2)) { global.putClass(anyName2, new byte[0]); - //global.putClass(anyName2, AnyClassWriter.construct(new AnyNativeDefinition(global), anyName2, toASMType())); + // global.putClass(anyName2, AnyClassWriter.construct(new + // AnyNativeDefinition(global), anyName2, toASMType())); } - + return anyName; } @@ -302,14 +303,15 @@ public class ZenTypeNative extends ZenType { } } } - + if (member == null) { Expression evalue = value.eval(environment); IPartialExpression member2 = memberExpansion(position, environment, evalue, name); if (member2 == null) { for (ZenTypeNative type : implementing) { member2 = type.memberExpansion(position, environment, evalue, name); - if (member2 != null) break; + if (member2 != null) + break; } } if (member2 == null) { @@ -348,7 +350,8 @@ public class ZenTypeNative extends ZenType { if (member2 == null) { for (ZenTypeNative type : implementing) { member2 = type.staticMemberExpansion(position, environment, name); - if (member2 != null) break; + if (member2 != null) + break; } } if (member2 == null) { @@ -392,36 +395,36 @@ public class ZenTypeNative extends ZenType { } return null; } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { if (cls.getSuperclass() != null) { ZenType superType = environment.getType(cls.getSuperclass()); - + rules.registerCastingRule(superType, new CastingRuleNone(this, superType)); - + superType.constructCastingRules(environment, rules, followCasters); } - + for (Class iface : cls.getInterfaces()) { ZenType ifaceType = environment.getType(iface); - + rules.registerCastingRule(ifaceType, new CastingRuleNone(this, ifaceType)); - + ifaceType.constructCastingRules(environment, rules, followCasters); } - + if (followCasters) { for (ZenNativeCaster caster : casters) { // TODO: implement } - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.constructCastingRules(environment, rules); } } - + rules.registerCastingRule(BOOL, new CastingNotNull(this)); rules.registerCastingRule(ANY, new CastingRuleNullableStaticMethod(JavaMethod.getStatic( getAnyClassName(environment), @@ -436,7 +439,7 @@ public class ZenTypeNative extends ZenType { || canCastImplicit(type, environment) || type.canCastExplicit(this, environment); } - + @Override public Class toJavaClass() { return cls; @@ -461,7 +464,7 @@ public class ZenTypeNative extends ZenType { public boolean isPointer() { return true; } - + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { for (ZenNativeOperator unaryOperator : unaryOperators) { @@ -469,7 +472,7 @@ public class ZenTypeNative extends ZenType { return new ExpressionCallVirtual(position, environment, unaryOperator.getMethod(), value); } } - + environment.error(position, "operator not supported"); return new ExpressionInvalid(position); } @@ -481,11 +484,11 @@ public class ZenTypeNative extends ZenType { return new ExpressionCallVirtual(position, environment, binaryOperator.getMethod(), left, right); } } - + environment.error(position, "operator not supported"); return new ExpressionInvalid(position); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { for (ZenNativeOperator trinaryOperator : trinaryOperators) { @@ -493,11 +496,11 @@ public class ZenTypeNative extends ZenType { return new ExpressionCallVirtual(position, environment, trinaryOperator.getMethod(), first, second, third); } } - + environment.error(position, "operator not supported"); return new ExpressionInvalid(position); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { if (type == CompareType.EQ || type == CompareType.NE) { @@ -512,7 +515,7 @@ public class ZenTypeNative extends ZenType { } } } - + return new ExpressionCompareGeneric(position, binary(position, environment, left, right, OperatorType.COMPARE), type); } @@ -520,91 +523,82 @@ public class ZenTypeNative extends ZenType { public Expression call( ZenPosition position, IEnvironmentGlobal environment, Expression receiver, Expression... arguments) { // TODO: support functional interfaces - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. } - + @Override public ZenType[] predictCallTypes(int numArguments) { // TODO: support functional interface return new ZenType[numArguments]; } - + private boolean hasBinary(ZenType type, OperatorType operator) { for (ZenNativeOperator binaryOperator : binaryOperators) { if (binaryOperator.getOperator() == operator) { return true; } } - + return false; } - - /*private void compileAnyUnary(String anySignature, OperatorType operator, IEnvironmentMethod environment) { - List operators = new ArrayList(); - for (ZenNativeOperator unary : this.unaryOperators) { - if (unary.getOperator() == operator) { - operators.add(unary); - } - } - - MethodOutput output = environment.getOutput(); - if (operators.isEmpty()) { - output.newObject(ZenRuntimeException.class); - output.dup(); - output.constant("Cannot " + operator + " " + classPkg + '.' + className); - output.construct(ZenRuntimeException.class, String.class); - output.aThrow(); - } else { - if (operators.size() > 1) { - environment.error(null, "Multiple " + operator + " operators for " + cls); - } - - ZenNativeOperator unary = operators.get(0); - - output.loadObject(0); - output.getField(anySignature, "value", signature(cls)); - - output.invoke(unary.getMethod()); - environment.getType(unary.getClass()).compileCast(null, environment, ANY); - output.returnObject(); - } - } - - private void compileAnyBinary(String anySignature, OperatorType operator, IEnvironmentMethod environment) { - List operators = new ArrayList(); - for (ZenNativeOperator binary : binaryOperators) { - if (binary.getOperator() == operator) { - operators.add(binary); - } - } - - MethodOutput output = environment.getOutput(); - if (operators.isEmpty()) { - output.newObject(ZenRuntimeException.class); - output.dup(); - output.constant("Cannot " + operator + " on " + classPkg + '.' + className); - output.construct(ZenRuntimeException.class, String.class); - output.aThrow(); - } else if (operators.size() == 1) { - ZenNativeOperator binary = operators.get(0); - - output.loadObject(0); - output.getField(anySignature, "value", signature(cls)); - output.loadObject(1); - output.invoke(binary.getMethod()); - environment.getType(binary.getClass()).compileCast(null, environment, ANY); - output.returnObject(); - } else { - environment.error(null, "Multiple " + operator + " operators for " + cls + " (which is not yet supported)"); - } - } - - public void compileAnyMember(String anySignature, EnvironmentMethod environment) { - // TODO: complete - MethodOutput output = environment.getOutput(); - output.aConstNull(); - output.returnObject(); - }*/ + + /* + * private void compileAnyUnary(String anySignature, OperatorType operator, + * IEnvironmentMethod environment) { List operators = new + * ArrayList(); for (ZenNativeOperator unary : + * this.unaryOperators) { if (unary.getOperator() == operator) { + * operators.add(unary); } } + * + * MethodOutput output = environment.getOutput(); if (operators.isEmpty()) { + * output.newObject(ZenRuntimeException.class); output.dup(); + * output.constant("Cannot " + operator + " " + classPkg + '.' + className); + * output.construct(ZenRuntimeException.class, String.class); + * output.aThrow(); } else { if (operators.size() > 1) { + * environment.error(null, "Multiple " + operator + " operators for " + + * cls); } + * + * ZenNativeOperator unary = operators.get(0); + * + * output.loadObject(0); output.getField(anySignature, "value", + * signature(cls)); + * + * output.invoke(unary.getMethod()); + * environment.getType(unary.getClass()).compileCast(null, environment, + * ANY); output.returnObject(); } } + * + * private void compileAnyBinary(String anySignature, OperatorType operator, + * IEnvironmentMethod environment) { List operators = new + * ArrayList(); for (ZenNativeOperator binary : + * binaryOperators) { if (binary.getOperator() == operator) { + * operators.add(binary); } } + * + * MethodOutput output = environment.getOutput(); if (operators.isEmpty()) { + * output.newObject(ZenRuntimeException.class); output.dup(); + * output.constant("Cannot " + operator + " on " + classPkg + '.' + + * className); output.construct(ZenRuntimeException.class, String.class); + * output.aThrow(); } else if (operators.size() == 1) { ZenNativeOperator + * binary = operators.get(0); + * + * output.loadObject(0); output.getField(anySignature, "value", + * signature(cls)); output.loadObject(1); output.invoke(binary.getMethod()); + * environment.getType(binary.getClass()).compileCast(null, environment, + * ANY); output.returnObject(); } else { environment.error(null, "Multiple " + * + operator + " operators for " + cls + " (which is not yet supported)"); + * } } + * + * public void compileAnyMember(String anySignature, EnvironmentMethod + * environment) { // TODO: complete MethodOutput output = + * environment.getOutput(); output.aConstNull(); output.returnObject(); } + */ @Override public String getName() { @@ -615,7 +609,7 @@ public class ZenTypeNative extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionNull(position); } - + private void addSubtypes(Queue todo, ITypeRegistry types) { while (!todo.isEmpty()) { ZenTypeNative current = todo.poll(); @@ -635,10 +629,10 @@ public class ZenTypeNative extends ZenType { } } } - + private class AnyNativeDefinition implements IAnyDefinition { private final IEnvironmentGlobal environment; - + public AnyNativeDefinition(IEnvironmentGlobal environment) { this.environment = environment; } @@ -646,7 +640,7 @@ public class ZenTypeNative extends ZenType { @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "F", null, null); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(F)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(anyName2); @@ -655,7 +649,7 @@ public class ZenTypeNative extends ZenType { valueOf.construct(anyName2, "L" + cls.getName() + ";"); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(L" + cls.getName() + ";)V", null, null); constructor.start(); constructor.loadObject(0); @@ -674,24 +668,24 @@ public class ZenTypeNative extends ZenType { output.constant(Type.getType(cls)); output.loadObject(1); output.invokeVirtual(Class.class, "isAssignableFrom", boolean.class, Class.class); - + Label lblNotAssignable = new Label(); output.ifEQ(lblNotAssignable); - + output.iConst1(); output.returnInt(); - + output.label(lblNotAssignable); - + for (ZenNativeCaster caster : casters) { caster.compileAnyCanCastImplicit(ZenTypeNative.this, output, environment, 0); } - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(ZenTypeNative.this, output, environment, 0); } - + output.iConst0(); output.returnInt(); } @@ -701,24 +695,24 @@ public class ZenTypeNative extends ZenType { output.constant(Type.getType(cls)); output.loadObject(1); output.invokeVirtual(Class.class, "isAssignableFrom", boolean.class, Class.class); - + Label lblNotAssignable = new Label(); output.ifEQ(lblNotAssignable); - + output.loadObject(0); output.returnObject(); - + output.label(lblNotAssignable); - + for (ZenNativeCaster caster : casters) { caster.compileAnyCast(ZenTypeNative.this, output, environment, 0, 1); } - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(ZenTypeNative.this, output, environment, 0, 1); } - + throwCastException(output, "float", 1); } @@ -726,18 +720,18 @@ public class ZenTypeNative extends ZenType { public void defineNot(MethodOutput output) { // TODO: implement throwUnsupportedException(output, getName(), "not"); - /*for (ZenNativeOperator unaryOperator : unaryOperators) { - if (unaryOperator.getOperator() == OperatorType.NOT) { - - } - } - - TypeExpansion expansion = environment.getExpansion(getName()); - if (expansion != null) { - if (expansion.compileAnyUnary(output, OperatorType.NOT)) { - - } - }*/ + /* + * for (ZenNativeOperator unaryOperator : unaryOperators) { if + * (unaryOperator.getOperator() == OperatorType.NOT) { + * + * } } + * + * TypeExpansion expansion = environment.getExpansion(getName()); if + * (expansion != null) { if (expansion.compileAnyUnary(output, + * OperatorType.NOT)) { + * + * } } + */ } @Override diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeNull.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeNull.java index 0dbacc6..9128011 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeNull.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeNull.java @@ -27,11 +27,11 @@ import stanhebben.zenscript.util.ZenPosition; public class ZenTypeNull extends ZenType { public static final ZenTypeNull INSTANCE = new ZenTypeNull(); private static final Type TYPE = Type.getType(Object.class); - + private ZenTypeNull() { - + } - + @Override public ICastingRule getCastingRule(ZenType type, IEnvironmentGlobal environment) { if (type.isPointer()) { @@ -43,27 +43,27 @@ public class ZenTypeNull extends ZenType { @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { - + } - + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { environment.error(position, "null has not operators"); return new ExpressionInvalid(position); } - + @Override public Expression binary(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, OperatorType operator) { environment.error(position, "null has not operators"); return new ExpressionInvalid(position); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "null has not operators"); return new ExpressionInvalid(position); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { environment.error(position, "null has not operators"); @@ -94,20 +94,20 @@ public class ZenTypeNull extends ZenType { return null; } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return type.isPointer(); - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return type.isPointer(); } + */ @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { return type.isPointer(); } - - /*@Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - return value; - }*/ + + /* + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { return value; } + */ @Override public Class toJavaClass() { @@ -134,16 +134,16 @@ public class ZenTypeNull extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - // nothing to do - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { // nothing to do } + */ @Override public String getName() { return "null"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { throw new UnsupportedOperationException("The null type does not have an any type"); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeShort.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeShort.java index 471bf34..f3c5a47 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeShort.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeShort.java @@ -42,18 +42,20 @@ import stanhebben.zenscript.value.IAny; public class ZenTypeShort extends ZenType { public static final ZenTypeShort INSTANCE = new ZenTypeShort(); - - //private static final JavaMethod SHORT_TOSTRING = JavaMethod.get(EMPTY_REGISTRY, Short.class, "toString", short.class); + + // private static final JavaMethod SHORT_TOSTRING = + // JavaMethod.get(EMPTY_REGISTRY, Short.class, "toString", short.class); private static final String ANY_NAME = "any/AnyShort"; private static final String ANY_NAME_2 = "any.AnyShort"; - - private ZenTypeShort() {} + + private ZenTypeShort() { + } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod environment) { return null; } - + @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { rules.registerCastingRule(BYTE, new CastingRuleI2B(null)); @@ -68,35 +70,28 @@ public class ZenTypeShort extends ZenType { rules.registerCastingRule(DOUBLE, new CastingRuleI2D(null)); rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleStaticMethod(DOUBLE_VALUEOF, new CastingRuleI2D(null))); rules.registerCastingRule(ANY, new CastingRuleStaticMethod(JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, BYTE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return (type.getNumberType() != 0 && type.getNumberType() >= NUM_SHORT) - || type == ZenTypeString.INSTANCE - || type == ANY - || canCastExpansion(environment, type); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return canCastImplicit(type, environment); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return (type.getNumberType() != 0 && type.getNumberType() + * >= NUM_SHORT) || type == ZenTypeString.INSTANCE || type == ANY || + * canCastExpansion(environment, type); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return canCastImplicit(type, environment); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Type toASMType() { @@ -141,47 +136,36 @@ public class ZenTypeShort extends ZenType { return false; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - MethodOutput output = environment.getOutput(); - - if (type == BYTE) { - output.i2b(); - } else if (type == ZenTypeByteObject.INSTANCE) { - output.i2b(); - output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); - } else if (type == SHORT) { - // nothing to do - } else if (type == ZenTypeShortObject.INSTANCE) { - output.invokeStatic(Short.class, "valueOf", Short.class, short.class); - } else if (type == INT) { - // nothing to do - } else if (type == ZenTypeIntObject.INSTANCE) { - output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); - } else if (type == LONG) { - output.i2l(); - } else if (type == ZenTypeLongObject.INSTANCE) { - output.i2l(); - output.invokeStatic(Long.class, "valueOf", Long.class, long.class); - } else if (type == FLOAT) { - output.i2f(); - } else if (type == ZenTypeFloatObject.INSTANCE) { - output.i2f(); - output.invokeStatic(Float.class, "valueOf", Float.class, float.class); - } else if (type == DOUBLE) { - output.i2d(); - } else if (type == ZenTypeDoubleObject.INSTANCE) { - output.i2d(); - output.invokeStatic(Double.class, "valueOf", Double.class, double.class); - } else if (type == STRING) { - output.invokeStatic(Short.class, "toString", String.class, short.class); - } else if (type == ANY) { - output.invokeStatic(getAnyClassName(environment), "valueOf", "(S)" + signature(IAny.class)); - } else if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "cannot cast " + this + " to " + type); - } - }*/ - + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { MethodOutput output = + * environment.getOutput(); + * + * if (type == BYTE) { output.i2b(); } else if (type == + * ZenTypeByteObject.INSTANCE) { output.i2b(); + * output.invokeStatic(Byte.class, "valueOf", Byte.class, byte.class); } + * else if (type == SHORT) { // nothing to do } else if (type == + * ZenTypeShortObject.INSTANCE) { output.invokeStatic(Short.class, + * "valueOf", Short.class, short.class); } else if (type == INT) { // + * nothing to do } else if (type == ZenTypeIntObject.INSTANCE) { + * output.invokeStatic(Integer.class, "valueOf", Integer.class, int.class); + * } else if (type == LONG) { output.i2l(); } else if (type == + * ZenTypeLongObject.INSTANCE) { output.i2l(); + * output.invokeStatic(Long.class, "valueOf", Long.class, long.class); } + * else if (type == FLOAT) { output.i2f(); } else if (type == + * ZenTypeFloatObject.INSTANCE) { output.i2f(); + * output.invokeStatic(Float.class, "valueOf", Float.class, float.class); } + * else if (type == DOUBLE) { output.i2d(); } else if (type == + * ZenTypeDoubleObject.INSTANCE) { output.i2d(); + * output.invokeStatic(Double.class, "valueOf", Double.class, double.class); + * } else if (type == STRING) { output.invokeStatic(Short.class, "toString", + * String.class, short.class); } else if (type == ANY) { + * output.invokeStatic(getAnyClassName(environment), "valueOf", "(S)" + + * signature(IAny.class)); } else if (!compileCastExpansion(position, + * environment, type)) { environment.error(position, "cannot cast " + this + + * " to " + type); } } + */ + @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { return new ExpressionArithmeticUnary(position, operator, value); @@ -196,16 +180,16 @@ public class ZenTypeShort extends ZenType { left.cast(position, environment, STRING), right.cast(position, environment, STRING), OperatorType.CAT); } - + return new ExpressionArithmeticBinary(position, operator, left, right.cast(position, environment, this)); } - + @Override public Expression trinary(ZenPosition position, IEnvironmentGlobal environment, Expression first, Expression second, Expression third, OperatorType operator) { environment.error(position, "short doesn't support this operation"); return new ExpressionInvalid(position); } - + @Override public Expression compare(ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { return new ExpressionArithmeticCompare(position, type, left, right.cast(position, environment, this)); @@ -227,14 +211,14 @@ public class ZenTypeShort extends ZenType { public String getName() { return "short"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { if (!environment.containsClass(ANY_NAME_2)) { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionShort(environment), ANY_NAME, Type.SHORT_TYPE)); } - + return ANY_NAME; } @@ -242,10 +226,10 @@ public class ZenTypeShort extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionInt(position, 0, SHORT); } - + private class AnyDefinitionShort implements IAnyDefinition { private final IEnvironmentGlobal environment; - + public AnyDefinitionShort(IEnvironmentGlobal environment) { this.environment = environment; } @@ -253,7 +237,7 @@ public class ZenTypeShort extends ZenType { @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "S", null, null); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(S)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(ANY_NAME); @@ -262,7 +246,7 @@ public class ZenTypeShort extends ZenType { valueOf.construct(ANY_NAME, "S"); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(S)V", null, null); constructor.start(); constructor.loadObject(0); @@ -273,43 +257,43 @@ public class ZenTypeShort extends ZenType { constructor.returnType(Type.VOID_TYPE); constructor.end(); } - + @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblCan = new Label(); - + output.constant(Type.BYTE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.SHORT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.INT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.LONG_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.FLOAT_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + output.constant(Type.DOUBLE_TYPE); output.loadObject(0); output.ifACmpEq(lblCan); - + TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(SHORT, output, environment, 0); } - + output.iConst0(); output.returnInt(); - + output.label(lblCan); output.iConst1(); output.returnInt(); @@ -321,7 +305,7 @@ public class ZenTypeShort extends ZenType { if (expansion != null) { expansion.compileAnyCast(SHORT, output, environment, 0, 1); } - + throwCastException(output, "short", 1); } @@ -571,21 +555,21 @@ public class ZenTypeShort extends ZenType { @Override public void defineAs(MethodOutput output) { int localValue = output.local(Type.SHORT_TYPE); - + getValue(output); output.store(Type.SHORT_TYPE, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(SHORT, output, environment, localValue, 1); } - + throwCastException(output, "short", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); - + output.loadObject(1); output.constant(Type.SHORT_TYPE); output.ifACmpEq(lblEq); @@ -595,7 +579,7 @@ public class ZenTypeShort extends ZenType { output.iConst1(); output.returnInt(); } - + @Override public void defineGetNumberType(MethodOutput output) { output.constant(IAny.NUM_SHORT); @@ -611,7 +595,7 @@ public class ZenTypeShort extends ZenType { public void defineIteratorMulti(MethodOutput output) { throwUnsupportedException(output, "short", "iterator"); } - + private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "S"); @@ -620,19 +604,19 @@ public class ZenTypeShort extends ZenType { @Override public void defineEquals(MethodOutput output) { Label lblNope = new Label(); - + output.loadObject(1); output.instanceOf(IAny.NAME); output.ifEQ(lblNope); - + getValue(output); output.loadObject(1); METHOD_ASSHORT.invokeVirtual(output); output.ifICmpNE(lblNope); - + output.iConst1(); output.returnInt(); - + output.label(lblNope); output.iConst0(); output.returnInt(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeShortObject.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeShortObject.java index f8dc285..554defc 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeShortObject.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeShortObject.java @@ -32,8 +32,9 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; */ public class ZenTypeShortObject extends ZenType { public static final ZenTypeShortObject INSTANCE = new ZenTypeShortObject(); - - private ZenTypeShortObject() {} + + private ZenTypeShortObject() { + } @Override public Expression unary(ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { @@ -101,37 +102,31 @@ public class ZenTypeShortObject extends ZenType { rules.registerCastingRule(DOUBLEOBJECT, new CastingRuleNullableStaticMethod( DOUBLE_VALUEOF, new CastingRuleVirtualMethod(DOUBLE_VALUE))); - + rules.registerCastingRule(STRING, new CastingRuleNullableVirtualMethod(SHORTOBJECT, SHORT_TOSTRING)); rules.registerCastingRule(ANY, new CastingRuleNullableStaticMethod( JavaMethod.getStatic(getAnyClassName(environment), "valueOf", ANY, SHORT), new CastingRuleVirtualMethod(SHORT_VALUE))); - + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return SHORT.canCastImplicit(type, environment); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return SHORT.canCastExplicit(type, environment); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type.getNumberType() > 0 || type == STRING) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return SHORT.canCastImplicit(type, environment); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return SHORT.canCastExplicit(type, environment); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type.getNumberType() > + * 0 || type == STRING) { return new ExpressionAs(position, value, type); } + * else if (canCastExpansion(environment, type)) { return + * castExpansion(position, environment, value, type); } else { return new + * ExpressionAs(position, value, type); } } + */ @Override public Class toJavaClass() { @@ -158,41 +153,35 @@ public class ZenTypeShortObject extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else if (type == SHORT) { - environment.getOutput().invokeVirtual(Short.class, "shortValue", short.class); - } else if (type == STRING) { - environment.getOutput().invokeVirtual(Short.class, "toString", String.class); - } else if (type == ANY) { - MethodOutput output = environment.getOutput(); - - Label lblNotNull = new Label(); - Label lblAfter = new Label(); - - output.dup(); - output.ifNonNull(lblNotNull); - output.aConstNull(); - output.goTo(lblAfter); - - output.label(lblNotNull); - output.invokeVirtual(Short.class, "shortValue", short.class); - output.invokeStatic(SHORT.getAnyClassName(environment), "valueOf", "(S)" + signature(IAny.class)); - - output.label(lblAfter); - } else { - environment.getOutput().invokeVirtual(Short.class, "shortValue", short.class); - SHORT.compileCast(position, environment, type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else if (type == SHORT) { + * environment.getOutput().invokeVirtual(Short.class, "shortValue", + * short.class); } else if (type == STRING) { + * environment.getOutput().invokeVirtual(Short.class, "toString", + * String.class); } else if (type == ANY) { MethodOutput output = + * environment.getOutput(); + * + * Label lblNotNull = new Label(); Label lblAfter = new Label(); + * + * output.dup(); output.ifNonNull(lblNotNull); output.aConstNull(); + * output.goTo(lblAfter); + * + * output.label(lblNotNull); output.invokeVirtual(Short.class, "shortValue", + * short.class); output.invokeStatic(SHORT.getAnyClassName(environment), + * "valueOf", "(S)" + signature(IAny.class)); + * + * output.label(lblAfter); } else { + * environment.getOutput().invokeVirtual(Short.class, "shortValue", + * short.class); SHORT.compileCast(position, environment, type); } } + */ @Override public String getName() { return "short"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { return SHORT.getAnyClassName(environment); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeString.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeString.java index f2ed3fa..c486690 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeString.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeString.java @@ -39,13 +39,14 @@ import stanhebben.zenscript.value.IAny; public class ZenTypeString extends ZenType { public static final ZenTypeString INSTANCE = new ZenTypeString(); - + private static final String ANY_NAME = "any/AnyString"; private static final String ANY_NAME_2 = "any.AnyString"; - + private final Type type = Type.getType(String.class); - - private ZenTypeString() {} + + private ZenTypeString() { + } @Override public IZenIterator makeIterator(int numValues, IEnvironmentMethod methodOutput) { @@ -73,35 +74,30 @@ public class ZenTypeString extends ZenType { "valueOf", ANY, STRING - ))); - + ))); + if (followCasters) { constructExpansionCastingRules(environment, rules); } } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return type == this || type == ANY || canCastExpansion(environment, type); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return type == this || type == ANY || type == BOOL || type.getNumberType() > 0 || canCastExpansion(environment, type); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - if (type == this) { - return value; - } else if (type == BOOL || type.getNumberType() > 0 || type == ANY) { - return new ExpressionAs(position, value, type); - } else if (canCastExpansion(environment, type)) { - return castExpansion(position, environment, value, type); - } else { - return new ExpressionAs(position, value, type); - } - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return type == this || type == ANY || + * canCastExpansion(environment, type); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return type == this || type == ANY || type == BOOL || + * type.getNumberType() > 0 || canCastExpansion(environment, type); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { if (type == this) { return + * value; } else if (type == BOOL || type.getNumberType() > 0 || type == + * ANY) { return new ExpressionAs(position, value, type); } else if + * (canCastExpansion(environment, type)) { return castExpansion(position, + * environment, value, type); } else { return new ExpressionAs(position, + * value, type); } } + */ @Override public Type toASMType() { @@ -146,46 +142,41 @@ public class ZenTypeString extends ZenType { return true; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - MethodOutput output = environment.getOutput(); - - if (type == STRING) { - // do nothing - } else if (type == BOOL) { - output.invokeStatic(Boolean.class, "parseBoolean", boolean.class, String.class); - } else if (type == ZenTypeBoolObject.INSTANCE) { - output.invokeStatic(Boolean.class, "valueOf", Boolean.class, String.class); - } else if (type == BYTE) { - output.invokeStatic(Byte.class, "parseByte", byte.class, String.class); - } else if (type == ZenTypeByteObject.INSTANCE) { - output.invokeStatic(Byte.class, "valueOf", Byte.class, String.class); - } else if (type == SHORT) { - output.invokeStatic(Short.class, "parseShort", short.class, String.class); - } else if (type == ZenTypeShortObject.INSTANCE) { - output.invokeStatic(Short.class, "valueof", Short.class, String.class); - } else if (type == INT) { - output.invokeStatic(Integer.class, "parseInt", int.class, String.class); - } else if (type == ZenTypeIntObject.INSTANCE) { - output.invokeStatic(Integer.class, "valueof", Integer.class, String.class); - } else if (type == LONG) { - output.invokeStatic(Long.class, "parseLong", long.class, String.class); - } else if (type == ZenTypeLongObject.INSTANCE) { - output.invokeStatic(Long.class, "valueof", Long.class, String.class); - } else if (type == FLOAT) { - output.invokeStatic(Float.class, "parseFloat", float.class, String.class); - } else if (type == ZenTypeFloatObject.INSTANCE) { - output.invokeStatic(Float.class, "valueOf", Float.class, String.class); - } else if (type == DOUBLE) { - output.invokeStatic(Double.class, "parseDouble", double.class, String.class); - } else if (type == ZenTypeDoubleObject.INSTANCE) { - output.invokeStatic(Double.class, "valueOf", Double.class, String.class); - } else if (type == ANY) { - output.invokeStatic(getAnyClassName(environment), "valueOf", "(Ljava/lang/String;)" + signature(IAny.class)); - } else if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "cannot cast " + this + " to " + type); - } - }*/ + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { MethodOutput output = + * environment.getOutput(); + * + * if (type == STRING) { // do nothing } else if (type == BOOL) { + * output.invokeStatic(Boolean.class, "parseBoolean", boolean.class, + * String.class); } else if (type == ZenTypeBoolObject.INSTANCE) { + * output.invokeStatic(Boolean.class, "valueOf", Boolean.class, + * String.class); } else if (type == BYTE) { output.invokeStatic(Byte.class, + * "parseByte", byte.class, String.class); } else if (type == + * ZenTypeByteObject.INSTANCE) { output.invokeStatic(Byte.class, "valueOf", + * Byte.class, String.class); } else if (type == SHORT) { + * output.invokeStatic(Short.class, "parseShort", short.class, + * String.class); } else if (type == ZenTypeShortObject.INSTANCE) { + * output.invokeStatic(Short.class, "valueof", Short.class, String.class); } + * else if (type == INT) { output.invokeStatic(Integer.class, "parseInt", + * int.class, String.class); } else if (type == ZenTypeIntObject.INSTANCE) { + * output.invokeStatic(Integer.class, "valueof", Integer.class, + * String.class); } else if (type == LONG) { output.invokeStatic(Long.class, + * "parseLong", long.class, String.class); } else if (type == + * ZenTypeLongObject.INSTANCE) { output.invokeStatic(Long.class, "valueof", + * Long.class, String.class); } else if (type == FLOAT) { + * output.invokeStatic(Float.class, "parseFloat", float.class, + * String.class); } else if (type == ZenTypeFloatObject.INSTANCE) { + * output.invokeStatic(Float.class, "valueOf", Float.class, String.class); } + * else if (type == DOUBLE) { output.invokeStatic(Double.class, + * "parseDouble", double.class, String.class); } else if (type == + * ZenTypeDoubleObject.INSTANCE) { output.invokeStatic(Double.class, + * "valueOf", Double.class, String.class); } else if (type == ANY) { + * output.invokeStatic(getAnyClassName(environment), "valueOf", + * "(Ljava/lang/String;)" + signature(IAny.class)); } else if + * (!compileCastExpansion(position, environment, type)) { + * environment.error(position, "cannot cast " + this + " to " + type); } } + */ @Override public Expression unary( @@ -255,7 +246,7 @@ public class ZenTypeString extends ZenType { if (right.getType().canCastImplicit(STRING, environment)) { return new ExpressionCompareGeneric(position, new ExpressionCallVirtual(position, environment, METHOD_ASINT, left, right), type); } - + Expression result = binaryExpansion(position, environment, left, right, OperatorType.COMPARE); if (result == null) { environment.error(position, "cannot compare strings"); @@ -281,12 +272,12 @@ public class ZenTypeString extends ZenType { public String getName() { return "string"; } - + /** * Returns the Java class name. * * @param environment - * @return + * @return */ @Override public String getAnyClassName(IEnvironmentGlobal environment) { @@ -294,7 +285,7 @@ public class ZenTypeString extends ZenType { environment.putClass(ANY_NAME_2, new byte[0]); environment.putClass(ANY_NAME_2, AnyClassWriter.construct(new AnyDefinitionString(environment), ANY_NAME, type)); } - + return ANY_NAME; } @@ -302,10 +293,10 @@ public class ZenTypeString extends ZenType { public Expression defaultValue(ZenPosition position) { return new ExpressionNull(position); } - + private class AnyDefinitionString implements IAnyDefinition { private final IEnvironmentGlobal environment; - + private AnyDefinitionString(IEnvironmentGlobal environment) { this.environment = environment; } @@ -313,7 +304,7 @@ public class ZenTypeString extends ZenType { @Override public void defineMembers(ClassVisitor output) { output.visitField(Opcodes.ACC_PRIVATE, "value", "Ljava/lang/String;", null, null); - + MethodOutput valueOf = new MethodOutput(output, Opcodes.ACC_PUBLIC | Opcodes.ACC_STATIC, "valueOf", "(Ljava/lang/String;)" + signature(IAny.class), null, null); valueOf.start(); valueOf.newObject(ANY_NAME); @@ -322,7 +313,7 @@ public class ZenTypeString extends ZenType { valueOf.construct(ANY_NAME, "Ljava/lang/String;"); valueOf.returnObject(); valueOf.end(); - + MethodOutput constructor = new MethodOutput(output, Opcodes.ACC_PUBLIC, "", "(Ljava/lang/String;)V", null, null); constructor.start(); constructor.loadObject(0); @@ -337,19 +328,19 @@ public class ZenTypeString extends ZenType { @Override public void defineStaticCanCastImplicit(MethodOutput output) { Label lblOthers = new Label(); - + output.constant(type); output.loadObject(0); output.ifACmpNe(lblOthers); output.iConst1(); output.returnInt(); - + output.label(lblOthers); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCanCastImplicit(STRING, output, environment, 0); } - + output.iConst0(); output.returnInt(); } @@ -360,7 +351,7 @@ public class ZenTypeString extends ZenType { if (expansion != null) { expansion.compileAnyCast(STRING, output, environment, 0, 1); } - + throwCastException(output, "string", 1); } @@ -474,7 +465,8 @@ public class ZenTypeString extends ZenType { @Override public void defineIndexGet(MethodOutput output) { - // return new AnyString(String.substring(other.asInt(), other.asInt() + 1)) + // return new AnyString(String.substring(other.asInt(), + // other.asInt() + 1)) getValue(output); output.loadObject(1); METHOD_ASINT.invokeVirtual(output); @@ -561,21 +553,21 @@ public class ZenTypeString extends ZenType { @Override public void defineAs(MethodOutput output) { int localValue = output.local(type); - + getValue(output); output.store(type, localValue); TypeExpansion expansion = environment.getExpansion(getName()); if (expansion != null) { expansion.compileAnyCast(STRING, output, environment, localValue, 1); } - + throwCastException(output, "string", 1); } @Override public void defineIs(MethodOutput output) { Label lblEq = new Label(); - + output.loadObject(1); output.constant(type); output.ifACmpEq(lblEq); @@ -601,7 +593,7 @@ public class ZenTypeString extends ZenType { public void defineIteratorMulti(MethodOutput output) { throwUnsupportedException(output, "string", "iterator"); } - + private void getValue(MethodOutput output) { output.loadObject(0); output.getField(ANY_NAME, "value", "Ljava/lang/String;"); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeVoid.java b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeVoid.java index 042dbec..b4ab707 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeVoid.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/ZenTypeVoid.java @@ -23,9 +23,10 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ZenTypeVoid extends ZenType { public static final ZenTypeVoid INSTANCE = new ZenTypeVoid(); - - private ZenTypeVoid() {} - + + private ZenTypeVoid() { + } + @Override public IPartialExpression getMember( ZenPosition position, @@ -52,24 +53,23 @@ public class ZenTypeVoid extends ZenType { @Override public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules, boolean followCasters) { - + } - /*@Override - public boolean canCastImplicit(ZenType type, IEnvironmentGlobal environment) { - return type == this || canCastExpansion(environment, type); - } - - @Override - public boolean canCastExplicit(ZenType type, IEnvironmentGlobal environment) { - return type == this || canCastExpansion(environment, type); - } - - @Override - public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression value, ZenType type) { - environment.error(position, "cannot cast void to other type"); - return new ExpressionInvalid(position, type); - }*/ + /* + * @Override public boolean canCastImplicit(ZenType type, IEnvironmentGlobal + * environment) { return type == this || canCastExpansion(environment, + * type); } + * + * @Override public boolean canCastExplicit(ZenType type, IEnvironmentGlobal + * environment) { return type == this || canCastExpansion(environment, + * type); } + * + * @Override public Expression cast(ZenPosition position, IEnvironmentGlobal + * environment, Expression value, ZenType type) { + * environment.error(position, "cannot cast void to other type"); return new + * ExpressionInvalid(position, type); } + */ @Override public Type toASMType() { @@ -91,17 +91,14 @@ public class ZenTypeVoid extends ZenType { return false; } - /*@Override - public void compileCast(ZenPosition position, IEnvironmentMethod environment, ZenType type) { - if (type == this) { - // nothing to do - } else { - if (!compileCastExpansion(position, environment, type)) { - environment.error(position, "cannot cast " + this + " to " + type); - } - } - }*/ - + /* + * @Override public void compileCast(ZenPosition position, + * IEnvironmentMethod environment, ZenType type) { if (type == this) { // + * nothing to do } else { if (!compileCastExpansion(position, environment, + * type)) { environment.error(position, "cannot cast " + this + " to " + + * type); } } } + */ + @Override public Expression unary( ZenPosition position, IEnvironmentGlobal environment, Expression value, OperatorType operator) { @@ -122,7 +119,7 @@ public class ZenTypeVoid extends ZenType { environment.error(position, "void does not have operators"); return new ExpressionInvalid(position, this); } - + @Override public Expression compare( ZenPosition position, IEnvironmentGlobal environment, Expression left, Expression right, CompareType type) { @@ -146,7 +143,7 @@ public class ZenTypeVoid extends ZenType { public String getName() { return "void"; } - + @Override public String getAnyClassName(IEnvironmentGlobal environment) { throw new UnsupportedOperationException("Cannot convert void to anything, not even any"); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/BaseCastingRule.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/BaseCastingRule.java index 7d831bc..3de7369 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/BaseCastingRule.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/BaseCastingRule.java @@ -15,7 +15,7 @@ import stanhebben.zenscript.type.ZenType; */ public abstract class BaseCastingRule implements ICastingRule { private final ICastingRule baseRule; - + public BaseCastingRule(ICastingRule baseRule) { this.baseRule = baseRule; } @@ -24,16 +24,16 @@ public abstract class BaseCastingRule implements ICastingRule { public final void compile(IEnvironmentMethod method) { if (baseRule != null) baseRule.compile(method); - + compileInner(method); } - + @Override public final ZenType getInputType() { return baseRule == null ? getInnerInputType() : baseRule.getInputType(); } - + public abstract ZenType getInnerInputType(); - + public abstract void compileInner(IEnvironmentMethod method); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyBool.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyBool.java index 28671e2..c1b30d3 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyBool.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyBool.java @@ -16,14 +16,15 @@ import stanhebben.zenscript.value.IAny; */ public class CastingAnyBool implements ICastingRule { public static final CastingAnyBool INSTANCE = new CastingAnyBool(); - - private CastingAnyBool() {} - + + private CastingAnyBool() { + } + @Override public void compile(IEnvironmentMethod method) { method.getOutput().invokeInterface(IAny.class, "asBool", boolean.class); } - + @Override public ZenType getInputType() { return ZenType.ANY; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyByte.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyByte.java index b3a6393..3ae1b59 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyByte.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyByte.java @@ -16,19 +16,20 @@ import stanhebben.zenscript.value.IAny; */ public class CastingAnyByte implements ICastingRule { public static final CastingAnyByte INSTANCE = new CastingAnyByte(); - - private CastingAnyByte() {} - + + private CastingAnyByte() { + } + @Override public void compile(IEnvironmentMethod method) { method.getOutput().invokeInterface(IAny.class, "asByte", byte.class); } - + @Override public ZenType getInputType() { return ZenType.ANY; } - + @Override public ZenType getResultingType() { return ZenType.BYTE; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyDouble.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyDouble.java index 0b76975..931ee99 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyDouble.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyDouble.java @@ -16,9 +16,10 @@ import stanhebben.zenscript.value.IAny; */ public class CastingAnyDouble implements ICastingRule { public static final CastingAnyDouble INSTANCE = new CastingAnyDouble(); - - private CastingAnyDouble() {} - + + private CastingAnyDouble() { + } + @Override public void compile(IEnvironmentMethod method) { method.getOutput().invokeInterface(IAny.class, "asDouble", double.class); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyFloat.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyFloat.java index 3ad4d51..31cf779 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyFloat.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyFloat.java @@ -16,9 +16,10 @@ import stanhebben.zenscript.value.IAny; */ public class CastingAnyFloat implements ICastingRule { public static final CastingAnyFloat INSTANCE = new CastingAnyFloat(); - - private CastingAnyFloat() {} - + + private CastingAnyFloat() { + } + @Override public void compile(IEnvironmentMethod method) { method.getOutput().invokeInterface(IAny.class, "asFloat", float.class); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyInt.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyInt.java index ec20e74..ac98008 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyInt.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyInt.java @@ -16,9 +16,10 @@ import stanhebben.zenscript.value.IAny; */ public class CastingAnyInt implements ICastingRule { public static final CastingAnyInt INSTANCE = new CastingAnyInt(); - - private CastingAnyInt() {} - + + private CastingAnyInt() { + } + @Override public void compile(IEnvironmentMethod method) { method.getOutput().invokeInterface(IAny.class, "asInt", int.class); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyLong.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyLong.java index c386f6c..690c4ff 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyLong.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyLong.java @@ -16,9 +16,10 @@ import stanhebben.zenscript.value.IAny; */ public class CastingAnyLong implements ICastingRule { public static final CastingAnyLong INSTANCE = new CastingAnyLong(); - - private CastingAnyLong() {} - + + private CastingAnyLong() { + } + @Override public void compile(IEnvironmentMethod method) { method.getOutput().invokeInterface(IAny.class, "asLong", long.class); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyShort.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyShort.java index c1d2c1f..832d4f6 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyShort.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyShort.java @@ -16,9 +16,10 @@ import stanhebben.zenscript.value.IAny; */ public class CastingAnyShort implements ICastingRule { public static final CastingAnyShort INSTANCE = new CastingAnyShort(); - - private CastingAnyShort() {} - + + private CastingAnyShort() { + } + @Override public void compile(IEnvironmentMethod method) { method.getOutput().invokeInterface(IAny.class, "asShort", short.class); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyString.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyString.java index 8c22305..1c93c20 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyString.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingAnyString.java @@ -18,24 +18,25 @@ import stanhebben.zenscript.value.IAny; */ public class CastingAnyString implements ICastingRule { public static final CastingAnyString INSTANCE = new CastingAnyString(); - - private CastingAnyString() {} - + + private CastingAnyString() { + } + @Override public void compile(IEnvironmentMethod method) { MethodOutput output = method.getOutput(); Label lblNonNull = new Label(); Label lblAfter = new Label(); - + output.dup(); output.ifNonNull(lblNonNull); output.pop(); output.aConstNull(); output.goTo(lblAfter); - + output.label(lblNonNull); output.invokeInterface(IAny.class, "asString", String.class); - + output.label(lblAfter); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingNotNull.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingNotNull.java index de9cade..1af3a60 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingNotNull.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingNotNull.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.util.MethodOutput; */ public class CastingNotNull implements ICastingRule { public ZenType fromType; - + public CastingNotNull(ZenType fromType) { this.fromType = fromType; } @@ -27,7 +27,7 @@ public class CastingNotNull implements ICastingRule { MethodOutput output = method.getOutput(); Label labelElse = new Label(); Label labelAfter = new Label(); - + output.ifNull(labelElse); output.iConst1(); output.goTo(labelAfter); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleAny.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleAny.java index a1c3fc1..709b73e 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleAny.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleAny.java @@ -16,11 +16,11 @@ import stanhebben.zenscript.value.IAny; */ public class CastingRuleAny implements ICastingRule { private final ZenType toType; - + public CastingRuleAny(ZenType toType) { this.toType = toType; } - + @Override public void compile(IEnvironmentMethod method) { method.getOutput().constant(toType); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleAnyAs.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleAnyAs.java index f2c08ec..6fb4322 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleAnyAs.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleAnyAs.java @@ -17,11 +17,11 @@ import stanhebben.zenscript.value.IAny; */ public class CastingRuleAnyAs implements ICastingRule { private final ZenType type; - + public CastingRuleAnyAs(ZenType type) { this.type = type; } - + @Override public void compile(IEnvironmentMethod method) { method.getOutput().constant(Type.getType(type.toJavaClass())); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleArrayArray.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleArrayArray.java index 6e5671c..01dfa33 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleArrayArray.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleArrayArray.java @@ -21,17 +21,17 @@ public class CastingRuleArrayArray implements ICastingRule { private final ICastingRule base; private final ZenTypeArrayBasic from; private final ZenTypeArrayBasic to; - + public CastingRuleArrayArray(ICastingRule base, ZenTypeArrayBasic from, ZenTypeArrayBasic to) { this.base = base; this.from = from; this.to = to; } - + @Override public void compile(IEnvironmentMethod method) { MethodOutput output = method.getOutput(); - + Type fromType = from.getBaseType().toASMType(); Type toType = to.getBaseType().toASMType(); @@ -55,13 +55,13 @@ public class CastingRuleArrayArray implements ICastingRule { // stack: original index value if (base != null) base.compile(method); - + output.loadObject(result); output.dupX2(); output.dupX2(); output.arrayStore(toType); output.pop(); - + // stack: original index output.iConst1(); output.iAdd(); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleArrayList.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleArrayList.java index 6c94d95..0053ca6 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleArrayList.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleArrayList.java @@ -20,46 +20,45 @@ public class CastingRuleArrayList implements ICastingRule { private final ICastingRule base; private final ZenTypeArrayBasic from; private final ZenTypeArrayList to; - + public CastingRuleArrayList(ICastingRule base, ZenTypeArrayBasic from, ZenTypeArrayList to) { this.base = base; this.from = from; this.to = to; } - + @Override public void compile(IEnvironmentMethod method) { MethodOutput output = method.getOutput(); - + // TODO: implement this throw new UnsupportedOperationException("Not yet implemented"); - -/* Type fromType = componentFrom.toASMType(); - Type toType = componentTo.toASMType(); - int result = output.local(List.class); - int iterator = output.local(Iterator.class); - - // construct new list - output.dup(); - - - output.invoke(List.class, "iterator", void.class); - output.storeObject(iterator); - - Label loop = new Label(); - output.label(loop); - output.loadObject(iterator); - - - if (base != null) - base.compile(method); - - - - output.pop(); - - output.loadObject(result);*/ + /* + * Type fromType = componentFrom.toASMType(); Type toType = + * componentTo.toASMType(); + * + * int result = output.local(List.class); int iterator = + * output.local(Iterator.class); + * + * // construct new list output.dup(); + * + * + * output.invoke(List.class, "iterator", void.class); + * output.storeObject(iterator); + * + * Label loop = new Label(); output.label(loop); + * output.loadObject(iterator); + * + * + * if (base != null) base.compile(method); + * + * + * + * output.pop(); + * + * output.loadObject(result); + */ } @Override diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateArray.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateArray.java index 00e926e..5f1fe70 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateArray.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateArray.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.type.ZenTypeArrayList; public class CastingRuleDelegateArray implements ICastingRuleDelegate { private final ICastingRuleDelegate base; private final ZenTypeArrayBasic from; - + public CastingRuleDelegateArray(ICastingRuleDelegate base, ZenTypeArrayBasic from) { this.base = base; this.from = from; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateList.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateList.java index cc98413..13d3056 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateList.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateList.java @@ -17,7 +17,7 @@ import stanhebben.zenscript.type.ZenTypeArrayList; public class CastingRuleDelegateList implements ICastingRuleDelegate { private final ICastingRuleDelegate base; private final ZenTypeArrayList from; - + public CastingRuleDelegateList(ICastingRuleDelegate base, ZenTypeArrayList from) { this.base = base; this.from = from; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateMap.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateMap.java index 3f845d0..7298a02 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateMap.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateMap.java @@ -16,7 +16,7 @@ import stanhebben.zenscript.type.ZenType; public class CastingRuleDelegateMap implements ICastingRuleDelegate { private final ZenType forType; private final Map target; - + public CastingRuleDelegateMap(ZenType forType, Map target) { this.forType = forType; this.target = target; @@ -25,8 +25,9 @@ public class CastingRuleDelegateMap implements ICastingRuleDelegate { @Override public void registerCastingRule(ZenType type, ICastingRule rule) { // XXX: remove before release - //System.out.println("Registering casting rule to convert " + forType + " to " + type + ": " + rule); - + // System.out.println("Registering casting rule to convert " + forType + + // " to " + type + ": " + rule); + target.put(type, rule); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateStaticMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateStaticMethod.java index c239675..207bd59 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateStaticMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleDelegateStaticMethod.java @@ -16,7 +16,7 @@ import stanhebben.zenscript.type.natives.IJavaMethod; public class CastingRuleDelegateStaticMethod implements ICastingRuleDelegate { private final ICastingRuleDelegate target; private final IJavaMethod method; - + public CastingRuleDelegateStaticMethod(ICastingRuleDelegate target, IJavaMethod method) { this.target = target; this.method = method; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleListArray.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleListArray.java index 34084eb..6d8dc41 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleListArray.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleListArray.java @@ -20,46 +20,45 @@ public class CastingRuleListArray implements ICastingRule { private final ICastingRule base; private final ZenTypeArrayList from; private final ZenTypeArrayBasic to; - + public CastingRuleListArray(ICastingRule base, ZenTypeArrayList from, ZenTypeArrayBasic to) { this.base = base; this.from = from; this.to = to; } - + @Override public void compile(IEnvironmentMethod method) { MethodOutput output = method.getOutput(); - + // TODO: implement this throw new UnsupportedOperationException("Not yet implemented"); - -/* Type fromType = componentFrom.toASMType(); - Type toType = componentTo.toASMType(); - int result = output.local(List.class); - int iterator = output.local(Iterator.class); - - // construct new list - output.dup(); - - - output.invoke(List.class, "iterator", void.class); - output.storeObject(iterator); - - Label loop = new Label(); - output.label(loop); - output.loadObject(iterator); - - - if (base != null) - base.compile(method); - - - - output.pop(); - - output.loadObject(result);*/ + /* + * Type fromType = componentFrom.toASMType(); Type toType = + * componentTo.toASMType(); + * + * int result = output.local(List.class); int iterator = + * output.local(Iterator.class); + * + * // construct new list output.dup(); + * + * + * output.invoke(List.class, "iterator", void.class); + * output.storeObject(iterator); + * + * Label loop = new Label(); output.label(loop); + * output.loadObject(iterator); + * + * + * if (base != null) base.compile(method); + * + * + * + * output.pop(); + * + * output.loadObject(result); + */ } @Override diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleListList.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleListList.java index 57074c8..f0ecaf5 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleListList.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleListList.java @@ -19,46 +19,45 @@ public class CastingRuleListList implements ICastingRule { private final ICastingRule base; private final ZenTypeArrayList from; private final ZenTypeArrayList to; - + public CastingRuleListList(ICastingRule base, ZenTypeArrayList from, ZenTypeArrayList to) { this.base = base; this.from = from; this.to = to; } - + @Override public void compile(IEnvironmentMethod method) { MethodOutput output = method.getOutput(); - + // TODO: implement this throw new UnsupportedOperationException("Not yet implemented"); - -/* Type fromType = componentFrom.toASMType(); - Type toType = componentTo.toASMType(); - int result = output.local(List.class); - int iterator = output.local(Iterator.class); - - // construct new list - output.dup(); - - - output.invoke(List.class, "iterator", void.class); - output.storeObject(iterator); - - Label loop = new Label(); - output.label(loop); - output.loadObject(iterator); - - - if (base != null) - base.compile(method); - - - - output.pop(); - - output.loadObject(result);*/ + /* + * Type fromType = componentFrom.toASMType(); Type toType = + * componentTo.toASMType(); + * + * int result = output.local(List.class); int iterator = + * output.local(Iterator.class); + * + * // construct new list output.dup(); + * + * + * output.invoke(List.class, "iterator", void.class); + * output.storeObject(iterator); + * + * Label loop = new Label(); output.label(loop); + * output.loadObject(iterator); + * + * + * if (base != null) base.compile(method); + * + * + * + * output.pop(); + * + * output.loadObject(result); + */ } @Override diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleMap.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleMap.java index 70f9f54..ee15e3c 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleMap.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleMap.java @@ -19,25 +19,34 @@ public class CastingRuleMap implements ICastingRule { private final ICastingRule valueRule; private final ZenTypeAssociative fromType; private final ZenTypeAssociative toType; - + public CastingRuleMap(ICastingRule keyRule, ICastingRule valueRule, ZenTypeAssociative fromType, ZenTypeAssociative toType) { this.keyRule = keyRule; this.valueRule = valueRule; this.fromType = fromType; this.toType = toType; } - + @Override public void compile(IEnvironmentMethod method) { // TODO: implement - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. } - + @Override public ZenType getInputType() { return fromType; } - + @Override public ZenType getResultingType() { return toType; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleMatchedFunction.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleMatchedFunction.java index 0133aeb..40ea52e 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleMatchedFunction.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleMatchedFunction.java @@ -19,7 +19,7 @@ public class CastingRuleMatchedFunction implements ICastingRule { private final ZenType toType; private final ICastingRule returnCastingRule; private final ICastingRule[] argumentCastingRules; - + public CastingRuleMatchedFunction(ZenTypeFunction fromType, ZenType toType, ICastingRule returnCastingRule, ICastingRule[] argumentCastingRules) { this.fromType = fromType; this.toType = toType; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNone.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNone.java index 4f2568a..7f61bd3 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNone.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNone.java @@ -16,7 +16,7 @@ import stanhebben.zenscript.type.ZenType; public class CastingRuleNone implements ICastingRule { private final ZenType fromType; private final ZenType toType; - + public CastingRuleNone(ZenType fromType, ZenType toType) { this.fromType = fromType; this.toType = toType; @@ -26,7 +26,7 @@ public class CastingRuleNone implements ICastingRule { public void compile(IEnvironmentMethod method) { // nothing to do } - + @Override public ZenType getInputType() { return fromType; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNullableStaticMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNullableStaticMethod.java index 3b10f27..832423f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNullableStaticMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNullableStaticMethod.java @@ -19,12 +19,12 @@ import stanhebben.zenscript.util.MethodOutput; public class CastingRuleNullableStaticMethod implements ICastingRule { private final IJavaMethod method; private final ICastingRule base; - + public CastingRuleNullableStaticMethod(IJavaMethod method) { this.method = method; base = null; } - + public CastingRuleNullableStaticMethod(IJavaMethod method, ICastingRule base) { this.method = method; this.base = base; @@ -33,7 +33,7 @@ public class CastingRuleNullableStaticMethod implements ICastingRule { @Override public void compile(IEnvironmentMethod method) { MethodOutput output = method.getOutput(); - + Label lblNotNull = new Label(); Label lblAfter = new Label(); @@ -44,7 +44,7 @@ public class CastingRuleNullableStaticMethod implements ICastingRule { output.goTo(lblAfter); output.label(lblNotNull); - + if (base != null) { base.compile(method); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNullableVirtualMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNullableVirtualMethod.java index 9d3598c..0b7d1de 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNullableVirtualMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleNullableVirtualMethod.java @@ -19,7 +19,7 @@ import stanhebben.zenscript.util.MethodOutput; public class CastingRuleNullableVirtualMethod implements ICastingRule { private final ZenType type; private final IJavaMethod method; - + public CastingRuleNullableVirtualMethod(ZenType type, IJavaMethod method) { this.type = type; this.method = method; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleStaticMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleStaticMethod.java index 91b36ef..8744c09 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleStaticMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleStaticMethod.java @@ -17,12 +17,12 @@ import stanhebben.zenscript.type.natives.IJavaMethod; public class CastingRuleStaticMethod implements ICastingRule { private final IJavaMethod method; private final ICastingRule base; - + public CastingRuleStaticMethod(IJavaMethod method) { this.method = method; this.base = null; } - + public CastingRuleStaticMethod(IJavaMethod method, ICastingRule base) { this.method = method; this.base = base; @@ -32,7 +32,7 @@ public class CastingRuleStaticMethod implements ICastingRule { public void compile(IEnvironmentMethod method) { if (base != null) base.compile(method); - + this.method.invokeStatic(method.getOutput()); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleVirtualMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleVirtualMethod.java index 13a16f1..6b6738d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleVirtualMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/CastingRuleVirtualMethod.java @@ -16,7 +16,7 @@ import stanhebben.zenscript.type.natives.IJavaMethod; */ public class CastingRuleVirtualMethod implements ICastingRule { private final IJavaMethod method; - + public CastingRuleVirtualMethod(IJavaMethod method) { this.method = method; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/ICastingRule.java b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/ICastingRule.java index 6fd781f..19b0a7d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/casting/ICastingRule.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/casting/ICastingRule.java @@ -15,8 +15,8 @@ import stanhebben.zenscript.type.ZenType; */ public interface ICastingRule { public void compile(IEnvironmentMethod method); - + public ZenType getInputType(); - + public ZenType getResultingType(); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/expand/ZenExpandCaster.java b/ZenScript/src/main/java/stanhebben/zenscript/type/expand/ZenExpandCaster.java index 573acd5..24a8847 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/expand/ZenExpandCaster.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/expand/ZenExpandCaster.java @@ -23,26 +23,26 @@ import stanhebben.zenscript.util.ZenPosition; */ public class ZenExpandCaster { private final IJavaMethod method; - + public ZenExpandCaster(IJavaMethod method) { this.method = method; } - + public ZenType getTarget() { return method.getReturnType(); } - + public void constructCastingRules(IEnvironmentGlobal environment, ICastingRuleDelegate rules) { ZenType type = method.getReturnType(); rules.registerCastingRule(type, new CastingRuleStaticMethod(method)); - + type.constructCastingRules(environment, new CastingRuleDelegateStaticMethod(rules, method), false); } - + public Expression cast(ZenPosition position, IEnvironmentGlobal environment, Expression expression) { return new ExpressionCallStatic(position, environment, method, expression); } - + public void compile(MethodOutput output) { method.invokeStatic(output); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/expand/ZenExpandMember.java b/ZenScript/src/main/java/stanhebben/zenscript/type/expand/ZenExpandMember.java index 81da083..1fdad05 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/expand/ZenExpandMember.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/expand/ZenExpandMember.java @@ -32,20 +32,20 @@ public class ZenExpandMember { private IJavaMethod getter; private IJavaMethod setter; private final List methods = new ArrayList(); - + public ZenExpandMember(String type, String name) { this.type = type; this.name = name; } - + public IPartialExpression instance(ZenPosition position, IEnvironmentGlobal environment, IPartialExpression value) { return new InstanceGetValue(position, value); } - + public IPartialExpression instance(ZenPosition position, IEnvironmentGlobal environment) { return new StaticGetValue(position); } - + public void setGetter(IJavaMethod getter) { if (this.getter != null) { throw new RuntimeException(type + "." + name + " already has a getter"); @@ -53,7 +53,7 @@ public class ZenExpandMember { this.getter = getter; } } - + public void setSetter(IJavaMethod setter) { if (this.setter != null) { throw new RuntimeException(type + "." + name + " already has a setter"); @@ -61,20 +61,20 @@ public class ZenExpandMember { this.setter = setter; } } - + public void addMethod(IJavaMethod method) { methods.add(method); } - + private class InstanceGetValue implements IPartialExpression { private final ZenPosition position; private final IPartialExpression value; - + public InstanceGetValue(ZenPosition position, IPartialExpression value) { this.position = position; this.value = value; } - + @Override public Expression eval(IEnvironmentGlobal environment) { return new ExpressionCallVirtual(position, environment, getter, value.eval(environment)); @@ -108,7 +108,7 @@ public class ZenExpandMember { public IZenSymbol toSymbol() { return null; } - + @Override public ZenType getType() { return getter.getReturnType(); @@ -127,18 +127,18 @@ public class ZenExpandMember { for (int i = 0; i < result.length; i++) { result[i] = base[i + 1]; } - + return result; } } - + private class StaticGetValue implements IPartialExpression { private final ZenPosition position; - + public StaticGetValue(ZenPosition position) { this.position = position; } - + @Override public Expression eval(IEnvironmentGlobal environment) { return new ExpressionCallStatic(position, environment, getter); @@ -169,7 +169,7 @@ public class ZenExpandMember { public IZenSymbol toSymbol() { return new StaticSymbol(); } - + @Override public ZenType getType() { return getter.getReturnType(); @@ -186,7 +186,7 @@ public class ZenExpandMember { return JavaMethod.predict(methods, numArguments); } } - + private class StaticSymbol implements IZenSymbol { @Override public IPartialExpression instance(ZenPosition position) { diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorList.java b/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorList.java index 97f46cc..b75ef28 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorList.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorList.java @@ -18,7 +18,6 @@ import stanhebben.zenscript.util.MethodOutput; * @author Stan */ - public class IteratorList implements IZenIterator { private final MethodOutput methodOutput; private final ZenType iteratorType; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorMap.java b/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorMap.java index c3e6875..fb6330f 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorMap.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorMap.java @@ -24,7 +24,7 @@ public class IteratorMap implements IZenIterator { private final MethodOutput methodOutput; private final ZenTypeAssociative type; private int iterator; - + public IteratorMap(MethodOutput methodOutput, ZenTypeAssociative type) { this.methodOutput = methodOutput; this.type = type; @@ -66,7 +66,7 @@ public class IteratorMap implements IZenIterator { @Override public void compileEnd() { - + } @Override diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorMapKeys.java b/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorMapKeys.java index d16516b..6605709 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorMapKeys.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/iterator/IteratorMapKeys.java @@ -47,7 +47,7 @@ public class IteratorMapKeys implements IZenIterator { "hasNext", boolean.class); methodOutput.ifEQ(exit); - + methodOutput.loadObject(iterator); methodOutput.invokeInterface(Iterator.class, "next", Object.class); methodOutput.store(type.getKeyType().toASMType(), locals[0]); @@ -60,7 +60,7 @@ public class IteratorMapKeys implements IZenIterator { @Override public void compileEnd() { - + } @Override diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/natives/JavaMethod.java b/ZenScript/src/main/java/stanhebben/zenscript/type/natives/JavaMethod.java index 9601b0e..716d6ad 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/natives/JavaMethod.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/natives/JavaMethod.java @@ -30,7 +30,7 @@ public class JavaMethod implements IJavaMethod { public static final int PRIORITY_LOW = 1; public static final int PRIORITY_MEDIUM = 2; public static final int PRIORITY_HIGH = 3; - + public static IJavaMethod get(ITypeRegistry types, Class cls, String name, Class... parameterTypes) { try { Method method = cls.getMethod(name, parameterTypes); @@ -44,23 +44,24 @@ public class JavaMethod implements IJavaMethod { throw new RuntimeException("method retrieval not permitted", ex); } } - + public static IJavaMethod getStatic(String owner, String name, ZenType returnType, ZenType... arguments) { return new JavaMethodGenerated(true, false, false, owner, name, returnType, arguments, new boolean[arguments.length]); } - + public static IJavaMethod get(ITypeRegistry types, Method method) { return new JavaMethod(method, types); } - + public static IJavaMethod select(boolean doStatic, List methods, IEnvironmentGlobal environment, Expression... arguments) { int bestPriority = PRIORITY_INVALID; IJavaMethod bestMethod = null; boolean isValid = false; - + for (IJavaMethod method : methods) { - if (method.isStatic() != doStatic) continue; - + if (method.isStatic() != doStatic) + continue; + int priority = method.getPriority(environment, arguments); if (priority == bestPriority) { isValid = false; @@ -70,14 +71,14 @@ public class JavaMethod implements IJavaMethod { bestPriority = priority; } } - + return isValid ? bestMethod : null; } - + public static ZenType[] predict(List methods, int numArguments) { ZenType[] results = new ZenType[numArguments]; boolean[] ambiguous = new boolean[numArguments]; - + for (IJavaMethod method : methods) { if (method.accepts(numArguments)) { ZenType[] parameterTypes = method.getParameterTypes(); @@ -102,38 +103,38 @@ public class JavaMethod implements IJavaMethod { } } } - + for (int i = 0; i < results.length; i++) { if (ambiguous[i]) { results[i] = null; } } - + return results; } - + public static Expression[] rematch(ZenPosition position, IJavaMethod method, IEnvironmentGlobal environment, Expression... arguments) { ZenType[] parameterTypes = method.getParameterTypes(); - + // small optimization - don't run through this all if not necessary if (arguments.length == 0 && parameterTypes.length == 0) { return arguments; } - + Expression[] result = new Expression[method.getParameterTypes().length]; for (int i = arguments.length; i < method.getParameterTypes().length; i++) { result[i] = parameterTypes[i].defaultValue(position); } - + int doUntil = parameterTypes.length; if (method.isVarargs()) { doUntil = arguments.length - 1; ZenType paramType = parameterTypes[parameterTypes.length - 1]; ZenType baseType = ((ZenTypeArray) paramType).getBaseType(); - + if (arguments.length == parameterTypes.length) { ZenType argType = arguments[arguments.length - 1].getType(); - + if (argType.equals(paramType)) { result[arguments.length - 1] = arguments[arguments.length - 1]; } else if (argType.equals(baseType)) { @@ -152,34 +153,34 @@ public class JavaMethod implements IJavaMethod { result[arguments.length - 1] = new ExpressionArray(position, (ZenTypeArrayBasic) paramType, values); } } - + for (int i = arguments.length; i < doUntil; i++) { result[i] = parameterTypes[i].defaultValue(position); } for (int i = 0; i < Math.min(arguments.length, doUntil); i++) { result[i] = arguments[i].cast(position, environment, parameterTypes[i]); } - + return result; } - + private final Method method; - + private final ZenType ownerType; private final ZenType[] parameterTypes; private final boolean[] optional; private final ZenType returnType; - + public JavaMethod(Method method, ITypeRegistry types) { this.method = method; - + ownerType = types.getType(method.getDeclaringClass()); returnType = types.getType(method.getGenericReturnType()); parameterTypes = new ZenType[method.getParameterTypes().length]; optional = new boolean[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameterTypes[i] = types.getType(method.getGenericParameterTypes()[i]); - + optional[i] = false; for (Annotation annotation : method.getParameterAnnotations()[i]) { if (annotation instanceof Optional) { @@ -187,59 +188,61 @@ public class JavaMethod implements IJavaMethod { } } } - + if (method.isVarArgs()) { optional[parameterTypes.length - 1] = true; } } - + @Override public boolean isStatic() { return (method.getModifiers() & Modifier.STATIC) > 0; } - + @Override public boolean isVarargs() { return method.isVarArgs(); } - + @Override public ZenType getReturnType() { return returnType; } - + @Override public ZenType[] getParameterTypes() { return parameterTypes; } - + public Class getOwner() { return method.getDeclaringClass(); } - + public Method getMethod() { return method; } - + @Override public boolean accepts(IEnvironmentGlobal environment, Expression... arguments) { return getPriority(environment, arguments) > 0; } - + @Override public boolean accepts(int numArguments) { if (numArguments > parameterTypes.length) { return method.isVarArgs(); - } if (numArguments == parameterTypes.length) { + } + if (numArguments == parameterTypes.length) { return true; } else { for (int i = numArguments; i < parameterTypes.length; i++) { - if (!optional[i]) return false; + if (!optional[i]) + return false; } return true; } } - + @Override public int getPriority(IEnvironmentGlobal environment, Expression... arguments) { int result = PRIORITY_HIGH; @@ -262,25 +265,25 @@ public class JavaMethod implements IJavaMethod { } } else if (arguments.length < parameterTypes.length) { result = PRIORITY_MEDIUM; - + int checkUntil = parameterTypes.length; if (method.isVarArgs()) { checkUntil--; } - + checkOptional: for (int i = arguments.length; i < checkUntil; i++) { if (!optional[i]) { return PRIORITY_INVALID; } } } - + int checkUntil = arguments.length; if (arguments.length == parameterTypes.length && method.isVarArgs()) { ZenType arrayType = parameterTypes[method.getParameterTypes().length - 1]; ZenType baseType = ((ZenTypeArray) arrayType).getBaseType(); ZenType argType = arguments[arguments.length - 1].getType(); - + if (argType.equals(arrayType)) { // OK } else if (argType.equals(baseType)) { @@ -292,10 +295,10 @@ public class JavaMethod implements IJavaMethod { } else { return PRIORITY_INVALID; } - + checkUntil = arguments.length - 1; } - + for (int i = 0; i < checkUntil; i++) { ZenType argType = arguments[i].getType(); ZenType paramType = parameterTypes[i]; @@ -307,7 +310,7 @@ public class JavaMethod implements IJavaMethod { } } } - + return result; } @@ -318,7 +321,7 @@ public class JavaMethod implements IJavaMethod { } else { if (method.getDeclaringClass().isInterface()) { output.invokeInterface( - method.getDeclaringClass(), + method.getDeclaringClass(), method.getName(), method.getReturnType(), method.getParameterTypes()); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/natives/JavaMethodGenerated.java b/ZenScript/src/main/java/stanhebben/zenscript/type/natives/JavaMethodGenerated.java index b0d6c4c..d72b8bf 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/natives/JavaMethodGenerated.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/natives/JavaMethodGenerated.java @@ -26,11 +26,11 @@ public class JavaMethodGenerated implements IJavaMethod { private final boolean isVarargs; private final String owner; private final String name; - + private final ZenType[] parameterTypes; private final boolean[] optional; private final ZenType returnType; - + private final String descriptor; public JavaMethodGenerated( @@ -47,11 +47,11 @@ public class JavaMethodGenerated implements IJavaMethod { this.isVarargs = isVarargs; this.owner = owner; this.name = name; - + this.returnType = returnType; this.parameterTypes = arguments; this.optional = optional; - + StringBuilder descriptorString = new StringBuilder(); descriptorString.append('('); for (ZenType argument : arguments) { @@ -61,31 +61,33 @@ public class JavaMethodGenerated implements IJavaMethod { descriptorString.append(returnType.getSignature()); descriptor = descriptorString.toString(); } - + @Override public boolean isStatic() { return isStatic; } - + @Override public boolean isVarargs() { return isVarargs; } - + @Override public boolean accepts(int numArguments) { if (numArguments > parameterTypes.length) { return isVarargs; - } if (numArguments == parameterTypes.length) { + } + if (numArguments == parameterTypes.length) { return true; } else { for (int i = numArguments; i < parameterTypes.length; i++) { - if (!optional[i]) return false; + if (!optional[i]) + return false; } return true; } } - + @Override public boolean accepts(IEnvironmentGlobal environment, Expression... arguments) { return getPriority(environment, arguments) > 0; @@ -113,25 +115,25 @@ public class JavaMethodGenerated implements IJavaMethod { } } else if (arguments.length < parameterTypes.length) { result = PRIORITY_MEDIUM; - + int checkUntil = parameterTypes.length; if (isVarargs) { checkUntil--; } - + checkOptional: for (int i = arguments.length; i < checkUntil; i++) { if (!optional[i]) { return PRIORITY_INVALID; } } } - + int checkUntil = arguments.length; if (arguments.length == parameterTypes.length && isVarargs) { ZenType arrayType = parameterTypes[parameterTypes.length - 1]; ZenType baseType = ((ZenTypeArray) arrayType).getBaseType(); ZenType argType = arguments[arguments.length - 1].getType(); - + if (argType.equals(arrayType)) { // OK } else if (argType.equals(baseType)) { @@ -143,10 +145,10 @@ public class JavaMethodGenerated implements IJavaMethod { } else { return PRIORITY_INVALID; } - + checkUntil = arguments.length - 1; } - + for (int i = 0; i < checkUntil; i++) { ZenType argType = arguments[i].getType(); ZenType paramType = parameterTypes[i]; @@ -158,7 +160,7 @@ public class JavaMethodGenerated implements IJavaMethod { } } } - + return result; } @@ -178,7 +180,16 @@ public class JavaMethodGenerated implements IJavaMethod { @Override public void invokeStatic(MethodOutput output) { if (!isStatic) { - throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. + throw new UnsupportedOperationException("Not supported yet."); // To + // change + // body + // of + // generated + // methods, + // choose + // Tools + // | + // Templates. } else { output.invokeStatic(owner, name, descriptor); } @@ -188,7 +199,7 @@ public class JavaMethodGenerated implements IJavaMethod { public ZenType getReturnType() { return returnType; } - + @Override public ZenType[] getParameterTypes() { return parameterTypes; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/natives/ZenNativeCaster.java b/ZenScript/src/main/java/stanhebben/zenscript/type/natives/ZenNativeCaster.java index dd93054..4836123 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/natives/ZenNativeCaster.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/natives/ZenNativeCaster.java @@ -17,15 +17,15 @@ import stanhebben.zenscript.util.MethodOutput; */ public class ZenNativeCaster { private final IJavaMethod method; - + public ZenNativeCaster(IJavaMethod method) { this.method = method; } - + public ZenType getReturnType() { return method.getReturnType(); } - + public void compile(MethodOutput output) { if (method.isStatic()) { method.invokeStatic(output); @@ -33,7 +33,7 @@ public class ZenNativeCaster { method.invokeVirtual(output); } } - + public void compileAnyCanCastImplicit(ZenType type, MethodOutput output, IEnvironmentGlobal environment, int localClass) { String casterAny = method.getReturnType().getAnyClassName(environment); if (casterAny == null) { @@ -49,19 +49,19 @@ public class ZenNativeCaster { output.returnInt(); output.label(skip); } - + public void compileAnyCast(ZenType type, MethodOutput output, IEnvironmentGlobal environment, int localValue, int localClass) { Label skip = new Label(); output.loadObject(localClass); output.constant(method.getReturnType().toASMType()); output.ifACmpNe(skip); output.load(type.toASMType(), localValue); - + compile(output); - + output.returnType(method.getReturnType().toASMType()); output.label(skip); - + String casterAny = method.getReturnType().getAnyClassName(environment); if (casterAny == null) // TODO: make sure this isn't necessary @@ -72,9 +72,9 @@ public class ZenNativeCaster { output.invokeStatic(casterAny, "rtCanCastImplicit", "(Ljava/lang/Class;)Z"); output.ifEQ(skip2); output.load(type.toASMType(), localValue); - + compile(output); - + output.returnType(method.getReturnType().toASMType()); output.label(skip2); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/type/natives/ZenNativeOperator.java b/ZenScript/src/main/java/stanhebben/zenscript/type/natives/ZenNativeOperator.java index 390d140..ef1f8fc 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/type/natives/ZenNativeOperator.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/type/natives/ZenNativeOperator.java @@ -15,16 +15,16 @@ import stanhebben.zenscript.annotations.OperatorType; public class ZenNativeOperator { private final OperatorType operator; private final IJavaMethod method; - + public ZenNativeOperator(OperatorType operator, IJavaMethod method) { this.operator = operator; this.method = method; } - + public OperatorType getOperator() { return operator; } - + public IJavaMethod getMethod() { return method; } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/util/AnyClassWriter.java b/ZenScript/src/main/java/stanhebben/zenscript/util/AnyClassWriter.java index 81a0a3f..9f44404 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/util/AnyClassWriter.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/util/AnyClassWriter.java @@ -56,7 +56,7 @@ public class AnyClassWriter { public static final IJavaMethod METHOD_GETNUMBERTYPE = JavaMethod.get(EMPTY_REGISTRY, IAny.class, "getNumberType"); public static final IJavaMethod METHOD_ITERATORSINGLE = JavaMethod.get(EMPTY_REGISTRY, IAny.class, "iteratorSingle"); public static final IJavaMethod METHOD_ITERATORMULTI = JavaMethod.get(EMPTY_REGISTRY, IAny.class, "iteratorMulti", int.class); - + private static final String SIG_ANY = "()" + signature(IAny.class); private static final String SIG_ANY_ANY = "(" + signature(IAny.class) + ")" + signature(IAny.class); private static final String SIG_ANY_INT = "(" + signature(IAny.class) + ")I"; @@ -66,9 +66,10 @@ public class AnyClassWriter { private static final String SIG_STRING_ANYARRAY_ANY = "(" + signature(String.class) + signature(IAny[].class) + ")" + signature(IAny.class); private static final String SIG_ANY_ANY_VOID = "(" + signature(IAny.class) + signature(IAny.class) + ")V"; private static final String SIG_ANYARRAY_ANY = "(" + signature(IAny[].class) + ")" + signature(IAny.class); - - private AnyClassWriter() {} - + + private AnyClassWriter() { + } + public static byte[] construct(IAnyDefinition definition, String name, Type asmType) { try { ClassWriter writer = new ClassWriter(ClassWriter.COMPUTE_FRAMES); @@ -366,7 +367,7 @@ public class AnyClassWriter { writer, Opcodes.ACC_PUBLIC, "iteratorSingle", - "()" + signature(Iterator.class), + "()" + signature(Iterator.class), "()Ljava/util/Iterator;", null); outputIteratorSingle.start(); @@ -395,17 +396,12 @@ public class AnyClassWriter { definition.defineHashCode(outputHashCode); outputHashCode.end(); - /*MethodOutput outputEquals = new MethodOutput( - writer, - Opcodes.ACC_PUBLIC, - "equals", - "(Ljava/lang/Object;)Z", - null, - null); - outputEquals.enableDebug(); - outputEquals.start(); - definition.defineEquals(outputEquals); - outputEquals.end();*/ + /* + * MethodOutput outputEquals = new MethodOutput( writer, + * Opcodes.ACC_PUBLIC, "equals", "(Ljava/lang/Object;)Z", null, + * null); outputEquals.enableDebug(); outputEquals.start(); + * definition.defineEquals(outputEquals); outputEquals.end(); + */ writer.visitEnd(); return writer.toByteArray(); @@ -413,30 +409,33 @@ public class AnyClassWriter { throw new RuntimeException("Could not construct any class for " + name, ex); } } - + public static void throwUnsupportedException(MethodOutput output, String fromType, String operation) { - // throw new UnsupportedOperationException(fromType + " does not support the " + operation + " operator"); + // throw new UnsupportedOperationException(fromType + + // " does not support the " + operation + " operator"); output.newObject(UnsupportedOperationException.class); output.dup(); output.constant(fromType + " does not support the " + operation + " operator"); output.construct(UnsupportedOperationException.class, String.class); output.aThrow(); } - + public static void throwCastException(MethodOutput output, String fromType, String toType) { - // throw new ClassCastException("Cannot cast " + fromType + " to " + [local:Class].getName()) + // throw new ClassCastException("Cannot cast " + fromType + " to " + + // [local:Class].getName()) output.newObject(ClassCastException.class); output.dup(); output.constant("Cannot cast " + fromType + " to " + toType); output.construct(ClassCastException.class, String.class); output.aThrow(); } - + public static void throwCastException(MethodOutput output, String fromType, int local) { - // throw new ClassCastException("Cannot cast " + fromType + " to " + [local:Class].getName()) + // throw new ClassCastException("Cannot cast " + fromType + " to " + + // [local:Class].getName()) output.newObject(ClassCastException.class); output.dup(); - + output.newObject(StringBuilder.class); output.dup(); output.construct(StringBuilder.class); @@ -446,7 +445,7 @@ public class AnyClassWriter { output.invokeVirtual(Class.class, "getName", String.class); output.invokeVirtual(StringBuilder.class, "append", StringBuilder.class, String.class); output.invokeVirtual(StringBuilder.class, "toString", String.class); - + output.construct(ClassCastException.class, String.class); output.aThrow(); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/util/IAnyDefinition.java b/ZenScript/src/main/java/stanhebben/zenscript/util/IAnyDefinition.java index 790b2f7..8196de3 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/util/IAnyDefinition.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/util/IAnyDefinition.java @@ -14,78 +14,78 @@ import org.objectweb.asm.ClassVisitor; */ public interface IAnyDefinition { public void defineMembers(ClassVisitor output); - + public void defineStaticCanCastImplicit(MethodOutput output); - + public void defineStaticAs(MethodOutput output); - + public void defineNot(MethodOutput output); - + public void defineNeg(MethodOutput output); - + public void defineAdd(MethodOutput output); - + public void defineSub(MethodOutput output); - + public void defineCat(MethodOutput output); - + public void defineMul(MethodOutput output); - + public void defineDiv(MethodOutput output); - + public void defineMod(MethodOutput output); - + public void defineAnd(MethodOutput output); - + public void defineOr(MethodOutput output); - + public void defineXor(MethodOutput output); - + public void defineRange(MethodOutput output); - + public void defineCompareTo(MethodOutput output); - + public void defineContains(MethodOutput output); - + public void defineMemberGet(MethodOutput output); - + public void defineMemberSet(MethodOutput output); - + public void defineMemberCall(MethodOutput output); - + public void defineIndexGet(MethodOutput output); - + public void defineIndexSet(MethodOutput output); - + public void defineCall(MethodOutput output); - + public void defineAsBool(MethodOutput output); - + public void defineAsByte(MethodOutput output); - + public void defineAsShort(MethodOutput output); - + public void defineAsInt(MethodOutput output); - + public void defineAsLong(MethodOutput output); - + public void defineAsFloat(MethodOutput output); - + public void defineAsDouble(MethodOutput output); - + public void defineAsString(MethodOutput output); - + public void defineAs(MethodOutput output); - + public void defineIs(MethodOutput output); - + public void defineGetNumberType(MethodOutput output); - + public void defineIteratorSingle(MethodOutput output); - + public void defineIteratorMulti(MethodOutput output); - + public void defineEquals(MethodOutput output); - + public void defineHashCode(MethodOutput output); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/util/MappingIterator.java b/ZenScript/src/main/java/stanhebben/zenscript/util/MappingIterator.java index 3ddf9a1..1eb8e80 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/util/MappingIterator.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/util/MappingIterator.java @@ -8,11 +8,11 @@ import java.util.Iterator; */ public abstract class MappingIterator implements Iterator { private final Iterator iterator; - + public MappingIterator(Iterator iterator) { this.iterator = iterator; } - + public abstract U map(T value); @Override diff --git a/ZenScript/src/main/java/stanhebben/zenscript/util/MethodOutput.java b/ZenScript/src/main/java/stanhebben/zenscript/util/MethodOutput.java index 7b69cb2..af7a8d0 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/util/MethodOutput.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/util/MethodOutput.java @@ -24,229 +24,229 @@ import static stanhebben.zenscript.util.ZenTypeUtil.signature; * @author Stanneke */ public class MethodOutput { -// private static final boolean debug = true; - + // private static final boolean debug = true; + private final LocalVariablesSorter visitor; - + private boolean debug = false; private int labelIndex = 1; private Map labelNames; - + public MethodOutput(ClassVisitor cls, int access, String name, String descriptor, String signature, String[] exceptions) { MethodVisitor methodVisitor = cls.visitMethod(access, name, descriptor, signature, exceptions); visitor = new LocalVariablesSorter(access, descriptor, methodVisitor); } - + public MethodOutput(LocalVariablesSorter visitor) { this.visitor = visitor; } - + public void enableDebug() { debug = true; } - + public void start() { if (debug) System.out.println("--start--"); - + visitor.visitCode(); } - + public void end() { if (debug) System.out.println("--end--"); - + visitor.visitMaxs(0, 0); visitor.visitEnd(); } - + public void label(Label label) { if (debug) System.out.println("Label " + getLabelName(label)); - + visitor.visitLabel(label); } - + public int local(Type type) { return visitor.newLocal(type); } - + public int local(Class cls) { return visitor.newLocal(Type.getType(cls)); } - + public void iConst0() { if (debug) System.out.println("iconst0"); - + visitor.visitInsn(ICONST_0); } - + public void iConst1() { if (debug) System.out.println("iconst1"); - + visitor.visitInsn(ICONST_1); } - + public void biPush(byte value) { if (debug) System.out.println("bipush"); - + visitor.visitIntInsn(BIPUSH, value); } - + public void siPush(short value) { if (debug) System.out.println("sipush"); - + visitor.visitIntInsn(SIPUSH, value); } - + public void aConstNull() { if (debug) System.out.println("null"); - + visitor.visitInsn(ACONST_NULL); } - + public void constant(Object value) { if (debug) System.out.println("ldc " + value); - + visitor.visitLdcInsn(value); } - + public void pop() { if (debug) System.out.println("pop"); - + visitor.visitInsn(POP); } - + public void pop(boolean large) { if (debug) System.out.println("pop"); - + visitor.visitInsn(large ? POP2 : POP); } - + public void dup() { if (debug) System.out.println("dup"); - + visitor.visitInsn(DUP); } - + public void dup(boolean large) { if (debug) System.out.println("dup"); - + visitor.visitInsn(large ? DUP2 : DUP); } - + public void dup2() { if (debug) System.out.println("dup2"); - + visitor.visitInsn(DUP2); } - + public void dupX1() { if (debug) System.out.println("dupx1"); - + visitor.visitInsn(DUP_X1); } - + public void dupX2() { if (debug) System.out.println("dupx2"); - + visitor.visitInsn(DUP_X2); } - + public void dup2X1() { if (debug) System.out.println("dup2_x1"); - + visitor.visitInsn(DUP2_X1); } - + public void dup2X2() { if (debug) System.out.println("dup2_x2"); - + visitor.visitInsn(DUP2_X2); } - + public void store(Type type, int local) { if (debug) System.out.println("store " + local); - + visitor.visitVarInsn(type.getOpcode(ISTORE), local); } - + public void load(Type type, int local) { if (debug) System.out.println("load " + local); - + visitor.visitVarInsn(type.getOpcode(ILOAD), local); } - + public void storeInt(int local) { if (debug) System.out.println("storeInt " + local); - + visitor.visitVarInsn(ISTORE, local); } - + public void loadInt(int local) { if (debug) System.out.println("loadInt " + local); - + visitor.visitVarInsn(ILOAD, local); } - + public void storeObject(int local) { if (debug) System.out.println("storeObject " + local); - + visitor.visitVarInsn(ASTORE, local); } - + public void loadObject(int local) { if (debug) System.out.println("loadObject " + local); - + visitor.visitVarInsn(ALOAD, local); } - + public void arrayLength() { if (debug) System.out.println("arrayLength"); - + visitor.visitInsn(ARRAYLENGTH); } - + public void arrayLoad(Type type) { if (debug) System.out.println("arrayLoad"); - + visitor.visitInsn(type.getOpcode(IALOAD)); } - + public void arrayStore(Type type) { if (debug) System.out.println("arrayStore"); - + visitor.visitInsn(type.getOpcode(IASTORE)); } - + public void newArray(Type componentType) { if (debug) System.out.println("newArray"); - + int sort = componentType.getSort(); if (sort == Type.METHOD) { throw new RuntimeException("Unsupported array type: " + componentType); @@ -255,449 +255,463 @@ public class MethodOutput { } else { int type = 0; switch (sort) { - case Type.BOOLEAN: type = Opcodes.T_BOOLEAN; break; - case Type.BYTE: type = Opcodes.T_BYTE; break; - case Type.SHORT: type = Opcodes.T_SHORT; break; - case Type.INT: type = Opcodes.T_INT; break; - case Type.LONG: type = Opcodes.T_LONG; break; - case Type.FLOAT: type = Opcodes.T_FLOAT; break; - case Type.DOUBLE: type = Opcodes.T_DOUBLE; break; + case Type.BOOLEAN: + type = Opcodes.T_BOOLEAN; + break; + case Type.BYTE: + type = Opcodes.T_BYTE; + break; + case Type.SHORT: + type = Opcodes.T_SHORT; + break; + case Type.INT: + type = Opcodes.T_INT; + break; + case Type.LONG: + type = Opcodes.T_LONG; + break; + case Type.FLOAT: + type = Opcodes.T_FLOAT; + break; + case Type.DOUBLE: + type = Opcodes.T_DOUBLE; + break; default: throw new RuntimeException("Unsupported array type: " + componentType); } visitor.visitIntInsn(NEWARRAY, type); } } - + public void newArray(Class componentType) { if (debug) System.out.println("newArray " + componentType.getName()); - + visitor.visitTypeInsn(NEWARRAY, internal(componentType)); } - + public void checkCast(Class newClass) { if (debug) System.out.println("checkCast " + newClass.getName()); - + visitor.visitTypeInsn(CHECKCAST, signature(newClass)); } - + public void checkCast(String newClass) { if (debug) System.out.println("checkCast " + newClass); - + visitor.visitTypeInsn(CHECKCAST, newClass); } - + public void iNeg() { if (debug) System.out.println("iNeg"); - + visitor.visitInsn(INEG); } - + public void iAdd() { if (debug) System.out.println("iAdd"); - + visitor.visitInsn(IADD); } - + public void iSub() { if (debug) System.out.println("iSub"); - + visitor.visitInsn(ISUB); } - + public void iMul() { if (debug) System.out.println("iMul"); - + visitor.visitInsn(IMUL); } - + public void iDiv() { if (debug) System.out.println("iDiv"); - + visitor.visitInsn(IDIV); } - + public void iRem() { if (debug) System.out.println("iRem"); - + visitor.visitInsn(IREM); } - + public void iAnd() { if (debug) System.out.println("iAnd"); - + visitor.visitInsn(IAND); } - + public void iOr() { if (debug) System.out.println("iOr"); - + visitor.visitInsn(IOR); } - + public void iXor() { if (debug) System.out.println("iXor"); - + visitor.visitInsn(IXOR); } - + public void iNot() { if (debug) System.out.println("iNot"); - + visitor.visitInsn(ICONST_M1); visitor.visitInsn(IXOR); } - + public void iShr() { if (debug) System.out.println("iShr"); - + visitor.visitInsn(ISHR); } - + public void iShl() { if (debug) System.out.println("iShl"); - + visitor.visitInsn(ISHL); } - + public void lNeg() { if (debug) System.out.println("lNeg"); - + visitor.visitInsn(LNEG); } - + public void lAdd() { if (debug) System.out.println("lAdd"); - + visitor.visitInsn(LADD); } - + public void lSub() { if (debug) System.out.println("lSub"); - + visitor.visitInsn(LSUB); } - + public void lMul() { if (debug) System.out.println("lMul"); - + visitor.visitInsn(LMUL); } - + public void lDiv() { if (debug) System.out.println("lDiv"); - + visitor.visitInsn(LDIV); } - + public void lRem() { if (debug) System.out.println("lRem"); - + visitor.visitInsn(LREM); } - + public void lAnd() { if (debug) System.out.println("lAnd"); - + visitor.visitInsn(LAND); } - + public void lOr() { if (debug) System.out.println("lOr"); - + visitor.visitInsn(LOR); } - + public void lXor() { if (debug) System.out.println("lXor"); - + visitor.visitInsn(LXOR); } - + public void lNot() { if (debug) System.out.println("lNot"); - + constant((long) -1); lXor(); } - + public void lShr() { if (debug) System.out.println("lShr"); - + visitor.visitInsn(LSHR); } - + public void lShl() { if (debug) System.out.println("lShl"); - + visitor.visitInsn(LSHL); } - + public void fNeg() { if (debug) System.out.println("fNeg"); - + visitor.visitInsn(FNEG); } - + public void fAdd() { if (debug) System.out.println("fAdd"); - + visitor.visitInsn(FADD); } - + public void fSub() { if (debug) System.out.println("fSub"); - + visitor.visitInsn(FSUB); } - + public void fMul() { if (debug) System.out.println("fMul"); - + visitor.visitInsn(FMUL); } - + public void fDiv() { if (debug) System.out.println("fDiv"); - + visitor.visitInsn(FDIV); } - + public void fRem() { if (debug) System.out.println("fRem"); - + visitor.visitInsn(FREM); } - + public void dNeg() { if (debug) System.out.println("dNeg"); - + visitor.visitInsn(DNEG); } - + public void dAdd() { if (debug) System.out.println("dAdd"); - + visitor.visitInsn(DADD); } - + public void dSub() { if (debug) System.out.println("dSub"); - + visitor.visitInsn(DSUB); } - + public void dMul() { if (debug) System.out.println("dMul"); - + visitor.visitInsn(DMUL); } - + public void dDiv() { if (debug) System.out.println("dDiv"); - + visitor.visitInsn(DDIV); } - + public void dRem() { if (debug) System.out.println("dRem"); - + visitor.visitInsn(DREM); } - + public void iinc(int local) { if (debug) System.out.println("iinc " + local); - + visitor.visitIincInsn(local, 1); } - + public void iinc(int local, int increment) { if (debug) System.out.println("iinc " + local + " + " + increment); - + visitor.visitIincInsn(local, increment); } - + public void i2b() { if (debug) System.out.println("i2b"); - + visitor.visitInsn(I2B); } - + public void i2s() { if (debug) System.out.println("i2s"); - + visitor.visitInsn(I2S); } - + public void i2l() { if (debug) System.out.println("i2l"); - + visitor.visitInsn(I2L); } - + public void i2f() { if (debug) System.out.println("i2f"); - + visitor.visitInsn(I2F); } - + public void i2d() { if (debug) System.out.println("i2d"); - + visitor.visitInsn(I2D); } - + public void l2i() { if (debug) System.out.println("l2i"); - + visitor.visitInsn(L2I); } - + public void l2f() { if (debug) System.out.println("l2f"); - + visitor.visitInsn(L2F); } - + public void l2d() { if (debug) System.out.println("l2d"); - + visitor.visitInsn(L2D); } - + public void f2i() { if (debug) System.out.println("f2i"); - + visitor.visitInsn(F2I); } - + public void f2l() { if (debug) System.out.println("f2l"); - + visitor.visitInsn(F2L); } - + public void f2d() { if (debug) System.out.println("f2d"); - + visitor.visitInsn(F2D); } - + public void d2i() { if (debug) System.out.println("d2i"); - + visitor.visitInsn(D2I); } - + public void d2l() { if (debug) System.out.println("d2l"); - + visitor.visitInsn(D2L); } - + public void d2f() { if (debug) System.out.println("d2f"); - + visitor.visitInsn(D2F); } - + public void lCmp() { if (debug) System.out.println("lCmp"); - + visitor.visitInsn(LCMP); } - + public void fCmp() { if (debug) System.out.println("fCmp"); - + visitor.visitInsn(FCMPL); } - + public void dCmp() { if (debug) System.out.println("dCmp"); - + visitor.visitInsn(DCMPL); } - + public void instanceOf(String clsName) { if (debug) System.out.println("instanceOf " + clsName); - + visitor.visitTypeInsn(INSTANCEOF, clsName); } - + public void invokeStatic(String owner, String name, String descriptor) { if (debug) System.out.println("invokeStatic " + owner + '.' + name + descriptor); - + if (owner == null) throw new IllegalArgumentException("owner cannot be null"); if (name == null) throw new IllegalArgumentException("name cannot be null"); if (descriptor == null) throw new IllegalArgumentException("descriptor cannot be null"); - + visitor.visitMethodInsn(INVOKESTATIC, owner, name, descriptor); } - + public void invokeStatic(Class owner, String name, Class result, Class... arguments) { StringBuilder descriptor = new StringBuilder(); descriptor.append('('); @@ -706,20 +720,20 @@ public class MethodOutput { } descriptor.append(')'); descriptor.append(result == null ? 'V' : signature(result)); - + if (debug) System.out.println("invokeStatic " + internal(owner) + '.' + name + descriptor); - + visitor.visitMethodInsn(INVOKESTATIC, internal(owner), name, descriptor.toString()); } - + public void invokeSpecial(String owner, String name, String descriptor) { if (debug) System.out.println("invokeSpecial " + owner + '.' + name + descriptor); - + visitor.visitMethodInsn(INVOKESPECIAL, owner, name, descriptor); } - + public void invoke(Class owner, String name, Class result, Class... arguments) { if (owner.isInterface()) { invokeInterface(owner, name, result, arguments); @@ -727,14 +741,14 @@ public class MethodOutput { invokeVirtual(owner, name, result, arguments); } } - + public void invokeVirtual(String owner, String name, String descriptor) { if (debug) System.out.println("invokeVirtual " + owner + '.' + name + descriptor); - + visitor.visitMethodInsn(INVOKEVIRTUAL, owner, name, descriptor); } - + public void invokeVirtual(Class owner, String name, Class result, Class... arguments) { StringBuilder descriptor = new StringBuilder(); descriptor.append('('); @@ -743,20 +757,20 @@ public class MethodOutput { } descriptor.append(')'); descriptor.append(result == null ? 'V' : signature(result)); - + if (debug) System.out.println("invokeVirtual " + owner + '.' + name + descriptor); - + visitor.visitMethodInsn(INVOKEVIRTUAL, internal(owner), name, descriptor.toString()); } - + public void invokeInterface(String owner, String name, String descriptor) { if (debug) System.out.println("invokeInterface " + owner + '.' + name + descriptor); - + visitor.visitMethodInsn(INVOKEINTERFACE, owner, name, descriptor); } - + public void invokeInterface(Class owner, String name, Class result, Class... arguments) { StringBuilder descriptor = new StringBuilder(); descriptor.append('('); @@ -765,27 +779,27 @@ public class MethodOutput { } descriptor.append(')'); descriptor.append(result == null ? 'V' : signature(result)); - + if (debug) System.out.println("invokeInterface " + owner + '.' + name + descriptor); - + visitor.visitMethodInsn(INVOKEINTERFACE, internal(owner), name, descriptor.toString()); } - + public void newObject(Class type) { if (debug) System.out.println("newObject " + type.getName()); - + visitor.visitTypeInsn(NEW, internal(type)); } - + public void newObject(String type) { if (debug) System.out.println("newObject " + type); - + visitor.visitTypeInsn(NEW, type); } - + public void construct(Class type, Class... arguments) { StringBuilder descriptor = new StringBuilder(); descriptor.append('('); @@ -793,13 +807,13 @@ public class MethodOutput { descriptor.append(signature(argument)); } descriptor.append(")V"); - + if (debug) System.out.println("invokeSpecial " + internal(type) + "." + descriptor); - + visitor.visitMethodInsn(INVOKESPECIAL, internal(type), "", descriptor.toString()); } - + public void construct(String type, String... arguments) { StringBuilder descriptor = new StringBuilder(); descriptor.append('('); @@ -807,20 +821,20 @@ public class MethodOutput { descriptor.append(argument); } descriptor.append(")V"); - + if (debug) System.out.println("invokeSpecial " + type + "." + descriptor); - + visitor.visitMethodInsn(INVOKESPECIAL, type, "", descriptor.toString()); } - + public void goTo(Label lbl) { if (debug) System.out.println("goTo " + getLabelName(lbl)); - + visitor.visitJumpInsn(GOTO, lbl); } - + /** * Jump if TOS == 0. * @@ -829,217 +843,217 @@ public class MethodOutput { public void ifEQ(Label lbl) { if (debug) System.out.println("ifEQ " + getLabelName(lbl)); - + visitor.visitJumpInsn(IFEQ, lbl); } - + public void ifNE(Label lbl) { if (debug) System.out.println("ifNE " + getLabelName(lbl)); - + visitor.visitJumpInsn(IFNE, lbl); } - + public void ifLT(Label lbl) { if (debug) System.out.println("ifLT " + getLabelName(lbl)); - + visitor.visitJumpInsn(IFLT, lbl); } - + public void ifGT(Label lbl) { if (debug) System.out.println("ifGT " + getLabelName(lbl)); - + visitor.visitJumpInsn(IFGT, lbl); } - + public void ifGE(Label lbl) { if (debug) System.out.println("ifGE " + getLabelName(lbl)); - + visitor.visitJumpInsn(IFGE, lbl); } - + public void ifLE(Label lbl) { if (debug) System.out.println("ifLE " + getLabelName(lbl)); - + visitor.visitJumpInsn(IFLE, lbl); } - + public void ifICmpLE(Label lbl) { if (debug) System.out.println("ifICmpLE " + getLabelName(lbl)); - + visitor.visitJumpInsn(IF_ICMPLE, lbl); } - + public void ifICmpGE(Label lbl) { if (debug) System.out.println("ifICmpGE " + getLabelName(lbl)); - + visitor.visitJumpInsn(IF_ICMPGE, lbl); } - + public void ifICmpEQ(Label lbl) { if (debug) System.out.println("ifICmpEQ " + getLabelName(lbl)); - + visitor.visitJumpInsn(IF_ICMPEQ, lbl); } - + public void ifICmpNE(Label lbl) { if (debug) System.out.println("ifICmpNE " + getLabelName(lbl)); - + visitor.visitJumpInsn(IF_ICMPNE, lbl); } - + public void ifICmpGT(Label lbl) { if (debug) System.out.println("ifICmpGT " + getLabelName(lbl)); - + visitor.visitJumpInsn(IF_ICMPGT, lbl); } - + public void ifICmpLT(Label lbl) { if (debug) System.out.println("ifICmpLT " + getLabelName(lbl)); - + visitor.visitJumpInsn(IF_ICMPLT, lbl); } - + public void ifACmpEq(Label lbl) { if (debug) System.out.println("ifICmpEQ " + getLabelName(lbl)); - + visitor.visitJumpInsn(IF_ACMPEQ, lbl); } - + public void ifACmpNe(Label lbl) { if (debug) System.out.println("ifACmpNE " + getLabelName(lbl)); - + visitor.visitJumpInsn(IF_ACMPNE, lbl); } - + public void ifNull(Label lbl) { if (debug) System.out.println("ifNull " + getLabelName(lbl)); - + visitor.visitJumpInsn(IFNULL, lbl); } - + public void ifNonNull(Label lbl) { if (debug) System.out.println("ifNonNull " + getLabelName(lbl)); - + visitor.visitJumpInsn(IFNONNULL, lbl); } - + public void ret() { if (debug) System.out.println("ret"); - + visitor.visitInsn(RETURN); } - + public void returnType(Type type) { if (debug) System.out.println("return " + type.getDescriptor()); - + visitor.visitInsn(type.getOpcode(IRETURN)); } - + public void returnInt() { if (debug) System.out.println("ireturn"); - + visitor.visitInsn(IRETURN); } - + public void returnObject() { if (debug) System.out.println("areturn"); - + visitor.visitInsn(ARETURN); } - + public void getField(String owner, String name, String descriptor) { if (debug) System.out.println("getField " + owner + '.' + name + ":" + descriptor); - + visitor.visitFieldInsn(GETFIELD, owner, name, descriptor); } - + public void getField(Class owner, String name, Class descriptor) { if (debug) System.out.println("getField " + owner.getName() + '.' + name + ":" + descriptor.getName()); - + visitor.visitFieldInsn(GETFIELD, internal(owner), name, signature(descriptor)); } - + public void putField(String owner, String name, String descriptor) { if (debug) System.out.println("putField " + owner + '.' + name + ":" + descriptor); - + visitor.visitFieldInsn(PUTFIELD, owner, name, descriptor); } - + public void putField(Class owner, String name, Class descriptor) { if (debug) System.out.println("putField " + owner.getName() + '.' + name + ":" + descriptor.getName()); - + visitor.visitFieldInsn(PUTFIELD, internal(owner), name, signature(descriptor)); } - + public void getStaticField(String owner, String name, String descriptor) { if (debug) System.out.println("getStatic " + owner + '.' + name + ":" + descriptor); - + visitor.visitFieldInsn(GETSTATIC, owner, name, descriptor); } - + public void getStaticField(Class owner, Field field) { if (debug) System.out.println("getField " + owner.getName() + '.' + field.getName() + ":" + signature(field.getType())); - + visitor.visitFieldInsn(GETSTATIC, internal(owner), field.getName(), signature(field.getType())); } - + public void putStaticField(String owner, String name, String descriptor) { if (debug) System.out.println("putStatic " + owner + '.' + name + ":" + descriptor); - + visitor.visitFieldInsn(PUTSTATIC, owner, name, descriptor); } - + public void putStaticField(Class owner, Field field) { if (debug) System.out.println("putStatic " + owner.getName() + '.' + field.getName() + ":" + signature(field.getType())); - + visitor.visitFieldInsn(PUTSTATIC, internal(owner), field.getName(), signature(field.getType())); } - + public void aThrow() { visitor.visitInsn(ATHROW); } - + public void position(ZenPosition position) { Label label = new Label(); visitor.visitLabel(label); visitor.visitLineNumber(position.getLine(), label); } - + private String getLabelName(Label lbl) { if (labelNames == null) labelNames = new HashMap(); - + if (!labelNames.containsKey(lbl)) { labelNames.put(lbl, "L" + labelIndex++); } - + return labelNames.get(lbl); } } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/util/StringUtil.java b/ZenScript/src/main/java/stanhebben/zenscript/util/StringUtil.java index c34357c..3029c56 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/util/StringUtil.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/util/StringUtil.java @@ -16,8 +16,9 @@ import stanhebben.zenscript.type.natives.IJavaMethod; * @author Stanneke */ public class StringUtil { - private StringUtil() {} - + private StringUtil() { + } + public static String join(String[] values, String separator) { StringBuilder result = new StringBuilder(); boolean first = true; @@ -31,7 +32,7 @@ public class StringUtil { } return result.toString(); } - + public static String join(Iterable values, String separator) { StringBuilder result = new StringBuilder(); boolean first = true; @@ -45,10 +46,10 @@ public class StringUtil { } return result.toString(); } - + /** - * If a set of methods is available and none matches, this method creates - * a suitable message. + * If a set of methods is available and none matches, this method creates a + * suitable message. * * @param methods matching methods * @param arguments calling arguments @@ -78,29 +79,30 @@ public class StringUtil { return message.toString(); } } - - /** - * Splits a string in parts, given a specified delimiter. - * - * @param value string to be split - * @param delimiter delimiter - * @return - */ - public static String[] split(String value, char delimiter) { - if (value == null) return null; - + + /** + * Splits a string in parts, given a specified delimiter. + * + * @param value string to be split + * @param delimiter delimiter + * @return + */ + public static String[] split(String value, char delimiter) { + if (value == null) + return null; + ArrayList result = new ArrayList(); - int start = 0; - outer: for (int i = 0; i < value.length(); i++) { - if (value.charAt(i) == delimiter) { - result.add(value.substring(start, i)); - start = i + 1; - } - } - result.add(value.substring(start)); - return result.toArray(new String[result.size()]); - } - + int start = 0; + outer: for (int i = 0; i < value.length(); i++) { + if (value.charAt(i) == delimiter) { + result.add(value.substring(start, i)); + start = i + 1; + } + } + result.add(value.substring(start)); + return result.toArray(new String[result.size()]); + } + /** * Processes a doc comment into paragraphs. * @@ -127,10 +129,10 @@ public class StringUtil { if (current.length() > 0) { output.add(current.toString()); } - + return output.toArray(new String[output.size()]); } - + // ######################## // ### String utilities ### // ######################## @@ -186,14 +188,14 @@ public class StringUtil { * what about \[IDIOT JAVA PREPROCESSOR]u? * * @param oldstr - * @return + * @return */ public static String unescapeString(String oldstr) { if ((oldstr.charAt(0) != '"' || oldstr.charAt(oldstr.length() - 1) != '"') && (oldstr.charAt(0) != '\'' || oldstr.charAt(oldstr.length() - 1) != '\'')) { // TODO: error - //throw new TweakerExecuteException("Not a valid string constant: " - // + oldstr); + // throw new TweakerExecuteException("Not a valid string constant: " + // + oldstr); } oldstr = oldstr.substring(1, oldstr.length() - 1); @@ -232,252 +234,252 @@ public class StringUtil { switch (cp) { - case 'r': - newstr.append('\r'); - break; /* switch */ + case 'r': + newstr.append('\r'); + break; /* switch */ - case 'n': - newstr.append('\n'); - break; /* switch */ + case 'n': + newstr.append('\n'); + break; /* switch */ - case 'f': - newstr.append('\f'); - break; /* switch */ + case 'f': + newstr.append('\f'); + break; /* switch */ - /* PASS a \b THROUGH!! */ - case 'b': - newstr.append("\\b"); - break; /* switch */ + /* PASS a \b THROUGH!! */ + case 'b': + newstr.append("\\b"); + break; /* switch */ - case 't': - newstr.append('\t'); - break; /* switch */ + case 't': + newstr.append('\t'); + break; /* switch */ - case 'a': - newstr.append('\007'); - break; /* switch */ + case 'a': + newstr.append('\007'); + break; /* switch */ - case 'e': - newstr.append('\033'); - break; /* switch */ - - /* - * A "control" character is what you get when you xor its codepoint - * with '@'==64. This only makes sense for ASCII, and may not yield - * a "control" character after all. - * - * Strange but true: "\c{" is ";", "\c}" is "=", etc. - */ - case 'c': { - if (++i == oldstr.length()) { - // TODO: error - //throw new TweakerExecuteException("trailing \\c"); - } - cp = oldstr.codePointAt(i); - /* - * don't need to grok surrogates, as next line blows them up - */ - if (cp > 0x7f) { - // TODO: error - //throw new TweakerExecuteException( - // "expected ASCII after \\c"); - } - newstr.append(Character.toChars(cp ^ 64)); - break; /* switch */ - } - - case '8': - case '9': - // TODO: error - //throw new TweakerExecuteException("illegal octal digit"); - /* NOTREACHED */ + case 'e': + newstr.append('\033'); + break; /* switch */ /* - * may be 0 to 2 octal digits following this one so back up one - * for fallthrough to next case; unread this digit and fall - * through to next case. + * A "control" character is what you get when you xor its + * codepoint with '@'==64. This only makes sense for ASCII, and + * may not yield a "control" character after all. + * + * Strange but true: "\c{" is ";", "\c}" is "=", etc. */ - case '1': - case '2': - case '3': - case '4': - case '5': - case '6': - case '7': - --i; - /* FALLTHROUGH */ - - /* - * Can have 0, 1, or 2 octal digits following a 0 this permits - * larger values than octal 377, up to octal 777. - */ - case '0': { - if (i + 1 == oldstr.length()) { - /* found \0 at end of string */ - newstr.append(Character.toChars(0)); + case 'c': { + if (++i == oldstr.length()) { + // TODO: error + // throw new TweakerExecuteException("trailing \\c"); + } + cp = oldstr.codePointAt(i); + /* + * don't need to grok surrogates, as next line blows them up + */ + if (cp > 0x7f) { + // TODO: error + // throw new TweakerExecuteException( + // "expected ASCII after \\c"); + } + newstr.append(Character.toChars(cp ^ 64)); break; /* switch */ } - i++; - int digits = 0; - int j; - for (j = 0; j <= 2; j++) { - if (i + j == oldstr.length()) { - break; /* for */ - } - /* safe because will unread surrogate */ - int ch = oldstr.charAt(i + j); - if (ch < '0' || ch > '7') { - break; /* for */ - } - digits++; - } - if (digits == 0) { - --i; - newstr.append('\0'); - break; /* switch */ - } - int value = 0; - try { - value = Integer - .parseInt(oldstr.substring(i, i + digits), 8); - } catch (NumberFormatException nfe) { - // TODO: error - //throw new TweakerExecuteException( - // "invalid octal value for \\0 escape"); - } - newstr.append(Character.toChars(value)); - i += digits - 1; - break; /* switch */ - } /* end case '0' */ - case 'x': { - if (i + 2 > oldstr.length()) { + case '8': + case '9': // TODO: error - //throw new TweakerExecuteException( - // "string too short for \\x escape"); - } - i++; - boolean saw_brace = false; - if (oldstr.charAt(i) == '{') { - /* ^^^^^^ ok to ignore surrogates here */ - i++; - saw_brace = true; - } - int j; - for (j = 0; j < 8; j++) { - - if (!saw_brace && j == 2) { - break; /* for */ - } + // throw new TweakerExecuteException("illegal octal digit"); + /* NOTREACHED */ /* - * ASCII test also catches surrogates + * may be 0 to 2 octal digits following this one so back up + * one for fallthrough to next case; unread this digit and + * fall through to next case. */ - int ch = oldstr.charAt(i + j); - if (ch > 127) { + case '1': + case '2': + case '3': + case '4': + case '5': + case '6': + case '7': + --i; + /* FALLTHROUGH */ + + /* + * Can have 0, 1, or 2 octal digits following a 0 this + * permits larger values than octal 377, up to octal 777. + */ + case '0': { + if (i + 1 == oldstr.length()) { + /* found \0 at end of string */ + newstr.append(Character.toChars(0)); + break; /* switch */ + } + i++; + int digits = 0; + int j; + for (j = 0; j <= 2; j++) { + if (i + j == oldstr.length()) { + break; /* for */ + } + /* safe because will unread surrogate */ + int ch = oldstr.charAt(i + j); + if (ch < '0' || ch > '7') { + break; /* for */ + } + digits++; + } + if (digits == 0) { + --i; + newstr.append('\0'); + break; /* switch */ + } + int value = 0; + try { + value = Integer + .parseInt(oldstr.substring(i, i + digits), 8); + } catch (NumberFormatException nfe) { // TODO: error - //throw new TweakerExecuteException( - // "illegal non-ASCII hex digit in \\x escape"); + // throw new TweakerExecuteException( + // "invalid octal value for \\0 escape"); } + newstr.append(Character.toChars(value)); + i += digits - 1; + break; /* switch */ + } /* end case '0' */ - if (saw_brace && ch == '}') { - break; /* for */ - } - - if (!((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))) { + case 'x': { + if (i + 2 > oldstr.length()) { // TODO: error - //throw new TweakerExecuteException(String.format( - // "illegal hex digit #%d '%c' in \\x", ch, ch)); + // throw new TweakerExecuteException( + // "string too short for \\x escape"); } + i++; + boolean saw_brace = false; + if (oldstr.charAt(i) == '{') { + /* ^^^^^^ ok to ignore surrogates here */ + i++; + saw_brace = true; + } + int j; + for (j = 0; j < 8; j++) { - } - if (j == 0) { - // TODO: error - //throw new TweakerExecuteException( - // "empty braces in \\x{} escape"); - } - int value = 0; - try { - value = Integer.parseInt(oldstr.substring(i, i + j), 16); - } catch (NumberFormatException nfe) { - // TODO: error - //throw new TweakerExecuteException( - // "invalid hex value for \\x escape"); - } - newstr.append(Character.toChars(value)); - if (saw_brace) { - j++; - } - i += j - 1; - break; /* switch */ - } + if (!saw_brace && j == 2) { + break; /* for */ + } - case 'u': { - if (i + 4 > oldstr.length()) { - // TODO: error - //throw new TweakerExecuteException( - // "string too short for \\u escape"); - } - i++; - int j; - for (j = 0; j < 4; j++) { - /* this also handles the surrogate issue */ - if (oldstr.charAt(i + j) > 127) { + /* + * ASCII test also catches surrogates + */ + int ch = oldstr.charAt(i + j); + if (ch > 127) { + // TODO: error + // throw new TweakerExecuteException( + // "illegal non-ASCII hex digit in \\x escape"); + } + + if (saw_brace && ch == '}') { + break; /* for */ + } + + if (!((ch >= '0' && ch <= '9') || (ch >= 'a' && ch <= 'f') || (ch >= 'A' && ch <= 'F'))) { + // TODO: error + // throw new TweakerExecuteException(String.format( + // "illegal hex digit #%d '%c' in \\x", ch, ch)); + } + + } + if (j == 0) { // TODO: error - //throw new TweakerExecuteException( - // "illegal non-ASCII hex digit in \\u escape"); + // throw new TweakerExecuteException( + // "empty braces in \\x{} escape"); } - } - int value = 0; - try { - value = Integer.parseInt(oldstr.substring(i, i + j), 16); - } catch (NumberFormatException nfe) { - // TODO: error - //throw new TweakerExecuteException( - // "invalid hex value for \\u escape"); - } - newstr.append(Character.toChars(value)); - i += j - 1; - break; /* switch */ - } - - case 'U': { - if (i + 8 > oldstr.length()) { - // TODO: error - //throw new TweakerExecuteException( - // "string too short for \\U escape"); - } - i++; - int j; - for (j = 0; j < 8; j++) { - /* this also handles the surrogate issue */ - if (oldstr.charAt(i + j) > 127) { + int value = 0; + try { + value = Integer.parseInt(oldstr.substring(i, i + j), 16); + } catch (NumberFormatException nfe) { // TODO: error - //throw new TweakerExecuteException( - // "illegal non-ASCII hex digit in \\U escape"); + // throw new TweakerExecuteException( + // "invalid hex value for \\x escape"); } + newstr.append(Character.toChars(value)); + if (saw_brace) { + j++; + } + i += j - 1; + break; /* switch */ } - int value = 0; - try { - value = Integer.parseInt(oldstr.substring(i, i + j), 16); - } catch (NumberFormatException nfe) { - // TODO: error - //throw new TweakerExecuteException( - // "invalid hex value for \\U escape"); - } - newstr.append(Character.toChars(value)); - i += j - 1; - break; /* switch */ - } - default: - newstr.append('\\'); - newstr.append(Character.toChars(cp)); - /* - * say(String.format( - * "DEFAULT unrecognized escape %c passed through", cp)); - */ - break; /* switch */ + case 'u': { + if (i + 4 > oldstr.length()) { + // TODO: error + // throw new TweakerExecuteException( + // "string too short for \\u escape"); + } + i++; + int j; + for (j = 0; j < 4; j++) { + /* this also handles the surrogate issue */ + if (oldstr.charAt(i + j) > 127) { + // TODO: error + // throw new TweakerExecuteException( + // "illegal non-ASCII hex digit in \\u escape"); + } + } + int value = 0; + try { + value = Integer.parseInt(oldstr.substring(i, i + j), 16); + } catch (NumberFormatException nfe) { + // TODO: error + // throw new TweakerExecuteException( + // "invalid hex value for \\u escape"); + } + newstr.append(Character.toChars(value)); + i += j - 1; + break; /* switch */ + } + + case 'U': { + if (i + 8 > oldstr.length()) { + // TODO: error + // throw new TweakerExecuteException( + // "string too short for \\U escape"); + } + i++; + int j; + for (j = 0; j < 8; j++) { + /* this also handles the surrogate issue */ + if (oldstr.charAt(i + j) > 127) { + // TODO: error + // throw new TweakerExecuteException( + // "illegal non-ASCII hex digit in \\U escape"); + } + } + int value = 0; + try { + value = Integer.parseInt(oldstr.substring(i, i + j), 16); + } catch (NumberFormatException nfe) { + // TODO: error + // throw new TweakerExecuteException( + // "invalid hex value for \\U escape"); + } + newstr.append(Character.toChars(value)); + i += j - 1; + break; /* switch */ + } + + default: + newstr.append('\\'); + newstr.append(Character.toChars(cp)); + /* + * say(String.format( + * "DEFAULT unrecognized escape %c passed through", cp)); + */ + break; /* switch */ } saw_backslash = false; diff --git a/ZenScript/src/main/java/stanhebben/zenscript/util/ZenPosition.java b/ZenScript/src/main/java/stanhebben/zenscript/util/ZenPosition.java index 7200f94..9225122 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/util/ZenPosition.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/util/ZenPosition.java @@ -16,27 +16,28 @@ public class ZenPosition { private final ZenParsedFile file; private final int line; private final int offset; - + public ZenPosition(ZenParsedFile file, int line, int offset) { - if (file != null && line <= 0) throw new IllegalArgumentException("Line must be positive"); - + if (file != null && line <= 0) + throw new IllegalArgumentException("Line must be positive"); + this.file = file; this.line = line; this.offset = offset; } - + public ZenParsedFile getFile() { return file; } - + public int getLine() { return line; } - + public int getLineOffset() { return offset; } - + @Override public String toString() { return (file == null ? "?" : file.getFileName()) + ":" + Integer.toString(line); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/util/ZenTypeUtil.java b/ZenScript/src/main/java/stanhebben/zenscript/util/ZenTypeUtil.java index fef5164..42e7c09 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/util/ZenTypeUtil.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/util/ZenTypeUtil.java @@ -18,9 +18,9 @@ import stanhebben.zenscript.compiler.TypeRegistry; */ public class ZenTypeUtil { public static final ITypeRegistry EMPTY_REGISTRY = new TypeRegistry(); - + private static final Map SIGNATURE_MAP; - + static { SIGNATURE_MAP = new HashMap(); SIGNATURE_MAP.put(boolean.class.getName(), "Z"); @@ -33,7 +33,7 @@ public class ZenTypeUtil { SIGNATURE_MAP.put(char.class.getName(), "C"); SIGNATURE_MAP.put(void.class.getName(), "V"); } - + public static String signature(Class cls) { if (SIGNATURE_MAP.containsKey(cls.getName())) { return SIGNATURE_MAP.get(cls.getName()); @@ -45,11 +45,11 @@ public class ZenTypeUtil { return signature; } } - + public static String internal(Class cls) { return cls.getName().replace('.', '/'); } - + public static String descriptor(Method method) { StringBuilder output = new StringBuilder(); output.append('('); diff --git a/ZenScript/src/main/java/stanhebben/zenscript/value/IAny.java b/ZenScript/src/main/java/stanhebben/zenscript/value/IAny.java index 654de1f..091557d 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/value/IAny.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/value/IAny.java @@ -14,79 +14,79 @@ import java.util.Iterator; */ public interface IAny { public static final String NAME = "stanhebben/zenscript/value/IAny"; - + public static final int NUM_BYTE = 1; public static final int NUM_SHORT = 2; public static final int NUM_INT = 3; public static final int NUM_LONG = 4; public static final int NUM_FLOAT = 5; public static final int NUM_DOUBLE = 6; - + public IAny not(); - + public IAny neg(); - + public IAny add(IAny value); - + public IAny sub(IAny value); - + public IAny cat(IAny value); - + public IAny mul(IAny value); - + public IAny div(IAny value); - + public IAny mod(IAny value); - + public IAny and(IAny value); - + public IAny or(IAny value); - + public IAny xor(IAny value); - + public IAny range(IAny value); - + public int compareTo(IAny value); - + public boolean contains(IAny value); - + public IAny memberGet(String member); - + public void memberSet(String member, IAny value); - + public IAny memberCall(String member, IAny... values); - + public IAny indexGet(IAny key); - + public void indexSet(IAny key, IAny value); - + public IAny call(IAny... values); - + public boolean asBool(); - + public byte asByte(); - + public short asShort(); - + public int asInt(); - + public long asLong(); - + public float asFloat(); - + public double asDouble(); - + public String asString(); - + public T as(Class cls); - + public boolean is(Class cls); - + public boolean canCastImplicit(Class cls); - + public int getNumberType(); - + public Iterator iteratorSingle(); - + public Iterator iteratorMulti(int n); } diff --git a/ZenScript/src/main/java/stanhebben/zenscript/value/IntRange.java b/ZenScript/src/main/java/stanhebben/zenscript/value/IntRange.java index b707e3c..8b87ac2 100644 --- a/ZenScript/src/main/java/stanhebben/zenscript/value/IntRange.java +++ b/ZenScript/src/main/java/stanhebben/zenscript/value/IntRange.java @@ -7,16 +7,16 @@ package stanhebben.zenscript.value; public class IntRange { private final int from; private final int to; - + public IntRange(int from, int to) { this.from = from; this.to = to; } - + public int getFrom() { return from; } - + public int getTo() { return to; }