From b8f17e6afb00b78ac31df98f7dc3bbe071a99e47 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sun, 11 Mar 2018 19:10:08 -0400 Subject: update rewriters for Stardew Valley 1.3 (#453) --- .../Rewriters/StaticFieldToConstantRewriter.cs | 63 ++++++++++++++++++++++ 1 file changed, 63 insertions(+) create mode 100644 src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs (limited to 'src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs') diff --git a/src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs b/src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs new file mode 100644 index 00000000..5e12b46a --- /dev/null +++ b/src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs @@ -0,0 +1,63 @@ +using System; +using Mono.Cecil; +using Mono.Cecil.Cil; +using StardewModdingAPI.Framework.ModLoading.Finders; + +namespace StardewModdingAPI.Framework.ModLoading.Rewriters +{ + /// Rewrites static field references into constant values. + /// The constant value type. + internal class StaticFieldToConstantRewriter : FieldFinder + { + /********* + ** Properties + *********/ + /// The constant value to replace with. + private readonly TValue Value; + + + /********* + ** Public methods + *********/ + /// Construct an instance. + /// The type whose field to which references should be rewritten. + /// The field name to rewrite. + /// The constant value to replace with. + public StaticFieldToConstantRewriter(Type type, string fieldName, TValue value) + : base(type.FullName, fieldName, InstructionHandleResult.None) + { + this.Value = value; + } + + /// 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; + + cil.Replace(instruction, this.CreateConstantInstruction(cil, this.Value)); + return InstructionHandleResult.Rewritten; + } + + + /********* + ** Private methods + *********/ + /// Create a CIL constant value instruction. + /// The CIL processor. + /// The constant value to set. + private Instruction CreateConstantInstruction(ILProcessor cil, object value) + { + if (typeof(TValue) == typeof(int)) + return cil.Create(OpCodes.Ldc_I4, (int)value); + if (typeof(TValue) == typeof(string)) + return cil.Create(OpCodes.Ldstr, (string)value); + throw new NotSupportedException($"Rewriting to constant values of type {typeof(TValue)} isn't currently supported."); + } + } +} -- cgit