#nullable disable
using System;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using StardewModdingAPI.Framework.ModLoading.Framework;
namespace StardewModdingAPI.Framework.ModLoading.Rewriters
{
/// Rewrites method references from one parent type to another if the signatures match.
internal class MethodParentRewriter : BaseInstructionHandler
{
/*********
** Fields
*********/
/// The full name of the type whose methods to remap.
private readonly string FromType;
/// The type with methods to map to.
private readonly Type ToType;
/*********
** Public methods
*********/
/// Construct an instance.
/// The type whose methods to remap.
/// The type with methods to map to.
/// A brief noun phrase indicating what the instruction finder matches (or null to generate one).
public MethodParentRewriter(string fromType, Type toType, string nounPhrase = null)
: base(nounPhrase ?? $"{fromType.Split('.').Last()} methods")
{
this.FromType = fromType;
this.ToType = toType;
}
/// Construct an instance.
/// The type whose methods to remap.
/// The type with methods to map to.
/// A brief noun phrase indicating what the instruction finder matches (or null to generate one).
public MethodParentRewriter(Type fromType, Type toType, string nounPhrase = null)
: this(fromType.FullName, toType, nounPhrase) { }
///
public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction)
{
// get method ref
MethodReference methodRef = RewriteHelper.AsMethodReference(instruction);
if (!this.IsMatch(methodRef))
return false;
// rewrite
methodRef.DeclaringType = module.ImportReference(this.ToType);
return this.MarkRewritten();
}
/*********
** Private methods
*********/
/// Get whether a CIL instruction matches.
/// The method reference.
private bool IsMatch(MethodReference methodRef)
{
return
methodRef != null
&& methodRef.DeclaringType.FullName == this.FromType
&& RewriteHelper.HasMatchingSignature(this.ToType, methodRef);
}
}
}