ShadowRealm.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315
  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. JS_DEFINE_ALLOCATOR(ShadowRealm);
  21. ShadowRealm::ShadowRealm(Realm& shadow_realm, NonnullOwnPtr<ExecutionContext> execution_context, Object& prototype)
  22. : Object(ConstructWithPrototypeTag::Tag, prototype)
  23. , m_shadow_realm(shadow_realm)
  24. , m_execution_context(move(execution_context))
  25. {
  26. }
  27. void ShadowRealm::visit_edges(Visitor& visitor)
  28. {
  29. Base::visit_edges(visitor);
  30. visitor.visit(m_shadow_realm);
  31. }
  32. // 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
  33. ThrowCompletionOr<void> copy_name_and_length(VM& vm, FunctionObject& function, FunctionObject& target, Optional<StringView> prefix, Optional<unsigned> arg_count)
  34. {
  35. // 1. If argCount is undefined, then set argCount to 0.
  36. if (!arg_count.has_value())
  37. arg_count = 0;
  38. // 2. Let L be 0.
  39. double length = 0;
  40. // 3. Let targetHasLength be ? HasOwnProperty(Target, "length").
  41. auto target_has_length = TRY(target.has_own_property(vm.names.length));
  42. // 4. If targetHasLength is true, then
  43. if (target_has_length) {
  44. // a. Let targetLen be ? Get(Target, "length").
  45. auto target_length = TRY(target.get(vm.names.length));
  46. // b. If Type(targetLen) is Number, then
  47. if (target_length.is_number()) {
  48. // i. If targetLen is +∞𝔽, set L to +∞.
  49. if (target_length.is_positive_infinity()) {
  50. length = target_length.as_double();
  51. }
  52. // ii. Else if targetLen is -∞𝔽, set L to 0.
  53. else if (target_length.is_negative_infinity()) {
  54. length = 0;
  55. }
  56. // iii. Else,
  57. else {
  58. // 1. Let targetLenAsInt be ! ToIntegerOrInfinity(targetLen).
  59. auto target_length_as_int = MUST(target_length.to_integer_or_infinity(vm));
  60. // 2. Assert: targetLenAsInt is finite.
  61. VERIFY(!isinf(target_length_as_int));
  62. // 3. Set L to max(targetLenAsInt - argCount, 0).
  63. length = max(target_length_as_int - *arg_count, 0);
  64. }
  65. }
  66. }
  67. // 5. Perform SetFunctionLength(F, L).
  68. function.set_function_length(length);
  69. // 6. Let targetName be ? Get(Target, "name").
  70. auto target_name = TRY(target.get(vm.names.name));
  71. // 7. If Type(targetName) is not String, set targetName to the empty String.
  72. if (!target_name.is_string())
  73. target_name = PrimitiveString::create(vm, String {});
  74. // 8. Perform SetFunctionName(F, targetName, prefix).
  75. function.set_function_name({ target_name.as_string().byte_string() }, move(prefix));
  76. return {};
  77. }
  78. // 3.1.3 PerformShadowRealmEval ( sourceText: a String, callerRealm: a Realm Record, evalRealm: a Realm Record, ), https://tc39.es/proposal-shadowrealm/#sec-performshadowrealmeval
  79. ThrowCompletionOr<Value> perform_shadow_realm_eval(VM& vm, StringView source_text, Realm& caller_realm, Realm& eval_realm)
  80. {
  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), Program::Type::Script, Parser::EvalInitialState {});
  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>(TRY_OR_THROW_OOM(vm, 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()).ptr();
  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::create(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, {}));
  130. // 16. Let result be Completion(EvalDeclarationInstantiation(body, varEnv, lexEnv, null, strictEval)).
  131. auto eval_result = eval_declaration_instantiation(vm, 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. // a. Set result to the result of evaluating body.
  136. auto maybe_executable = Bytecode::compile(vm, program, {}, FunctionKind::Normal, "ShadowRealmEval"sv);
  137. if (maybe_executable.is_error())
  138. result = maybe_executable.release_error();
  139. else {
  140. auto executable = maybe_executable.release_value();
  141. auto value_and_frame = vm.bytecode_interpreter().run_and_return_frame(*executable, nullptr);
  142. if (value_and_frame.value.is_error()) {
  143. result = value_and_frame.value.release_error();
  144. } else {
  145. // Resulting value is in the accumulator.
  146. result = value_and_frame.frame->registers()[0].value_or(js_undefined());
  147. }
  148. }
  149. }
  150. // 18. If result.[[Type]] is normal and result.[[Value]] is empty, then
  151. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  152. // a. Set result to NormalCompletion(undefined).
  153. result = normal_completion(js_undefined());
  154. }
  155. // 19. Suspend evalContext and remove it from the execution context stack.
  156. // NOTE: We don't support this concept yet.
  157. vm.pop_execution_context();
  158. // 20. Resume the context that is now on the top of the execution context stack as the running execution context.
  159. // NOTE: We don't support this concept yet.
  160. // 21. If result.[[Type]] is not normal, throw a TypeError exception.
  161. if (result.type() != Completion::Type::Normal)
  162. return vm.throw_completion<TypeError>(ErrorType::ShadowRealmEvaluateAbruptCompletion);
  163. // 22. Return ? GetWrappedValue(callerRealm, result.[[Value]]).
  164. return get_wrapped_value(vm, caller_realm, *result.value());
  165. // NOTE: Also see "Editor's Note" in the spec regarding the TypeError above.
  166. }
  167. // 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
  168. ThrowCompletionOr<Value> shadow_realm_import_value(VM& vm, ByteString specifier_string, ByteString export_name_string, Realm& caller_realm, Realm& eval_realm, ExecutionContext& eval_context)
  169. {
  170. // FIXME: evalRealm isn't being used anywhere in this AO (spec issue)
  171. (void)eval_realm;
  172. auto& realm = *vm.current_realm();
  173. // 1. Assert: evalContext is an execution context associated to a ShadowRealm instance's [[ExecutionContext]].
  174. // 2. Let innerCapability be ! NewPromiseCapability(%Promise%).
  175. auto inner_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  176. // 3. Let runningContext be the running execution context.
  177. // 4. If runningContext is not already suspended, suspend runningContext.
  178. // NOTE: We don't support this concept yet.
  179. // 5. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  180. TRY(vm.push_execution_context(eval_context, {}));
  181. // 6. Let referrer be the Realm component of evalContext.
  182. auto referrer = JS::NonnullGCPtr { *eval_context.realm };
  183. // 7. Perform HostLoadImportedModule(referrer, specifierString, empty, innerCapability).
  184. vm.host_load_imported_module(referrer, ModuleRequest { specifier_string }, nullptr, inner_capability);
  185. // 7. Suspend evalContext and remove it from the execution context stack.
  186. // NOTE: We don't support this concept yet.
  187. vm.pop_execution_context();
  188. // 8. Resume the context that is now on the top of the execution context stack as the running execution context.
  189. // NOTE: We don't support this concept yet.
  190. // 9. Let steps be the steps of an ExportGetter function as described below.
  191. auto steps = [string = move(export_name_string)](auto& vm) -> ThrowCompletionOr<Value> {
  192. // 1. Assert: exports is a module namespace exotic object.
  193. VERIFY(vm.argument(0).is_object());
  194. auto& exports = vm.argument(0).as_object();
  195. VERIFY(is<ModuleNamespaceObject>(exports));
  196. // 2. Let f be the active function object.
  197. auto function = vm.running_execution_context().function;
  198. // 3. Let string be f.[[ExportNameString]].
  199. // 4. Assert: Type(string) is String.
  200. // 5. Let hasOwn be ? HasOwnProperty(exports, string).
  201. auto has_own = TRY(exports.has_own_property(string));
  202. // 6. If hasOwn is false, throw a TypeError exception.
  203. if (!has_own)
  204. return vm.template throw_completion<TypeError>(ErrorType::MissingRequiredProperty, string);
  205. // 7. Let value be ? Get(exports, string).
  206. auto value = TRY(exports.get(string));
  207. // 8. Let realm be f.[[Realm]].
  208. auto* realm = function->realm();
  209. VERIFY(realm);
  210. // 9. Return ? GetWrappedValue(realm, value).
  211. return get_wrapped_value(vm, *realm, value);
  212. };
  213. // 10. Let onFulfilled be CreateBuiltinFunction(steps, 1, "", « [[ExportNameString]] », callerRealm).
  214. // 11. Set onFulfilled.[[ExportNameString]] to exportNameString.
  215. auto on_fulfilled = NativeFunction::create(realm, move(steps), 1, "", &caller_realm);
  216. // 12. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  217. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  218. // NOTE: Even though the spec tells us to use %ThrowTypeError%, it's not observable if we actually do.
  219. // Throw a nicer TypeError forwarding the import error message instead (we know the argument is an Error object).
  220. auto throw_type_error = NativeFunction::create(realm, {}, [](auto& vm) -> ThrowCompletionOr<Value> {
  221. return vm.template throw_completion<TypeError>(vm.argument(0).as_object().get_without_side_effects(vm.names.message).as_string().utf8_string());
  222. });
  223. // 13. Return PerformPromiseThen(innerCapability.[[Promise]], onFulfilled, callerRealm.[[Intrinsics]].[[%ThrowTypeError%]], promiseCapability).
  224. return verify_cast<Promise>(inner_capability->promise().ptr())->perform_then(on_fulfilled, throw_type_error, promise_capability);
  225. }
  226. // 3.1.5 GetWrappedValue ( callerRealm: a Realm Record, value: unknown, ), https://tc39.es/proposal-shadowrealm/#sec-getwrappedvalue
  227. ThrowCompletionOr<Value> get_wrapped_value(VM& vm, Realm& caller_realm, Value value)
  228. {
  229. auto& realm = *vm.current_realm();
  230. // 1. If Type(value) is Object, then
  231. if (value.is_object()) {
  232. // a. If IsCallable(value) is false, throw a TypeError exception.
  233. if (!value.is_function())
  234. return vm.throw_completion<TypeError>(ErrorType::ShadowRealmWrappedValueNonFunctionObject, value);
  235. // b. Return ? WrappedFunctionCreate(callerRealm, value).
  236. return TRY(WrappedFunction::create(realm, caller_realm, value.as_function()));
  237. }
  238. // 2. Return value.
  239. return value;
  240. }
  241. }