ErrorConstructor.cs 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 JsString _name;
  10. private static readonly JsString _functionName = new JsString("Error");
  11. public ErrorConstructor(Engine engine, JsString functionName) : base(engine, functionName)
  12. {
  13. }
  14. public static ErrorConstructor CreateErrorConstructor(Engine engine, JsString name)
  15. {
  16. var obj = new ErrorConstructor(engine, name)
  17. {
  18. _name = name,
  19. _prototype = engine.Function.PrototypeObject
  20. };
  21. // The value of the [[Prototype]] internal property of the Error constructor is the Function prototype object (15.11.3)
  22. obj.PrototypeObject = ErrorPrototype.CreatePrototypeObject(engine, obj, name);
  23. obj._length = PropertyDescriptor.AllForbiddenDescriptor.NumberOne;
  24. // The initial value of Error.prototype is the Error prototype object
  25. obj._prototypeDescriptor = new PropertyDescriptor(obj.PrototypeObject, PropertyFlag.AllForbidden);
  26. return obj;
  27. }
  28. public override JsValue Call(JsValue thisObject, JsValue[] arguments)
  29. {
  30. return Construct(arguments, thisObject);
  31. }
  32. public ObjectInstance Construct(JsValue[] arguments)
  33. {
  34. return Construct(arguments, this);
  35. }
  36. public ObjectInstance Construct(JsValue[] arguments, JsValue newTarget)
  37. {
  38. var o = OrdinaryCreateFromConstructor(
  39. newTarget,
  40. PrototypeObject,
  41. static (e, state) => new ErrorInstance(e, (JsString) state),
  42. _name);
  43. var jsValue = arguments.At(0);
  44. if (!jsValue.IsUndefined())
  45. {
  46. var msg = TypeConverter.ToString(jsValue);
  47. var msgDesc = new PropertyDescriptor(msg, true, false, true);
  48. o.DefinePropertyOrThrow("message", msgDesc);
  49. }
  50. var lastSyntaxNode = _engine.GetLastSyntaxNode();
  51. var stackString = lastSyntaxNode == null ? Undefined : _engine.CallStack.BuildCallStackString(lastSyntaxNode.Location);
  52. var stackDesc = new PropertyDescriptor(stackString, true, false, true);
  53. o.DefinePropertyOrThrow(CommonProperties.Stack, stackDesc);
  54. return o;
  55. }
  56. public ErrorPrototype PrototypeObject { get; private set; }
  57. protected internal override ObjectInstance GetPrototypeOf()
  58. {
  59. return _name._value != "Error" ? _engine.Error : _prototype;
  60. }
  61. }
  62. }