ErrorConstructor.cs 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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, (JsString) state),
  39. _name);
  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. return o;
  52. }
  53. }
  54. }