You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

212 lines
10 KiB

  1. using IPA.Logging;
  2. using IPA.Utilities;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Linq.Expressions;
  8. #if NET4
  9. using Task = System.Threading.Tasks.Task;
  10. using TaskEx = System.Threading.Tasks.Task;
  11. using Expression = System.Linq.Expressions.Expression;
  12. using ExpressionEx = System.Linq.Expressions.Expression;
  13. #endif
  14. #if NET3
  15. using System.Threading.Tasks;
  16. using Net3_Proxy;
  17. using Path = Net3_Proxy.Path;
  18. using File = Net3_Proxy.File;
  19. using Directory = Net3_Proxy.Directory;
  20. #endif
  21. namespace IPA.Loader
  22. {
  23. // NOTE: TaskEx.WhenAll() (Task.WhenAll() in .NET 4) returns CompletedTask if it has no arguments, which we need for .NET 3
  24. internal class PluginExecutor
  25. {
  26. public enum Special
  27. {
  28. None, Self, Bare
  29. }
  30. public PluginMetadata Metadata { get; }
  31. public Special SpecialType { get; }
  32. public PluginExecutor(PluginMetadata meta, Special specialType = Special.None)
  33. {
  34. Metadata = meta;
  35. SpecialType = specialType;
  36. if (specialType != Special.None)
  37. {
  38. CreatePlugin = m => null;
  39. LifecycleEnable = o => { };
  40. LifecycleDisable = o => TaskEx.WhenAll();
  41. }
  42. else
  43. PrepareDelegates();
  44. }
  45. public object Instance { get; private set; } = null;
  46. private Func<PluginMetadata, object> CreatePlugin { get; set; }
  47. private Action<object> LifecycleEnable { get; set; }
  48. // disable may be async (#24)
  49. private Func<object, Task> LifecycleDisable { get; set; }
  50. public void Create()
  51. {
  52. if (Instance != null) return;
  53. Instance = CreatePlugin(Metadata);
  54. }
  55. public void Enable() => LifecycleEnable(Instance);
  56. public Task Disable() => LifecycleDisable(Instance);
  57. private void PrepareDelegates()
  58. { // TODO: use custom exception types or something
  59. PluginLoader.Load(Metadata);
  60. var type = Metadata.Assembly.GetType(Metadata.PluginType.FullName);
  61. CreatePlugin = MakeCreateFunc(type, Metadata.Name);
  62. LifecycleEnable = MakeLifecycleEnableFunc(type, Metadata.Name);
  63. LifecycleDisable = MakeLifecycleDisableFunc(type, Metadata.Name);
  64. }
  65. private static Func<PluginMetadata, object> MakeCreateFunc(Type type, string name)
  66. { // TODO: what do i want the visibiliy of Init methods to be?
  67. var ctors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
  68. .Select(c => (c, attr: c.GetCustomAttribute<InitAttribute>()))
  69. .NonNull(t => t.attr)
  70. .OrderByDescending(t => t.c.GetParameters().Length)
  71. .Select(t => t.c).ToArray();
  72. if (ctors.Length > 1)
  73. Logger.loader.Warn($"Plugin {name} has multiple [Init] constructors. Picking the one with the most parameters.");
  74. bool usingDefaultCtor = false;
  75. var ctor = ctors.FirstOrDefault();
  76. if (ctor == null)
  77. { // this is a normal case
  78. usingDefaultCtor = true;
  79. ctor = type.GetConstructor(Type.EmptyTypes);
  80. if (ctor == null)
  81. throw new InvalidOperationException($"{type.FullName} does not expose a public default constructor and has no constructors marked [Init]");
  82. }
  83. var initMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
  84. .Select(m => (m, attr: m.GetCustomAttribute<InitAttribute>()))
  85. .NonNull(t => t.attr).Select(t => t.m).ToArray();
  86. // verify that they don't have lifecycle attributes on them
  87. foreach (var method in initMethods)
  88. {
  89. var attrs = method.GetCustomAttributes(typeof(IEdgeLifecycleAttribute), false);
  90. if (attrs.Length != 0)
  91. throw new InvalidOperationException($"Method {method} on {type.FullName} has both an [Init] attribute and a lifecycle attribute.");
  92. }
  93. var metaParam = Expression.Parameter(typeof(PluginMetadata), "meta");
  94. var objVar = ExpressionEx.Variable(type, "objVar");
  95. var persistVar = ExpressionEx.Variable(typeof(object), "persistVar");
  96. var createExpr = Expression.Lambda<Func<PluginMetadata, object>>(
  97. ExpressionEx.Block(new[] { objVar, persistVar },
  98. initMethods
  99. .Select(m => PluginInitInjector.InjectedCallExpr(m.GetParameters(), metaParam, persistVar, es => Expression.Call(objVar, m, es)))
  100. .Prepend(ExpressionEx.Assign(objVar,
  101. usingDefaultCtor
  102. ? Expression.New(ctor)
  103. : PluginInitInjector.InjectedCallExpr(ctor.GetParameters(), metaParam, persistVar, es => Expression.New(ctor, es))))
  104. .Append(Expression.Convert(objVar, typeof(object)))),
  105. metaParam);
  106. // TODO: since this new system will be doing a fuck load of compilation, maybe add FastExpressionCompiler
  107. return createExpr.Compile();
  108. }
  109. // TODO: make enable and disable able to take a bool indicating which it is
  110. private static Action<object> MakeLifecycleEnableFunc(Type type, string name)
  111. {
  112. var noEnableDisable = type.GetCustomAttribute<NoEnableDisableAttribute>() is not null;
  113. var enableMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
  114. .Select(m => (m, attrs: m.GetCustomAttributes(typeof(IEdgeLifecycleAttribute), false)))
  115. .Select(t => (t.m, attrs: t.attrs.Cast<IEdgeLifecycleAttribute>()))
  116. .Where(t => t.attrs.Any(a => a.Type == EdgeLifecycleType.Enable))
  117. .Select(t => t.m).ToArray();
  118. if (enableMethods.Length == 0)
  119. {
  120. if (!noEnableDisable)
  121. Logger.loader.Notice($"Plugin {name} has no methods marked [OnStart] or [OnEnable]. Is this intentional?");
  122. return o => { };
  123. }
  124. foreach (var m in enableMethods)
  125. {
  126. if (m.GetParameters().Length > 0)
  127. throw new InvalidOperationException($"Method {m} on {type.FullName} is marked [OnStart] or [OnEnable] and has parameters.");
  128. if (m.ReturnType != typeof(void))
  129. Logger.loader.Warn($"Method {m} on {type.FullName} is marked [OnStart] or [OnEnable] and returns a value. It will be ignored.");
  130. }
  131. var objParam = Expression.Parameter(typeof(object), "obj");
  132. var instVar = ExpressionEx.Variable(type, "inst");
  133. var createExpr = Expression.Lambda<Action<object>>(
  134. ExpressionEx.Block(new[] { instVar },
  135. enableMethods
  136. .Select(m => (Expression)Expression.Call(instVar, m))
  137. .Prepend(ExpressionEx.Assign(instVar, Expression.Convert(objParam, type)))),
  138. objParam);
  139. return createExpr.Compile();
  140. }
  141. private static Func<object, Task> MakeLifecycleDisableFunc(Type type, string name)
  142. {
  143. var noEnableDisable = type.GetCustomAttribute<NoEnableDisableAttribute>() is not null;
  144. var disableMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
  145. .Select(m => (m, attrs: m.GetCustomAttributes(typeof(IEdgeLifecycleAttribute), false)))
  146. .Select(t => (t.m, attrs: t.attrs.Cast<IEdgeLifecycleAttribute>()))
  147. .Where(t => t.attrs.Any(a => a.Type == EdgeLifecycleType.Disable))
  148. .Select(t => t.m).ToArray();
  149. if (disableMethods.Length == 0)
  150. {
  151. if (!noEnableDisable)
  152. Logger.loader.Notice($"Plugin {name} has no methods marked [OnExit] or [OnDisable]. Is this intentional?");
  153. return o => TaskEx.WhenAll();
  154. }
  155. var taskMethods = new List<MethodInfo>();
  156. var nonTaskMethods = new List<MethodInfo>();
  157. foreach (var m in disableMethods)
  158. {
  159. if (m.GetParameters().Length > 0)
  160. throw new InvalidOperationException($"Method {m} on {type.FullName} is marked [OnExit] or [OnDisable] and has parameters.");
  161. if (m.ReturnType != typeof(void))
  162. {
  163. if (typeof(Task).IsAssignableFrom(m.ReturnType))
  164. {
  165. taskMethods.Add(m);
  166. continue;
  167. }
  168. else
  169. Logger.loader.Warn($"Method {m} on {type.FullName} is marked [OnExit] or [OnDisable] and returns a non-Task value. It will be ignored.");
  170. }
  171. nonTaskMethods.Add(m);
  172. }
  173. Expression<Func<Task>> completedTaskDel = () => TaskEx.WhenAll();
  174. var getCompletedTask = completedTaskDel.Body;
  175. var taskWhenAll = typeof(TaskEx).GetMethod(nameof(TaskEx.WhenAll), new[] { typeof(Task[]) });
  176. var objParam = Expression.Parameter(typeof(object), "obj");
  177. var instVar = ExpressionEx.Variable(type, "inst");
  178. var createExpr = Expression.Lambda<Func<object, Task>>(
  179. ExpressionEx.Block(new[] { instVar },
  180. nonTaskMethods
  181. .Select(m => (Expression)Expression.Call(instVar, m))
  182. .Prepend(ExpressionEx.Assign(instVar, Expression.Convert(objParam, type)))
  183. .Append(
  184. taskMethods.Count == 0
  185. ? getCompletedTask
  186. : Expression.Call(taskWhenAll,
  187. Expression.NewArrayInit(typeof(Task),
  188. taskMethods.Select(m =>
  189. (Expression)Expression.Convert(Expression.Call(instVar, m), typeof(Task))))))),
  190. objParam);
  191. return createExpr.Compile();
  192. }
  193. }
  194. }