ShadowRealm.cpp 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331
  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. GC_DEFINE_ALLOCATOR(ShadowRealm);
  21. ShadowRealm::ShadowRealm(Object& prototype)
  22. : Object(ConstructWithPrototypeTag::Tag, prototype)
  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 = PrimitiveString::create(vm, String {});
  72. // 8. Perform SetFunctionName(F, targetName, prefix).
  73. function.set_function_name({ target_name.as_string().byte_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. // 1. Perform ? HostEnsureCanCompileStrings(evalRealm, « », sourceText, false).
  80. TRY(vm.host_ensure_can_compile_strings(eval_realm, {}, source_text, EvalMode::Indirect));
  81. // 2. Perform the following substeps in an implementation-defined order, possibly interleaving parsing and error detection:
  82. // a. Let script be ParseText(StringToCodePoints(sourceText), Script).
  83. auto parser = Parser(Lexer(source_text), Program::Type::Script, Parser::EvalInitialState {});
  84. auto program = parser.parse_program();
  85. // b. If script is a List of errors, throw a SyntaxError exception.
  86. if (parser.has_errors()) {
  87. auto& error = parser.errors()[0];
  88. return vm.throw_completion<SyntaxError>(error.to_string());
  89. }
  90. // c. If script Contains ScriptBody is false, return undefined.
  91. if (program->children().is_empty())
  92. return js_undefined();
  93. // d. Let body be the ScriptBody of script.
  94. // e. If body Contains NewTarget is true, throw a SyntaxError exception.
  95. // f. If body Contains SuperProperty is true, throw a SyntaxError exception.
  96. // g. If body Contains SuperCall is true, throw a SyntaxError exception.
  97. // FIXME: Implement these, we probably need a generic way of scanning the AST for certain nodes.
  98. // 3. Let strictEval be IsStrict of script.
  99. auto strict_eval = program->is_strict_mode();
  100. // 4. Let runningContext be the running execution context.
  101. // 5. If runningContext is not already suspended, suspend runningContext.
  102. // NOTE: This would be unused due to step 9 and is omitted for that reason.
  103. // 6. Let evalContext be GetShadowRealmContext(evalRealm, strictEval).
  104. auto eval_context = get_shadow_realm_context(eval_realm, strict_eval);
  105. // 7. Let lexEnv be evalContext's LexicalEnvironment.
  106. auto lexical_environment = eval_context->lexical_environment;
  107. // 8. Let varEnv be evalContext's VariableEnvironment.
  108. auto variable_environment = eval_context->variable_environment;
  109. // 9. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  110. TRY(vm.push_execution_context(*eval_context, {}));
  111. // 10. Let result be Completion(EvalDeclarationInstantiation(body, varEnv, lexEnv, null, strictEval)).
  112. auto eval_result = eval_declaration_instantiation(vm, program, variable_environment, lexical_environment, nullptr, strict_eval);
  113. Completion result;
  114. // 11. If result.[[Type]] is normal, then
  115. if (!eval_result.is_throw_completion()) {
  116. // a. Set result to the result of evaluating body.
  117. auto maybe_executable = Bytecode::compile(vm, program, FunctionKind::Normal, "ShadowRealmEval"sv);
  118. if (maybe_executable.is_error()) {
  119. result = maybe_executable.release_error();
  120. } else {
  121. auto executable = maybe_executable.release_value();
  122. auto result_and_return_register = vm.bytecode_interpreter().run_executable(*executable, {});
  123. if (result_and_return_register.value.is_error()) {
  124. result = result_and_return_register.value.release_error();
  125. } else {
  126. // Resulting value is in the accumulator.
  127. result = result_and_return_register.return_register_value.value_or(js_undefined());
  128. }
  129. }
  130. }
  131. // 12. If result.[[Type]] is normal and result.[[Value]] is empty, then
  132. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  133. // a. Set result to NormalCompletion(undefined).
  134. result = normal_completion(js_undefined());
  135. }
  136. // 13. Suspend evalContext and remove it from the execution context stack.
  137. // NOTE: We don't support this concept yet.
  138. vm.pop_execution_context();
  139. // 14. Resume the context that is now on the top of the execution context stack as the running execution context.
  140. // NOTE: We don't support this concept yet.
  141. // 15. If result.[[Type]] is not normal, then
  142. if (result.type() != Completion::Type::Normal) {
  143. // a. Let copiedError be CreateTypeErrorCopy(callerRealm, result.[[Value]]).
  144. // b. Return ThrowCompletion(copiedError).
  145. return vm.throw_completion<TypeError>(ErrorType::ShadowRealmEvaluateAbruptCompletion);
  146. }
  147. // 16. Return ? GetWrappedValue(callerRealm, result.[[Value]]).
  148. return get_wrapped_value(vm, caller_realm, *result.value());
  149. // NOTE: Also see "Editor's Note" in the spec regarding the TypeError above.
  150. }
  151. // 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
  152. ThrowCompletionOr<Value> shadow_realm_import_value(VM& vm, ByteString specifier_string, ByteString export_name_string, Realm& caller_realm, Realm& eval_realm)
  153. {
  154. auto& realm = *vm.current_realm();
  155. // 1. Let evalContext be GetShadowRealmContext(evalRealm, true).
  156. auto eval_context = get_shadow_realm_context(eval_realm, true);
  157. // 2. Let innerCapability be ! NewPromiseCapability(%Promise%).
  158. auto inner_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  159. // 3. Let runningContext be the running execution context.
  160. // 4. If runningContext is not already suspended, suspend runningContext.
  161. // NOTE: We don't support this concept yet.
  162. // 5. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  163. TRY(vm.push_execution_context(*eval_context, {}));
  164. // 6. Let referrer be the Realm component of evalContext.
  165. auto referrer = GC::Ref { *eval_context->realm };
  166. // 7. Perform HostLoadImportedModule(referrer, specifierString, empty, innerCapability).
  167. vm.host_load_imported_module(referrer, ModuleRequest { specifier_string }, nullptr, inner_capability);
  168. // 7. Suspend evalContext and remove it from the execution context stack.
  169. // NOTE: We don't support this concept yet.
  170. vm.pop_execution_context();
  171. // 8. Resume the context that is now on the top of the execution context stack as the running execution context.
  172. // NOTE: We don't support this concept yet.
  173. // 9. Let steps be the steps of an ExportGetter function as described below.
  174. auto steps = [string = move(export_name_string)](auto& vm) -> ThrowCompletionOr<Value> {
  175. // 1. Assert: exports is a module namespace exotic object.
  176. VERIFY(vm.argument(0).is_object());
  177. auto& exports = vm.argument(0).as_object();
  178. VERIFY(is<ModuleNamespaceObject>(exports));
  179. // 2. Let f be the active function object.
  180. auto function = vm.running_execution_context().function;
  181. // 3. Let string be f.[[ExportNameString]].
  182. // 4. Assert: Type(string) is String.
  183. // 5. Let hasOwn be ? HasOwnProperty(exports, string).
  184. auto has_own = TRY(exports.has_own_property(string));
  185. // 6. If hasOwn is false, throw a TypeError exception.
  186. if (!has_own)
  187. return vm.template throw_completion<TypeError>(ErrorType::MissingRequiredProperty, string);
  188. // 7. Let value be ? Get(exports, string).
  189. auto value = TRY(exports.get(string));
  190. // 8. Let realm be f.[[Realm]].
  191. auto* realm = function->realm();
  192. VERIFY(realm);
  193. // 9. Return ? GetWrappedValue(realm, value).
  194. return get_wrapped_value(vm, *realm, value);
  195. };
  196. // 10. Let onFulfilled be CreateBuiltinFunction(steps, 1, "", « [[ExportNameString]] », callerRealm).
  197. // 11. Set onFulfilled.[[ExportNameString]] to exportNameString.
  198. auto on_fulfilled = NativeFunction::create(realm, move(steps), 1, "", &caller_realm);
  199. // 12. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  200. auto promise_capability = MUST(new_promise_capability(vm, realm.intrinsics().promise_constructor()));
  201. // NOTE: Even though the spec tells us to use %ThrowTypeError%, it's not observable if we actually do.
  202. // Throw a nicer TypeError forwarding the import error message instead (we know the argument is an Error object).
  203. auto throw_type_error = NativeFunction::create(realm, {}, [](auto& vm) -> ThrowCompletionOr<Value> {
  204. return vm.template throw_completion<TypeError>(vm.argument(0).as_object().get_without_side_effects(vm.names.message).as_string().utf8_string());
  205. });
  206. // 13. Return PerformPromiseThen(innerCapability.[[Promise]], onFulfilled, callerRealm.[[Intrinsics]].[[%ThrowTypeError%]], promiseCapability).
  207. return verify_cast<Promise>(inner_capability->promise().ptr())->perform_then(on_fulfilled, throw_type_error, promise_capability);
  208. }
  209. // 3.1.5 GetWrappedValue ( callerRealm: a Realm Record, value: unknown, ), https://tc39.es/proposal-shadowrealm/#sec-getwrappedvalue
  210. ThrowCompletionOr<Value> get_wrapped_value(VM& vm, Realm& caller_realm, Value value)
  211. {
  212. auto& realm = *vm.current_realm();
  213. // 1. If Type(value) is Object, then
  214. if (value.is_object()) {
  215. // a. If IsCallable(value) is false, throw a TypeError exception.
  216. if (!value.is_function())
  217. return vm.throw_completion<TypeError>(ErrorType::ShadowRealmWrappedValueNonFunctionObject, value);
  218. // b. Return ? WrappedFunctionCreate(callerRealm, value).
  219. return TRY(WrappedFunction::create(realm, caller_realm, value.as_function()));
  220. }
  221. // 2. Return value.
  222. return value;
  223. }
  224. // 3.1.7 GetShadowRealmContext ( shadowRealmRecord, strictEval ), https://tc39.es/proposal-shadowrealm/#sec-getshadowrealmcontext
  225. NonnullOwnPtr<ExecutionContext> get_shadow_realm_context(Realm& shadow_realm, bool strict_eval)
  226. {
  227. // 1. Let lexEnv be NewDeclarativeEnvironment(shadowRealmRecord.[[GlobalEnv]]).
  228. Environment* lexical_environment = new_declarative_environment(shadow_realm.global_environment()).ptr();
  229. // 2. Let varEnv be shadowRealmRecord.[[GlobalEnv]].
  230. Environment* variable_environment = &shadow_realm.global_environment();
  231. // 3. If strictEval is true, set varEnv to lexEnv.
  232. if (strict_eval)
  233. variable_environment = lexical_environment;
  234. // 4. Let context be a new ECMAScript code execution context.
  235. auto context = ExecutionContext::create();
  236. // 5. Set context's Function to null.
  237. context->function = nullptr;
  238. // 6. Set context's Realm to shadowRealmRecord.
  239. context->realm = &shadow_realm;
  240. // 7. Set context's ScriptOrModule to null.
  241. context->script_or_module = {};
  242. // 8. Set context's VariableEnvironment to varEnv.
  243. context->variable_environment = variable_environment;
  244. // 9. Set context's LexicalEnvironment to lexEnv.
  245. context->lexical_environment = lexical_environment;
  246. // 10. Set context's PrivateEnvironment to null.
  247. context->private_environment = nullptr;
  248. // Non-standard
  249. context->is_strict_mode = strict_eval;
  250. // 11. Return context.
  251. return context;
  252. }
  253. }