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.

208 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 Net3_Proxy;
  16. using System.Threading.Tasks;
  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 enableMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
  113. .Select(m => (m, attrs: m.GetCustomAttributes(typeof(IEdgeLifecycleAttribute), false)))
  114. .Select(t => (t.m, attrs: t.attrs.Cast<IEdgeLifecycleAttribute>()))
  115. .Where(t => t.attrs.Any(a => a.Type == EdgeLifecycleType.Enable))
  116. .Select(t => t.m).ToArray();
  117. if (enableMethods.Length == 0)
  118. {
  119. Logger.loader.Notice($"Plugin {name} has no methods marked [OnStart] or [OnEnable]. Is this intentional?");
  120. return o => { };
  121. }
  122. foreach (var m in enableMethods)
  123. {
  124. if (m.GetParameters().Length > 0)
  125. throw new InvalidOperationException($"Method {m} on {type.FullName} is marked [OnStart] or [OnEnable] and has parameters.");
  126. if (m.ReturnType != typeof(void))
  127. Logger.loader.Warn($"Method {m} on {type.FullName} is marked [OnStart] or [OnEnable] and returns a value. It will be ignored.");
  128. }
  129. var objParam = Expression.Parameter(typeof(object), "obj");
  130. var instVar = ExpressionEx.Variable(type, "inst");
  131. var createExpr = Expression.Lambda<Action<object>>(
  132. ExpressionEx.Block(new[] { instVar },
  133. enableMethods
  134. .Select(m => (Expression)Expression.Call(instVar, m))
  135. .Prepend(ExpressionEx.Assign(instVar, Expression.Convert(objParam, type)))),
  136. objParam);
  137. return createExpr.Compile();
  138. }
  139. private static Func<object, Task> MakeLifecycleDisableFunc(Type type, string name)
  140. {
  141. var disableMethods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance)
  142. .Select(m => (m, attrs: m.GetCustomAttributes(typeof(IEdgeLifecycleAttribute), false)))
  143. .Select(t => (t.m, attrs: t.attrs.Cast<IEdgeLifecycleAttribute>()))
  144. .Where(t => t.attrs.Any(a => a.Type == EdgeLifecycleType.Disable))
  145. .Select(t => t.m).ToArray();
  146. if (disableMethods.Length == 0)
  147. {
  148. Logger.loader.Notice($"Plugin {name} has no methods marked [OnExit] or [OnDisable]. Is this intentional?");
  149. return o => TaskEx.WhenAll();
  150. }
  151. var taskMethods = new List<MethodInfo>();
  152. var nonTaskMethods = new List<MethodInfo>();
  153. foreach (var m in disableMethods)
  154. {
  155. if (m.GetParameters().Length > 0)
  156. throw new InvalidOperationException($"Method {m} on {type.FullName} is marked [OnExit] or [OnDisable] and has parameters.");
  157. if (m.ReturnType != typeof(void))
  158. {
  159. if (typeof(Task).IsAssignableFrom(m.ReturnType))
  160. {
  161. taskMethods.Add(m);
  162. continue;
  163. }
  164. else
  165. Logger.loader.Warn($"Method {m} on {type.FullName} is marked [OnExit] or [OnDisable] and returns a non-Task value. It will be ignored.");
  166. }
  167. nonTaskMethods.Add(m);
  168. }
  169. Expression<Func<Task>> completedTaskDel = () => TaskEx.WhenAll();
  170. var getCompletedTask = completedTaskDel.Body;
  171. var taskWhenAll = typeof(TaskEx).GetMethod(nameof(TaskEx.WhenAll), new[] { typeof(Task[]) });
  172. var objParam = Expression.Parameter(typeof(object), "obj");
  173. var instVar = ExpressionEx.Variable(type, "inst");
  174. var createExpr = Expression.Lambda<Func<object, Task>>(
  175. ExpressionEx.Block(new[] { instVar },
  176. nonTaskMethods
  177. .Select(m => (Expression)Expression.Call(instVar, m))
  178. .Prepend(ExpressionEx.Assign(instVar, Expression.Convert(objParam, type)))
  179. .Append(
  180. taskMethods.Count == 0
  181. ? getCompletedTask
  182. : Expression.Call(taskWhenAll,
  183. Expression.NewArrayInit(typeof(Task),
  184. taskMethods.Select(m =>
  185. (Expression)Expression.Convert(Expression.Call(instVar, m), typeof(Task))))))),
  186. objParam);
  187. return createExpr.Compile();
  188. }
  189. }
  190. }