using System; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Finders; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites field references into property references. internal class FieldToPropertyRewriter : FieldFinder { /********* ** Properties *********/ /// The type whose field to which references should be rewritten. private readonly Type Type; /// The field name to rewrite. private readonly string FieldName; /********* ** Public methods *********/ /// Construct an instance. /// The type whose field to which references should be rewritten. /// The field name to rewrite. public FieldToPropertyRewriter(Type type, string fieldName) : base(type.FullName, fieldName, InstructionHandleResult.None) { this.Type = type; this.FieldName = fieldName; } /// 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 override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged) { if (!this.IsMatch(instruction)) return InstructionHandleResult.None; 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)); return InstructionHandleResult.Rewritten; } } }