ShadowRealm.cpp 13 KB

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