diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 15405303..5713f306 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -36,11 +36,21 @@ import javax.lang.model.type.DeclaredType; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; +import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.Mixin; import org.spongepowered.asm.mixin.Pseudo; +import org.spongepowered.asm.mixin.MixinEnvironment.Option; +import org.spongepowered.asm.mixin.extensibility.IMixinInfo; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.injection.struct.SelectorAnnotationContext; +import org.spongepowered.asm.mixin.injection.struct.Target; +import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.refmap.ReferenceMapper; +import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementAccessor; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerAccessor.AnnotatedElementInvoker; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjectionPoint; +import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementSliceInjectionPoint; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerInjector.AnnotatedElementInjector; import org.spongepowered.tools.obfuscation.AnnotatedMixinElementHandlerOverwrite.AnnotatedElementOverwrite; import org.spongepowered.tools.obfuscation.interfaces.IMessagerSuppressible; @@ -55,10 +65,12 @@ import org.spongepowered.tools.obfuscation.mirror.TypeHandle; import org.spongepowered.tools.obfuscation.mirror.TypeUtils; import org.spongepowered.tools.obfuscation.struct.InjectorRemap; +import com.google.common.base.Strings; + /** * Information about a mixin stored during processing */ -class AnnotatedMixin { +class AnnotatedMixin implements IMixinContext { /** * Mixin annotation @@ -289,7 +301,7 @@ class AnnotatedMixin { /** * Get the mixin class */ - public TypeElement getMixin() { + public TypeElement getMixinElement() { return this.mixin; } @@ -303,6 +315,7 @@ class AnnotatedMixin { /** * Get the mixin class reference */ + @Override public String getClassRef() { return this.classRef; } @@ -368,46 +381,100 @@ class AnnotatedMixin { } public void registerInjector(ExecutableElement method, AnnotationHandle inject, InjectorRemap remap) { + System.err.printf(">>> %s\n", method); this.methods.remove(method); - this.injectors.registerInjector(new AnnotatedElementInjector(method, inject, remap)); + AnnotatedElementInjector injectorElement = new AnnotatedElementInjector(method, inject, this, remap); + this.injectors.registerInjector(injectorElement); List ats = inject.getAnnotationList("at"); for (AnnotationHandle at : ats) { - this.registerInjectionPoint(method, inject, at, remap, "@At(%s)"); + this.registerInjectionPoint(method, inject, "at", at, remap, "@At(%s)"); } List slices = inject.getAnnotationList("slice"); for (AnnotationHandle slice : slices) { String id = slice.getValue("id", ""); + String coord = "slice"; + if (!Strings.isNullOrEmpty(id)) { + coord += "." + id; + } + SelectorAnnotationContext sliceContext = new SelectorAnnotationContext(injectorElement, slice, coord); AnnotationHandle from = slice.getAnnotation("from"); if (from != null) { - this.registerInjectionPoint(method, inject, from, remap, "@Slice[" + id + "](from=@At(%s))"); + this.registerSliceInjectionPoint(method, inject, "from", from, remap, "@Slice[" + id + "](from=@At(%s))", sliceContext); } AnnotationHandle to = slice.getAnnotation("to"); if (to != null) { - this.registerInjectionPoint(method, inject, to, remap, "@Slice[" + id + "](to=@At(%s))"); + this.registerSliceInjectionPoint(method, inject, "to", to, remap, "@Slice[" + id + "](to=@At(%s))", sliceContext); } } } - public void registerInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at, InjectorRemap remap, String format) { - this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, at, remap), format); + public void registerInjectionPoint(ExecutableElement element, AnnotationHandle inject, String selectorCoordinate, AnnotationHandle at, + InjectorRemap remap, String format) { + this.injectors.registerInjectionPoint(new AnnotatedElementInjectionPoint(element, inject, this, selectorCoordinate, at, remap), format); } + public void registerSliceInjectionPoint(ExecutableElement element, AnnotationHandle inject, String selectorCoordinate, AnnotationHandle at, + InjectorRemap remap, String format, ISelectorContext parentContext) { + this.injectors.registerInjectionPoint(new AnnotatedElementSliceInjectionPoint(element, inject, this, selectorCoordinate, at, remap, + parentContext), format); + } + public void registerAccessor(ExecutableElement element, AnnotationHandle accessor, boolean shouldRemap) { this.methods.remove(element); - this.accessors.registerAccessor(new AnnotatedElementAccessor(element, accessor, shouldRemap)); + this.accessors.registerAccessor(new AnnotatedElementAccessor(element, accessor, this, shouldRemap)); } public void registerInvoker(ExecutableElement element, AnnotationHandle invoker, boolean shouldRemap) { this.methods.remove(element); - this.accessors.registerAccessor(new AnnotatedElementInvoker(element, invoker, shouldRemap)); + this.accessors.registerAccessor(new AnnotatedElementInvoker(element, invoker, this, shouldRemap)); } public void registerSoftImplements(AnnotationHandle implementsAnnotation) { this.softImplements.process(implementsAnnotation); } + @Override + public ReferenceMapper getReferenceMapper() { + return null; + } + + @Override + public String getClassName() { + return this.getClassRef().replace('/', '.'); + } + + @Override + public String getTargetClassRef() { + throw new UnsupportedOperationException("Target class not available at compile time"); + } + + @Override + public IMixinInfo getMixin() { + throw new UnsupportedOperationException("MixinInfo not available at compile time"); + } + + @Override + public Extensions getExtensions() { + throw new UnsupportedOperationException("Mixin Extensions not available at compile time"); + } + + @Override + public boolean getOption(Option option) { + throw new UnsupportedOperationException("Options not available at compile time"); + } + + @Override + public int getPriority() { + throw new UnsupportedOperationException("Priority not available at compile time"); + } + + @Override + public Target getTargetMethod(MethodNode into) { + throw new UnsupportedOperationException("Target not available at compile time"); + } + } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 6517e6c1..433fba93 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -33,8 +33,10 @@ import javax.lang.model.element.VariableElement; import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; +import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; @@ -104,6 +106,50 @@ abstract class AnnotatedMixinElementHandler { } + abstract static class AnnotatedElementExecutable extends AnnotatedElement implements ISelectorContext { + + private final IMixinContext context; + + private final String selectorCoordinate; + + public AnnotatedElementExecutable(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, String selectorCoordinate) { + super(element, annotation); + this.context = context; + this.selectorCoordinate = selectorCoordinate; + } + + @Override + public ISelectorContext getParent() { + return null; + } + + @Override + public IMixinContext getMixin() { + return this.context; + } + + @Override + public Object getMethod() { + return this.getElement(); + } + + @Override + public Object getSelectorAnnotation() { + return this.getAnnotation(); + } + + @Override + public String getSelectorCoordinate() { + return this.selectorCoordinate; + } + + @Override + public String remap(String reference) { + return reference; + } + + } + /** * A name of an element which may have aliases */ diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java index b65d3a9e..e3e75e19 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerAccessor.java @@ -30,18 +30,12 @@ import javax.lang.model.type.TypeKind; import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; -import org.objectweb.asm.tree.MethodNode; -import org.spongepowered.asm.mixin.MixinEnvironment.Option; -import org.spongepowered.asm.mixin.extensibility.IMixinInfo; import org.spongepowered.asm.mixin.gen.AccessorInfo; import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorName; import org.spongepowered.asm.mixin.gen.AccessorInfo.AccessorType; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.injection.struct.Target; import org.spongepowered.asm.mixin.refmap.IMixinContext; -import org.spongepowered.asm.mixin.refmap.ReferenceMapper; -import org.spongepowered.asm.mixin.transformer.ext.Extensions; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.Constants; @@ -60,21 +54,21 @@ import com.google.common.base.Strings; /** * A module for {@link AnnotatedMixin} which handles accessors */ -public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler implements IMixinContext { +public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler { /** * Accessor element */ - static class AnnotatedElementAccessor extends AnnotatedElement { + static class AnnotatedElementAccessor extends AnnotatedElementExecutable { protected final boolean shouldRemap; - + protected final TypeMirror returnType; protected String targetName; - public AnnotatedElementAccessor(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) { - super(element, annotation); + public AnnotatedElementAccessor(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, boolean shouldRemap) { + super(element, annotation, context, "value"); this.shouldRemap = shouldRemap; this.returnType = this.getElement().getReturnType(); } @@ -147,8 +141,8 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH private AccessorType type = AccessorType.METHOD_PROXY; - public AnnotatedElementInvoker(ExecutableElement element, AnnotationHandle annotation, boolean shouldRemap) { - super(element, annotation, shouldRemap); + public AnnotatedElementInvoker(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, boolean shouldRemap) { + super(element, annotation, context, shouldRemap); } @Override @@ -201,56 +195,11 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH } } - + public AnnotatedMixinElementHandlerAccessor(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); } - @Override - public ReferenceMapper getReferenceMapper() { - return null; - } - - @Override - public String getClassName() { - return this.mixin.getClassRef().replace('/', '.'); - } - - @Override - public String getClassRef() { - return this.mixin.getClassRef(); - } - - @Override - public String getTargetClassRef() { - throw new UnsupportedOperationException("Target class not available at compile time"); - } - - @Override - public IMixinInfo getMixin() { - throw new UnsupportedOperationException("MixinInfo not available at compile time"); - } - - @Override - public Extensions getExtensions() { - throw new UnsupportedOperationException("Mixin Extensions not available at compile time"); - } - - @Override - public boolean getOption(Option option) { - throw new UnsupportedOperationException("Options not available at compile time"); - } - - @Override - public int getPriority() { - throw new UnsupportedOperationException("Priority not available at compile time"); - } - - @Override - public Target getTargetMethod(MethodNode into) { - throw new UnsupportedOperationException("Target not available at compile time"); - } - /** * Register a new accessor * @@ -387,7 +336,7 @@ public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementH } private String inflectAccessorTarget(AnnotatedElementAccessor elem) { - return AccessorInfo.inflectTarget(elem.getSimpleName(), elem.getAccessorType(), "", this, false); + return AccessorInfo.inflectTarget(elem.getSimpleName(), elem.getAccessorType(), "", elem, false); } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index afd76ceb..fdd02a6c 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -35,6 +35,7 @@ import javax.tools.Diagnostic; import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.injection.Coerce; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor; @@ -42,6 +43,7 @@ import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; +import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException; @@ -61,12 +63,12 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler /** * Injector element */ - static class AnnotatedElementInjector extends AnnotatedElement { + static class AnnotatedElementInjector extends AnnotatedElementExecutable { private final InjectorRemap state; - public AnnotatedElementInjector(ExecutableElement element, AnnotationHandle annotation, InjectorRemap shouldRemap) { - super(element, annotation); + public AnnotatedElementInjector(ExecutableElement element, AnnotationHandle annotation, IMixinContext context, InjectorRemap shouldRemap) { + super(element, annotation, context, "method"); this.state = shouldRemap; } @@ -100,7 +102,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler /** * Injection point element */ - static class AnnotatedElementInjectionPoint extends AnnotatedElement { + static class AnnotatedElementInjectionPoint extends AnnotatedElementExecutable { private final AnnotationHandle at; @@ -108,8 +110,9 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler private final InjectorRemap state; - public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, AnnotationHandle at, InjectorRemap state) { - super(element, inject); + public AnnotatedElementInjectionPoint(ExecutableElement element, AnnotationHandle inject, IMixinContext context, String selectorCoordinate, + AnnotationHandle at, InjectorRemap state) { + super(element, inject, context, selectorCoordinate); this.at = at; this.state = state; } @@ -122,6 +125,11 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return this.at; } + @Override + public Object getSelectorAnnotation() { + return this.getAt(); + } + public String getAtArg(String key) { if (this.args == null) { this.args = new HashMap(); @@ -147,6 +155,23 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } + static class AnnotatedElementSliceInjectionPoint extends AnnotatedElementInjectionPoint { + + private final ISelectorContext parentContext; + + public AnnotatedElementSliceInjectionPoint(ExecutableElement element, AnnotationHandle inject, IMixinContext context, + String selectorCoordinate, AnnotationHandle at, InjectorRemap state, ISelectorContext parentContext) { + super(element, inject, context, selectorCoordinate, at, state); + this.parentContext = parentContext; + } + + @Override + public ISelectorContext getParent() { + return this.parentContext; + } + + } + AnnotatedMixinElementHandlerInjector(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) { super(ap, mixin); } @@ -157,7 +182,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } for (String reference : elem.getAnnotation().getList("method")) { - ITargetSelector targetSelector = TargetSelector.parse(reference); + ITargetSelector targetSelector = TargetSelector.parse(reference, elem); try { targetSelector.validate(); @@ -231,8 +256,8 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler String conflictType = this.mixin.isMultiTarget() ? "Multi-target" : "Target"; if (elem.hasCoerceArgument() && targetMember.getOwner() == null && targetMember.getDesc() == null) { - ITargetSelector oldMember = TargetSelector.parse(ex.getOld()); - ITargetSelector newMember = TargetSelector.parse(ex.getNew()); + ITargetSelector oldMember = TargetSelector.parse(ex.getOld(), elem); + ITargetSelector newMember = TargetSelector.parse(ex.getNew(), elem); String oldName = oldMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)oldMember).getName() : oldMember.toString(); String newName = newMember instanceof ITargetSelectorByName ? ((ITargetSelectorByName)newMember).getName() : newMember.toString(); if (oldName != null && oldName.equals(newName)) { @@ -284,7 +309,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return; } - ITargetSelector selector = TargetSelector.parse(reference); + ITargetSelector selector = TargetSelector.parse(reference, elem); if (selector instanceof ITargetSelectorConstructor) { ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector; String target = member.toCtorType(); @@ -321,7 +346,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler return; } - ITargetSelector targetSelector = TargetSelector.parse(reference); + ITargetSelector targetSelector = TargetSelector.parse(reference, elem); if (!(targetSelector instanceof ITargetSelectorRemappable)) { return; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java index 537da970..330494ed 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerSoftImplements.java @@ -67,7 +67,7 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl // Derp? if (interfaces.size() < 1) { - this.ap.printMessage(Kind.WARNING, "Empty @Implements annotation", this.mixin.getMixin(), implementsAnnotation.asMirror()); + this.ap.printMessage(Kind.WARNING, "Empty @Implements annotation", this.mixin.getMixinElement(), implementsAnnotation.asMirror()); return; } @@ -82,8 +82,8 @@ public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinEl String prefix = interfaceAnnotation.getValue("prefix"); this.processSoftImplements(remap, iface, prefix); } catch (Exception ex) { - this.ap.printMessage(Kind.ERROR, "Unexpected error: " + ex.getClass().getName() + ": " + ex.getMessage(), this.mixin.getMixin(), - interfaceAnnotation.asMirror()); + this.ap.printMessage(Kind.ERROR, "Unexpected error: " + ex.getClass().getName() + ": " + ex.getMessage(), + this.mixin.getMixinElement(), interfaceAnnotation.asMirror()); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java index 71afb97d..469226cf 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java @@ -36,13 +36,15 @@ import javax.lang.model.element.ExecutableElement; import javax.lang.model.element.TypeElement; import javax.lang.model.element.VariableElement; +import org.spongepowered.asm.util.asm.IAnnotationHandle; + import com.google.common.collect.ImmutableList; /** * A wrapper for {@link AnnotationMirror} which provides a more convenient way * to access annotation values. */ -public final class AnnotationHandle { +public final class AnnotationHandle implements IAnnotationHandle { public static final AnnotationHandle MISSING = new AnnotationHandle(null); @@ -79,6 +81,17 @@ public final class AnnotationHandle { return this.annotation != null; } + /* (non-Javadoc) + * @see org.spongepowered.asm.util.asm.IAnnotationHandle#getDesc() + */ + @Override + public String getDesc() { + if (this.annotation == null) { + return "java/lang/Annotation"; + } + return TypeUtils.getInternalName(this.annotation.getAnnotationType()); + } + @Override public String toString() { if (this.annotation == null) { diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java index e11bded5..deee0838 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGenerator.java @@ -55,7 +55,7 @@ public abstract class AccessorGenerator { protected void checkModifiers() { if (this.info.isStatic() && !this.targetIsStatic) { - IMixinContext context = this.info.getContext(); + IMixinContext context = this.info.getMixin(); throw new InvalidInjectionException(context, String.format("%s is invalid. Accessor method is%s static but the target is not.", this.info, this.info.isStatic() ? "" : " not")); } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java index cee3d330..0dad09c5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorFieldSetter.java @@ -60,9 +60,9 @@ public class AccessorGeneratorFieldSetter extends AccessorGeneratorField { return; } - if (this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) { LogManager.getLogger("mixin").warn("{} for final field {}::{} is not @Mutable", this.info, - ((MixinTargetContext)this.info.getContext()).getTarget(), this.targetField.name); + ((MixinTargetContext)this.info.getMixin()).getTarget(), this.targetField.name); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java index 5c09ad4f..bcbc16ff 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorGeneratorObjectFactory.java @@ -41,7 +41,7 @@ public class AccessorGeneratorObjectFactory extends AccessorGeneratorMethodProxy public AccessorGeneratorObjectFactory(AccessorInfo info) { super(info, true); if (!info.isStatic()) { - throw new InvalidInjectionException(info.getContext(), String.format("%s is invalid. Factory method must be static.", this.info)); + throw new InvalidInjectionException(info.getMixin(), String.format("%s is invalid. Factory method must be static.", this.info)); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java index 3e9000df..32dee538 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -39,11 +39,11 @@ import org.objectweb.asm.tree.FieldNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; @@ -344,7 +344,7 @@ public class AccessorInfo extends SpecialMethodInfo { } return inflectedTarget; } - return TargetSelector.parseName(name, this.mixin); + return TargetSelector.parseName(name, this); } /** @@ -354,7 +354,7 @@ public class AccessorInfo extends SpecialMethodInfo { * foo for example. */ protected String inflectTarget() { - return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this.mixin, + return AccessorInfo.inflectTarget(this.method.name, this.type, this.toString(), this, this.mixin.getEnvironment().getOption(Option.DEBUG_VERBOSE)); } @@ -375,7 +375,7 @@ public class AccessorInfo extends SpecialMethodInfo { * @return inflected target member name or null if name cannot be * inflected */ - public static String inflectTarget(String name, AccessorType type, String description, IMixinContext context, boolean verbose) { + public static String inflectTarget(String name, AccessorType type, String description, ISelectorContext context, boolean verbose) { return AccessorInfo.inflectTarget(AccessorName.of(name), type, description, context, verbose); } @@ -396,7 +396,7 @@ public class AccessorInfo extends SpecialMethodInfo { * @return inflected target member name or null if name cannot be * inflected */ - public static String inflectTarget(AccessorName name, AccessorType type, String description, IMixinContext context, boolean verbose) { + public static String inflectTarget(AccessorName name, AccessorType type, String description, ISelectorContext context, boolean verbose) { if (name != null) { if (!type.isExpectedPrefix(name.prefix) && verbose) { LogManager.getLogger("mixin").warn("Unexpected prefix for {}, found [{}] expecting {}", description, name.prefix, diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java index 85d48c85..e7541e74 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/throwables/InvalidAccessorException.java @@ -43,7 +43,7 @@ public class InvalidAccessorException extends InvalidMixinException { } public InvalidAccessorException(AccessorInfo info, String message) { - super(info.getContext(), message); + super(info.getMixin(), message); this.info = info; } @@ -53,7 +53,7 @@ public class InvalidAccessorException extends InvalidMixinException { } public InvalidAccessorException(AccessorInfo info, Throwable cause) { - super(info.getContext(), cause); + super(info.getMixin(), cause); this.info = info; } @@ -63,7 +63,7 @@ public class InvalidAccessorException extends InvalidMixinException { } public InvalidAccessorException(AccessorInfo info, String message, Throwable cause) { - super(info.getContext(), message, cause); + super(info.getMixin(), message, cause); this.info = info; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java index b98dcad7..f13199f5 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/IInjectionPointContext.java @@ -26,28 +26,31 @@ package org.spongepowered.asm.mixin.injection; import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; -import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.util.IMessageSink; /** * Context for an injection point, used to access the mixin as well as the owner * method and annotation for the injection point */ -public interface IInjectionPointContext extends IMessageSink { - - /** - * Get the mixin context for this injection - */ - public abstract IMixinContext getContext(); +public interface IInjectionPointContext extends IMessageSink, ISelectorContext { /** * Get the injection handler method */ + @Override public abstract MethodNode getMethod(); /** * Get the parent annotation (eg. the @Inject annotation) */ + @Override public abstract AnnotationNode getAnnotation(); - + + /** + * Get the selector annotation (eg. the @At annotation) + */ + @Override + public abstract AnnotationNode getSelectorAnnotation(); + } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java index 33ecc1b0..e30de0af 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -30,6 +30,7 @@ import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import java.lang.reflect.Array; import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; @@ -50,6 +51,7 @@ import org.spongepowered.asm.mixin.injection.callback.CallbackInjector; import org.spongepowered.asm.mixin.injection.modify.AfterStoreLocal; import org.spongepowered.asm.mixin.injection.modify.BeforeLoadLocal; import org.spongepowered.asm.mixin.injection.points.*; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -60,6 +62,7 @@ import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.IMessageSink; import com.google.common.base.Joiner; +import com.google.common.base.Strings; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableList.Builder; @@ -92,9 +95,17 @@ public abstract class InjectionPoint { @Target(ElementType.TYPE) public @interface AtCode { + /** + * Namespace for this code. Final selectors will be specified as + * <namespace>:<code> in order to avoid overlaps + * between consumer-provided injection points. + */ + public String namespace() default ""; + /** * The string code used to specify the annotated injection point in At - * annotations + * annotations, prefixed with namespace from the annotation or from the + * declaring configuration. */ public String value(); @@ -200,18 +211,18 @@ public abstract class InjectionPoint { static { // Standard Injection Points - InjectionPoint.register(BeforeFieldAccess.class); - InjectionPoint.register(BeforeInvoke.class); - InjectionPoint.register(BeforeNew.class); - InjectionPoint.register(BeforeReturn.class); - InjectionPoint.register(BeforeStringInvoke.class); - InjectionPoint.register(JumpInsnPoint.class); - InjectionPoint.register(MethodHead.class); - InjectionPoint.register(AfterInvoke.class); - InjectionPoint.register(BeforeLoadLocal.class); - InjectionPoint.register(AfterStoreLocal.class); - InjectionPoint.register(BeforeFinalReturn.class); - InjectionPoint.register(BeforeConstant.class); + InjectionPoint.registerBuiltIn(BeforeFieldAccess.class); + InjectionPoint.registerBuiltIn(BeforeInvoke.class); + InjectionPoint.registerBuiltIn(BeforeNew.class); + InjectionPoint.registerBuiltIn(BeforeReturn.class); + InjectionPoint.registerBuiltIn(BeforeStringInvoke.class); + InjectionPoint.registerBuiltIn(JumpInsnPoint.class); + InjectionPoint.registerBuiltIn(MethodHead.class); + InjectionPoint.registerBuiltIn(AfterInvoke.class); + InjectionPoint.registerBuiltIn(BeforeLoadLocal.class); + InjectionPoint.registerBuiltIn(AfterStoreLocal.class); + InjectionPoint.registerBuiltIn(BeforeFinalReturn.class); + InjectionPoint.registerBuiltIn(BeforeConstant.class); } private final String slice; @@ -568,7 +579,7 @@ public abstract class InjectionPoint { public static List parse(IInjectionPointContext context, List ats) { Builder injectionPoints = ImmutableList.builder(); for (AnnotationNode at : ats) { - InjectionPoint injectionPoint = InjectionPoint.parse(context, at); + InjectionPoint injectionPoint = InjectionPoint.parse(new InjectionPointAnnotationContext(context, at, "at"), at); if (injectionPoint != null) { injectionPoints.add(injectionPoint); } @@ -619,7 +630,7 @@ public abstract class InjectionPoint { * failed */ public static InjectionPoint parse(IMixinContext context, MethodNode method, AnnotationNode parent, AnnotationNode at) { - return InjectionPoint.parse(new AnnotatedMethodInfo(context, method, parent), at); + return InjectionPoint.parse(new InjectionPointAnnotationContext(new AnnotatedMethodInfo(context, method, parent), at, "at"), at); } /** @@ -696,8 +707,8 @@ public abstract class InjectionPoint { public static InjectionPoint parse(IInjectionPointContext context, String at, At.Shift shift, int by, List args, String target, String slice, int ordinal, int opcode, String id) { InjectionPointData data = new InjectionPointData(context, at, args, target, slice, ordinal, opcode, id); - Class ipClass = findClass(context.getContext(), data); - InjectionPoint point = InjectionPoint.create(context.getContext(), data, ipClass); + Class ipClass = InjectionPoint.findClass(context.getMixin(), data); + InjectionPoint point = InjectionPoint.create(context.getMixin(), data, ipClass); return InjectionPoint.shift(context, point, shift, by); } @@ -732,6 +743,8 @@ public abstract class InjectionPoint { InjectionPoint point = null; try { point = ipCtor.newInstance(data); + } catch (InvocationTargetException ex) { + throw new InvalidInjectionException(context, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex.getCause()); } catch (Exception ex) { throw new InvalidInjectionException(context, "Error whilst instancing injection point " + ipClass.getName() + " for " + data.getAt(), ex); } @@ -748,7 +761,7 @@ public abstract class InjectionPoint { } else if (shift == At.Shift.AFTER) { return InjectionPoint.after(point); } else if (shift == At.Shift.BY) { - InjectionPoint.validateByValue(context.getContext(), context.getMethod(), context.getAnnotation(), point, by); + InjectionPoint.validateByValue(context.getMixin(), context.getMethod(), context.getAnnotation(), point, by); return InjectionPoint.shift(point, by); } } @@ -802,19 +815,53 @@ public abstract class InjectionPoint { * * @param type injection point type to register */ + @Deprecated public static void register(Class type) { + } + + /** + * 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 + * @param namespace namespace for AtCode + */ + public static void register(Class type, String namespace) { AtCode code = type.getAnnotation(AtCode.class); if (code == null) { throw new IllegalArgumentException("Injection point class " + type + " is not annotated with @AtCode"); } + String annotationNamespace = code.namespace(); + if (!Strings.isNullOrEmpty(annotationNamespace)) { + namespace = annotationNamespace; + } + Class existing = InjectionPoint.types.get(code.value()); if (existing != null && !existing.equals(type)) { LogManager.getLogger("mixin").debug("Overriding InjectionPoint {} with {} (previously {})", code.value(), type.getName(), existing.getName()); + } else if (Strings.isNullOrEmpty(namespace)) { + LogManager.getLogger("mixin").warn("Registration of InjectionPoint {} with {} without specifying namespace is deprecated.", + code.value(), type.getName()); } - InjectionPoint.types.put(code.value(), type); + String id = code.value(); + if (!Strings.isNullOrEmpty(namespace)) { + id = namespace + ":" + code.value(); + } + + InjectionPoint.types.put(id, type); + } + + /** + * Register a built-in injection point class. Skips validation and + * namespacing checks + * + * @param type injection point type to register + */ + private static void registerBuiltIn(Class type) { + InjectionPoint.types.put(type.getAnnotation(AtCode.class).value(), type); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java index 9d04b89d..633649ec 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/Injector.java @@ -256,7 +256,7 @@ public abstract class Injector { public final void inject(Target target, List nodes) { for (InjectionNode node : nodes) { if (node.isRemoved()) { - if (this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) { Injector.logger.warn("Target node for {} was removed by a previous injector in {}", this.info, target); } continue; @@ -279,7 +279,7 @@ public abstract class Injector { * @return Target insn nodes in the target method */ private Collection findTargetNodes(InjectorTarget injectorTarget, List injectionPoints) { - IMixinContext mixin = this.info.getContext(); + IMixinContext mixin = this.info.getMixin(); MethodNode method = injectorTarget.getMethod(); Map targetNodes = new TreeMap(); Collection nodes = new ArrayList(32); @@ -522,7 +522,7 @@ public abstract class Injector { * @param args Array of handler args, must not be null */ protected final void validateParams(InjectorData injector, Type returnType, Type... args) { - String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getContext()); + String description = String.format("%s %s method %s from %s", this.annotationType, injector, this, this.info.getMixin()); int argIndex = 0; try { injector.coerceReturnType = this.checkCoerce(-1, returnType, description, injector.allowCoerceArgs); @@ -588,7 +588,7 @@ public abstract class Injector { Object argIndex = isReturn ? "" : " at index " + index; if (fromType.equals(toType)) { - if (coerce != null && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (coerce != null && this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) { Injector.logger.info("Possibly-redundant @Coerce on {} {} type{}, {} is identical to {}", description, argType, argIndex, SignaturePrinter.getTypeName(toType), SignaturePrinter.getTypeName(fromType)); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java index 85ac3af6..9852b75a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/code/MethodSlice.java @@ -40,10 +40,11 @@ import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.Selector; import org.spongepowered.asm.mixin.injection.Slice; +import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationContext; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException; -import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Annotations; +import org.spongepowered.asm.util.Bytecode; import com.google.common.base.Strings; @@ -406,7 +407,7 @@ public final class MethodSlice { } if (!result) { - if (this.owner.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (this.owner.getMixin().getOption(Option.DEBUG_VERBOSE)) { MethodSlice.logger.warn("{} did not match any instructions", this.describe(description)); } return failValue; @@ -434,7 +435,7 @@ public final class MethodSlice { private static String describeSlice(String description, ISliceContext owner) { String annotation = Bytecode.getSimpleName(owner.getAnnotation()); MethodNode method = owner.getMethod(); - return String.format("%s->%s(%s)::%s%s", owner.getContext(), annotation, description, method.name, method.desc); + return String.format("%s->%s(%s)::%s%s", owner.getMixin(), annotation, description, method.name, method.desc); } private static String getSliceName(String id) { @@ -469,12 +470,17 @@ public final class MethodSlice { */ public static MethodSlice parse(ISliceContext info, AnnotationNode node) { String id = Annotations.getValue(node, "id"); + String coord = "slice"; + if (!Strings.isNullOrEmpty(id)) { + coord += "." + id; + } + InjectionPointAnnotationContext sliceContext = new InjectionPointAnnotationContext(info, node, coord); AnnotationNode from = Annotations.getValue(node, "from"); AnnotationNode to = Annotations.getValue(node, "to"); - InjectionPoint fromPoint = from != null ? InjectionPoint.parse(info, from) : null; - InjectionPoint toPoint = to != null ? InjectionPoint.parse(info, to) : null; + InjectionPoint fromPoint = from != null ? InjectionPoint.parse(new InjectionPointAnnotationContext(sliceContext, from, "from"), from) : null; + InjectionPoint toPoint = to != null ? InjectionPoint.parse(new InjectionPointAnnotationContext(sliceContext, to, "to"), to) : null; return new MethodSlice(info, id, fromPoint, toPoint); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java index b722d806..df75a876 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyArgsInjector.java @@ -53,7 +53,7 @@ public class ModifyArgsInjector extends InvokeInjector { public ModifyArgsInjector(InjectionInfo info) { super(info, "@ModifyArgs"); - this.argsClassGenerator = info.getContext().getExtensions().getGenerator(ArgsClassGenerator.class); + this.argsClassGenerator = info.getMixin().getExtensions().getGenerator(ArgsClassGenerator.class); } /* (non-Javadoc) @@ -84,7 +84,7 @@ public class ModifyArgsInjector extends InvokeInjector { + targetMethod.name + targetMethod.desc + " with no arguments!"); } - String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getContext().getMixin()).getName(); + String clArgs = this.argsClassGenerator.getArgsClass(targetMethod.desc, this.info.getMixin().getMixin()).getName(); boolean withArgs = this.verifyTarget(target); InsnList insns = new InsnList(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java index 3f60bb30..a9ad8835 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/ModifyConstantInjector.java @@ -133,7 +133,7 @@ public class ModifyConstantInjector extends RedirectInjector { private void injectConstantModifier(Target target, AbstractInsnNode constNode) { final Type constantType = Bytecode.getConstantType(constNode); - if (constantType.getSort() <= Type.INT && this.info.getContext().getOption(Option.DEBUG_VERBOSE)) { + if (constantType.getSort() <= Type.INT && this.info.getMixin().getOption(Option.DEBUG_VERBOSE)) { this.checkNarrowing(target, constNode, constantType); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java index a8aa0f47..2cde5ecd 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/invoke/RedirectInjector.java @@ -234,7 +234,7 @@ public class RedirectInjector extends InvokeInjector { protected RedirectInjector(InjectionInfo info, String annotationType) { super(info, annotationType); - int priority = info.getContext().getPriority(); + int priority = info.getMixin().getPriority(); boolean isFinal = Annotations.getVisible(this.methodNode, Final.class) != null; this.meta = new Meta(priority, isFinal, this.info.toString(), this.methodNode.desc); } @@ -463,7 +463,7 @@ public class RedirectInjector extends InvokeInjector { Type elementType = field.type.getElementType(); int valueArgIndex = field.getTotalDimensions(); if (this.checkCoerce(valueArgIndex, elementType, String.format("%s array setter method %s from %s", - this.annotationType, this, this.info.getContext()), true)) { + this.annotationType, this, this.info.getMixin()), true)) { elementType = this.methodArgs[valueArgIndex]; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java index 16d5abd1..4d02c557 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/modify/ModifyVariableInjector.java @@ -81,7 +81,7 @@ public class ModifyVariableInjector extends Injector { LocalVariableInjectionPoint(InjectionPointData data) { super(data); - this.mixin = data.getContext(); + this.mixin = data.getMixin(); } @Override diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java index 8354bb58..db18ffdb 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeConstant.java @@ -182,9 +182,9 @@ public class BeforeConstant extends InjectionPoint { String strClassValue = data.get("classValue", null); this.typeValue = strClassValue != null ? Type.getObjectType(strClassValue.replace('.', '/')) : null; - this.matchByType = this.validateDiscriminator(data.getContext(), "V", empty, "in @At(\"CONSTANT\") args"); + this.matchByType = this.validateDiscriminator(data.getMixin(), "V", empty, "in @At(\"CONSTANT\") args"); if ("V".equals(this.matchByType)) { - throw new InvalidInjectionException(data.getContext(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args"); + throw new InvalidInjectionException(data.getMixin(), "No constant discriminator could be parsed in @At(\"CONSTANT\") args"); } List conditions = new ArrayList(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java index 053fb872..f34f7c65 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeFinalReturn.java @@ -64,7 +64,7 @@ public class BeforeFinalReturn extends InjectionPoint { public BeforeFinalReturn(InjectionPointData data) { super(data); - this.context = data.getContext(); + this.context = data.getMixin(); } @Override diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java index d58c273a..406cceb4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeInvoke.java @@ -127,7 +127,7 @@ public class BeforeInvoke extends InjectionPoint { this.ordinal = data.getOrdinal(); this.log = data.get("log", false); this.className = this.getClassName(); - this.context = data.getContext(); + this.context = data.getMixin(); this.allowPermissive = this.context.getOption(Option.REFMAP_REMAP) && this.context.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE) && !this.context.getReferenceMapper().isDefault(); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java index 7b0df8ce..c0484c5e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/points/BeforeNew.java @@ -113,7 +113,7 @@ public class BeforeNew extends InjectionPoint { String target = Strings.emptyToNull(data.get("class", data.get("target", "")).replace('.', '/')); ITargetSelector member = TargetSelector.parseAndValidate(target, data.getContext()); if (!(member instanceof ITargetSelectorConstructor)) { - throw new InvalidInjectionPointException(data.getContext(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s", + throw new InvalidInjectionPointException(data.getMixin(), "Failed parsing @At(\"NEW\") target descriptor \"%s\" on %s", target, data.getDescription()); } ITargetSelectorConstructor targetSelector = (ITargetSelectorConstructor)member; diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java new file mode 100644 index 00000000..9178198e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ISelectorContext.java @@ -0,0 +1,83 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors; + +import org.spongepowered.asm.mixin.refmap.IMixinContext; + +/** + * Context passed to a {@link ITargetSelector Target Selector} in order to + * support context-sensitive behaviour for the selector. For example obtaining + * the name of the source mixin, or the element containing the selector itself. + */ +public interface ISelectorContext { + + /** + * Get the parent (outer/containing) context. Can be null if this is a root + * element such as an injector method, in which case the parent is the mixin + * instead. + */ + public abstract ISelectorContext getParent(); + + /** + * Get the mixin containing this selector. + */ + public abstract IMixinContext getMixin(); + + /** + * Get the root method upon which this selector is operating, usually the + * injector method + */ + public abstract Object getMethod(); + + /** + * Get the root annotation for the selector, for example the injector or + * accessor annotation + */ + public abstract Object getAnnotation(); + + /** + * Get the annotation for this selector, for example the @At annotation + */ + public abstract Object getSelectorAnnotation(); + + /** + * Get the coordinate for this selector. This is the local coordinate of the + * selector without any parent parts. Parent parts are prepended by + * consumers during the resolve process. + */ + public abstract String getSelectorCoordinate(); + + /** + * Remap a reference in the context of this selector, usually via the local + * refmap of the mixin configuration but can be overridden as needed, for + * example to provide selector-local remap behaviour. + * + * @param reference Reference to remap + * @return Remapped reference or original reference if not remapped, must + * not return null! + */ + public abstract String remap(String reference); + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java index 1dffd05b..d194324a 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelector.java @@ -26,7 +26,7 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.objectweb.asm.tree.AbstractInsnNode; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.injection.struct.MemberMatcher; import org.spongepowered.asm.util.asm.ElementNode; /** @@ -40,13 +40,49 @@ import org.spongepowered.asm.util.asm.ElementNode; *

Explicit Target Selectors are handled internally using * {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the * supported variants and examples.

+ * + *

Pattern Target Selectors (Regex Selectors)

+ * + *

Pattern Target Selectors are handled internally using + * {@link MemberMatcher}, see the javadoc for {@link MemberMatcher} for the + * supported variants and examples. Pattern Selectors always end with a forward + * slash character.

+ * + *

Dynamic Target Selectors

+ * + *

Dynamic Target Selectors can be built-in or user-supplied types + * with their own specialised syntax or behaviour. Dynamic selectors are + * specified in the following format, and can be recognised by the fact that + * the selector string starts with "@":

+ * + *
+ *   // Built-in dynamic selector without argument string
+ *   @SelectorId
+ *   
+ *   // Built-in dynamic selector with empty argument string
+ *   @SelectorId()
+ *   
+ *   // Built-in dynamic selector with argument
+ *   @SelectorId(custom,argument,string,in,any,format)
+ *   
+ *   // User-provided dynamic selector with argument. Note that user-provided
+ *   // dynamic selectors are namespaced to avoid conflicts.
+ *   @Namespace:SelectorId(some arguments)
+ *
+ * + *

The exact format of the argument string is specified by the dynamic + * selector itself, consult the documentation for the dynamic selector you are + * using for details on the required format.

+ * */ public interface ITargetSelector { /** * Get the next target selector in this path (or null if this * selector is the last selector in the chain. Called at recurse points in - * the subject in order to match against the child subject. + * the subject in order to match against the child subject. + * + *

Can return null

*/ public abstract ITargetSelector next(); @@ -61,6 +97,8 @@ public interface ITargetSelector { * already configured according to "foo" may simply return this * object, or might return an identically-configured copy.

* + *

Must not return null

+ * * @param args Configuration arguments * @return Configured selector, may return this selector if the specified * condition is already satisfied @@ -86,7 +124,7 @@ public interface ITargetSelector { * @param context Context to attach to * @return Attached selector */ - public abstract ITargetSelector attach(IMixinContext context) throws InvalidSelectorException; + public abstract ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException; /** * Number of candidates which this selector should match diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java new file mode 100644 index 00000000..234a5f43 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java @@ -0,0 +1,62 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors; + +import java.lang.annotation.ElementType; +import java.lang.annotation.Retention; +import java.lang.annotation.RetentionPolicy; + +/** + * Decoration interface for dynamic target selectors + */ +public interface ITargetSelectorDynamic extends ITargetSelector { + + /** + * Decoration for subclasses which indicates id used for a specific selector + * when specified, for example @MyNamespace:MySelector(argshere) + * would specify "MySelector" + */ + @Retention(RetentionPolicy.RUNTIME) + @java.lang.annotation.Target(ElementType.TYPE) + public @interface SelectorId { + + /** + * Namespace for this code. Final selectors will be specified as + * <namespace>:<id> in order to avoid overlaps + * between consumer-provided selectors. If left blank defaults to the + * namespace specified in the configuration. + */ + public String namespace() default ""; + + /** + * The string code used to specify the selector selector strings, + * prefixed with namespace from the annotation or from the declaring + * configuration. + */ + public String value(); + + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java new file mode 100644 index 00000000..519b90b4 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java @@ -0,0 +1,96 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.spongepowered.asm.util.asm.ElementNode; + +public class InvalidSelector implements ITargetSelector { + + private String input; + + private Throwable cause; + + public InvalidSelector(Throwable cause) { + this(cause, null); + } + + public InvalidSelector(String input) { + this(null, input); + } + + public InvalidSelector(Throwable cause, String input) { + this.input = input; + this.cause = cause; + } + + @Override + public ITargetSelector next() { + return null; + } + + @Override + public ITargetSelector configure(String... args) { + return this; + } + + @Override + public ITargetSelector validate() throws InvalidSelectorException { + if (this.cause instanceof InvalidSelectorException) { + throw (InvalidSelectorException)this.cause; + } + String message = "Error parsing target selector"; + if (this.input != null) { + message += ", the input was in an unexpected format: " + this.input; + } + if (this.cause != null) { + throw new InvalidSelectorException(message, this.cause); + } + throw new InvalidSelectorException(message); + } + + @Override + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + return this; + } + + @Override + public int getMatchCount() { + return 0; + } + + @Override + public MatchResult match(ElementNode node) { + this.validate(); + return MatchResult.NONE; + } + + @Override + public MatchResult match(AbstractInsnNode insn) { + this.validate(); + return MatchResult.NONE; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java index f3ed43cb..39640c98 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/TargetSelector.java @@ -24,14 +24,29 @@ */ package org.spongepowered.asm.mixin.injection.selectors; +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; import java.util.ArrayList; +import java.util.LinkedHashMap; import java.util.List; +import java.util.Locale; +import java.util.Map; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import javax.tools.Diagnostic.Kind; + +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; -import org.spongepowered.asm.mixin.refmap.IMixinContext; -import org.spongepowered.asm.mixin.refmap.IReferenceMapper; +import org.spongepowered.asm.mixin.injection.struct.MemberMatcher; +import org.spongepowered.asm.mixin.throwables.MixinError; +import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.util.asm.ElementNode; +import org.spongepowered.asm.util.logging.MessageRouter; + +import com.google.common.base.Strings; /** * Utility class for parsing selectors @@ -85,17 +100,121 @@ public final class TargetSelector { } + /** + * A dynamic selector registration entry + */ + static class DynamicSelectorEntry { + + final String namespace; + + final String id; + + final Class type; + + final Method parse; + + DynamicSelectorEntry(String namespace, String id, Class type) throws NoSuchMethodException { + this.namespace = namespace; + this.id = id; + this.type = type; + this.parse = type.getDeclaredMethod("parse", String.class, ISelectorContext.class); + if (!Modifier.isStatic(this.parse.getModifiers())) { + throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static"); + } + if (!ITargetSelectorDynamic.class.isAssignableFrom(this.parse.getReturnType())) { + throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + + "] must return an ITargetSelectorDynamic subtype"); + } + } + + String getCode() { + return (this.namespace != null ? this.namespace + ":" : "") + this.id; + } + + ITargetSelectorDynamic parse(String input, ISelectorContext context) throws ReflectiveOperationException { + try { + return (ITargetSelectorDynamic)this.parse.invoke(null, input, context); + } catch (InvocationTargetException itex) { + Throwable cause = itex.getCause(); + if (cause instanceof MixinException) { + throw (MixinException)cause; + } + Throwable ex = cause != null ? cause : itex; + throw new MixinError("Error parsing dynamic target selector [" + this.type.getName() + "] for " + context, ex); + } + } + } + + /** + * Pattern for matching dynamic selectors + */ + private static final Pattern PATTERN_DYNAMIC = Pattern.compile("^\\x40([a-z]+(:[a-z]+)?)(\\((.*)\\))?$", Pattern.CASE_INSENSITIVE); + + /** + * Registered dynamic selectors + */ + private static Map dynamicSelectors = new LinkedHashMap(); + private TargetSelector() { } /** - * Parse a target selector from a string and perform validation + * Register a dynamic target selector class. The supplied class must be + * decorated with an {@link SelectorId} annotation for registration to + * succeed. * - * @param string String to parse target selector from - * @return parsed target selector + * @param type ITargetSelectorDynamic to register + * @param namespace namespace for SelectorId */ - public static ITargetSelector parseAndValidate(String string) throws InvalidMemberDescriptorException { - return TargetSelector.parse(string, null, null).validate(); + public static void register(Class type, String namespace) { + SelectorId selectorId = type.getAnnotation(SelectorId.class); + if (selectorId == null) { + throw new IllegalArgumentException("Dynamic target selector class " + type + " is not annotated with @SelectorId"); + } + + String annotationNamespace = selectorId.namespace(); + if (!Strings.isNullOrEmpty(annotationNamespace)) { + namespace = annotationNamespace; + } + + if (Strings.isNullOrEmpty(namespace)) { + throw new IllegalArgumentException("Dynamic target selector class " + type + + " has no namespace. Please specify namespace in SelectorId annotation or declaring configuration"); + } + + DynamicSelectorEntry entry; + try { + entry = new DynamicSelectorEntry(namespace, selectorId.value().toLowerCase(Locale.ROOT), type); + } catch (NoSuchMethodException ex) { + throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method"); + } + DynamicSelectorEntry existing = TargetSelector.dynamicSelectors.get(entry.id); + if (existing != null) { // && !existing.type.equals(type)) { + MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding target selector for @%s with %s (previously %s)", + entry.id, type.getName(), existing.type.getName())); + } else { + MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new target selector for @%s with %s", + entry.id, type.getName())); + } + + TargetSelector.dynamicSelectors.put(entry.getCode(), entry); + } + + /** + * Register a built-in target selector class. Skips validation and + * namespacing checks + * + * @param type ITargetSelectorDynamic to register + */ + private static void registerBuiltIn(Class type) { + SelectorId selectorId = type.getAnnotation(SelectorId.class); + DynamicSelectorEntry entry; + try { + entry = new DynamicSelectorEntry(null, selectorId.value().toLowerCase(Locale.ROOT), type); + } catch (NoSuchMethodException ex) { + throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method"); + } + TargetSelector.dynamicSelectors.put(entry.getCode(), entry); } /** @@ -105,18 +224,8 @@ public final class TargetSelector { * @param context Context to use for reference mapping * @return parsed target selector */ - public static ITargetSelector parseAndValidate(String string, IMixinContext context) throws InvalidMemberDescriptorException { - return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef()).validate(); - } - - /** - * Parse a target selector from a string - * - * @param string String to parse target selector from - * @return parsed target selector - */ - public static ITargetSelector parse(String string) { - return TargetSelector.parse(string, null, null); + public static ITargetSelector parseAndValidate(String string, ISelectorContext context) throws InvalidMemberDescriptorException { + return TargetSelector.parse(string, context).validate(); } /** @@ -126,8 +235,42 @@ public final class TargetSelector { * @param context Context to use for reference mapping * @return parsed target selector */ - public static ITargetSelector parse(String string, IMixinContext context) { - return TargetSelector.parse(string, context.getReferenceMapper(), context.getClassRef()); + public static ITargetSelector parse(String string, ISelectorContext context) { + string = string.trim(); + + // Ending with slash indicates a regex target, no other type of target + // selector can end (legally) with a forward slash + if (string.endsWith("/")) { + MemberMatcher regexMatcher = MemberMatcher.parse(string, context); + if (regexMatcher != null) { + return regexMatcher; + } + } + + // Starting with @ indicates a dynamic target. Parse as a regular + // MemberInfo if the selector does not start with @ + if (!string.startsWith("@")) { + return MemberInfo.parse(string, context); + } + + Matcher dynamic = TargetSelector.PATTERN_DYNAMIC.matcher(string); + if (!dynamic.matches()) { + return new InvalidSelector(new InvalidSelectorException("Dynamic selector was in an unrecognised format. Parsing selector: " + string)); + } + + String selectorId = dynamic.group(1).toLowerCase(Locale.ROOT); + if (!TargetSelector.dynamicSelectors.containsKey(selectorId)) { + return new InvalidSelector(new InvalidSelectorException("Dynamic selector with id '@" + dynamic.group(1) + + "' is not registered. Parsing selector: " + string)); + } + + try { + return TargetSelector.dynamicSelectors.get(selectorId).parse(Strings.nullToEmpty(dynamic.group(4)), context); + } catch (ReflectiveOperationException ex) { + return new InvalidSelector(ex.getCause(), string); + } catch (Exception ex) { + return new InvalidSelector(ex); + } } /** @@ -141,7 +284,7 @@ public final class TargetSelector { * @param context Mixin context * @return remapped name or original name */ - public static String parseName(String name, IMixinContext context) { + public static String parseName(String name, ISelectorContext context) { ITargetSelector selector = TargetSelector.parse(name, context); if (!(selector instanceof ITargetSelectorByName)) { return name; @@ -150,10 +293,6 @@ public final class TargetSelector { return mappedName != null ? mappedName : name; } - private static ITargetSelector parse(String input, IReferenceMapper refMapper, String mixinClass) { - return MemberInfo.parse(input, refMapper, mixinClass); - } - /** * Run query on supplied target nodes * diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java new file mode 100644 index 00000000..70f6d2b3 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java @@ -0,0 +1,57 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.selectors.dynamic; + +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; + +/** + * Base class for dynamic selectors, just to reduce some boilerplate + */ +public abstract class DynamicSelectorAbstract implements ITargetSelectorDynamic { + + @Override + public ITargetSelector configure(String... args) { + return this; + } + + @Override + public ITargetSelector validate() throws InvalidSelectorException { + return this; + } + + @Override + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + return this; + } + + @Override + public int getMatchCount() { + return Integer.MAX_VALUE; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java index 646e6f73..e94cf747 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionInfo.java @@ -300,7 +300,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC Set selectors = new LinkedHashSet(); for (String method : methods) { try { - selectors.add(TargetSelector.parseAndValidate(method, this.mixin).attach(this.mixin)); + selectors.add(TargetSelector.parseAndValidate(method, this).attach(this)); } catch (InvalidMemberDescriptorException ex) { throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: \"%s\". %s", this.annotationType, this.methodName, method, this.mixin.getReferenceMapper().getStatus())); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java new file mode 100644 index 00000000..1228ad64 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointAnnotationContext.java @@ -0,0 +1,88 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.struct; + +import org.objectweb.asm.tree.AnnotationNode; +import org.objectweb.asm.tree.MethodNode; +import org.spongepowered.asm.mixin.injection.IInjectionPointContext; +import org.spongepowered.asm.util.Bytecode; + +/** + * Specialised SelectorAnnotationContext for injection points + */ +public class InjectionPointAnnotationContext extends SelectorAnnotationContext implements IInjectionPointContext { + + /** + * Parent context + */ + private IInjectionPointContext parentContext; + + public InjectionPointAnnotationContext(IInjectionPointContext parent, Object selectorAnnotation, String selectorCoordinate) { + super(parent, selectorAnnotation, selectorCoordinate); + this.parentContext = parent; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.util.IMessageSink + * #addMessage(java.lang.String, java.lang.Object[]) + */ + @Override + public void addMessage(String format, Object... args) { + this.parentContext.addMessage(format, args); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.struct + * .SelectorAnnotationContext#getMethod() + */ + @Override + public MethodNode getMethod() { + return this.parentContext.getMethod(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.struct + * .SelectorAnnotationContext#getAnnotation() + */ + @Override + public AnnotationNode getAnnotation() { + return this.parentContext.getAnnotation(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.struct + * .SelectorAnnotationContext#getSelectorAnnotation() + */ + @Override + public AnnotationNode getSelectorAnnotation() { + return (AnnotationNode)super.getSelectorAnnotation(); + } + + @Override + public String toString() { + return String.format("%s->@%s(%s)", this.parentContext, Bytecode.getSimpleName(this.getSelectorAnnotation()), this.getSelectorCoordinate()); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java index f970537e..edded14b 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectionPointData.java @@ -39,6 +39,7 @@ 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.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -174,10 +175,17 @@ public class InjectionPointData { } /** - * Get the context + * Get the injection point context */ - public IMixinContext getContext() { - return this.context.getContext(); + public IInjectionPointContext getContext() { + return this.context; + } + + /** + * Get the mixin context + */ + public IMixinContext getMixin() { + return this.context.getMixin(); } /** @@ -258,9 +266,9 @@ public class InjectionPointData { */ public ITargetSelector get(String key) { try { - return TargetSelector.parseAndValidate(this.get(key, ""), this.getContext()); - } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionPointException(this.getContext(), "Failed parsing @At(\"%s\").%s descriptor \"%s\" on %s", + return TargetSelector.parseAndValidate(this.get(key, ""), this.context); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").%s \"%s\" on %s", this.at, key, this.target, this.getDescription()); } } @@ -270,9 +278,9 @@ public class InjectionPointData { */ public ITargetSelector getTarget() { try { - return TargetSelector.parseAndValidate(this.target, this.getContext()); - } catch (InvalidMemberDescriptorException ex) { - throw new InvalidInjectionPointException(this.getContext(), "Failed parsing @At(\"%s\").target descriptor \"%s\" on %s", + return TargetSelector.parseAndValidate(this.target, this.context); + } catch (InvalidSelectorException ex) { + throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").target \"%s\" on %s", this.at, this.target, this.getDescription()); } } @@ -281,7 +289,7 @@ public class InjectionPointData { * Get a description of this injector for use in error messages */ public String getDescription() { - return InjectionInfo.describeInjector(this.getContext(), this.getParent(), this.getMethod()); + return InjectionInfo.describeInjector(this.context.getMixin(), this.context.getAnnotation(), this.context.getMethod()); } /** @@ -340,7 +348,7 @@ public class InjectionPointData { } private static Pattern createPattern() { - return Pattern.compile(String.format("^([^:]+):?(%s)?$", Joiner.on('|').join(Selector.values()))); + return Pattern.compile(String.format("^(.+?)(:(%s))?$", Joiner.on('|').join(Selector.values()))); } /** @@ -359,7 +367,7 @@ public class InjectionPointData { } private static Selector parseSelector(Matcher matcher) { - return matcher.matches() && matcher.group(2) != null ? Selector.valueOf(matcher.group(2)) : Selector.DEFAULT; + return matcher.matches() && matcher.group(3) != null ? Selector.valueOf(matcher.group(3)) : Selector.DEFAULT; } private static int parseInt(String string, int defaultValue) { diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java index e4a932fb..37df0ee0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberInfo.java @@ -28,14 +28,13 @@ import org.objectweb.asm.Type; import org.objectweb.asm.tree.AbstractInsnNode; import org.objectweb.asm.tree.FieldInsnNode; import org.objectweb.asm.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorConstructor; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.MatchResult; -import org.spongepowered.asm.mixin.refmap.IMixinContext; -import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.throwables.MixinException; import org.spongepowered.asm.obfuscation.mapping.IMapping; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; @@ -630,8 +629,8 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * #attach(org.spongepowered.asm.mixin.refmap.IMixinContext) */ @Override - public ITargetSelector attach(IMixinContext context) throws InvalidSelectorException { - if (this.owner != null && !this.owner.equals(context.getTargetClassRef())) { + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + if (this.owner != null && !this.owner.equals(context.getMixin().getTargetClassRef())) { throw new TargetNotSupportedException(this.owner); } return this; @@ -679,17 +678,16 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * Parse a MemberInfo from a string * * @param input String to parse MemberInfo from - * @param refMapper Reference mapper to use - * @param className Class context to use for remapping + * @param context Selector context for this parse request * @return parsed MemberInfo */ - public static MemberInfo parse(String input, IReferenceMapper refMapper, String className) { + public static MemberInfo parse(String input, ISelectorContext context) { String desc = null; String owner = null; String name = Strings.nullToEmpty(input).replaceAll("\\s", ""); - if (refMapper != null) { - name = refMapper.remap(className, name); + if (context != null) { + name = context.remap(name); } int lastDotPos = name.lastIndexOf('.'); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java new file mode 100644 index 00000000..229658f6 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/MemberMatcher.java @@ -0,0 +1,267 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.struct; + +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.regex.PatternSyntaxException; + +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; +import org.spongepowered.asm.mixin.injection.selectors.MatchResult; +import org.spongepowered.asm.util.asm.ElementNode; + +/** + * A {@link ITargetSelector Target Selector} which matches an element of + * candidate members using a regular expression. This selector is not remappable + * and is not suitable for use in obfuscated environments. + * + *

Regular expressions for this selector should be enclosed in / as + * a delimiter character, and \ characters must be escaped per normal + * Java conventions (eg. use \\s instead of \s since the + * backslash must be escaped). Forward slash (/) characters in the + * regex must be escaped as well to avoid being consumed as ending delimiters. + *

+ * + *

By default the regex match is performed against the name of the + * candidate, to specify matching against owner or desc, each + * pattern should be prefixed with owner= or desc= outside + * the delimiting /. + * + *

Some examples:

+ *
+ *   // Matches candidates starting with "foo"
+ *   /^foo/
+ *   
+ *   // Matches candidates ending with "Bar" and which take a single integer
+ *   /bar$/ desc=/^\\(I\\)/
+ *   
+ *   // The same example but with "name" explicitly specified (optional)
+ *   name=/bar$/ desc=/^\\(I\\)/
+ *   
+ *   // Matches candidates whose name contains "Entity"
+ *   /Entity/
+ *   
+ *   // Matches candidates whose owner contains "/google/", note the escaping of
+ *   // the forward slash symbols
+ *   owner=/\\/google\\//
+ *
+ * + *

The owner, name and desc expressions can be + * provided in any order.

+ */ +public final class MemberMatcher implements ITargetSelector { + + /** + * Regex selector, searches for targets using supplied regular expression + */ + private static final Pattern PATTERN = Pattern.compile("((owner|name|desc)\\s*=\\s*)?/(.*?)(? MatchResult match(ElementNode node) { + return node == null ? MatchResult.NONE : this.matches(node.getOwnerName(), node.getName(), node.getDesc()); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #matches(org.objectweb.asm.tree.AbstractInsnNode) + */ + @Override + public MatchResult match(AbstractInsnNode insn) { + if (insn instanceof MethodInsnNode) { + MethodInsnNode method = (MethodInsnNode)insn; + return this.matches(method.owner, method.name, method.desc); + } else if (insn instanceof FieldInsnNode) { + FieldInsnNode field = (FieldInsnNode)insn; + return this.matches(field.owner, field.name, field.desc); + } + return MatchResult.NONE; + } + + private MatchResult matches(String... args) { + MatchResult result = MatchResult.NONE; +// boolean exactOnly = true; + + for (int i = 0; i < this.patterns.length; i++) { + if (this.patterns[i] == null || args[i] == null) { + continue; + } + + if (this.patterns[i].matcher(args[i]).find()) { +// String pattern = this.patterns[i].pattern(); +// if (pattern.startsWith("^") && pattern.endsWith("$") && exactOnly) { + result = MatchResult.EXACT_MATCH; +// } else { +// result = MatchResult.EXACT_MATCH; +// exactOnly = false; +// } + } else { + result = MatchResult.NONE; + } + } + + return result; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java index 818b76ef..ad184f18 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/ModifyConstantInjectionInfo.java @@ -70,7 +70,7 @@ public class ModifyConstantInjectionInfo extends InjectionInfo { Type returnType = Type.getReturnType(this.method.desc); for (AnnotationNode at : ats) { - this.injectionPoints.add(new BeforeConstant(this.getContext(), at, returnType.getDescriptor())); + this.injectionPoints.add(new BeforeConstant(this.getMixin(), at, returnType.getDescriptor())); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java new file mode 100644 index 00000000..3d1d2f8f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/SelectorAnnotationContext.java @@ -0,0 +1,130 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.injection.struct; + +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; +import org.spongepowered.asm.mixin.refmap.IMixinContext; + +/** + * Narrowed context for selectors in annotations which are themselves inside + * a parent annotation, for example @At annotations within a parent + * @Inject annotation. + */ +public class SelectorAnnotationContext implements ISelectorContext { + + /** + * The selector context of the parent, eg. the @Inject context + */ + private final ISelectorContext parent; + + /** + * The annotation for this selector + */ + private final Object selectorAnnotation; + + /** + * The coordinate for this selector + */ + private final String selectorCoordinate; + + /** + * Create a specialised context for a child annotation + * + * @param parent Parent selector context, eg. context of the outer element + * such as @Inject + * @param selectorAnnotation Annotation for this selector, eg. @At + * @param selectorCoordinate Coordinate for this selector + */ + public SelectorAnnotationContext(ISelectorContext parent, Object selectorAnnotation, String selectorCoordinate) { + this.parent = parent; + this.selectorAnnotation = selectorAnnotation; + this.selectorCoordinate = selectorCoordinate; + } + + /** + * Get the parent of this selector, must not return null + * + * @return parent context + */ + @Override + public ISelectorContext getParent() { + return this.parent; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getMixin() + */ + @Override + public IMixinContext getMixin() { + return this.parent.getMixin(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getMethod() + */ + @Override + public Object getMethod() { + return this.parent.getMethod(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getAnnotation() + */ + @Override + public Object getAnnotation() { + return this.parent.getAnnotation(); + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getSelectorAnnotation() + */ + @Override + public Object getSelectorAnnotation() { + return this.selectorAnnotation; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getSelectorCoordinate() + */ + @Override + public String getSelectorCoordinate() { + return this.selectorCoordinate; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #remap(java.lang.String) + */ + @Override + public String remap(String reference) { + return this.parent.remap(reference); + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java index b80ddb07..5131e261 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidInjectionException.java @@ -50,12 +50,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, String message) { - super(info.getContext(), message); + super(info.getMixin(), message); this.info = info; } public InvalidInjectionException(InjectionInfo info, String message, ActivityStack activityContext) { - super(info.getContext(), message, activityContext); + super(info.getMixin(), message, activityContext); this.info = info; } @@ -70,12 +70,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, Throwable cause) { - super(info.getContext(), cause); + super(info.getMixin(), cause); this.info = info; } public InvalidInjectionException(InjectionInfo info, Throwable cause, ActivityStack activityContext) { - super(info.getContext(), cause, activityContext); + super(info.getMixin(), cause, activityContext); this.info = info; } @@ -90,12 +90,12 @@ public class InvalidInjectionException extends InvalidMixinException { } public InvalidInjectionException(InjectionInfo info, String message, Throwable cause) { - super(info.getContext(), message, cause); + super(info.getMixin(), message, cause); this.info = info; } public InvalidInjectionException(InjectionInfo info, String message, Throwable cause, ActivityStack activityContext) { - super(info.getContext(), message, cause, activityContext); + super(info.getMixin(), message, cause, activityContext); this.info = info; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java index 85eae4d2..2fe9e2ac 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/throwables/InvalidSliceException.java @@ -40,7 +40,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, String message) { - super(owner.getContext(), message); + super(owner.getMixin(), message); } public InvalidSliceException(IMixinContext context, Throwable cause) { @@ -48,7 +48,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, Throwable cause) { - super(owner.getContext(), cause); + super(owner.getMixin(), cause); } public InvalidSliceException(IMixinContext context, String message, Throwable cause) { @@ -56,7 +56,7 @@ public class InvalidSliceException extends InvalidInjectionException { } public InvalidSliceException(ISliceContext owner, String message, Throwable cause) { - super(owner.getContext(), message, cause); + super(owner.getMixin(), message, cause); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java index e60da758..07aba734 100644 --- a/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/struct/AnnotatedMethodInfo.java @@ -30,7 +30,9 @@ import org.objectweb.asm.tree.AnnotationNode; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.IInjectionPointContext; +import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.refmap.IMixinContext; +import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.util.logging.MessageRouter; /** @@ -58,6 +60,24 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { this.method = method; this.annotation = annotation; } + + @Override + public String remap(String reference) { + if (this.context != null) { + IReferenceMapper referenceMapper = this.context.getReferenceMapper(); + return referenceMapper != null ? referenceMapper.remap(this.context.getClassName(), reference) : reference; + } + return reference; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ISelectorContext + * #getParent() + */ + @Override + public ISelectorContext getParent() { + return null; + } /** * Get the mixin target context for this annotated method @@ -65,7 +85,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { * @return the target context */ @Override - public final IMixinContext getContext() { + public final IMixinContext getMixin() { return this.context; } @@ -80,15 +100,36 @@ public class AnnotatedMethodInfo implements IInjectionPointContext { } /** - * Get the annotation which this InjectionInfo was created from + * Get the primary annotation which makes this method special * - * @return The annotation which this InjectionInfo was created from + * @return The primary method annotation */ @Override public final AnnotationNode getAnnotation() { return this.annotation; } + /** + * Get the annotation context for selectors operating in the context of this + * method. + * + * @return The selector context annotation + */ + @Override + public AnnotationNode getSelectorAnnotation() { + return this.annotation; + } + + /** + * Get the selector coordinate for this method + * + * @return The selector context annotation + */ + @Override + public String getSelectorCoordinate() { + return "method"; + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.IInjectionPointContext * #addMessage(java.lang.String, java.lang.Object[]) diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java index b178d87c..e1edf045 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -46,6 +46,8 @@ import org.spongepowered.asm.mixin.extensibility.IMixinConfigPlugin; import org.spongepowered.asm.mixin.injection.At; import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.InjectionPoint; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; +import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.refmap.ReferenceMapper; import org.spongepowered.asm.mixin.refmap.RemappingReferenceMapper; @@ -76,9 +78,15 @@ final class MixinConfig implements Comparable, IMixinConfig { @SerializedName("defaultGroup") String defaultGroup = "default"; + @SerializedName("namespace") + String namespace; + @SerializedName("injectionPoints") List injectionPoints; + @SerializedName("dynamicSelectors") + List dynamicSelectors; + @SerializedName("maxShiftBy") int maxShiftBy = InjectionPoint.DEFAULT_ALLOWED_SHIFT_BY; @@ -459,7 +467,7 @@ final class MixinConfig implements Comparable, IMixinConfig { this.initialised = true; this.initCompatibilityLevel(); - this.initInjectionPoints(); + this.initExtensions(); return this.checkVersion(); } @@ -514,46 +522,68 @@ final class MixinConfig implements Comparable, IMixinConfig { return fallbackEnvironment; } - private void initInjectionPoints() { - if (this.injectorOptions.injectionPoints == null) { - return; + private void initExtensions() { + if (this.injectorOptions.injectionPoints != null) { + for (String injectionPointClassName : this.injectorOptions.injectionPoints) { + this.initInjectionPoint(injectionPointClassName, this.injectorOptions.namespace); + } } - for (String injectionPointClassName : this.injectorOptions.injectionPoints) { - this.initInjectionPoint(injectionPointClassName); + if (this.injectorOptions.dynamicSelectors != null) { + for (String dynamicSelectorClassName : this.injectorOptions.dynamicSelectors) { + this.initDynamicSelector(dynamicSelectorClassName, this.injectorOptions.namespace); + } } } @SuppressWarnings("unchecked") - public void initInjectionPoint(String className) { + private void initInjectionPoint(String className, String namespace) { try { - Class injectionPointClass = null; - try { - injectionPointClass = this.service.getClassProvider().findClass(className, true); - } catch (ClassNotFoundException cnfe) { - this.logger.error("Unable to register injection point {} for {}, the specified class was not found", className, this, cnfe); - return; + Class injectionPointClass = this.findExtensionClass(className, InjectionPoint.class, "injection point"); + if (injectionPointClass != null) { + try { + injectionPointClass.getDeclaredMethod("find", String.class, InsnList.class, Collection.class); + } catch (NoSuchMethodException cnfe) { + this.logger.error("Unable to register injection point {} for {}, the class is not compatible with this version of Mixin", + className, this, cnfe); + return; + } + + InjectionPoint.register((Class)injectionPointClass, namespace); } - - if (!InjectionPoint.class.isAssignableFrom(injectionPointClass)) { - this.logger.error("Unable to register injection point {} for {}, class must extend InjectionPoint", className, this); - return; - } - - try { - injectionPointClass.getDeclaredMethod("find", String.class, InsnList.class, Collection.class); - } catch (NoSuchMethodException cnfe) { - this.logger.error("Unable to register injection point {} for {}, the class is not compatible with this version of Mixin", - className, this, cnfe); - return; - } - - InjectionPoint.register((Class)injectionPointClass); } catch (Throwable th) { this.logger.catching(th); } } + @SuppressWarnings("unchecked") + private void initDynamicSelector(String className, String namespace) { + try { + Class dynamicSelectorClass = this.findExtensionClass(className, ITargetSelectorDynamic.class, "dynamic selector"); + if (dynamicSelectorClass != null) { + TargetSelector.register((Class)dynamicSelectorClass, namespace); + } + } catch (Throwable th) { + this.logger.catching(th); + } + } + + private Class findExtensionClass(String className, Class superType, String extensionType) { + Class extensionClass = null; + try { + extensionClass = this.service.getClassProvider().findClass(className, true); + } catch (ClassNotFoundException cnfe) { + this.logger.error("Unable to register {} {} for {}, the specified class was not found", extensionType, className, this, cnfe); + return null; + } + + if (!superType.isAssignableFrom(extensionClass)) { + this.logger.error("Unable to register {} {} for {}, class is not assignable to {}", extensionType, className, this, superType); + return null; + } + return extensionClass; + } + private boolean checkVersion() throws MixinInitialisationError { if (this.version == null) { // If the parent is non-null, then the version check has already been diff --git a/src/main/java/org/spongepowered/asm/util/Locals.java b/src/main/java/org/spongepowered/asm/util/Locals.java index e3cb05d8..f57974a6 100644 --- a/src/main/java/org/spongepowered/asm/util/Locals.java +++ b/src/main/java/org/spongepowered/asm/util/Locals.java @@ -171,7 +171,11 @@ public final class Locals { for (Iterator iter = method.instructions.iterator(); iter.hasNext();) { AbstractInsnNode insn = iter.next(); if (storeInsn != null) { - frame[storeInsn.var] = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); + LocalVariableNode storedLocal = Locals.getLocalVariableAt(classNode, method, insn, storeInsn.var); + frame[storeInsn.var] = storedLocal; + if (storedLocal != null && storeInsn.var < method.maxLocals - 1 && Type.getType(storedLocal.desc).getSize() == 2) { + frame[storeInsn.var + 1] = null; // TOP + } storeInsn = null; } diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java new file mode 100644 index 00000000..15348b4c --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java @@ -0,0 +1,38 @@ +/* + * This file is part of Mixin, licensed under the MIT License (MIT). + * + * Copyright (c) SpongePowered + * 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.util.asm; + +/** + * Interface for annotation handle since main classes may need to read info from + * mirror annotations in the AP + */ +public interface IAnnotationHandle { + + /** + * Get the annotation descriptor + */ + public abstract String getDesc(); + +}