ErrorConstructor.cs 2.5 KB

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