using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using HarmonyLib;
namespace StardewModdingAPI.Framework.RewriteFacades
{
/// Maps Harmony 1.x methods to Harmony 2.x to avoid breaking older mods.
/// This is public to support SMAPI rewriting and should not be referenced directly by mods.
public class HarmonyInstanceMethods : Harmony
{
/*********
** Public methods
*********/
/// Construct an instance.
/// The unique patch identifier.
public HarmonyInstanceMethods(string id)
: base(id) { }
/// Creates a new Harmony instance.
/// A unique identifier for the instance.
public static Harmony Create(string id)
{
return new Harmony(id);
}
/// Apply one or more patches to a method.
/// The original method.
/// The prefix to apply.
/// The postfix to apply.
/// The transpiler to apply.
public DynamicMethod Patch(MethodBase original, HarmonyMethod prefix = null, HarmonyMethod postfix = null, HarmonyMethod transpiler = null)
{
try
{
MethodInfo method = base.Patch(original: original, prefix: prefix, postfix: postfix, transpiler: transpiler);
return new DynamicMethod(method.Name, method.Attributes, method.CallingConvention, method.ReturnType, method.GetParameters().Select(p => p.ParameterType).ToArray(), method.Module, true);
}
catch (Exception ex)
{
var patchTypes = new List();
if (prefix != null)
patchTypes.Add("prefix");
if (postfix != null)
patchTypes.Add("postfix");
if (transpiler != null)
patchTypes.Add("transpiler");
throw new Exception($"Failed applying {string.Join("/", patchTypes)} to method {original.DeclaringType?.FullName}.{original.Name}", ex);
}
}
}
}