using System; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.AssemblyRewriters.Framework; namespace StardewModdingAPI.AssemblyRewriters.Rewriters { /// Rewrites method references from one parent type to another if the signatures match. public class MethodParentRewriter : BaseMethodRewriter { /********* ** Properties *********/ /// The type whose methods to remap. private readonly Type FromType; /// The type with methods to map to. private readonly Type ToType; /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. private readonly bool OnlyIfPlatformChanged; /********* ** Accessors *********/ /// A brief noun phrase indicating what the instruction finder matches. public override string NounPhrase { get; } /********* ** Public methods *********/ /// Construct an instance. /// The type whose methods to remap. /// The type with methods to map to. /// Whether to only rewrite references if loading the assembly on a different platform than it was compiled on. /// A brief noun phrase indicating what the instruction finder matches (or null to generate one). public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false, string nounPhrase = null) { this.FromType = fromType; this.ToType = toType; this.NounPhrase = nounPhrase ?? $"{fromType.Name} methods"; this.OnlyIfPlatformChanged = onlyIfPlatformChanged; } /********* ** Protected methods *********/ /// Get whether a method reference should be rewritten. /// The IL instruction. /// The method reference. /// Whether the mod was compiled on a different platform. protected override bool IsMatch(Instruction instruction, MethodReference methodRef, bool platformChanged) { return (!this.OnlyIfPlatformChanged || platformChanged) && methodRef.DeclaringType.FullName == this.FromType.FullName && this.HasMatchingSignature(this.ToType, methodRef); } /// Rewrite a method for compatibility. /// The module being rewritten. /// The CIL rewriter. /// The instruction which calls the method. /// The method reference invoked by the . /// Metadata for mapping assemblies to the current platform. protected override void Rewrite(ModuleDefinition module, ILProcessor cil, Instruction instruction, MethodReference methodRef, PlatformAssemblyMap assemblyMap) { methodRef.DeclaringType = module.Import(this.ToType); } } }