ErrorConstructor.cs 2.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using Jint.Native.Function;
  3. using Jint.Native.Object;
  4. using Jint.Runtime;
  5. using Jint.Runtime.Descriptors;
  6. namespace Jint.Native.Error
  7. {
  8. public sealed class ErrorConstructor : FunctionInstance, IConstructor
  9. {
  10. private readonly Func<Intrinsics, ObjectInstance> _intrinsicDefaultProto;
  11. internal ErrorConstructor(
  12. Engine engine,
  13. Realm realm,
  14. ObjectInstance functionPrototype,
  15. ObjectInstance objectPrototype,
  16. JsString name, Func<Intrinsics, ObjectInstance> intrinsicDefaultProto)
  17. : base(engine, realm, name)
  18. {
  19. _intrinsicDefaultProto = intrinsicDefaultProto;
  20. _prototype = functionPrototype;
  21. PrototypeObject = new ErrorPrototype(engine, realm, this, objectPrototype, name, ObjectClass.Object);
  22. _length = new PropertyDescriptor(JsNumber.PositiveOne, PropertyFlag.Configurable);
  23. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  24. }
  25. public ErrorPrototype PrototypeObject { get; }
  26. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  27. {
  28. return Construct(arguments, this);
  29. }
  30. public ObjectInstance Construct(JsValue[] arguments)
  31. {
  32. return Construct(arguments, this);
  33. }
  34. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) => Construct(arguments, newTarget);
  35. /// <summary>
  36. /// https://tc39.es/ecma262/#sec-nativeerror
  37. /// </summary>
  38. private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  39. {
  40. var o = OrdinaryCreateFromConstructor(
  41. newTarget,
  42. _intrinsicDefaultProto,
  43. static (engine, realm, state) => new ErrorInstance(engine));
  44. var jsValue = arguments.At(0);
  45. if (!jsValue.IsUndefined())
  46. {
  47. var msg = TypeConverter.ToString(jsValue);
  48. var msgDesc = new PropertyDescriptor(msg, true, false, true);
  49. o.DefinePropertyOrThrow("message", msgDesc);
  50. }
  51. var lastSyntaxNode = _engine.GetLastSyntaxNode();
  52. var stackString = lastSyntaxNode == null ? Undefined : _engine.CallStack.BuildCallStackString(lastSyntaxNode.Location);
  53. var stackDesc = new PropertyDescriptor(stackString, PropertyFlag.NonEnumerable);
  54. o.DefinePropertyOrThrow(CommonProperties.Stack, stackDesc);
  55. var options = arguments.At(1);
  56. if (options is ObjectInstance oi && oi.HasProperty("cause"))
  57. {
  58. var cause = oi.Get("cause");
  59. var causeDesc = new PropertyDescriptor(cause, PropertyFlag.NonEnumerable);
  60. o.DefinePropertyOrThrow("cause", causeDesc);
  61. }
  62. return o;
  63. }
  64. }
  65. }