TypeReference.cs 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211
  1. using System.Collections.Concurrent;
  2. using System.Reflection;
  3. using Jint.Collections;
  4. using Jint.Native;
  5. using Jint.Native.Function;
  6. using Jint.Native.Object;
  7. using Jint.Runtime.Descriptors;
  8. using Jint.Runtime.Interop.Reflection;
  9. namespace Jint.Runtime.Interop
  10. {
  11. public sealed class TypeReference : FunctionInstance, IConstructor, IObjectWrapper
  12. {
  13. private static readonly JsString _name = new("typereference");
  14. private static readonly ConcurrentDictionary<Type, MethodDescriptor[]> _constructorCache = new();
  15. private static readonly ConcurrentDictionary<MemberAccessorKey, ReflectionAccessor> _memberAccessors = new();
  16. private readonly record struct MemberAccessorKey(Type Type, string PropertyName);
  17. private TypeReference(Engine engine, Type type)
  18. : base(engine, engine.Realm, _name, FunctionThisMode.Global)
  19. {
  20. ReferenceType = type;
  21. _prototype = engine.Realm.Intrinsics.Function.PrototypeObject;
  22. _length = PropertyDescriptor.AllForbiddenDescriptor.NumberZero;
  23. var proto = new JsObject(engine);
  24. _prototypeDescriptor = new PropertyDescriptor(proto, PropertyFlag.AllForbidden);
  25. PreventExtensions();
  26. }
  27. public Type ReferenceType { get; }
  28. public static TypeReference CreateTypeReference<T>(Engine engine)
  29. {
  30. return CreateTypeReference(engine, typeof(T));
  31. }
  32. public static TypeReference CreateTypeReference(Engine engine, Type type)
  33. {
  34. return new TypeReference(engine, type);
  35. }
  36. protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments)
  37. {
  38. // direct calls on a TypeReference constructor object is equivalent to the new operator
  39. return Construct(arguments, Undefined);
  40. }
  41. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) => Construct(arguments, newTarget);
  42. private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  43. {
  44. static ObjectInstance ObjectCreator(Engine engine, Realm realm, ObjectCreateState state)
  45. {
  46. var arguments = state.Arguments;
  47. var referenceType = state.TypeReference.ReferenceType;
  48. var fromOptionsCreator = engine.Options.Interop.CreateTypeReferenceObject(engine, referenceType, arguments);
  49. ObjectInstance? result = null;
  50. if (fromOptionsCreator is not null)
  51. {
  52. result = TypeConverter.ToObject(realm, FromObject(engine, fromOptionsCreator));
  53. }
  54. else if (arguments.Length == 0 && referenceType.IsValueType)
  55. {
  56. var instance = Activator.CreateInstance(referenceType);
  57. result = TypeConverter.ToObject(realm, FromObject(engine, instance));
  58. }
  59. else
  60. {
  61. var constructors = _constructorCache.GetOrAdd(
  62. referenceType,
  63. t => MethodDescriptor.Build(t.GetConstructors(BindingFlags.Public | BindingFlags.Instance)));
  64. foreach (var (method, _, _) in TypeConverter.FindBestMatch(engine, constructors, _ => arguments))
  65. {
  66. var retVal = method.Call(engine, null, arguments);
  67. result = TypeConverter.ToObject(realm, retVal);
  68. // todo: cache method info
  69. break;
  70. }
  71. }
  72. if (result is null)
  73. {
  74. ExceptionHelper.ThrowTypeError(realm, $"Could not resolve a constructor for type {referenceType} for given arguments");
  75. }
  76. result.SetPrototypeOf(state.TypeReference);
  77. return result;
  78. }
  79. // TODO should inject prototype that reflects TypeReference's target's layout
  80. var thisArgument = OrdinaryCreateFromConstructor(
  81. newTarget,
  82. static intrinsics => intrinsics.Object.PrototypeObject,
  83. ObjectCreator,
  84. new ObjectCreateState(this, arguments));
  85. return thisArgument;
  86. }
  87. private readonly record struct ObjectCreateState(TypeReference TypeReference, JsValue[] Arguments);
  88. internal override bool OrdinaryHasInstance(JsValue v)
  89. {
  90. if (v is IObjectWrapper wrapper)
  91. {
  92. return wrapper.Target.GetType() == ReferenceType;
  93. }
  94. return base.OrdinaryHasInstance(v);
  95. }
  96. public override bool DefineOwnProperty(JsValue property, PropertyDescriptor desc)
  97. {
  98. return false;
  99. }
  100. public override bool Delete(JsValue property)
  101. {
  102. return false;
  103. }
  104. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  105. {
  106. if (!CanPut(property))
  107. {
  108. return false;
  109. }
  110. var ownDesc = GetOwnProperty(property);
  111. ownDesc.Value = value;
  112. return true;
  113. }
  114. public override PropertyDescriptor GetOwnProperty(JsValue property)
  115. {
  116. if (property is not JsString jsString)
  117. {
  118. return PropertyDescriptor.Undefined;
  119. }
  120. var key = jsString._value;
  121. var descriptor = PropertyDescriptor.Undefined;
  122. if (_properties?.TryGetValue(key, out descriptor) != true)
  123. {
  124. descriptor = CreatePropertyDescriptor(key);
  125. if (!ReferenceEquals(descriptor, PropertyDescriptor.Undefined))
  126. {
  127. _properties ??= new PropertyDictionary();
  128. _properties[key] = descriptor;
  129. return descriptor;
  130. }
  131. }
  132. return base.GetOwnProperty(property);
  133. }
  134. private PropertyDescriptor CreatePropertyDescriptor(string name)
  135. {
  136. var key = new MemberAccessorKey(ReferenceType, name);
  137. var accessor = _memberAccessors.GetOrAdd(key, x => ResolveMemberAccessor(_engine, x.Type, x.PropertyName));
  138. return accessor.CreatePropertyDescriptor(_engine, ReferenceType, enumerable: true);
  139. }
  140. private static ReflectionAccessor ResolveMemberAccessor(Engine engine, Type type, string name)
  141. {
  142. var typeResolver = engine.Options.Interop.TypeResolver;
  143. if (type.IsEnum)
  144. {
  145. var memberNameComparer = typeResolver.MemberNameComparer;
  146. var typeResolverMemberNameCreator = typeResolver.MemberNameCreator;
  147. var enumValues = Enum.GetValues(type);
  148. var enumNames = Enum.GetNames(type);
  149. for (var i = 0; i < enumValues.Length; i++)
  150. {
  151. var enumOriginalName = enumNames.GetValue(i).ToString();
  152. var member = type.GetMember(enumOriginalName)[0];
  153. foreach (var exposedName in typeResolverMemberNameCreator(member))
  154. {
  155. if (memberNameComparer.Equals(name, exposedName))
  156. {
  157. var value = enumValues.GetValue(i);
  158. return new ConstantValueAccessor(JsNumber.Create(value));
  159. }
  160. }
  161. }
  162. return ConstantValueAccessor.NullAccessor;
  163. }
  164. const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;
  165. return typeResolver.TryFindMemberAccessor(engine, type, name, bindingFlags, indexerToTry: null, out var accessor)
  166. ? accessor
  167. : ConstantValueAccessor.NullAccessor;
  168. }
  169. public object Target => ReferenceType;
  170. }
  171. }