summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/ModLoading/Rewriters/StaticFieldToConstantRewriter.cs
blob: f34d4943e8d4a71dd31c0c18d914737d9af057d0 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
using System;
using Mono.Cecil;
using Mono.Cecil.Cil;
using StardewModdingAPI.Framework.ModLoading.Framework;

namespace StardewModdingAPI.Framework.ModLoading.Rewriters
{
    /// <summary>Rewrites static field references into constant values.</summary>
    /// <typeparam name="TValue">The constant value type.</typeparam>
    internal class StaticFieldToConstantRewriter<TValue> : BaseInstructionHandler
    {
        /*********
        ** Fields
        *********/
        /// <summary>The type containing the field to which references should be rewritten.</summary>
        private readonly Type Type;

        /// <summary>The field name to which references should be rewritten.</summary>
        private readonly string FromFieldName;

        /// <summary>The constant value to replace with.</summary>
        private readonly TValue Value;


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="type">The type whose field to which references should be rewritten.</param>
        /// <param name="fieldName">The field name to rewrite.</param>
        /// <param name="value">The constant value to replace with.</param>
        public StaticFieldToConstantRewriter(Type type, string fieldName, TValue value)
            : base(defaultPhrase: $"{type.FullName}.{fieldName} field")
        {
            this.Type = type;
            this.FromFieldName = fieldName;
            this.Value = value;
        }

        /// <inheritdoc />
        public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction)
        {
            // get field reference
            FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction);
            if (!RewriteHelper.IsFieldReferenceTo(fieldRef, this.Type.FullName, this.FromFieldName))
                return false;

            // rewrite to constant
            if (typeof(TValue) == typeof(int))
            {
                instruction.OpCode = OpCodes.Ldc_I4;
                instruction.Operand = this.Value;
            }
            else if (typeof(TValue) == typeof(string))
            {
                instruction.OpCode = OpCodes.Ldstr;
                instruction.Operand = this.Value;
            }
            else
                throw new NotSupportedException($"Rewriting to constant values of type {typeof(TValue)} isn't currently supported.");

            return this.MarkRewritten();
        }
    }
}