Finalise desc selector and javadoc, enhancements to explicit selector

This commit is contained in:
Mumfrey committed 2021-02-14 21:33:06 +00:00
1 parent ae5bb845da
commit 6f35fe1ded
40 files changed
+1672 -428

No files matched your search

@@ -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> TNode findTarget(List<ElementNode<TNode>> nodes) {
Result<TNode> result = TargetSelector.<TNode>run(this.target.configure("orphan"), nodes);
Result<TNode> result = TargetSelector.<TNode>run(this.target.configure(Configure.ORPHAN), nodes);
try {
return result.getSingleResult(true);
@@ -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<MethodNode> result = TargetSelector.<MethodNode>run(this.target.configure("orphan"), ElementNode.methodList(this.classNode));
Result<MethodNode> result = TargetSelector.<MethodNode>run(this.target.configure(Configure.ORPHAN),
ElementNode.methodList(this.classNode));
try {
return result.getSingleResult(true);
@@ -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 <em>
* calls</em> or field <em>accesses</em> (eg. when using this value inside
* {@link At#desc &#64;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 <tt>min</tt>. 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 <em>calls</em> or field <em>accesses</em> (eg. when
* using this value inside {@link At#desc &#64;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 <tt>max</tt> to the same value as {@link #min min}.
* Values less than 1 are treated as <tt>Integer.MAX_VALUE</tt> (the
* default) since setting a value of 0 or less has no meaning.
*/
public int max() default Integer.MAX_VALUE;
}
@@ -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<? extends InjectionPoint>)Class.forName(type);
ipClass = (Class<? extends InjectionPoint>)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);
@@ -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, "<init>", "(Ljava/lang/String;)V", false));
insns.add(new InsnNode(Opcodes.ATHROW));
extraStack.add(3);
}
/**
@@ -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();
@@ -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<AbstractInsnNode> 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<AbstractInsnNode> 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;
}
@@ -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.</p>
*
* <blockquote><code>
* <del>// An example explicit target selector</del><br />
* Lfully/qualified/OwnerClass;methodName*(III)V
* </code></blockquote>
*
* <h3>Pattern Target Selectors (Regex Selectors)</h3>
*
* <p><b>Pattern</b> 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.</p>
*
* <blockquote><code>
* <del>// Matches candidates ending with "Bar" and which take a single int
* <br /></del>
* /bar$/ desc=/^\\(I\\)/<br />
* <br />
* <del>// The same example but with "name" explicitly specified (optional)
* <br /></del>
* name=/bar$/ desc=/^\\(I\\)/<br />
* <br />
* <del>// Matches candidates whose name contains "Entity"</del><br />
* /Entity/
* </code></blockquote>
*
* <h3>Dynamic Target Selectors</h3>
*
* <p><b>Dynamic</b> 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 "<tt>&#064;</tt>":</p>
* with their own specialised syntax or behaviour.</p>
*
* <h4>Built-in dynamic selectors:</h4>
*
* <ul>
* <li>{@link DynamicSelectorDesc &#64;Desc Selector}: Selector which uses
* descriptors defined in {@link Desc &#64;Desc} annotations</li>
* </ul>
*
* <p>Dynamic selectors are specified in the following format, and can be
* recognised by the fact that the selector string starts with "<tt>&#64;</tt>":
* </p>
*
* <blockquote><pre>
* <del>// Built-in dynamic selector without argument string</del>
* &#064;SelectorId
* <del>// Built-in dynamic selector without argument string</del>
* &#064;SelectorId
*
* <del>// Built-in dynamic selector with empty argument string</del>
* &#064;SelectorId()
* <del>// Built-in dynamic selector with empty argument string</del>
* &#064;SelectorId()
*
* <del>// Built-in dynamic selector with argument</del>
* &#064;SelectorId(custom,argument,string,in,any,format)
* <del>// Built-in dynamic selector with argument</del>
* &#064;SelectorId(custom,argument,string,in,any,format)
*
* <del>// User-provided dynamic selector with argument. Note that
* // user-provided dynamic selectors are namespaced to avoid conflicts.</del>
* &#064;Namespace:SelectorId(some arguments)</pre>
* <del>// User-provided dynamic selector with argument. Note that
* // user-provided dynamic selectors are namespaced to avoid conflicts.</del>
* &#064;Namespace:SelectorId(some arguments)</pre>
* </blockquote>
*
* <p>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 <tt>null</tt> 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.
*
* <p>In other words, calling <tt>configure("foo")</tt> when this object is
* <i>already</i> configured according to "foo" may simply return this
* object, or might return an identically-configured copy.</p>
* <p>In other words, calling <tt>configure(Configure.ORPHAN)</tt> when this
* object is <i>already</i> an orphan or does not support orphaning, may
* simply return this object, or might return an identically-configured
* copy.</p>
*
* <p>Must not return null</p>
* <p>Must not return null, defaults to returning unmodified selector.</p>
*
* @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
@@ -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 <tt>&lt;init&gt;</tt>
*/
public abstract boolean isConstructor();
/**
* Get whether this selector represents a class initialiser
*
* @return true if member name is <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isClassInitialiser();
/**
* Get whether this selector represents a constructor or class initialiser
*
* @return true if member name is <tt>&lt;init&gt;</tt> or
* <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isInitialiser();
/**
* Get a representation of this selector as a complete descriptor
*/
@@ -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<? extends Annotation> value();
}
}
@@ -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 <tt>&lt;init&gt;</tt>
*/
public abstract boolean isConstructor();
/**
* Get whether this selector represents a class initialiser
*
* @return true if member name is <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isClassInitialiser();
/**
* Get whether this selector represents a constructor or class initialiser
*
* @return true if member name is <tt>&lt;init&gt;</tt> or
* <tt>&lt;clinit&gt;</tt>
*/
public abstract boolean isInitialiser();
/**
* Returns this selector as a {@link MappingField} or
* {@link MappingMethod}
@@ -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 <tt>
* null</tt>, 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 <TNode> MatchResult match(ElementNode<TNode> 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();
@@ -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;
}
@@ -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<? extends ITargetSelectorDynamic> type;
final Method parse;
final Class<? extends Annotation> annotation;
final Method mdParseString, mdParseAnnotation;
DynamicSelectorEntry(String namespace, String id, Class<? extends ITargetSelectorDynamic> 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<? extends Annotation> annotation = null;
Method mdParseAnnotation = null;
SelectorAnnotation selectorAnnotation = type.<SelectorAnnotation>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<ITargetSelector> parseAndValidate(Iterable<?> selectors, ISelectorContext context) throws InvalidSelectorException {
Set<ITargetSelector> parsed = TargetSelector.parse(selectors, context, new LinkedHashSet<ITargetSelector>());
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<ITargetSelector> parse(Iterable<?> selectors, ISelectorContext context) {
return TargetSelector.parse(selectors, context, new LinkedHashSet<ITargetSelector>());
}
/**
* 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 <tt>parsed</tt> parameter,
* for convenience
*/
public static Set<ITargetSelector> parse(Iterable<?> selectors, ISelectorContext context, Set<ITargetSelector> parsed) {
if (parsed == null) {
parsed = new LinkedHashSet<ITargetSelector>();
}
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 <TNode> Node type
* @return query result
*/
public static <TNode> Result<TNode> run(ITargetSelector target, List<ElementNode<TNode>> nodes) {
public static <TNode> Result<TNode> run(ITargetSelector selector, List<ElementNode<TNode>> nodes) {
List<TNode> candidates = new ArrayList<TNode>();
TNode exactMatch = TargetSelector.runSelector(target, nodes, candidates);
TNode exactMatch = TargetSelector.runSelector(selector, nodes, candidates);
return new Result<TNode>(exactMatch, candidates);
}
/**
* Run query on supplied target nodes
*
* @param targets Target selector
* @param selector Target selector
* @param nodes Node collection to enumerate
* @param <TNode> Node type
* @return query result
*/
public static <TNode> Result<TNode> run(Iterable<ITargetSelector> targets, List<ElementNode<TNode>> nodes) {
public static <TNode> Result<TNode> run(Iterable<ITargetSelector> selector, List<ElementNode<TNode>> nodes) {
TNode exactMatch = null;
List<TNode> candidates = new ArrayList<TNode>();
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<TNode>(exactMatch, candidates);
}
private static <TNode> TNode runSelector(ITargetSelector target, List<ElementNode<TNode>> nodes, List<TNode> candidates) {
private static <TNode> TNode runSelector(ITargetSelector selector, List<ElementNode<TNode>> nodes, List<TNode> candidates) {
int matchCount = 0;
TNode exactMatch = null;
for (ElementNode<TNode> 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;
}
@@ -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<String> searched;
/**
* Selector context
*/
private final ISelectorContext context;
/**
* The resolved descriptor
*/
private final IAnnotationHandle desc;
/**
* Selector context
*/
private final ISelectorContext context;
Descriptor(Set<String> searched, ISelectorContext context, IAnnotationHandle desc) {
Descriptor(Set<String> 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.<Type>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.<Type>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.<Integer>getValue("min", 0) : 0);
Integer max = this.desc != null ? this.desc.<Integer>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;
}
@@ -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 &#064;Desc} annotations. The descriptor
@@ -137,7 +144,7 @@ import org.spongepowered.asm.util.asm.IAnnotationHandle;
* &nbsp; &nbsp; &#064;Inject(method = "&#064;Desc", at = &#064;At(value =
* "INVOKE" target = "<ins>&#064;Desc(?)</ins>"))
* <br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {
* &nbsp; &nbsp; void myHandler(int arg, CallbackInfo ci) {
* </code></blockquote>
*
* <p>This will cause the resolver to pretty-print the considered coordinates
@@ -160,7 +167,8 @@ import org.spongepowered.asm.util.asm.IAnnotationHandle;
* supports.</p>
*/
@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)
@@ -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();
}
@@ -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);
}
}
@@ -0,0 +1,59 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.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;
}
}
@@ -0,0 +1,29 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* Exceptions for selectors.
*/
package org.spongepowered.asm.mixin.injection.selectors.throwables;
@@ -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<ITargetSelector> parseTargets() {
Set<ITargetSelector> selectors = new LinkedHashSet<ITargetSelector>();
TargetSelector.parse(Annotations.<String>getValue(this.annotation, "method", false), this, selectors);
TargetSelector.parse(Annotations.<AnnotationNode>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<ITargetSelector> attachedSelectors = new LinkedHashSet<ITargetSelector>();
for (String method : Annotations.<String>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.<AnnotationNode>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<AnnotationNode> 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())));
}
}
@@ -288,7 +288,7 @@ public class InjectionPointData {
if (desc != null) {
String id = Annotations.<String>getValue(desc, "id", "at");
if ("at".equalsIgnoreCase(id)) {
return DynamicSelectorDesc.of(this.context, Annotations.handleOf(desc));
return DynamicSelectorDesc.of(Annotations.handleOf(desc), this.context);
}
}
}
@@ -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));
}
@@ -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;
}
}
@@ -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.</p>
*
* <p>Some examples:</p>
* <blockquote><pre>
* <del>// references a method or field called func_1234_a, if there are
* // multiple members with the same signature, matches the first occurrence
*</del> func_1234_a
*
* <del>// references a method or field called func_1234_a, if there are
* // multiple members with matching name, matches all occurrences</del>
* func_1234_a*
*
* <del>// references all methods which take 3 ints and return a bool</del>
* *(III)Z
*
* <del>// references a method called func_1234_a which takes 3 ints and
* // returns a bool</del>
* func_1234_a(III)Z
*
* <del>// references a field called field_5678_z which is a String</del>
* field_5678_z:Ljava/lang/String;
*
* <del>// references a ctor which takes a single String argument</del>
* &lt;init&gt;(Ljava/lang/String;)V
*
* <del>// references a method called func_1234_a in class foo.bar.Baz</del>
* Lfoo/bar/Baz;func_1234_a
*
* <del>// references a field called field_5678_z in class com.example.Dave
*</del> Lcom/example/Dave;field_5678_z
*
* <del>// references a field called field_5678_z in class com.example.Dave
* // which is of type String</del>
* Lcom/example/Dave;field_5678_z:Ljava/lang/String;
*
* <del>// references a method called func_1234_a in class foo.bar.Baz which
* // takes three doubles and returns void</del>
* Lfoo/bar/Baz;func_1234_a(DDD)V
*
* <del>// alternate syntax for the same</del>
* foo.bar.Baz.func_1234_a(DDD)V</pre>
* </blockquote>
* <p>In general a <tt>MemberInfo</tt> consists of 4 parts, <span class="ownr">
* owner</span>, <span class="name">name</span>, <span class="quan">quantifier
* </span> and <span class="desc">descriptor</span>, all of which are optional:
* </p>
*
* <table class="selectorTable">
* <thead>
* <tr>
* <th>&nbsp;</th>
* <th class="ownr">Owner</th>
* <th class="name">Name</th>
* <th class="quan">Quantifier</th>
* <th>&nbsp;</th>
* <th class="desc">Descriptor</th>
* <th>Resulting selector string</th>
* </tr>
* </thead>
* <tbody>
* <tr>
* <td class="th">Method</td>
* <td class="ownr">Lfully/qualified/OwnerClass;</td>
* <td class="name">methodName</td>
* <td class="quan">{1,3}</td>
* <td>&nbsp;</td>
* <td class="desc">(III)V</td>
* <td><span class="ownr">Lfully/qualified/OwnerClass;</span><span
* class="name">methodName</span><span class="quan">{1,3}</span><span
* class="desc">(III)V</span></td>
* </tr>
* <tr>
* <td class="th">Field</td>
* <td class="ownr">Lfully/qualified/OwnerClass;</td>
* <td class="name">fieldName</td>
* <td class="quan">*</td>
* <td>:</td>
* <td class="desc">Ljava/lang/String;</td>
* <td><span class="ownr">Lfully/qualified/OwnerClass;</span><span
* class="name">fieldName</span><span class="quan">*</span>:<span
* class="desc">Ljava/lang/String;</span></td>
* </tr>
* </tbody>
* </table>
*
* <p>Any part of the selector can be omitted, though they must appear in the
* correct order. Some examples:</p>
*
* <blockquote><code>
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with the same signature, matches the first occurrence<br /></del>
* <span class="name">func_1234_a</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches all occurrences</del><br />
* <span class="name">func_1234_a</span><span class="quan">*</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches all occurrences, matching less than 1
* <br />
* // occurrence is an error condition</del><br />
* <span class="name">func_1234_a</span><span class="quan">+</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches up to 3 occurrences</del><br />
* <span class="name">func_1234_a</span><span class="quan">{,3}</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches exactly 3 occurrences, matching fewer
* <br />
* // than 3 occurrences is an error condition</del><br />
* <span class="name">func_1234_a</span><span class="quan">{3}</span><br />
* <br />
* <del>// selects a method or field called func_1234_a, if there are multiple
* <br />
* // members with matching name, matches at least 3 occurrences, matching fewer
* <br />
* // than 3 occurrences is an error condition</del><br />
* <span class="name">func_1234_a</span><span class="quan">{3,}</span><br />
* <br />
* <del>// selects all members of any type and descriptor</del><br />
* <span class="quan">*</span><br />
* <br />
* <del>// selects the first member of any type and descriptor</del><br />
* <span class="quan">{1}</span><br />
* <br />
* <del>// selects all methods which take 3 ints and return a bool</del><br />
* <span class="quan">*</span><span class="desc">(III)Z</span><br />
* <br />
* <del>// selects the first 2 methods which take a bool and return void</del>
* <br />
* <span class="quan">{2}</span><span class="desc">(Z)V</span><br />
* <br />
* <del>// selects a method called func_1234_a which takes 3 ints and returns a
* bool</del><br />
* <span class="name">func_1234_a</span><span class="desc">(III)Z</span><br />
* <br />
* <del>// selects a field called field_5678_z which is a String</del><br />
* <span class="name">field_5678_z</span>:<span class="desc">Ljava/lang/String;
* </span><br />
* <br />
* <del>// selects a ctor which takes a single String argument</del><br />
* <span class="name">&lt;init&gt;</span><span
* class="desc">(Ljava/lang/String;)V</span><br />
* <br />
* <del>// selects a method called func_1234_a in class foo.bar.Baz</del><br />
* <span class="ownr">Lfoo/bar/Baz;</span><span class="name">func_1234_a</span>
* <br />
* <br />
* <del>// selects a field called field_5678_z in class com.example.Dave</del>
* <br />
* <span class="ownr">Lcom/example/Dave;</span><span class="name">field_5678_z
* </span><br />
* <br />
* <del>// selects a field called field_5678_z in class com.example.Dave<br />
* // which is of type String</del><br />
* <span class="ownr">Lcom/example/Dave;</span><span
* class="name">field_5678_z</span>:<span class="desc">Ljava/lang/String;
* </span><br />
* <br />
* <del>// selects a method called func_1234_a in class foo.bar.Baz which<br />
* // takes three doubles and returns void</del><br />
* <span class="ownr">Lfoo/bar/Baz;</span><span
* class="name">func_1234_a</span><span class="desc">(DDD)V</span><br />
* <br />
* <del>// alternate syntax for the same</del><br />
* <span class="ownr">foo.bar.Baz</span>.<span
* class="name">func_1234_a</span><span class="desc">(DDD)V</span>
* </code></blockquote>
*
* <h4>Notes</h4>
*
* <ul>
* <li>All whitespace in the selector string is stripped before the selector
* is parsed.</li>
* <li><span class="quan">Quantifiers</span> for selectors can be used as a
* form of early validation (prior to injector <tt>require</tt> directives)
* that an injection point has matched a required number of targets or to
* limit the number of matches it can return.</li>
* <li>The syntax for <span class="quan">quantifiers</span> is based on the
* syntax for <a href="https://www.regular-expressions.info/refrepeat.html"
* target="_top">quantifiers in regular expressions</a>, though more
* limited. In particular:
* <ul>
* <li><b>No quantifer</b> is equivalent to the regex <tt>?</tt>
* quantifier, in that undecorated selectors can match <tt>{0,1}</tt>,
* this is for backward compatibility reasons. Likewise <tt>?</tt> is
* not supported since it's implied. To require exactly one match use
* <tt>{1}</tt>.</li>
* <li>The quantifiers <tt>*</tt> and <tt>+</tt> work the same as their
* regex counterparts.</li>
* </ul>
* </li>
* </ul>
*/
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)^<?[\\w\\p{Sc}]+>?$")) {
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);
}
/**
@@ -1034,6 +1034,13 @@ final class MixinConfig implements Comparable<MixinConfig>, 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
@@ -1009,23 +1009,23 @@ class MixinInfo implements Comparable<MixinInfo>, 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);
}
/**
@@ -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;
@@ -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;
@@ -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
@@ -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.<Type>getValue(key, Type.VOID_TYPE);
}
@Override
public List<Type> getTypeList(String key) {
return this.<Type>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<? extends Annotation> annotationType) {
return Type.getType(annotationType).getInternalName();
}
/**
* Returns the simple name of an annotation, mainly used for printing
@@ -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
@@ -0,0 +1,214 @@
/*
* This file is part of Mixin, licensed under the MIT License (MIT).
*
* Copyright (c) SpongePowered <https://www.spongepowered.org>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.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;
}
}
@@ -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<IAnnotationHandle> 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