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."); } } }