ShadowRealm.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311
  1. /*
  2. * Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Bytecode/Executable.h>
  7. #include <LibJS/Bytecode/Interpreter.h>
  8. #include <LibJS/Lexer.h>
  9. #include <LibJS/Parser.h>
  10. #include <LibJS/Runtime/AbstractOperations.h>
  11. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  12. #include <LibJS/Runtime/GlobalEnvironment.h>
  13. #include <LibJS/Runtime/ModuleNamespaceObject.h>
  14. #include <LibJS/Runtime/NativeFunction.h>
  15. #include <LibJS/Runtime/PromiseCapability.h>
  16. #include <LibJS/Runtime/PromiseConstructor.h>
  17. #include <LibJS/Runtime/ShadowRealm.h>
  18. #include <LibJS/Runtime/WrappedFunction.h>
  19. namespace JS {
  20. ShadowRealm::ShadowRealm(Realm& shadow_realm, ExecutionContext execution_context, Object& prototype)
  21. : Object(ConstructWithPrototypeTag::Tag, prototype)
  22. , m_shadow_realm(shadow_realm)
  23. , m_execution_context(move(execution_context))
  24. {
  25. }
  26. void ShadowRealm::visit_edges(Visitor& visitor)
  27. {
  28. Base::visit_edges(visitor);
  29. visitor.visit(m_shadow_realm);
  30. }
  31. // 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
  32. ThrowCompletionOr<void> copy_name_and_length(VM& vm, FunctionObject& function, FunctionObject& target, Optional<StringView> prefix, Optional<unsigned> arg_count)
  33. {
  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 = PrimitiveString::create(vm, String {});
  73. // 8. Perform SetFunctionName(F, targetName, prefix).
  74. function.set_function_name({ TRY(target_name.as_string().deprecated_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(VM& vm, StringView source_text, Realm& caller_realm, Realm& eval_realm)
  79. {
  80. // FIXME: Needs to be updated to latest ECMA-262. See: https://github.com/tc39/proposal-shadowrealm/issues/367
  81. // 1. Perform ? HostEnsureCanCompileStrings(callerRealm, evalRealm).
  82. TRY(vm.host_ensure_can_compile_strings(eval_realm));
  83. // 2. Perform the following substeps in an implementation-defined order, possibly interleaving parsing and error detection:
  84. // a. Let script be ParseText(StringToCodePoints(sourceText), Script).
  85. auto parser = Parser(Lexer(source_text), Program::Type::Script, Parser::EvalInitialState {});
  86. auto program = parser.parse_program();
  87. // b. If script is a List of errors, throw a SyntaxError exception.
  88. if (parser.has_errors()) {
  89. auto& error = parser.errors()[0];
  90. return vm.throw_completion<SyntaxError>(TRY_OR_THROW_OOM(vm, error.to_string()));
  91. }
  92. // c. If script Contains ScriptBody is false, return undefined.
  93. if (program->children().is_empty())
  94. return js_undefined();
  95. // d. Let body be the ScriptBody of script.
  96. // e. If body Contains NewTarget is true, throw a SyntaxError exception.
  97. // f. If body Contains SuperProperty is true, throw a SyntaxError exception.
  98. // g. If body Contains SuperCall is true, throw a SyntaxError exception.
  99. // FIXME: Implement these, we probably need a generic way of scanning the AST for certain nodes.
  100. // 3. Let strictEval be IsStrict of script.
  101. auto strict_eval = program->is_strict_mode();
  102. // 4. Let runningContext be the running execution context.
  103. // NOTE: This would be unused due to step 11 and is omitted for that reason.
  104. // 5. Let lexEnv be NewDeclarativeEnvironment(evalRealm.[[GlobalEnv]]).
  105. Environment* lexical_environment = new_declarative_environment(eval_realm.global_environment()).ptr();
  106. // 6. Let varEnv be evalRealm.[[GlobalEnv]].
  107. Environment* variable_environment = &eval_realm.global_environment();
  108. // 7. If strictEval is true, set varEnv to lexEnv.
  109. if (strict_eval)
  110. variable_environment = lexical_environment;
  111. // 8. If runningContext is not already suspended, suspend runningContext.
  112. // NOTE: We don't support this concept yet.
  113. // 9. Let evalContext be a new ECMAScript code execution context.
  114. auto eval_context = ExecutionContext { vm.heap() };
  115. // 10. Set evalContext's Function to null.
  116. eval_context.function = nullptr;
  117. // 11. Set evalContext's Realm to evalRealm.
  118. eval_context.realm = &eval_realm;
  119. // 12. Set evalContext's ScriptOrModule to null.
  120. // Note: This is already the default value.
  121. // 13. Set evalContext's VariableEnvironment to varEnv.
  122. eval_context.variable_environment = variable_environment;
  123. // 14. Set evalContext's LexicalEnvironment to lexEnv.
  124. eval_context.lexical_environment = lexical_environment;
  125. // Non-standard
  126. eval_context.is_strict_mode = strict_eval;
  127. // 15. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  128. TRY(vm.push_execution_context(eval_context, {}));
  129. // 16. Let result be Completion(EvalDeclarationInstantiation(body, varEnv, lexEnv, null, strictEval)).
  130. auto eval_result = eval_declaration_instantiation(vm, program, variable_environment, lexical_environment, nullptr, strict_eval);
  131. Completion result;
  132. // 17. If result.[[Type]] is normal, then
  133. if (!eval_result.is_throw_completion()) {
  134. // a. Set result to the result of evaluating body.
  135. auto maybe_executable = Bytecode::compile(vm, program, FunctionKind::Normal, "ShadowRealmEval"sv);
  136. if (maybe_executable.is_error())
  137. result = maybe_executable.release_error();
  138. else {
  139. auto executable = maybe_executable.release_value();
  140. auto value_and_frame = vm.bytecode_interpreter().run_and_return_frame(eval_realm, *executable, nullptr);
  141. if (value_and_frame.value.is_error()) {
  142. result = value_and_frame.value.release_error();
  143. } else {
  144. // Resulting value is in the accumulator.
  145. result = value_and_frame.frame->registers.at(0).value_or(js_undefined());
  146. }
  147. }
  148. }
  149. // 18. If result.[[Type]] is normal and result.[[Value]] is empty, then
  150. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  151. // a. Set result to NormalCompletion(undefined).
  152. result = normal_completion(js_undefined());
  153. }
  154. // 19. 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. // 20. 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. // 21. If result.[[Type]] is not normal, throw a TypeError exception.
  160. if (result.type() != Completion::Type::Normal)
  161. return vm.throw_completion<TypeError>(ErrorType::ShadowRealmEvaluateAbruptCompletion);
  162. // 22. Return ? GetWrappedValue(callerRealm, result.[[Value]]).
  163. return get_wrapped_value(vm, caller_realm, *result.value());
  164. // NOTE: Also see "Editor's Note" in the spec regarding the TypeError above.
  165. }
  166. // 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
  167. ThrowCompletionOr<Value> shadow_realm_import_value(VM& vm, DeprecatedString specifier_string, DeprecatedString export_name_string, Realm& caller_realm, Realm& eval_realm, ExecutionContext& eval_context)
  168. {
  169. // FIXME: evalRealm isn't being used anywhere in this AO (spec issue)
  170. (void)eval_realm;
  171. auto& realm = *vm.current_realm();
  172. // 1. Assert: evalContext is an execution context associated to a ShadowRealm instance's [[ExecutionContext]].
  173. // 2. Let innerCapability be ! NewPromiseCapability(%Promise%).
  174. auto inner_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  175. // 3. Let runningContext be the running execution context.
  176. // 4. If runningContext is not already suspended, suspend runningContext.
  177. // NOTE: We don't support this concept yet.
  178. // 5. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  179. TRY(vm.push_execution_context(eval_context, {}));
  180. // 6. Perform HostImportModuleDynamically(null, specifierString, innerCapability).
  181. MUST_OR_THROW_OOM(vm.host_import_module_dynamically(Empty {}, ModuleRequest { move(specifier_string) }, inner_capability));
  182. // 7. Suspend evalContext and remove it from the execution context stack.
  183. // NOTE: We don't support this concept yet.
  184. vm.pop_execution_context();
  185. // 8. Resume the context that is now on the top of the execution context stack as the running execution context.
  186. // NOTE: We don't support this concept yet.
  187. // 9. Let steps be the steps of an ExportGetter function as described below.
  188. auto steps = [string = move(export_name_string)](auto& vm) -> ThrowCompletionOr<Value> {
  189. // 1. Assert: exports is a module namespace exotic object.
  190. VERIFY(vm.argument(0).is_object());
  191. auto& exports = vm.argument(0).as_object();
  192. VERIFY(is<ModuleNamespaceObject>(exports));
  193. // 2. Let f be the active function object.
  194. auto function = vm.running_execution_context().function;
  195. // 3. Let string be f.[[ExportNameString]].
  196. // 4. Assert: Type(string) is String.
  197. // 5. Let hasOwn be ? HasOwnProperty(exports, string).
  198. auto has_own = TRY(exports.has_own_property(string));
  199. // 6. If hasOwn is false, throw a TypeError exception.
  200. if (!has_own)
  201. return vm.template throw_completion<TypeError>(ErrorType::MissingRequiredProperty, string);
  202. // 7. Let value be ? Get(exports, string).
  203. auto value = TRY(exports.get(string));
  204. // 8. Let realm be f.[[Realm]].
  205. auto* realm = function->realm();
  206. VERIFY(realm);
  207. // 9. Return ? GetWrappedValue(realm, value).
  208. return get_wrapped_value(vm, *realm, value);
  209. };
  210. // 10. Let onFulfilled be CreateBuiltinFunction(steps, 1, "", « [[ExportNameString]] », callerRealm).
  211. // 11. Set onFulfilled.[[ExportNameString]] to exportNameString.
  212. auto on_fulfilled = NativeFunction::create(realm, move(steps), 1, "", &caller_realm);
  213. // 12. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  214. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  215. // NOTE: Even though the spec tells us to use %ThrowTypeError%, it's not observable if we actually do.
  216. // Throw a nicer TypeError forwarding the import error message instead (we know the argument is an Error object).
  217. auto throw_type_error = NativeFunction::create(realm, {}, [](auto& vm) -> ThrowCompletionOr<Value> {
  218. return vm.template throw_completion<TypeError>(vm.argument(0).as_object().get_without_side_effects(vm.names.message).as_string().utf8_string());
  219. });
  220. // 13. Return PerformPromiseThen(innerCapability.[[Promise]], onFulfilled, callerRealm.[[Intrinsics]].[[%ThrowTypeError%]], promiseCapability).
  221. return verify_cast<Promise>(inner_capability->promise().ptr())->perform_then(on_fulfilled, throw_type_error, promise_capability);
  222. }
  223. // 3.1.5 GetWrappedValue ( callerRealm: a Realm Record, value: unknown, ), https://tc39.es/proposal-shadowrealm/#sec-getwrappedvalue
  224. ThrowCompletionOr<Value> get_wrapped_value(VM& vm, Realm& caller_realm, Value value)
  225. {
  226. auto& realm = *vm.current_realm();
  227. // 1. If Type(value) is Object, then
  228. if (value.is_object()) {
  229. // a. If IsCallable(value) is false, throw a TypeError exception.
  230. if (!value.is_function())
  231. return vm.throw_completion<TypeError>(ErrorType::ShadowRealmWrappedValueNonFunctionObject, value);
  232. // b. Return ? WrappedFunctionCreate(callerRealm, value).
  233. return TRY(WrappedFunction::create(realm, caller_realm, value.as_function()));
  234. }
  235. // 2. Return value.
  236. return value;
  237. }
  238. }