Increase checkstyle checks. Javadoc all the things.

This commit is contained in:
Mumfrey committed 2017-01-31 19:15:31 +00:00
1 parent 9fd488cd62
commit 791aba7087
89 files changed
+1518 -305

No files matched your search

@@ -55,21 +55,52 @@ public final class Blackboard {
private Blackboard() {}
/**
* Get a value from the blackboard and duck-type it to the specified type
*
* @param key blackboard key
* @return value
* @param <T> duck type
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key) {
return (T)Launch.blackboard.get(key);
}
/**
* Put the specified value onto the blackboard
*
* @param key blackboard key
* @param value new value
*/
public static void put(String key, Object value) {
Launch.blackboard.put(key, value);
}
/**
* Get the value from the blackboard but return <tt>defaultValue</tt> if the
* specified key is not set.
*
* @param key blackboard key
* @param defaultValue value to return if the key is not set or is null
* @return value from blackboard or default value
* @param <T> duck type
*/
@SuppressWarnings("unchecked")
public static <T> T get(String key, T defaultValue) {
Object value = Launch.blackboard.get(key);
return value != null ? (T)value : defaultValue;
}
/**
* Get a string from the blackboard, returns default value if not set or
* null.
*
* @param key blackboard key
* @param defaultValue default value to return if the specified key is not
* set or is null
* @return value from blackboard or default
*/
public static String getString(String key, String defaultValue) {
Object value = Launch.blackboard.get(key);
return value != null ? value.toString() : defaultValue;
@@ -59,7 +59,7 @@ public interface IMixinPlatformAgent {
/**
* Called from <tt>injectIntoClassLoader</tt> in the parent tweaker
*
* @param classLoader
* @param classLoader classLoader to inject into
*/
public abstract void injectIntoClassLoader(LaunchClassLoader classLoader);
@@ -37,7 +37,7 @@ import java.util.jar.Manifest;
* "Main" attribute cache for a URI container, mainly to avoid constantly
* opening jar files just to read odd values out of the manifest.
*/
class MainAttributes {
final class MainAttributes {
private static final Map<URI, MainAttributes> instances = new HashMap<URI, MainAttributes>();
@@ -34,6 +34,7 @@ import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.Blackboard;
import net.minecraft.launchwrapper.ITweaker;
import net.minecraft.launchwrapper.LaunchClassLoader;
/**
@@ -41,7 +42,7 @@ import net.minecraft.launchwrapper.LaunchClassLoader;
*/
public class MixinContainer {
public static final List<String> agentClasses = new ArrayList<String>();
private static final List<String> agentClasses = new ArrayList<String>();
static {
Blackboard.put(Blackboard.Keys.AGENTS, MixinContainer.agentClasses);
@@ -79,6 +80,9 @@ public class MixinContainer {
return this.uri;
}
/**
* Get phase provider names from all agents in this container
*/
public Collection<String> getPhaseProviders() {
List<String> phaseProviders = new ArrayList<String>();
for (IMixinPlatformAgent agent : this.agents) {
@@ -91,7 +95,7 @@ public class MixinContainer {
}
/**
*
* Prepare agents in this container
*/
public void prepare() {
for (IMixinPlatformAgent agent : this.agents) {
@@ -100,6 +104,10 @@ public class MixinContainer {
}
}
/**
* If this container is the primary container, initialise agents in this
* container as primary
*/
public void initPrimaryContainer() {
for (IMixinPlatformAgent agent : this.agents) {
this.logger.debug("Processing launch tasks for {}", agent);
@@ -108,7 +116,9 @@ public class MixinContainer {
}
/**
* @param classLoader
* Notify all agents to inject into classLoader
*
* @param classLoader classLoader to injec
*/
public void injectIntoClassLoader(LaunchClassLoader classLoader) {
for (IMixinPlatformAgent agent : this.agents) {
@@ -117,6 +127,13 @@ public class MixinContainer {
}
}
/**
* Analogue of {@link ITweaker#getLaunchTarget}, queries all agents and
* returns first valid launch target. Returns null if no agents have launch
* target.
*
* @return launch target from agent or null
*/
public String getLaunchTarget() {
for (IMixinPlatformAgent agent : this.agents) {
String launchTarget = agent.getLaunchTarget();
@@ -60,7 +60,8 @@ public abstract class MixinPlatformAgentAbstract implements IMixinPlatformAgent
/**
* Create a new platform agent for the specified URI
*
* @param uri
* @param manager platform manager
* @param uri URI of the resource for this agent
*/
public MixinPlatformAgentAbstract(MixinPlatformManager manager, URI uri) {
this.manager = manager;
@@ -36,6 +36,10 @@ import net.minecraft.launchwrapper.LaunchClassLoader;
*/
public class MixinPlatformAgentDefault extends MixinPlatformAgentAbstract {
/**
* @param manager platform manager
* @param uri URI of the resource for this agent
*/
public MixinPlatformAgentDefault(MixinPlatformManager manager, URI uri) {
super(manager, uri);
}
@@ -88,7 +88,8 @@ public class MixinPlatformAgentFML extends MixinPlatformAgentAbstract {
private Class<?> clCoreModManager;
/**
* @param uri
* @param manager platform manager
* @param uri URI of the resource for this agent
*/
public MixinPlatformAgentFML(MixinPlatformManager manager, URI uri) {
super(manager, uri);
@@ -110,6 +110,9 @@ public class MixinPlatformManager {
this.scanClasspath();
}
/**
* Get the phase provider classes from the primary container
*/
public Collection<String> getPhaseProviderClasses() {
Collection<String> phaseProviders = this.primaryContainer.getPhaseProviders();
if (phaseProviders != null) {
@@ -119,6 +122,13 @@ public class MixinPlatformManager {
return Collections.<String>emptyList();
}
/**
* Add a new URI to this platform and return the new container (or an
* existing container if the URI was previously registered)
*
* @param uri URI to add
* @return container for specified URI
*/
public final MixinContainer addContainer(URI uri) {
MixinContainer existingContainer = this.containers.get(uri);
if (existingContainer != null) {
@@ -135,6 +145,11 @@ public class MixinPlatformManager {
return container;
}
/**
* Prepare all containers in this platform
*
* @param args command-line arguments from tweaker
*/
public final void prepare(List<String> args) {
this.prepared = true;
for (MixinContainer container : this.containers.values()) {
@@ -165,6 +180,12 @@ public class MixinPlatformManager {
}
}
/**
* Initialise the primary container and dispatch injectIntoClassLoader to
* all containers
*
* @param classLoader classloader to inject into
*/
public final void injectIntoClassLoader(LaunchClassLoader classLoader) {
if (this.injected) {
return;
@@ -213,6 +234,10 @@ public class MixinPlatformManager {
}
}
/**
* Queries all containers for launch target, returns null if no containers
* specify a launch target
*/
public String getLaunchTarget() {
for (MixinContainer container : this.containers.values()) {
String mainClass = container.getLaunchTarget();
@@ -79,6 +79,9 @@ public @interface Interface {
this.forceRemap = forceRemap;
}
/**
* Returns whether this remap type should force remapping
*/
public boolean forceRemap() {
return this.forceRemap;
}
@@ -75,7 +75,7 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Environment phase, deliberately not implemented as an enum
*/
public static class Phase {
public static final class Phase {
/**
* Not initialised phase
@@ -132,6 +132,13 @@ public final class MixinEnvironment implements ITokenProvider {
return this.name;
}
/**
* Get a phase by name, returns <tt>null</tt> if no phases exist with
* the specified name
*
* @param name phase name to lookup
* @return phase object or <tt>null</tt> if non existent
*/
public static Phase forName(String name) {
for (Phase phase : Phase.phases) {
if (phase.name.equals(name)) {
@@ -527,8 +534,14 @@ public final class MixinEnvironment implements ITokenProvider {
*/
public static enum CompatibilityLevel {
/**
* Java 6 and above
*/
JAVA_6(6, Opcodes.V1_6, false),
/**
* Java 7 and above
*/
JAVA_7(7, Opcodes.V1_7, false) {
@Override
@@ -538,6 +551,9 @@ public final class MixinEnvironment implements ITokenProvider {
},
/**
* Java 8 and above
*/
JAVA_8(8, Opcodes.V1_8, true) {
@Override
@@ -566,22 +582,46 @@ public final class MixinEnvironment implements ITokenProvider {
this.maxCompatibleLevel = maxCompatibleLevel;
}
/**
* Get whether this compatibility level is supported in the current
* environment
*/
boolean isSupported() {
return true;
}
/**
* Class version expected at this compatibility level
*/
public int classVersion() {
return this.classVersion;
}
/**
* Get whether this environment supports non-abstract methods in
* interfaces, true in Java 1.8 and above
*/
public boolean supportsMethodsInInterfaces() {
return this.supportsMethodsInInterfaces;
}
/**
* Get whether this level is the same or greater than the specified
* level
*
* @param level level to compare to
* @return true if this level is equal or higher the supplied level
*/
public boolean isAtLeast(CompatibilityLevel level) {
return this.ver >= level.ver;
return level == null || this.ver >= level.ver;
}
/**
* Get whether this level can be elevated to the specified level
*
* @param level desired level
* @return true if this level supports elevation
*/
public boolean canElevateTo(CompatibilityLevel level) {
if (level == null || this.maxCompatibleLevel == null) {
return true;
@@ -589,6 +629,12 @@ public final class MixinEnvironment implements ITokenProvider {
return level.ver <= this.maxCompatibleLevel.ver;
}
/**
* True if this level can support the specified level
*
* @param level desired level
* @return true if the other level can be elevated to this level
*/
public boolean canSupport(CompatibilityLevel level) {
if (level == null) {
return true;
@@ -925,7 +971,7 @@ public final class MixinEnvironment implements ITokenProvider {
try {
@SuppressWarnings("unchecked")
Class<? extends IEnvironmentTokenProvider> providerClass =
(Class<? extends IEnvironmentTokenProvider>)Class.forName(providerName, true, Launch.classLoader);
(Class<? extends IEnvironmentTokenProvider>)Class.forName(providerName, true, Launch.classLoader);
IEnvironmentTokenProvider provider = providerClass.newInstance();
this.registerTokenProvider(provider);
} catch (Throwable th) {
@@ -1079,7 +1125,7 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Set the obfuscation context
*
* @param context
* @param context new context
*/
public void setObfuscationContext(String context) {
this.obfuscationContext = context;
@@ -1305,7 +1351,7 @@ public final class MixinEnvironment implements ITokenProvider {
/**
* Internal callback
*
* @param phase
* @param phase phase to go to
*/
static void gotoPhase(Phase phase) {
if (phase == null || phase.ordinal < 0) {
@@ -59,6 +59,11 @@ public final class Mixins {
private Mixins() {}
/**
* Add multiple configurations
*
* @param configFiles config resources to add
*/
public static void addConfigurations(String... configFiles) {
MixinEnvironment fallback = MixinEnvironment.getDefaultEnvironment();
for (String configFile : configFiles) {
@@ -57,6 +57,9 @@ public interface IMixinErrorHandler {
*/
ERROR(Level.FATAL);
/**
* Logging level for the specified error action
*/
public final Level logLevel;
private ErrorAction(Level logLevel) {
@@ -93,10 +93,24 @@ public class AccessorInfo extends SpecialMethodInfo {
this.expectedPrefixes = expectedPrefixes;
}
/**
* Returns true if the supplied prefix string is an allowed prefix for
* this accessor type
*
* @param prefix prefix to check
* @return true if the expected prefix set contains the supplied value
*/
public boolean isExpectedPrefix(String prefix) {
return this.expectedPrefixes.contains(prefix);
}
/**
* Returns all the expected prefixes for this accessor type as a string
* for debugging/error message purposes
*
* @return string representation of expected prefixes for this accessor
* type
*/
public String getExpectedPrefixes() {
return this.expectedPrefixes.toString();
}
@@ -203,11 +217,34 @@ public class AccessorInfo extends SpecialMethodInfo {
return MemberInfo.parse(name, this.mixin).name;
}
/**
* Uses the name of this accessor method and the calculated accessor type to
* try and inflect the name of the target field or method. This allows a
* method named <tt>getFoo</tt> to be inflected to a target named
* <tt>foo</tt> for example.
*/
protected String inflectTarget() {
return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this.mixin,
this.mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE));
}
/**
* Uses the name of an accessor method and the accessor type to try and
* inflect the name of the target field or method. This allows a method
* named <tt>getFoo</tt> to be inflected to a target named <tt>foo</tt> for
* example.
*
* @param accessorName Name of the accessor method
* @param accessorType Type of accessor being processed, this is calculated
* from the method signature (<tt>void</tt> methods being setters,
* methods with return types being getters)
* @param accessorDescription description of the accessor to include in
* error messages
* @param context Mixin context
* @param verbose Emit warnings when accessor prefix doesn't match type
* @return inflected target member name or <tt>null</tt> if name cannot be
* inflected
*/
public static String inflectTarget(String accessorName, AccessorType accessorType, String accessorDescription,
IMixinContext context, boolean verbose) {
Matcher nameMatcher = AccessorInfo.PATTERN_ACCESSOR.matcher(accessorName);
@@ -303,6 +340,7 @@ public class AccessorInfo extends SpecialMethodInfo {
* fields and methods.
*
* @param nodes Node list to search (method/field list)
* @param <TNode> node type
* @return best match
*/
protected <TNode> TNode findTarget(List<TNode> nodes) {
@@ -43,14 +43,32 @@ import java.lang.annotation.RetentionPolicy;
*/
@Retention(RetentionPolicy.RUNTIME)
public @interface At {
/**
* <b>Shift</b> is used to shift resulting opcodes
*/
public enum Shift {
/**
* Do not shift the returned opcodes
*/
NONE,
/**
* Shift the returned opcodes back one instruction
*/
BEFORE,
/**
* Shift the returned opcodes forward one instruction
*/
AFTER,
/**
* Shift the returned opcodes by the amount specified in {@link At#by}
*/
BY
}
/**
@@ -110,7 +128,7 @@ public @interface At {
/**
* <p>The <b>named arguments</b> list is used to expand the scope of the
* annotation beyond the fixed values below in order to accommodate the
* needs of custom injection point classes.
* needs of custom injection point classes.</p>
*
* @return Named arguments for the injection point
*/
@@ -143,6 +143,7 @@ public class InjectionNodes extends ArrayList<InjectionNodes.InjectionNode> {
*
* @param key meta key
* @param value meta value
* @param <V> value type
*/
public <V> InjectionNode decorate(String key, V value) {
if (this.decorations == null) {
@@ -158,7 +159,7 @@ public class InjectionNodes extends ArrayList<InjectionNodes.InjectionNode> {
* @param key meta key
* @return true if the specified decoration exists
*/
public <K> boolean hasDecoration(K key) {
public boolean hasDecoration(String key) {
return this.decorations != null && this.decorations.get(key) != null;
}
@@ -167,6 +168,7 @@ public class InjectionNodes extends ArrayList<InjectionNodes.InjectionNode> {
*
* @param key meta key
* @return decoration value or null if absent
* @param <V> value type
*/
@SuppressWarnings("unchecked")
public <V> V getDecoration(String key) {
@@ -186,7 +188,7 @@ public class InjectionNodes extends ArrayList<InjectionNodes.InjectionNode> {
*/
@Override
public String toString() {
return String.format("InjectionNode[%s]", ASMHelper.getNodeDescriptionForDebug(this.currentTarget).replaceAll("\\s+", " "));
return String.format("InjectionNode[%s]", ASMHelper.describeNode(this.currentTarget).replaceAll("\\s+", " "));
}
}
@@ -600,6 +600,12 @@ public abstract class InjectionPoint {
return point;
}
/**
* Register an injection point class. The supplied class must be decorated
* with an {@link AtCode} annotation for registration purposes.
*
* @param type injection point type to register
*/
public static void register(Class<? extends InjectionPoint> type) {
AtCode code = type.<AtCode>getAnnotation(AtCode.class);
if (code == null) {
@@ -110,6 +110,14 @@ public class CallbackInfo implements Cancellable {
return CallbackInfo.class.getName();
}
/**
* Gets the {@link CallbackInfo} class name to use for the specified return
* type. Currently returns {@link CallbackInfo} for void types and
* {@link CallbackInfoReturnable} for non-void types.
*
* @param returnType return type of the target method
* @return CallbackInfo class name to use
*/
public static String getCallInfoClassName(Type returnType) {
return (returnType.equals(Type.VOID_TYPE) ? CallbackInfo.class.getName() : CallbackInfoReturnable.class.getName()).replace('.', '/');
}
@@ -31,6 +31,14 @@ import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
*/
public interface ISliceContext extends IInjectionPointContext {
/**
* Fetch slice with the specified id from this context, the slice id may be
* transformed internally by the context according to restrictions on the
* injector itself
*
* @param id slice id to fetch
* @return method slice matching query
*/
public abstract MethodSlice getSlice(String id);
}
@@ -159,6 +159,12 @@ public abstract class Injector {
myNodes.add(target.injectionNodes.add(node));
}
/**
* Performs the injection on the specified target
*
* @param target target to inject into
* @param nodes selected nodes
*/
public final void inject(Target target, List<InjectionNode> nodes) {
for (InjectionNode node : nodes) {
if (node.isRemoved()) {
@@ -270,10 +276,26 @@ public abstract class Injector {
return "(" + Joiner.on("").join(args) + ")";
}
/**
* Returns whether the <tt>from</tt> type can be coerced to the <tt>to</tt>
* type.
*
* @param from type to coerce from
* @param to type to coerce to
* @return true if <tt>from</tt> can be coerced to <tt>to</tt>
*/
public static boolean canCoerce(Type from, Type to) {
return Injector.canCoerce(from.getDescriptor(), to.getDescriptor());
}
/**
* Returns whether the <tt>from</tt> type can be coerced to the <tt>to</tt>
* type.
*
* @param from type to coerce from
* @param to type to coerce to
* @return true if <tt>from</tt> can be coerced to <tt>to</tt>
*/
public static boolean canCoerce(String from, String to) {
if (from.length() > 1 || to.length() > 1) {
return false;
@@ -282,6 +304,14 @@ public abstract class Injector {
return Injector.canCoerce(from.charAt(0), to.charAt(0));
}
/**
* Returns whether the <tt>from</tt> type can be coerced to the <tt>to</tt>
* type.
*
* @param from type to coerce from
* @param to type to coerce to
* @return true if <tt>from</tt> can be coerced to <tt>to</tt>
*/
public static boolean canCoerce(char from, char to) {
return to == 'I' && "IBSCZ".indexOf(from) > -1;
}
@@ -101,15 +101,18 @@ public class InjectorTarget {
}
/**
* Get the slice instructions for the specified
* Get the slice instructions for the specified injection point
*
* @param injectionPoint
* @param injectionPoint injection point to fetch slice for
* @return slice
*/
public InsnList getSlice(InjectionPoint injectionPoint) {
return this.getSlice(injectionPoint.getSlice());
}
/**
* Dispose all cached instruction lists
*/
public void dispose() {
for (ReadOnlyInsnList insns : this.cache.values()) {
insns.dispose();
@@ -46,7 +46,7 @@ import com.google.common.base.Strings;
/**
* Stores information about a defined method slice for a particular injector.
*/
public class MethodSlice {
public final class MethodSlice {
/**
* A read-only wrapper for an {@link InsnList} which only allows the segment
@@ -39,7 +39,7 @@ import org.spongepowered.asm.util.ASMHelper;
* be different to declared slice ids because they are mapped by the underlying
* injector. Some injectors only support a single slice.
*/
public class MethodSlices {
public final class MethodSlices {
/**
* Injector which owns this collection of slices
@@ -63,7 +63,7 @@ public class MethodSlices {
/**
* Add a slice to this collection
*
* @param slice
* @param slice slice to add
*/
private void add(MethodSlice slice) {
String id = this.info.getSliceId(slice.getId());
@@ -266,7 +266,7 @@ public class RedirectInjector extends InvokeInjector {
ConstructorRedirectData meta = node.<ConstructorRedirectData>getDecoration(ConstructorRedirectData.KEY);
boolean wildcard = node.<Boolean>getDecoration(RedirectInjector.KEY_WILD).booleanValue();
if (wildcard && meta.injected == 0) {
throw new InvalidInjectionException(this.info, this.annotationType + " ctor invocation was not found in " + target);
throw new InvalidInjectionException(this.info, this.annotationType + " ctor invocation was not found in " + target);
}
}
}
@@ -317,7 +317,6 @@ public class RedirectInjector extends InvokeInjector {
private void injectAtFieldAccess(Target target, InjectionNode node) {
final FieldInsnNode fieldNode = (FieldInsnNode)node.getCurrentTarget();
final int opCode = fieldNode.getOpcode();
final boolean staticField = opCode == Opcodes.GETSTATIC || opCode == Opcodes.PUTSTATIC;
final Type ownerType = Type.getType("L" + fieldNode.owner + ";");
final Type fieldType = Type.getType(fieldNode.desc);
@@ -330,7 +329,7 @@ public class RedirectInjector extends InvokeInjector {
int fuzz = node.<Integer>getDecoration(RedirectInjector.KEY_FUZZ).intValue();
this.injectAtArrayField(target, fieldNode, opCode, ownerType, fieldType, fuzz);
} else {
this.injectAtScalarField(target, fieldNode, opCode, staticField, ownerType, fieldType);
this.injectAtScalarField(target, fieldNode, opCode, ownerType, fieldType);
}
}
@@ -373,6 +372,12 @@ public class RedirectInjector extends InvokeInjector {
* regardless of whether it's a read or write because it just depends on the
* actual handler signature, the correct arguments are already on the stack
* thanks to the nature of xALOAD and xASTORE.
*
* @param target target method
* @param fieldNode field node
* @param varNode array access node
* @param withArgs true if the descriptor includes captured arguments from
* the target method signature
*/
public void injectArrayRedirect(Target target, FieldInsnNode fieldNode, AbstractInsnNode varNode, boolean withArgs) {
if (!this.isStatic) {
@@ -390,14 +395,20 @@ public class RedirectInjector extends InvokeInjector {
/**
* Redirect a field get or set
*
* @param target target method
* @param fieldNode field access node
* @param opCode field access type
* @param ownerType type of the field owner
* @param fieldType field type
*/
public void injectAtScalarField(Target target, final FieldInsnNode fieldNode, int opCode, boolean staticField, Type ownerType, Type fieldType) {
public void injectAtScalarField(Target target, final FieldInsnNode fieldNode, int opCode, Type ownerType, Type fieldType) {
AbstractInsnNode invoke = null;
InsnList insns = new InsnList();
if (opCode == Opcodes.GETSTATIC || opCode == Opcodes.GETFIELD) {
invoke = this.injectAtGetField(insns, target, fieldNode, staticField, ownerType, fieldType);
invoke = this.injectAtGetField(insns, target, fieldNode, opCode == Opcodes.GETSTATIC, ownerType, fieldType);
} else if (opCode == Opcodes.PUTSTATIC || opCode == Opcodes.PUTFIELD) {
invoke = this.injectAtPutField(insns, target, fieldNode, staticField, ownerType, fieldType);
invoke = this.injectAtPutField(insns, target, fieldNode, opCode == Opcodes.PUTSTATIC, ownerType, fieldType);
} else {
throw new InvalidInjectionException(this.info, "Unspported opcode " + ASMHelper.getOpcodeName(opCode) + " for " + this.info);
}
@@ -466,6 +477,12 @@ public class RedirectInjector extends InvokeInjector {
/**
* Check that the handler descriptor matches the calculated descriptor for
* the access being redirected.
*
* @param desc computed descriptor
* @param target target method
* @param type redirector type in human-readable text, for error messages
* @return true if the descriptor was found and includes target method args,
* false if the descriptor was found and does not capture target args
*/
protected boolean checkDescriptor(String desc, Target target, String type) {
if (this.methodNode.desc.equals(desc)) {
@@ -176,8 +176,8 @@ public class BeforeLoadLocal extends ContextualInjectionPoint {
protected BeforeLoadLocal(InjectionPointData data,
int opcode, boolean opcodeAfter) {
super(data.getMixin());
this.returnType = data.getReturnType();
super(data.getContext());
this.returnType = data.getMethodReturnType();
this.discriminator = data.getLocalVariableDiscriminator();
this.opcode = data.getOpcode(this.returnType.getOpcode(opcode));
this.ordinal = data.getOrdinal();
@@ -210,7 +210,7 @@ public class LocalVariableDiscriminator {
private final Set<String> names;
/**
* @param argsOnly
* @param argsOnly true to only search within the method arguments
* @param ordinal target variable ordinal
* @param index target variable index
* @param names target variable names
@@ -271,6 +271,15 @@ public class LocalVariableDiscriminator {
return this.ordinal < 0 && this.index < context.baseArgIndex && this.names.isEmpty();
}
/**
* Find a matching local variable in the specified target
*
* @param returnType variable tyoe
* @param argsOnly only match in the method args
* @param target target method
* @param node current instruction
* @return index of local or -1 if not matched
*/
public int findLocal(Type returnType, boolean argsOnly, Target target, AbstractInsnNode node) {
try {
return this.findLocal(new Context(returnType, argsOnly, target, node));
@@ -279,6 +288,12 @@ public class LocalVariableDiscriminator {
}
}
/**
* Find a local variable for the specified context
*
* @param context search context
* @return index of local or -1 if not found
*/
public int findLocal(Context context) {
if (this.isImplicit(context)) {
return this.findImplicitLocal(context);
@@ -286,6 +301,14 @@ public class LocalVariableDiscriminator {
return this.findExplicitLocal(context);
}
/**
* Find an implicit local, this means that we expect exactly 1 variable with
* the specified type in scope, if more than one is found then we throw an
* {@link InvalidImplicitDiscriminatorException}
*
* @param context search context
* @return local variable index
*/
private int findImplicitLocal(final Context context) {
int found = 0;
int count = 0;
@@ -305,6 +328,13 @@ public class LocalVariableDiscriminator {
throw new InvalidImplicitDiscriminatorException("Found " + count + " candidate variables but exactly 1 is required.");
}
/**
* Find an explicit local variable in the local variable table. Returns -1
* if no variables match the discriminator
*
* @param context search context
* @return variable index or -1 if not found
*/
private int findExplicitLocal(final Context context) {
for (int index = context.baseArgIndex; index < context.locals.length; index++) {
Local local = context.locals[index];
@@ -331,6 +361,12 @@ public class LocalVariableDiscriminator {
return -1;
}
/**
* Parse a local variable discriminator from the supplied annotation
*
* @param annotation annotation to parse
* @return discriminator configured using values from the annoation
*/
public static LocalVariableDiscriminator parse(AnnotationNode annotation) {
boolean argsOnly = ASMHelper.<Boolean>getAnnotationValue(annotation, "argsOnly", Boolean.FALSE).booleanValue();
int ordinal = ASMHelper.<Integer>getAnnotationValue(annotation, "ordinal", -1);
@@ -73,15 +73,15 @@ public class ModifyVariableInjector extends Injector {
*/
abstract static class ContextualInjectionPoint extends InjectionPoint {
protected final IMixinContext mixin;
protected final IMixinContext context;
ContextualInjectionPoint(IMixinContext mixin) {
this.mixin = mixin;
ContextualInjectionPoint(IMixinContext context) {
this.context = context;
}
@Override
public boolean find(String desc, InsnList insns, Collection<AbstractInsnNode> nodes) {
throw new InvalidInjectionException(this.mixin, "STORE injection point must be used in conjunction with @ModifyVariable");
throw new InvalidInjectionException(this.context, "STORE injection point must be used in conjunction with @ModifyVariable");
}
abstract boolean find(Target target, Collection<AbstractInsnNode> nodes);
@@ -100,7 +100,8 @@ public class ModifyVariableInjector extends Injector {
/**
* @param info Injection info
* @param print
* @param print True to print this injector's discovered LVT
* @param discriminator discriminator
*/
public ModifyVariableInjector(InjectionInfo info, boolean print, LocalVariableDiscriminator discriminator) {
super(info);
@@ -65,7 +65,7 @@ import org.spongepowered.asm.util.ASMHelper;
* </pre>
* </blockquote>
*
* <p>Matching array access:<p>
* <p>Matching array access:</p>
* <p>For array fields, it is possible to match field accesses followed by a
* corresponding array element <em>get</em> or <em>set</em> operation. To enable
* this behaviour specify the <tt>array</tt> named-argument with the desired
@@ -86,6 +86,9 @@ import org.spongepowered.asm.util.ASMHelper;
@AtCode("FIELD")
public class BeforeFieldAccess extends BeforeInvoke {
/**
* Default fuzz factor for searching for array access opcodes
*/
public static final int ARRAY_SEARCH_FUZZ_DEFAULT = 8;
/**
@@ -153,6 +156,20 @@ public class BeforeFieldAccess extends BeforeInvoke {
return super.addInsn(insns, nodes, insn);
}
/**
* Searches for an array access instruction in the supplied instruction list
* which is within <tt>searchRange</tt> instructions of the supplied field
* instruction. Searching halts if the search range is exhausted, if an
* {@link Opcodes#ARRAYLENGTH} opcode is encountered immediately after the
* specified access, if a matching field access is found, or if the end of
* the method is reached.
*
* @param insns Instruction list to search
* @param fieldNode Field instruction to search from
* @param opcode array access opcode to search for
* @param searchRange search range
* @return matching opcode or <tt>null</tt> if not matched
*/
public static AbstractInsnNode findArrayNode(InsnList insns, FieldInsnNode fieldNode, int opcode, int searchRange) {
int pos = 0;
for (Iterator<AbstractInsnNode> iter = insns.iterator(insns.indexOf(fieldNode) + 1); iter.hasNext();) {
@@ -58,12 +58,12 @@ import org.spongepowered.asm.mixin.refmap.IMixinContext;
@AtCode("TAIL")
public class BeforeFinalReturn extends InjectionPoint {
private final IMixinContext mixin;
private final IMixinContext context;
public BeforeFinalReturn(InjectionPointData data) {
super(data);
this.mixin = data.getMixin();
this.context = data.getContext();
}
@Override
@@ -83,7 +83,7 @@ public class BeforeFinalReturn extends InjectionPoint {
// WAT?
if (ret == null) {
throw new InvalidInjectionException(this.mixin, "TAIL could not locate a valid RETURN in the target method!");
throw new InvalidInjectionException(this.context, "TAIL could not locate a valid RETURN in the target method!");
}
nodes.add(ret);
@@ -102,6 +102,12 @@ public class BeforeInvoke extends InjectionPoint {
return String.format("@At(%s)", atCode != null ? atCode.value() : this.getClass().getSimpleName().toUpperCase());
}
/**
* Set the logging state for this injector
*
* @param logging logging state
* @return fluent interface
*/
public BeforeInvoke setLogging(boolean logging) {
this.log = logging;
return this;
@@ -108,11 +108,14 @@ public class BeforeNew extends InjectionPoint {
this.ordinal = data.getOrdinal();
String target = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/'));
MemberInfo member = MemberInfo.parseAndValidate(target, data.getMixin());
MemberInfo member = MemberInfo.parseAndValidate(target, data.getContext());
this.target = member.toCtorType();
this.desc = member.toCtorDesc();
}
/**
* Returns whether this injection point has a constructor descriptor defined
*/
public boolean hasDescriptor() {
return this.desc != null;
}
@@ -261,6 +261,12 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
}
/**
* Callback from injector which notifies us that a callback was injected. No
* longer used.
*
* @param target target into which the injector injected
*/
public void notifyInjected(Target target) {
// this.targets.remove(target.method);
}
@@ -297,7 +303,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
* support use of a single slice will always return the default id (an empty
* string)
*
* @param id
* @param id slice id
* @return mapped id
*/
public String getSliceId(String id) {
@@ -386,6 +392,15 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
}
/**
* Parse an injector from the specified method (if an injector annotation is
* present). If no injector annotation is present then <tt>null</tt> is
* returned.
*
* @param mixin context
* @param method mixin method
* @return parsed InjectionInfo or null
*/
public static InjectionInfo parse(MixinTargetContext mixin, MethodNode method) {
AnnotationNode annotation = InjectionInfo.getInjectorAnnotation(mixin.getMixin(), method);
@@ -408,6 +423,15 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
return null;
}
/**
* Returns any injector annotation found on the specified method. If
* multiple matching annotations are found then an exception is thrown. If
* no annotations are present then <tt>null</tt> is returned.
*
* @param mixin context
* @param method mixin method
* @return annotation or null
*/
@SuppressWarnings("unchecked")
public static AnnotationNode getInjectorAnnotation(IMixinInfo mixin, MethodNode method) {
AnnotationNode annotation = null;
@@ -426,6 +450,12 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
return annotation;
}
/**
* Get the conform prefix for an injector handler by type
*
* @param annotation Annotation to inspect
* @return conform prefix
*/
public static String getInjectorPrefix(AnnotationNode annotation) {
if (annotation != null) {
if (annotation.desc.endsWith(ModifyArg.class.getSimpleName() + ";")) {
@@ -34,6 +34,7 @@ import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector;
import org.spongepowered.asm.mixin.injection.modify.LocalVariableDiscriminator;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException;
@@ -61,7 +62,7 @@ public class InjectionPointData {
/**
* Mixin
*/
private final IMixinContext mixin;
private final IMixinContext context;
/**
* Injector callback
@@ -108,9 +109,9 @@ public class InjectionPointData {
*/
private final int opcode;
public InjectionPointData(IMixinContext mixin, MethodNode method, AnnotationNode parent, String at, List<String> args, String target,
public InjectionPointData(IMixinContext context, MethodNode method, AnnotationNode parent, String at, List<String> args, String target,
String slice, int ordinal, int opcode) {
this.mixin = mixin;
this.context = context;
this.method = method;
this.parent = parent;
this.at = at;
@@ -146,101 +147,165 @@ public class InjectionPointData {
}
}
/**
* Get the <tt>at</tt> value on the injector
*/
public String getAt() {
return this.at;
}
/**
* Get the parsed constructor <tt>type</tt> for this injector
*/
public String getType() {
return this.type;
}
/**
* Get the selector value parsed from the injector
*/
public Selector getSelector() {
return this.selector;
}
public IMixinContext getMixin() {
return this.mixin;
/**
* Get the context
*/
public IMixinContext getContext() {
return this.context;
}
/**
* Get the annotated method
*/
public MethodNode getMethod() {
return this.method;
}
/**
* Get the return type of the annotated method
*/
public Type getMethodReturnType() {
return Type.getReturnType(this.method.desc);
}
/**
* Get the root annotation (eg. {@link Inject})
*/
public AnnotationNode getParent() {
return this.parent;
}
/**
* Get the slice id specified on the injector
*/
public String getSlice() {
return this.slice;
}
public Type getReturnType() {
return Type.getReturnType(this.method.desc);
}
public LocalVariableDiscriminator getLocalVariableDiscriminator() {
return LocalVariableDiscriminator.parse(this.parent);
}
/**
* Get the supplied value from the named args, return defaultValue if the
* arg is not set
*
* @param key argument name
* @param defaultValue value to return if the arg is not set
* @return argument value or default if not set
*/
public String get(String key, String defaultValue) {
String value = this.args.get(key);
return value != null ? value : defaultValue;
}
/**
* Get the supplied value from the named args, return defaultValue if the
* arg is not set
*
* @param key argument name
* @param defaultValue value to return if the arg is not set
* @return argument value or default if not set
*/
public int get(String key, int defaultValue) {
return this.parseInt(this.get(key, String.valueOf(defaultValue)), defaultValue);
return InjectionPointData.parseInt(this.get(key, String.valueOf(defaultValue)), defaultValue);
}
/**
* Get the supplied value from the named args, return defaultValue if the
* arg is not set
*
* @param key argument name
* @param defaultValue value to return if the arg is not set
* @return argument value or default if not set
*/
public boolean get(String key, boolean defaultValue) {
return this.parseBoolean(this.get(key, String.valueOf(defaultValue)), defaultValue);
return InjectionPointData.parseBoolean(this.get(key, String.valueOf(defaultValue)), defaultValue);
}
/**
* Get the supplied value from the named args as a {@link MemberInfo},
* throws an exception if the argument cannot be parsed as a MemberInfo.
*
* @param key argument name
* @return argument value as a MemberInfo
*/
public MemberInfo get(String key) {
try {
return MemberInfo.parseAndValidate(this.get(key, ""), this.mixin);
return MemberInfo.parseAndValidate(this.get(key, ""), this.context);
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionPointException(this.mixin, "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s",
this.at, key, this.target, InjectionInfo.describeInjector(this.mixin, this.parent, this.method));
}
}
private int parseInt(String string, int defaultValue) {
try {
return Integer.parseInt(string);
} catch (Exception ex) {
return defaultValue;
}
}
private boolean parseBoolean(String string, boolean defaultValue) {
try {
return Boolean.parseBoolean(string);
} catch (Exception ex) {
return defaultValue;
throw new InvalidInjectionPointException(this.context, "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s",
this.at, key, this.target, InjectionInfo.describeInjector(this.context, this.parent, this.method));
}
}
/**
* Get the target value specified on the injector
*/
public MemberInfo getTarget() {
try {
return MemberInfo.parseAndValidate(this.target, this.mixin);
return MemberInfo.parseAndValidate(this.target, this.context);
} catch (InvalidMemberDescriptorException ex) {
throw new InvalidInjectionPointException(this.mixin, "Failed parsing @At(\"%s\") descriptor \"%s\" on %s",
this.at, this.target, InjectionInfo.describeInjector(this.mixin, this.parent, this.method));
throw new InvalidInjectionPointException(this.context, "Failed parsing @At(\"%s\") descriptor \"%s\" on %s",
this.at, this.target, InjectionInfo.describeInjector(this.context, this.parent, this.method));
}
}
/**
* Get the ordinal specified on the injection point
*/
public int getOrdinal() {
return this.ordinal;
}
/**
* Get the opcode specified on the injection point
*/
public int getOpcode() {
return this.opcode;
}
/**
* Get the opcode specified on the injection point or return the default if
* no opcode was specified
*
* @param defaultOpcode opcode to return if none specified
* @return opcode or default
*/
public int getOpcode(int defaultOpcode) {
return this.opcode > 0 ? this.opcode : defaultOpcode;
}
/**
* Get the opcode specified on the injection point or return the default if
* no opcode was specified or if the specified opcode does not appear in the
* supplied list of valid opcodes
*
* @param defaultOpcode opcode to return if none specified
* @param validOpcodes valid opcodes
* @return opcode or default
*/
public int getOpcode(int defaultOpcode, int... validOpcodes) {
for (int validOpcode : validOpcodes) {
if (this.opcode == validOpcode) {
@@ -259,6 +324,17 @@ public class InjectionPointData {
return Pattern.compile(String.format("^([^:]+):?(%s)?$", Joiner.on('|').join(Selector.values())));
}
/**
* Parse a constructor type from the supplied <tt>at</tt> string
*
* @param at at to parse
* @return parsed constructor type
*/
public static String parseType(String at) {
Matcher matcher = InjectionPointData.AT_PATTERN.matcher(at);
return InjectionPointData.parseType(matcher, at);
}
private static String parseType(Matcher matcher, String at) {
return matcher.matches() ? matcher.group(1) : at;
}
@@ -266,10 +342,21 @@ public class InjectionPointData {
private static Selector parseSelector(Matcher matcher) {
return matcher.matches() && matcher.group(2) != null ? Selector.valueOf(matcher.group(2)) : Selector.DEFAULT;
}
public static String parseType(String at) {
Matcher matcher = InjectionPointData.AT_PATTERN.matcher(at);
return InjectionPointData.parseType(matcher, at);
private static int parseInt(String string, int defaultValue) {
try {
return Integer.parseInt(string);
} catch (Exception ex) {
return defaultValue;
}
}
private static boolean parseBoolean(String string, boolean defaultValue) {
try {
return Boolean.parseBoolean(string);
} catch (Exception ex) {
return defaultValue;
}
}
}
@@ -282,6 +282,9 @@ public class MemberInfo {
return this.owner + "/" + this.name;
}
/**
* Returns this MemberInfo as a java-style descriptor
*/
public String toDescriptor() {
if (this.desc == null) {
return "";
@@ -290,6 +293,9 @@ public class MemberInfo {
return new SignaturePrinter(this).setFullyQualified(true).toDescriptor();
}
/**
* Returns the <em>constructor type</em> represented by this MemberInfo
*/
public String toCtorType() {
if (this.unparsed == null) {
return null;
@@ -311,6 +317,10 @@ public class MemberInfo {
return this.desc != null ? this.desc : this.unparsed;
}
/**
* Returns the <em>constructor descriptor</em> represented by this
* MemberInfo, returns null if no descriptor is present.
*/
public String toCtorDesc() {
if (this.desc != null && this.desc.startsWith("(") && this.desc.indexOf(')') > -1) {
return this.desc.substring(0, this.desc.indexOf(')') + 1) + "V";
@@ -319,6 +329,11 @@ public class MemberInfo {
return null;
}
/**
* Get the return type for this MemberInfo, if the decriptor is present,
* returns null if the descriptor is absent or if this MemberInfo represents
* a field
*/
public String getReturnType() {
if (this.desc == null || this.desc.indexOf(')') == -1 || this.desc.indexOf('(') != 0 ) {
return null;
@@ -331,10 +346,17 @@ public class MemberInfo {
return returnType;
}
/**
* Returns this MemberInfo as a {@link MappingField} or
* {@link MappingMethod}
*/
public IMapping<?> asMapping() {
return this.isField() ? this.asFieldMapping() : this.asMethodMapping();
}
/**
* Returns this MemberInfo as a mapping method
*/
public MappingMethod asMethodMapping() {
if (!this.isFullyQualified()) {
throw new MixinException("Cannot convert unqualified reference " + this + " to MethodMapping");
@@ -347,6 +369,9 @@ public class MemberInfo {
return new MappingMethod(this.owner, this.name, this.desc);
}
/**
* Returns this MemberInfo as a mapping field
*/
public MappingField asFieldMapping() {
if (!this.isField()) {
throw new MixinException("Cannot convert non-field reference " + this + " to FieldMapping");
@@ -620,12 +645,14 @@ public class MemberInfo {
return new MemberInfo(name, owner, desc, matchAll, input);
}
/**
* Return the supplied mapping parsed as a MemberInfo
*
* @param mapping mapping to parse
* @return new MemberInfo
*/
public static MemberInfo fromMapping(IMapping<?> mapping) {
return new MemberInfo(mapping);
}
public static void main(String[] args) {
MemberInfo m = MemberInfo.parseAndValidate(null); //"(Lfoo;III)Lfoo/bar/qcv;");
System.err.printf(">> [%s] [%s]\n", m.toCtorType(), m.toCtorDesc());
}
}
@@ -104,7 +104,7 @@ public class ModifyConstantInjectionInfo extends InjectionInfo {
if (this.log) {
BeforeConstant.logger.info("BeforeConstant is searching for an constants in method with descriptor {}", desc);
}
}
ListIterator<AbstractInsnNode> iter = insns.iterator();
for (int ordinal = 0; iter.hasNext();) {
@@ -118,7 +118,7 @@ public class ModifyConstantInjectionInfo extends InjectionInfo {
}
if (this.ordinal == -1 || this.ordinal == ordinal) {
if (this.log) {
BeforeConstant.logger.info(" BeforeConstant found {}", ASMHelper.getNodeDescriptionForDebug(insn).trim());
BeforeConstant.logger.info(" BeforeConstant found {}", ASMHelper.describeNode(insn).trim());
}
nodes.add(insn);
found = true;
@@ -41,6 +41,9 @@ import org.spongepowered.asm.util.ASMHelper;
*/
public class Target implements Comparable<Target>, Iterable<AbstractInsnNode> {
/**
* Target class node
*/
public final ClassNode classNode;
/**
@@ -177,8 +180,7 @@ public class Target implements Comparable<Target>, Iterable<AbstractInsnNode> {
}
/**
* Allocate a number of new stack variables for this method, returns the
* first stack index of the allocated range
* Allocate a number of new local variables for this method
*
* @param locals number of locals to allocate
*/
@@ -186,16 +188,33 @@ public class Target implements Comparable<Target>, Iterable<AbstractInsnNode> {
this.setMaxLocals(this.maxLocals + locals);
}
/**
* Set the maxlocals for this target to the specified value, the specfied
* value must be higher than the original max locals
*
* @param maxLocals max locals value to set
*/
public void setMaxLocals(int maxLocals) {
if (maxLocals > this.method.maxLocals) {
this.method.maxLocals = maxLocals;
}
}
/**
* Allocate a number of new stack variables for this method
*
* @param stack number of stack entries to allocate
*/
public void addToStack(int stack) {
this.setMaxStack(this.maxStack + stack);
}
/**
* Set the max stack size for this target to the specified value, the
* specfied value must be higher than the original max stack
*
* @param maxStack max stack value to set
*/
public void setMaxStack(int maxStack) {
if (maxStack > this.method.maxStack) {
this.method.maxStack = maxStack;
@@ -290,14 +309,29 @@ public class Target implements Comparable<Target>, Iterable<AbstractInsnNode> {
return this.toString().compareTo(o.toString());
}
/**
* Return the index of the specified instruction in this instruction list
*
* @param insn instruction to locate, must exist in the target
* @return opcode index
*/
public int indexOf(AbstractInsnNode insn) {
return this.insns.indexOf(insn);
}
/**
* Return the instruction at the specified index
*
* @param index opcode index
* @return requested instruction
*/
public AbstractInsnNode get(int index) {
return this.insns.get(index);
}
/* (non-Javadoc)
* @see java.lang.Iterable#iterator()
*/
@Override
public Iterator<AbstractInsnNode> iterator() {
return this.insns.iterator();
@@ -337,6 +371,7 @@ public class Target implements Comparable<Target>, Iterable<AbstractInsnNode> {
* @param location Instruction to replace
* @param champion Instruction which notionally replaces the original insn
* @param before Instructions to actually insert (must contain champion)
* @param after Instructions to insert after the specified location
*/
public void wrapNode(AbstractInsnNode location, AbstractInsnNode champion, InsnList before, InsnList after) {
this.insns.insertBefore(location, before);
@@ -53,10 +53,28 @@ public interface IMixinContext {
*/
public abstract ReferenceMapper getReferenceMapper();
/**
* Retrieve the value of the specified <tt>option</tt> from the environment
* this mixin belongs to.
*
* @param option option to check
* @return option value
*/
public abstract boolean getOption(Option option);
/**
* Get the priority of the mixin
*/
public abstract int getPriority();
public abstract Target getTargetMethod(MethodNode into);
/**
* Obtain a {@link Target} method handle for a method in the target, this is
* used by consumers to manipulate the bytecode in a target method in a
* controlled manner.
*
* @param method method node to wrap
* @return target method
*/
public abstract Target getTargetMethod(MethodNode method);
}
@@ -63,7 +63,7 @@ import com.google.common.collect.ImmutableSet;
* information needed to support more complex mixin behaviour such as detached
* superclass and mixin inheritance.
*/
public class ClassInfo extends TreeInfo {
public final class ClassInfo extends TreeInfo {
public static final int INCLUDE_PRIVATE = Opcodes.ACC_PRIVATE;
public static final int INCLUDE_STATIC = Opcodes.ACC_STATIC;
@@ -137,10 +137,16 @@ public class ClassInfo extends TreeInfo {
this.searchType = searchType;
}
/**
* Return the next traversal type for this traversal type
*/
public Traversal next() {
return this.next;
}
/**
* Return whether this traversal type allows traversal
*/
public boolean canTraverse() {
return this.traverse;
}
@@ -158,10 +164,19 @@ public class ClassInfo extends TreeInfo {
private static final String[] FRAMETYPES = { "NEW", "FULL", "APPEND", "CHOP", "SAME", "SAME1" };
/**
* Frame index
*/
public final int index;
/**
* Frame type
*/
public final int type;
/**
* Frame local count
*/
public final int locals;
FrameData(int index, int type, int locals) {
@@ -338,7 +353,7 @@ public class ClassInfo extends TreeInfo {
}
/**
* @param name
* @param name new name
* @return the passed-in argument, for fluency
*/
public String renameTo(String name) {
@@ -964,7 +979,7 @@ public class ClassInfo extends TreeInfo {
*
* @param superClass Name of the superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
* anywhere
*/
public boolean hasSuperClass(String superClass) {
return this.hasSuperClass(superClass, Traversal.NONE);
@@ -976,7 +991,7 @@ public class ClassInfo extends TreeInfo {
* @param superClass Name of the superclass to search for in the hierarchy
* @param traversal Traversal type to allow during this lookup
* @return true if the specified class appears in the class's hierarchy
* anywhere
* anywhere
*/
public boolean hasSuperClass(String superClass, Traversal traversal) {
if (ClassInfo.JAVA_LANG_OBJECT.equals(superClass)) {
@@ -991,7 +1006,7 @@ public class ClassInfo extends TreeInfo {
*
* @param superClass Superclass to search for in the hierarchy
* @return true if the specified class appears in the class's hierarchy
* anywhere
* anywhere
*/
public boolean hasSuperClass(ClassInfo superClass) {
return this.hasSuperClass(superClass, Traversal.NONE);
@@ -1003,7 +1018,7 @@ public class ClassInfo extends TreeInfo {
* @param superClass Superclass to search for in the hierarchy
* @param traversal Traversal type to allow during this lookup
* @return true if the specified class appears in the class's hierarchy
* anywhere
* anywhere
*/
public boolean hasSuperClass(ClassInfo superClass, Traversal traversal) {
if (ClassInfo.OBJECT == superClass) {
@@ -42,7 +42,7 @@ import org.spongepowered.asm.util.ASMHelper;
* Information about an interface being runtime-patched onto a mixin target
* class, see {@link org.spongepowered.asm.mixin.Implements Implements}
*/
public class InterfaceInfo extends TreeInfo {
public final class InterfaceInfo extends TreeInfo {
/**
* Parent mixin
@@ -31,11 +31,10 @@ import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError;
import org.spongepowered.asm.util.ASMHelper;
/**
* Reference to a field or method that also includes invocation
* instructions.
* Reference to a field or method that also includes invocation instructions.
*
* To instances are defined to be equal if they both refer to the same method
* and have the same invocation instructions.
* <p>To instances are defined to be equal if they both refer to the same method
* and have the same invocation instructions.</p>
*/
public abstract class MemberRef {
@@ -74,6 +74,13 @@ public class MethodMapper {
return this.info;
}
/**
* Conforms an injector handler method
*
* @param mixin owner mixin
* @param handler annotated injector handler method
* @param method method in target
*/
public void remapHandlerMethod(MixinInfo mixin, MethodNode handler, Method method) {
if (!(handler instanceof MixinMethodNode) || !((MixinMethodNode)handler).isInjector()) {
return;
@@ -92,6 +99,12 @@ public class MethodMapper {
handler.name = method.renameTo(handlerName);
}
/**
* Get the name for a handler method provided a source mixin method
*
* @param method mixin method
* @return conformed handler name
*/
public String getHandlerName(MixinMethodNode method) {
String prefix = InjectionInfo.getInjectorPrefix(method.getInjectorAnnotation());
String classUID = MethodMapper.getClassUID(method.getOwner().getClassRef());
@@ -310,7 +310,7 @@ class MixinApplicatorStandard {
/**
* Mixin interfaces implemented by the mixin class onto the target class
*
* @param mixin
* @param mixin mixin target context
*/
protected void applyInterfaces(MixinTargetContext mixin) {
for (String interfaceName : mixin.getInterfaces()) {
@@ -324,7 +324,7 @@ class MixinApplicatorStandard {
/**
* Mixin misc attributes from mixin class onto the target class
*
* @param mixin
* @param mixin mixin target context
*/
protected void applyAttributes(MixinTargetContext mixin) {
if (mixin.shouldSetSourceFile()) {
@@ -336,7 +336,7 @@ class MixinApplicatorStandard {
/**
* Mixin class-level annotations on the mixin into the target class
*
* @param mixin
* @param mixin mixin target context
*/
protected void applyAnnotations(MixinTargetContext mixin) {
ClassNode sourceClass = mixin.getClassNode();
@@ -349,7 +349,7 @@ class MixinApplicatorStandard {
* fields so that transformMethod can rename field references in the method
* body.
*
* @param mixin
* @param mixin mixin target context
*/
protected void applyFields(MixinTargetContext mixin) {
this.mergeShadowFields(mixin);
@@ -384,7 +384,7 @@ class MixinApplicatorStandard {
/**
* Mixin methods from the mixin class into the target class
*
* @param mixin
* @param mixin mixin target context
*/
protected void applyMethods(MixinTargetContext mixin) {
for (MethodNode shadow : mixin.getShadowMethods()) {
@@ -413,7 +413,7 @@ class MixinApplicatorStandard {
this.mergeMethod(mixin, mixinMethod);
} else if (Constants.CLINIT.equals(mixinMethod.name)) {
// Class initialiser insns get appended
this.appendInsns(mixinMethod);
this.appendInsns(mixin, mixinMethod);
}
}
@@ -576,9 +576,10 @@ class MixinApplicatorStandard {
* Handles appending instructions from the source method to the target
* method. Both methods must return void
*
* @param method
* @param mixin mixin target context
* @param method source method
*/
protected final void appendInsns(MethodNode method) {
protected final void appendInsns(MixinTargetContext mixin, MethodNode method) {
if (Type.getReturnType(method.desc) != Type.VOID_TYPE) {
throw new IllegalArgumentException("Attempted to merge insns from a method which does not return void");
}
@@ -611,7 +612,7 @@ class MixinApplicatorStandard {
* (Attempts to) find and patch field initialisers from the mixin into the
* target class
*
* @param mixin
* @param mixin mixin target context
*/
protected void applyInitialisers(MixinTargetContext mixin) {
// Try to find a suitable constructor, we need a constructor with line numbers in order to extract the initialiser
@@ -662,7 +663,7 @@ class MixinApplicatorStandard {
* Identifies line numbers in the supplied ctor which correspond to the
* start and end of the method body.
*
* @param ctor
* @param ctor constructor to scan
* @return range indicating the line numbers of the specified constructor
* and the position of the superclass ctor invocation
*/
@@ -706,14 +707,16 @@ class MixinApplicatorStandard {
* Get insns corresponding to the instance initialiser (hopefully) from the
* supplied constructor.
*
* TODO Potentially rewrite this to be less horrible.
*
* @param mixin
* @param ctor
* @param mixin mixin target context
* @param ctor constructor to inspect
* @return initialiser bytecode extracted from the supplied constructor, or
* null if the constructor range could not be parsed
*/
protected final Deque<AbstractInsnNode> getInitialiser(MixinTargetContext mixin, MethodNode ctor) {
//
// TODO Potentially rewrite this to be less horrible.
//
// Find the range of line numbers which corresponds to the constructor body
Range init = this.getConstructorRange(ctor);
if (!init.isValid()) {
@@ -781,8 +784,9 @@ class MixinApplicatorStandard {
/**
* Inject initialiser code into the target constructor
*
* @param ctor
* @param initialiser
* @param mixin mixin target context
* @param ctor target constructor
* @param initialiser initialiser instructions
*/
protected final void injectInitialiser(MixinTargetContext mixin, MethodNode ctor, Deque<AbstractInsnNode> initialiser) {
Map<LabelNode, LabelNode> labels = ASMHelper.cloneLabels(ctor.instructions);
@@ -901,8 +905,8 @@ class MixinApplicatorStandard {
/**
* Check visibility before merging a mixin method
*
* @param mixin
* @param mixinMethod
* @param mixin mixin target context
* @param mixinMethod method to check
*/
protected void checkMethodVisibility(MixinTargetContext mixin, MethodNode mixinMethod) {
if (ASMHelper.hasFlag(mixinMethod, Opcodes.ACC_STATIC)
@@ -62,7 +62,7 @@ import net.minecraft.launchwrapper.Launch;
/**
* Mixin configuration bundle
*/
class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
final class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
/**
* Wrapper for injection options
@@ -738,7 +738,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Check whether this configuration bundle has a mixin for the specified
* class
*
* @param targetClass
* @param targetClass target class
* @return true if this bundle contains any mixins for the specified target
*/
public boolean hasMixinsFor(String targetClass) {
@@ -748,7 +748,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
/**
* Get mixins for the specified target class
*
* @param targetClass
* @param targetClass target class
* @return mixins for the specified target
*/
public List<MixinInfo> getMixinsFor(String targetClass) {
@@ -805,7 +805,7 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
* Factory method, creates a new mixin configuration bundle from the
* specified configFile, which must be accessible on the classpath
*
* @param configFile
* @param configFile configuration file to load
* @param outer fallback environment
* @return new Config
*/
@@ -479,7 +479,8 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* True if this mixin class can actually be classloaded
*
* @return
* @return whether this subtype is directly classloadable (supports
* classloader pinholing)
*/
boolean isLoadable() {
return false;
@@ -488,8 +489,8 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Validate a single target before adding
*
* @param targetName
* @param targetInfo
* @param targetName target class name
* @param targetInfo information about the target class
*/
void validateTarget(String targetName, ClassInfo targetInfo) {
boolean targetIsInterface = targetInfo.isInterface();
@@ -740,11 +741,13 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Internal ctor, called by {@link MixinConfig}
*
* @param parent
* @param mixinName
* @param runTransformers
* @param plugin
* @param suppressPlugin
* @param parent configuration which owns this mixin, the parent
* @param mixinName name of this mixin (class name stub)
* @param runTransformers true if this mixin should run transformers on its
* bytecode when loading
* @param plugin mixin config companion plugin, may be null
* @param suppressPlugin true to suppress the plugin from filtering targets
* of this mixin
*/
MixinInfo(MixinConfig parent, String mixinName, boolean runTransformers, IMixinConfigPlugin plugin, boolean suppressPlugin) {
this.parent = parent;
@@ -805,8 +808,8 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Read the target class names from the {@link Mixin} annotation
*
* @param classNode
* @param suppressPlugin
* @param classNode mixin classnode
* @param suppressPlugin true to suppress plugin filtering targets
* @return target class list read from classNode
*/
protected List<ClassInfo> readTargetClasses(MixinClassNode classNode, boolean suppressPlugin) {
@@ -896,7 +899,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Read the priority from the {@link Mixin} annotation
*
* @param classNode
* @param classNode mixin classnode
* @return priority read from classNode
*/
protected int readPriority(ClassNode classNode) {
@@ -1092,7 +1095,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Get a new mixin target context object for the specified target
*
* @param target
* @param target target class context
* @return new context
*/
MixinTargetContext createContextFor(TargetClassContext target) {
@@ -1101,10 +1104,12 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
}
/**
* @param mixinClassName
* @param runTransformers
* @return
* @throws ClassNotFoundException
* Load the mixin class bytes
*
* @param mixinClassName mixin class name
* @param runTransformers true to run transformers on the loaded bytecode
* @return mixin bytecode
* @throws ClassNotFoundException if the mixin bytes could not be found
*/
private byte[] loadMixinClass(String mixinClassName, boolean runTransformers) throws ClassNotFoundException {
byte[] mixinBytes = null;
@@ -188,7 +188,7 @@ class MixinPreProcessorStandard {
/**
* Run the second pass, attach to the specified context
*
* @param context
* @param context mixin target context
*/
MixinPreProcessorStandard attach(MixinTargetContext context) {
if (this.attached) {
@@ -474,8 +474,8 @@ class MixinPreProcessorStandard {
boolean isFinal = field.isDecoratedFinal();
if (this.verboseLogging && ASMHelper.hasFlag(target, Opcodes.ACC_FINAL) != isFinal) {
String message = isFinal
? "@Shadow field {}::{} is decorated with @Final but target is not final"
: "@Shadow target {}::{} is final but shadow is not decorated with @Final";
? "@Shadow field {}::{} is decorated with @Final but target is not final"
: "@Shadow target {}::{} is final but shadow is not decorated with @Final";
MixinPreProcessorStandard.logger.warn(message, this.mixin, mixinField.name);
}
@@ -180,21 +180,29 @@ public class MixinTargetContext implements IMixinContext {
}
/**
* @param method
* Add a shadow method to this mixin context, called by the preprocessor
*
* @param method shadow method to add
*/
void addShadowMethod(MethodNode method) {
this.shadowMethods.add(method);
}
/**
* @param fieldNode
* Add a shadow field to this mixin context, called by the preprocessor
*
* @param fieldNode field node
* @param fieldInfo field info
*/
void addShadowField(FieldNode fieldNode, Field fieldInfo) {
this.shadowFields.put(fieldNode, fieldInfo);
}
/**
* @param method
* Add an accessor method to this mixin context, called by the preprocessor
*
* @param method method to add
* @param type annotation type
*/
void addAccessorMethod(MethodNode method, Class<? extends Annotation> type) {
this.accessors.add(AccessorInfo.of(this, method, type));
@@ -203,7 +211,7 @@ public class MixinTargetContext implements IMixinContext {
/**
* Callback from the applicator which notifies us that a method was merged
*
* @param method
* @param method merged method
*/
void addMergedMethod(MethodNode method) {
this.mergedMethods.add(method);
@@ -1032,10 +1040,26 @@ public class MixinTargetContext implements IMixinContext {
this.mixin.postApply(transformedName, targetClass);
}
/**
* Obtain a unique name for the specified method from the target class
* context
*
* @param method method to obtain a name for
* @param preservePrefix true to preserve the method prefix (decorate as
* postfix) otherwise decorates as infix
* @return unique method name
*/
public String getUniqueName(MethodNode method, boolean preservePrefix) {
return this.targetClass.getUniqueName(method, preservePrefix);
}
/**
* Obtain a unique name for the specified field from the target class
* context
*
* @param field field to obtain a name for
* @return unique field name
*/
public String getUniqueName(FieldNode field) {
return this.targetClass.getUniqueName(field);
}
@@ -1077,6 +1101,10 @@ public class MixinTargetContext implements IMixinContext {
this.injectors.clear();
}
/**
* Expand accessor methods mixed into the target class by populating the
* method bodies
*/
public List<MethodNode> generateAccessors() {
for (AccessorInfo accessor : this.accessors) {
accessor.locate();
@@ -333,8 +333,7 @@ public class MixinTransformer extends TreeTransformer {
MixinTransformer.logger.info("Attempting to load Fernflower decompiler{}", as ? " (Threaded mode)" : "");
String className = "org.spongepowered.asm.mixin.transformer.debug.RuntimeDecompiler" + (as ? "Async" : "");
@SuppressWarnings("unchecked")
Class<? extends IDecompiler> clazz =
(Class<? extends IDecompiler>)Class.forName(className);
Class<? extends IDecompiler> clazz = (Class<? extends IDecompiler>)Class.forName(className);
Constructor<? extends IDecompiler> ctor = clazz.getDeclaredConstructor(File.class);
IDecompiler decompiler = ctor.newInstance(outputPath);
MixinTransformer.logger.info("Fernflower decompiler was successfully initialised, exported classes will be decompiled{}",
@@ -779,7 +778,7 @@ public class MixinTransformer extends TreeTransformer {
* Apply mixins for specified target class to the class described by the
* supplied byte array.
*
* @param context
* @param context target class context
* @return class bytecode after application of mixins
*/
private byte[] applyMixins(TargetClassContext context) {
@@ -218,8 +218,8 @@ class TargetClassContext {
/**
* Finds a field in the target class
*
* @param aliases
* @param desc
* @param aliases aliases for the field
* @param desc field descriptor
* @return Target field or null if not found
*/
FieldNode findAliasedField(Deque<String> aliases, String desc) {
@@ -104,7 +104,7 @@ abstract class TreeInfo {
* @param name Original class name
* @param transformedName Name of the class to load
* @return raw class bytecode
* @throws IOException
* @throws IOException if an error occurs reading the class bytes
*/
private static byte[] getClassBytes(String name, String transformedName) throws IOException {
byte[] classBytes = Launch.classLoader.getClassBytes(name);
@@ -130,9 +130,9 @@ abstract class TreeInfo {
* Since we obtain the class bytes with getClassBytes(), we need to apply
* the transformers ourself
*
* @param name
* @param transformedName
* @param basicClass
* @param name class name
* @param transformedName transformed class name
* @param basicClass input class bytes
* @return class bytecode after processing by all registered transformers
* except the excluded transformers
*/
@@ -32,7 +32,7 @@ public interface IHotSwap {
/**
* Registers a mixin class with the agent.
*
* This is needed as the mixin needs to be loaded to be redefined.
* <p>This is needed as the mixin needs to be loaded to be redefined.</p>
*
* @param name Fully qualified name of the mixin class
*/
@@ -41,8 +41,8 @@ public interface IHotSwap {
/**
* Registers a class targeted by at least one mixin.
*
* This is used to rollback the target class to a state before the mixin's
* where applied.
* <p>This is used to rollback the target class to a state before the
* mixin's were applied.</p>
*
* @param name Name of the class
* @param bytecode Bytecode of the class before mixin's have been applied
@@ -135,6 +135,11 @@ public class SourceMap {
}
}
/**
* Append lines representing this File to the supplied StringBuilder
*
* @param sb StringBuilder to append to
*/
public void appendLines(StringBuilder sb) {
sb.append("1#").append(this.id) // Map line number 1 (onwards) in file number <index>
.append(",").append(this.size) // repeated <file.size> times (eg. lines 1 to <file.size + 1>)
@@ -217,18 +222,48 @@ public class SourceMap {
return this.sourceFile.replace(".java", "$mixin.java");
}
/**
* Add a file to this SourceMap in the default stratum
*
* @param classNode class node to read details from
* @return new File
*/
public File addFile(ClassNode classNode) {
return this.addFile(this.defaultStratum, classNode);
}
/**
* Add a file to this SourceMap in the specified stratum
*
* @param stratumName name of the stratum to add to
* @param classNode class node to read file details from
* @return new File
*/
public File addFile(String stratumName, ClassNode classNode) {
return this.addFile(stratumName, classNode.sourceFile, classNode.name + ".java", ASMHelper.getMaxLineNumber(classNode, 500, 50));
}
public File addFile( String sourceFileName, String sourceFilePath, int size) {
/**
* Add a file to this SourceMap in the default stratum
*
* @param sourceFileName source filename
* @param sourceFilePath path to source file
* @param size number of lines to allocate
* @return new File
*/
public File addFile(String sourceFileName, String sourceFilePath, int size) {
return this.addFile(this.defaultStratum, sourceFileName, sourceFilePath, size);
}
/**
* Add a file to this SourceMap in the specified stratum
*
* @param stratumName name of the stratum to add to
* @param sourceFileName source filename
* @param sourceFilePath path to source file
* @param size number of lines to allocate
* @return new File
*/
public File addFile(String stratumName, String sourceFileName, String sourceFilePath, int size) {
Stratum stratum = this.strata.get(stratumName);
if (stratum == null) {
@@ -42,6 +42,12 @@ public class RemapperChain implements IRemapper {
return String.format("RemapperChain[%d]", this.remappers.size());
}
/**
* Add a new remapper to this chain
*
* @param remapper remapper to add
* @return fluent interface
*/
public RemapperChain add(IRemapper remapper) {
this.remappers.add(remapper);
return this;
@@ -95,6 +95,13 @@ public class MappingMethod implements IMapping<MappingMethod> {
return new MappingMethod(this.getOwner(), this.getSimpleName(), this.getDesc());
}
/**
* Return a clone of this mapping with the supplied prefix added. Returns
* this object if the prefix matches the existing name.
*
* @param prefix prefix to prepend
* @return cloned mapping
*/
public MappingMethod addPrefix(String prefix) {
String simpleName = this.getSimpleName();
if (simpleName == null || simpleName.startsWith(prefix)) {
@@ -50,24 +50,39 @@ import com.google.common.primitives.Ints;
/**
* Utility methods for working with ASM
*/
public class ASMHelper {
public final class ASMHelper {
/**
* Integer constant opcodes
*/
public static final int[] CONSTANTS_INT = {
Opcodes.ICONST_M1, Opcodes.ICONST_0, Opcodes.ICONST_1, Opcodes.ICONST_2, Opcodes.ICONST_3, Opcodes.ICONST_4, Opcodes.ICONST_5
};
/**
* Float constant opcodes
*/
public static final int[] CONSTANTS_FLOAT = {
Opcodes.FCONST_0, Opcodes.FCONST_1, Opcodes.FCONST_2
};
/**
* Double constant opcodes
*/
public static final int[] CONSTANTS_DOUBLE = {
Opcodes.DCONST_0, Opcodes.DCONST_1
};
/**
* Long constant opcodes
*/
public static final int[] CONSTANTS_LONG = {
Opcodes.LCONST_0, Opcodes.LCONST_1
};
/**
* All constant opcodes
*/
public static final int[] CONSTANTS_ALL = {
Opcodes.ACONST_NULL,
Opcodes.ICONST_M1,
@@ -90,15 +105,19 @@ public class ASMHelper {
};
private static final String[] CONSTANTS_TYPES = {
null,
"I",
"I", "I", "I", "I", "I", "I",
"J", "J",
"F", "F", "F",
"D", "D",
"I", //"B",
"I", //"S"
null,
"I",
"I", "I", "I", "I", "I", "I",
"J", "J",
"F", "F", "F",
"D", "D",
"I", //"B",
"I", //"S"
};
private ASMHelper() {
// utility class
}
/**
* Finds a method given the method descriptor
@@ -173,7 +192,7 @@ public class ASMHelper {
System.err.printf("%s%s\n", method.name, method.desc);
int i = 0;
for (Iterator<AbstractInsnNode> iter = method.instructions.iterator(); iter.hasNext();) {
System.err.printf("[%4d] %s\n", i++, ASMHelper.getNodeDescriptionForDebug(iter.next()));
System.err.printf("[%4d] %s\n", i++, ASMHelper.describeNode(iter.next()));
}
}
@@ -196,10 +215,20 @@ public class ASMHelper {
* @param node Node to print
*/
public static void printNode(AbstractInsnNode node) {
System.err.printf("%s\n", ASMHelper.getNodeDescriptionForDebug(node));
System.err.printf("%s\n", ASMHelper.describeNode(node));
}
public static String getNodeDescriptionForDebug(AbstractInsnNode node) {
/**
* Gets a description of the supplied node for debugging purposes
*
* @param node node to describe
* @return human-readable description of node
*/
public static String describeNode(AbstractInsnNode node) {
if (node == null) {
return String.format(" %-14s ", "null");
}
if (node instanceof LabelNode) {
return String.format("[%s]", ((LabelNode)node).getLabel());
}
@@ -645,10 +674,22 @@ public class ASMHelper {
return Enum.valueOf(enumClass, value[1]);
}
/**
* Returns true if the supplied method node is static
*
* @param method method node
* @return true if the method has the {@link Opcodes#ACC_STATIC} flag
*/
public static boolean methodIsStatic(MethodNode method) {
return (method.access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC;
}
/**
* Returns true if the supplied field node is static
*
* @param field field node
* @return true if the field has the {@link Opcodes#ACC_STATIC} flag
*/
public static boolean fieldIsStatic(FieldNode field) {
return (field.access & Opcodes.ACC_STATIC) == Opcodes.ACC_STATIC;
}
@@ -733,6 +774,14 @@ public class ASMHelper {
}
}
/**
* Clones all of the labels in the source instruction list and returns the
* clones in a map of old label -&gt; new label. This is used to facilitate
* the use of {@link AbstractInsnNode#clone}.
*
* @param source instruction list
* @return map of existing labels to their cloned counterparts
*/
public static Map<LabelNode, LabelNode> cloneLabels(InsnList source) {
Map<LabelNode, LabelNode> labels = new HashMap<LabelNode, LabelNode>();
@@ -747,8 +796,13 @@ public class ASMHelper {
}
/**
* @param returnType
* @param args
* Generate a bytecode descriptor from the supplied tokens. Each token can
* be a {@link Type}, a {@link Class} or otherwise is converted in-place by
* calling {@link Object#toString toString}.
*
* @param returnType object representing the method return type, can be
* <tt>null</tt> for <tt>void</tt>
* @param args objects representing argument types
*/
public static String generateDescriptor(Object returnType, Object... args) {
StringBuilder sb = new StringBuilder().append('(');
@@ -761,7 +815,10 @@ public class ASMHelper {
}
/**
* @param arg
* Converts the supplied object to a descriptor component, used by
* {@link #generateDescriptor}.
*
* @param arg object to convert
*/
private static String toDescriptor(Object arg) {
if (arg instanceof String) {
@@ -774,18 +831,46 @@ public class ASMHelper {
return arg == null ? "" : arg.toString();
}
/**
* Returns the simple name of an annotation, mainly used for printing
* annotation names in error messages/user-facing strings
*
* @param annotationType annotation
* @return annotation's simple name
*/
public static String getSimpleName(Class<? extends Annotation> annotationType) {
return annotationType.getSimpleName();
}
/**
* Returns the simple name of an annotation, mainly used for printing
* annotation names in error messages/user-facing strings
*
* @param annotation annotation node
* @return annotation's simple name
*/
public static String getSimpleName(AnnotationNode annotation) {
return ASMHelper.getSimpleName(annotation.desc);
}
/**
* Returns the simple name from an object type descriptor (in L...; format)
*
* @param desc type descriptor
* @return "simple" name
*/
public static String getSimpleName(String desc) {
return desc.substring(desc.lastIndexOf('/') + 1).replace(";", "");
int pos = Math.max(desc.lastIndexOf('/'), 0);
return desc.substring(pos + 1).replace(";", "");
}
/**
* Gets whether the supplied instruction is a constant instruction (eg.
* <tt>ICONST_1</tt>)
*
* @param insn instruction to check
* @return true if the supplied instruction is a constant
*/
public static boolean isConstant(AbstractInsnNode insn) {
if (insn == null) {
return false;
@@ -793,6 +878,14 @@ public class ASMHelper {
return Ints.contains(ASMHelper.CONSTANTS_ALL, insn.getOpcode());
}
/**
* If the supplied instruction is a constant, returns the constant value
* from the instruction
*
* @param insn constant instruction to process
* @return the constant value or <tt>null</tt> if the value cannot be parsed
* (or is null)
*/
public static Object getConstant(AbstractInsnNode insn) {
if (insn == null) {
return null;
@@ -810,6 +903,13 @@ public class ASMHelper {
return index < 0 ? null : ASMHelper.CONSTANTS_VALUES[index];
}
/**
* Returns the {@link Type} of a particular constant instruction's payload
*
* @param insn constant instruction
* @return type of constant or <tt>null</tt> if it cannot be parsed (or is
* null)
*/
public static Type getConstantType(AbstractInsnNode insn) {
if (insn == null) {
return null;
@@ -838,8 +938,8 @@ public class ASMHelper {
/**
* Check whether the specified flag is set on the specified class
*
* @param classNode
* @param flag
* @param classNode class node
* @param flag flag to check
* @return True if the specified flag is set in this method's access flags
*/
public static boolean hasFlag(ClassNode classNode, int flag) {
@@ -849,8 +949,8 @@ public class ASMHelper {
/**
* Check whether the specified flag is set on the specified method
*
* @param method
* @param flag
* @param method method node
* @param flag flag to check
* @return True if the specified flag is set in this method's access flags
*/
public static boolean hasFlag(MethodNode method, int flag) {
@@ -860,8 +960,8 @@ public class ASMHelper {
/**
* Check whether the specified flag is set on the specified field
*
* @param field
* @param flag
* @param field field node
* @param flag flag to check
* @return True if the specified flag is set in this field's access flags
*/
public static boolean hasFlag(FieldNode field, int flag) {
@@ -1265,7 +1265,7 @@ public class ClassSignature {
@Override
public String toString() {
while (this.rawInterfaces.size() > 0) {
this.addRawInterface(this.rawInterfaces.remove());
this.addRawInterface(this.rawInterfaces.remove());
}
StringBuilder sb = new StringBuilder();
@@ -72,9 +72,9 @@ public final class ConstraintParser {
* <dd><em>Greater than or equal to</em> 1234 (equivalent to <code>1234
* &gt;</code>)</dd>
* <dt><pre>(1234-1300)</pre></dt>
* <dd>Value must be <em>between</dd> 1234 and 1300 (inclusive)
* <dd>Value must be <em>between</em> 1234 and 1300 (inclusive)</dd>
* <dt><pre>(1234+10)</pre></dt>
* <dd>Value must be <em>between</dd> 1234 and 1234+10 (1234-1244
* <dd>Value must be <em>between</em> 1234 and 1234+10 (1234-1244
* inclusive)</dd>
* </dl>
*
@@ -220,6 +220,13 @@ public final class ConstraintParser {
return this.max;
}
/**
* Checks the current token against the environment and throws a
* {@link ConstraintViolationException} if the constraint is invalid
*
* @param environment environment to fetch constraints
* @throws ConstraintViolationException if constraint is not valid
*/
public void check(ITokenProvider environment) throws ConstraintViolationException {
if (this != Constraint.NONE) {
Integer value = environment.getToken(this.token);
@@ -240,6 +247,10 @@ public final class ConstraintParser {
}
}
/**
* Gets a human-readable description of the range expressed by this
* constraint
*/
public String getRangeHumanReadable() {
if (this.min == Integer.MIN_VALUE && this.max == Integer.MAX_VALUE) {
return "ANY VALUE";
@@ -262,6 +273,14 @@ public final class ConstraintParser {
private ConstraintParser() {
}
/**
* Parse the supplied expression as a constraint and returns a new
* Constraint. Returns {@link Constraint#NONE} if the constraint could not
* be parsed or is empty.
*
* @param expr constraint expression to parse
* @return parsed constraint
*/
public static Constraint parse(String expr) {
if (expr == null || expr.length() == 0) {
return Constraint.NONE;
@@ -281,6 +300,15 @@ public final class ConstraintParser {
return head != null ? head : Constraint.NONE;
}
/**
* Parse a constraint expression on the supplied annotation as a constraint
* and returns a new Constraint. Returns {@link Constraint#NONE} if the
* constraint could not be parsed or is empty.
*
* @param annotation annotation containing the constraint expression to
* parse
* @return parsed constraint
*/
public static Constraint parse(AnnotationNode annotation) {
String constraints = ASMHelper.getAnnotationValue(annotation, "constraints", "");
return ConstraintParser.parse(constraints);
@@ -36,6 +36,9 @@ public abstract class JavaVersion {
private JavaVersion() {}
/**
* Get the current java version, calculates if necessary
*/
public static double current() {
if (JavaVersion.current == 0.0) {
JavaVersion.current = JavaVersion.resolveCurrentVersion();
@@ -54,13 +54,17 @@ import org.spongepowered.asm.util.throwables.LVTGeneratorException;
/**
* Utility methods for working with local variables using ASM
*/
public class Locals {
public final class Locals {
/**
* Cached local variable lists, to avoid having to recalculate them
* (expensive) if multiple injectors are working with the same method
*/
private static final Map<String, List<LocalVariableNode>> calculatedLocalVariables = new HashMap<String, List<LocalVariableNode>>();
private Locals() {
// utility class
}
/**
* Injects appropriate LOAD opcodes into the supplied InsnList for each
@@ -70,6 +74,7 @@ public class Locals {
* RETURN values in locals)
* @param insns Instruction List to inject into
* @param pos Start position
* @param limit maximum number of locals to consume
*/
public static void loadLocals(Type[] locals, InsnList insns, int pos, int limit) {
for (; pos < locals.length && limit > 0; pos++) {
@@ -54,10 +54,24 @@ public abstract class ObfuscationUtil {
private ObfuscationUtil() {}
/**
* Map a descriptor using the supplied rempper
*
* @param desc descriptor to remap
* @param remapper remapper to use
* @return mapped descriptor
*/
public static String mapDescriptor(String desc, IClassRemapper remapper) {
return ObfuscationUtil.remapDescriptor(desc, remapper, false);
}
/**
* Unmap (inverse of map) a descriptor using the supplied rempper
*
* @param desc descriptor to unmap
* @param remapper remapper to use
* @return unmapped descriptor
*/
public static String unmapDescriptor(String desc, IClassRemapper remapper) {
return ObfuscationUtil.remapDescriptor(desc, remapper, true);
}
@@ -486,7 +486,7 @@ public class PrettyPrinter {
* <code>printer.table("Column 1", 30, "Column 2", 20, Alignment.RIGHT);
* </code>
*
* @param format
* @param format format string, see description
* @return fluent interface
*/
public PrettyPrinter table(Object... format) {
@@ -123,14 +123,25 @@ public class SignaturePrinter {
}
}
/**
* Return only the arguments portion of this signature as a Java-style block
*/
public String getFormattedArgs() {
return this.appendArgs(new StringBuilder(), true).toString();
}
/**
* Get string representation of this signature's return type
*/
public String getReturnType() {
return SignaturePrinter.getTypeName(this.returnType, false, this.fullyQualified);
}
/**
* Set modifiers on this signature using the supplied method node
*
* @param method method node to read modifiers from
*/
public void setModifiers(MethodNode method) {
String returnType = SignaturePrinter.getTypeName(Type.getReturnType(method.desc), false, this.fullyQualified);
if ((method.access & Opcodes.ACC_PUBLIC) != 0) {
@@ -144,25 +155,50 @@ public class SignaturePrinter {
}
}
/**
* Set modifiers on this signature explicitly. Use the special token
* <tt>${returnType}</tt> to insert the return type into the modifier
* string.
*
* @param modifiers modifiers to prepend
* @return fluent interface
*/
public SignaturePrinter setModifiers(String modifiers) {
this.modifiers = modifiers.replace("${returnType}", this.getReturnType());
return this;
}
/**
* Set whether this signature generates fully-qualified class output, mainly
* used when generating signatures for Mirror
*
* @param fullyQualified new value for fully-qualified
* @return fluent interface
*/
public SignaturePrinter setFullyQualified(boolean fullyQualified) {
this.fullyQualified = fullyQualified;
return this;
}
/**
* Get whether this printer will fully-qualify class names in generated
* signatures
*/
public boolean isFullyQualified() {
return this.fullyQualified;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
@Override
public String toString() {
return this.appendArgs(new StringBuilder().append(this.modifiers).append(" ").append(this.name), false).toString();
}
/**
* Return this signature in descriptor format (return type after args)
*/
public String toDescriptor() {
StringBuilder args = this.appendArgs(new StringBuilder(), true);
return args.append(SignaturePrinter.getTypeName(this.returnType, false, this.fullyQualified)).toString();
@@ -33,7 +33,7 @@ import java.util.regex.Pattern;
* </code> format as a sequence of four shorts packed into a long. This is to
* facilitate meaningful comparison between version numbers.
*/
public class VersionNumber implements Comparable<VersionNumber>, Serializable {
public final class VersionNumber implements Comparable<VersionNumber>, Serializable {
private static final long serialVersionUID = 1L;
@@ -46,7 +46,7 @@ public class VersionNumber implements Comparable<VersionNumber>, Serializable {
/**
* Regex for matching a version number specified as a string
*/
private static final Pattern versionNumberPattern =
private static final Pattern PATTERN =
Pattern.compile("^(\\d{1,5})(?:\\.(\\d{1,5})(?:\\.(\\d{1,5})(?:\\.(\\d{1,5}))?)?)?(-[a-zA-Z0-9_\\-]+)?$");
/**
@@ -190,7 +190,7 @@ public class VersionNumber implements Comparable<VersionNumber>, Serializable {
return defaultVersion;
}
Matcher versionNumberPatternMatcher = VersionNumber.versionNumberPattern.matcher(version);
Matcher versionNumberPatternMatcher = VersionNumber.PATTERN.matcher(version);
if (!versionNumberPatternMatcher.matches()) {
return defaultVersion;
}
@@ -153,6 +153,9 @@ public final class LaunchClassLoaderUtil {
}
}
/**
* Get the classloader exclusions from the target classloader
*/
public Set<String> getClassLoaderExceptions() {
if (this.classLoaderExceptions != null) {
return this.classLoaderExceptions;
@@ -160,6 +163,9 @@ public final class LaunchClassLoaderUtil {
return Collections.<String>emptySet();
}
/**
* Get the transformer exclusions from the target classloader
*/
public Set<String> getTransformerExceptions() {
if (this.transformerExceptions != null) {
return this.transformerExceptions;
@@ -27,8 +27,8 @@ package org.spongepowered.asm.util.throwables;
import org.spongepowered.asm.mixin.throwables.MixinException;
/**
* Exception thrown when something goes horribly wrong whilst <s>summoning the
* antichrist</s> generating the LVT for a target method.
* Exception thrown when something goes horribly wrong whilst <del>summoning the
* antichrist</del> generating the LVT for a target method.
*/
public class LVTGeneratorException extends MixinException {