summaryrefslogtreecommitdiff
path: root/src/SMAPI/Framework/ModLoading/Rewriters/HeuristicFieldRewriter.cs
blob: 2eee8ff9bea9dcf10bb0fb3cd0eb9973b942acd9 (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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
using System.Collections.Generic;
using System.Linq;
using Mono.Cecil;
using Mono.Cecil.Cil;
using StardewModdingAPI.Framework.ModLoading.Framework;

namespace StardewModdingAPI.Framework.ModLoading.Rewriters
{
    /// <summary>Automatically fix references to fields that have been replaced by a property or const field.</summary>
    internal class HeuristicFieldRewriter : BaseInstructionHandler
    {
        /*********
        ** Fields
        *********/
        /// <summary>The assembly names to which to rewrite broken references.</summary>
        private readonly ISet<string> RewriteReferencesToAssemblies;


        /*********
        ** Public methods
        *********/
        /// <summary>Construct an instance.</summary>
        /// <param name="rewriteReferencesToAssemblies">The assembly names to which to rewrite broken references.</param>
        public HeuristicFieldRewriter(ISet<string> rewriteReferencesToAssemblies)
            : base(defaultPhrase: "field changed to property") // ignored since we specify phrases
        {
            this.RewriteReferencesToAssemblies = rewriteReferencesToAssemblies;
        }

        /// <inheritdoc />
        public override bool Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction)
        {
            // get field ref
            FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction);
            if (fieldRef == null || !this.ShouldValidate(fieldRef.DeclaringType))
                return false;

            // skip if not broken
            FieldDefinition fieldDefinition = fieldRef.Resolve();
            if (fieldDefinition?.HasConstant == false)
                return false;

            // rewrite if possible
            TypeDefinition declaringType = fieldRef.DeclaringType.Resolve();
            bool isRead = instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Ldfld;
            return
                this.TryRewriteToProperty(module, instruction, fieldRef, declaringType, isRead)
                || this.TryRewriteToConstField(instruction, fieldDefinition);
        }


        /*********
        ** Private methods
        *********/
        /// <summary>Whether references to the given type should be validated.</summary>
        /// <param name="type">The type reference.</param>
        private bool ShouldValidate(TypeReference type)
        {
            return type != null && this.RewriteReferencesToAssemblies.Contains(type.Scope.Name);
        }

        /// <summary>Try rewriting the field into a matching property.</summary>
        /// <param name="module">The assembly module containing the instruction.</param>
        /// <param name="instruction">The CIL instruction to rewrite.</param>
        /// <param name="fieldRef">The field reference.</param>
        /// <param name="declaringType">The type on which the field was defined.</param>
        /// <param name="isRead">Whether the field is being read; else it's being written to.</param>
        private bool TryRewriteToProperty(ModuleDefinition module, Instruction instruction, FieldReference fieldRef, TypeDefinition declaringType, bool isRead)
        {
            // get equivalent property
            PropertyDefinition property = declaringType?.Properties.FirstOrDefault(p => p.Name == fieldRef.Name);
            MethodDefinition method = isRead ? property?.GetMethod : property?.SetMethod;
            if (method == null)
                return false;

            // rewrite field to property
            instruction.OpCode = OpCodes.Call;
            instruction.Operand = module.ImportReference(method);

            this.Phrases.Add($"{fieldRef.DeclaringType.Name}.{fieldRef.Name} (field => property)");
            return this.MarkRewritten();
        }

        /// <summary>Try rewriting the field into a matching const field.</summary>
        /// <param name="instruction">The CIL instruction to rewrite.</param>
        /// <param name="field">The field definition.</param>
        private bool TryRewriteToConstField(Instruction instruction, FieldDefinition field)
        {
            // must have been a static field read, and the new field must be const
            if (instruction.OpCode != OpCodes.Ldsfld || field?.HasConstant != true)
                return false;

            // get opcode for value type
            Instruction loadInstruction = RewriteHelper.GetLoadValueInstruction(field.Constant);
            if (loadInstruction == null)
                return false;

            // rewrite to constant
            instruction.OpCode = loadInstruction.OpCode;
            instruction.Operand = loadInstruction.Operand;

            this.Phrases.Add($"{field.DeclaringType.Name}.{field.Name} (field => const)");
            return this.MarkRewritten();
        }
    }
}