From 84330e86809dff4a3e70c3cbd59f0373f7017799 Mon Sep 17 00:00:00 2001 From: Jesse Plamondon-Willard Date: Sat, 17 Feb 2018 18:43:19 -0500 Subject: split proxy builder & factory (#435) --- .../Framework/Reflection/InterfaceProxyBuilder.cs | 92 +++++++++------------- .../Framework/Reflection/InterfaceProxyFactory.cs | 58 ++++++++++++++ 2 files changed, 94 insertions(+), 56 deletions(-) create mode 100644 src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs (limited to 'src/SMAPI/Framework/Reflection') diff --git a/src/SMAPI/Framework/Reflection/InterfaceProxyBuilder.cs b/src/SMAPI/Framework/Reflection/InterfaceProxyBuilder.cs index 5abebc18..7a2958fb 100644 --- a/src/SMAPI/Framework/Reflection/InterfaceProxyBuilder.cs +++ b/src/SMAPI/Framework/Reflection/InterfaceProxyBuilder.cs @@ -1,82 +1,47 @@ using System; -using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Reflection.Emit; namespace StardewModdingAPI.Framework.Reflection { - /// Generates proxy classes to access mod APIs through an arbitrary interface. + /// Generates a proxy class to access a mod API through an arbitrary interface. internal class InterfaceProxyBuilder { /********* ** Properties *********/ - /// The CLR module in which to create proxy classes. - private readonly ModuleBuilder ModuleBuilder; + /// The target class type. + private readonly Type TargetType; - /// The generated proxy types. - private readonly IDictionary GeneratedTypes = new Dictionary(); + /// The generated proxy type. + private readonly Type ProxyType; /********* ** Public methods *********/ /// Construct an instance. - public InterfaceProxyBuilder() - { - AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName($"StardewModdingAPI.Proxies, Version={this.GetType().Assembly.GetName().Version}, Culture=neutral"), AssemblyBuilderAccess.Run); - this.ModuleBuilder = assemblyBuilder.DefineDynamicModule("StardewModdingAPI.Proxies"); - } - - /// Create an API proxy. - /// The interface through which to access the API. - /// The API instance to access. - /// The unique ID of the mod consuming the API. - /// The unique ID of the mod providing the API. - public TInterface CreateProxy(object instance, string sourceModID, string targetModID) - where TInterface : class + /// The type name to generate. + /// The CLR module in which to create proxy classes. + /// The interface type to implement. + /// The target type. + public InterfaceProxyBuilder(string name, ModuleBuilder moduleBuilder, Type interfaceType, Type targetType) { // validate - if (instance == null) - throw new InvalidOperationException("Can't proxy access to a null API."); - if (!typeof(TInterface).IsInterface) - throw new InvalidOperationException("The proxy type must be an interface, not a class."); - - // get proxy type - Type targetType = instance.GetType(); - string proxyTypeName = $"StardewModdingAPI.Proxies.From<{sourceModID}_{typeof(TInterface).FullName}>_To<{targetModID}_{targetType.FullName}>"; - if (!this.GeneratedTypes.TryGetValue(proxyTypeName, out Type type)) - { - type = this.CreateProxyType(proxyTypeName, typeof(TInterface), targetType); - this.GeneratedTypes[proxyTypeName] = type; - } + if (name == null) + throw new ArgumentNullException(nameof(name)); + if (targetType == null) + throw new ArgumentNullException(nameof(targetType)); - // create instance - ConstructorInfo constructor = type.GetConstructor(new[] { targetType }); - if (constructor == null) - throw new InvalidOperationException($"Couldn't find the constructor for generated proxy type '{proxyTypeName}'."); // should never happen - return (TInterface)constructor.Invoke(new[] { instance }); - } - - - /********* - ** Private methods - *********/ - /// Define a class which proxies access to a target type through an interface. - /// The name of the proxy type to generate. - /// The interface type through which to access the target. - /// The target type to access. - private Type CreateProxyType(string proxyTypeName, Type interfaceType, Type targetType) - { // define proxy type - TypeBuilder proxyBuilder = this.ModuleBuilder.DefineType(proxyTypeName, TypeAttributes.Public | TypeAttributes.Class); + TypeBuilder proxyBuilder = moduleBuilder.DefineType(name, TypeAttributes.Public | TypeAttributes.Class); proxyBuilder.AddInterfaceImplementation(interfaceType); // create field to store target instance - FieldBuilder field = proxyBuilder.DefineField("__Target", targetType, FieldAttributes.Private); + FieldBuilder targetField = proxyBuilder.DefineField("__Target", targetType, FieldAttributes.Private); - // create constructor which accepts target instance + // create constructor which accepts target instance and sets field { ConstructorBuilder constructor = proxyBuilder.DefineConstructor(MethodAttributes.Public, CallingConventions.Standard | CallingConventions.HasThis, new[] { targetType }); ILGenerator il = constructor.GetILGenerator(); @@ -86,7 +51,7 @@ namespace StardewModdingAPI.Framework.Reflection il.Emit(OpCodes.Call, typeof(object).GetConstructor(new Type[0])); // call base constructor il.Emit(OpCodes.Ldarg_0); // this il.Emit(OpCodes.Ldarg_1); // load argument - il.Emit(OpCodes.Stfld, field); // set field to loaded argument + il.Emit(OpCodes.Stfld, targetField); // set field to loaded argument il.Emit(OpCodes.Ret); } @@ -97,13 +62,28 @@ namespace StardewModdingAPI.Framework.Reflection if (targetMethod == null) throw new InvalidOperationException($"The {interfaceType.FullName} interface defines method {proxyMethod.Name} which doesn't exist in the API."); - this.ProxyMethod(proxyBuilder, targetMethod, field); + this.ProxyMethod(proxyBuilder, targetMethod, targetField); } - // create type - return proxyBuilder.CreateType(); + // save info + this.TargetType = targetType; + this.ProxyType = proxyBuilder.CreateType(); + } + + /// Create an instance of the proxy for a target instance. + /// The target instance. + public object CreateInstance(object targetInstance) + { + ConstructorInfo constructor = this.ProxyType.GetConstructor(new[] { this.TargetType }); + if (constructor == null) + throw new InvalidOperationException($"Couldn't find the constructor for generated proxy type '{this.ProxyType.Name}'."); // should never happen + return constructor.Invoke(new[] { targetInstance }); } + + /********* + ** Private methods + *********/ /// Define a method which proxies access to a method on the target. /// The proxy type being generated. /// The target method. diff --git a/src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs b/src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs new file mode 100644 index 00000000..e14a9f08 --- /dev/null +++ b/src/SMAPI/Framework/Reflection/InterfaceProxyFactory.cs @@ -0,0 +1,58 @@ +using System; +using System.Collections.Generic; +using System.Reflection; +using System.Reflection.Emit; + +namespace StardewModdingAPI.Framework.Reflection +{ + /// Generates proxy classes to access mod APIs through an arbitrary interface. + internal class InterfaceProxyFactory + { + /********* + ** Properties + *********/ + /// The CLR module in which to create proxy classes. + private readonly ModuleBuilder ModuleBuilder; + + /// The generated proxy types. + private readonly IDictionary Builders = new Dictionary(); + + + /********* + ** Public methods + *********/ + /// Construct an instance. + public InterfaceProxyFactory() + { + AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(new AssemblyName($"StardewModdingAPI.Proxies, Version={this.GetType().Assembly.GetName().Version}, Culture=neutral"), AssemblyBuilderAccess.Run); + this.ModuleBuilder = assemblyBuilder.DefineDynamicModule("StardewModdingAPI.Proxies"); + } + + /// Create an API proxy. + /// The interface through which to access the API. + /// The API instance to access. + /// The unique ID of the mod consuming the API. + /// The unique ID of the mod providing the API. + public TInterface CreateProxy(object instance, string sourceModID, string targetModID) + where TInterface : class + { + // validate + if (instance == null) + throw new InvalidOperationException("Can't proxy access to a null API."); + if (!typeof(TInterface).IsInterface) + throw new InvalidOperationException("The proxy type must be an interface, not a class."); + + // get proxy type + Type targetType = instance.GetType(); + string proxyTypeName = $"StardewModdingAPI.Proxies.From<{sourceModID}_{typeof(TInterface).FullName}>_To<{targetModID}_{targetType.FullName}>"; + if (!this.Builders.TryGetValue(proxyTypeName, out InterfaceProxyBuilder builder)) + { + builder = new InterfaceProxyBuilder(proxyTypeName, this.ModuleBuilder, typeof(TInterface), targetType); + this.Builders[proxyTypeName] = builder; + } + + // create instance + return (TInterface)builder.CreateInstance(instance); + } + } +} -- cgit