From 2b336faa1bcdf7c2abc1cffb72c1def70fa6e8a7 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Thu, 9 Feb 2017 23:03:36 -0500 Subject: add field rewriter for the `Game1.player` change in SDV 1.2 (#231) --- .../Rewriters/SDV1_2/Game1_Player_FieldRewriter.cs | 42 ++++++++++++++++++++++ 1 file changed, 42 insertions(+) create mode 100644 src/StardewModdingAPI.AssemblyRewriters/Rewriters/SDV1_2/Game1_Player_FieldRewriter.cs (limited to 'src/StardewModdingAPI.AssemblyRewriters/Rewriters/SDV1_2/Game1_Player_FieldRewriter.cs') diff --git a/src/StardewModdingAPI.AssemblyRewriters/Rewriters/SDV1_2/Game1_Player_FieldRewriter.cs b/src/StardewModdingAPI.AssemblyRewriters/Rewriters/SDV1_2/Game1_Player_FieldRewriter.cs new file mode 100644 index 00000000..fb87c19a --- /dev/null +++ b/src/StardewModdingAPI.AssemblyRewriters/Rewriters/SDV1_2/Game1_Player_FieldRewriter.cs @@ -0,0 +1,42 @@ +using System.Diagnostics.CodeAnalysis; +using Mono.Cecil; +using Mono.Cecil.Cil; +using StardewModdingAPI.AssemblyRewriters.Framework; +using StardewValley; + +namespace StardewModdingAPI.AssemblyRewriters.Rewriters.SDV1_2 +{ + /// Rewrites field references to . + /// Stardew Valley changed the field to a property, which broke many mods that reference it. + [SuppressMessage("ReSharper", "InconsistentNaming", Justification = "This class is not meant to be used directly, and is deliberately named to make it easier to know what it changes at a glance.")] + public class Game1_Player_FieldRewriter : BaseFieldRewriter + { + /********* + ** 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 ShouldRewrite(Instruction instruction, FieldReference fieldRef, bool platformChanged) + { + return + (instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Stsfld) // static field + && fieldRef.DeclaringType.FullName == typeof(Game1).FullName + && fieldRef.Name == nameof(Game1.player); + } + + /// 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 ? "get" : "set"; + MethodReference propertyRef = module.Import(typeof(Game1).GetMethod($"{methodPrefix}_{nameof(Game1.player)}")); + cil.Replace(instruction, cil.Create(OpCodes.Call, propertyRef)); + } + } +} -- cgit