ShadowRealmConstructor.cs 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. using Jint.Native.Function;
  2. using Jint.Native.Object;
  3. using Jint.Runtime;
  4. using Jint.Runtime.Descriptors;
  5. using Jint.Runtime.Environments;
  6. namespace Jint.Native.ShadowRealm;
  7. /// <summary>
  8. /// https://tc39.es/proposal-shadowrealm/#sec-properties-of-the-shadowRealm-constructor
  9. /// </summary>
  10. public sealed class ShadowRealmConstructor : FunctionInstance, IConstructor
  11. {
  12. private static readonly JsString _functionName = new JsString("ShadowRealm");
  13. internal ShadowRealmConstructor(
  14. Engine engine,
  15. Realm realm,
  16. FunctionPrototype functionPrototype,
  17. ObjectPrototype objectPrototype)
  18. : base(engine, realm, _functionName)
  19. {
  20. _prototype = functionPrototype;
  21. PrototypeObject = new ShadowRealmPrototype(engine, realm, this, objectPrototype);
  22. _length = new PropertyDescriptor(0, PropertyFlag.Configurable);
  23. _prototypeDescriptor = new PropertyDescriptor(PrototypeObject, PropertyFlag.AllForbidden);
  24. }
  25. private ShadowRealmPrototype PrototypeObject { get; }
  26. protected internal override JsValue Call(JsValue thisObject, JsValue[] arguments)
  27. {
  28. ExceptionHelper.ThrowTypeError(_realm, "Constructor ShadowRealm requires 'new'");
  29. return null;
  30. }
  31. public ShadowRealmInstance Construct()
  32. {
  33. return Construct(PrototypeObject);
  34. }
  35. private ShadowRealmInstance Construct(JsValue newTarget)
  36. {
  37. var realmRec = _engine._host.CreateRealm();
  38. var o = OrdinaryCreateFromConstructor(
  39. newTarget,
  40. static intrinsics => intrinsics.ShadowRealm.PrototypeObject,
  41. static (engine, _, realmRec) =>
  42. {
  43. var context = new ExecutionContext(
  44. scriptOrModule: null,
  45. lexicalEnvironment: realmRec!.GlobalEnv,
  46. variableEnvironment: realmRec.GlobalEnv,
  47. privateEnvironment: null,
  48. realm: realmRec,
  49. function: null);
  50. return new ShadowRealmInstance(engine, context, realmRec);
  51. },
  52. realmRec);
  53. // this are currently handled as part of realm construction
  54. // SetRealmGlobalObject(realmRec, Undefined, Undefined);
  55. // SetDefaultGlobalBindings(o._ShadowRealm);
  56. _engine._host.InitializeShadowRealm(o._shadowRealm);
  57. return o;
  58. }
  59. ObjectInstance IConstructor.Construct(JsValue[] arguments, JsValue newTarget)
  60. {
  61. if (newTarget.IsUndefined())
  62. {
  63. ExceptionHelper.ThrowTypeError(_realm);
  64. }
  65. return Construct(newTarget);
  66. }
  67. }