diff --git a/docs/javadoc/mixin.css b/docs/javadoc/mixin.css index fbebec3a..87631c8f 100644 --- a/docs/javadoc/mixin.css +++ b/docs/javadoc/mixin.css @@ -72,7 +72,7 @@ table.infoTable { border-collapse: collapse; } -table.infoTable td, table.infoTable th, table.cellTable td, table.cellTable th { +table.infoTable td, table.infoTable th, table.cellTable td, table.cellTable th, table.selectorTable td, table.selectorTable th { padding: 6px 8px; background-color: #F0F0F0; } @@ -81,11 +81,44 @@ table.cellTable th, table.cellTable td { text-align: center; } -table.infoTable th, table.cellTable th, table.infoTable td.th, table.cellTable td.th { +table.infoTable th, table.cellTable th, table.infoTable td.th, table.cellTable td.th, table.selectorTable th, table.selectorTable td.th { background-color: #CCC; font-weight: bold; } +table.selectorTable tbody td, table.selectorTable thead th { + border-left: 6px solid #FFF; +} + +table.selectorTable tbody td { + font-family: 'Consolas', monospace; +} + +table.selectorTable th, table.selectorTable td.th { + background: transparent; + font-family: inherit; +} + +table.selectorTable thead th.ownr { background-color: #CFC } +table.selectorTable thead th.name { background-color: #CCF } +table.selectorTable thead th.quan { background-color: #FFC } +table.selectorTable thead th.desc { background-color: #FCC } + +table.selectorTable tbody td.ownr { background-color: #F0FFF0 } +table.selectorTable tbody td.name { background-color: #F0F0FF } +table.selectorTable tbody td.quan { background-color: #FFFFF0 } +table.selectorTable tbody td.desc { background-color: #FFF0F0 } + +span.aownr { background-color: #DFD } +span.aname { background-color: #DDF } +span.aquan { background-color: #FFD } +span.adesc { background-color: #FDD } + +span.ownr {color: #090 } +span.name {color: #009 } +span.quan {color: #990 } +span.desc {color: #900 } + a[name] { color: #353833; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java index 2143f37d..dc31d05b 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixin.java @@ -384,7 +384,6 @@ class AnnotatedMixin implements IMixinContext, IAnnotatedElement { } public void registerInjector(ExecutableElement method, AnnotationHandle inject, InjectorRemap remap) { - System.err.printf(">>> %s\n", method); this.methods.remove(method); AnnotatedElementInjector injectorElement = new AnnotatedElementInjector(method, inject, this, remap); this.injectors.registerInjector(injectorElement); diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java index 0d715188..cd24aad5 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandler.java @@ -143,6 +143,11 @@ abstract class AnnotatedMixinElementHandler { public IAnnotationHandle getAnnotation(Class annotationClass) { return AnnotationHandle.of(AnnotatedElementExecutable.this.getElement(), annotationClass); } + + @Override + public String toString() { + return AnnotatedElementExecutable.this.getElement().getSimpleName().toString(); + } }; } @@ -161,6 +166,11 @@ abstract class AnnotatedMixinElementHandler { return reference; } + @Override + public String toString() { + return TypeUtils.getName(this.element); + } + } /** @@ -545,12 +555,12 @@ abstract class AnnotatedMixinElementHandler { * Checks whether the referenced method exists in all targets and raises * warnings where appropriate */ - protected final void validateReferencedTarget(ExecutableElement method, AnnotationHandle inject, ITargetSelector reference, String type) { - if (!(reference instanceof ITargetSelectorByName)) { + protected final void validateReferencedTarget(AnnotatedElementExecutable elem, String reference, ITargetSelector targetSelector, String subject) { + if (!(targetSelector instanceof ITargetSelectorByName)) { return; } - ITargetSelectorByName nameRef = (ITargetSelectorByName)reference; + ITargetSelectorByName nameRef = (ITargetSelectorByName)targetSelector; String signature = nameRef.toDescriptor(); for (TypeHandle target : this.mixin.getTargets()) { @@ -560,8 +570,8 @@ abstract class AnnotatedMixinElementHandler { MethodHandle targetMethod = target.findMethod(nameRef.getName(), signature); if (targetMethod == null) { - this.ap.printMessage(Kind.WARNING, "Cannot find target method for " + type + " in " + target, method, inject.asMirror(), - SuppressedBy.TARGET); + this.ap.printMessage(Kind.WARNING, "Cannot find target method \"" + nameRef.getName() + nameRef.getDesc() + "\" for " + subject + + " in " + target, elem.getElement(), elem.getAnnotation().asMirror(), SuppressedBy.TARGET); } } } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java index 6d88dda8..ba36a3a4 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/AnnotatedMixinElementHandlerInjector.java @@ -40,6 +40,7 @@ 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.TargetSelector; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; @@ -125,6 +126,11 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler public AnnotationHandle getAt() { return this.at; } + + public AnnotationMirror getAtErrorElement(CompilerEnvironment compilerEnvironment) { + // JDT supports hanging the error on the @At annotation directly, doing this in javac doesn't work + return (compilerEnvironment == CompilerEnvironment.JDT ? this.getAt() : this.getAnnotation()).asMirror(); + } @Override public IAnnotationHandle getSelectorAnnotation() { @@ -183,33 +189,38 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler } for (String reference : elem.getAnnotation().getList("method")) { - ITargetSelector targetSelector = TargetSelector.parse(reference, elem); - - try { - targetSelector.validate(); - } catch (InvalidMemberDescriptorException ex) { - elem.printMessage(this.ap, Kind.ERROR, ex.getMessage()); - } + this.registerInjectorTarget(elem, reference, TargetSelector.parse(reference, elem), elem + ".method=\"" + reference + "\""); + } + + for (IAnnotationHandle desc : elem.getAnnotation().getAnnotationList("target")) { + String subject = String.format("%s.target=@Desc(id = \"%s\")", elem, desc.getValue("id", "")); + this.registerInjectorTarget(elem, null, TargetSelector.parse(desc, elem), subject); + } + } + + private void registerInjectorTarget(AnnotatedElementInjector elem, String reference, ITargetSelector targetSelector, String subject) { + try { + targetSelector.validate(); + } catch (InvalidSelectorException ex) { + elem.printMessage(this.ap, Kind.ERROR, ex.getMessage()); + } - if (!(targetSelector instanceof ITargetSelectorRemappable)) { - continue; - } - - ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)targetSelector; - if (targetMember.getName() == null) { - continue; - } - - if (targetMember.getDesc() != null) { - this.validateReferencedTarget(elem.getElement(), elem.getAnnotation(), targetMember, elem.toString()); - } - - if (!elem.shouldRemap()) { - continue; - } - + if (!(targetSelector instanceof ITargetSelectorByName)) { + return; + } + + ITargetSelectorByName targetMember = (ITargetSelectorByName)targetSelector; + if (targetMember.getName() == null) { + return; + } + + if (targetMember.getDesc() != null) { + this.validateReferencedTarget(elem, reference, targetMember, subject); + } + + if (targetSelector instanceof ITargetSelectorRemappable && elem.shouldRemap()) { for (TypeHandle target : this.mixin.getTargets()) { - if (!this.registerInjector(elem, reference, targetMember, target)) { + if (!this.registerInjector(elem, reference, (ITargetSelectorRemappable)targetMember, target)) { break; } } @@ -290,91 +301,87 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler this.ap.printMessage(Kind.ERROR, "Injector in interface is unsupported", elem.getElement()); } - if (!elem.shouldRemap()) { - return; - } - - String type = InjectionPointData.parseType(elem.getAt().getValue("value")); - String target = elem.getAt().getValue("target"); - - if ("NEW".equals(type)) { - this.remapNewTarget(String.format(format, type + "."), target, elem); - this.remapNewTarget(String.format(format, type + ".args[class]"), elem.getAtArg("class"), elem); - } else { - this.remapReference(String.format(format, type + "."), target, elem); - } - } - - protected final void remapNewTarget(String subject, String reference, AnnotatedElementInjectionPoint elem) { + String reference = elem.getAt().getValue("target"); if (reference == null) { return; } - + ITargetSelector selector = TargetSelector.parse(reference, elem); - if (selector instanceof ITargetSelectorConstructor) { - ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector; - String target = member.toCtorType(); - - if (target != null) { - String desc = member.toCtorDesc(); - MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V"); - ObfuscationData remapped = this.obf.getDataProvider().getRemappedMethod(m); - if (remapped.isEmpty() && !SpecialPackages.isExcludedPackage(member.toCtorType())) { - this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), - elem.getAnnotation().asMirror(), SuppressedBy.MAPPING); - return; - } - - ObfuscationData mappings = new ObfuscationData(); - for (ObfuscationType type : remapped) { - MappingMethod mapping = remapped.get(type); - if (desc == null) { - mappings.put(type, mapping.getOwner()); - } else { - mappings.put(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";")); - } - } + + try { + selector.validate(); + } catch (InvalidMemberDescriptorException ex) { + this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), elem.getAtErrorElement(this.ap.getCompilerEnvironment())); + } + + if (elem.shouldRemap()) { + String type = InjectionPointData.parseType(elem.getAt().getValue("value")); + if ("NEW".equals(type)) { + String classReference = elem.getAtArg("class"); + ITargetSelector classSelector = TargetSelector.parse(classReference, elem); - this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings); + this.remapNewTarget(String.format(format, type + "."), reference, selector, elem); + this.remapNewTarget(String.format(format, type + ".args[class]"), classReference, classSelector, elem); + } else { + this.remapReference(String.format(format, type + "."), reference, selector, elem); } } + } + + protected final void remapNewTarget(String subject, String reference, ITargetSelector selector, AnnotatedElementInjectionPoint elem) { + if (!(selector instanceof ITargetSelectorConstructor)) { + return; + } + + ITargetSelectorConstructor member = (ITargetSelectorConstructor)selector; + String target = member.toCtorType(); + + if (target != null) { + String desc = member.toCtorDesc(); + MappingMethod m = new MappingMethod(target, ".", desc != null ? desc : "()V"); + ObfuscationData remapped = this.obf.getDataProvider().getRemappedMethod(m); + if (remapped.isEmpty() && !SpecialPackages.isExcludedPackage(member.toCtorType())) { + this.ap.printMessage(Kind.WARNING, "Cannot find class mapping for " + subject + " '" + target + "'", elem.getElement(), + elem.getAnnotation().asMirror(), SuppressedBy.MAPPING); + return; + } + ObfuscationData mappings = new ObfuscationData(); + for (ObfuscationType type : remapped) { + MappingMethod mapping = remapped.get(type); + if (desc == null) { + mappings.put(type, mapping.getOwner()); + } else { + mappings.put(type, mapping.getDesc().replace(")V", ")L" + mapping.getOwner() + ";")); + } + } + + this.obf.getReferenceManager().addClassMapping(this.classRef, reference, mappings); + } + elem.notifyRemapped(); } - protected final void remapReference(String subject, String reference, AnnotatedElementInjectionPoint elem) { - if (reference == null) { + protected final void remapReference(String subject, String reference, ITargetSelector selector, AnnotatedElementInjectionPoint elem) { + if (!(selector instanceof ITargetSelectorRemappable)) { return; } - - ITargetSelector targetSelector = TargetSelector.parse(reference, elem); - if (!(targetSelector instanceof ITargetSelectorRemappable)) { - return; - } - ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)targetSelector; - - // JDT supports hanging the error on the @At annotation directly, doing this in javac doesn't work - AnnotationMirror errorsOn = (this.ap.getCompilerEnvironment() == CompilerEnvironment.JDT ? elem.getAt() : elem.getAnnotation()).asMirror(); + ITargetSelectorRemappable targetMember = (ITargetSelectorRemappable)selector; + AnnotationMirror errorElement = elem.getAtErrorElement(this.ap.getCompilerEnvironment()); if (!targetMember.isFullyQualified()) { String missing = targetMember.getOwner() == null ? (targetMember.getDesc() == null ? "owner and signature" : "owner") : "signature"; - this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, missing " + missing, elem.getElement(), errorsOn); + this.ap.printMessage(Kind.ERROR, subject + " is not fully qualified, missing " + missing, elem.getElement(), errorElement); return; } - try { - targetMember.validate(); - } catch (InvalidMemberDescriptorException ex) { - this.ap.printMessage(Kind.ERROR, ex.getMessage(), elem.getElement(), errorsOn); - } - try { if (targetMember.isField()) { ObfuscationData obfFieldData = this.obf.getDataProvider().getObfFieldRecursive(targetMember); if (obfFieldData.isEmpty()) { if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) { this.ap.printMessage(Kind.WARNING, "Cannot find field mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn, SuppressedBy.MAPPING); + errorElement, SuppressedBy.MAPPING); } return; } @@ -384,7 +391,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler if (obfMethodData.isEmpty()) { if (targetMember.getOwner() == null || !SpecialPackages.isExcludedPackage(targetMember.getOwner())) { this.ap.printMessage(Kind.WARNING, "Cannot find method mapping for " + subject + " '" + reference + "'", elem.getElement(), - errorsOn, SuppressedBy.MAPPING); + errorElement, SuppressedBy.MAPPING); } return; } @@ -394,7 +401,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler // Since references are fully-qualified, it shouldn't be possible for there to be multiple mappings, however // we catch and log the error in case something weird happens in the mapping provider this.ap.printMessage(Kind.ERROR, "Unexpected reference conflict for " + subject + ": " + reference + " -> " - + ex.getNew() + " previously defined as " + ex.getOld(), elem.getElement(), errorsOn); + + ex.getNew() + " previously defined as " + ex.getOld(), elem.getElement(), errorElement); return; } diff --git a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java index 8cf91fc3..40d68279 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/ObfuscationEnvironment.java @@ -37,7 +37,6 @@ import javax.lang.model.type.TypeMirror; import javax.tools.Diagnostic.Kind; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorRemappable; -import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.ObfuscationUtil; @@ -281,7 +280,7 @@ public abstract class ObfuscationEnvironment implements IObfuscationEnvironment } } - return transformed ? new MemberInfo(method.getName(), owner, desc, method.getMatchCount() > 1) : null; + return transformed ? method.move(owner).transform(desc) : null; } /** 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 63890786..638c0ad2 100644 --- a/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java +++ b/src/ap/java/org/spongepowered/tools/obfuscation/mirror/AnnotationHandle.java @@ -80,6 +80,7 @@ public final class AnnotationHandle implements IAnnotationHandle { * * @return true if the annotation exists */ + @Override public boolean exists() { return this.annotation != null; } @@ -239,6 +240,12 @@ public final class AnnotationHandle implements IAnnotationHandle { return Collections.unmodifiableList(annotations); } + @Override + public Type getTypeValue(String key) { + TypeMirror typeMirror = this.getValue(key); + return typeMirror == null ? Type.VOID_TYPE : Type.getType(TypeUtils.getInternalName(typeMirror)); + } + @Override public List getTypeList(String key) { List list = this.getList(key); 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 225d544f..e85b9a20 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/AccessorInfo.java @@ -42,6 +42,7 @@ 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.ITargetSelector.Configure; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.struct.SpecialMethodInfo; @@ -509,7 +510,7 @@ public class AccessorInfo extends SpecialMethodInfo { * @return best match */ protected TNode findTarget(List> nodes) { - Result result = TargetSelector.run(this.target.configure("orphan"), nodes); + Result result = TargetSelector.run(this.target.configure(Configure.ORPHAN), nodes); try { return result.getSingleResult(true); diff --git a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java index cde243e7..ed2b4b68 100644 --- a/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/gen/InvokerInfo.java @@ -28,6 +28,7 @@ import org.objectweb.asm.Type; import org.objectweb.asm.tree.MethodNode; import org.spongepowered.asm.mixin.gen.throwables.InvalidAccessorException; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector.Result; @@ -102,7 +103,8 @@ class InvokerInfo extends AccessorInfo { } private MethodNode findTargetMethod() { - Result result = TargetSelector.run(this.target.configure("orphan"), ElementNode.methodList(this.classNode)); + Result result = TargetSelector.run(this.target.configure(Configure.ORPHAN), + ElementNode.methodList(this.classNode)); try { return result.getSingleResult(true); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java index 5a9613dd..50fd27d1 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/Desc.java @@ -111,4 +111,34 @@ public @interface Desc { */ public Class[] args() default { }; + /** + * The minimum number of times this selector should match. By default the + * selector is allowed to match no targets. When selecting fields or methods + * setting this value to anything other than 0 or 1 is pointless since the + * member can either be present or absent. However when matching method + * calls or field accesses (eg. when using this value inside + * {@link At#desc @At.desc}) this allows a minimum number of matches to + * be specified in order to provide early validation that the selector + * matched the correct number of candidates. To specify an exact number of + * matches, set {@link #max max} to the same value as min. Values + * less than zero are ignored since selectors cannot match a negative number + * of times. + */ + public int min() default 0; + + /** + * The maximum number of times this selector can match. By default the + * selector is allowed to match an unlimited number of targets. When + * selecting fields or methods, setting this value to anything other than 1 + * is pointless since the member can either be present or absent. However + * when matching method calls or field accesses (eg. when + * using this value inside {@link At#desc @At.desc}) this allows a + * maximum number of matches to be specified in order to limit the number of + * times that the selector can match candidates. To specify an exact number + * of matches, set max to the same value as {@link #min min}. + * Values less than 1 are treated as Integer.MAX_VALUE (the + * default) since setting a value of 0 or less has no meaning. + */ + public int max() default Integer.MAX_VALUE; + } 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 5a2f332e..d9c371f0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/InjectionPoint.java @@ -58,6 +58,7 @@ import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionExceptio import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.struct.AnnotatedMethodInfo; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; +import org.spongepowered.asm.service.MixinService; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.IMessageSink; @@ -720,7 +721,7 @@ public abstract class InjectionPoint { if (ipClass == null) { if (type.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) { try { - ipClass = (Class)Class.forName(type); + ipClass = (Class)MixinService.getService().getClassProvider().findClass(type); InjectionPoint.types.put(type, ipClass); } catch (Exception ex) { throw new InvalidInjectionException(context, data + " could not be loaded or is not a valid InjectionPoint", ex); 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 633649ec..9a2b54f3 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 @@ -620,12 +620,13 @@ public abstract class Injector { * @param exceptionType Type of exception to throw (binary name) * @param message Message to pass to the exception constructor */ - protected void throwException(InsnList insns, String exceptionType, String message) { + protected void throwException(InsnList insns, Extension extraStack, String exceptionType, String message) { insns.add(new TypeInsnNode(Opcodes.NEW, exceptionType)); insns.add(new InsnNode(Opcodes.DUP)); insns.add(new LdcInsnNode(message)); insns.add(new MethodInsnNode(Opcodes.INVOKESPECIAL, exceptionType, "", "(Ljava/lang/String;)V", false)); insns.add(new InsnNode(Opcodes.ATHROW)); + extraStack.add(3); } /** 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 6e6d1967..efaf1860 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 @@ -774,7 +774,7 @@ public class RedirectInjector extends InvokeInjector { LabelNode nullCheckSucceeded = new LabelNode(); insns.add(new InsnNode(Opcodes.DUP)); insns.add(new JumpInsnNode(Opcodes.IFNONNULL, nullCheckSucceeded)); - this.throwException(insns, RedirectInjector.NPE, String.format("%s %s %s returned null for %s", + this.throwException(insns, extraStack, RedirectInjector.NPE, String.format("%s %s %s returned null for %s", this.annotationType, type, this, value)); insns.add(nullCheckSucceeded); extraStack.add(); 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 406cceb4..ffb250e4 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 @@ -35,10 +35,13 @@ import org.objectweb.asm.tree.InsnList; import org.objectweb.asm.tree.MethodInsnNode; import org.spongepowered.asm.mixin.MixinEnvironment.Option; import org.spongepowered.asm.mixin.injection.At; +import org.spongepowered.asm.mixin.injection.IInjectionPointContext; import org.spongepowered.asm.mixin.injection.InjectionPoint; import org.spongepowered.asm.mixin.injection.InjectionPoint.AtCode; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorByName; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; import org.spongepowered.asm.mixin.injection.struct.InjectionPointData; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.refmap.IMixinContext; @@ -108,7 +111,12 @@ public class BeforeInvoke extends InjectionPoint { /** * */ - protected final IMixinContext context; + protected final IInjectionPointContext context; + + /** + * + */ + protected final IMixinContext mixin; /** * Logger reference @@ -127,9 +135,10 @@ public class BeforeInvoke extends InjectionPoint { this.ordinal = data.getOrdinal(); this.log = data.get("log", false); this.className = this.getClassName(); - this.context = data.getMixin(); - this.allowPermissive = this.context.getOption(Option.REFMAP_REMAP) && this.context.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE) - && !this.context.getReferenceMapper().isDefault(); + this.context = data.getContext(); + this.mixin = data.getMixin(); + this.allowPermissive = this.mixin.getOption(Option.REFMAP_REMAP) && this.mixin.getOption(Option.REFMAP_REMAP_ALLOW_PERMISSIVE) + && !this.mixin.getReferenceMapper().isDefault(); } private String getClassName() { @@ -155,14 +164,14 @@ public class BeforeInvoke extends InjectionPoint { */ @Override public boolean find(String desc, InsnList insns, Collection nodes) { - this.log("{} is searching for an injection point in method with descriptor {}", this.className, desc); + this.log("{}->{} is searching for an injection point in method with descriptor {}", this.context, this.className, desc); boolean hasDescriptor = this.target instanceof ITargetSelectorByName && ((ITargetSelectorByName)this.target).getDesc() == null; boolean found = this.find(desc, insns, nodes, this.target, SearchType.STRICT); if (!found && hasDescriptor && this.allowPermissive) { this.logger.warn("STRICT match for {} using \"{}\" in {} returned 0 results, attempting permissive search. " - + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.context); + + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, this.target, this.mixin); found = this.find(desc, insns, nodes, this.target, SearchType.PERMISSIVE); } @@ -174,10 +183,10 @@ public class BeforeInvoke extends InjectionPoint { return false; } - ITargetSelector target = searchType == SearchType.PERMISSIVE ? selector.configure("permissive") : selector; + ITargetSelector target = (searchType == SearchType.PERMISSIVE ? selector.configure(Configure.PERMISSIVE) : selector) + .configure(Configure.SELECT_INSTRUCTION); - int ordinal = 0; - int found = 0; + int ordinal = 0, found = 0, matchCount = 0; ListIterator iter = insns.iterator(); while (iter.hasNext()) { @@ -185,23 +194,22 @@ public class BeforeInvoke extends InjectionPoint { if (this.matchesInsn(insn)) { MemberInfo nodeInfo = new MemberInfo(insn); - this.log("{} is considering insn {}", this.className, nodeInfo); + this.log("{}->{} is considering {}", this.context, this.className, nodeInfo); if (target.match(insn).isExactMatch()) { - this.log("{} > found a matching insn, checking preconditions...", this.className); + this.log("{}->{} > found a matching insn, checking preconditions...", this.context, this.className); + if (++matchCount > selector.getMaxMatchCount()) { + break; + } if (this.matchesOrdinal(ordinal)) { - this.log("{} > > > found a matching insn at ordinal {}", this.className, ordinal); + this.log("{}->{} > > > found a matching insn at ordinal {}", this.context, this.className, ordinal); if (this.addInsn(insns, nodes, insn)) { found++; } - - if (this.ordinal == ordinal) { - break; - } } - + ordinal++; } } @@ -211,7 +219,12 @@ public class BeforeInvoke extends InjectionPoint { if (searchType == SearchType.PERMISSIVE && found > 1) { this.logger.warn("A permissive match for {} using \"{}\" in {} matched {} instructions, this may cause unexpected behaviour. " - + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.context, found); + + "To inhibit permissive search set mixin.env.allowPermissiveMatch=false", this.className, selector, this.mixin, found); + } + + if (matchCount < selector.getMinMatchCount()) { + throw new SelectorConstraintException(selector, String.format("%s did not match the required number of targets (required=%d, matched=%d)", + selector, selector.getMinMatchCount(), matchCount)); } return found > 0; @@ -231,7 +244,7 @@ public class BeforeInvoke extends InjectionPoint { } protected boolean matchesOrdinal(int ordinal) { - this.log("{} > > comparing target ordinal {} with current ordinal {}", this.className, this.ordinal, ordinal); + this.log("{}->{} > > comparing target ordinal {} with current ordinal {}", this.context, this.className, this.ordinal, ordinal); return this.ordinal == -1 || this.ordinal == ordinal; } 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 f385c897..642a41ab 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 @@ -25,6 +25,8 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.objectweb.asm.tree.AbstractInsnNode; +import org.spongepowered.asm.mixin.injection.Desc; +import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.util.asm.ElementNode; @@ -40,6 +42,11 @@ import org.spongepowered.asm.util.asm.ElementNode; * {@link MemberInfo} structs, see the javadoc for {@link MemberInfo} for the * supported variants and examples.

* + *
+ * // An example explicit target selector
+ * Lfully/qualified/OwnerClass;methodName*(III)V + *
+ * *

Pattern Target Selectors (Regex Selectors)

* *

Pattern Target Selectors are handled internally using @@ -47,26 +54,48 @@ import org.spongepowered.asm.util.asm.ElementNode; * supported variants and examples. Pattern Selectors always end with a forward * slash character.

* + *
+ * // Matches candidates ending with "Bar" and which take a single int + *
+ * /bar$/ desc=/^\\(I\\)/
+ *
+ * // The same example but with "name" explicitly specified (optional) + *
+ * name=/bar$/ desc=/^\\(I\\)/
+ *
+ * // Matches candidates whose name contains "Entity"
+ * /Entity/ + *
+ * *

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 "@":

+ * with their own specialised syntax or behaviour.

+ * + *

Built-in dynamic selectors:

+ * + *
    + *
  • {@link DynamicSelectorDesc @Desc Selector}: Selector which uses + * descriptors defined in {@link Desc @Desc} annotations
  • + *
+ * + *

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 without argument string
+ * @SelectorId
  *   
- *   // Built-in dynamic selector with empty 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)
+ * // 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)
+ * // 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 @@ -76,6 +105,67 @@ import org.spongepowered.asm.util.asm.ElementNode; */ public interface ITargetSelector { + /** + * Available selector reconfigurations + */ + public enum Configure { + + /** + * Configure this selector for matching members in a class. Usually used + * to set defaults for match limits based on role. + */ + SELECT_MEMBER(0), + + /** + * Configure this selector for matching field and method instructions in + * a method body. Usually used to set defaults for match limits. + */ + SELECT_INSTRUCTION(0), + + /** + * Where supported, changes the owner selection to the specified value. + */ + MOVE(1), + + /** + * Where supported, changes the owner selection to match all owners, + * retaining other properties. + */ + ORPHAN(0), + + /** + * Where supported, changes the descriptor to the specified value. + */ + TRANSFORM(1), + + /** + * Where supported, changes the descriptor to match all target + * descriptors, retaining other properties + */ + PERMISSIVE(0), + + /** + * Where supported, removes the min and max limits for the selector, + * allowing it to return as many or as few matches as required. + */ + CLEAR_LIMITS(0); + + private int requiredArgs; + + private Configure(int requiredArgs) { + this.requiredArgs = requiredArgs; + } + + public void checkArgs(String... args) throws IllegalArgumentException { + int argc = args == null ? 0 : args.length; + if (argc < this.requiredArgs) { + throw new IllegalArgumentException("Insufficient arguments for " + this.name() + " mutation. Required " + this.requiredArgs + + " but received " + argc); + } + } + + } + /** * 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 @@ -90,19 +180,22 @@ public interface ITargetSelector { * supplied arguments. Results from this method should be idempotent in * terms of the configuration of the returned object, but do not have to * necessarily return the same object if the callee already matches the - * supplied configuration, though this is generally the case. + * supplied configuration, or if the requested mutation is not supported by + * the selector, though this is generally the case. * - *

In other words, calling configure("foo") when this object is - * already configured according to "foo" may simply return this - * object, or might return an identically-configured copy.

+ *

In other words, calling configure(Configure.ORPHAN) when this + * object is already an orphan or does not support orphaning, may + * simply return this object, or might return an identically-configured + * copy.

* - *

Must not return null

+ *

Must not return null, defaults to returning unmodified selector.

* + * @param request Requested operation * @param args Configuration arguments * @return Configured selector, may return this selector if the specified * condition is already satisfied */ - public abstract ITargetSelector configure(String... args); + public abstract ITargetSelector configure(Configure request, String... args); /** * Perform basic sanity-check validation of the selector, checks that the @@ -126,9 +219,14 @@ public interface ITargetSelector { public abstract ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException; /** - * Number of candidates which this selector should match + * Minimum number of candidates this selector must match */ - public abstract int getMatchCount(); + public abstract int getMinMatchCount(); + + /** + * Maximum number of candidates this selector can match + */ + public abstract int getMaxMatchCount(); /** * Test whether this selector matches the supplied element node diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java index c1c9d803..ccfb1299 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorByName.java @@ -44,43 +44,6 @@ public interface ITargetSelectorByName extends ITargetSelector { */ public abstract String getDesc(); - /** - * Get whether this reference is fully qualified - * - * @return true if all components of this reference are non-null - */ - public abstract boolean isFullyQualified(); - - /** - * Get whether this target selector is definitely a field, the output of - * this method is undefined if {@link #isFullyQualified} returns false. - * - * @return true if this is definitely a field - */ - public abstract boolean isField(); - - /** - * Get whether this member represents a constructor - * - * @return true if member name is <init> - */ - public abstract boolean isConstructor(); - - /** - * Get whether this selector represents a class initialiser - * - * @return true if member name is <clinit> - */ - public abstract boolean isClassInitialiser(); - - /** - * Get whether this selector represents a constructor or class initialiser - * - * @return true if member name is <init> or - * <clinit> - */ - public abstract boolean isInitialiser(); - /** * Get a representation of this selector as a complete descriptor */ 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 index 234a5f43..e9ffee8e 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorDynamic.java @@ -24,6 +24,7 @@ */ package org.spongepowered.asm.mixin.injection.selectors; +import java.lang.annotation.Annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; @@ -58,5 +59,20 @@ public interface ITargetSelectorDynamic extends ITargetSelector { public String value(); } + + /** + * Decoration for subclasses which indicates an annotation type from which + * the selector can be parsed. + */ + @Retention(RetentionPolicy.RUNTIME) + @java.lang.annotation.Target(ElementType.TYPE) + public @interface SelectorAnnotation { + + /** + * Annotation type for the selector + */ + public Class value(); + + } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java index 55780b59..9cc3253d 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/ITargetSelectorRemappable.java @@ -33,7 +33,44 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; * service */ public interface ITargetSelectorRemappable extends ITargetSelectorByName { + + /** + * Get whether this reference is fully qualified + * + * @return true if all components of this reference are non-null + */ + public abstract boolean isFullyQualified(); + + /** + * Get whether this target selector is definitely a field, the output of + * this method is undefined if {@link #isFullyQualified} returns false. + * + * @return true if this is definitely a field + */ + public abstract boolean isField(); + + /** + * Get whether this member represents a constructor + * + * @return true if member name is <init> + */ + public abstract boolean isConstructor(); + /** + * Get whether this selector represents a class initialiser + * + * @return true if member name is <clinit> + */ + public abstract boolean isClassInitialiser(); + + /** + * Get whether this selector represents a constructor or class initialiser + * + * @return true if member name is <init> or + * <clinit> + */ + public abstract boolean isInitialiser(); + /** * Returns this selector as a {@link MappingField} or * {@link MappingMethod} 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 index 519b90b4..42feb510 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/InvalidSelector.java @@ -27,10 +27,21 @@ package org.spongepowered.asm.mixin.injection.selectors; import org.objectweb.asm.tree.AbstractInsnNode; import org.spongepowered.asm.util.asm.ElementNode; +/** + * Since the contract of {@link TargetSelector#parse} prohibits returing + * null, instances of this selector are returned when supplied arguments + * are unparseable in order to throw exceptions only during validation. + */ public class InvalidSelector implements ITargetSelector { + /** + * The original input string, used in error messages + */ private String input; + /** + * The cause of the parser failure, emitted from {@link #validate} + */ private Throwable cause; public InvalidSelector(Throwable cause) { @@ -45,17 +56,37 @@ public class InvalidSelector implements ITargetSelector { this.input = input; this.cause = cause; } + + @Override + public String toString() { + if (this.cause != null) { + return String.format("%s: %s", this.cause.getClass().getName(), this.cause.getMessage()); + } + return this.input; + } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #next() + */ @Override public ITargetSelector next() { return null; } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #configure(ITargetSelector.Configure, java.lang.String[]) + */ @Override - public ITargetSelector configure(String... args) { + public ITargetSelector configure(Configure request, String... args) { return this; } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #validate() + */ @Override public ITargetSelector validate() throws InvalidSelectorException { if (this.cause instanceof InvalidSelectorException) { @@ -71,22 +102,47 @@ public class InvalidSelector implements ITargetSelector { throw new InvalidSelectorException(message); } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #attach(ISelectorContext) + */ @Override public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { return this; } - + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #getMinMatchCount() + */ @Override - public int getMatchCount() { + public int getMinMatchCount() { return 0; } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #getMaxMatchCount() + */ + @Override + public int getMaxMatchCount() { + return 0; + } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #match(org.spongepowered.asm.util.asm.ElementNode) + */ @Override public MatchResult match(ElementNode node) { this.validate(); return MatchResult.NONE; } + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #match(org.objectweb.asm.tree.AbstractInsnNode) + */ @Override public MatchResult match(AbstractInsnNode insn) { this.validate(); diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java index 7700e855..f3d77f03 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/MemberMatcher.java @@ -121,7 +121,7 @@ public final class MemberMatcher implements ITargetSelector { * @param context selector context * @return parsed MemberMatcher */ - public static MemberMatcher parse(String input, ISelectorContext context) { + public static MemberMatcher parse(final String input, ISelectorContext context) { Matcher matcher = MemberMatcher.PATTERN.matcher(input); Pattern[] patterns = new Pattern[3]; Exception parseException = null; @@ -173,6 +173,11 @@ public final class MemberMatcher implements ITargetSelector { return this; } + @Override + public String toString() { + return this.input; + } + /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector * #next() @@ -187,7 +192,8 @@ public final class MemberMatcher implements ITargetSelector { * #configure(java.lang.String[]) */ @Override - public ITargetSelector configure(String... args) { + public ITargetSelector configure(Configure request, String... args) { + request.checkArgs(args); return this; } @@ -200,13 +206,22 @@ public final class MemberMatcher implements ITargetSelector { public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { return this; } + + /* (non-Javadoc) + * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector + * #getMinMatchCount() + */ + @Override + public int getMinMatchCount() { + return 0; + } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #getMatchCount() + * #getMaxMatchCount() */ @Override - public int getMatchCount() { + public int getMaxMatchCount() { return Integer.MAX_VALUE; } 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 c255a165..f5a6815c 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,26 +24,34 @@ */ package org.spongepowered.asm.mixin.injection.selectors; +import java.lang.annotation.Annotation; 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.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; +import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.tools.Diagnostic.Kind; +import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorAnnotation; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; -import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; import org.spongepowered.asm.mixin.injection.struct.MemberInfo; import org.spongepowered.asm.mixin.throwables.MixinError; import org.spongepowered.asm.mixin.throwables.MixinException; +import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.asm.ElementNode; +import org.spongepowered.asm.util.asm.IAnnotationHandle; import org.spongepowered.asm.util.logging.MessageRouter; import com.google.common.base.Strings; @@ -111,20 +119,42 @@ public final class TargetSelector { final Class type; - final Method parse; - + final Class annotation; + + final Method mdParseString, mdParseAnnotation; + 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())) { + this.mdParseString = type.getDeclaredMethod("parse", String.class, ISelectorContext.class); + if (!Modifier.isStatic(this.mdParseString.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() + if (!ITargetSelectorDynamic.class.isAssignableFrom(this.mdParseString.getReturnType())) { + throw new MixinError("parse(String) method for dynamic target selector [" + this.type.getName() + "] must return an ITargetSelectorDynamic subtype"); } + + Class annotation = null; + Method mdParseAnnotation = null; + + SelectorAnnotation selectorAnnotation = type.getAnnotation(SelectorAnnotation.class); + if (selectorAnnotation != null) { + annotation = selectorAnnotation.value(); + mdParseAnnotation = type.getDeclaredMethod("parse", IAnnotationHandle.class, ISelectorContext.class); + + if (!Modifier.isStatic(mdParseAnnotation.getModifiers())) { + throw new MixinError("parse method for dynamic target selector [" + this.type.getName() + "] must be static"); + } + if (!ITargetSelectorDynamic.class.isAssignableFrom(mdParseAnnotation.getReturnType())) { + throw new MixinError("parse(Annotation) method for dynamic target selector [" + this.type.getName() + + "] must return an ITargetSelectorDynamic subtype"); + } + } + + this.annotation = annotation; + this.mdParseAnnotation = mdParseAnnotation; } String getCode() { @@ -132,8 +162,16 @@ public final class TargetSelector { } ITargetSelectorDynamic parse(String input, ISelectorContext context) throws ReflectiveOperationException { + return this.parse(input, context, this.mdParseString); + } + + ITargetSelectorDynamic parse(IAnnotationHandle input, ISelectorContext context) throws ReflectiveOperationException { + return this.parse(input, context, this.mdParseAnnotation); + } + + ITargetSelectorDynamic parse(Object input, ISelectorContext context, Method parseMethod) throws ReflectiveOperationException { try { - return (ITargetSelectorDynamic)this.parse.invoke(null, input, context); + return (ITargetSelectorDynamic)parseMethod.invoke(null, input, context); } catch (InvocationTargetException itex) { Throwable cause = itex.getCause(); if (cause instanceof MixinException) { @@ -234,6 +272,18 @@ public final class TargetSelector { TargetSelector.dynamicSelectors.put("mixin:" + entry.id, entry); } + /** + * Parse a target selector from the supplied annotation and perform + * validation + * + * @param annotation Annotation to parse target selector from + * @param context Context to use for reference mapping + * @return parsed target selector + */ + public static ITargetSelector parseAndValidate(IAnnotationHandle annotation, ISelectorContext context) throws InvalidSelectorException { + return TargetSelector.parse(annotation, context).validate(); + } + /** * Parse a target selector from a string and perform validation * @@ -241,10 +291,98 @@ public final class TargetSelector { * @param context Context to use for reference mapping * @return parsed target selector */ - public static ITargetSelector parseAndValidate(String string, ISelectorContext context) throws InvalidMemberDescriptorException { + public static ITargetSelector parseAndValidate(String string, ISelectorContext context) throws InvalidSelectorException { return TargetSelector.parse(string, context).validate(); } + /** + * Parse a collection of target selector representations (strings, + * annotations, class literals) into selectors. + * + * @param selectors Selectors to parse + * @param context Selection context + * @return parsed collection of selectors, uses LinkedHashSet to preserve + * parse ordering + */ + public static Set parseAndValidate(Iterable selectors, ISelectorContext context) throws InvalidSelectorException { + Set parsed = TargetSelector.parse(selectors, context, new LinkedHashSet()); + for (ITargetSelector selector : parsed) { + selector.validate(); + } + return parsed; + } + + /** + * Parse a collection of target selector representations (strings, + * annotations, class literals) into selectors. + * + * @param selectors Selectors to parse + * @param context Selection context + * @return parsed collection of selectors, uses LinkedHashSet to preserve + * parse ordering + */ + public static Set parse(Iterable selectors, ISelectorContext context) { + return TargetSelector.parse(selectors, context, new LinkedHashSet()); + } + + /** + * Parse a collection of target selector representations (strings, + * annotations, class literals) into selectors and store them in the + * provided collection. + * + * @param selectors Selectors to parse + * @param context Selection context + * @param parsed Collection to add parsed selectors to, initialised as a + * LinkedHashSet if null + * @return the same collection passed in via the parsed parameter, + * for convenience + */ + public static Set parse(Iterable selectors, ISelectorContext context, Set parsed) { + if (parsed == null) { + parsed = new LinkedHashSet(); + } + if (selectors != null) { + for (Object selector : selectors) { + if (selector instanceof IAnnotationHandle) { + parsed.add(TargetSelector.parse((IAnnotationHandle)selector, context)); + } else if (selector instanceof AnnotationNode) { + parsed.add(TargetSelector.parse(Annotations.handleOf(selector), context)); + } else if (selector instanceof String) { + parsed.add(TargetSelector.parse((String)selector, context)); + } else if (selector instanceof Class) { + String desc = Type.getType((Class)selector).getDescriptor(); + parsed.add(TargetSelector.parse(desc, context)); + } else if (selector != null) { + parsed.add(TargetSelector.parse(selector.toString(), context)); + } + } + } + return parsed; + } + + /** + * Parse a target selector from the supplied annotation + * + * @param annotation String to parse target selector from + * @param context Context to use for reference mapping + * @return parsed target selector + */ + public static ITargetSelector parse(IAnnotationHandle annotation, ISelectorContext context) { + for (DynamicSelectorEntry entry : TargetSelector.dynamicSelectors.values()) { + if (entry.annotation != null && Annotations.getDesc(entry.annotation).equals(annotation.getDesc())) { + try { + return entry.parse(annotation, context); + } catch (ReflectiveOperationException ex) { + return new InvalidSelector(ex.getCause()); + } catch (Exception ex) { + return new InvalidSelector(ex); + } + } + } + + return new InvalidSelector(new InvalidSelectorException("Dynamic selector for annotation " + annotation + " is not registered.")); + } + /** * Parse a target selector from a string * @@ -313,30 +451,30 @@ public final class TargetSelector { /** * Run query on supplied target nodes * - * @param target Target selector + * @param selector Target selector * @param nodes Node collection to enumerate * @param Node type * @return query result */ - public static Result run(ITargetSelector target, List> nodes) { + public static Result run(ITargetSelector selector, List> nodes) { List candidates = new ArrayList(); - TNode exactMatch = TargetSelector.runSelector(target, nodes, candidates); + TNode exactMatch = TargetSelector.runSelector(selector, nodes, candidates); return new Result(exactMatch, candidates); } /** * Run query on supplied target nodes * - * @param targets Target selector + * @param selector Target selector * @param nodes Node collection to enumerate * @param Node type * @return query result */ - public static Result run(Iterable targets, List> nodes) { + public static Result run(Iterable selector, List> nodes) { TNode exactMatch = null; List candidates = new ArrayList(); - for (ITargetSelector target : targets) { + for (ITargetSelector target : selector) { TNode selectorExactMatch = TargetSelector.runSelector(target, nodes, candidates); if (exactMatch == null) { exactMatch = selectorExactMatch; @@ -346,11 +484,16 @@ public final class TargetSelector { return new Result(exactMatch, candidates); } - private static TNode runSelector(ITargetSelector target, List> nodes, List candidates) { + private static TNode runSelector(ITargetSelector selector, List> nodes, List candidates) { + int matchCount = 0; TNode exactMatch = null; for (ElementNode element : nodes) { - MatchResult match = target.match(element); + MatchResult match = selector.match(element); if (match.isMatch()) { + matchCount++; + if (matchCount > selector.getMaxMatchCount()) { + break; + } TNode node = element.get(); if (!candidates.contains(node)) { candidates.add(node); @@ -360,6 +503,12 @@ public final class TargetSelector { } } } + + if (matchCount < selector.getMinMatchCount()) { + throw new SelectorConstraintException(selector, String.format("%s did not match the required number of targets (required=%d, matched=%d)", + selector, selector.getMinMatchCount(), matchCount)); + } + return exactMatch; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java index 62dd7197..8257c664 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DescriptorResolver.java @@ -39,6 +39,7 @@ import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext; import org.spongepowered.asm.mixin.transformer.MixinTargetContext; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.PrettyPrinter; +import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.asm.IAnnotatedElement; import org.spongepowered.asm.util.asm.IAnnotationHandle; @@ -63,20 +64,20 @@ public final class DescriptorResolver { */ private final Set searched; - /** - * Selector context - */ - private final ISelectorContext context; - /** * The resolved descriptor */ private final IAnnotationHandle desc; + + /** + * Selector context + */ + private final ISelectorContext context; - Descriptor(Set searched, ISelectorContext context, IAnnotationHandle desc) { + Descriptor(Set searched, IAnnotationHandle desc, ISelectorContext context) { this.searched = searched; - this.context = context; this.desc = desc; + this.context = context; } /** @@ -119,7 +120,7 @@ public final class DescriptorResolver { if (this.desc == null) { return Type.VOID_TYPE; } - Type ownerClass = this.desc.getValue("owner", Type.VOID_TYPE); + Type ownerClass = this.desc.getTypeValue("owner"); return ownerClass == Type.VOID_TYPE ? Type.getObjectType(this.context.getMixin().getTargetClassRef()) : ownerClass; } @@ -149,7 +150,18 @@ public final class DescriptorResolver { if (this.desc == null) { return Type.VOID_TYPE; } - return this.desc.getValue("ret", Type.VOID_TYPE); + return this.desc.getTypeValue("ret"); + } + + @Override + public Quantifier getMatches() { + if (this.desc == null) { + return Quantifier.DEFAULT; + } + + int min = Math.max(0, this.desc != null ? this.desc.getValue("min", 0) : 0); + Integer max = this.desc != null ? this.desc.getValue("max", null) : null; + return new Quantifier(min, max != null ? (max > 0 ? max : Integer.MAX_VALUE) : -1); } } @@ -244,8 +256,8 @@ public final class DescriptorResolver { private DescriptorResolver() { } - public static IResolvedDescriptor resolve(ISelectorContext context, IAnnotationHandle desc) { - return new Descriptor(Collections.emptySet(), context, desc); + public static IResolvedDescriptor resolve(IAnnotationHandle desc, ISelectorContext context) { + return new Descriptor(Collections.emptySet(), desc, context); } /** @@ -268,14 +280,13 @@ public final class DescriptorResolver { IAnnotationHandle desc = DescriptorResolver.resolve(id, context, observer, context.getSelectorCoordinate(true)); observer.postResolve(); - return new Descriptor(observer.getSearched(), context, desc); + return new Descriptor(observer.getSearched(), desc, context); } /** * Recursive function which checks an element and then recurses to parent */ private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate) { - IAnnotationHandle annotation = Annotations.handleOf(context.getSelectorAnnotation()); observer.visit(coordinate, annotation, annotation.toString() + ".desc"); @@ -293,7 +304,8 @@ public final class DescriptorResolver { ISelectorContext root = DescriptorResolver.getRoot(context); String rootCoordinate = root.getSelectorCoordinate(false); - String mixinCoordinate = root != context && !rootCoordinate.equals(coordinate) ? rootCoordinate + "." + coordinate : coordinate; + String mixinCoordinate = (root != context || !coordinate.contains(".")) && !rootCoordinate.equals(coordinate) + ? rootCoordinate + "." + coordinate : coordinate; // Next check with the current coordinates on the mixin resolved = DescriptorResolver.resolve(id, context, observer, mixinCoordinate, context.getMixin(), "mixin"); @@ -386,7 +398,8 @@ public final class DescriptorResolver { } else if (element instanceof MixinTargetContext) { return Annotations.handleOf(Annotations.getVisible(((MixinTargetContext)element).getClassNode(), annotationClass)); } else if (element instanceof IAnnotatedElement) { - return ((IAnnotatedElement)element).getAnnotation(annotationClass); + IAnnotationHandle annotation = ((IAnnotatedElement)element).getAnnotation(annotationClass); + return annotation != null && annotation.exists() ? annotation : null; } else if (element == null) { return null; } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java index ed773f26..7175cab2 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorDesc.java @@ -34,13 +34,20 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.Slice; 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.ITargetSelectorByName; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorAnnotation; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId; +import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.MatchResult; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Quantifier; +import org.spongepowered.asm.util.SignaturePrinter; import org.spongepowered.asm.util.asm.ElementNode; import org.spongepowered.asm.util.asm.IAnnotationHandle; +import com.google.common.base.Strings; + /** * A {@link ITargetSelector Target Selector} which matches candidates using * descriptors contained in {@link Desc @Desc} annotations. The descriptor @@ -137,7 +144,7 @@ import org.spongepowered.asm.util.asm.IAnnotationHandle; *     @Inject(method = "@Desc", at = @At(value = * "INVOKE" target = "@Desc(?)")) *
- *     void myHandlerMethod(int arg, CallbackInfo ci) { + *     void myHandler(int arg, CallbackInfo ci) { * * *

This will cause the resolver to pretty-print the considered coordinates @@ -160,7 +167,8 @@ import org.spongepowered.asm.util.asm.IAnnotationHandle; * supports.

*/ @SelectorId("Desc") -public final class DynamicSelectorDesc extends DynamicSelectorAbstract { +@SelectorAnnotation(Desc.class) +public final class DynamicSelectorDesc implements ITargetSelectorDynamic, ITargetSelectorByName { /** * Parser/resolver error mesage, only stored if the descriptor is invalid so @@ -203,15 +211,24 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { */ private final String methodDesc; + /** + * Required matches + */ + private final Quantifier matches; + private DynamicSelectorDesc(IResolvedDescriptor desc) { - this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType()); + this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType(), desc.getMatches()); + } + + private DynamicSelectorDesc(DynamicSelectorDesc desc, Quantifier quantifier) { + this(desc.parseException, desc.id, desc.owner, desc.name, desc.args, desc.returnType, quantifier); } private DynamicSelectorDesc(InvalidSelectorException ex) { - this(ex, null, null, null, null, null); + this(ex, null, null, null, null, null, Quantifier.NONE); } - private DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType) { + private DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType, Quantifier matches) { this.parseException = ex; this.id = id; @@ -219,7 +236,8 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { this.name = name; this.args = args; this.returnType = returnType; - this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null; + this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null; + this.matches = matches; } /** @@ -235,8 +253,22 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { IResolvedDescriptor descriptor = DescriptorResolver.resolve(input, context); if (!descriptor.isResolved()) { String extra = input.length() == 0 ? ". " + descriptor.getResolutionInfo() : ""; - InvalidSelectorException ex = new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra); - return new DynamicSelectorDesc(ex); + return new DynamicSelectorDesc(new InvalidSelectorException("Could not resolve @Desc(" + input + ") for " + context + extra)); + } + return DynamicSelectorDesc.of(descriptor); + } + + /** + * Convert the supplied annotation into a selector instance + * + * @param context Selector context + * @param desc Annotation to parse + * @return selector + */ + public static DynamicSelectorDesc parse(IAnnotationHandle desc, ISelectorContext context) { + IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context); + if (!descriptor.isResolved()) { + return new DynamicSelectorDesc(new InvalidSelectorException("Invalid descriptor")); } return DynamicSelectorDesc.of(descriptor); } @@ -259,16 +291,16 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { /** * Convert the supplied annotation into a selector instance * - * @param context Selector context * @param desc Annotation to parse + * @param context Selector context * @return selector */ - public static DynamicSelectorDesc of(ISelectorContext context, IAnnotationHandle desc) { - IResolvedDescriptor descriptor = DescriptorResolver.resolve("", context); + public static DynamicSelectorDesc of(IAnnotationHandle desc, ISelectorContext context) { + IResolvedDescriptor descriptor = DescriptorResolver.resolve(desc, context); if (!descriptor.isResolved()) { return null; } - return DynamicSelectorDesc.of(context, descriptor.getAnnotation()); + return DynamicSelectorDesc.of(descriptor); } /** @@ -281,18 +313,61 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { return new DynamicSelectorDesc(desc); } + @Override + public String toString() { + StringBuilder sb = new StringBuilder("@Desc("); + boolean started = false; + if (!Strings.isNullOrEmpty(this.id)) { + sb.append("id = \"").append(this.id).append("\""); + started = true; + } + + if (this.owner != Type.VOID_TYPE) { + if (started) { + sb.append(", "); + } + sb.append("owner = ").append(SignaturePrinter.getTypeName(this.owner, false, false)).append(".class"); + started = true; + } + + if (started) { + sb.append(", "); + } + sb.append("name = \"").append(this.name).append("\""); + + if (this.args.length > 0) { + sb.append(", args = { "); + for (int i = 0; i < this.args.length; i++) { + if (i > 0) { + sb.append(", "); + } + sb.append(SignaturePrinter.getTypeName(this.args[i], false, false)).append(".class"); + } + sb.append(" }"); + } + + if (this.returnType != Type.VOID_TYPE) { + sb.append(", ret = ").append(SignaturePrinter.getTypeName(this.returnType, false, false)).append(".class"); + } + + sb.append(")"); + return sb.toString(); + } + public String getId() { return this.id; } - public Type getOwner() { - return this.owner; + @Override + public String getOwner() { + return this.owner.getInternalName(); } - + + @Override public String getName() { return this.name; } - + public Type[] getArgs() { return this.args; } @@ -300,7 +375,17 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { public Type getReturnType() { return this.returnType; } - + + @Override + public String getDesc() { + return this.methodDesc; + } + + @Override + public String toDescriptor() { + return new SignaturePrinter(this).setFullyQualified(true).toDescriptor(); + } + @Override public ITargetSelector validate() throws InvalidSelectorException { if (this.parseException != null) { @@ -313,10 +398,54 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract { public ITargetSelector next() { return this; // Recurse } - + @Override - public int getMatchCount() { - return 1; + public ITargetSelector configure(Configure request, String... args) { + request.checkArgs(args); + switch (request) { + case SELECT_MEMBER: + if (this.matches.isDefault()) { + return new DynamicSelectorDesc(this, Quantifier.SINGLE); + } + break; + case SELECT_INSTRUCTION: + if (this.matches.isDefault()) { + return new DynamicSelectorDesc(this, Quantifier.ANY); + } + break; + case MOVE: + return new DynamicSelectorDesc(this.parseException, this.id, Type.getObjectType(args[0]), this.name, this.args, this.returnType, + this.matches); + case CLEAR_LIMITS: + if (this.getMinMatchCount() != 0 || this.getMaxMatchCount() < Integer.MAX_VALUE) { + return new DynamicSelectorDesc(this.parseException, this.id, Type.getObjectType(args[0]), this.name, this.args, this.returnType, + Quantifier.ANY); + } + break; + default: + break; + } + return this; + } + + @Override + public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { + return this; + } + + @Override + public int getMinMatchCount() { + return this.matches.getClampedMin(); + } + + @Override + public int getMaxMatchCount() { + return this.matches.getClampedMax(); + } + + @Override + public MatchResult matches(String owner, String name, String desc) { + return this.matches(owner, name, desc, this.methodDesc); } /* (non-Javadoc) diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java index 5b1bc5e9..c6a99687 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/IResolvedDescriptor.java @@ -25,6 +25,7 @@ package org.spongepowered.asm.mixin.injection.selectors.dynamic; import org.objectweb.asm.Type; +import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.asm.IAnnotationHandle; /** @@ -77,5 +78,10 @@ public interface IResolvedDescriptor { * if the descriptor was not resolved. */ public abstract Type getReturnType(); + + /** + * Get the specified matches values from the resolved descriptor. + */ + public abstract Quantifier getMatches(); } 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/throwables/SelectorConstraintException.java similarity index 61% rename from src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java rename to src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorConstraintException.java index 70f6d2b3..7b3e5079 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/dynamic/DynamicSelectorAbstract.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorConstraintException.java @@ -22,36 +22,30 @@ * 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; +package org.spongepowered.asm.mixin.injection.selectors.throwables; -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 + * Exception to be thrown when a {@link ITargetSelector target selector} + * {@link ITargetSelector#getMinMatchCount min} or + * {@link ITargetSelector#getMaxMatchCount max} constraint is not met when + * running the selector */ -public abstract class DynamicSelectorAbstract implements ITargetSelectorDynamic { +public class SelectorConstraintException extends SelectorException { - @Override - public ITargetSelector configure(String... args) { - return this; + private static final long serialVersionUID = 1L; + + public SelectorConstraintException(ITargetSelector selector, String message) { + super(selector, message); } - @Override - public ITargetSelector validate() throws InvalidSelectorException { - return this; + public SelectorConstraintException(ITargetSelector selector, Throwable cause) { + super(selector, cause); } - @Override - public ITargetSelector attach(ISelectorContext context) throws InvalidSelectorException { - return this; - } - - @Override - public int getMatchCount() { - return Integer.MAX_VALUE; + public SelectorConstraintException(ITargetSelector selector, String message, Throwable cause) { + super(selector, message, cause); } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java new file mode 100644 index 00000000..f681e05f --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/SelectorException.java @@ -0,0 +1,59 @@ +/* + * 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.throwables; + +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.throwables.MixinException; + +/** + * Exception to be thrown for error conditions raised by {@link ITargetSelector + * target selectors} + */ +public class SelectorException extends MixinException { + + private static final long serialVersionUID = 1L; + + private final ITargetSelector selector; + + public SelectorException(ITargetSelector selector, String message) { + super(message); + this.selector = selector; + } + + public SelectorException(ITargetSelector selector, Throwable cause) { + super(cause); + this.selector = selector; + } + + public SelectorException(ITargetSelector selector, String message, Throwable cause) { + super(message, cause); + this.selector = selector; + } + + public ITargetSelector getSelector() { + return this.selector; + } + +} diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java new file mode 100644 index 00000000..5227389e --- /dev/null +++ b/src/main/java/org/spongepowered/asm/mixin/injection/selectors/throwables/package-info.java @@ -0,0 +1,29 @@ +/* + * 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. + */ + +/** + * Exceptions for selectors. + */ +package org.spongepowered.asm.mixin.injection.selectors.throwables; 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 63ee06a7..1a5f83ce 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 @@ -30,8 +30,16 @@ import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.reflect.Constructor; import java.lang.reflect.InvocationTargetException; -import java.util.*; +import java.util.ArrayDeque; +import java.util.ArrayList; +import java.util.Collection; +import java.util.Deque; +import java.util.LinkedHashMap; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Map; import java.util.Map.Entry; +import java.util.Set; import javax.tools.Diagnostic.Kind; @@ -51,9 +59,11 @@ import org.spongepowered.asm.mixin.injection.code.InjectorTarget; import org.spongepowered.asm.mixin.injection.code.MethodSlice; import org.spongepowered.asm.mixin.injection.code.MethodSlices; import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector; +import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector.Configure; import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; import org.spongepowered.asm.mixin.injection.selectors.TargetSelector; -import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorConstraintException; +import org.spongepowered.asm.mixin.injection.selectors.throwables.SelectorException; import org.spongepowered.asm.mixin.injection.struct.InjectionNodes.InjectionNode; import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; @@ -293,13 +303,24 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC protected Set parseTargets() { Set selectors = new LinkedHashSet(); + TargetSelector.parse(Annotations.getValue(this.annotation, "method", false), this, selectors); + TargetSelector.parse(Annotations.getValue(this.annotation, "target", false), this, selectors); + + // Raise an error if we have no selectors + if (selectors.size() == 0) { + throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets", + this.annotationType, this.methodName)); + } + + Set attachedSelectors = new LinkedHashSet(); - for (String method : Annotations.getValue(this.annotation, "method", false)) { + // Validate and attach the parsed selectors + for (ITargetSelector selector : selectors) { try { - selectors.add(TargetSelector.parseAndValidate(method, this).attach(this)); + attachedSelectors.add(selector.validate().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())); + throw new InvalidInjectionException(this, String.format("%s annotation on %s, has invalid target descriptor: %s. %s", + this.annotationType, this.methodName, ex.getMessage(), this.mixin.getReferenceMapper().getStatus())); } catch (TargetNotSupportedException ex) { throw new InvalidInjectionException(this, String.format("%s annotation on %s specifies a target class '%s', which is not supported", @@ -310,22 +331,8 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC ex.getMessage())); } } - - for (AnnotationNode target : Annotations.getValue(this.annotation, "target", false)) { - try { - selectors.add(DynamicSelectorDesc.of(this, Annotations.handleOf(target)).validate()); - } catch (InvalidSelectorException ex) { - throw new InvalidInjectionException(this, - String.format("%s annotation on %s is decorated with an invalid selector: %s", this.annotationType, this.methodName, - ex.getMessage())); - } - } - - if (selectors.size() == 0) { - throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets", - this.annotationType, this.methodName)); - } - return selectors; + + return attachedSelectors; } protected List readInjectionPoints() { @@ -383,8 +390,14 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC for (MethodNode targetMethod : this.targets) { Target target = this.mixin.getTargetMethod(targetMethod); InjectorTarget injectorTarget = new InjectorTarget(this, target); - this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); - injectorTarget.dispose(); + try { + this.targetNodes.put(target, this.injector.find(injectorTarget, this.injectionPoints)); + } catch (SelectorException ex) { + throw new InvalidInjectionException(this, String.format("Injection validation failed: %s on %s: %s. %s%s", + this.annotationType, this.methodName, ex.getMessage(), this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo())); + } finally { + injectorTarget.dispose(); + } } } @@ -544,27 +557,42 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC int passes = this.mixin.getOption(Option.REFMAP_REMAP) ? 2 : 1; for (ITargetSelector selector : selectors) { - int matchCount = selector.getMatchCount(); - for (int count = 0, pass = 0; pass < passes && count < 1; pass++) { + selector = selector.configure(Configure.SELECT_MEMBER, null); + + int matchCount = 0; + int maxCount = selector.getMaxMatchCount(); + + // Second pass ignores descriptor + ITargetSelector permissiveSelector = selector.configure(Configure.PERMISSIVE); + if (permissiveSelector == selector) { + // Selector is already permissive, so skip the second pass + passes = 1; + } + + scan: for (int pass = 0; pass < passes && matchCount < 1; pass++) { + ITargetSelector passSelector = pass == 0 ? selector : permissiveSelector; for (MethodNode target : this.classNode.methods) { - if (selector.match(ElementNode.of(this.classNode, target)).isExactMatch()) { + if (passSelector.match(ElementNode.of(this.classNode, target)).isExactMatch()) { + matchCount++; + boolean isMixinMethod = Annotations.getVisible(target, MixinMerged.class) != null; - if (matchCount > 1 && (Bytecode.isStatic(target) != this.isStatic || target == this.method || isMixinMethod)) { - continue; + if (maxCount <= 1 || ((this.isStatic || !Bytecode.isStatic(target)) && target != this.method && !isMixinMethod)) { + this.checkTarget(target); + this.targets.add(target); } - - this.checkTarget(target); - this.targets.add(target); - count++; - - if (count >= matchCount) { - break; + + if (matchCount >= maxCount) { + break scan; } } } - - // Second pass ignores descriptor - selector = selector.configure("permissive"); + } + + if (matchCount < selector.getMinMatchCount()) { + throw new InvalidInjectionException(this, new SelectorConstraintException(selector, String.format( + "Injection validation failed: %s for %s on %s did not match the required number of targets (required=%d, matched=%d). %s%s", + selector, this.annotationType, this.methodName, selector.getMinMatchCount(), matchCount, + this.mixin.getReferenceMapper().getStatus(), this.getDynamicInfo()))); } } 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 d7c620a3..cb4290a9 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 @@ -288,7 +288,7 @@ public class InjectionPointData { if (desc != null) { String id = Annotations.getValue(desc, "id", "at"); if ("at".equalsIgnoreCase(id)) { - return DynamicSelectorDesc.of(this.context, Annotations.handleOf(desc)); + return DynamicSelectorDesc.of(Annotations.handleOf(desc), this.context); } } } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java index 0871898d..e65384b3 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InjectorGroupInfo.java @@ -264,7 +264,8 @@ public class InjectorGroupInfo { int min = this.getMinRequired(); int max = this.getMaxAllowed(); if (total < min) { - throw new InjectionValidationException(this, String.format("expected %d invocation(s) but only %d succeeded", min, total)); + String only = total > 0 ? "only " : ""; + throw new InjectionValidationException(this, String.format("expected %d invocation(s) but %s%d succeeded", min, only, total)); } else if (total > max) { throw new InjectionValidationException(this, String.format("maximum of %d invocation(s) allowed but %d succeeded", max, total)); } diff --git a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java index 82ffd7ee..c8320813 100644 --- a/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java +++ b/src/main/java/org/spongepowered/asm/mixin/injection/struct/InvalidMemberDescriptorException.java @@ -32,17 +32,25 @@ import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException; public class InvalidMemberDescriptorException extends InvalidSelectorException { private static final long serialVersionUID = 1L; + private final String input; - public InvalidMemberDescriptorException(String message) { + public InvalidMemberDescriptorException(String input, String message) { super(message); + this.input = input; } - public InvalidMemberDescriptorException(Throwable cause) { + public InvalidMemberDescriptorException(String input, Throwable cause) { super(cause); + this.input = input; } - public InvalidMemberDescriptorException(String message, Throwable cause) { + public InvalidMemberDescriptorException(String input, String message, Throwable cause) { super(message, cause); + this.input = input; + } + + public String getInput() { + return this.input; } } 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 fa59165c..36de13e2 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 @@ -41,6 +41,7 @@ import org.spongepowered.asm.obfuscation.mapping.common.MappingField; import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod; import org.spongepowered.asm.util.Bytecode; import org.spongepowered.asm.util.Constants; +import org.spongepowered.asm.util.Quantifier; import org.spongepowered.asm.util.SignaturePrinter; import org.spongepowered.asm.util.asm.ElementNode; @@ -55,46 +56,163 @@ import com.google.common.base.Strings; * target members need to be specified as Strings in order to parse the String * representation to something useful.

* - *

Some examples:

- *
- *   // references a method or field called func_1234_a, if there are
- *   // multiple members with the same signature, matches the first occurrence
- *   func_1234_a
- *   
- *   // references a method or field called func_1234_a, if there are
- *   // multiple members with matching name, matches all occurrences
- *   func_1234_a*
- *   
- *   // references all methods which take 3 ints and return a bool
- *   *(III)Z
- *   
- *   // references a method called func_1234_a which takes 3 ints and
- *   // returns a bool
- *   func_1234_a(III)Z
- *   
- *   // references a field called field_5678_z which is a String
- *   field_5678_z:Ljava/lang/String;
- *   
- *   // references a ctor which takes a single String argument 
- *   <init>(Ljava/lang/String;)V
- *   
- *   // references a method called func_1234_a in class foo.bar.Baz
- *   Lfoo/bar/Baz;func_1234_a
- *  
- *   // references a field called field_5678_z in class com.example.Dave
- *   Lcom/example/Dave;field_5678_z
- *  
- *   // references a field called field_5678_z in class com.example.Dave
- *   // which is of type String
- *   Lcom/example/Dave;field_5678_z:Ljava/lang/String;
- *  
- *   // references a method called func_1234_a in class foo.bar.Baz which
- *   // takes three doubles and returns void
- *   Lfoo/bar/Baz;func_1234_a(DDD)V
- *   
- *   // alternate syntax for the same
- *   foo.bar.Baz.func_1234_a(DDD)V
- *
+ *

In general a MemberInfo consists of 4 parts, + * owner, name, quantifier + * and descriptor, all of which are optional: + *

+ * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + * + *
 OwnerNameQuantifier DescriptorResulting selector string
MethodLfully/qualified/OwnerClass;methodName{1,3} (III)VLfully/qualified/OwnerClass;methodName{1,3}(III)V
FieldLfully/qualified/OwnerClass;fieldName*:Ljava/lang/String;Lfully/qualified/OwnerClass;fieldName*:Ljava/lang/String;
+ * + *

Any part of the selector can be omitted, though they must appear in the + * correct order. Some examples:

+ * + *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with the same signature, matches the first occurrence
+ * func_1234_a
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches all occurrences

+ * func_1234_a*
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches all occurrences, matching less than 1 + *
+ * // occurrence is an error condition

+ * func_1234_a+
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches up to 3 occurrences

+ * func_1234_a{,3}
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches exactly 3 occurrences, matching fewer + *
+ * // than 3 occurrences is an error condition

+ * func_1234_a{3}
+ *
+ * // selects a method or field called func_1234_a, if there are multiple + *
+ * // members with matching name, matches at least 3 occurrences, matching fewer + *
+ * // than 3 occurrences is an error condition

+ * func_1234_a{3,}
+ *
+ * // selects all members of any type and descriptor
+ * *
+ *
+ * // selects the first member of any type and descriptor
+ * {1}
+ *
+ * // selects all methods which take 3 ints and return a bool
+ * *(III)Z
+ *
+ * // selects the first 2 methods which take a bool and return void + *
+ * {2}(Z)V
+ *
+ * // selects a method called func_1234_a which takes 3 ints and returns a + * bool
+ * func_1234_a(III)Z
+ *
+ * // selects a field called field_5678_z which is a String
+ * field_5678_z:Ljava/lang/String; + *
+ *
+ * // selects a ctor which takes a single String argument
+ * <init>(Ljava/lang/String;)V
+ *
+ * // selects a method called func_1234_a in class foo.bar.Baz
+ * Lfoo/bar/Baz;func_1234_a + *
+ *
+ * // selects a field called field_5678_z in class com.example.Dave + *
+ * Lcom/example/Dave;field_5678_z + *
+ *
+ * // selects a field called field_5678_z in class com.example.Dave
+ * // which is of type String

+ * Lcom/example/Dave;field_5678_z:Ljava/lang/String; + *
+ *
+ * // selects a method called func_1234_a in class foo.bar.Baz which
+ * // takes three doubles and returns void

+ * Lfoo/bar/Baz;func_1234_a(DDD)V
+ *
+ * // alternate syntax for the same
+ * foo.bar.Baz.func_1234_a(DDD)V + *
+ * + *

Notes

+ * + *
    + *
  • All whitespace in the selector string is stripped before the selector + * is parsed.
  • + *
  • Quantifiers for selectors can be used as a + * form of early validation (prior to injector require directives) + * that an injection point has matched a required number of targets or to + * limit the number of matches it can return.
  • + *
  • The syntax for quantifiers is based on the + * syntax for quantifiers in regular expressions, though more + * limited. In particular: + *
      + *
    • No quantifer is equivalent to the regex ? + * quantifier, in that undecorated selectors can match {0,1}, + * this is for backward compatibility reasons. Likewise ? is + * not supported since it's implied. To require exactly one match use + * {1}.
    • + *
    • The quantifiers * and + work the same as their + * regex counterparts.
    • + *
    + *
  • + *
*/ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelectorConstructor { @@ -114,9 +232,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec private final String desc; /** - * True to match all matching members, not just the first + * Required matches */ - private final boolean matchAll; + private final Quantifier matches; /** * Force this member to report as a field @@ -126,17 +244,27 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec /** * The actual String value passed into the {@link #parse} method */ - private final String unparsed; + private final String input; + + /** + * ctor + * + * @param name Member name, must not be null + * @param matches Quantifier specifying the number of matches required + */ + public MemberInfo(String name, Quantifier matches) { + this(name, null, null, matches, null); + } /** * ctor * * @param name Member name, must not be null - * @param matchAll true if this info should match all matching references, - * or only the first + * @param minMatches Min number of matches required + * @param maxMatches Max number of matches allowed */ - public MemberInfo(String name, boolean matchAll) { - this(name, null, null, matchAll); + public MemberInfo(String name, int minMatches, int maxMatches) { + this(name, null, null, new Quantifier(minMatches, maxMatches), null); } /** @@ -145,11 +273,23 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param name Member name, must not be null * @param owner Member owner, can be null otherwise must be in internal form * without L; - * @param matchAll true if this info should match all matching references, - * or only the first + * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, String owner, boolean matchAll) { - this(name, owner, null, matchAll); + public MemberInfo(String name, String owner, Quantifier matches) { + this(name, owner, null, matches, null); + } + + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param minMatches Min number of matches required + * @param maxMatches Max number of matches allowed + */ + public MemberInfo(String name, String owner, int minMatches, int maxMatches) { + this(name, owner, null, new Quantifier(minMatches, maxMatches), null); } /** @@ -161,7 +301,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param desc Member descriptor, can be null */ public MemberInfo(String name, String owner, String desc) { - this(name, owner, desc, false); + this(name, owner, desc, Quantifier.DEFAULT, null); } /** @@ -171,10 +311,10 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param owner Member owner, can be null otherwise must be in internal form * without L; * @param desc Member descriptor, can be null - * @param matchAll True to match all matching members, not just the first + * @param matches Quantifier specifying the number of matches required */ - public MemberInfo(String name, String owner, String desc, boolean matchAll) { - this(name, owner, desc, matchAll, null); + public MemberInfo(String name, String owner, String desc, Quantifier matches) { + this(name, owner, desc, matches, null); } /** @@ -184,9 +324,37 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param owner Member owner, can be null otherwise must be in internal form * without L; * @param desc Member descriptor, can be null - * @param matchAll True to match all matching members, not just the first + * @param minMatches Min number of matches required + * @param maxMatches Max number of matches allowed */ - public MemberInfo(String name, String owner, String desc, boolean matchAll, String unparsed) { + public MemberInfo(String name, String owner, String desc, int minMatches, int maxMatches) { + this(name, owner, desc, new Quantifier(minMatches, maxMatches), null); + } + + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param desc Member descriptor, can be null + * @param minMatches Min number of matches required + * @param maxMatches Max number of matches allowed + */ + public MemberInfo(String name, String owner, String desc, int minMatches, int maxMatches, String input) { + this(name, owner, desc, new Quantifier(minMatches, maxMatches), input); + } + + /** + * ctor + * + * @param name Member name, must not be null + * @param owner Member owner, can be null otherwise must be in internal form + * without L; + * @param desc Member descriptor, can be null + * @param matches Quantifier specifying the number of matches required + */ + public MemberInfo(String name, String owner, String desc, Quantifier matches, String input) { if (owner != null && owner.contains(".")) { throw new IllegalArgumentException("Attempt to instance a MemberInfo with an invalid owner format"); } @@ -194,9 +362,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = owner; this.name = name; this.desc = desc; - this.matchAll = matchAll; + this.matches = matches; this.forceField = false; - this.unparsed = unparsed; + this.input = input; } /** @@ -206,9 +374,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param insn instruction node to copy values from */ public MemberInfo(AbstractInsnNode insn) { - this.matchAll = false; + this.matches = Quantifier.DEFAULT; this.forceField = false; - this.unparsed = null; + this.input = null; if (insn instanceof MethodInsnNode) { MethodInsnNode methodNode = (MethodInsnNode) insn; @@ -234,9 +402,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = mapping.getOwner(); this.name = mapping.getSimpleName(); this.desc = mapping.getDesc(); - this.matchAll = false; + this.matches = Quantifier.SINGLE; this.forceField = mapping.getType() == IMapping.Type.FIELD; - this.unparsed = null; + this.input = null; } /** @@ -248,9 +416,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = setOwner ? method.getOwner() : remapped.owner; this.name = method.getSimpleName(); this.desc = method.getDesc(); - this.matchAll = remapped.matchAll; + this.matches = remapped.matches; this.forceField = false; - this.unparsed = null; + this.input = null; } /** @@ -263,9 +431,9 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec this.owner = owner; this.name = original.name; this.desc = original.desc; - this.matchAll = original.matchAll; + this.matches = original.matches; this.forceField = original.forceField; - this.unparsed = null; + this.input = null; } @Override @@ -289,8 +457,13 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec } @Override - public int getMatchCount() { - return this.matchAll ? Integer.MAX_VALUE : 1; + public int getMinMatchCount() { + return this.matches.getClampedMin(); + } + + @Override + public int getMaxMatchCount() { + return this.matches.getClampedMax(); } /* (non-Javadoc) @@ -300,12 +473,12 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec public String toString() { String owner = this.owner != null ? "L" + this.owner + ";" : ""; String name = this.name != null ? this.name : ""; - String qualifier = this.matchAll ? "*" : ""; + String quantifier = this.matches.toString(); String desc = this.desc != null ? this.desc : ""; String separator = desc.startsWith("(") ? "" : (this.desc != null ? ":" : ""); - return owner + name + qualifier + separator + desc; + return owner + name + quantifier + separator + desc; } - + /** * Return this MemberInfo as an SRG mapping * @@ -342,7 +515,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec */ @Override public String toCtorType() { - if (this.unparsed == null) { + if (this.input == null) { return null; } @@ -359,7 +532,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec return this.name; } - return this.desc != null ? this.desc : this.unparsed; + return this.desc != null ? this.desc : this.input; } /** @@ -478,52 +651,60 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * * @return fluent * - * @throws InvalidMemberDescriptorException if any validation check fails + * @throws InvalidSelectorException if any validation check fails */ @Override - public MemberInfo validate() throws InvalidMemberDescriptorException { + public MemberInfo validate() throws InvalidSelectorException { + // Parse emits a match count of 0 if the quantifier is incorrectly specified + if (this.getMaxMatchCount() == 0) { + throw new InvalidMemberDescriptorException(this.input, "Malformed quantifier in selector: " + this.input); + } + // Extremely naive class name validation, just to spot really egregious errors if (this.owner != null) { if (!this.owner.matches("(?i)^[\\w\\p{Sc}/]+$")) { - throw new InvalidMemberDescriptorException("Invalid owner: " + this.owner); + throw new InvalidMemberDescriptorException(this.input, "Invalid owner: " + this.owner); } // We can't detect this situation 100% reliably, but we can take a // decent stab at it in order to detect really obvious cases where // the user types a dot instead of a semicolon - if (this.unparsed != null && this.unparsed.lastIndexOf('.') > 0 && this.owner.startsWith("L")) { - throw new InvalidMemberDescriptorException("Malformed owner: " + this.owner + " If you are seeing this message unexpectedly and the" - + " owner appears to be correct, replace the owner descriptor with formal type L" + this.owner + "; to suppress this error"); + if (this.input != null && this.input.lastIndexOf('.') > 0 && this.owner.startsWith("L")) { + throw new InvalidMemberDescriptorException(this.input, "Malformed owner: " + this.owner + " If you are seeing this message" + + "unexpectedly and the owner appears to be correct, replace the owner descriptor with formal type L" + this.owner + + "; to suppress this error"); } } // Also naive validation, we're looking for stupid errors here if (this.name != null && !this.name.matches("(?i)^?$")) { - throw new InvalidMemberDescriptorException("Invalid name: " + this.name); + throw new InvalidMemberDescriptorException(this.input, "Invalid name: " + this.name); } if (this.desc != null) { if (!this.desc.matches("^(\\([\\w\\p{Sc}\\[/;]*\\))?\\[*[\\w\\p{Sc}/;]+$")) { - throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc); } if (this.isField()) { if (!this.desc.equals(Type.getType(this.desc).getDescriptor())) { - throw new InvalidMemberDescriptorException("Invalid field type in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid field type in descriptor: " + this.desc); } } else { try { Type.getArgumentTypes(this.desc); } catch (Exception ex) { - throw new InvalidMemberDescriptorException("Invalid descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid descriptor: " + this.desc); } String retString = this.desc.substring(this.desc.indexOf(')') + 1); try { Type retType = Type.getType(retString); if (!retString.equals(retType.getDescriptor())) { - throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: " + + this.desc); } } catch (Exception ex) { - throw new InvalidMemberDescriptorException("Invalid return type \"" + retString + "\" in descriptor: " + this.desc); + throw new InvalidMemberDescriptorException(this.input, "Invalid return type \"" + retString + "\" in descriptor: " + + this.desc); } } } @@ -590,46 +771,68 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec } ITargetSelectorByName other = (ITargetSelectorByName)obj; - boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField : other.isField(); - boolean otherMatchAll = other.getMatchCount() == Integer.MAX_VALUE; + boolean otherForceField = other instanceof MemberInfo ? ((MemberInfo)other).forceField + : other instanceof ITargetSelectorRemappable ? ((ITargetSelectorRemappable)other).isField() : false; - return this.matchAll == otherMatchAll && this.forceField == otherForceField + return this.compareMatches(other) && this.forceField == otherForceField && Objects.equal(this.owner, other.getOwner()) && Objects.equal(this.name, other.getName()) && Objects.equal(this.desc, other.getDesc()); } + /** + * Compare local match count with match count of other selector + */ + private boolean compareMatches(ITargetSelectorByName other) { + if (other instanceof MemberInfo) { + return ((MemberInfo)other).matches.equals(this.matches); + } + return this.getMinMatchCount() == other.getMinMatchCount() && this.getMaxMatchCount() == other.getMaxMatchCount(); + } + /* (non-Javadoc) * @see java.lang.Object#hashCode() */ @Override public int hashCode() { - return Objects.hashCode(this.matchAll, this.owner, this.name, this.desc); + return Objects.hashCode(this.matches, this.owner, this.name, this.desc); } /* (non-Javadoc) * @see org.spongepowered.asm.mixin.injection.selectors.ITargetSelector - * #configure(java.lang.String[]) + * #mutate(java.lang.String[]) */ @Override - public ITargetSelector configure(String... args) { - ITargetSelectorRemappable configured = this; - for (String arg : args) { - if (arg == null) { - continue; - } - - if (arg.startsWith("move:")) { - configured = configured.move(Strings.emptyToNull(arg.substring(5))); - } else if (arg.startsWith("transform:")) { - configured = configured.transform(Strings.emptyToNull(arg.substring(10))); - } else if ("permissive".equals(arg)) { - configured = configured.transform(null); - } else if ("orphan".equals(arg)) { - configured = configured.move(null); - } + public ITargetSelector configure(Configure request, String... args) { + request.checkArgs(args); + switch (request) { + case SELECT_MEMBER: + if (this.matches.isDefault()) { + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.SINGLE); + } + break; + case SELECT_INSTRUCTION: + if (this.matches.isDefault()) { + return new MemberInfo(this.name, this.owner, this.desc, Quantifier.ANY); + } + break; + case MOVE: + return this.move(Strings.emptyToNull(args[0])); + case ORPHAN: + return this.move(null); + case TRANSFORM: + return this.transform(Strings.emptyToNull(args[0])); + case PERMISSIVE: + return this.transform(null); + case CLEAR_LIMITS: + if (this.matches.getMin() != 0 || this.matches.getMax() < Integer.MAX_VALUE) { + return new MemberInfo(this.name, this.owner, this.desc, 0, Integer.MAX_VALUE); + } + break; + default: + break; } - return configured; + return this; } /* (non-Javadoc) @@ -667,7 +870,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec if ((newDesc == null && this.desc == null) || (newDesc != null && newDesc.equals(this.desc))) { return this; } - return new MemberInfo(this.name, this.owner, newDesc, this.matchAll); + return new MemberInfo(this.name, this.owner, newDesc, this.matches); } /** @@ -689,7 +892,7 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec * @param context Selector context for this parse request * @return parsed MemberInfo */ - public static MemberInfo parse(String input, ISelectorContext context) { + public static MemberInfo parse(final String input, final ISelectorContext context) { String desc = null; String owner = null; String name = Strings.nullToEmpty(input).replaceAll("\\s", ""); @@ -723,16 +926,40 @@ public final class MemberInfo implements ITargetSelectorRemappable, ITargetSelec name = ""; } - boolean matchAll = name.endsWith("*"); - if (matchAll) { + // Use default quantifier with negative max value. Used to indicate that + // an explicit quantifier was not parsed from the selector string, this + // allows us to provide backward-compatible behaviour for injection + // points vs. selecting target members which have different default + // semantics when omitting the quantifier. This is handled by consumers + // calling configure() with SELECT_MEMBER or SELECT_INSTRUCTION to + // promote the default case to a concrete case. + Quantifier quantifier = Quantifier.DEFAULT; + if (name.endsWith("*")) { + quantifier = Quantifier.ANY; name = name.substring(0, name.length() - 1); + } else if (name.endsWith("+")) { + quantifier = Quantifier.PLUS; + name = name.substring(0, name.length() - 1); + } else if (name.endsWith("}")) { + quantifier = Quantifier.NONE; // Assume invalid until quantifier is parsed + int bracePos = name.indexOf("{"); + if (bracePos >= 0) { + try { + quantifier = Quantifier.parse(name.substring(bracePos, name.length())); + name = name.substring(0, bracePos); + } catch (Exception ex) { + // Handled later in validate since matchCount will be 0 + } + } + } else if (name.indexOf("{") >= 0) { + quantifier = Quantifier.NONE; // Probably incomplete quantifier } if (name.isEmpty()) { name = null; } - return new MemberInfo(name, owner, desc, matchAll, input); + return new MemberInfo(name, owner, desc, quantifier, input); } /** 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 6a75f3ea..a41b76b4 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinConfig.java @@ -1034,6 +1034,13 @@ final class MixinConfig implements Comparable, IMixinConfig { public Level getLoggingLevel() { return this.verboseLogging ? Level.INFO : Level.DEBUG; } + + /** + * Get whether verbose logging is enabled + */ + public boolean isVerboseLogging() { + return this.verboseLogging; + } /** * Get whether this config's package matches the supplied class name diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java index f18b3dbb..0193ff74 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinInfo.java @@ -1009,23 +1009,23 @@ class MixinInfo implements Comparable, IMixinInfo { if (this.isVirtual()) { this.logger.debug("Skipping virtual target {} for {}", target.name, this); } else { - this.handleTargetError(String.format("@Mixin target %s was not found %s", target.name, this)); + this.handleTargetError(String.format("@Mixin target %s was not found %s", target.name, this), false); } return null; } this.type.validateTarget(target.name, targetInfo); if (target.isPrivate && targetInfo.isPublic() && !this.isVirtual()) { - this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this)); + this.handleTargetError(String.format("@Mixin target %s is public in %s and should be specified in value", target.name, this), true); } return targetInfo; } - private void handleTargetError(String message) { + private void handleTargetError(String message, boolean verboseOnly) { if (this.strict) { this.logger.error(message); throw new InvalidMixinException(this, message); } - this.logger.warn(message); + this.logger.log(verboseOnly && !this.parent.isVerboseLogging() ? Level.DEBUG : Level.WARN, message); } /** diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java index a0931ecf..e3b30fd0 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinPostProcessor.java @@ -48,6 +48,7 @@ import org.spongepowered.asm.mixin.transformer.meta.MixinProxy; import org.spongepowered.asm.mixin.transformer.throwables.MixinTransformerError; import org.spongepowered.asm.util.Annotations; import org.spongepowered.asm.util.Bytecode; +import org.spongepowered.asm.util.Bytecode.Visibility; /** * Performs post-processing tasks required for certain classes which pass @@ -170,6 +171,11 @@ class MixinPostProcessor implements MixinConfig.IListener { MixinClassNode mixinClassNode = mixin.getClassNode(0); ClassInfo targetClass = mixin.getTargets().get(0); + if (!Bytecode.hasFlag(mixinClassNode, Opcodes.ACC_PUBLIC)) { + Bytecode.setVisibility(mixinClassNode, Visibility.PUBLIC); + transformed = true; + } + for (MixinMethodNode methodNode : mixinClassNode.mixinMethods) { if (!Bytecode.hasFlag(methodNode, Opcodes.ACC_STATIC)) { continue; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java index b4ccbbc3..54506428 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/MixinTargetContext.java @@ -54,8 +54,8 @@ import org.spongepowered.asm.mixin.injection.Inject; import org.spongepowered.asm.mixin.injection.struct.InjectionInfo; import org.spongepowered.asm.mixin.injection.struct.InjectorGroupInfo; import org.spongepowered.asm.mixin.injection.struct.Target; -import org.spongepowered.asm.mixin.injection.throwables.InjectionError; import org.spongepowered.asm.mixin.injection.throwables.InjectionValidationException; +import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionException; import org.spongepowered.asm.mixin.refmap.IMixinContext; import org.spongepowered.asm.mixin.refmap.IReferenceMapper; import org.spongepowered.asm.mixin.struct.MemberRef; @@ -1194,9 +1194,9 @@ public class MixinTargetContext extends ClassContext implements IMixinContext { activity.end(); } catch (InjectionValidationException ex) { InjectorGroupInfo group = ex.getGroup(); - throw new InjectionError( + throw new InvalidInjectionException(group.getMembers().iterator().next().getMixin(), String.format("Critical injection failure: Callback group %s in %s failed injection check: %s", - group, this.mixin, ex.getMessage())); + group, this.mixin, ex.getMessage()), ex); } catch (InvalidMixinException ex) { ex.prepend(this.activities); throw ex; diff --git a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java index c72601de..f1768adc 100644 --- a/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java +++ b/src/main/java/org/spongepowered/asm/mixin/transformer/ext/extensions/ExtensionCheckInterfaces.java @@ -86,13 +86,29 @@ public class ExtensionCheckInterfaces implements IExtension { * Strict mode */ private boolean strict; + + /** + * True once the output dir and csv have been created, not triggered until + * something is written + */ + private boolean started = false; public ExtensionCheckInterfaces() { File debugOutputFolder = new File(Constants.DEBUG_OUTPUT_DIR, ExtensionCheckInterfaces.AUDIT_DIR); - debugOutputFolder.mkdirs(); this.csv = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_CSV_FILENAME); this.report = new File(debugOutputFolder, ExtensionCheckInterfaces.IMPL_REPORT_TXT_FILENAME); + } + + /** + * Delayed creation of CSV so the dir doesn't get created when the extension + * is inactive + */ + private void start() { + if (this.started) { + return; + } + this.started = true; this.csv.getParentFile().mkdirs(); try { @@ -137,6 +153,8 @@ public class ExtensionCheckInterfaces implements IExtension { */ @Override public void postApply(ITargetClassContext context) { + this.start(); + ClassInfo targetClassInfo = context.getClassInfo(); // If the target is abstract and strict mode is not enabled, skip this class diff --git a/src/main/java/org/spongepowered/asm/util/Annotations.java b/src/main/java/org/spongepowered/asm/util/Annotations.java index 08a27eb1..d248c593 100644 --- a/src/main/java/org/spongepowered/asm/util/Annotations.java +++ b/src/main/java/org/spongepowered/asm/util/Annotations.java @@ -55,7 +55,7 @@ import com.google.common.collect.Lists; public final class Annotations { /** - * Wrapper for AnnotationNode to support access via IAnnotationHandle + * Wrapper for {@link AnnotationNode} to support access via common interface */ public static class Handle implements IAnnotationHandle { @@ -66,13 +66,18 @@ public final class Annotations { this.annotation = annotation; } + @Override + public boolean exists() { + return true; + } + public AnnotationNode getNode() { return this.annotation; } @Override public String getDesc() { - return this.annotation.desc; + return Type.getType(this.annotation.desc).getInternalName(); } @Override @@ -87,6 +92,11 @@ public final class Annotations { return list; } + @Override + public Type getTypeValue(String key) { + return this.getValue(key, Type.VOID_TYPE); + } + @Override public List getTypeList(String key) { return this.getList(key); @@ -160,6 +170,16 @@ public final class Annotations { throw new IllegalArgumentException("Unsupported annotation type: " + annotation.getClass().getName()); } } + + /** + * Returns the bytecode descriptor of an annotation + * + * @param annotationType annotation + * @return annotation's descriptor + */ + public static String getDesc(Class annotationType) { + return Type.getType(annotationType).getInternalName(); + } /** * Returns the simple name of an annotation, mainly used for printing diff --git a/src/main/java/org/spongepowered/asm/util/Bytecode.java b/src/main/java/org/spongepowered/asm/util/Bytecode.java index c1b02b35..f4a33ba4 100644 --- a/src/main/java/org/spongepowered/asm/util/Bytecode.java +++ b/src/main/java/org/spongepowered/asm/util/Bytecode.java @@ -999,6 +999,17 @@ public final class Bytecode { return Bytecode.Visibility.PACKAGE; } + /** + * Set the visibility of the specified class, leaving other access flags + * unchanged + * + * @param classNode class to change + * @param visibility new visibility + */ + public static void setVisibility(ClassNode classNode, Visibility visibility) { + classNode.access = Bytecode.setVisibility(classNode.access, visibility.access); + } + /** * Set the visibility of the specified member, leaving other access flags * unchanged @@ -1021,6 +1032,17 @@ public final class Bytecode { field.access = Bytecode.setVisibility(field.access, visibility.access); } + /** + * Set the visibility of the specified class, leaving other access flags + * unchanged + * + * @param classNode class to change + * @param access new visibility + */ + public static void setVisibility(ClassNode classNode, int access) { + classNode.access = Bytecode.setVisibility(classNode.access, access); + } + /** * Set the visibility of the specified member, leaving other access flags * unchanged diff --git a/src/main/java/org/spongepowered/asm/util/Quantifier.java b/src/main/java/org/spongepowered/asm/util/Quantifier.java new file mode 100644 index 00000000..12141ec7 --- /dev/null +++ b/src/main/java/org/spongepowered/asm/util/Quantifier.java @@ -0,0 +1,214 @@ +/* + * 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; + +/** + * A regex-style quantifier, specified as a number or pair of numbers in braces. + */ +public final class Quantifier { + + /** + * Default quantifier, used when a quantifier was not specified + * (empty string) + */ + public static Quantifier DEFAULT = new Quantifier(0, -1); + + /** + * Invalid (matches none) + */ + public static Quantifier NONE = new Quantifier(0, 0); + + /** + * Single (matches zero or 1) + */ + public static Quantifier SINGLE = new Quantifier(0, 1); + + /** + * Default (matches any) + */ + public static Quantifier ANY = new Quantifier(0, Integer.MAX_VALUE); + + /** + * Plus (matches 1 or more) + */ + public static Quantifier PLUS = new Quantifier(1, Integer.MAX_VALUE); + + /** + * Minimum value, parsed from expression, 0 if unbounded + */ + private final int min; + + /** + * Maximum value, parsed from expression, Integer.MAX_VALUE if unbounded + */ + private final int max; + + public Quantifier(int min, int max) { + this.min = min; + this.max = max; + } + + /** + * Check whether this is a defaulted qualifier + */ + public boolean isDefault() { + return this.min == 0 && this.max < 0; + } + + /** + * Get the literal min value + */ + public int getMin() { + return this.min; + } + + /** + * Get the literal max value + */ + public int getMax() { + return this.max; + } + + /** + * Get the clamped min value + */ + public int getClampedMin() { + return Math.max(0, this.min); + } + + /** + * Get the clamped max value + */ + public int getClampedMax() { + return this.max < 0 ? 1 : Math.max(this.min, this.max); + } + + /* (non-Javadoc) + * @see java.lang.Object#toString() + */ + @Override + public String toString() { + StringBuilder sb = new StringBuilder("{"); + if (this.min == this.max) { + sb.append(this.min); + } else if (this.max < this.min) { + return ""; + } else { + if (this.min == 0) { + if (this.max == 1) { + return ""; + } else if (this.max == Integer.MAX_VALUE) { + return "*"; + } + } + if (this.min == 1 && this.max == Integer.MAX_VALUE) { + return "+"; + } + if (this.min > 0) { + sb.append(this.min); + } + if (this.min >= 0) { + sb.append(','); + } + if (this.max < Integer.MAX_VALUE) { + sb.append(this.max); + } + } + return sb.append('}').toString(); + } + + /** + * Parse a quantifier from the supplied string + * + * @param string string to parse + * @return parsed quantifier, malformed quantifiers return NONE + */ + public static Quantifier parse(String string) { + if (string == null || ((string = string.trim()).length() == 0)) { + return Quantifier.DEFAULT; + } + + if ("*".equals(string)) { + return Quantifier.ANY; + } + + if ("+".equals(string)) { + return Quantifier.PLUS; + } + + if (!string.startsWith("{") || !string.endsWith("}") || string.length() < 3) { + return Quantifier.NONE; // malformed + } + + String inner = string.substring(1, string.length() - 1).trim(); + if (inner.isEmpty()) { + return Quantifier.NONE; + } + + String strMin = inner; + String strMax = inner; + + int comma = inner.indexOf(','); + if (comma > -1) { + strMin = inner.substring(0, comma).trim(); + strMax = inner.substring(comma + 1).trim(); + } + + try { + int min = strMin.length() > 0 ? Integer.parseInt(strMin) : 0; + int max = strMax.length() > 0 ? Integer.parseInt(strMax) : Integer.MAX_VALUE; + return new Quantifier(min, max); + } catch (NumberFormatException ex) { + return Quantifier.NONE; + } + } + + /* (non-Javadoc) + * @see java.lang.Object#equals(java.lang.Object) + */ + @Override + public boolean equals(Object obj) { + if (obj instanceof Quantifier) { + Quantifier other = (Quantifier)obj; + return other.min == this.min && other.max == this.max; + } + + if (obj instanceof Number) { + int intValue = ((Number)obj).intValue(); + return (intValue == this.min) && (intValue == this.max); + } + + return false; + } + + /* (non-Javadoc) + * @see java.lang.Object#hashCode() + */ + @Override + public int hashCode() { + return 31 * this.min * this.max; + } + +} diff --git a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java index 2695337c..b38b42c7 100644 --- a/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java +++ b/src/main/java/org/spongepowered/asm/util/asm/IAnnotationHandle.java @@ -27,12 +27,22 @@ package org.spongepowered.asm.util.asm; import java.util.List; import org.objectweb.asm.Type; +import org.objectweb.asm.tree.AnnotationNode; /** - * Interface for annotation handle since main classes may need to read info from - * mirror annotations in the AP + * Interface for annotation handle since some classes may need to read info from + * both ASM {@link AnnotationNode}s at runtime and mirror annotations in the AP + * at compile time. */ public interface IAnnotationHandle { + + /** + * Get whether the annotation inside the handle actually exists, if the + * contained element is null, returns false. + * + * @return true if the annotation exists + */ + public abstract boolean exists(); /** * Get the annotation descriptor @@ -48,7 +58,23 @@ public interface IAnnotationHandle { public abstract List getAnnotationList(String key); /** - * Retrieve an annotation key as a list of annotation Types + * Get an annotation value as an ASM {@link Type}. This is special-cased + * because the different APIs return class literals in different ways. Under + * ASM we will receieve {@link Type} instances, but at compile time we will + * get {@link TypeMirror}s instead. This overload is provided so that + * subclasses have to marshal everything into {@link Type} for consistency. + * + * @param key key to fetch + * @return value + */ + public abstract Type getTypeValue(String key); + + /** + * Retrieve an annotation key as a list of Types. This is special-cased + * because the different APIs return class literals in different ways. Under + * ASM we will receieve {@link Type} instances, but at compile time we will + * get {@link TypeMirror}s instead. This overload is provided so that + * subclasses have to marshal everything into {@link Type} for consistency. * * @param key key to fetch * @return list of types