ShadowRealm.cpp 13 KB

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