ShadowRealm.cpp 13 KB

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