ShadowRealm.cpp 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Lexer.h>
  7. #include <LibJS/Parser.h>
  8. #include <LibJS/Runtime/AbstractOperations.h>
  9. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  10. #include <LibJS/Runtime/ModuleNamespaceObject.h>
  11. #include <LibJS/Runtime/NativeFunction.h>
  12. #include <LibJS/Runtime/PromiseConstructor.h>
  13. #include <LibJS/Runtime/PromiseReaction.h>
  14. #include <LibJS/Runtime/ShadowRealm.h>
  15. #include <LibJS/Runtime/WrappedFunction.h>
  16. namespace JS {
  17. ShadowRealm::ShadowRealm(Realm& shadow_realm, ExecutionContext execution_context, Object& prototype)
  18. : Object(prototype)
  19. , m_shadow_realm(shadow_realm)
  20. , m_execution_context(move(execution_context))
  21. {
  22. }
  23. void ShadowRealm::visit_edges(Visitor& visitor)
  24. {
  25. Base::visit_edges(visitor);
  26. visitor.visit(&m_shadow_realm);
  27. }
  28. // 3.1.1 PerformShadowRealmEval ( sourceText, callerRealm, evalRealm ), https://tc39.es/proposal-shadowrealm/#sec-performshadowrealmeval
  29. ThrowCompletionOr<Value> perform_shadow_realm_eval(GlobalObject& global_object, StringView source_text, Realm& caller_realm, Realm& eval_realm)
  30. {
  31. auto& vm = global_object.vm();
  32. // 1. Assert: Type(sourceText) is String.
  33. // 2. Assert: callerRealm is a Realm Record.
  34. // 3. Assert: evalRealm is a Realm Record.
  35. // 4. Perform ? HostEnsureCanCompileStrings(callerRealm, evalRealm).
  36. // FIXME: We don't have this host-defined abstract operation yet.
  37. // 5. Perform the following substeps in an implementation-defined order, possibly interleaving parsing and error detection:
  38. // a. Let script be ParseText(! StringToCodePoints(sourceText), Script).
  39. auto parser = Parser(Lexer(source_text));
  40. auto program = parser.parse_program();
  41. // b. If script is a List of errors, throw a SyntaxError exception.
  42. if (parser.has_errors()) {
  43. auto& error = parser.errors()[0];
  44. return vm.throw_completion<JS::SyntaxError>(global_object, error.to_string());
  45. }
  46. // c. If script Contains ScriptBody is false, return undefined.
  47. if (program->children().is_empty())
  48. return js_undefined();
  49. // d. Let body be the ScriptBody of script.
  50. // e. If body Contains NewTarget is true, throw a SyntaxError exception.
  51. // f. If body Contains SuperProperty is true, throw a SyntaxError exception.
  52. // g. If body Contains SuperCall is true, throw a SyntaxError exception.
  53. // FIXME: Implement these, we probably need a generic way of scanning the AST for certain nodes.
  54. // 6. Let strictEval be IsStrict of script.
  55. auto strict_eval = program->is_strict_mode();
  56. // 7. Let runningContext be the running execution context.
  57. // NOTE: This would be unused due to step 11 and is omitted for that reason.
  58. // 8. Let lexEnv be NewDeclarativeEnvironment(evalRealm.[[GlobalEnv]]).
  59. Environment* lexical_environment = new_declarative_environment(eval_realm.global_environment());
  60. // 9. Let varEnv be evalRealm.[[GlobalEnv]].
  61. Environment* variable_environment = &eval_realm.global_environment();
  62. // 10. If strictEval is true, set varEnv to lexEnv.
  63. if (strict_eval)
  64. variable_environment = lexical_environment;
  65. // 11. If runningContext is not already suspended, suspend runningContext.
  66. // NOTE: We don't support this concept yet.
  67. // 12. Let evalContext be a new ECMAScript code execution context.
  68. auto eval_context = ExecutionContext { vm.heap() };
  69. // 13. Set evalContext's Function to null.
  70. eval_context.function = nullptr;
  71. // 14. Set evalContext's Realm to evalRealm.
  72. eval_context.realm = &eval_realm;
  73. // 15. Set evalContext's ScriptOrModule to null.
  74. // Note: This is already the default value.
  75. // 16. Set evalContext's VariableEnvironment to varEnv.
  76. eval_context.variable_environment = variable_environment;
  77. // 17. Set evalContext's LexicalEnvironment to lexEnv.
  78. eval_context.lexical_environment = lexical_environment;
  79. // Non-standard
  80. eval_context.is_strict_mode = strict_eval;
  81. // 18. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  82. TRY(vm.push_execution_context(eval_context, eval_realm.global_object()));
  83. // 19. Let result be EvalDeclarationInstantiation(body, varEnv, lexEnv, null, strictEval).
  84. auto eval_result = eval_declaration_instantiation(vm, eval_realm.global_object(), program, variable_environment, lexical_environment, nullptr, strict_eval);
  85. Completion result;
  86. // 20. If result.[[Type]] is normal, then
  87. if (!eval_result.is_throw_completion()) {
  88. // TODO: Optionally use bytecode interpreter?
  89. // a. Set result to the result of evaluating body.
  90. result = program->execute(vm.interpreter(), eval_realm.global_object());
  91. }
  92. // 21. If result.[[Type]] is normal and result.[[Value]] is empty, then
  93. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  94. // a. Set result to NormalCompletion(undefined).
  95. result = normal_completion(js_undefined());
  96. }
  97. // 22. Suspend evalContext and remove it from the execution context stack.
  98. // NOTE: We don't support this concept yet.
  99. vm.pop_execution_context();
  100. // 23. Resume the context that is now on the top of the execution context stack as the running execution context.
  101. // NOTE: We don't support this concept yet.
  102. // 24. If result.[[Type]] is not normal, throw a TypeError exception.
  103. if (result.type() != Completion::Type::Normal)
  104. return vm.throw_completion<TypeError>(global_object, ErrorType::ShadowRealmEvaluateAbruptCompletion);
  105. // 25. Return ? GetWrappedValue(callerRealm, result.[[Value]]).
  106. return get_wrapped_value(global_object, caller_realm, *result.value());
  107. // NOTE: Also see "Editor's Note" in the spec regarding the TypeError above.
  108. }
  109. // 3.1.2 ShadowRealmImportValue ( specifierString, exportNameString, callerRealm, evalRealm, evalContext ), https://tc39.es/proposal-shadowrealm/#sec-shadowrealmimportvalue
  110. ThrowCompletionOr<Value> shadow_realm_import_value(GlobalObject& global_object, String specifier_string, String export_name_string, Realm& caller_realm, Realm& eval_realm, ExecutionContext& eval_context)
  111. {
  112. auto& vm = global_object.vm();
  113. // 1. Assert: Type(specifierString) is String.
  114. // 2. Assert: Type(exportNameString) is String.
  115. // 3. Assert: callerRealm is a Realm Record.
  116. // 4. Assert: evalRealm is a Realm Record.
  117. // 5. Assert: evalContext is an execution context associated to a ShadowRealm instance's [[ExecutionContext]].
  118. // 6. Let innerCapability be ! NewPromiseCapability(%Promise%).
  119. auto inner_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor()));
  120. // 7. Let runningContext be the running execution context.
  121. // 8. If runningContext is not already suspended, suspend runningContext.
  122. // NOTE: We don't support this concept yet.
  123. // 9. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  124. TRY(vm.push_execution_context(eval_context, eval_realm.global_object()));
  125. // 10. Perform ! HostImportModuleDynamically(null, specifierString, innerCapability).
  126. vm.host_import_module_dynamically(Empty {}, ModuleRequest { move(specifier_string) }, inner_capability);
  127. // 11. Suspend evalContext and remove it from the execution context stack.
  128. // NOTE: We don't support this concept yet.
  129. vm.pop_execution_context();
  130. // 12. Resume the context that is now on the top of the execution context stack as the running execution context.
  131. // NOTE: We don't support this concept yet.
  132. // 13. Let steps be the steps of an ExportGetter function as described below.
  133. // 14. Let onFulfilled be ! CreateBuiltinFunction(steps, 1, "", « [[ExportNameString]] », callerRealm).
  134. // 15. Set onFulfilled.[[ExportNameString]] to exportNameString.
  135. // FIXME: Support passing a realm to NativeFunction::create()
  136. (void)caller_realm;
  137. auto* on_fulfilled = NativeFunction::create(
  138. global_object,
  139. "",
  140. [string = move(export_name_string)](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
  141. // 1. Assert: exports is a module namespace exotic object.
  142. VERIFY(vm.argument(0).is_object());
  143. auto& exports = vm.argument(0).as_object();
  144. VERIFY(is<ModuleNamespaceObject>(exports));
  145. // 2. Let f be the active function object.
  146. auto* function = vm.running_execution_context().function;
  147. // 3. Let string be f.[[ExportNameString]].
  148. // 4. Assert: Type(string) is String.
  149. // 5. Let hasOwn be ? HasOwnProperty(exports, string).
  150. auto has_own = TRY(exports.has_own_property(string));
  151. // 6. If hasOwn is false, throw a TypeError exception.
  152. if (!has_own)
  153. return vm.template throw_completion<TypeError>(global_object, ErrorType::MissingRequiredProperty, string);
  154. // 7. Let value be ? Get(exports, string).
  155. auto value = TRY(exports.get(string));
  156. // 8. Let realm be f.[[Realm]].
  157. auto* realm = function->realm();
  158. VERIFY(realm);
  159. // 9. Return ? GetWrappedValue(realm, value).
  160. return get_wrapped_value(global_object, *realm, value);
  161. });
  162. on_fulfilled->define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  163. on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  164. // 16. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  165. auto promise_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor()));
  166. // NOTE: Even though the spec tells us to use %ThrowTypeError%, it's not observable if we actually do.
  167. // Throw a nicer TypeError forwarding the import error message instead (we know the argument is an Error object).
  168. auto* throw_type_error = NativeFunction::create(global_object, {}, [](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
  169. return vm.template throw_completion<TypeError>(global_object, vm.argument(0).as_object().get_without_side_effects(vm.names.message).as_string().string());
  170. });
  171. // 17. Return ! PerformPromiseThen(innerCapability.[[Promise]], onFulfilled, callerRealm.[[Intrinsics]].[[%ThrowTypeError%]], promiseCapability).
  172. return verify_cast<Promise>(inner_capability.promise)->perform_then(on_fulfilled, throw_type_error, promise_capability);
  173. }
  174. // 3.1.3 GetWrappedValue ( callerRealm, value ), https://tc39.es/proposal-shadowrealm/#sec-getwrappedvalue
  175. ThrowCompletionOr<Value> get_wrapped_value(GlobalObject& global_object, Realm& caller_realm, Value value)
  176. {
  177. auto& vm = global_object.vm();
  178. // 1. Assert: callerRealm is a Realm Record.
  179. // 2. If Type(value) is Object, then
  180. if (value.is_object()) {
  181. // a. If IsCallable(value) is false, throw a TypeError exception.
  182. if (!value.is_function())
  183. return vm.throw_completion<TypeError>(global_object, ErrorType::ShadowRealmWrappedValueNonFunctionObject, value);
  184. // b. Return ! WrappedFunctionCreate(callerRealm, value).
  185. return WrappedFunction::create(global_object, caller_realm, value.as_function());
  186. }
  187. // 3. Return value.
  188. return value;
  189. }
  190. }