using System; using System.Reflection; using Mono.Cecil; using Mono.Cecil.Cil; using StardewModdingAPI.Framework.ModLoading.Finders; namespace StardewModdingAPI.Framework.ModLoading.Rewriters { /// Rewrites references to one field with another. internal class FieldReplaceRewriter : FieldFinder { /********* ** Fields *********/ /// The new field to reference. private readonly FieldInfo ToField; /********* ** Public methods *********/ /// Construct an instance. /// The type whose field to which references should be rewritten. /// The field name to rewrite. /// The new field name to reference. public FieldReplaceRewriter(Type type, string fromFieldName, string toFieldName) : base(type.FullName, fromFieldName, InstructionHandleResult.None) { this.ToField = type.GetField(toFieldName); if (this.ToField == null) throw new InvalidOperationException($"The {type.FullName} class doesn't have a {toFieldName} field."); } /// 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; FieldReference newRef = module.ImportReference(this.ToField); cil.Replace(instruction, cil.Create(instruction.OpCode, newRef)); return InstructionHandleResult.Rewritten; } } }