using System;
using Mono.Cecil;
using Mono.Cecil.Cil;
using StardewModdingAPI.AssemblyRewriters.Framework;
namespace StardewModdingAPI.AssemblyRewriters.Rewriters
{
/// Rewrites field references into property references.
public class FieldToPropertyRewriter : BaseFieldRewriter
{
/*********
** Properties
*********/
/// The type whose field to which references should be rewritten.
private readonly Type Type;
/// The field name to rewrite.
private readonly string FieldName;
/*********
** Accessors
*********/
/// A brief noun phrase indicating what the instruction finder matches.
public override string NounPhrase { get; }
/*********
** Public methods
*********/
/// Construct an instance.
/// The type whose field to which references should be rewritten.
/// The field name to rewrite.
/// A brief noun phrase indicating what the instruction finder matches (or null to generate one).
public FieldToPropertyRewriter(Type type, string fieldName, string nounPhrase = null)
{
this.Type = type;
this.FieldName = fieldName;
this.NounPhrase = nounPhrase ?? $"{type.Name}.{fieldName} field";
}
/*********
** Protected methods
*********/
/// Get whether a field reference should be rewritten.
/// The IL instruction.
/// The field reference.
/// Whether the mod was compiled on a different platform.
protected override bool IsMatch(Instruction instruction, FieldReference fieldRef, bool platformChanged)
{
return
fieldRef.DeclaringType.FullName == this.Type.FullName
&& fieldRef.Name == this.FieldName;
}
/// Rewrite a method for compatibility.
/// The module being rewritten.
/// The CIL rewriter.
/// The instruction which references the field.
/// The field reference invoked by the .
/// Metadata for mapping assemblies to the current platform.
protected override void Rewrite(ModuleDefinition module, ILProcessor cil, Instruction instruction, FieldReference fieldRef, PlatformAssemblyMap assemblyMap)
{
string methodPrefix = instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Ldfld ? "get" : "set";
MethodReference propertyRef = module.Import(this.Type.GetMethod($"{methodPrefix}_{this.FieldName}"));
cil.Replace(instruction, cil.Create(OpCodes.Call, propertyRef));
}
}
}