using System; using Mono.Cecil; using Mono.Cecil.Cil; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites method references from one parent type to another if the signatures match. internal class MethodParentRewriter : IInstructionHandler { /********* ** 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 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. public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false) { this.FromType = fromType; this.ToType = toType; this.NounPhrase = $"{fromType.Name} methods"; this.OnlyIfPlatformChanged = onlyIfPlatformChanged; } /// Perform the predefined logic for a method if applicable. /// The assembly module containing the instruction. /// The method definition containing the instruction. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. public InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged) { return InstructionHandleResult.None; } /// Perform the predefined logic for an instruction if applicable. /// The assembly module containing the instruction. /// The CIL processor. /// The instruction to handle. /// Metadata for mapping assemblies to the current platform. /// Whether the mod was compiled on a different platform. public InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { if (!this.IsMatch(instruction, platformChanged)) return InstructionHandleResult.None; MethodReference methodRef = (MethodReference)instruction.Operand; methodRef.DeclaringType = module.ImportReference(this.ToType); return InstructionHandleResult.Rewritten; } /********* ** Protected methods *********/ /// Get whether a CIL instruction matches. /// The IL instruction. /// Whether the mod was compiled on a different platform. protected bool IsMatch(Instruction instruction, bool platformChanged) { MethodReference methodRef = RewriteHelper.AsMethodReference(instruction); return methodRef != null && (platformChanged || !this.OnlyIfPlatformChanged) && methodRef.DeclaringType.FullName == this.FromType.FullName && RewriteHelper.HasMatchingSignature(this.ToType, methodRef); } } }