Port accessor functionality from liteloader, update for mixin style

This commit is contained in:
Mumfrey committed 2016-10-07 18:24:55 +01:00
1 parent 81007a9546
commit f83d7757d7
38 files changed
+1974 -230

No files matched your search

@@ -0,0 +1,76 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.Shadow;
/**
* Defines an accessor method in a mixin, the method can be a getter (must
* return the field type and take no arguments) or a setter (must take an
* argument of the field type and return void). The annotated method must be
* <tt>abstract</tt>.
*
* <p>Accessors provide a simple way of gaining access to internal class members
* in a target class without needing to resort to access transformers, and
* without the usual need to {@link Shadow} a target field. This can both
* greatly simplify mixins which <b>only</b> contain accessors, and provide for
* faster development than with access transformers since no re-decompile is
* needed to put the changes into effect.</p>
*
* <p>Accessors can be used in regular mixins as a convenient way to generate
* getters and setters. They can also be used to create <i>"Accessor Mixins"</i>
* which are special mixins defined as <tt>interface</tt>s which must
* <b>only</b> contain {@link Accessor} and {@link Invoker} methods. Unlike
* normal mixins however, <i>Accessor Mixins</i> are accessible via user code
* and thus no surrogate <i>"Duck"</i> interface is required to expose the
* generated methods, the mixin itself acts as its own Duck.</p>
*
* <ul><li>See also {@link Invoker}</li></ul>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Accessor {
/**
* Normally the target field name is inflected by examining the annotated
* method name. If the annotated method starts with "get", "set" or "is"
* followed by a capital letter, then the prefix is stripped and the
* remainder of the method name is used as the target field name.
*
* <p>However sometimes it maye be desirable to name an accessor method
* differently to the target field name. In this case you may specify the
* field using its name.</p>
*
* @return name for the target field, or empty string to inflect using the
* annotated method name
*/
public String value() default "";
}
@@ -0,0 +1,71 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import java.util.ArrayList;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.MethodNode;
/**
* Base class for accessor generators
*/
public abstract class AccessorGenerator {
/**
* Accessor info which describes the accessor
*/
protected final AccessorInfo info;
public AccessorGenerator(AccessorInfo info) {
this.info = info;
}
/**
* Create an empty accessor method based on the source method
*
* @param maxLocals max locals size for method
* @param maxStack max stack size for method
* @return new method
*/
protected final MethodNode createMethod(int maxLocals, int maxStack) {
MethodNode method = this.info.getMethod();
MethodNode accessor = new MethodNode(Opcodes.ASM5, method.access & ~Opcodes.ACC_ABSTRACT, method.name, method.desc, null, null);
accessor.visibleAnnotations = new ArrayList<AnnotationNode>();
accessor.visibleAnnotations.add(this.info.getAnnotation());
accessor.maxLocals = maxLocals;
accessor.maxStack = maxStack;
return accessor;
}
/**
* Generate the accessor method
*
* @return generated accessor method
*/
public abstract MethodNode generate();
}
@@ -0,0 +1,58 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.FieldNode;
/**
* Accessor generator for field accessors
*/
public abstract class AccessorGeneratorField extends AccessorGenerator {
/**
* The target field, identified by the accessor info
*/
protected final FieldNode targetField;
/**
* The type of the target member
*/
protected final Type targetType;
/**
* True for instance field, false for static field
*/
protected final boolean isInstanceField;
public AccessorGeneratorField(AccessorInfo info) {
super(info);
this.targetField = info.getTargetField();
this.targetType = info.getTargetFieldType();
this.isInstanceField = (this.targetField.access & Opcodes.ACC_STATIC) == 0;
}
}
@@ -0,0 +1,57 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.InsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
/**
* Generator for instance field getters
*/
public class AccessorGeneratorFieldGetter extends AccessorGeneratorField {
public AccessorGeneratorFieldGetter(AccessorInfo info) {
super(info);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.gen.AccessorGenerator#generate()
*/
@Override
public MethodNode generate() {
MethodNode method = this.createMethod(this.targetType.getSize(), this.targetType.getSize());
if (this.isInstanceField) {
method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
int opcode = this.isInstanceField ? Opcodes.GETFIELD : Opcodes.GETSTATIC;
method.instructions.add(new FieldInsnNode(opcode, this.info.getClassNode().name, this.targetField.name, this.targetField.desc));
method.instructions.add(new InsnNode(this.targetType.getOpcode(Opcodes.IRETURN)));
return method;
}
}
@@ -0,0 +1,61 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.FieldInsnNode;
import org.spongepowered.asm.lib.tree.InsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
/**
* Generator for field setters
*/
public class AccessorGeneratorFieldSetter extends AccessorGeneratorField {
public AccessorGeneratorFieldSetter(AccessorInfo info) {
super(info);
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.gen.AccessorGenerator#generate()
*/
@Override
public MethodNode generate() {
int stackSpace = this.isInstanceField ? 1 : 0;
int maxLocals = stackSpace + this.targetType.getSize();
int maxStack = stackSpace + this.targetType.getSize();
MethodNode method = this.createMethod(maxLocals, maxStack);
if (this.isInstanceField) {
method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
method.instructions.add(new VarInsnNode(this.targetType.getOpcode(Opcodes.ILOAD), stackSpace));
int opcode = this.isInstanceField ? Opcodes.PUTFIELD : Opcodes.PUTSTATIC;
method.instructions.add(new FieldInsnNode(opcode, this.info.getClassNode().name, this.targetField.name, this.targetField.desc));
method.instructions.add(new InsnNode(Opcodes.RETURN));
return method;
}
}
@@ -0,0 +1,83 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.InsnNode;
import org.spongepowered.asm.lib.tree.MethodInsnNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.lib.tree.VarInsnNode;
import org.spongepowered.asm.util.ASMHelper;
/**
* Generator for proxy methods
*/
public class AccessorGeneratorMethodProxy extends AccessorGenerator {
/**
* The target field, identified by the accessor info
*/
private final MethodNode targetMethod;
/**
* Accessor method argument types (raw, from method)
*/
private final Type[] argTypes;
/**
* Accessor method return type (raw, from method)
*/
private final Type returnType;
/**
* True for instance method, false for static method
*/
private final boolean isInstanceMethod;
public AccessorGeneratorMethodProxy(AccessorInfo info) {
super(info);
this.targetMethod = info.getTargetMethod();
this.argTypes = info.getArgTypes();
this.returnType = info.getReturnType();
this.isInstanceMethod = !ASMHelper.hasFlag(this.targetMethod, Opcodes.ACC_STATIC);
}
@Override
public MethodNode generate() {
int size = ASMHelper.getArgsSize(this.argTypes) + this.returnType.getSize();
MethodNode method = this.createMethod(size, size);
if (this.isInstanceMethod) {
method.instructions.add(new VarInsnNode(Opcodes.ALOAD, 0));
}
ASMHelper.loadArgs(this.argTypes, method.instructions, 1);
boolean isPrivate = ASMHelper.hasFlag(this.targetMethod, Opcodes.ACC_PRIVATE);
int opcode = this.isInstanceMethod ? (isPrivate ? Opcodes.INVOKESPECIAL : Opcodes.INVOKEVIRTUAL) : Opcodes.INVOKESTATIC;
method.instructions.add(new MethodInsnNode(opcode, this.info.getClassNode().name, this.targetMethod.name, this.targetMethod.desc, false));
method.instructions.add(new InsnNode(this.returnType.getOpcode(Opcodes.IRETURN)));
return method;
}
}
@@ -0,0 +1,378 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.logging.log4j.LogManager;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext;
import org.spongepowered.asm.mixin.struct.SpecialMethodInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.ASMHelper;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableSet;
/**
* Information about an accessor
*/
public class AccessorInfo extends SpecialMethodInfo {
/**
* Accessor types
*/
public enum AccessorType {
/**
* A field getter, accessor must accept no args and return field type
*/
FIELD_GETTER(ImmutableSet.<String>of("get", "is")) {
@Override
AccessorGenerator getGenerator(AccessorInfo info) {
return new AccessorGeneratorFieldGetter(info);
}
},
/**
* A field setter, accessor must accept single arg of the field type and
* return void
*/
FIELD_SETTER(ImmutableSet.<String>of("set")) {
@Override
AccessorGenerator getGenerator(AccessorInfo info) {
return new AccessorGeneratorFieldSetter(info);
}
},
/**
* An invoker (proxy) method
*/
METHOD_PROXY(ImmutableSet.<String>of("call", "invoke")) {
@Override
AccessorGenerator getGenerator(AccessorInfo info) {
return new AccessorGeneratorMethodProxy(info);
}
};
private final Set<String> expectedPrefixes;
private AccessorType(Set<String> expectedPrefixes) {
this.expectedPrefixes = expectedPrefixes;
}
public boolean isExpectedPrefix(String prefix) {
return this.expectedPrefixes.contains(prefix);
}
public String getExpectedPrefixes() {
return this.expectedPrefixes.toString();
}
abstract AccessorGenerator getGenerator(AccessorInfo info);
}
/**
* Pattern for matching accessor names (for inflector)
*/
protected static final Pattern PATTERN_ACCESSOR = Pattern.compile("^(get|set|is|invoke|call)(([A-Z])(.*))$");
/**
* Accessor method argument types (raw, from method)
*/
protected final Type[] argTypes;
/**
* Accessor method return type (raw, from method)
*/
protected final Type returnType;
/**
* Type of accessor to generate, computed based on the signature of the
* target method.
*/
protected final AccessorType type;
/**
* For field accessors, the expected type of the target field
*/
private final Type targetFieldType;
/**
* Computed information about the target field or method, name and
* descriptor
*/
protected final MemberInfo target;
/**
* For accessors, stores the discovered target field
*/
protected FieldNode targetField;
/**
* For invokers, stores the discovered target method
*/
protected MethodNode targetMethod;
public AccessorInfo(MixinTargetContext mixin, MethodNode method) {
this(mixin, method, Accessor.class);
}
protected AccessorInfo(MixinTargetContext mixin, MethodNode method, Class<? extends Annotation> annotationClass) {
super(mixin, method, ASMHelper.getVisibleAnnotation(method, annotationClass));
this.argTypes = Type.getArgumentTypes(method.desc);
this.returnType = Type.getReturnType(method.desc);
this.type = this.initType();
this.targetFieldType = this.initTargetFieldType();
this.target = this.initTarget();
}
protected AccessorType initType() {
if (this.returnType.equals(Type.VOID_TYPE)) {
return AccessorType.FIELD_SETTER;
}
return AccessorType.FIELD_GETTER;
}
protected Type initTargetFieldType() {
switch (this.type) {
case FIELD_GETTER:
if (this.argTypes.length > 0) {
throw new InvalidAccessorException(this.mixin, this + " must take exactly 0 arguments, found " + this.argTypes.length);
}
return this.returnType;
case FIELD_SETTER:
if (this.argTypes.length != 1) {
throw new InvalidAccessorException(this.mixin, this + " must take exactly 1 argument, found " + this.argTypes.length);
}
return this.argTypes[0];
default:
throw new InvalidAccessorException(this.mixin, "Computed unsupported accessor type " + this.type + " for " + this);
}
}
protected MemberInfo initTarget() {
MemberInfo target = new MemberInfo(this.getTargetName(), null, this.targetFieldType.getDescriptor());
this.annotation.visit("target", target.toString());
return target;
}
protected String getTargetName() {
String name = ASMHelper.<String>getAnnotationValue(this.annotation);
if (Strings.isNullOrEmpty(name)) {
String inflectedTarget = this.inflectTarget();
if (inflectedTarget == null) {
throw new InvalidAccessorException(this.mixin, "Failed to inflect target name for " + this + ", supported prefixes: [get, set, is]");
}
return inflectedTarget;
}
return MemberInfo.parse(name, this.mixin).name;
}
protected String inflectTarget() {
return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this.mixin,
this.mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE));
}
public static String inflectTarget(String accessorName, AccessorType accessorType, String accessorDescription,
IReferenceMapperContext context, boolean verbose) {
Matcher nameMatcher = AccessorInfo.PATTERN_ACCESSOR.matcher(accessorName);
if (nameMatcher.matches()) {
String prefix = nameMatcher.group(1);
String firstChar = nameMatcher.group(3);
String remainder = nameMatcher.group(4);
// If the entire name is upper case, do not lowercase the first char
String name = String.format("%s%s", AccessorInfo.toLowerCase(firstChar, !AccessorInfo.isUpperCase(remainder)), remainder);
if (!accessorType.isExpectedPrefix(prefix) && verbose) {
LogManager.getLogger("mixin").warn("Unexpected prefix for {}, found [{}] expecting {}", accessorDescription, prefix,
accessorType.getExpectedPrefixes());
}
return MemberInfo.parse(name, context).name;
}
return null;
}
/**
* Get the inflected/specified target member for this accessor
*/
public final MemberInfo getTarget() {
return this.target;
}
/**
* For field accessors, returns the field type, returns null for invokers
*/
public final Type getTargetFieldType() {
return this.targetFieldType;
}
/**
* For field accessors, returns the target field, returns null for invokers
*/
public final FieldNode getTargetField() {
return this.targetField;
}
/**
* For invokers, returns the target method, returns null for field accessors
*/
public final MethodNode getTargetMethod() {
return this.targetMethod;
}
/**
* Get the return type of the annotated method
*/
public final Type getReturnType() {
return this.returnType;
}
/**
* Get the argument types of the annotated method
*/
public final Type[] getArgTypes() {
return this.argTypes;
}
@Override
public String toString() {
return String.format("%s->@%s[%s]::%s%s", this.mixin.toString(), ASMHelper.getSimpleName(this.annotation), this.type.toString(),
this.method.name, this.method.desc);
}
/**
* First pass, locate the target field in the class. This is done after all
* other mixins are applied so that mixin-added fields and methods can be
* targetted.
*/
public void locate() {
this.targetField = this.findTargetField();
}
/**
* Second pass, generate the actual accessor method for this accessor. The
* method still respects intrinsic/mixinmerged rules so is not guaranteed to
* be added to the target class
*
* @return generated accessor method
*/
public MethodNode generate() {
return this.type.getGenerator(this).generate();
}
private FieldNode findTargetField() {
return this.<FieldNode>findTarget(this.classNode.fields);
}
/**
* Generified candidate search, since the search logic is the same for both
* fields and methods.
*
* @param nodes Node list to search (method/field list)
* @return best match
*/
protected <TNode> TNode findTarget(List<TNode> nodes) {
TNode exactMatch = null;
List<TNode> candidates = new ArrayList<TNode>();
for (TNode node : nodes) {
String desc = AccessorInfo.<TNode>getNodeDesc(node);
if (desc == null || !desc.equals(this.target.desc)) {
continue;
}
String name = AccessorInfo.<TNode>getNodeName(node);
if (name != null) {
if (name.equals(this.target.name)) {
exactMatch = node;
}
if (name.equalsIgnoreCase(this.target.name)) {
candidates.add(node);
}
}
}
if (exactMatch != null) {
if (candidates.size() > 1) {
LogManager.getLogger("mixin").debug("{} found an exact match for {} but other candidates were found!", this, this.target);
}
return exactMatch;
}
if (candidates.size() == 1) {
return candidates.get(0);
}
throw new InvalidAccessorException(this, "Multiple candidates were found matching " + this.target + " in " + this.classNode.name
+ " for " + this);
}
private static <TNode> String getNodeDesc(TNode node) {
return (node instanceof MethodNode) ? ((MethodNode)node).desc : ((node instanceof FieldNode) ? ((FieldNode)node).desc : null);
}
private static <TNode> String getNodeName(TNode node) {
return (node instanceof MethodNode) ? ((MethodNode)node).name : ((node instanceof FieldNode) ? ((FieldNode)node).name : null);
}
/**
* Return a wrapper AccessorInfo of the correct type based on the method
* passed in.
*
* @param mixin mixin context which owns this accessor
* @param method annotated method
* @param type annotation type to process
* @return parsed AccessorInfo
*/
public static AccessorInfo of(MixinTargetContext mixin, MethodNode method, Class<? extends Annotation> type) {
if (type == Accessor.class) {
return new AccessorInfo(mixin, method);
} else if (type == Invoker.class) {
return new InvokerInfo(mixin, method);
}
throw new InvalidAccessorException(mixin, "Could not parse accessor for unknown type " + type.getName());
}
private static String toLowerCase(String string, boolean condition) {
return condition ? string.toLowerCase() : string;
}
private static boolean isUpperCase(String string) {
return string.toUpperCase().equals(string);
}
}
@@ -0,0 +1,76 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.Shadow;
/**
* Defines an <em>invoker method</em> (also known as a <em>proxy method</em> in
* a mixin, the method. The annotated method must be <tt>abstract</tt> and the
* signature of the method must match the target method precisely.
*
* <p>Invokers provide a simple way of gaining access to internal class members
* in a target class without needing to resort to access transformers, and
* without the usual need to {@link Shadow} a target method. This can both
* greatly simplify mixins which <b>only</b> contain accessors, and provide for
* faster development than with access transformers since no re-decompile is
* needed to put the changes into effect.</p>
*
* <p>Invokers can be used in regular mixins as a way to provide access to a
* private method without needing to shadow and then manually proxy the method
* call. They can also be used to create <i>"Accessor Mixins"</i> which are
* special mixins defined as <tt>interface</tt>s which must <b>only</b> contain
* {@link Accessor} and {@link Invoker} methods. Unlike normal mixins however,
* <i>Accessor Mixins</i> are accessible via user code and thus no surrogate
* <i>"Duck"</i> interface is required to expose the generated methods, the
* mixin itself acts as its own Duck.</p>
*
* <ul><li>See also {@link Accessor}</li></ul>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
public @interface Invoker {
/**
* Normally the target method name is inflected by examining the annotated
* method name. If the annotated method starts with "call" or "invoke"
* followed by a capital letter, then the prefix is stripped and the
* remainder of the method name is used as the target method name.
*
* <p>However sometimes it maye be desirable to name an accessor method
* differently to the target method. In this case you may specify the method
* using its name.</p>
*
* @return name for the target method, or empty string to inflect using the
* annotated method name
*/
public String value() default "";
}
@@ -0,0 +1,65 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen;
import org.spongepowered.asm.lib.Type;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* Information about an invoker
*/
public class InvokerInfo extends AccessorInfo {
public InvokerInfo(MixinTargetContext mixin, MethodNode method) {
super(mixin, method, Invoker.class);
}
@Override
protected AccessorType initType() {
return AccessorType.METHOD_PROXY;
}
@Override
protected Type initTargetFieldType() {
return null;
}
@Override
protected MemberInfo initTarget() {
return new MemberInfo(this.getTargetName(), null, this.method.desc);
}
@Override
public void locate() {
this.targetMethod = this.findTargetMethod();
}
private MethodNode findTargetMethod() {
return this.<MethodNode>findTarget(this.classNode.methods);
}
}
@@ -0,0 +1,74 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.gen.throwables;
import org.spongepowered.asm.mixin.gen.AccessorInfo;
import org.spongepowered.asm.mixin.refmap.IReferenceMapperContext;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
/**
* Thrown when an accessor fails a state check
*/
public class InvalidAccessorException extends InvalidMixinException {
private static final long serialVersionUID = 2L;
private final AccessorInfo info;
public InvalidAccessorException(IReferenceMapperContext context, String message) {
super(context, message);
this.info = null;
}
public InvalidAccessorException(AccessorInfo info, String message) {
super(info.getContext(), message);
this.info = info;
}
public InvalidAccessorException(IReferenceMapperContext context, Throwable cause) {
super(context, cause);
this.info = null;
}
public InvalidAccessorException(AccessorInfo info, Throwable cause) {
super(info.getContext(), cause);
this.info = info;
}
public InvalidAccessorException(IReferenceMapperContext context, String message, Throwable cause) {
super(context, message, cause);
this.info = null;
}
public InvalidAccessorException(AccessorInfo info, String message, Throwable cause) {
super(info.getContext(), message, cause);
this.info = info;
}
public AccessorInfo getAccessorInfo() {
return this.info;
}
}
@@ -35,7 +35,6 @@ import java.util.Map.Entry;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.Final;
import org.spongepowered.asm.mixin.MixinEnvironment;
@@ -52,6 +51,7 @@ import org.spongepowered.asm.mixin.injection.Redirect;
import org.spongepowered.asm.mixin.injection.code.Injector;
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException;
import org.spongepowered.asm.mixin.struct.SpecialMethodInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.mixin.transformer.meta.MixinMerged;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
@@ -61,24 +61,7 @@ import org.spongepowered.asm.util.ASMHelper;
* Contructs information about an injection from an {@link Inject} annotation
* and allows the injection to be processed.
*/
public abstract class InjectionInfo {
protected final AnnotationNode annotation;
/**
* Class
*/
protected final ClassNode classNode;
/**
* Annotated method
*/
protected final MethodNode method;
/**
* Mixin data
*/
protected final MixinTargetContext mixin;
public abstract class InjectionInfo extends SpecialMethodInfo {
/**
* Annotated method is static
@@ -139,10 +122,7 @@ public abstract class InjectionInfo {
* @param annotation Annotation to parse
*/
protected InjectionInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
this.mixin = mixin;
this.method = method;
this.annotation = annotation;
this.classNode = mixin.getTargetClassNode();
super(mixin, method, annotation);
this.isStatic = ASMHelper.methodIsStatic(method);
this.readAnnotation();
}
@@ -287,42 +267,6 @@ public abstract class InjectionInfo {
return InjectionInfo.describeInjector(this.mixin, this.annotation, this.method);
}
/**
* Get the mixin target context for this injection
*
* @return the target context
*/
public MixinTargetContext getContext() {
return this.mixin;
}
/**
* Get the annotation which this InjectionInfo was created from
*
* @return The annotation which this InjectionInfo was created from
*/
public AnnotationNode getAnnotation() {
return this.annotation;
}
/**
* Get the class node for this injection
*
* @return the class containing the injector and the target
*/
public ClassNode getClassNode() {
return this.classNode;
}
/**
* Get method being called
*
* @return injector method
*/
public MethodNode getMethod() {
return this.method;
}
/**
* Get methods being injected into
*
@@ -127,6 +127,18 @@ public class MemberInfo {
this(name, owner, null, matchAll);
}
/**
* ctor
*
* @param name Member name, must not be null
* @param owner Member owner, can be null otherwise must be in internal form
* without L;
* @param desc Member descriptor, can be null
*/
public MemberInfo(String name, String owner, String desc) {
this(name, owner, desc, false);
}
/**
* ctor
*
@@ -429,7 +441,7 @@ public class MemberInfo {
* @param newOwner New owner for this member
*/
public MemberInfo move(String newOwner) {
if (newOwner.equals(this.owner)) {
if ((newOwner == null && this.owner == null) || (newOwner != null && newOwner.equals(this.owner))) {
return this;
}
return new MemberInfo(this, newOwner);
@@ -0,0 +1,100 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.struct;
import org.spongepowered.asm.lib.tree.AnnotationNode;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
/**
* Information about a special mixin method such as an injector or accessor
*/
public abstract class SpecialMethodInfo {
/**
* Annotation on the method
*/
protected final AnnotationNode annotation;
/**
* Class
*/
protected final ClassNode classNode;
/**
* Annotated method
*/
protected final MethodNode method;
/**
* Mixin data
*/
protected final MixinTargetContext mixin;
public SpecialMethodInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
this.mixin = mixin;
this.method = method;
this.annotation = annotation;
this.classNode = mixin.getTargetClassNode();
}
/**
* Get the mixin target context for this injection
*
* @return the target context
*/
public final MixinTargetContext getContext() {
return this.mixin;
}
/**
* Get the annotation which this InjectionInfo was created from
*
* @return The annotation which this InjectionInfo was created from
*/
public final AnnotationNode getAnnotation() {
return this.annotation;
}
/**
* Get the class node for this injection
*
* @return the class containing the injector and the target
*/
public final ClassNode getClassNode() {
return this.classNode;
}
/**
* Get method being called
*
* @return injector method
*/
public final MethodNode getMethod() {
return this.method;
}
}
@@ -48,6 +48,8 @@ import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.Mutable;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.Unique;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Member.Type;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
import org.spongepowered.asm.util.ASMHelper;
@@ -357,19 +359,26 @@ public class ClassInfo extends TreeInfo {
private final List<FrameData> frames;
private boolean isAccessor;
public Method(Member member) {
super(member);
this.frames = member instanceof Method ? ((Method)member).frames : null;
}
@SuppressWarnings("unchecked")
public Method(MethodNode method) {
this(method, false);
this.setUnique(ASMHelper.getVisibleAnnotation(method, Unique.class) != null);
this.isAccessor = ASMHelper.getSingleVisibleAnnotation(method, Accessor.class, Invoker.class) != null;
}
@SuppressWarnings("unchecked")
public Method(MethodNode method, boolean injected) {
super(Type.METHOD, method.name, method.desc, method.access, injected);
this.frames = this.gatherFrames(method);
this.setUnique(ASMHelper.getVisibleAnnotation(method, Unique.class) != null);
this.isAccessor = ASMHelper.getSingleVisibleAnnotation(method, Accessor.class, Invoker.class) != null;
}
public Method(String name, String desc) {
@@ -407,6 +416,10 @@ public class ClassInfo extends TreeInfo {
return ClassInfo.this;
}
public boolean isAccessor() {
return this.isAccessor;
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Method)) {
@@ -415,6 +428,7 @@ public class ClassInfo extends TreeInfo {
return super.equals(obj);
}
}
/**
@@ -37,7 +37,7 @@ import org.spongepowered.asm.mixin.transformer.throwables.InvalidInterfaceMixinE
* Applicator for interface mixins, mainly just disables things which aren't
* supported for interface mixins
*/
public class MixinApplicatorInterface extends MixinApplicatorStandard {
class MixinApplicatorInterface extends MixinApplicatorStandard {
/**
* ctor
@@ -68,7 +68,7 @@ import com.google.common.collect.ImmutableList;
/**
* Applies mixins to a target class
*/
public class MixinApplicatorStandard {
class MixinApplicatorStandard {
/**
* Annotations which can have constraints
@@ -289,6 +289,7 @@ public class MixinApplicatorStandard {
break;
case INJECT:
this.applyAccessors(mixin);
this.applyInjections(mixin);
break;
@@ -379,24 +380,32 @@ public class MixinApplicatorStandard {
*/
protected void applyMethods(MixinTargetContext mixin) {
for (MethodNode shadow : mixin.getShadowMethods()) {
MethodNode target = this.findTargetMethod(shadow);
if (target != null) {
this.mergeAnnotations(shadow, target);
}
this.applyShadowMethod(mixin, shadow);
}
for (MethodNode mixinMethod : mixin.getMethods()) {
// Reparent all mixin methods into the target class
mixin.transformMethod(mixinMethod);
this.applyNormalMethod(mixin, mixinMethod);
}
}
if (!mixinMethod.name.startsWith("<")) {
this.checkMethodVisibility(mixin, mixinMethod);
this.checkMethodConstraints(mixin, mixinMethod);
this.mergeMethod(mixin, mixinMethod);
} else if (Constants.CLINIT.equals(mixinMethod.name)) {
// Class initialiser insns get appended
this.appendInsns(mixinMethod);
}
protected void applyShadowMethod(MixinTargetContext mixin, MethodNode shadow) {
MethodNode target = this.findTargetMethod(shadow);
if (target != null) {
this.mergeAnnotations(shadow, target);
}
}
protected void applyNormalMethod(MixinTargetContext mixin, MethodNode mixinMethod) {
// Reparent all mixin methods into the target class
mixin.transformMethod(mixinMethod);
if (!mixinMethod.name.startsWith("<")) {
this.checkMethodVisibility(mixin, mixinMethod);
this.checkMethodConstraints(mixin, mixinMethod);
this.mergeMethod(mixin, mixinMethod);
} else if (Constants.CLINIT.equals(mixinMethod.name)) {
// Class initialiser insns get appended
this.appendInsns(mixinMethod);
}
}
@@ -860,6 +869,20 @@ public class MixinApplicatorStandard {
protected void applyInjections(MixinTargetContext mixin) {
mixin.applyInjections();
}
/**
* Apply all accessors discovered during preprocessing
*
* @param mixin Mixin being applied
*/
protected void applyAccessors(MixinTargetContext mixin) {
List<MethodNode> accessorMethods = mixin.generateAccessors();
for (MethodNode method : accessorMethods) {
if (!method.name.startsWith("<")) {
this.mergeMethod(mixin, method);
}
}
}
/**
* Check visibility before merging a mixin method
@@ -41,7 +41,10 @@ import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.launch.MixinInitialisationError;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
@@ -113,6 +116,11 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
*/
private final transient Set<String> syntheticInnerClasses = new HashSet<String>();
/**
* Accessor mixins in this set
*/
private final transient Set<String> passThroughClasses = new HashSet<String>();
/**
* Marshal
*/
@@ -475,6 +483,9 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
if (hotSwapper != null) {
hotSwapper.registerMixinClass(mixin.getClassName());
}
if (mixin.isLoadable()) {
this.passThroughClasses.add(mixin.getClassName());
}
this.mixins.add(mixin);
}
} catch (InvalidMixinException ex) {
@@ -673,14 +684,52 @@ class MixinConfig implements Comparable<MixinConfig>, IMixinConfig {
}
/**
* Get whether this config can allow passthrough for the specified class
* Get whether the specified class is a synthetic inner class for this
* config
*
* @param className Class name to check
* @return True if the specified class name is in this config's passthrough
* set
*/
public boolean canPassThrough(String className) {
return this.syntheticInnerClasses.contains(className);
return this.syntheticInnerClasses.contains(className) || this.passThroughClasses.contains(className);
}
public ClassNode passThrough(String className, ClassNode passThroughClassNode) {
if (this.syntheticInnerClasses.contains(className)) {
return this.passThroughSyntheticInner(passThroughClassNode);
}
return passThroughClassNode;
}
/**
* "Pass through" a synthetic inner class. Transforms package-private
* members in the class into public so that they are accessible from their
* new home in the target class
*
* @param classNode Class to pass through as tree
* @return transformed class
*/
private ClassNode passThroughSyntheticInner(ClassNode classNode) {
// Make the class public
classNode.access |= Opcodes.ACC_PUBLIC;
// Make package-private fields public
for (FieldNode field : classNode.fields) {
if ((field.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) {
field.access |= Opcodes.ACC_PUBLIC;
}
}
// Make package-private methods public
for (MethodNode method : classNode.methods) {
if ((method.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) {
method.access |= Opcodes.ACC_PUBLIC;
}
}
return classNode;
}
/**
@@ -25,6 +25,7 @@
package org.spongepowered.asm.mixin.transformer;
import java.io.IOException;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
@@ -57,6 +58,7 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.injection.Surrogate;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.throwables.InvalidMixinException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinReloadException;
import org.spongepowered.asm.mixin.transformer.throwables.MixinTargetAlreadyLoadedException;
@@ -100,7 +102,11 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
}
public boolean isSurrogate() {
return ASMHelper.getVisibleAnnotation(this, Surrogate.class) != null;
return this.getVisibleAnnotation(Surrogate.class) != null;
}
public AnnotationNode getVisibleAnnotation(Class<? extends Annotation> annotationClass) {
return ASMHelper.getVisibleAnnotation(this, annotationClass);
}
public AnnotationNode getInjectorAnnotation() {
@@ -277,7 +283,7 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
this.validateRemappables(targetClasses);
// Read information from the mixin
this.readImplementations();
this.readImplementations(type);
this.readInnerClasses();
// Takeoff validation
@@ -334,8 +340,9 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
/**
* Read and process any {@link Implements} annotations on the mixin
*/
void readImplementations() {
void readImplementations(SubType type) {
this.interfaces.addAll(this.classNode.interfaces);
this.interfaces.addAll(type.getInterfaces());
AnnotationNode implementsAnnotation = ASMHelper.getInvisibleAnnotation(this.classNode, Implements.class);
if (implementsAnnotation == null) {
@@ -454,6 +461,10 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
this.targetMustBeInterface = targetMustBeInterface;
}
Collection<String> getInterfaces() {
return Collections.<String>emptyList();
}
/**
* Get whether this mixin is detached super, must call {@link #validate}
* first
@@ -463,7 +474,16 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
boolean isDetachedSuper() {
return this.detached;
}
/**
* True if this mixin class can actually be classloaded
*
* @return
*/
boolean isLoadable() {
return false;
}
/**
* Validate a single target before adding
*
@@ -555,7 +575,74 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
MixinPreProcessorStandard createPreProcessor(MixinClassNode classNode) {
return new MixinPreProcessorInterface(this.mixin, classNode);
}
}
/**
* An accessor mixin
*/
static class Accessor extends SubType {
private final Collection<String> interfaces = new ArrayList<String>();
Accessor(MixinInfo info) {
super(info, "@Mixin", false);
this.interfaces.add(info.getClassRef());
}
@Override
boolean isLoadable() {
return true;
}
@Override
Collection<String> getInterfaces() {
return this.interfaces;
}
@Override
void validateTarget(String targetName, ClassInfo targetInfo) {
boolean targetIsInterface = targetInfo.isInterface();
if (targetIsInterface && !MixinEnvironment.getCompatibilityLevel().supportsMethodsInInterfaces()) {
throw new InvalidMixinException(this.mixin, "Accessor mixin targetting an interface is not supported in current enviromnment");
}
}
@Override
void validate(State state, List<ClassInfo> targetClasses) {
ClassNode classNode = state.getClassNode();
if (!"java/lang/Object".equals(classNode.superName)) {
throw new InvalidMixinException(this.mixin, "Super class of " + this + " is invalid, found "
+ classNode.superName.replace('/', '.'));
}
}
@Override
MixinPreProcessorStandard createPreProcessor(MixinClassNode classNode) {
return new MixinPreProcessorAccessor(this.mixin, classNode);
}
}
static SubType getTypeFor(MixinInfo mixin) {
if (!mixin.getClassInfo().isInterface()) {
return new SubType.Standard(mixin);
}
boolean containsNonAccessorMethod = false;
for (Method method : mixin.getClassInfo().getMethods()) {
containsNonAccessorMethod |= !method.isAccessor();
}
if (containsNonAccessorMethod) {
// If the mixin contains any other methods, treat it as a regular interface mixin
return new SubType.Interface(mixin);
}
// The mixin contains no non-accessor methods, so we can treat it as an accessor
return new SubType.Accessor(mixin);
}
}
/**
@@ -666,13 +753,20 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
byte[] mixinBytes = this.loadMixinClass(this.className, runTransformers);
this.pendingState = new State(mixinBytes);
this.info = this.pendingState.getClassInfo();
this.type = this.initType();
this.type = SubType.getTypeFor(this);
} catch (InvalidMixinException ex) {
throw ex;
} catch (Exception ex) {
throw new InvalidMixinException(this, ex);
}
if (!this.type.isLoadable()) {
// Inject the mixin class name into the LaunchClassLoader's invalid
// classes set so that any classes referencing the mixin directly will
// cause the game to crash
MixinInfo.classLoaderUtil.registerInvalidClass(this.className);
}
// Read the class bytes and transform
try {
this.priority = this.readPriority(this.pendingState.getClassNode());
@@ -684,18 +778,6 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
throw new InvalidMixinException(this, ex);
}
}
/**
* Initialise the mixin subtype handler
*
* @return subtype
*/
private SubType initType() {
if (this.info.isInterface()) {
return new SubType.Interface(this);
}
return new SubType.Standard(this);
}
/**
* Run validation pass
@@ -910,6 +992,13 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
return this.getState().isUnique();
}
/**
* True if the mixin class is actually class-loadable
*/
public boolean isLoadable() {
return this.type.isLoadable();
}
/**
* Get the logging level for this mixin
*/
@@ -1000,11 +1089,6 @@ class MixinInfo extends TreeInfo implements Comparable<MixinInfo>, IMixinInfo {
throw new InvalidMixinException(this, "An error was encountered whilst loading the mixin class", ex);
}
// Inject the mixin class name into the LaunchClassLoader's invalid
// classes set so that any classes referencing the mixin directly will
// cause the game to crash
MixinInfo.classLoaderUtil.registerInvalidClass(mixinClassName);
return mixinBytes;
}
@@ -0,0 +1,38 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.transformer;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
/**
* Bytecode preprocessor for accessor mixins
*/
class MixinPreProcessorAccessor extends MixinPreProcessorInterface {
public MixinPreProcessorAccessor(MixinInfo mixin, MixinClassNode classNode) {
super(mixin, classNode);
}
}
@@ -40,6 +40,9 @@ import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.Overwrite;
import org.spongepowered.asm.mixin.Shadow;
import org.spongepowered.asm.mixin.gen.Accessor;
import org.spongepowered.asm.mixin.gen.Invoker;
import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Field;
import org.spongepowered.asm.mixin.transformer.ClassInfo.Method;
import org.spongepowered.asm.mixin.transformer.MixinInfo.MixinClassNode;
@@ -208,26 +211,30 @@ class MixinPreProcessorStandard {
continue;
}
if (mixinMethod.isInjector()) {
if (this.attachInjectorMethod(context, mixinMethod)) {
continue;
}
if (this.processShadowMethod(context, mixinMethod)) {
iter.remove();
context.addShadowMethod(mixinMethod);
continue;
}
if (this.processOverwriteMethod(context, mixinMethod)) {
continue;
}
if (this.processUniqueMethod(context, mixinMethod)) {
if (this.attachAccessorMethod(context, mixinMethod)) {
iter.remove();
continue;
}
this.processMethod(mixinMethod);
if (this.attachShadowMethod(context, mixinMethod)) {
iter.remove();
continue;
}
if (this.attachOverwriteMethod(context, mixinMethod)) {
continue;
}
if (this.attachUniqueMethod(context, mixinMethod)) {
iter.remove();
continue;
}
this.attachMethod(mixinMethod);
}
}
@@ -235,33 +242,60 @@ class MixinPreProcessorStandard {
return true;
}
protected boolean processShadowMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
return this.processSpecialMethod(context, mixinMethod, Shadow.class, false);
protected boolean attachInjectorMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
return mixinMethod.isInjector();
}
protected boolean processOverwriteMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
return this.processSpecialMethod(context, mixinMethod, Overwrite.class, true);
protected boolean attachAccessorMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
return this.attachAccessorMethod(context, mixinMethod, Accessor.class) || this.attachAccessorMethod(context, mixinMethod, Invoker.class);
}
protected boolean processSpecialMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class<? extends Annotation> type,
boolean overwrite) {
AnnotationNode annotation = ASMHelper.getVisibleAnnotation(mixinMethod, type);
private boolean attachAccessorMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class<? extends Annotation> type) {
AnnotationNode annotation = mixinMethod.getVisibleAnnotation(type);
if (annotation == null) {
return false;
}
if (this.mixin.isUnique() && overwrite) {
throw new InvalidMixinException(this.mixin, "@Overwrite method " + mixinMethod.name + " found in a @Unique mixin");
Method method = this.getSpecialMethod(mixinMethod, type);
if (!method.isAbstract()) {
throw new InvalidAccessorException(context, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " is not abstract");
}
if (method.isStatic()) {
throw new InvalidAccessorException(context, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " cannot be static");
}
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL);
context.addAccessorMethod(mixinMethod, type);
return true;
}
protected boolean attachShadowMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
if (this.attachSpecialMethod(context, mixinMethod, Shadow.class, false)) {
context.addShadowMethod(mixinMethod);
return true;
}
return false;
}
protected boolean attachOverwriteMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
return this.attachSpecialMethod(context, mixinMethod, Overwrite.class, true);
}
protected boolean attachSpecialMethod(MixinTargetContext context, MixinMethodNode mixinMethod, Class<? extends Annotation> type,
boolean overwrite) {
AnnotationNode annotation = mixinMethod.getVisibleAnnotation(type);
if (annotation == null) {
return false;
}
if (overwrite) {
this.checkMixinNotUnique(mixinMethod, type);
}
Method method = this.getSpecialMethod(mixinMethod, type);
MethodNode target = context.findMethod(mixinMethod, annotation);
if (method.isUnique()) {
throw new InvalidMixinException(this.mixin, "@" + ASMHelper.getSimpleName(type) + " method " + mixinMethod.name + " cannot be @Unique");
}
if (target == null) {
if (overwrite) {
return false;
@@ -275,7 +309,7 @@ class MixinPreProcessorStandard {
}
if (Constants.CTOR.equals(target.name)) {
throw new InvalidMixinException(this.mixin, "Nice try! Cannot alias a constructor!");
throw new InvalidMixinException(this.mixin, "Nice try! " + mixinMethod.name + " cannot alias a constructor!");
}
if (!target.name.equals(mixinMethod.name)) {
@@ -289,7 +323,27 @@ class MixinPreProcessorStandard {
return true;
}
protected boolean processUniqueMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
protected Method getSpecialMethod(MixinMethodNode mixinMethod, Class<? extends Annotation> type) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL);
this.checkMethodNotUnique(type, method);
return method;
}
protected void checkMethodNotUnique(Class<? extends Annotation> type, Method method) {
if (method.isUnique()) {
String annotation = "@" + ASMHelper.getSimpleName(type);
throw new InvalidMixinException(this.mixin, annotation + " method " + method.getName() + " cannot be @Unique");
}
}
protected void checkMixinNotUnique(MixinMethodNode mixinMethod, Class<? extends Annotation> type) {
if (this.mixin.isUnique()) {
String annotation = "@" + ASMHelper.getSimpleName(type);
throw new InvalidMixinException(this.mixin, annotation + " method " + mixinMethod.name + " found in a @Unique mixin");
}
}
protected boolean attachUniqueMethod(MixinTargetContext context, MixinMethodNode mixinMethod) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod, ClassInfo.INCLUDE_ALL);
if (method == null || (!method.isUnique() && !this.mixin.isUnique())) {
return false;
@@ -319,7 +373,7 @@ class MixinPreProcessorStandard {
return true;
}
protected void processMethod(MixinMethodNode mixinMethod) {
protected void attachMethod(MixinMethodNode mixinMethod) {
Method method = this.mixin.getClassInfo().findMethod(mixinMethod);
if (method == null) {
return;
@@ -24,6 +24,7 @@
*/
package org.spongepowered.asm.mixin.transformer;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
@@ -47,6 +48,7 @@ import org.spongepowered.asm.mixin.MixinEnvironment.CompatibilityLevel;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.SoftOverride;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.gen.AccessorInfo;
import org.spongepowered.asm.mixin.injection.Inject;
import org.spongepowered.asm.mixin.injection.InjectorGroupInfo;
import org.spongepowered.asm.mixin.injection.struct.InjectionInfo;
@@ -128,7 +130,12 @@ public class MixinTargetContext implements IReferenceMapperContext {
* Injectors for this target
*/
private final List<InjectionInfo> injectors = new ArrayList<InjectionInfo>();
/**
* Accessor method list
*/
private final List<AccessorInfo> accessors = new ArrayList<AccessorInfo>();
/**
* True if this mixin inherits from a mixin at any point in its hierarchy
*/
@@ -178,6 +185,13 @@ public class MixinTargetContext implements IReferenceMapperContext {
this.shadowFields.put(fieldNode, fieldInfo);
}
/**
* @param method
*/
void addAccessorMethod(MethodNode method, Class<? extends Annotation> type) {
this.accessors.add(AccessorInfo.of(this, method, type));
}
/**
* Callback from the applicator which notifies us that a method was merged
*
@@ -1016,4 +1030,17 @@ public class MixinTargetContext implements IReferenceMapperContext {
this.injectors.clear();
}
public List<MethodNode> generateAccessors() {
for (AccessorInfo accessor : this.accessors) {
accessor.locate();
}
List<MethodNode> methods = new ArrayList<MethodNode>();
for (AccessorInfo accessor : this.accessors) {
methods.add(accessor.generate());
}
return methods;
}
}
@@ -43,10 +43,7 @@ import org.apache.commons.io.FileUtils;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.spongepowered.asm.lib.Opcodes;
import org.spongepowered.asm.lib.tree.ClassNode;
import org.spongepowered.asm.lib.tree.FieldNode;
import org.spongepowered.asm.lib.tree.MethodNode;
import org.spongepowered.asm.mixin.MixinEnvironment;
import org.spongepowered.asm.mixin.MixinEnvironment.Option;
import org.spongepowered.asm.mixin.MixinEnvironment.Phase;
@@ -55,11 +52,11 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfig;
import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin;
import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler;
import org.spongepowered.asm.mixin.extensibility.IMixinErrorHandler.ErrorAction;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.throwables.ClassAlreadyLoadedException;
import org.spongepowered.asm.mixin.throwables.MixinApplyError;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.mixin.throwables.MixinPrepareError;
import org.spongepowered.asm.mixin.extensibility.IMixinInfo;
import org.spongepowered.asm.mixin.transformer.MixinTransformerModuleCheckClass.ValidationFailedException;
import org.spongepowered.asm.mixin.transformer.debug.IDecompiler;
import org.spongepowered.asm.mixin.transformer.debug.IHotSwap;
@@ -492,7 +489,7 @@ public class MixinTransformer extends TreeTransformer {
for (MixinConfig config : this.configs) {
if (config.packageMatch(transformedName)) {
if (config.canPassThrough(transformedName)) {
return this.passThrough(name, transformedName, basicClass);
return this.passThrough(config, name, transformedName, basicClass);
}
invalidRef = true;
continue;
@@ -678,36 +675,18 @@ public class MixinTransformer extends TreeTransformer {
}
/**
* "Pass through" a synthetic inner class. Transforms package-private
* members in the class into public so that they are accessible from their
* new home in the target class
* Pass a class through a specific config, used to access classes within a
* mixin package through a pinhole
*
* @param config
* @param name original class name
* @param transformedName deobfuscated class name
* @param basicClass class bytecode
* @return public-ified class bytecode
*/
private byte[] passThrough(String name, String transformedName, byte[] basicClass) {
ClassNode passThroughClass = this.readClass(basicClass, true);
// Make the class public
passThroughClass.access |= Opcodes.ACC_PUBLIC;
// Make package-private fields public
for (FieldNode field : passThroughClass.fields) {
if ((field.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) {
field.access |= Opcodes.ACC_PUBLIC;
}
}
// Make package-private methods public
for (MethodNode method : passThroughClass.methods) {
if ((method.access & (Opcodes.ACC_PRIVATE | Opcodes.ACC_PROTECTED)) == 0) {
method.access |= Opcodes.ACC_PUBLIC;
}
}
return this.writeClass(transformedName, passThroughClass, false);
private byte[] passThrough(MixinConfig config, String name, String transformedName, byte[] basicClass) {
ClassNode classNode = config.passThrough(transformedName, this.readClass(basicClass, true));
return this.writeClass(transformedName, classNode, false);
}
/**
@@ -29,14 +29,12 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.transformer.MixinApplicatorStandard;
/**
* <p><b>For internal use only!</b> Contains small parts. Keep out of reach of
* children.</p>
*
* <p>Decoration annotation used by the {@link MixinApplicatorStandard} to mark
* methods in a class which have been added or overwritten by a mixin.</p>
* <p>Decoration annotation used by the mixin applicator to mark methods in a
* class which have been added or overwritten by a mixin.</p>
*/
@Target({ ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)