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.

191 lines
8.1 KiB

4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
4 years ago
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Reflection;
  5. using IPA.Config;
  6. using IPA.Logging;
  7. using IPA.Utilities;
  8. using System.Linq.Expressions;
  9. #if NET4
  10. using Expression = System.Linq.Expressions.Expression;
  11. using ExpressionEx = System.Linq.Expressions.Expression;
  12. #endif
  13. #if NET3
  14. using Net3_Proxy;
  15. #endif
  16. namespace IPA.Loader
  17. {
  18. /// <summary>
  19. /// The type that handles value injecting into a plugin's initialization methods.
  20. /// </summary>
  21. /// <remarks>
  22. /// The default injectors and what they provide are shown in this table.
  23. /// <list type="table">
  24. /// <listheader>
  25. /// <term>Parameter Type</term>
  26. /// <description>Injected Value</description>
  27. /// </listheader>
  28. /// <item>
  29. /// <term><see cref="Logger"/></term>
  30. /// <description>A <see cref="StandardLogger"/> specialized for the plugin being injected</description>
  31. /// </item>
  32. /// <item>
  33. /// <term><see cref="PluginMetadata"/></term>
  34. /// <description>The <see cref="PluginMetadata"/> of the plugin being injected</description>
  35. /// </item>
  36. /// <item>
  37. /// <term><see cref="Config.Config"/></term>
  38. /// <description>
  39. /// <para>A <see cref="Config.Config"/> object for the plugin being injected.</para>
  40. /// <para>
  41. /// These parameters may have <see cref="Config.Config.NameAttribute"/> and <see cref="Config.Config.PreferAttribute"/> to control
  42. /// how it is constructed.
  43. /// </para>
  44. /// </description>
  45. /// </item>
  46. /// </list>
  47. /// For all of the default injectors, only one of each will be generated, and any later parameters will recieve the same value as the first one.
  48. /// </remarks>
  49. public static class PluginInitInjector
  50. {
  51. /// <summary>
  52. /// A typed injector for a plugin's Init method. When registered, called for all associated types. If it returns null, the default for the type will be used.
  53. /// </summary>
  54. /// <param name="previous">the previous return value of the function, or <see langword="null"/> if never called for plugin.</param>
  55. /// <param name="param">the <see cref="ParameterInfo"/> of the parameter being injected.</param>
  56. /// <param name="meta">the <see cref="PluginMetadata"/> for the plugin being loaded.</param>
  57. /// <returns>the value to inject into that parameter.</returns>
  58. public delegate object InjectParameter(object previous, ParameterInfo param, PluginMetadata meta);
  59. /// <summary>
  60. /// Adds an injector to be used when calling future plugins' Init methods.
  61. /// </summary>
  62. /// <param name="type">the type of the parameter.</param>
  63. /// <param name="injector">the function to call for injection.</param>
  64. public static void AddInjector(Type type, InjectParameter injector)
  65. {
  66. injectors.Add(new TypedInjector(type, injector));
  67. }
  68. private struct TypedInjector : IEquatable<TypedInjector>
  69. {
  70. public Type Type;
  71. public InjectParameter Injector;
  72. public TypedInjector(Type t, InjectParameter i)
  73. { Type = t; Injector = i; }
  74. public object Inject(object prev, ParameterInfo info, PluginMetadata meta)
  75. => Injector(prev, info, meta);
  76. public bool Equals(TypedInjector other)
  77. => Type == other.Type && Injector == other.Injector;
  78. public override bool Equals(object obj)
  79. => obj is TypedInjector i && Equals(i);
  80. public override int GetHashCode()
  81. => Type.GetHashCode() ^ Injector.GetHashCode();
  82. public static bool operator ==(TypedInjector a, TypedInjector b) => a.Equals(b);
  83. public static bool operator !=(TypedInjector a, TypedInjector b) => !a.Equals(b);
  84. }
  85. private static readonly List<TypedInjector> injectors = new List<TypedInjector>
  86. {
  87. new TypedInjector(typeof(Logger), (prev, param, meta) => prev ?? new StandardLogger(meta.Name)),
  88. new TypedInjector(typeof(PluginMetadata), (prev, param, meta) => prev ?? meta),
  89. new TypedInjector(typeof(Config.Config), (prev, param, meta) =>
  90. {
  91. if (prev != null) return prev;
  92. return Config.Config.GetConfigFor(meta.Name, param);
  93. })
  94. };
  95. private static int? MatchPriority(Type target, Type source)
  96. {
  97. if (target == source) return int.MaxValue;
  98. if (!target.IsAssignableFrom(source)) return null;
  99. if (!target.IsInterface && !source.IsSubclassOf(target)) return int.MinValue;
  100. int value = 0;
  101. while (true)
  102. {
  103. if (source == null) return value;
  104. if (target.IsInterface && source.GetInterfaces().Contains(target))
  105. return value;
  106. else if (target == source)
  107. return value;
  108. else
  109. {
  110. value--; // lower priority
  111. source = source.BaseType;
  112. }
  113. }
  114. }
  115. private static readonly MethodInfo InjectMethod = typeof(PluginInitInjector).GetMethod(nameof(Inject), BindingFlags.NonPublic | BindingFlags.Static);
  116. internal static Expression InjectedCallExpr(ParameterInfo[] initParams, Expression meta, Expression persistVar, Func<IEnumerable<Expression>, Expression> exprGen)
  117. {
  118. var arr = ExpressionEx.Variable(typeof(object[]), "initArr");
  119. return ExpressionEx.Block(new[] { arr },
  120. ExpressionEx.Assign(arr, Expression.Call(InjectMethod, Expression.Constant(initParams), meta, persistVar)),
  121. exprGen(initParams
  122. .Select(p => p.ParameterType)
  123. .Select((t, i) => (Expression)Expression.Convert(
  124. Expression.ArrayIndex(arr, Expression.Constant(i)), t))));
  125. }
  126. internal static object[] Inject(ParameterInfo[] initParams, PluginMetadata meta, ref object persist)
  127. {
  128. var initArgs = new List<object>();
  129. var previousValues = persist as Dictionary<TypedInjector, object>;
  130. if (previousValues == null)
  131. {
  132. previousValues = new Dictionary<TypedInjector, object>(injectors.Count);
  133. persist = previousValues;
  134. }
  135. foreach (var param in initParams)
  136. {
  137. var paramType = param.ParameterType;
  138. var value = paramType.GetDefault();
  139. var toUse = injectors.Select(i => (inject: i, priority: MatchPriority(paramType, i.Type))) // check match priority, combine it
  140. .Where(t => t.priority != null) // filter null priorities
  141. .Select(t => (t.inject, priority: t.priority.Value)) // remove nullable
  142. .OrderByDescending(t => t.priority) // sort by value
  143. .Select(t => t.inject); // remove priority value
  144. // this tries injectors in order of closest match by type provided
  145. foreach (var pair in toUse)
  146. {
  147. object prev = null;
  148. if (previousValues.ContainsKey(pair))
  149. prev = previousValues[pair];
  150. var val = pair.Inject(prev, param, meta);
  151. if (previousValues.ContainsKey(pair))
  152. previousValues[pair] = val;
  153. else
  154. previousValues.Add(pair, val);
  155. if (val == null) continue;
  156. value = val;
  157. break;
  158. }
  159. initArgs.Add(value);
  160. }
  161. //init.Invoke(instance, initArgs.ToArray());
  162. return initArgs.ToArray();
  163. }
  164. }
  165. }