InteropHelper.cs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  1. using System.Diagnostics.CodeAnalysis;
  2. using System.Globalization;
  3. using System.Reflection;
  4. using Jint.Extensions;
  5. using Jint.Native;
  6. namespace Jint.Runtime.Interop;
  7. #pragma warning disable IL2072
  8. internal sealed class InteropHelper
  9. {
  10. internal const DynamicallyAccessedMemberTypes DefaultDynamicallyAccessedMemberTypes = DynamicallyAccessedMemberTypes.PublicConstructors
  11. | DynamicallyAccessedMemberTypes.PublicProperties
  12. | DynamicallyAccessedMemberTypes.PublicMethods
  13. | DynamicallyAccessedMemberTypes.PublicFields
  14. | DynamicallyAccessedMemberTypes.PublicEvents;
  15. internal readonly record struct AssignableResult(int Score, Type MatchingGivenType)
  16. {
  17. public bool IsAssignable => Score >= 0;
  18. }
  19. /// <summary>
  20. /// resources:
  21. /// https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/how-to-examine-and-instantiate-generic-types-with-reflection
  22. /// https://stackoverflow.com/questions/74616/how-to-detect-if-type-is-another-generic-type/1075059#1075059
  23. /// https://docs.microsoft.com/en-us/dotnet/api/system.type.isconstructedgenerictype?view=net-6.0
  24. /// This can be improved upon - specifically as mentioned in the above MS document:
  25. /// GetGenericParameterConstraints()
  26. /// and array handling - i.e.
  27. /// GetElementType()
  28. /// </summary>
  29. internal static AssignableResult IsAssignableToGenericType(
  30. [DynamicallyAccessedMembers(DefaultDynamicallyAccessedMemberTypes | DynamicallyAccessedMemberTypes.Interfaces)]
  31. Type givenType,
  32. [DynamicallyAccessedMembers(DefaultDynamicallyAccessedMemberTypes | DynamicallyAccessedMemberTypes.Interfaces)]
  33. Type genericType)
  34. {
  35. if (givenType is null)
  36. {
  37. return new AssignableResult(-1, typeof(void));
  38. }
  39. if (!genericType.IsConstructedGenericType)
  40. {
  41. // as mentioned here:
  42. // https://docs.microsoft.com/en-us/dotnet/api/system.type.isconstructedgenerictype?view=net-6.0
  43. // this effectively means this generic type is open (i.e. not closed) - so any type is "possible" - without looking at the code in the method we don't know
  44. // whether any operations are being applied that "don't work"
  45. return new AssignableResult(2, givenType);
  46. }
  47. var interfaceTypes = givenType.GetInterfaces();
  48. foreach (var it in interfaceTypes)
  49. {
  50. if (it.IsGenericType)
  51. {
  52. var givenTypeGenericDef = it.GetGenericTypeDefinition();
  53. if (givenTypeGenericDef == genericType)
  54. {
  55. return new AssignableResult(0, it);
  56. }
  57. else if (genericType.IsGenericType && (givenTypeGenericDef == genericType.GetGenericTypeDefinition()))
  58. {
  59. return new AssignableResult(0, it);
  60. }
  61. // TPC: we could also add a loop to recurse and iterate thru the iterfaces of generic type - because of covariance/contravariance
  62. }
  63. }
  64. if (givenType.IsGenericType && givenType.GetGenericTypeDefinition() == genericType)
  65. {
  66. return new AssignableResult(0, givenType);
  67. }
  68. var baseType = givenType.BaseType;
  69. if (baseType == null)
  70. {
  71. return new AssignableResult(-1, givenType);
  72. }
  73. return IsAssignableToGenericType(baseType, genericType);
  74. }
  75. /// <summary>
  76. /// Determines how well parameter type matches target method's type.
  77. /// </summary>
  78. private static int CalculateMethodParameterScore(Engine engine, ParameterInfo parameter, JsValue parameterValue)
  79. {
  80. var paramType = parameter.ParameterType;
  81. var objectValue = parameterValue.ToObject();
  82. var objectValueType = objectValue?.GetType();
  83. if (objectValueType == paramType)
  84. {
  85. return 0;
  86. }
  87. if (objectValue is null)
  88. {
  89. if (!parameter.IsOptional && !TypeIsNullable(paramType))
  90. {
  91. // this is bad
  92. return -1;
  93. }
  94. return 0;
  95. }
  96. if (paramType == typeof(JsValue))
  97. {
  98. // JsValue is convertible to. But it is still not a perfect match
  99. return 1;
  100. }
  101. if (paramType == typeof(object))
  102. {
  103. // a catch-all, prefer others over it
  104. return 5;
  105. }
  106. const int ScoreForDifferentTypeButFittingNumberRange = 2;
  107. if (parameterValue.IsNumber())
  108. {
  109. var num = (JsNumber) parameterValue;
  110. var numValue = num._value;
  111. if (paramType == typeof(double))
  112. {
  113. return 0;
  114. }
  115. if (paramType == typeof(float) && numValue is <= float.MaxValue and >= float.MinValue)
  116. {
  117. return ScoreForDifferentTypeButFittingNumberRange;
  118. }
  119. var isInteger = num.IsInteger() || TypeConverter.IsIntegralNumber(num._value);
  120. // if value is integral number and within allowed range for the parameter type, we consider this perfect match
  121. if (isInteger)
  122. {
  123. if (paramType == typeof(int))
  124. {
  125. return 0;
  126. }
  127. if (paramType == typeof(long))
  128. {
  129. return ScoreForDifferentTypeButFittingNumberRange;
  130. }
  131. // check if we can narrow without exception throwing versions (CanChangeType)
  132. var integerValue = (int) num._value;
  133. if (paramType == typeof(short) && integerValue is <= short.MaxValue and >= short.MinValue)
  134. {
  135. return ScoreForDifferentTypeButFittingNumberRange;
  136. }
  137. if (paramType == typeof(ushort) && integerValue is <= ushort.MaxValue and >= ushort.MinValue)
  138. {
  139. return ScoreForDifferentTypeButFittingNumberRange;
  140. }
  141. if (paramType == typeof(byte) && integerValue is <= byte.MaxValue and >= byte.MinValue)
  142. {
  143. return ScoreForDifferentTypeButFittingNumberRange;
  144. }
  145. if (paramType == typeof(sbyte) && integerValue is <= sbyte.MaxValue and >= sbyte.MinValue)
  146. {
  147. return ScoreForDifferentTypeButFittingNumberRange;
  148. }
  149. }
  150. }
  151. if (paramType.IsEnum &&
  152. parameterValue is JsNumber jsNumber
  153. && jsNumber.IsInteger()
  154. && paramType.GetEnumUnderlyingType() == typeof(int)
  155. && Enum.IsDefined(paramType, jsNumber.AsInteger()))
  156. {
  157. // we can do conversion from int value to enum
  158. return 0;
  159. }
  160. if (paramType.IsAssignableFrom(objectValueType))
  161. {
  162. // is-a-relation
  163. return 1;
  164. }
  165. if (parameterValue.IsArray() && paramType.IsArray)
  166. {
  167. // we have potential, TODO if we'd know JS array's internal type we could have exact match
  168. return 2;
  169. }
  170. // not sure the best point to start generic type tests
  171. if (paramType.IsGenericParameter)
  172. {
  173. var genericTypeAssignmentScore = IsAssignableToGenericType(objectValueType!, paramType);
  174. if (genericTypeAssignmentScore.Score != -1)
  175. {
  176. return genericTypeAssignmentScore.Score;
  177. }
  178. }
  179. if (CanChangeType(objectValue, paramType))
  180. {
  181. // forcing conversion isn't ideal, but works, especially for int -> double for example
  182. return 3;
  183. }
  184. foreach (var m in objectValueType!.GetOperatorOverloadMethods())
  185. {
  186. if (paramType.IsAssignableFrom(m.ReturnType) && m.Name is "op_Implicit" or "op_Explicit")
  187. {
  188. // implicit/explicit operator conversion is OK, but not ideal
  189. return 3;
  190. }
  191. }
  192. if (ReflectionExtensions.TryConvertViaTypeCoercion(paramType, engine.Options.Interop.ValueCoercion, parameterValue, out _))
  193. {
  194. // gray JS zone where we start to do odd things
  195. return 10;
  196. }
  197. // will rarely succeed
  198. return 100;
  199. }
  200. /// <summary>
  201. /// Method's match score tells how far away it's from ideal candidate. 0 = ideal, bigger the the number,
  202. /// the farther away the candidate is from ideal match. Negative signals impossible match.
  203. /// </summary>
  204. private static int CalculateMethodScore(Engine engine, MethodDescriptor method, JsCallArguments arguments)
  205. {
  206. if (method.Parameters.Length == 0 && arguments.Length == 0)
  207. {
  208. // perfect
  209. return 0;
  210. }
  211. var score = 0;
  212. for (var i = 0; i < arguments.Length; i++)
  213. {
  214. var jsValue = arguments[i];
  215. var parameterScore = CalculateMethodParameterScore(engine, method.Parameters[i], jsValue);
  216. if (parameterScore < 0)
  217. {
  218. return parameterScore;
  219. }
  220. score += parameterScore;
  221. }
  222. return score;
  223. }
  224. private static bool CanChangeType(object value, Type targetType)
  225. {
  226. if (value is null && !targetType.IsValueType)
  227. {
  228. return true;
  229. }
  230. if (value is not IConvertible)
  231. {
  232. return false;
  233. }
  234. try
  235. {
  236. Convert.ChangeType(value, targetType, CultureInfo.InvariantCulture);
  237. return true;
  238. }
  239. catch
  240. {
  241. // nope
  242. return false;
  243. }
  244. }
  245. internal static bool TypeIsNullable(Type type)
  246. {
  247. return !type.IsValueType || Nullable.GetUnderlyingType(type) != null;
  248. }
  249. internal readonly record struct MethodMatch(MethodDescriptor Method, JsCallArguments Arguments, int Score = 0) : IComparable<MethodMatch>
  250. {
  251. public int CompareTo(MethodMatch other) => Score.CompareTo(other.Score);
  252. }
  253. internal static IEnumerable<MethodMatch> FindBestMatch<TState>(
  254. Engine engine,
  255. MethodDescriptor[] methods,
  256. Func<MethodDescriptor, TState, JsValue[]> argumentProvider,
  257. TState state)
  258. {
  259. List<MethodMatch>? matchingByParameterCount = null;
  260. foreach (var method in methods)
  261. {
  262. var parameterInfos = method.Parameters;
  263. var arguments = argumentProvider(method, state);
  264. if (arguments.Length <= parameterInfos.Length
  265. && arguments.Length >= parameterInfos.Length - method.ParameterDefaultValuesCount)
  266. {
  267. var score = CalculateMethodScore(engine, method, arguments);
  268. if (score == 0)
  269. {
  270. // perfect match
  271. yield return new MethodMatch(method, arguments);
  272. yield break;
  273. }
  274. if (score < 0)
  275. {
  276. // discard
  277. continue;
  278. }
  279. matchingByParameterCount ??= [];
  280. matchingByParameterCount.Add(new MethodMatch(method, arguments, score));
  281. }
  282. }
  283. if (matchingByParameterCount == null)
  284. {
  285. yield break;
  286. }
  287. if (matchingByParameterCount.Count > 1)
  288. {
  289. matchingByParameterCount.Sort();
  290. }
  291. foreach (var match in matchingByParameterCount)
  292. {
  293. yield return match;
  294. }
  295. }
  296. }