ErrorConstructor.cs 2.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  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. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget) => Construct(arguments, newTarget);
  34. private ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  35. {
  36. var o = OrdinaryCreateFromConstructor(
  37. newTarget,
  38. static intrinsics => intrinsics.Error.PrototypeObject,
  39. static (engine, realm, state) => new ErrorInstance(engine));
  40. var jsValue = arguments.At(0);
  41. if (!jsValue.IsUndefined())
  42. {
  43. var msg = TypeConverter.ToString(jsValue);
  44. var msgDesc = new PropertyDescriptor(msg, true, false, true);
  45. o.DefinePropertyOrThrow("message", msgDesc);
  46. }
  47. var lastSyntaxNode = _engine.GetLastSyntaxNode();
  48. var stackString = lastSyntaxNode == null ? Undefined : _engine.CallStack.BuildCallStackString(lastSyntaxNode.Location);
  49. var stackDesc = new PropertyDescriptor(stackString, PropertyFlag.NonEnumerable);
  50. o.DefinePropertyOrThrow(CommonProperties.Stack, stackDesc);
  51. var options = arguments.At(1);
  52. if (options is ObjectInstance oi && oi.HasProperty("cause"))
  53. {
  54. var cause = oi.Get("cause");
  55. var causeDesc = new PropertyDescriptor(cause, PropertyFlag.NonEnumerable);
  56. o.DefinePropertyOrThrow("cause", causeDesc);
  57. }
  58. return o;
  59. }
  60. }
  61. }