### Set up MixinSquared with ShadowJar for other platforms Source: https://github.com/bawnorton/mixinsquared/blob/master/README.md Rough guide for setting up MixinSquared on platforms not covered by the provided setup, using ShadowJar to relocate and include the library. You will need to look into the specifics of setting up ShadowJar for your platform. ```gradle plugins { id "com.github.johnrengelman.shadow" version "8.1.0" } configurations { implementation.extendsFrom shadow } repositories { maven { url = "https://maven.bawnorton.com" } } dependencies { shadow(annotationProcessor("com.github.bawnorton.mixinsquared:mixinsquared-common:0.3.7")) } shadowJar { configurations = [project.configurations.shadow] relocate("com.bawnorton.mixinsquared", "your.package.goes.here.mixinsquared") mergeServiceFiles() } ``` -------------------------------- ### Example: registering a canceller Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinCancellerRegistrar.md Shows how to register a MixinCanceller that cancels mixins whose class name starts with "com.example.legacy". Duplicate registration of the same instance is a no-op. ```java import com.bawnorton.mixinsquared.api.MixinCanceller; import com.bawnorton.mixinsquared.canceller.MixinCancellerRegistrar; public class MyMod { public static void registerCancellers() { MixinCancellerRegistrar.register(new MixinCanceller() { @Override public boolean shouldCancel(List targetClassNames, String mixinClassName) { return mixinClassName.startsWith("com.example.legacy"); } }); // duplicate registration of the same instance is a no-op (HashSet) MixinCancellerRegistrar.register(otherCanceller); } } ``` -------------------------------- ### setupLogging() method Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredAnnotationProcessor.md Attempts to install a SimpleMessager into Mixin's MessageRouter. Returns true on success, false if Mixin classes are missing (NoClassDefFoundError). ```java private static boolean setupLogging() { try { MessageRouter.setMessager(new SimpleMessager()); return true; } catch (NoClassDefFoundError e) { return false; } } ``` -------------------------------- ### Compile-time log output example Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredAnnotationProcessor.md Example of log output produced by SimpleMessager during compilation. ```text [WARNING] ...mixin message... [ERROR] ... ``` -------------------------------- ### Gradle dependency example Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredAnnotationProcessor.md Shows how to declare the annotation processor in a Gradle build, pulling in the mixinsquared-fabric artifact. ```java // build.gradle (Gradle) — the annotation processor is pulled in alongside the runtime jar dependencies { include(implementation(annotationProcessor("com.github.bawnorton.mixinsquared:mixinsquared-fabric:0.3.7"))) } ``` -------------------------------- ### Standard usage in a custom IMixinConfigPlugin Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredBootstrap.md Example of calling MixinSquaredBootstrap.init() in onLoad and reOrderExtensions() in getMixins() for platforms without a built-in plugin. ```java // In a custom IMixinConfigPlugin for a platform without a built-in plugin // (see configuration.md, "Any Other Platform"): public class MyMixinConfigPlugin implements IMixinConfigPlugin { @Override public void onLoad(String mixinPackage) { MixinSquaredBootstrap.init(); } @Override public List getMixins() { MixinSquaredBootstrap.reOrderExtensions(); return null; } } ``` -------------------------------- ### Example mixin with @Redirect handler Source: https://github.com/bawnorton/mixinsquared/wiki/Home Example mixin that redirects a damage method and logs a warning when another mod does not handle the damage. ```java @Mixin(TargetClass.class) public abstract class TargetClassMixin { @Redirect( method = "targetMethod", at = @At( value = "INVOKE", target = "Lpackage/to/TargetClass;damage(Lpackage/to/class/DamageSource;F)Z" ) ) private boolean handleDamage(TargetClass instance, DamageSource source, float amount) { if(!AnotherMod.handleDamage(source, amount)) { LOGGER.warn("Could not handle damage"); } } } ``` -------------------------------- ### Example: interacting with the adapters Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/reflection.md Shows how to use TargetClassContextExtension.tryAs to access the live mixins set and print each mixin's class name. The consumer is only invoked when the context is an instance of the internal TargetClassContext. ```java import com.bawnorton.mixinsquared.reflection.TargetClassContextExtension; TargetClassContextExtension.tryAs(context, ctx -> { ctx.getMixins().forEach(mixinInfo -> { System.out.println(mixinInfo.getClassName()); }); }); ``` -------------------------------- ### Fabric entrypoint provider example (fabric.mod.json fragment) Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/platform.md Shows how to register a canceller and an adjuster via the 'mixinsquared' and 'mixinsquared-adjuster' entrypoints in a fabric.mod.json fragment. Replace 'com.example.MyCanceller' and 'com.example.MyAdjuster' with your own class names. ```json // fabric.mod.json fragment { "entrypoints": { "mixinsquared": [ "com.example.MyCanceller" ], "mixinsquared-adjuster": [ "com.example.MyAdjuster" ] } } ``` -------------------------------- ### Basic canceller example Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinCanceller.md A simple implementation that cancels a specific mixin by name. ```java import com.bawnorton.mixinsquared.api.MixinCanceller; public class BugsOutCanceller implements MixinCanceller { @Override public boolean shouldCancel(List targetClassNames, String mixinClassName) { // Prevent "BuggyMixin" from ever being applied return mixinClassName.equals("com.example.bug.BuggyMixin"); } } ``` -------------------------------- ### Reading mixin configuration by name Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinAnnotationReader.md Example of reading a mixin's configuration by class name using the static convenience methods. Prints the targets, priority, and remap values. ```java import com.bawnorton.mixinsquared.tools.MixinAnnotationReader; public static void inspectMixin(String className) { List targets = MixinAnnotationReader.getValue(className); int priority = MixinAnnotationReader.getPriority(className); boolean remap = MixinAnnotationReader.getRemap(className); System.out.println(className + " -> targets: " + targets + ", priority: " + priority + ", remap: " + remap); } ``` -------------------------------- ### Change detection with AnnotationEqualityVisitor Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/util.md Example usage in the kernel: creates a visitor with a copy of the node before adjustment, runs the adjuster, visits the adjusted node, and checks if the adjuster modified the annotation. ```java import com.bawnorton.mixinsquared.util.AnnotationEqualityVisitor; AnnotationEqualityVisitor visitor = new AnnotationEqualityVisitor(nodeBefore.copy()); nodeAfter = adjuster.adjust(targets, mixin, handler, nodeAfter); visitor.visit(nodeAfter); if (!visitor.isEqual()) { System.err.println("adjuster modified the annotation"); } ``` -------------------------------- ### Custom IExtension implementing MixinSquaredExtension Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredExtension.md Example of a custom IExtension implementing MixinSquaredExtension to receive the same 'run before everything else' treatment. Third-party authors typically do not implement this interface; it is an internal contract. ```java import com.bawnorton.mixinsquared.ext.MixinSquaredExtension; import org.spongepowered.asm.mixin.MixinEnvironment; import org.spongepowered.asm.mixin.transformer.ext.IExtension; import org.spongepowered.asm.mixin.transformer.ext.ITargetClassContext; import org.objectweb.asm.tree.ClassNode; public class MyExtension implements IExtension, MixinSquaredExtension { @Override public boolean checkActive(MixinEnvironment environment) { return true; } @Override public void preApply(ITargetClassContext context) { /* runs before non-Squared extensions */ } @Override public void postApply(ITargetClassContext context) { } @Override public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) { } } ``` -------------------------------- ### Instance methods is, as, get, set Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableAnnotationNode.md Instance methods for AdjustableAnnotationNode: is() checks descriptor equality, as() downcasts with a ClassCastException on failure, get() reads an annotation value returning Optional.empty() when absent, and set() writes a value. ```java public boolean is(Class annotation) { return desc.equals(Type.getDescriptor(annotation)); } public T as(Class type) { if (type.isInstance(this)) { return type.cast(this); } throw new ClassCastException(String.format( "Cannot cast %s to %s", this.getClass().getSimpleName(), type.getSimpleName() )); } public Optional get(String key) { return Optional.ofNullable(Annotations.getValue(this, key)); } public void set(String key, T value) { Annotations.setValue(this, key, value); } ``` -------------------------------- ### get(String) Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableAnnotationNode.md Reads an annotation value by key, returning an Optional that may be empty. ```APIDOC ## [INSTANCE] get ### Description Retrieves the value of an annotation attribute by its key. ### Method Instance method ### Signature ```java public Optional get(String key) ``` ### Parameters - **key** (String) - Required - The attribute name. ### Returns - **Optional** - The value if present, otherwise Optional.empty(). ### Example ```java Optional value = node.get("value"); ``` ``` -------------------------------- ### Adjusting a @Redirect in an adjuster Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableRedirectFamily.md Example showing how to adjust a @Redirect annotation by changing its target method. ```APIDOC ## Adjusting a @Redirect in an adjuster ### Description This example demonstrates how to adjust a @Redirect annotation by modifying its target method using the AdjustableRedirectNode API. ### Code Example ```java import com.bawnorton.mixinsquared.adjuster.tools.AdjustableAnnotationNode; import com.bawnorton.mixinsquared.adjuster.tools.AdjustableRedirectNode; public AdjustableAnnotationNode handleRedirect(AdjustableAnnotationNode node) { if (!node.is(Redirect.class)) return node; AdjustableRedirectNode redirect = node.as(AdjustableRedirectNode.class); return redirect.withAt(at -> at.withTarget(t -> "Lpackage/to/NewTarget;method()V")); } ``` ``` -------------------------------- ### Building a @ModifyArg node for a specific index Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableRedirectFamily.md Example showing how to build a @ModifyArg node with a specific index and method. ```APIDOC ## Building a @ModifyArg node for a specific index ### Description This example demonstrates how to construct a @ModifyArg node with a custom injection point, index, and method using the AdjustableModifyArgNode API. ### Code Example ```java import com.bawnorton.mixinsquared.adjuster.tools.AdjustableAtNode; import com.bawnorton.mixinsquared.adjuster.tools.AdjustableModifyArgNode; AdjustableAtNode invoke = AdjustableAtNode.InjectionPoint.custom("INVOKE").toNode() .withTarget(t -> "Lexample/Target;run(Ljava/lang/String;)V"); AdjustableModifyArgNode modifyArg = AdjustableModifyArgNode.defaultNode(invoke) .withIndex(i -> 1) .withMethod(m -> { m.add("targetMethod"); return m; }); ``` ``` -------------------------------- ### MixinAnnotationAdjuster.adjust Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinAnnotationAdjuster.md Documentation for the MixinAnnotationAdjuster.adjust method, including its signature, parameters, return value, and usage examples. ```APIDOC ## MixinAnnotationAdjuster.adjust ### Description Adjusts a mixin annotation node during the annotation adjustment process. This method is called by the framework for each registered adjuster, allowing modification or removal of annotations on mixin handler methods. ### Method adjust ### Signature `AdjustableAnnotationNode adjust(List targetClassNames, String mixinClassName, MethodNode handlerNode, AdjustableAnnotationNode annotationNode)` ### Parameters - **targetClassNames** (List) - Required - The list of target class names for the mixin. - **mixinClassName** (String) - Required - The name of the mixin class. - **handlerNode** (MethodNode) - Required - The ASM MethodNode representing the handler method. - **annotationNode** (AdjustableAnnotationNode) - Required - The adjustable annotation node to modify. ### Return Value - **AdjustableAnnotationNode** - The adjusted annotation node, or `null` to remove the annotation entirely. ### Behavior - The framework iterates over all registered adjusters in `HashSet` iteration order. - For each adjuster, it copies the current node, builds an `AnnotationEqualityVisitor`, calls `adjust`, and checks if the node changed. - If changed, logs a warning and debug lines. - Returns the final node to `ExtensionAnnotationAdjust`. ### Example: Basic Adjuster ```java import com.bawnorton.mixinsquared.adjuster.tools.AdjustableAnnotationNode; import com.bawnorton.mixinsquared.adjuster.tools.AdjustableAtNode; import com.bawnorton.mixinsquared.adjuster.tools.AdjustableRedirectNode; import com.bawnorton.mixinsquared.adjuster.tools.type.AtAnnotationNode; import com.bawnorton.mixinsquared.api.MixinAnnotationAdjuster; import org.objectweb.asm.tree.MethodNode; public class MyAnnotationAdjuster implements MixinAnnotationAdjuster { @Override public AdjustableAnnotationNode adjust(List targetClassNames, String mixinClassName, MethodNode handlerNode, AdjustableAnnotationNode annotationNode) { // Only touch @Redirect annotations if (!annotationNode.is(Redirect.class)) return annotationNode; AdjustableRedirectNode redirect = annotationNode.as(AdjustableRedirectNode.class); // force remap=false on every @At target so obfuscated names pass through redirect.withAt(at -> { at.setRemap(false); return at; }); return redirect; } } ``` ### Example: Removal and Error Handling ```java @Override public AdjustableAnnotationNode adjust(List targetClassNames, String mixinClassName, MethodNode handlerNode, AdjustableAnnotationNode annotationNode) { // 1. returning null removes the annotation entirely if (targetClassNames.contains("com.example.BlockedTarget")) { LOGGER.warn("Removing annotation from {}", mixinClassName); return null; } // 2. guard against the annotation class not existing at runtime: // the node may still be inspected/set regardless of availability try { annotationNode.get("someKey"); } catch (Exception e) { // never assumed to happen; adjustments should tolerate missing values return annotationNode; } return annotationNode; } ``` ``` -------------------------------- ### Example: internal use — invoking the registry directly Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinCancellerRegistrar.md Mirror of ExtensionCancelApplication's predicate, calling shouldCancel directly with a consumer that prints the canceller name to stderr. ```java // Mirror of ExtensionCancelApplication's predicate (kernel code) boolean cancelled = MixinCancellerRegistrar.shouldCancel( targets, mixinClassName, name -> System.err.println("cancelled by " + name) ); ``` -------------------------------- ### Example: selector used by a mixin (application code) Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/DynamicSelectorHandler.md Shows how to use @TargetHandler with @Redirect in a mixin to target a specific handler method. The @TargetHandler specifies the mixin and method name, and the @Redirect uses the special selector "@MixinSquared:Handler". ```java @Mixin(value = TargetClass.class, priority = 1500) public abstract class TargetClassMixinSquared { @TargetHandler(mixin = "com.bawnorton.mixin.TargetClassMixin", name = "handleDamage") @Redirect(method = "@MixinSquared:Handler", at = @At(value = "INVOKE", target = "org/slf4j/Logger.warn(Ljava/lang/String;)V")) private void reduceLogLevel(Logger instance, String message) { instance.debug(message); } } ``` -------------------------------- ### Example: self-target detection (error handling) Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/DynamicSelectorHandler.md Demonstrates a @TargetHandler that targets its own mixin class, which causes an InvalidSelectorException at attach time. Includes a try-catch block to handle this exception. ```java // In mixin "com.foo.MyMixin": @TargetHandler(mixin = "com.foo.MyMixin", name = "handler$targetMethod") // same class! @Inject(method = "@MixinSquared:Handler", at = @At("HEAD")) private void boom(CallbackInfo ci) { } ``` ```java try { // trigger selector validation... } catch (InvalidSelectorException e) { System.err.println("MixinSquared selector misconfigured: " + e.getMessage()); } ``` -------------------------------- ### Conceptual use of TargetClassContextExtension with MixinCancellerRegistrar Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/ExtensionCancelApplication.md Conceptual example showing the equivalent behavior of the extension when used directly. It is not typical to consume the extension directly; the registrar drives it. The snippet illustrates how to remove mixins from the context's mixin set based on MixinCancellerRegistrar.shouldCancel. ```java // Direct consumption is not typical — the extension is driven by the registrar. // The equivalent behavior: TargetClassContextExtension.tryAs(context, ctx -> { ctx.getMixins().removeIf(mixin -> MixinCancellerRegistrar.shouldCancel( targetClassNames(mixin), mixin.getClassName(), DebugLogger::log)); }); ``` -------------------------------- ### MixinSquaredBootstrap.init() Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredBootstrap.md Initializes the MixinSquared runtime by registering the dynamic selector handler and internal extensions. Idempotent; safe to call multiple times. ```APIDOC ## MixinSquaredBootstrap.init() ### Description Initializes the MixinSquared runtime by registering the dynamic selector handler and internal extensions. Idempotent; safe to call multiple times. ### Method STATIC ### Endpoint MixinSquaredBootstrap.init() ### Parameters None ### Request Example ```java MixinSquaredBootstrap.init(); ``` ### Response #### Success Response - **void** - No return value. #### Response Example ```java // No return value ``` ### Error Handling - No errors are thrown by this method. ``` -------------------------------- ### MixinSquaredBootstrap.init() method Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredBootstrap.md Idempotent initialization method that registers the DynamicSelectorHandler and the two internal extensions. Must be called before using the @MixinSquared:Handler selector. ```java public static void init() { if (initialized) return; initialized = true; TargetSelector.register(DynamicSelectorHandler.class, "MixinSquared"); ExtensionRegistrar.register(new ExtensionCancelApplication()); ExtensionRegistrar.register(new ExtensionAnnotationAdjust()); } ``` -------------------------------- ### Implement IMixinConfigPlugin for Fabric platform Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/platform.md Implements IMixinConfigPlugin for the Fabric platform. onLoad bootstraps and loads API implementations; getMixins calls MixinSquaredBootstrap.reOrderExtensions() (must run before MixinExtras processes sugar annotations) and returns null. getRefMapperConfig returns null, shouldApplyMixin always returns true, and acceptTargets/preApply/postApply are no-ops. ```java @Override public void onLoad(String mixinPackage) { MixinSquaredBootstrap.init(); MixinSquaredApiImplLoader.load(); } @Override public String getRefMapperConfig() { return null; } @Override public boolean shouldApplyMixin(String targetClassName, String mixinClassName) { return true; } @Override public void acceptTargets(Set myTargets, Set otherTargets) { } @Override public List getMixins() { MixinSquaredBootstrap.reOrderExtensions(); return null; } @Override public void preApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } @Override public void postApply(String targetClassName, ClassNode targetClass, String mixinClassName, IMixinInfo mixinInfo) { } ``` -------------------------------- ### Selective canceller with conditions and logging Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinCanceller.md Cancels mixins for target classes that start with a legacy package prefix, logging a message to stderr. ```java public class SelectiveCanceller implements MixinCanceller { @Override public boolean shouldCancel(List targetClassNames, String mixinClassName) { // Include the caller class name as the first element per @TargetHandler-style docs? No: // targetClassNames are the mixin's targets ("com.example.Example" format). if (targetClassNames.stream().anyMatch(name -> name.startsWith("com.example.legacy"))) { System.err.println("Skipping " + mixinClassName + " on legacy targets"); return true; } return false; } } ``` -------------------------------- ### Building an @Inject node programmatically Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableInjectorFamilies.md Shows how to create an AdjustableInjectNode with a default HEAD injection point and configure its method, cancellable, locals, and order properties. ```APIDOC ## Building an @Inject node programmatically ### Description Constructs an AdjustableInjectNode with a HEAD injection point and configures method, cancellable, locals, and order. ### Code Example ```java import com.bawnorton.mixinsquared.adjuster.tools.AdjustableAtNode; import com.bawnorton.mixinsquared.adjuster.tools.AdjustableInjectNode; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; AdjustableAtNode head = AdjustableAtNode.InjectionPoint.HEAD.toNode(); AdjustableInjectNode inject = AdjustableInjectNode.defaultNode(head) .withMethod(methods -> { methods.add("someMethod"); return methods; }) .withCancellable(c -> true) .withLocals(l -> LocalCapture.CAPTURE_FAILHARD) .withOrder(o -> 500); ``` ### Defaults - `method`: `[]` - `require`: `-1` - `expect`: `1` - `allow`: `-1` - `constraints`: `""` (core injectors only) - `order`: `1000` (core injectors only) - `remap`: `false` (annotation default is true; node getter returns `false` when absent) - `at` (list): `[]` - `slice` (list): `[]` - `id`: `""` (only AdjustableInjectNode via OptionalIdAnnotationNode) - `cancellable`: `false` (only AdjustableInjectNode) - `locals`: `LocalCapture.NO_CAPTURE` (only AdjustableInjectNode) ``` -------------------------------- ### Build @At("HEAD") and custom INVOKE node with target and shift Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableAtNode.md Builds an @At("HEAD") node and a custom INVOKE node with target, shift AFTER, and by 1, then adds the invoke node to an injector's at list. ```java import com.bawnorton.mixinsquared.adjuster.tools.AdjustableAtNode; import com.bawnorton.mixinsquared.adjuster.tools.type.AtAnnotationNode; import org.spongepowered.asm.mixin.injection.At; AdjustableAtNode head = AdjustableAtNode.InjectionPoint.HEAD.toNode(); AdjustableAtNode invoke = AdjustableAtNode.InjectionPoint.custom("INVOKE") .toNode() .withTarget(t -> "Lpackage/to/TargetClass;damage(Lpackage/to/class/DamageSource;F)Z") .withShift(s -> At.Shift.AFTER) .withBy(b -> 1); // use inside an injector node: inject.withAt(ats -> { ats.add(invoke); return ats; }); ``` -------------------------------- ### Initialize MixinSquared in onLoad method Source: https://github.com/bawnorton/mixinsquared/blob/master/README.md Call MixinSquaredBootstrap.init() in the onLoad method of an IMixinConfigPlugin implementation to initialize MixinSquared manually. ```java MixinSquaredBootstrap.init(); ``` -------------------------------- ### ExtensionAnnotationAdjust class implementing IExtension Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/ExtensionAnnotationAdjust.md Shows the full class skeleton with the checkActive, preApply, postApply, and export methods. checkActive always returns true, preApply performs the annotation adjustment logic, and postApply and export are no-ops. ```java public final class ExtensionAnnotationAdjust implements IExtension, MixinSquaredExtension { private static final ILogger LOGGER = MixinService.getService().getLogger("mixinsquared-annotation-adjuster"); @Override public boolean checkActive(MixinEnvironment environment) { return true; } @Override public void preApply(ITargetClassContext context) { TargetClassContextExtension.tryAs(context, contextExtension -> { SortedSet mixinInfos = contextExtension.getMixins(); mixinInfos.forEach(mixinInfo -> MixinInfoExtension.tryAs(mixinInfo, mixinInfoExtension -> { ClassNode mixinClassNode = mixinInfo.getClassNode(0); List targetClassNames = mixinInfo.getTargetClasses().stream().map(s -> s.replaceAll("/", ".")).collect(Collectors.toList()); String mixinClassName = mixinInfo.getClassName(); ... })); }); } @Override public void postApply(ITargetClassContext context) { } @Override public void export(MixinEnvironment env, String name, boolean force, ClassNode classNode) { } } ``` -------------------------------- ### Error handling for unloadable mixin Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinAnnotationReader.md Example of error handling for an unloadable mixin. The static getTargets(String) method throws a RuntimeException wrapping ClassNotFoundException or IOException, which is caught and printed with the cause. ```java try { // ClassNotFoundException / IOException are wrapped in RuntimeException List targets = MixinAnnotationReader.getTargets("com.example.NoSuchMixin"); } catch (RuntimeException e) { System.err.println("Could not load mixin bytecode: " + e.getCause()); } ``` -------------------------------- ### Load Fabric entrypoints for MixinCanceller and MixinAnnotationAdjuster Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/platform.md Loads consumer-provided MixinCanceller and MixinAnnotationAdjuster implementations from Fabric entrypoints. Uses entrypoint names "mixinsquared" and "mixinsquared-adjuster", registering each into the corresponding registrar. On any Throwable, prints "Mod provides a broken implementation:" plus the stack trace to System.err and skips that provider. ```java public final class MixinSquaredApiImplLoader { public static void load() { FabricLoader.getInstance().getEntrypointContainers("mixinsquared", MixinCanceller.class).forEach(container -> { String id = container.getProvider().getMetadata().getId(); try { MixinCanceller canceller = container.getEntrypoint(); MixinCancellerRegistrar.register(canceller); } catch (Throwable e) { System.err.printf("Mod %s provides a broken MixinCanceller implementation:\n", id); e.printStackTrace(System.err); } }); FabricLoader.getInstance().getEntrypointContainers("mixinsquared-adjuster", MixinAnnotationAdjuster.class).forEach(container -> { String id = container.getProvider().getMetadata().getId(); try { MixinAnnotationAdjuster annotationAdjuster = container.getEntrypoint(); MixinAnnotationAdjusterRegistrar.register(annotationAdjuster); } catch (Throwable e) { System.err.printf("Mod %s provides a broken MixinAnnotationAdjuster implementation:\n", id); e.printStackTrace(System.err); } }); } } ``` -------------------------------- ### Building an @Inject node programmatically Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableInjectorFamilies.md Constructs an AdjustableInjectNode with a HEAD injection point, adds a method name, enables cancellable, sets local capture to CAPTURE_FAILHARD, and sets order to 500. Requires imports from com.bawnorton.mixinsquared.adjuster.tools and org.spongepowered.asm.mixin.injection.callback. ```java import com.bawnorton.mixinsquared.adjuster.tools.AdjustableAtNode; import com.bawnorton.mixinsquared.adjuster.tools.AdjustableInjectNode; import org.spongepowered.asm.mixin.injection.callback.LocalCapture; AdjustableAtNode head = AdjustableAtNode.InjectionPoint.HEAD.toNode(); AdjustableInjectNode inject = AdjustableInjectNode.defaultNode(head) .withMethod(methods -> { methods.add("someMethod"); return methods; }) .withCancellable(c -> true) .withLocals(l -> LocalCapture.CAPTURE_FAILHARD) .withOrder(o -> 500); ``` -------------------------------- ### Class declaration and static initializer Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredAnnotationProcessor.md The processor class is annotated with @ApiStatus.Internal and @SupportedAnnotationTypes({}). Its static initializer calls setupLogging() and, if successful, registers DynamicSelectorHandler under the name "MixinSquared". ```java @ApiStatus.Internal @SupportedAnnotationTypes({}) public final class MixinSquaredAnnotationProcessor extends AbstractProcessor { static { if (setupLogging()) { TargetSelector.register(DynamicSelectorHandler.class, "MixinSquared"); } } ... } ``` -------------------------------- ### Use @TargetHandler to reduce log level Source: https://github.com/bawnorton/mixinsquared/wiki/Home MixinSquared mixin that uses @TargetHandler to target the handler from the example mixin and reduce the log level from warn to debug. Requires a higher priority than the target mixin. ```java @Mixin(value = TargetClass.class, priority = 1500) // priority is higher than the target mixin public abstract class TargetClassMixinSquared { @TargetHandler( mixin = "com.bawnorton.mixin.TargetClassMixin", name = "handleDamage" ) @Redirect( method = "@MixinSquared:Handler", at = @At( value = "INVOKE", target = "org/slf4j/Logger.warn(Ljava/lang/String;)V" ) ) private void reduceLogLevel(Logger instance, String message) { instance.debug(message); } } ``` -------------------------------- ### RemapperHolderAnnotationNode base class Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableAccessAndSugar.md Package-private base class for adjustable annotation nodes that hold a remapper. The remapper is installed by ExtensionAnnotationAdjust via node.setRemapper(node -> node.applyRefmap(mixinInfoExtension::remapClassName)); public RemappableAnnotationNode.applyRefmap() invokes it. ```java abstract class RemapperHolderAnnotationNode extends AdjustableAnnotationNode implements RemappableAnnotationNode { private Consumer remapper; protected RemapperHolderAnnotationNode(AnnotationNode node) { super(node); } @ApiStatus.Internal public Consumer getRemapper() { return remapper; } @ApiStatus.Internal public void setRemapper(Consumer remapper) { this.remapper = remapper; } } ``` -------------------------------- ### Fabric/Quilt entrypoint registration Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinCanceller.md JSON configuration to expose the canceller as an entrypoint named 'mixinsquared' in fabric.mod.json. ```json { "entrypoints": { "mixinsquared": [ "com.example.BugsOutCanceller" ] } } ``` -------------------------------- ### MixinSquaredBootstrap.reOrderExtensions() re-ordering logic Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredExtension.md Re-orders the extension registry and active extensions so all MixinSquaredExtension instances come first, preserving relative order. Called from IMixinConfigPlugin.getMixins() on every platform. ```java // MixinSquaredBootstrap.reOrderExtensions() — exact source List mixinSquaredExtensions = extensions .stream() .filter(MixinSquaredExtension.class::isInstance) .collect(Collectors.toList()); extensions.removeAll(mixinSquaredExtensions); extensions.addAll(0, mixinSquaredExtensions); List activeExtensions = extensionsExtension.getActiveExtensions(); ImmutableList.Builder builder = ImmutableList.builder(); activeExtensions.stream() .filter(MixinSquaredExtension.class::isInstance) .forEach(builder::add); activeExtensions.stream() .filter(extension -> !(extension instanceof MixinSquaredExtension)) .forEach(builder::add); extensionsExtension.setActiveExtensions(builder.build()); ``` -------------------------------- ### RemappableAnnotationNode interface with refmap support Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/types.md Provides accessors for the remap annotation attribute (default false) and an internal remapper callback. The no-arg applyRefmap() invokes the remapper installed by ExtensionAnnotationAdjust to apply the mixin's refmap. ```java public interface RemappableAnnotationNode extends MutableAnnotationNode { default boolean getRemap() { ... orElse(false) } default void setRemap(boolean remap) { ... } default RemappableAnnotationNode withRemap(UnaryOperator remap) { ... } @ApiStatus.Internal void applyRefmap(UnaryOperator refmapApplicator); @ApiStatus.Internal Consumer getRemapper(); @ApiStatus.Internal void setRemapper(Consumer remapper); @ApiStatus.AvailableSince("0.3.0-beta.1") default void applyRefmap() { Consumer remapper = getRemapper(); if (remapper != null) { remapper.accept(this); } } } ``` -------------------------------- ### AdjustableWrapWithConditionNode constructor and defaultNode Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableMixinExtrasInjectors.md Shows the constructor and defaultNode factory for AdjustableWrapWithConditionNode. The defaultNode has no required attributes. ```java public AdjustableWrapWithConditionNode(AnnotationNode node) { super(node); } public static AdjustableWrapWithConditionNode defaultNode() { ... } // no required attributes ``` -------------------------------- ### AdjustableLocalNode API for MixinExtras @Local Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableAccessAndSugar.md Shows the public API of AdjustableLocalNode: constructor, defaultNode, and the with* methods for print, ordinal, index, name, argsOnly, and type. The getters return defaults (empty list, false, void.class) when the attribute is absent. ```java public AdjustableLocalNode(AnnotationNode node) { super(node); } public static AdjustableLocalNode defaultNode() { ... } @Override public AdjustableLocalNode withPrint(UnaryOperator print) // PrintableAnnotationNode @Override public AdjustableLocalNode withOrdinal(UnaryOperator ordinal) // NthTargetAnnotationNode @Override public AdjustableLocalNode withIndex(UnaryOperator index) // NthTargetAnnotationNode public List getName() { return this.>get("name").orElse(new ArrayList<>()); } public void setName(List name) { this.set("name", name); } public AdjustableLocalNode withName(UnaryOperator> name) { ... } public boolean getArgsOnly() { return this.get("argsOnly").orElse(false); } public void setArgsOnly(boolean argsOnly) { this.set("argsOnly", argsOnly); } public AdjustableLocalNode withArgsOnly(UnaryOperator argsOnly) { ... } public Class getType() { return this.>get("type").orElse(void.class); } public void setType(Class type) { this.set("type", type); } public AdjustableLocalNode withType(UnaryOperator> type) { ... } ``` -------------------------------- ### InjectionPoint enum constants with custom() and toNode() Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/types.md Defines the injection point constants used by `@At`. `HEAD`/`TAIL` target method bounds, `INVOKE`/`INVOKE_ASSIGN`/`INVOKE_STRING` handle invocations, `FIELD` field access, `NEW` object instantiation, `CONSTANT` constant reads, `JUMP` branches, and `CUSTOM` custom points. `custom(String)` records the custom name; `toNode()` throws `IllegalStateException` if the custom name was never set. For example, `InjectionPoint.custom("MIXINEXTRAS:EXPRESSION").toNode()` produces an `AdjustableAtNode` for `@At("MIXINEXTRAS:EXPRESSION")`. ```java public enum InjectionPoint { HEAD, TAIL, INVOKE, INVOKE_ASSIGN, INVOKE_STRING, FIELD, NEW, CONSTANT, JUMP, CUSTOM; private String customName; public static InjectionPoint custom(String name) { ... } public AdjustableAtNode toNode() { ... } } ``` -------------------------------- ### Static convenience methods for MixinAnnotationReader Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinAnnotationReader.md Static convenience method signatures. Each constructs a new MixinAnnotationReader and forwards to the matching instance method. The String overloads inherit the RuntimeException failure mode wrapping ClassNotFoundException or IOException. ```java public static List getValue(String mixinClassName) public static List getTargets(String mixinClassName) public static int getPriority(String mixinClassName) public static boolean getRemap(String mixinClassName) public static List getValue(ClassNode mixinClassNode) public static List getTargets(ClassNode mixinClassNode) public static int getPriority(ClassNode mixinClassNode) public static boolean getRemap(ClassNode mixinClassNode) ``` -------------------------------- ### ServiceLoader implementation loading for Forge/NeoForge Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/configuration.md Loads the consumer implementations once as static fields using ServiceLoader. Requires providers to be registered via META-INF/services in the consuming jar. ```java private static final ServiceLoader CANCELLERS = ServiceLoader.load(MixinCanceller.class); private static final ServiceLoader ANNOTATION_ADJUSTERS = ServiceLoader.load(MixinAnnotationAdjuster.class); ``` -------------------------------- ### Register bundled extensions with ExtensionRegistrar Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/ExtensionRegistrar.md Use this pattern to register the two bundled extensions into the active Mixin transformer's extension registry. It is identical to the kernel usage in MixinSquaredBootstrap.init() and requires Mixin's environment to be initialized. ```java import com.bawnorton.mixinsquared.adjuster.ExtensionAnnotationAdjust; import com.bawnorton.mixinsquared.canceller.ExtensionCancelApplication; import com.bawnorton.mixinsquared.ext.ExtensionRegistrar; ExtensionRegistrar.register(new ExtensionCancelApplication()); ExtensionRegistrar.register(new ExtensionAnnotationAdjust()); ``` -------------------------------- ### MixinSquaredMod - Forge mod entry point Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/platform.md Empty class marking the mod id `mixingsquared` with `@Mod("mixinsquared")`. The `mods.toml` sets `modId = "mixinsquared"`, `FMLModType: GAMELIBRARY`, and `MixinConfigs: mixinsquared.forge.init.mixins.json`. ```java @Mod("mixinsquared") public class MixinSquaredMod { } ``` -------------------------------- ### MixinSquaredBootstrap fields: NAME and VERSION Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredBootstrap.md Public static final fields defining the MixinSquared name and version. ```java public static final String NAME = "mixinsquared"; public static final String VERSION = "0.3.7"; ``` -------------------------------- ### TargetClassContextExtension class definition Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/reflection.md Shows the public API of the TargetClassContextExtension class, including the constructor, tryAs static method, and getMixins method. The constructor and tryAs method are shown with ellipses for brevity in the source. ```java public final class TargetClassContextExtension { private final ITargetClassContext reference; private final FieldReference> mixinsField; public TargetClassContextExtension(ITargetClassContext reference) { ... } public static void tryAs(ITargetClassContext reference, Consumer consumer) { ... } @SuppressWarnings("unchecked") public SortedSet getMixins() { ... } } ``` -------------------------------- ### AdjustableRedirectNode constructor and defaultNode factory Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableRedirectFamily.md Constructs an AdjustableRedirectNode from an existing AnnotationNode and provides a factory method to create a default node with a specified @At annotation. The defaultNode method is not static; call it on an instance, e.g., new AdjustableRedirectNode(rawNode).defaultNode(at). ```java public AdjustableRedirectNode(AnnotationNode node) { super(node); } public AdjustableRedirectNode defaultNode(AdjustableAtNode atNode) { AnnotationNode node = new AnnotationNode(KnownAnnotations.REDIRECT.desc()); AdjustableRedirectNode defaultNode = new AdjustableRedirectNode(node); defaultNode.setAt(atNode); return defaultNode; } ``` -------------------------------- ### Register MixinCanceller via service file Source: https://github.com/bawnorton/mixinsquared/wiki/Mixin-Canceller Content of the service file in META-INF/services/ named com.bawnorton.mixinsquared.api.MixinCanceller. It must contain the fully qualified name of your MixinCanceller implementation. ```text com.example.mod.YourModMixinCanceller ``` -------------------------------- ### Overridden methods: getSupportedSourceVersion() and process() Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/MixinSquaredAnnotationProcessor.md getSupportedSourceVersion() returns SourceVersion.latestSupported(). process() always returns true and performs no per-round work. ```java @Override public SourceVersion getSupportedSourceVersion() { return SourceVersion.latestSupported(); } @Override public boolean process(Set annotations, RoundEnvironment roundEnv) { return true; } ``` -------------------------------- ### AnnotationEqualityVisitor constructor and isEqual method Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/util.md Constructor takes the expected AnnotationNode and initializes the ASM API version. The isEqual() method returns the accumulated equality result. ```java public AnnotationEqualityVisitor(AnnotationNode other) { super(ASM_API); this.other = other; } public boolean isEqual() { return isEqual; } ``` -------------------------------- ### AdjustableNextNode getters, setters, and with-methods Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableDescSliceConstant.md Provides getters, setters, and fluent with-methods for the Next annotation attributes: name, ret, args, min, and max. Defaults are empty string, Type.VOID_TYPE, empty List, 0, and Integer.MAX_VALUE respectively. The defaultNode() factory returns an empty Next node. ```java public AdjustableNextNode(AnnotationNode node) { super(node); } public static AdjustableNextNode defaultNode() { ... } // empty Next node public String getName() { return this.get("name").orElse(""); } public void setName(String name) { this.set("name", name); } public AdjustableNextNode withName(UnaryOperator name) { ... } public Type getRet() { return this.get("ret").orElse(Type.VOID_TYPE); } public void setRet(Type ret) { this.set("ret", ret); } public AdjustableNextNode withRet(UnaryOperator ret) { ... } public List getArgs() { return this.>get("args").orElse(new ArrayList<>()); } public void setArgs(List args) { this.set("args", args); } public AdjustableNextNode withArgs(UnaryOperator> args) { ... } public int getMin() { return this.get("min").orElse(0); } public void setMin(int min) { this.set("min", min); } public AdjustableNextNode withMin(UnaryOperator min) { ... } public int getMax() { return this.get("max").orElse(Integer.MAX_VALUE); } public void setMax(int max) { this.set("max", max); } public AdjustableNextNode withMax(UnaryOperator max) { ... } ``` -------------------------------- ### Register MixinAnnotationAdjuster via META-INF/services Source: https://github.com/bawnorton/mixinsquared/wiki/Mixin-Annotation-Adjuster Place this content in a file named com.bawnorton.mixinsquared.api.MixinAnnotationAdjuster inside the META-INF/services/ directory. It references your MixinAnnotationAdjuster implementation(s). ```text com.example.mod.YourModMixinAnnotationAdjuster ``` -------------------------------- ### Static factory fromList(...) Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableAnnotationNode.md Converts a list of raw AnnotationNode objects into a list of AdjustableAnnotationNode instances using the provided factory. The returned list preserves the size and order of the input. ```java public static List fromList(List nodes, AdjustableAnnotationNodeFactory factory) { List list = new ArrayList<>(nodes.size()); for (AnnotationNode node : nodes) { list.add(factory.create(node)); } return list; } ``` -------------------------------- ### AdjustableSliceNode class methods Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableDescSliceConstant.md Shows the core methods of AdjustableSliceNode: constructors, defaultNode(), withId(), and getters/setters for the 'from' and 'to' attributes. The getters default to @At("HEAD") and @At("TAIL") when the attribute is absent. The withFrom and withTo methods are shown as ellipses in the source. ```java public AdjustableSliceNode(AnnotationNode node) { super(node); } public static AdjustableSliceNode defaultNode() { AnnotationNode node = new AnnotationNode(KnownAnnotations.SLICE.desc()); return new AdjustableSliceNode(node); } @Override public AdjustableSliceNode withId(UnaryOperator id) { return (AdjustableSliceNode) OptionalIdAnnotationNode.super.withId(id); } public AdjustableAtNode getFrom() { return this.get("from") .map(AdjustableAtNode::new) .orElse(AdjustableAtNode.InjectionPoint.HEAD.toNode()); } public void setFrom(AdjustableAtNode from) { this.set("from", from); } public AdjustableSliceNode withFrom(UnaryOperator from) { ... } public AdjustableAtNode getTo() { return this.get("to") .map(AdjustableAtNode::new) .orElse(AdjustableAtNode.InjectionPoint.TAIL.toNode()); } public void setTo(AdjustableAtNode to) { this.set("to", to); } public AdjustableSliceNode withTo(UnaryOperator to) { ... } ``` -------------------------------- ### fromList(List, AdjustableAnnotationNodeFactory) Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableAnnotationNode.md Static factory method that converts a list of raw AnnotationNode objects into a list of AdjustableAnnotationNode instances using the provided factory. ```APIDOC ## [STATIC] fromList ### Description Converts a list of raw annotation nodes into a list of adjustable annotation nodes using the provided factory. ### Method Static factory method ### Signature ```java public static List fromList(List nodes, AdjustableableAnnotationNodeFactory factory) ``` ### Parameters - **nodes** (List) - Required - Raw annotation nodes to convert. - **factory** (AdjustableAnnotationNodeFactory) - Required - Factory that creates an AdjustableAnnotationNode from each raw node. ### Returns - **List** - A list of adjusted nodes, one per input node, preserving order and size. ### Example ```java List rawNodes = ...; AdjustableAnnotationNodeFactory factory = ...; List adjusted = AdjustableAnnotationNode.fromList(rawNodes, factory); ``` ``` -------------------------------- ### Register a MixinCanceller provider for Forge/NeoForge Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/platform.md Registers a custom MixinCanceller implementation for Forge/NeoForge by placing the fully qualified class name in the service file. The file must be located at META-INF/services/com.bawnorton.mixinsquared.api.MixinCanceller. ```java // META-INF/services/com.bawnorton.mixinsquared.api.MixinCanceller com.example.MyCanceller ``` -------------------------------- ### Build constant with log flag Source: https://github.com/bawnorton/mixinsquared/blob/master/_autodocs/api-reference/AdjustableDescSliceConstant.md Builds an AdjustableConstantNode with string value, log flag, and ordinal. No throws are applicable. ```java import com.bawnorton.mixinsquared.adjuster.tools.AdjustableConstantNode; AdjustableConstantNode c = AdjustableConstantNode.defaultNode() .withStringValue(s -> "hello") .withLog(l -> true) .withOrdinal(o -> 3); ```