ClrFunctionInstance.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. using System.Runtime.ExceptionServices;
  2. using Jint.Native;
  3. using Jint.Native.Function;
  4. using Jint.Runtime.Descriptors;
  5. namespace Jint.Runtime.Interop
  6. {
  7. /// <summary>
  8. /// Wraps a Clr method into a FunctionInstance
  9. /// </summary>
  10. public sealed class ClrFunctionInstance : FunctionInstance, IEquatable<ClrFunctionInstance>
  11. {
  12. internal readonly Func<JsValue, JsValue[], JsValue> _func;
  13. public ClrFunctionInstance(
  14. Engine engine,
  15. string name,
  16. Func<JsValue, JsValue[], JsValue> func,
  17. int length = 0,
  18. PropertyFlag lengthFlags = PropertyFlag.AllForbidden)
  19. : base(engine, engine.Realm, new JsString(name))
  20. {
  21. _func = func;
  22. _prototype = engine._originalIntrinsics.Function.PrototypeObject;
  23. _length = lengthFlags == PropertyFlag.AllForbidden
  24. ? PropertyDescriptor.AllForbiddenDescriptor.ForNumber(length)
  25. : new PropertyDescriptor(JsNumber.Create(length), lengthFlags);
  26. }
  27. protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments)
  28. {
  29. try
  30. {
  31. return _func(thisObject, arguments);
  32. }
  33. catch (Exception e) when (e is not JavaScriptException)
  34. {
  35. if (_engine.Options.Interop.ExceptionHandler(e))
  36. {
  37. ExceptionHelper.ThrowJavaScriptException(_realm.Intrinsics.Error, e.Message);
  38. }
  39. else
  40. {
  41. ExceptionDispatchInfo.Capture(e).Throw();
  42. }
  43. return Undefined;
  44. }
  45. }
  46. public override bool Equals(JsValue? obj)
  47. {
  48. return Equals(obj as ClrFunctionInstance);
  49. }
  50. public bool Equals(ClrFunctionInstance? other)
  51. {
  52. if (ReferenceEquals(null, other))
  53. {
  54. return false;
  55. }
  56. if (ReferenceEquals(this, other))
  57. {
  58. return true;
  59. }
  60. if (_func == other._func)
  61. {
  62. return true;
  63. }
  64. return false;
  65. }
  66. }
  67. }