blob: 00daf337d8efe1430f6e2d592529429915dd1dc6 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
|
#nullable disable
using System;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using StardewModdingAPI.Framework.ModLoading.Framework;
namespace StardewModdingAPI.Framework.ModLoading.Rewriters
{
/// <summary>Rewrites method references from one parent type to another if the signatures match.</summary>
internal class MethodParentRewriter : BaseInstructionHandler
{
/*********
** Fields
*********/
/// <summary>The full name of the type whose methods to remap.</summary>
private readonly string FromType;
/// <summary>The type with methods to map to.</summary>
private readonly Type ToType;
/*********
** Public methods
*********/
/// <summary>Construct an instance.</summary>
/// <param name="fromType">The type whose methods to remap.</param>
/// <param name="toType">The type with methods to map to.</param>
/// <param name="nounPhrase">A brief noun phrase indicating what the instruction finder matches (or <c>null</c> to generate one).</param>
public MethodParentRewriter(string fromType, Type toType, string nounPhrase = null)
: base(nounPhrase ?? $"{fromType.Split('.').Last()} methods")
{
this.FromType = fromType;
this.ToType = toType;
}
/// <summary>Construct an instance.</summary>
/// <param name="fromType">The type whose methods to remap.</param>
/// <param name="toType">The type with methods to map to.</param>
/// <param name="nounPhrase">A brief noun phrase indicating what the instruction finder matches (or <c>null</c> to generate one).</param>
public MethodParentRewriter(Type fromType, Type toType, string nounPhrase = null)
: this(fromType.FullName, toType, nounPhrase) { }
/// <inheritdoc />
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
*********/
/// <summary>Get whether a CIL instruction matches.</summary>
/// <param name="methodRef">The method reference.</param>
private bool IsMatch(MethodReference methodRef)
{
return
methodRef != null
&& methodRef.DeclaringType.FullName == this.FromType
&& RewriteHelper.HasMatchingSignature(this.ToType, methodRef);
}
}
}
|