using Mono.Cecil;
using Mono.Cecil.Cil;
namespace StardewModdingAPI.AssemblyRewriters.Finders
{
/// Finds incompatible CIL instructions that reference a given event and throws an .
public class EventFinder : IInstructionRewriter
{
/*********
** Properties
*********/
/// The full type name for which to find references.
private readonly string FullTypeName;
/// The event name for which to find references.
private readonly string EventName;
/*********
** Accessors
*********/
/// A brief noun phrase indicating what the instruction finder matches.
public string NounPhrase { get; }
/*********
** Public methods
*********/
/// Construct an instance.
/// The full type name for which to find references.
/// The event name for which to find references.
/// A brief noun phrase indicating what the instruction finder matches (or null to generate one).
public EventFinder(string fullTypeName, string eventName, string nounPhrase = null)
{
this.FullTypeName = fullTypeName;
this.EventName = eventName;
this.NounPhrase = nounPhrase ?? $"{fullTypeName}.{eventName} event";
}
/// Rewrite a method definition for compatibility.
/// The module being rewritten.
/// The method definition to rewrite.
/// Metadata for mapping assemblies to the current platform.
/// Whether the mod was compiled on a different platform.
/// Returns whether the instruction was rewritten.
/// The CIL instruction is not compatible, and can't be rewritten.
public virtual bool Rewrite(ModuleDefinition module, MethodDefinition method, PlatformAssemblyMap assemblyMap, bool platformChanged)
{
return false;
}
/// Rewrite a CIL instruction for compatibility.
/// The module being rewritten.
/// The CIL rewriter.
/// The instruction to rewrite.
/// Metadata for mapping assemblies to the current platform.
/// Whether the mod was compiled on a different platform.
/// Returns whether the instruction was rewritten.
/// The CIL instruction is not compatible, and can't be rewritten.
public virtual bool Rewrite(ModuleDefinition module, ILProcessor cil, Instruction instruction, PlatformAssemblyMap assemblyMap, bool platformChanged)
{
if (!this.IsMatch(instruction))
return false;
throw new IncompatibleInstructionException(this.NounPhrase);
}
/*********
** Protected methods
*********/
/// Get whether a CIL instruction matches.
/// The IL instruction.
protected bool IsMatch(Instruction instruction)
{
MethodReference methodRef = RewriteHelper.AsMethodReference(instruction);
return
methodRef != null
&& methodRef.DeclaringType.FullName == this.FullTypeName
&& (methodRef.Name == "add_" + this.EventName || methodRef.Name == "remove_" + this.EventName);
}
}
}