summaryrefslogtreecommitdiff
path: root/src/StardewModdingAPI/Framework/ModLoading/Rewriters
diff options
context:
space:
mode:
Diffstat (limited to 'src/StardewModdingAPI/Framework/ModLoading/Rewriters')
-rw-r--r--src/StardewModdingAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs50
-rw-r--r--src/StardewModdingAPI/Framework/ModLoading/Rewriters/FieldToPropertyRewriter.cs51
-rw-r--r--src/StardewModdingAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs88
-rw-r--r--src/StardewModdingAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs154
-rw-r--r--src/StardewModdingAPI/Framework/ModLoading/Rewriters/Wrappers/SpriteBatchWrapper.cs59
5 files changed, 402 insertions, 0 deletions
diff --git a/src/StardewModdingAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs
new file mode 100644
index 00000000..63358b39
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/FieldReplaceRewriter.cs
@@ -0,0 +1,50 @@
+using System;
+using System.Reflection;
+using Mono.Cecil;
+using Mono.Cecil.Cil;
+using StardewModdingAPI.Framework.ModLoading.Finders;
+
+namespace StardewModdingAPI.Framework.ModLoading.Rewriters
+{
+ /// <summary>Rewrites references to one field with another.</summary>
+ internal class FieldReplaceRewriter : FieldFinder
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The new field to reference.</summary>
+ private readonly FieldInfo ToField;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="type">The type whose field to which references should be rewritten.</param>
+ /// <param name="fromFieldName">The field name to rewrite.</param>
+ /// <param name="toFieldName">The new field name to reference.</param>
+ public FieldReplaceRewriter(Type type, string fromFieldName, string toFieldName)
+ : base(type.FullName, fromFieldName, InstructionHandleResult.None)
+ {
+ this.ToField = type.GetField(toFieldName);
+ if (this.ToField == null)
+ throw new InvalidOperationException($"The {type.FullName} class doesn't have a {toFieldName} field.");
+ }
+
+ /// <summary>Perform the predefined logic for an instruction if applicable.</summary>
+ /// <param name="module">The assembly module containing the instruction.</param>
+ /// <param name="cil">The CIL processor.</param>
+ /// <param name="instruction">The instruction to handle.</param>
+ /// <param name="assemblyMap">Metadata for mapping assemblies to the current platform.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged)
+ {
+ if (!this.IsMatch(instruction))
+ return InstructionHandleResult.None;
+
+ FieldReference newRef = module.Import(this.ToField);
+ cil.Replace(instruction, cil.Create(instruction.OpCode, newRef));
+ return InstructionHandleResult.Rewritten;
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/ModLoading/Rewriters/FieldToPropertyRewriter.cs b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/FieldToPropertyRewriter.cs
new file mode 100644
index 00000000..a20b8bee
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/FieldToPropertyRewriter.cs
@@ -0,0 +1,51 @@
+using System;
+using Mono.Cecil;
+using Mono.Cecil.Cil;
+using StardewModdingAPI.Framework.ModLoading.Finders;
+
+namespace StardewModdingAPI.Framework.ModLoading.Rewriters
+{
+ /// <summary>Rewrites field references into property references.</summary>
+ internal class FieldToPropertyRewriter : FieldFinder
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The type whose field to which references should be rewritten.</summary>
+ private readonly Type Type;
+
+ /// <summary>The field name to rewrite.</summary>
+ private readonly string FieldName;
+
+
+ /*********
+ ** 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>
+ public FieldToPropertyRewriter(Type type, string fieldName)
+ : base(type.FullName, fieldName, InstructionHandleResult.None)
+ {
+ this.Type = type;
+ this.FieldName = fieldName;
+ }
+
+ /// <summary>Perform the predefined logic for an instruction if applicable.</summary>
+ /// <param name="module">The assembly module containing the instruction.</param>
+ /// <param name="cil">The CIL processor.</param>
+ /// <param name="instruction">The instruction to handle.</param>
+ /// <param name="assemblyMap">Metadata for mapping assemblies to the current platform.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged)
+ {
+ if (!this.IsMatch(instruction))
+ return InstructionHandleResult.None;
+
+ string methodPrefix = instruction.OpCode == OpCodes.Ldsfld || instruction.OpCode == OpCodes.Ldfld ? "get" : "set";
+ MethodReference propertyRef = module.Import(this.Type.GetMethod($"{methodPrefix}_{this.FieldName}"));
+ cil.Replace(instruction, cil.Create(OpCodes.Call, propertyRef));
+ return InstructionHandleResult.Rewritten;
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs
new file mode 100644
index 00000000..974fcf4c
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/MethodParentRewriter.cs
@@ -0,0 +1,88 @@
+using System;
+using Mono.Cecil;
+using Mono.Cecil.Cil;
+
+namespace StardewModdingAPI.Framework.ModLoading.Rewriters
+{
+ /// <summary>Rewrites method references from one parent type to another if the signatures match.</summary>
+ internal class MethodParentRewriter : IInstructionHandler
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The type whose methods to remap.</summary>
+ private readonly Type FromType;
+
+ /// <summary>The type with methods to map to.</summary>
+ private readonly Type ToType;
+
+ /// <summary>Whether to only rewrite references if loading the assembly on a different platform than it was compiled on.</summary>
+ private readonly bool OnlyIfPlatformChanged;
+
+
+ /*********
+ ** Accessors
+ *********/
+ /// <summary>A brief noun phrase indicating what the instruction finder matches.</summary>
+ public string NounPhrase { get; }
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="fromType">The type whose methods to remap.</param>
+ /// <param name="toType">The type with methods to map to.</param>
+ /// <param name="onlyIfPlatformChanged">Whether to only rewrite references if loading the assembly on a different platform than it was compiled on.</param>
+ public MethodParentRewriter(Type fromType, Type toType, bool onlyIfPlatformChanged = false)
+ {
+ this.FromType = fromType;
+ this.ToType = toType;
+ this.NounPhrase = $"{fromType.Name} methods";
+ this.OnlyIfPlatformChanged = onlyIfPlatformChanged;
+ }
+
+ /// <summary>Perform the predefined logic for a method if applicable.</summary>
+ /// <param name="module">The assembly module containing the instruction.</param>
+ /// <param name="method">The method definition containing the instruction.</param>
+ /// <param name="assemblyMap">Metadata for mapping assemblies to the current platform.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ public InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged)
+ {
+ return InstructionHandleResult.None;
+ }
+
+ /// <summary>Perform the predefined logic for an instruction if applicable.</summary>
+ /// <param name="module">The assembly module containing the instruction.</param>
+ /// <param name="cil">The CIL processor.</param>
+ /// <param name="instruction">The instruction to handle.</param>
+ /// <param name="assemblyMap">Metadata for mapping assemblies to the current platform.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ public InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged)
+ {
+ if (!this.IsMatch(instruction, platformChanged))
+ return InstructionHandleResult.None;
+
+ MethodReference methodRef = (MethodReference)instruction.Operand;
+ methodRef.DeclaringType = module.Import(this.ToType);
+ return InstructionHandleResult.Rewritten;
+ }
+
+
+ /*********
+ ** Protected methods
+ *********/
+ /// <summary>Get whether a CIL instruction matches.</summary>
+ /// <param name="instruction">The IL instruction.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ protected bool IsMatch(Instruction instruction, bool platformChanged)
+ {
+ MethodReference methodRef = RewriteHelper.AsMethodReference(instruction);
+ return
+ methodRef != null
+ && (platformChanged || !this.OnlyIfPlatformChanged)
+ && methodRef.DeclaringType.FullName == this.FromType.FullName
+ && RewriteHelper.HasMatchingSignature(this.ToType, methodRef);
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs
new file mode 100644
index 00000000..74f2fcdd
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/TypeReferenceRewriter.cs
@@ -0,0 +1,154 @@
+using System;
+using Mono.Cecil;
+using Mono.Cecil.Cil;
+using StardewModdingAPI.Framework.ModLoading.Finders;
+
+namespace StardewModdingAPI.Framework.ModLoading.Rewriters
+{
+ /// <summary>Rewrites all references to a type.</summary>
+ internal class TypeReferenceRewriter : TypeFinder
+ {
+ /*********
+ ** Properties
+ *********/
+ /// <summary>The full type name to which to find references.</summary>
+ private readonly string FromTypeName;
+
+ /// <summary>The new type to reference.</summary>
+ private readonly Type ToType;
+
+
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ /// <param name="fromTypeFullName">The full type name to which to find references.</param>
+ /// <param name="toType">The new type to reference.</param>
+ public TypeReferenceRewriter(string fromTypeFullName, Type toType)
+ : base(fromTypeFullName, InstructionHandleResult.None)
+ {
+ this.FromTypeName = fromTypeFullName;
+ this.ToType = toType;
+ }
+
+ /// <summary>Perform the predefined logic for a method if applicable.</summary>
+ /// <param name="module">The assembly module containing the instruction.</param>
+ /// <param name="method">The method definition containing the instruction.</param>
+ /// <param name="assemblyMap">Metadata for mapping assemblies to the current platform.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ public override InstructionHandleResult Handle(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged)
+ {
+ bool rewritten = false;
+
+ // return type
+ if (this.IsMatch(method.ReturnType))
+ {
+ method.ReturnType = this.RewriteIfNeeded(module, method.ReturnType);
+ rewritten = true;
+ }
+
+ // parameters
+ foreach (ParameterDefinition parameter in method.Parameters)
+ {
+ if (this.IsMatch(parameter.ParameterType))
+ {
+ parameter.ParameterType = this.RewriteIfNeeded(module, parameter.ParameterType);
+ rewritten = true;
+ }
+ }
+
+ // generic parameters
+ for (int i = 0; i < method.GenericParameters.Count; i++)
+ {
+ var parameter = method.GenericParameters[i];
+ if (this.IsMatch(parameter))
+ {
+ TypeReference newType = this.RewriteIfNeeded(module, parameter);
+ if (newType != parameter)
+ method.GenericParameters[i] = new GenericParameter(parameter.Name, newType);
+ rewritten = true;
+ }
+ }
+
+ // local variables
+ foreach (VariableDefinition variable in method.Body.Variables)
+ {
+ if (this.IsMatch(variable.VariableType))
+ {
+ variable.VariableType = this.RewriteIfNeeded(module, variable.VariableType);
+ rewritten = true;
+ }
+ }
+
+ return rewritten
+ ? InstructionHandleResult.Rewritten
+ : InstructionHandleResult.None;
+ }
+
+ /// <summary>Perform the predefined logic for an instruction if applicable.</summary>
+ /// <param name="module">The assembly module containing the instruction.</param>
+ /// <param name="cil">The CIL processor.</param>
+ /// <param name="instruction">The instruction to handle.</param>
+ /// <param name="assemblyMap">Metadata for mapping assemblies to the current platform.</param>
+ /// <param name="platformChanged">Whether the mod was compiled on a different platform.</param>
+ public override InstructionHandleResult Handle(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged)
+ {
+ if (!this.IsMatch(instruction) && !instruction.ToString().Contains(this.FromTypeName))
+ return InstructionHandleResult.None;
+
+ // field reference
+ FieldReference fieldRef = RewriteHelper.AsFieldReference(instruction);
+ if (fieldRef != null)
+ {
+ fieldRef.DeclaringType = this.RewriteIfNeeded(module, fieldRef.DeclaringType);
+ fieldRef.FieldType = this.RewriteIfNeeded(module, fieldRef.FieldType);
+ }
+
+ // method reference
+ MethodReference methodRef = RewriteHelper.AsMethodReference(instruction);
+ if (methodRef != null)
+ {
+ methodRef.DeclaringType = this.RewriteIfNeeded(module, methodRef.DeclaringType);
+ methodRef.ReturnType = this.RewriteIfNeeded(module, methodRef.ReturnType);
+ foreach (var parameter in methodRef.Parameters)
+ parameter.ParameterType = this.RewriteIfNeeded(module, parameter.ParameterType);
+ }
+
+ // type reference
+ if (instruction.Operand is TypeReference typeRef)
+ {
+ TypeReference newRef = this.RewriteIfNeeded(module, typeRef);
+ if (typeRef != newRef)
+ cil.Replace(instruction, cil.Create(instruction.OpCode, newRef));
+ }
+
+ return InstructionHandleResult.Rewritten;
+ }
+
+ /*********
+ ** Private methods
+ *********/
+ /// <summary>Get the adjusted type reference if it matches, else the same value.</summary>
+ /// <param name="module">The assembly module containing the instruction.</param>
+ /// <param name="type">The type to replace if it matches.</param>
+ private TypeReference RewriteIfNeeded(ModuleDefinition module, TypeReference type)
+ {
+ // root type
+ if (type.FullName == this.FromTypeName)
+ return module.Import(this.ToType);
+
+ // generic arguments
+ if (type is GenericInstanceType genericType)
+ {
+ for (int i = 0; i < genericType.GenericArguments.Count; i++)
+ genericType.GenericArguments[i] = this.RewriteIfNeeded(module, genericType.GenericArguments[i]);
+ }
+
+ // generic parameters (e.g. constraints)
+ for (int i = 0; i < type.GenericParameters.Count; i++)
+ type.GenericParameters[i] = new GenericParameter(this.RewriteIfNeeded(module, type.GenericParameters[i]));
+
+ return type;
+ }
+ }
+}
diff --git a/src/StardewModdingAPI/Framework/ModLoading/Rewriters/Wrappers/SpriteBatchWrapper.cs b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/Wrappers/SpriteBatchWrapper.cs
new file mode 100644
index 00000000..7a631f69
--- /dev/null
+++ b/src/StardewModdingAPI/Framework/ModLoading/Rewriters/Wrappers/SpriteBatchWrapper.cs
@@ -0,0 +1,59 @@
+using System.Diagnostics.CodeAnalysis;
+using Microsoft.Xna.Framework;
+using Microsoft.Xna.Framework.Graphics;
+
+namespace StardewModdingAPI.Framework.ModLoading.Rewriters.Wrappers
+{
+ /// <summary>Wraps <see cref="SpriteBatch"/> methods that are incompatible when converting compiled code between MonoGame and XNA.</summary>
+ internal class SpriteBatchWrapper : SpriteBatch
+ {
+ /*********
+ ** Public methods
+ *********/
+ /// <summary>Construct an instance.</summary>
+ public SpriteBatchWrapper(GraphicsDevice graphicsDevice) : base(graphicsDevice) { }
+
+
+ /****
+ ** MonoGame signatures
+ ****/
+ [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Linux/Mac.")]
+ public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix? matrix)
+ {
+ base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, matrix ?? Matrix.Identity);
+ }
+
+ /****
+ ** XNA signatures
+ ****/
+ [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")]
+ public new void Begin()
+ {
+ base.Begin();
+ }
+
+ [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")]
+ public new void Begin(SpriteSortMode sortMode, BlendState blendState)
+ {
+ base.Begin(sortMode, blendState);
+ }
+
+ [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")]
+ public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState)
+ {
+ base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState);
+ }
+
+ [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")]
+ public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect)
+ {
+ base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect);
+ }
+
+ [SuppressMessage("ReSharper", "CS0109", Justification = "The 'new' modifier applies when compiled on Windows.")]
+ public new void Begin(SpriteSortMode sortMode, BlendState blendState, SamplerState samplerState, DepthStencilState depthStencilState, RasterizerState rasterizerState, Effect effect, Matrix transformMatrix)
+ {
+ base.Begin(sortMode, blendState, samplerState, depthStencilState, rasterizerState, effect, transformMatrix);
+ }
+ }
+}