Flesh out Desc selector javadoc and functionality

This commit is contained in:
Mumfrey committed 2021-02-03 20:54:12 +00:00
1 parent f9aeec8b05
commit ef6422f26e
31 files changed
+634 -202

No files matched your search

@@ -147,7 +147,7 @@ abstract class AnnotatedMixinElementHandler {
}
@Override
public Object getSelectorAnnotation() {
public IAnnotationHandle getSelectorAnnotation() {
return this.getAnnotation();
}
@@ -54,7 +54,7 @@ import com.google.common.base.Strings;
/**
* A module for {@link AnnotatedMixin} which handles accessors
*/
public class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler {
class AnnotatedMixinElementHandlerAccessor extends AnnotatedMixinElementHandler {
/**
* Accessor element
@@ -46,6 +46,7 @@ import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorExcep
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.obfuscation.mapping.common.MappingField;
import org.spongepowered.asm.obfuscation.mapping.common.MappingMethod;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.tools.obfuscation.ReferenceManager.ReferenceConflictException;
import org.spongepowered.tools.obfuscation.ext.SpecialPackages;
import org.spongepowered.tools.obfuscation.interfaces.IMixinAnnotationProcessor;
@@ -126,7 +127,7 @@ class AnnotatedMixinElementHandlerInjector extends AnnotatedMixinElementHandler
}
@Override
public Object getSelectorAnnotation() {
public IAnnotationHandle getSelectorAnnotation() {
return this.getAt();
}
@@ -43,7 +43,7 @@ import org.spongepowered.tools.obfuscation.mirror.TypeHandle;
/**
* A module for {@link AnnotatedMixin} whic handles soft-implements clauses
*/
public class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinElementHandler {
class AnnotatedMixinElementHandlerSoftImplements extends AnnotatedMixinElementHandler {
AnnotatedMixinElementHandlerSoftImplements(IMixinAnnotationProcessor ap, AnnotatedMixin mixin) {
super(ap, mixin);
@@ -40,7 +40,7 @@ import org.spongepowered.asm.mixin.Mixin;
/**
* Base class for mixin annotation processor modules
*/
public abstract class MixinObfuscationProcessor extends AbstractProcessor {
abstract class MixinObfuscationProcessor extends AbstractProcessor {
/**
* Mixin info manager
@@ -28,6 +28,7 @@ import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
@@ -79,7 +80,7 @@ public class MixinContainer {
continue;
}
MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(), this.handle);
MixinContainer.logger.debug("{} {} container {}", simpleName, acceptAction.name().toLowerCase(Locale.ROOT), this.handle);
} catch (InstantiationException ex) {
Throwable cause = ex.getCause();
if (cause instanceof RuntimeException) {
@@ -73,7 +73,7 @@ public abstract class AccessorGenerator {
MethodNode accessor = new MethodNode(ASM.API_VERSION, (method.access & ~Opcodes.ACC_ABSTRACT) | Opcodes.ACC_SYNTHETIC, method.name,
method.desc, null, null);
accessor.visibleAnnotations = new ArrayList<AnnotationNode>();
accessor.visibleAnnotations.add(this.info.getAnnotation());
accessor.visibleAnnotations.add(this.info.getAnnotationNode());
accessor.maxLocals = maxLocals;
accessor.maxStack = maxStack;
return accessor;
@@ -461,7 +461,7 @@ public class AccessorInfo extends SpecialMethodInfo {
@Override
public String toString() {
String typeString = this.type != null ? this.type.toString() : "UNPARSED_ACCESSOR";
return String.format("%s->@%s[%s]::%s%s", this.mixin, Bytecode.getSimpleName(this.annotation), typeString,
return String.format("%s->@%s[%s]::%s%s", this.mixin, Annotations.getSimpleName(this.annotation), typeString,
this.methodName, this.method.desc);
}
@@ -30,22 +30,85 @@ import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
/**
* TODO Javadoc
* <p>A descriptor for matching a target element, for details of usage see
* {@link DynamicSelectorDesc}.</p>
*
* <p>Unlike {@link MemberInfo Explicit Target Selectors} which can match any
* element of a candidate member, <tt>&#064;Desc</tt> descriptors always match
* all elements of a target explicitly. Element defaults are as follows:</p>
*
* <blockquote><dl>
* <dt>{@link #owner}</dt>
* <dd>Defaults to the current target of the mixin if not specified</dd>
* <dt>{@link #ret}</dt>
* <dd>Defaults to <tt>void</tt></dd>
* <dt>{@link #args}</dt>
* <dd>Defaults to an empty array matching a target with <b>no arguments</b>,
* omitting this value does <em>not</em> mean "match any" signature and
* will explicitly match targets with no arguments. This value is ignored
* for fields.</dd>
* </dl></blockquote>
*
* <h4>Notes</h4>
*
* <ul>
* <li>It should be noted that specifying the only required value
* ({@link #value}) will therefore match elements with owner type equal to the
* current mixin target, taking no arguments and returning void.</li>
*
* <li>Note that when matching fields the value of {@link #args} is ignored.
* </li>
* </ul>
*/
@Target({ ElementType.TYPE, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Repeatable(Descriptors.class)
public @interface Desc {
/**
* The identifier for this descriptor. Can be an implicit coordinate or a
* user-defined string. IDs are not case-sensitive but must be unique within
* a mixin or resolution scope. For more details on resolution for
* descriptors see {@link DynamicSelectorDesc}.
*/
public String id() default "";
public Class<?> owner() default Void.class;
/**
* The owner of the member to match. The "owner" is the class which declares
* the member <b>or, ocasionally</b> the type of class upon which a virtual
* call is being made. For example if a class <tt>SuperType</tt> defines a
* method <tt>doSomething</tt>, usually <tt>owner</tt> will be
* <tt>SuperType</tt>. However note that where a method retrieves a
* reference to a derived type <tt>DerivedType</tt> which overrides
* <tt>doSomething</tt>, it's possible the invocation will be made using
* that type. To ensure usage of the correct type, inspect the disassembled
* bytecode for your target.
*
* <p>When <tt>owner</tt> is not specified, it defaults to the <em>current
* </em> target of the mixin.</p>
*/
public Class<?> owner() default void.class;
/**
* The name of the member to match. Must be specified. Matched
* case-sensitively against targets.
*/
public String value();
public Class<?> ret() default Void.class;
/**
* The return type of a method to match, or the declared type of a field.
* Defaults to <tt>void</tt>.
*/
public Class<?> ret() default void.class;
/**
* The argument types of a method to match, ignored for fields. Note that
* failing to specify this value <b>matches a target with no arguments</b>.
*/
public Class<?>[] args() default { };
}
@@ -44,13 +44,6 @@ public interface IInjectionPointContext extends IMessageSink, ISelectorContext {
/**
* Get the parent annotation (eg. the &#064;Inject annotation)
*/
@Override
public abstract AnnotationNode getAnnotation();
/**
* Get the selector annotation (eg. the &#064;At annotation)
*/
@Override
public abstract AnnotationNode getSelectorAnnotation();
public abstract AnnotationNode getAnnotationNode();
}
@@ -38,6 +38,7 @@ import java.util.HashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.ListIterator;
import java.util.Locale;
import java.util.Map;
import org.apache.logging.log4j.LogManager;
@@ -58,7 +59,6 @@ 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.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.IMessageSink;
import com.google.common.base.Joiner;
@@ -715,7 +715,7 @@ public abstract class InjectionPoint {
@SuppressWarnings("unchecked")
private static Class<? extends InjectionPoint> findClass(IMixinContext context, InjectionPointData data) {
String type = data.getType();
Class<? extends InjectionPoint> ipClass = InjectionPoint.types.get(type);
Class<? extends InjectionPoint> ipClass = InjectionPoint.types.get(type.toUpperCase(Locale.ROOT));
if (ipClass == null) {
if (type.matches("^([A-Za-z_][A-Za-z0-9_]*\\.)+[A-Za-z_][A-Za-z0-9_]*$")) {
try {
@@ -761,7 +761,7 @@ public abstract class InjectionPoint {
} else if (shift == At.Shift.AFTER) {
return InjectionPoint.after(point);
} else if (shift == At.Shift.BY) {
InjectionPoint.validateByValue(context.getMixin(), context.getMethod(), context.getAnnotation(), point, by);
InjectionPoint.validateByValue(context.getMixin(), context.getMethod(), context.getAnnotationNode(), point, by);
return InjectionPoint.shift(point, by);
}
}
@@ -793,7 +793,7 @@ public abstract class InjectionPoint {
allowed = InjectionPoint.MAX_ALLOWED_SHIFT_BY;
}
String message = String.format("@%s(%s) Shift.BY=%d on %s::%s exceeds %s%d. %s", Bytecode.getSimpleName(parent), point,
String message = String.format("@%s(%s) Shift.BY=%d on %s::%s exceeds %s%d. %s", Annotations.getSimpleName(parent), point,
by, context, method.name, limitBreached, allowed, advice);
if (err == ShiftByViolationBehaviour.WARN && allowed < InjectionPoint.MAX_ALLOWED_SHIFT_BY) {
@@ -806,7 +806,7 @@ public abstract class InjectionPoint {
protected String getAtCode() {
AtCode code = this.getClass().<AtCode>getAnnotation(AtCode.class);
return code == null ? this.getClass().getName() : code.value();
return code == null ? this.getClass().getName() : code.value().toUpperCase();
}
/**
@@ -846,9 +846,9 @@ public abstract class InjectionPoint {
code.value(), type.getName());
}
String id = code.value();
String id = code.value().toUpperCase(Locale.ROOT);
if (!Strings.isNullOrEmpty(namespace)) {
id = namespace + ":" + code.value();
id = namespace.toUpperCase(Locale.ROOT) + ":" + id;
}
InjectionPoint.types.put(id, type);
@@ -861,7 +861,9 @@ public abstract class InjectionPoint {
* @param type injection point type to register
*/
private static void registerBuiltIn(Class<? extends InjectionPoint> type) {
InjectionPoint.types.put(type.<AtCode>getAnnotation(AtCode.class).value(), type);
String code = type.<AtCode>getAnnotation(AtCode.class).value().toUpperCase(Locale.ROOT);
InjectionPoint.types.put(code, type);
InjectionPoint.types.put("MIXIN:" + code, type);
}
}
@@ -44,7 +44,6 @@ import org.spongepowered.asm.mixin.injection.struct.InjectionPointAnnotationCont
import org.spongepowered.asm.mixin.injection.throwables.InjectionError;
import org.spongepowered.asm.mixin.injection.throwables.InvalidSliceException;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Bytecode;
import com.google.common.base.Strings;
@@ -433,7 +432,7 @@ public final class MethodSlice {
}
private static String describeSlice(String description, ISliceContext owner) {
String annotation = Bytecode.getSimpleName(owner.getAnnotation());
String annotation = Annotations.getSimpleName(owner.getAnnotationNode());
MethodNode method = owner.getMethod();
return String.format("%s->%s(%s)::%s%s", owner.getMixin(), annotation, description, method.name, method.desc);
}
@@ -99,7 +99,7 @@ public final class MethodSlices {
public static MethodSlices parse(InjectionInfo info) {
MethodSlices slices = new MethodSlices(info);
AnnotationNode annotation = info.getAnnotation();
AnnotationNode annotation = info.getAnnotationNode();
if (annotation != null) {
for (AnnotationNode node : Annotations.<AnnotationNode>getValue(annotation, "slice", true)) {
MethodSlice slice = MethodSlice.parse(info, node);
@@ -25,6 +25,7 @@
package org.spongepowered.asm.mixin.injection.selectors;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* Context passed to a {@link ITargetSelector Target Selector} in order to
@@ -55,12 +56,12 @@ public interface ISelectorContext {
* Get the root annotation for the selector, for example the injector or
* accessor annotation
*/
public abstract Object getAnnotation();
public abstract IAnnotationHandle getAnnotation();
/**
* Get the annotation for this selector, for example the &#064;At annotation
*/
public abstract Object getSelectorAnnotation();
public abstract IAnnotationHandle getSelectorAnnotation();
/**
* Get the coordinate for this selector. This is the local coordinate of the
@@ -26,7 +26,6 @@ package org.spongepowered.asm.mixin.injection.selectors;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.injection.struct.MemberMatcher;
import org.spongepowered.asm.util.asm.ElementNode;
/**
@@ -56,17 +55,17 @@ import org.spongepowered.asm.util.asm.ElementNode;
* the selector string starts with "<tt>&#064;</tt>":</p>
*
* <blockquote><pre>
* // Built-in dynamic selector without argument string
* <del>// Built-in dynamic selector without argument string</del>
* &#064;SelectorId
*
* // Built-in dynamic selector with empty argument string
* <del>// Built-in dynamic selector with empty argument string</del>
* &#064;SelectorId()
*
* // Built-in dynamic selector with argument
* <del>// Built-in dynamic selector with argument</del>
* &#064;SelectorId(custom,argument,string,in,any,format)
*
* // User-provided dynamic selector with argument. Note that user-provided
* // dynamic selectors are namespaced to avoid conflicts.
* <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>
*
@@ -22,7 +22,7 @@
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.spongepowered.asm.mixin.injection.struct;
package org.spongepowered.asm.mixin.injection.selectors;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@@ -31,10 +31,6 @@ import java.util.regex.PatternSyntaxException;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelector;
import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
import org.spongepowered.asm.mixin.injection.selectors.MatchResult;
import org.spongepowered.asm.util.asm.ElementNode;
/**
@@ -56,20 +52,20 @@ import org.spongepowered.asm.util.asm.ElementNode;
*
* <p>Some examples:</p>
* <blockquote><pre>
* // Matches candidates starting with "foo"
* <del>// Matches candidates starting with "foo"</del>
* /^foo/
*
* // Matches candidates ending with "Bar" and which take a single integer
* /bar$/ desc=/^\\(I\\)/
* <del>// Matches candidates ending with "Bar" and which take a single int
*</del> /bar$/ desc=/^\\(I\\)/
*
* // The same example but with "name" explicitly specified (optional)
* name=/bar$/ desc=/^\\(I\\)/
* <del>// The same example but with "name" explicitly specified (optional)
*</del> name=/bar$/ desc=/^\\(I\\)/
*
* // Matches candidates whose name contains "Entity"
* <del>// Matches candidates whose name contains "Entity"</del>
* /Entity/
*
* // Matches candidates whose owner contains "/google/", note the escaping of
* // the forward slash symbols
* <del>// Matches candidates whose owner contains "/google/", note the
* // escaping of the forward slash symbols</del>
* owner=/\\/google\\//</pre>
* </blockquote>
*
@@ -41,7 +41,6 @@ import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.Se
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDesc;
import org.spongepowered.asm.mixin.injection.struct.InvalidMemberDescriptorException;
import org.spongepowered.asm.mixin.injection.struct.MemberInfo;
import org.spongepowered.asm.mixin.injection.struct.MemberMatcher;
import org.spongepowered.asm.mixin.throwables.MixinError;
import org.spongepowered.asm.mixin.throwables.MixinException;
import org.spongepowered.asm.util.asm.ElementNode;
@@ -141,16 +140,20 @@ public final class TargetSelector {
throw (MixinException)cause;
}
Throwable ex = cause != null ? cause : itex;
ex.printStackTrace();
throw new MixinError("Error parsing dynamic target selector [" + this.type.getName() + "] for " + context, ex);
}
}
}
/**
* Regex for dynamic selector ids
*/
private static final String DYNAMIC_SELECTOR_ID = "[a-z]+(:[a-z]+)?";
/**
* Pattern for matching dynamic selectors
*/
private static final Pattern PATTERN_DYNAMIC = Pattern.compile("^\\x40([a-z]+(:[a-z]+)?)(\\((.*)\\))?$", Pattern.CASE_INSENSITIVE);
private static final Pattern PATTERN_DYNAMIC = Pattern.compile("(?i)^\\x40(" + TargetSelector.DYNAMIC_SELECTOR_ID + ")(\\((.*)\\))?$");
/**
* Registered dynamic selectors
@@ -190,20 +193,27 @@ public final class TargetSelector {
DynamicSelectorEntry entry;
try {
entry = new DynamicSelectorEntry(namespace, selectorId.value().toLowerCase(Locale.ROOT), type);
entry = new DynamicSelectorEntry(namespace.toLowerCase(Locale.ROOT), selectorId.value().toLowerCase(Locale.ROOT), type);
} catch (NoSuchMethodException ex) {
throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method");
}
DynamicSelectorEntry existing = TargetSelector.dynamicSelectors.get(entry.id);
if (existing != null) { // && !existing.type.equals(type)) {
MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding target selector for @%s with %s (previously %s)",
entry.id, type.getName(), existing.type.getName()));
} else {
MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new target selector for @%s with %s",
entry.id, type.getName()));
String code = entry.getCode();
if (!Pattern.matches(TargetSelector.DYNAMIC_SELECTOR_ID, code)) {
throw new IllegalArgumentException("Dynamic target selector class " + type
+ " has an invalid id. Only alpha characters can be used in selector ids and namespaces");
}
TargetSelector.dynamicSelectors.put(entry.getCode(), entry);
DynamicSelectorEntry existing = TargetSelector.dynamicSelectors.get(code);
if (existing != null) { // && !existing.type.equals(type)) {
MessageRouter.getMessager().printMessage(Kind.WARNING, String.format("Overriding target selector for @%s with %s (previously %s)",
code, type.getName(), existing.type.getName()));
} else {
MessageRouter.getMessager().printMessage(Kind.OTHER, String.format("Registering new target selector for @%s with %s",
code, type.getName()));
}
TargetSelector.dynamicSelectors.put(code, entry);
}
/**
@@ -220,7 +230,8 @@ public final class TargetSelector {
} catch (NoSuchMethodException ex) {
throw new MixinError("Dynamic target selector class " + type.getName() + " does not contain a valid parse method");
}
TargetSelector.dynamicSelectors.put(entry.getCode(), entry);
TargetSelector.dynamicSelectors.put(entry.id, entry);
TargetSelector.dynamicSelectors.put("mixin:" + entry.id, entry);
}
/**
@@ -25,10 +25,12 @@
package org.spongepowered.asm.mixin.injection.selectors.dynamic;
import java.lang.annotation.Annotation;
import java.util.Collections;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.Desc;
@@ -36,9 +38,11 @@ import org.spongepowered.asm.mixin.injection.Descriptors;
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.asm.IAnnotatedElement;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
/**
@@ -51,7 +55,7 @@ public final class DescriptorResolver {
/**
* Resolution result
*/
public static final class Result {
static final class Descriptor implements IResolvedDescriptor {
/**
* The set of coordinates which were searched, stored here so they can
@@ -59,43 +63,190 @@ public final class DescriptorResolver {
*/
private final Set<String> searched;
/**
* Selector context
*/
private final ISelectorContext context;
/**
* The resolved descriptor
*/
private final IAnnotationHandle desc;
Result(Set<String> searched, IAnnotationHandle desc) {
Descriptor(Set<String> searched, ISelectorContext context, IAnnotationHandle desc) {
this.searched = searched;
this.context = context;
this.desc = desc;
}
/**
* True if the resolution process was successful
*/
@Override
public boolean isResolved() {
return this.desc != null;
}
/**
* Get information about the resolution of this descriptor, for
* inclusion in error messages when isResolved is false
*
*/
@Override
public String getResolutionInfo() {
if (this.searched == null) {
return "";
}
return String.format("Searched coordinates [ \"%s\" ]", Joiner.on("\", \"").join(this.searched));
}
/**
* Gets the resolved descriptor annotation if successful, otherwise
* returns null
*/
@Override
public IAnnotationHandle getAnnotation() {
return this.desc;
}
/**
* Gets the set of coordinates which were searched during resolution
*/
public Set<String> getSearched() {
return this.searched;
@Override
public String getId() {
return this.desc != null ? this.desc.<String>getValue("id", "") : "";
}
@Override
public Type getOwner() {
if (this.desc == null) {
return Type.VOID_TYPE;
}
Type ownerClass = this.desc.<Type>getValue("owner", Type.VOID_TYPE);
return ownerClass == Type.VOID_TYPE ? Type.getObjectType(this.context.getMixin().getTargetClassRef()) : ownerClass;
}
@Override
public String getName() {
if (this.desc == null) {
return "";
}
String value = this.desc.<String>getValue("value", "");
if (!value.isEmpty()) {
return value;
}
return this.desc.<String>getValue("name", "");
}
@Override
public Type[] getArgs() {
if (this.desc == null) {
return new Type[0];
}
List<Type> args = this.desc.getTypeList("args");
return args.toArray(new Type[args.size()]);
}
@Override
public Type getReturnType() {
if (this.desc == null) {
return Type.VOID_TYPE;
}
return this.desc.<Type>getValue("ret", Type.VOID_TYPE);
}
}
/**
* Observer for the resolution process, used to support printing resolution
* path during debug or collecting resolution info for inclusion in error
* messages
*/
interface IResolverObserver {
/**
* Called when the resolver visits a coordinate on the specified member
*
* @param coordinate coordinate being visited
* @param element element being visited
* @param detail diagnostic detail
*/
public abstract void visit(String coordinate, Object element, String detail);
/**
* Get all of the searched coordinates, for inclusion in error messages
*/
public abstract Set<String> getSearched();
/**
* Called after resolution completes
*/
public abstract void postResolve();
}
/**
* Basic resolver observer which just collects searched coordinates
*/
static class ResolverObserverBasic implements IResolverObserver {
private final Set<String> searched = new LinkedHashSet<String>();
@Override
public void visit(String coordinate, Object element, String detail) {
this.searched.add(coordinate);
}
@Override
public Set<String> getSearched() {
return this.searched;
}
@Override
public void postResolve() {
}
}
/**
* Debug resolver observer which prints resolution debug info after
* resolution is complete
*/
static class ResolverObserverDebug extends ResolverObserverBasic {
private final PrettyPrinter printer = new PrettyPrinter();
ResolverObserverDebug(ISelectorContext context) {
this.printer.add("Searching for implicit descriptor").add(context).hr().table();
this.printer.tr("Context Coordinate:", context.getSelectorCoordinate(true) + " (" + context.getSelectorCoordinate(false) + ")");
this.printer.tr("Selector Annotation:", context.getSelectorAnnotation());
this.printer.tr("Root Annotation:", context.getAnnotation());
this.printer.tr("Method:", context.getMethod()).hr();
this.printer.table("Search Coordinate", "Search Element", "Detail").th().hr();
}
@Override
public void visit(String coordinate, Object element, String detail) {
super.visit(coordinate, element, detail);
this.printer.tr(coordinate, element, detail);
}
@Override
public void postResolve() {
this.printer.print();
}
}
/**
* Special ID used to instruct the resolver to print its progress.
*/
public static String PRINT_ID = "?";
// No
private DescriptorResolver() {
}
public static IResolvedDescriptor resolve(ISelectorContext context, IAnnotationHandle desc) {
return new Descriptor(Collections.emptySet(), context, desc);
}
/**
* Resolve the specified descriptor id starting at the specified context
@@ -104,40 +255,48 @@ public final class DescriptorResolver {
* @param context Selector context, usually from the source annotation
* @return Resolution result
*/
public static Result resolve(String id, ISelectorContext context) {
Set<String> searched = new LinkedHashSet<String>();
public static IResolvedDescriptor resolve(String id, ISelectorContext context) {
IResolverObserver observer = new ResolverObserverBasic();
if (!Strings.isNullOrEmpty(id)) {
searched.add(id);
if (DescriptorResolver.PRINT_ID.equals(id)) {
observer = new ResolverObserverDebug(context);
id = "";
} else {
observer.visit(id, "", "");
}
}
return DescriptorResolver.resolve(id, context, searched, context.getSelectorCoordinate(true));
IAnnotationHandle desc = DescriptorResolver.resolve(id, context, observer, context.getSelectorCoordinate(true));
observer.postResolve();
return new Descriptor(observer.getSearched(), context, desc);
}
/**
* Recursive function which checks an element and then recurses to parent
*/
private static Result resolve(String id, ISelectorContext context, Set<String> searched, String coordinate) {
searched.add(coordinate);
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");
// First check if there's a "desc" value on the current annotation
Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, annotation.getAnnotationList("desc"));
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, annotation.getAnnotationList("desc"));
if (resolved != null) {
return resolved;
}
// Next check with the current coordinates on the owning method
resolved = DescriptorResolver.resolve(id, context, searched, coordinate, context.getMethod());
resolved = DescriptorResolver.resolve(id, context, observer, coordinate, context.getMethod(), "method");
if (resolved != null) {
return resolved;
}
ISelectorContext root = DescriptorResolver.getRoot(context);
String rootCoordinate = root.getSelectorCoordinate(false);
String mixinCoordinate = !rootCoordinate.equals(coordinate) ? rootCoordinate + "." + coordinate : coordinate;
String mixinCoordinate = root != context && !rootCoordinate.equals(coordinate) ? rootCoordinate + "." + coordinate : coordinate;
// Next check with the current coordinates on the mixin
resolved = DescriptorResolver.resolve(id, context, searched, mixinCoordinate, context.getMixin());
resolved = DescriptorResolver.resolve(id, context, observer, mixinCoordinate, context.getMixin(), "mixin");
if (resolved != null) {
return resolved;
}
@@ -146,22 +305,23 @@ public final class DescriptorResolver {
ISelectorContext parent = context.getParent();
if (parent != null) {
String parentCoordinate = parent.getSelectorCoordinate(false) + "." + coordinate;
return DescriptorResolver.resolve(id, parent, searched, parentCoordinate);
return DescriptorResolver.resolve(id, parent, observer, parentCoordinate);
}
// If all else fails, return failure
return new Result(searched, null);
return null;
}
/**
* Attempt to resolve on an element
*/
private static Result resolve(String id, ISelectorContext context, Set<String> searched, String coordinate, Object element) {
searched.add(coordinate);
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate, Object element,
String detail) {
observer.visit(coordinate, element, detail);
IAnnotationHandle descriptors = DescriptorResolver.getVisibleAnnotation(element, Descriptors.class);
if (descriptors != null) {
Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, descriptors.getAnnotationList("value"));
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, descriptors.getAnnotationList("value"));
if (resolved != null) {
return resolved;
}
@@ -169,7 +329,7 @@ public final class DescriptorResolver {
IAnnotationHandle descriptor = DescriptorResolver.getVisibleAnnotation(element, Desc.class);
if (descriptor != null) {
Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, descriptor);
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, descriptor);
if (resolved != null) {
return resolved;
}
@@ -181,12 +341,11 @@ public final class DescriptorResolver {
/**
* Attempt resolution using annotations from a particular element
*/
private static Result resolve(String id, ISelectorContext context, Set<String> searched, String coordinate,
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate,
List<IAnnotationHandle> availableDescriptors) {
if (availableDescriptors != null) {
searched.add(coordinate);
for (IAnnotationHandle desc : availableDescriptors) {
Result resolved = DescriptorResolver.resolve(id, context, searched, coordinate, desc);
IAnnotationHandle resolved = DescriptorResolver.resolve(id, context, observer, coordinate, desc);
if (resolved != null) {
return resolved;
}
@@ -198,12 +357,13 @@ public final class DescriptorResolver {
/**
* Attempt resolution using an actual annotation
*/
private static Result resolve(String id, ISelectorContext context, Set<String> searched, String coordinate, IAnnotationHandle desc) {
private static IAnnotationHandle resolve(String id, ISelectorContext context, IResolverObserver observer, String coordinate,
IAnnotationHandle desc) {
if (desc != null) {
String descriptorId = desc.getValue("id", coordinate);
boolean implicit = Strings.isNullOrEmpty(id);
if ((implicit && descriptorId.equalsIgnoreCase(coordinate)) || (!implicit && descriptorId.equalsIgnoreCase(id))) {
return new Result(searched, desc);
return desc;
}
}
return null;
@@ -24,47 +24,149 @@
*/
package org.spongepowered.asm.mixin.injection.selectors.dynamic;
import java.util.List;
import java.util.Set;
import org.objectweb.asm.Type;
import org.objectweb.asm.tree.AbstractInsnNode;
import org.objectweb.asm.tree.FieldInsnNode;
import org.objectweb.asm.tree.MethodInsnNode;
import org.spongepowered.asm.mixin.injection.At;
import org.spongepowered.asm.mixin.injection.Desc;
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.ITargetSelectorDynamic.SelectorId;
import org.spongepowered.asm.mixin.injection.selectors.InvalidSelectorException;
import org.spongepowered.asm.mixin.injection.selectors.ITargetSelectorDynamic.SelectorId;
import org.spongepowered.asm.mixin.injection.selectors.MatchResult;
import org.spongepowered.asm.mixin.injection.selectors.dynamic.DescriptorResolver.Result;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.asm.ElementNode;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* A {@link ITargetSelector Target Selector} which matches candidates using
* descriptors contained in {@link Desc} annotations. The descriptor annotations
* may be local, or may be applied to the method or even the owning mixin using
* user-specified ids, or implicit coordinates.
* descriptors contained in {@link Desc &#064;Desc} annotations. The descriptor
* annotations may be local, or may be applied to the method or even the owning
* mixin using user-specified ids, or implicit coordinates based on the relative
* location of the consumer. eg. an &#064;At annotation and the &#064;Desc
* annotation itself, which might be on a parent element for convenience.
*
* <p>TODO complete javadoc</p>
* <p>See {@link Desc &#064;Desc} for the specific syntax of descriptor
* annotations.</p>
*
* <h3>Local Descriptors</h3>
*
* <p>Some annotations can use {@link Desc &#064;Desc} selectors directly,
* namely {@link At &#064;At} (specified in {@link At#desc &#064;At.desc}) and
* all <b>Injector</b> annotations (specified in <tt>target</tt> - for example
* {@link Inject#target &#064;Inject.target}). In these cases it is not
* necessary to specify an {@link Desc#id id} for the descriptor since the usage
* is inferred from context.</p>
*
* <h3>Resolved Descriptors</h3>
*
* <p>Descriptors can also be placed as annotations on the mixin method or the
* mixin class, thus allowing descriptors to be re-used by multiple consumers.
* For example where several injectors target the same method, the descriptor
* can be placed on the mixin itself and consumed by id. In this situation it is
* necessary to specify an {@link Desc#id id} for the descriptor and specify the
* chosen id as a selector string:</p>
*
* <blockquote><code>&#064;Mixin(TargetClass.class)<br />
* &#064;Desc(id = "<ins>foo</ins>", value = "getFoo", args = { int.class })
* <br />
* abstract class MyMixin {<br />
* <br />
* &nbsp; &nbsp; &#064;Inject(target = "<ins>&#064;Desc(foo)</ins>", at =
* &#064;At("RETURN"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }<br />
* <br />
* }</code></blockquote>
*
* <p>Note that the id string can be anything you wish, but is matched
* case-insensitively and must be non-empty, so feel free to be as descriptive
* as you wish.</p>
*
* <h4>Implicit coordinates</h4>
*
* <p>As an alternative to specifying an <em>explicit</em> descriptor id for
* descriptors, it is also possible to use implicit coordinates generated using
* the location of the consumer. To do so, use the selector <tt>"&#064;Desc"
* </tt> with no arguments and give the descriptor an {@link Desc#id id} which
* corresponds to the coordinate of the consumer:</p>
*
* <p>In this example, the coordinate of the {@link At &#064;At} annotation,
* <tt>"at"</tt> is used as the descriptor id.</p>
*
* <blockquote><code>
* &nbsp; &nbsp; &#064;Desc(id = "<ins>at</ins>",
* value = "theMethodName", args = { String.class }, ret = boolean.class)<br />
* &nbsp; &nbsp; &#064;Inject(method = "targetMethod()V", at =
* &#064;At(value = "INVOKE" target = "<ins>&#064;Desc</ins>"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }
* </code></blockquote>
*
* <p>As the resolver widens its search it adds new components to the start of
* the implicit coordinate which match the element, separated by dots. For
* example {@link At &#064;At} annotations inside a {@link Slice &#064;Slice}
* will first resolve as (local coordinate) <tt>from</tt>, followed by
* <tt>slice.from</tt>, and finally <tt>handlerMethodName.slice.from</tt>. This
* allows implicit coordinates to be used up to the mixin level as in the first
* example.</p>
*
* <blockquote><code>&#064;Mixin(TargetClass.class)<br />
* &#064;Desc(id = "<ins>myHandlerMethod.at</ins>", value = "theMethodName",
* args = { String.class }, ret = boolean.class)<br />
* &#064;Desc(id = "<ins>myHandlerMethod.method</ins>", value = "getFoo", args =
* { int.class })<br />
* abstract class MyMixin {<br />
* <br />
* &nbsp; &nbsp; &#064;Inject(method = "<ins>@Desc</ins>", at = &#064;At(value =
* "INVOKE" target = "<ins>&#064;Desc</ins>"))<br />
* &nbsp; &nbsp; void myHandlerMethod(int arg, CallbackInfo ci) {<br />
* &nbsp; &nbsp; &nbsp; ...<br />
* &nbsp; &nbsp; }
* </code></blockquote>
*
* <p>To view the coordinates used to resolve the descriptor for a particular
* element, use the special id "?" in the selector:</p>
*
* <blockquote><code>
* &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) {
* </code></blockquote>
*
* <p>This will cause the resolver to pretty-print the considered coordinates
* and elements into the console:</p>
*
* <blockquote><pre>/*****************************************************&#47;
*&#47;* Coordinate Search Element Detail *&#47;
*&#47;*****************************************************&#47;
*&#47;* at &#64;At &#64;At.desc *&#47;
*&#47;* at myHandler method *&#47;
*&#47;* myhandler.at mixins.json:MyMixin mixin *&#47;
*&#47;* myhandler.at &#64;Redirect &#64;Redirect.desc *&#47;
*&#47;* myhandler.at myhandler method *&#47;
*&#47;*****************************************************&#47;</pre>
*</blockquote>
*
* <p>Don't worry that some combinations of coordinate and element are not
* possible (for example there is no member <tt>desc</tt> on <tt>&#64;At</tt>).
* The resolver doesn't know that and scans each visited element for members it
* supports.</p>
*/
@SelectorId("Desc")
public final class DynamicSelectorDesc extends DynamicSelectorAbstract {
/**
* The input string, only stored if the descriptor is invalid so we can emit
* it in the error message
* Parser/resolver error mesage, only stored if the descriptor is invalid so
* we can emit it when {@link #validate} is called
*/
private final String input;
/**
* Searched coordinates, only stored if the descriptor is invalid so we can
* emit it in the error message
*/
private final Set<String> searched;
private final InvalidSelectorException parseException;
/**
* Resolved id
@@ -101,23 +203,23 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract {
*/
private final String methodDesc;
private DynamicSelectorDesc(String id, Type owner, String name, Type[] args, Type returnType) {
this(null, null, id, owner, name, args, returnType, Bytecode.getDescriptor(returnType, args));
private DynamicSelectorDesc(IResolvedDescriptor desc) {
this(null, desc.getId(), desc.getOwner(), desc.getName(), desc.getArgs(), desc.getReturnType());
}
private DynamicSelectorDesc(String input, Set<String> searched) {
this(input, searched, null, null, null, null, null, null);
private DynamicSelectorDesc(InvalidSelectorException ex) {
this(ex, null, null, null, null, null);
}
private DynamicSelectorDesc(String input, Set<String> searched, String id, Type owner, String name, Type[] args, Type returnType, String desc) {
this.input = input;
this.searched = searched;
private DynamicSelectorDesc(InvalidSelectorException ex, String id, Type owner, String name, Type[] args, Type returnType) {
this.parseException = ex;
this.id = id;
this.owner = owner;
this.name = name;
this.args = args;
this.returnType = returnType;
this.methodDesc = desc;
this.methodDesc = returnType != null ? Bytecode.getDescriptor(returnType, args) : null;
}
/**
@@ -130,11 +232,13 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract {
* @return parsed selector
*/
public static DynamicSelectorDesc parse(String input, ISelectorContext context) {
Result result = DescriptorResolver.resolve(input, context);
if (!result.isResolved()) {
return new DynamicSelectorDesc(input, result.getSearched());
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 DynamicSelectorDesc.of(context, result.getAnnotation());
return DynamicSelectorDesc.of(descriptor);
}
/**
@@ -145,11 +249,11 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract {
* @return parsed selector
*/
public static DynamicSelectorDesc resolve(ISelectorContext context) {
Result result = DescriptorResolver.resolve("", context);
if (!result.isResolved()) {
IResolvedDescriptor descriptor = DescriptorResolver.resolve("", context);
if (!descriptor.isResolved()) {
return null;
}
return DynamicSelectorDesc.of(context, result.getAnnotation());
return DynamicSelectorDesc.of(descriptor);
}
/**
@@ -160,24 +264,21 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract {
* @return selector
*/
public static DynamicSelectorDesc of(ISelectorContext context, IAnnotationHandle desc) {
return DynamicSelectorDesc.of(context.getMixin(), desc);
IResolvedDescriptor descriptor = DescriptorResolver.resolve("", context);
if (!descriptor.isResolved()) {
return null;
}
return DynamicSelectorDesc.of(context, descriptor.getAnnotation());
}
/**
* Convert the supplied annotation into a selector instance
*
* @param mixin Mixin context
* @param desc Annotation to parse
* @param desc Resolved descriptor
* @return selector
*/
public static DynamicSelectorDesc of(IMixinContext mixin, IAnnotationHandle desc) {
String id = desc.<String>getValue("id", "");
Type ownerClass = desc.<Type>getValue("owner", Type.VOID_TYPE);
Type owner = ownerClass == Type.VOID_TYPE ? Type.getObjectType(mixin.getTargetClassRef()) : ownerClass;
String name = desc.<String>getValue();
List<Type> args = desc.getTypeList("args");
Type returnType = desc.<Type>getValue("ret", Type.VOID_TYPE);
return new DynamicSelectorDesc(id, owner, name, args.toArray(new Type[args.size()]), returnType);
public static DynamicSelectorDesc of(IResolvedDescriptor desc) {
return new DynamicSelectorDesc(desc);
}
public String getId() {
@@ -202,9 +303,8 @@ public final class DynamicSelectorDesc extends DynamicSelectorAbstract {
@Override
public ITargetSelector validate() throws InvalidSelectorException {
if (this.input != null) {
String extra = this.input.length() == 0 ? " searched in " + this.searched : "";
throw new InvalidSelectorException("Could not resolve @Desc(" + this.input + ")" + extra);
if (this.parseException != null) {
throw this.parseException;
}
return this;
}
@@ -0,0 +1,81 @@
/*
* 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.dynamic;
import org.objectweb.asm.Type;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* A resolved descriptor, or rather the result of resolving a descriptor. If the
* descriptor was not resolved then {@link #isResolved} returns <tt>false</tt>.
*/
public interface IResolvedDescriptor {
/**
* Get whether the descriptor was successfully resolved
*/
public abstract boolean isResolved();
/**
* Get the resolved descriptor, or null if the descriptor was not resolved
*/
public abstract IAnnotationHandle getAnnotation();
/**
* Get information about the resolution process (eg. visited implicit
* coordinates) as a human-readable string for inclusion in error messages.
*/
public abstract String getResolutionInfo();
/**
* Get the ID of the resolved descriptor, should match the query
*/
public abstract String getId();
/**
* Get the owner from the resolved descriptor, returns <tt>void</tt> if the
* descriptor was not resolved.
*/
public abstract Type getOwner();
/**
* Get the name from the resolved descriptor, returns an empty string if the
* descriptor was not resolved.
*/
public abstract String getName();
/**
* Get the arguments from the resolved descriptor, returns an empty array if
* the descriptor was not resolved.
*/
public abstract Type[] getArgs();
/**
* Get the return type from the resolved descriptor, returns <tt>void</tt>
* if the descriptor was not resolved.
*/
public abstract Type getReturnType();
}
@@ -313,7 +313,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
for (AnnotationNode target : Annotations.<AnnotationNode>getValue(this.annotation, "target", false)) {
try {
selectors.add(DynamicSelectorDesc.of(this.mixin, Annotations.handleOf(target)).validate());
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,
@@ -322,7 +322,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
if (selectors.size() == 0) {
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'desc' to specify targets",
throw new InvalidInjectionException(this, String.format("%s annotation on %s is missing 'method' or 'target' to specify targets",
this.annotationType, this.methodName));
}
return selectors;
@@ -680,7 +680,7 @@ public abstract class InjectionInfo extends SpecialMethodInfo implements ISliceC
}
static String describeInjector(IMixinContext mixin, AnnotationNode annotation, MethodNode method) {
return String.format("%s->@%s::%s%s", mixin.toString(), Bytecode.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc);
return String.format("%s->@%s::%s%s", mixin.toString(), Annotations.getSimpleName(annotation), MethodNodeEx.getName(method), method.desc);
}
/**
@@ -27,7 +27,8 @@ package org.spongepowered.asm.mixin.injection.struct;
import org.objectweb.asm.tree.AnnotationNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* Specialised SelectorAnnotationContext for injection points
@@ -39,11 +40,16 @@ public class InjectionPointAnnotationContext extends SelectorAnnotationContext i
*/
private IInjectionPointContext parentContext;
public InjectionPointAnnotationContext(IInjectionPointContext parent, Object selectorAnnotation, String selectorCoordinate) {
public InjectionPointAnnotationContext(IInjectionPointContext parent, IAnnotationHandle selectorAnnotation, String selectorCoordinate) {
super(parent, selectorAnnotation, selectorCoordinate);
this.parentContext = parent;
}
public InjectionPointAnnotationContext(IInjectionPointContext parent, AnnotationNode selectorAnnotation, String selectorCoordinate) {
super(parent, Annotations.handleOf(selectorAnnotation), selectorCoordinate);
this.parentContext = parent;
}
/* (non-Javadoc)
* @see org.spongepowered.asm.util.IMessageSink
* #addMessage(java.lang.String, java.lang.Object[])
@@ -62,27 +68,27 @@ public class InjectionPointAnnotationContext extends SelectorAnnotationContext i
return this.parentContext.getMethod();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.IInjectionPointContext
* #getAnnotationNode()
*/
@Override
public AnnotationNode getAnnotationNode() {
return this.parentContext.getAnnotationNode();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.struct
* .SelectorAnnotationContext#getAnnotation()
*/
@Override
public AnnotationNode getAnnotation() {
public IAnnotationHandle getAnnotation() {
return this.parentContext.getAnnotation();
}
/* (non-Javadoc)
* @see org.spongepowered.asm.mixin.injection.struct
* .SelectorAnnotationContext#getSelectorAnnotation()
*/
@Override
public AnnotationNode getSelectorAnnotation() {
return (AnnotationNode)super.getSelectorAnnotation();
}
@Override
public String toString() {
return String.format("%s->@%s(%s)", this.parentContext, Bytecode.getSimpleName(this.getSelectorAnnotation()),
return String.format("%s->%s(%s)", this.parentContext, this.getSelectorAnnotation(),
this.getSelectorCoordinate(false));
}
@@ -45,7 +45,9 @@ import org.spongepowered.asm.mixin.injection.selectors.dynamic.DynamicSelectorDe
import org.spongepowered.asm.mixin.injection.throwables.InvalidInjectionPointException;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.Annotations.Handle;
import org.spongepowered.asm.util.IMessageSink;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import com.google.common.base.Joiner;
import com.google.common.base.Strings;
@@ -208,7 +210,7 @@ public class InjectionPointData {
* Get the root annotation (eg. {@link Inject})
*/
public AnnotationNode getParent() {
return this.context.getAnnotation();
return this.context.getAnnotationNode();
}
/**
@@ -281,7 +283,8 @@ public class InjectionPointData {
public ITargetSelector getTarget() {
try {
if (Strings.isNullOrEmpty(this.target)) {
AnnotationNode desc = Annotations.<AnnotationNode>getValue(this.context.getSelectorAnnotation(), "desc");
IAnnotationHandle selectorAnnotation = this.context.getSelectorAnnotation();
AnnotationNode desc = Annotations.<AnnotationNode>getValue(((Handle)selectorAnnotation).getNode(), "desc");
if (desc != null) {
String id = Annotations.<String>getValue(desc, "id", "at");
if ("at".equalsIgnoreCase(id)) {
@@ -291,7 +294,7 @@ public class InjectionPointData {
}
return TargetSelector.parseAndValidate(this.target, this.context);
} catch (InvalidSelectorException ex) {
throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed parsing @At(\"%s\").target \"%s\" on %s",
throw new InvalidInjectionPointException(this.getMixin(), ex, "Failed validating @At(\"%s\").target \"%s\" on %s",
this.at, this.target, this.getDescription());
}
}
@@ -300,7 +303,7 @@ public class InjectionPointData {
* Get a description of this injector for use in error messages
*/
public String getDescription() {
return InjectionInfo.describeInjector(this.context.getMixin(), this.context.getAnnotation(), this.context.getMethod());
return InjectionInfo.describeInjector(this.context.getMixin(), this.context.getAnnotationNode(), this.context.getMethod());
}
/**
@@ -26,6 +26,7 @@ package org.spongepowered.asm.mixin.injection.struct;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
/**
* Narrowed context for selectors in annotations which are themselves inside
@@ -42,7 +43,7 @@ public class SelectorAnnotationContext implements ISelectorContext {
/**
* The annotation for this selector
*/
private final Object selectorAnnotation;
private final IAnnotationHandle selectorAnnotation;
/**
* The coordinate for this selector
@@ -57,7 +58,7 @@ public class SelectorAnnotationContext implements ISelectorContext {
* @param selectorAnnotation Annotation for this selector, eg. &#064;At
* @param selectorCoordinate Coordinate for this selector
*/
public SelectorAnnotationContext(ISelectorContext parent, Object selectorAnnotation, String selectorCoordinate) {
public SelectorAnnotationContext(ISelectorContext parent, IAnnotationHandle selectorAnnotation, String selectorCoordinate) {
this.parent = parent;
this.selectorAnnotation = selectorAnnotation;
this.selectorCoordinate = selectorCoordinate;
@@ -96,7 +97,7 @@ public class SelectorAnnotationContext implements ISelectorContext {
* #getAnnotation()
*/
@Override
public Object getAnnotation() {
public IAnnotationHandle getAnnotation() {
return this.parent.getAnnotation();
}
@@ -105,7 +106,7 @@ public class SelectorAnnotationContext implements ISelectorContext {
* #getSelectorAnnotation()
*/
@Override
public Object getSelectorAnnotation() {
public IAnnotationHandle getSelectorAnnotation() {
return this.selectorAnnotation;
}
@@ -24,6 +24,8 @@
*/
package org.spongepowered.asm.mixin.struct;
import java.util.Locale;
import javax.tools.Diagnostic.Kind;
import org.objectweb.asm.tree.AnnotationNode;
@@ -33,6 +35,8 @@ import org.spongepowered.asm.mixin.injection.IInjectionPointContext;
import org.spongepowered.asm.mixin.injection.selectors.ISelectorContext;
import org.spongepowered.asm.mixin.refmap.IMixinContext;
import org.spongepowered.asm.mixin.refmap.IReferenceMapper;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.asm.IAnnotationHandle;
import org.spongepowered.asm.util.logging.MessageRouter;
/**
@@ -105,6 +109,14 @@ public class AnnotatedMethodInfo implements IInjectionPointContext {
public String getMethodName() {
return this.method.name;
}
/**
* Get the primary annotation which makes this method special
*/
@Override
public AnnotationNode getAnnotationNode() {
return this.annotation;
}
/**
* Get the primary annotation which makes this method special
@@ -112,8 +124,8 @@ public class AnnotatedMethodInfo implements IInjectionPointContext {
* @return The primary method annotation
*/
@Override
public final AnnotationNode getAnnotation() {
return this.annotation;
public final IAnnotationHandle getAnnotation() {
return Annotations.handleOf(this.annotation);
}
/**
@@ -123,8 +135,8 @@ public class AnnotatedMethodInfo implements IInjectionPointContext {
* @return The selector context annotation
*/
@Override
public AnnotationNode getSelectorAnnotation() {
return this.annotation;
public IAnnotationHandle getSelectorAnnotation() {
return Annotations.handleOf(this.annotation);
}
/**
@@ -134,7 +146,7 @@ public class AnnotatedMethodInfo implements IInjectionPointContext {
*/
@Override
public String getSelectorCoordinate(boolean leaf) {
return leaf ? "method" : this.getMethodName().toLowerCase();
return leaf ? "method" : this.getMethodName().toLowerCase(Locale.ROOT);
}
/* (non-Javadoc)
@@ -29,7 +29,7 @@ import org.objectweb.asm.tree.ClassNode;
import org.objectweb.asm.tree.MethodNode;
import org.spongepowered.asm.mixin.transformer.ClassInfo;
import org.spongepowered.asm.mixin.transformer.MixinTargetContext;
import org.spongepowered.asm.util.Bytecode;
import org.spongepowered.asm.util.Annotations;
import org.spongepowered.asm.util.asm.MethodNodeEx;
/**
@@ -60,7 +60,7 @@ public class SpecialMethodInfo extends AnnotatedMethodInfo {
public SpecialMethodInfo(MixinTargetContext mixin, MethodNode method, AnnotationNode annotation) {
super(mixin, method, annotation);
this.mixin = mixin;
this.annotationType = this.annotation != null ? "@" + Bytecode.getSimpleName(this.annotation) : "Undecorated injector";
this.annotationType = this.annotation != null ? "@" + Annotations.getSimpleName(this.annotation) : "Undecorated injector";
this.classNode = mixin.getTargetClassNode();
this.methodName = MethodNodeEx.getName(method);
}
@@ -636,7 +636,7 @@ class MixinApplicatorStandard {
return true;
}
throw new InvalidMixinException(mixin, String.format("Incompatible @%s %s (for %s) in %s previously written by %s (for %s)",
Bytecode.getSimpleName(accMethod), method.name, myTarget, mixin, owner, trTarget));
Annotations.getSimpleName(accMethod), method.name, myTarget, mixin, owner, trTarget));
}
}
@@ -112,7 +112,7 @@ class MixinPreProcessorStandard {
private SpecialMethod(boolean isOverwrite, Class<? extends Annotation> type) {
this.isOverwrite = isOverwrite;
this.annotation = type;
this.description = "@" + Bytecode.getSimpleName(type);
this.description = "@" + Annotations.getSimpleName(type);
}
private SpecialMethod(boolean isOverwrite) {
@@ -380,7 +380,7 @@ class MixinPreProcessorStandard {
} else {
String uniqueName = context.getUniqueName(mixinMethod, true);
MixinPreProcessorStandard.logger.log(this.mixin.getLoggingLevel(), "Renaming @{} method {}{} to {} in {}",
Bytecode.getSimpleName(annotation), mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin);
Annotations.getSimpleName(annotation), mixinMethod.name, mixinMethod.desc, uniqueName, this.mixin);
mixinMethod.name = method.conform(uniqueName);
}
@@ -1257,7 +1257,7 @@ public class MixinTargetContext extends ClassContext implements IMixinContext {
}
methodActivity.next("Undecorate");
method.visibleAnnotations.remove(injectInfo.getAnnotation());
method.visibleAnnotations.remove(injectInfo.getAnnotationNode());
methodActivity.end();
}
prepareActivity.end();
@@ -61,11 +61,15 @@ public final class Annotations {
private final AnnotationNode annotation;
public Handle(AnnotationNode annotation) {
Handle(AnnotationNode annotation) {
Preconditions.checkNotNull(annotation, "annotation");
this.annotation = annotation;
}
public AnnotationNode getNode() {
return this.annotation;
}
@Override
public String getDesc() {
return this.annotation.desc;
@@ -116,7 +120,7 @@ public final class Annotations {
@Override
public String toString() {
return "@" + Bytecode.getSimpleName(this.annotation);
return "@" + Annotations.getSimpleName(this.annotation);
}
}
@@ -157,6 +161,28 @@ public final class Annotations {
}
}
/**
* Returns the simple name of an annotation, mainly used for printing
* annotation names in error messages/user-facing strings
*
* @param annotationType annotation
* @return annotation's simple name
*/
public static String getSimpleName(Class<? extends Annotation> annotationType) {
return annotationType.getSimpleName();
}
/**
* Returns the simple name of an annotation, mainly used for printing
* annotation names in error messages/user-facing strings
*
* @param annotation annotation node
* @return annotation's simple name
*/
public static String getSimpleName(AnnotationNode annotation) {
return Bytecode.getSimpleName(annotation.desc);
}
/**
* Set a runtime-visible annotation of the specified class on the supplied
* field node
@@ -26,7 +26,6 @@ package org.spongepowered.asm.util;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.lang.annotation.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
@@ -766,17 +765,6 @@ public final class Bytecode {
return desc.substring(0, desc.lastIndexOf(')') + 1) + returnType;
}
/**
* Returns the simple name of an annotation, mainly used for printing
* annotation names in error messages/user-facing strings
*
* @param annotationType annotation
* @return annotation's simple name
*/
public static String getSimpleName(Class<? extends Annotation> annotationType) {
return annotationType.getSimpleName();
}
/**
* Returns the simple name of a type representing a class
*
@@ -786,17 +774,6 @@ public final class Bytecode {
public static String getSimpleName(Type type) {
return type.getSort() < Type.ARRAY ? type.getDescriptor() : Bytecode.getSimpleName(type.getClassName());
}
/**
* Returns the simple name of an annotation, mainly used for printing
* annotation names in error messages/user-facing strings
*
* @param annotation annotation node
* @return annotation's simple name
*/
public static String getSimpleName(AnnotationNode annotation) {
return Bytecode.getSimpleName(annotation.desc);
}
/**
* Returns the simple name from an object type descriptor (in L...; format)