TypeReference.cs 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206
  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 ObjectInstance(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. ObjectInstance? result = null;
  49. if (arguments.Length == 0 && referenceType.IsValueType)
  50. {
  51. var instance = Activator.CreateInstance(referenceType);
  52. result = TypeConverter.ToObject(realm, FromObject(engine, instance));
  53. }
  54. else
  55. {
  56. var constructors = _constructorCache.GetOrAdd(
  57. referenceType,
  58. t => MethodDescriptor.Build(t.GetConstructors(BindingFlags.Public | BindingFlags.Instance)));
  59. foreach (var (method, _, _) in TypeConverter.FindBestMatch(engine, constructors, _ => arguments))
  60. {
  61. var retVal = method.Call(engine, null, arguments);
  62. result = TypeConverter.ToObject(realm, retVal);
  63. // todo: cache method info
  64. break;
  65. }
  66. }
  67. if (result is null)
  68. {
  69. ExceptionHelper.ThrowTypeError(realm, "No public methods with the specified arguments were found.");
  70. }
  71. result.SetPrototypeOf(state.TypeReference);
  72. return result;
  73. }
  74. // TODO should inject prototype that reflects TypeReference's target's layout
  75. var thisArgument = OrdinaryCreateFromConstructor(
  76. newTarget,
  77. static intrinsics => intrinsics.Object.PrototypeObject,
  78. ObjectCreator,
  79. new ObjectCreateState(this, arguments));
  80. return thisArgument;
  81. }
  82. private readonly record struct ObjectCreateState(TypeReference TypeReference, JsValue[] Arguments);
  83. internal override bool OrdinaryHasInstance(JsValue v)
  84. {
  85. if (v is IObjectWrapper wrapper)
  86. {
  87. return wrapper.Target.GetType() == ReferenceType;
  88. }
  89. return base.OrdinaryHasInstance(v);
  90. }
  91. public override bool DefineOwnProperty(JsValue property, PropertyDescriptor desc)
  92. {
  93. return false;
  94. }
  95. public override bool Delete(JsValue property)
  96. {
  97. return false;
  98. }
  99. public override bool Set(JsValue property, JsValue value, JsValue receiver)
  100. {
  101. if (!CanPut(property))
  102. {
  103. return false;
  104. }
  105. var ownDesc = GetOwnProperty(property);
  106. ownDesc.Value = value;
  107. return true;
  108. }
  109. public override PropertyDescriptor GetOwnProperty(JsValue property)
  110. {
  111. if (property is not JsString jsString)
  112. {
  113. return PropertyDescriptor.Undefined;
  114. }
  115. var key = jsString._value;
  116. var descriptor = PropertyDescriptor.Undefined;
  117. if (_properties?.TryGetValue(key, out descriptor) != true)
  118. {
  119. descriptor = CreatePropertyDescriptor(key);
  120. if (!ReferenceEquals(descriptor, PropertyDescriptor.Undefined))
  121. {
  122. _properties ??= new PropertyDictionary();
  123. _properties[key] = descriptor;
  124. return descriptor;
  125. }
  126. }
  127. return base.GetOwnProperty(property);
  128. }
  129. private PropertyDescriptor CreatePropertyDescriptor(string name)
  130. {
  131. var key = new MemberAccessorKey(ReferenceType, name);
  132. var accessor = _memberAccessors.GetOrAdd(key, x => ResolveMemberAccessor(_engine, x.Type, x.PropertyName));
  133. return accessor.CreatePropertyDescriptor(_engine, ReferenceType, enumerable: true);
  134. }
  135. private static ReflectionAccessor ResolveMemberAccessor(Engine engine, Type type, string name)
  136. {
  137. var typeResolver = engine.Options.Interop.TypeResolver;
  138. if (type.IsEnum)
  139. {
  140. var memberNameComparer = typeResolver.MemberNameComparer;
  141. var typeResolverMemberNameCreator = typeResolver.MemberNameCreator;
  142. var enumValues = Enum.GetValues(type);
  143. var enumNames = Enum.GetNames(type);
  144. for (var i = 0; i < enumValues.Length; i++)
  145. {
  146. var enumOriginalName = enumNames.GetValue(i).ToString();
  147. var member = type.GetMember(enumOriginalName)[0];
  148. foreach (var exposedName in typeResolverMemberNameCreator(member))
  149. {
  150. if (memberNameComparer.Equals(name, exposedName))
  151. {
  152. var value = enumValues.GetValue(i);
  153. return new ConstantValueAccessor(JsNumber.Create(value));
  154. }
  155. }
  156. }
  157. return ConstantValueAccessor.NullAccessor;
  158. }
  159. const BindingFlags bindingFlags = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;
  160. return typeResolver.TryFindMemberAccessor(engine, type, name, bindingFlags, indexerToTry: null, out var accessor)
  161. ? accessor
  162. : ConstantValueAccessor.NullAccessor;
  163. }
  164. public object Target => ReferenceType;
  165. }
  166. }