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/Lexer.h>
  7. #include <LibJS/Parser.h>
  8. #include <LibJS/Runtime/AbstractOperations.h>
  9. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  10. #include <LibJS/Runtime/ModuleNamespaceObject.h>
  11. #include <LibJS/Runtime/NativeFunction.h>
  12. #include <LibJS/Runtime/PromiseConstructor.h>
  13. #include <LibJS/Runtime/PromiseReaction.h>
  14. #include <LibJS/Runtime/ShadowRealm.h>
  15. #include <LibJS/Runtime/WrappedFunction.h>
  16. namespace JS {
  17. ShadowRealm::ShadowRealm(Realm& shadow_realm, ExecutionContext execution_context, Object& prototype)
  18. : Object(prototype)
  19. , m_shadow_realm(shadow_realm)
  20. , m_execution_context(move(execution_context))
  21. {
  22. }
  23. void ShadowRealm::visit_edges(Visitor& visitor)
  24. {
  25. Base::visit_edges(visitor);
  26. visitor.visit(&m_shadow_realm);
  27. }
  28. // 3.1.2 CopyNameAndLength ( F: a function object, Target: a function object, prefix: a String, optional argCount: a Number, ), https://tc39.es/proposal-shadowrealm/#sec-copynameandlength
  29. ThrowCompletionOr<void> copy_name_and_length(GlobalObject& global_object, FunctionObject& function, FunctionObject& target, StringView prefix, Optional<unsigned> arg_count)
  30. {
  31. auto& vm = global_object.vm();
  32. // 1. If argCount is undefined, then set argCount to 0.
  33. if (!arg_count.has_value())
  34. arg_count = 0;
  35. // 2. Let L be 0.
  36. double length = 0;
  37. // 3. Let targetHasLength be ? HasOwnProperty(Target, "length").
  38. auto target_has_length = TRY(target.has_own_property(vm.names.length));
  39. // 4. If targetHasLength is true, then
  40. if (target_has_length) {
  41. // a. Let targetLen be ? Get(Target, "length").
  42. auto target_length = TRY(target.get(vm.names.length));
  43. // b. If Type(targetLen) is Number, then
  44. if (target_length.is_number()) {
  45. // i. If targetLen is +∞𝔽, set L to +∞.
  46. if (target_length.is_positive_infinity()) {
  47. length = target_length.as_double();
  48. }
  49. // ii. Else if targetLen is -∞𝔽, set L to 0.
  50. else if (target_length.is_negative_infinity()) {
  51. length = 0;
  52. }
  53. // iii. Else,
  54. else {
  55. // 1. Let targetLenAsInt be ! ToIntegerOrInfinity(targetLen).
  56. auto target_length_as_int = MUST(target_length.to_integer_or_infinity(global_object));
  57. // 2. Assert: targetLenAsInt is finite.
  58. VERIFY(!isinf(target_length_as_int));
  59. // 3. Set L to max(targetLenAsInt - argCount, 0).
  60. length = max(target_length_as_int - *arg_count, 0);
  61. }
  62. }
  63. }
  64. // 5. Perform ! SetFunctionLength(F, L).
  65. function.set_function_length(length);
  66. // 6. Let targetName be ? Get(Target, "name").
  67. auto target_name = TRY(target.get(vm.names.name));
  68. // 7. If Type(targetName) is not String, set targetName to the empty String.
  69. if (!target_name.is_string())
  70. target_name = js_string(vm, String::empty());
  71. // 8. Perform ! SetFunctionName(F, targetName, prefix).
  72. function.set_function_name({ target_name.as_string().string() }, prefix);
  73. return {};
  74. }
  75. // 3.1.3 PerformShadowRealmEval ( sourceText: a String, callerRealm: a Realm Record, evalRealm: a Realm Record, ), https://tc39.es/proposal-shadowrealm/#sec-performshadowrealmeval
  76. ThrowCompletionOr<Value> perform_shadow_realm_eval(GlobalObject& global_object, StringView source_text, Realm& caller_realm, Realm& eval_realm)
  77. {
  78. auto& vm = global_object.vm();
  79. // 1. Perform ? HostEnsureCanCompileStrings(callerRealm, evalRealm).
  80. // FIXME: We don't have this host-defined abstract operation yet.
  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));
  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<JS::SyntaxError>(global_object, 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. // NOTE: This would be unused due to step 11 and is omitted for that reason.
  102. // 5. Let lexEnv be NewDeclarativeEnvironment(evalRealm.[[GlobalEnv]]).
  103. Environment* lexical_environment = new_declarative_environment(eval_realm.global_environment());
  104. // 6. Let varEnv be evalRealm.[[GlobalEnv]].
  105. Environment* variable_environment = &eval_realm.global_environment();
  106. // 7. If strictEval is true, set varEnv to lexEnv.
  107. if (strict_eval)
  108. variable_environment = lexical_environment;
  109. // 8. If runningContext is not already suspended, suspend runningContext.
  110. // NOTE: We don't support this concept yet.
  111. // 9. Let evalContext be a new ECMAScript code execution context.
  112. auto eval_context = ExecutionContext { vm.heap() };
  113. // 10. Set evalContext's Function to null.
  114. eval_context.function = nullptr;
  115. // 11. Set evalContext's Realm to evalRealm.
  116. eval_context.realm = &eval_realm;
  117. // 12. Set evalContext's ScriptOrModule to null.
  118. // Note: This is already the default value.
  119. // 13. Set evalContext's VariableEnvironment to varEnv.
  120. eval_context.variable_environment = variable_environment;
  121. // 14. Set evalContext's LexicalEnvironment to lexEnv.
  122. eval_context.lexical_environment = lexical_environment;
  123. // Non-standard
  124. eval_context.is_strict_mode = strict_eval;
  125. // 15. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  126. TRY(vm.push_execution_context(eval_context, eval_realm.global_object()));
  127. // 16. Let result be EvalDeclarationInstantiation(body, varEnv, lexEnv, null, strictEval).
  128. auto eval_result = eval_declaration_instantiation(vm, eval_realm.global_object(), program, variable_environment, lexical_environment, nullptr, strict_eval);
  129. Completion result;
  130. // 17. If result.[[Type]] is normal, then
  131. if (!eval_result.is_throw_completion()) {
  132. // TODO: Optionally use bytecode interpreter?
  133. // a. Set result to the result of evaluating body.
  134. result = program->execute(vm.interpreter(), eval_realm.global_object());
  135. }
  136. // 18. If result.[[Type]] is normal and result.[[Value]] is empty, then
  137. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  138. // a. Set result to NormalCompletion(undefined).
  139. result = normal_completion(js_undefined());
  140. }
  141. // 19. Suspend evalContext and remove it from the execution context stack.
  142. // NOTE: We don't support this concept yet.
  143. vm.pop_execution_context();
  144. // 20. Resume the context that is now on the top of the execution context stack as the running execution context.
  145. // NOTE: We don't support this concept yet.
  146. // 21. If result.[[Type]] is not normal, throw a TypeError exception.
  147. if (result.type() != Completion::Type::Normal)
  148. return vm.throw_completion<TypeError>(global_object, ErrorType::ShadowRealmEvaluateAbruptCompletion);
  149. // 22. Return ? GetWrappedValue(callerRealm, result.[[Value]]).
  150. return get_wrapped_value(global_object, caller_realm, *result.value());
  151. // NOTE: Also see "Editor's Note" in the spec regarding the TypeError above.
  152. }
  153. // 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
  154. 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)
  155. {
  156. auto& vm = global_object.vm();
  157. // 1. Assert: evalContext is an execution context associated to a ShadowRealm instance's [[ExecutionContext]].
  158. // 2. Let innerCapability be ! NewPromiseCapability(%Promise%).
  159. auto inner_capability = MUST(new_promise_capability(global_object, global_object.promise_constructor()));
  160. // 3. Let runningContext be the running execution context.
  161. // 4. If runningContext is not already suspended, suspend runningContext.
  162. // NOTE: We don't support this concept yet.
  163. // 5. Push evalContext onto the execution context stack; evalContext is now the running execution context.
  164. TRY(vm.push_execution_context(eval_context, eval_realm.global_object()));
  165. // 6. Perform ! HostImportModuleDynamically(null, specifierString, innerCapability).
  166. vm.host_import_module_dynamically(Empty {}, ModuleRequest { move(specifier_string) }, inner_capability);
  167. // 7. Suspend evalContext and remove it from the execution context stack.
  168. // NOTE: We don't support this concept yet.
  169. vm.pop_execution_context();
  170. // 8. Resume the context that is now on the top of the execution context stack as the running execution context.
  171. // NOTE: We don't support this concept yet.
  172. // 9. Let steps be the steps of an ExportGetter function as described below.
  173. // 10. Let onFulfilled be ! CreateBuiltinFunction(steps, 1, "", « [[ExportNameString]] », callerRealm).
  174. // 11. Set onFulfilled.[[ExportNameString]] to exportNameString.
  175. // FIXME: Support passing a realm to NativeFunction::create()
  176. (void)caller_realm;
  177. auto* on_fulfilled = NativeFunction::create(
  178. global_object,
  179. "",
  180. [string = move(export_name_string)](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
  181. // 1. Assert: exports is a module namespace exotic object.
  182. VERIFY(vm.argument(0).is_object());
  183. auto& exports = vm.argument(0).as_object();
  184. VERIFY(is<ModuleNamespaceObject>(exports));
  185. // 2. Let f be the active function object.
  186. auto* function = vm.running_execution_context().function;
  187. // 3. Let string be f.[[ExportNameString]].
  188. // 4. Assert: Type(string) is String.
  189. // 5. Let hasOwn be ? HasOwnProperty(exports, string).
  190. auto has_own = TRY(exports.has_own_property(string));
  191. // 6. If hasOwn is false, throw a TypeError exception.
  192. if (!has_own)
  193. return vm.template throw_completion<TypeError>(global_object, ErrorType::MissingRequiredProperty, string);
  194. // 7. Let value be ? Get(exports, string).
  195. auto value = TRY(exports.get(string));
  196. // 8. Let realm be f.[[Realm]].
  197. auto* realm = function->realm();
  198. VERIFY(realm);
  199. // 9. Return ? GetWrappedValue(realm, value).
  200. return get_wrapped_value(global_object, *realm, value);
  201. });
  202. on_fulfilled->define_direct_property(vm.names.length, Value(1), Attribute::Configurable);
  203. on_fulfilled->define_direct_property(vm.names.name, js_string(vm, String::empty()), Attribute::Configurable);
  204. // 12. Let promiseCapability be ! NewPromiseCapability(%Promise%).
  205. auto promise_capability = MUST(new_promise_capability(global_object, 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(global_object, {}, [](auto& vm, auto& global_object) -> ThrowCompletionOr<Value> {
  209. return vm.template throw_completion<TypeError>(global_object, 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. // 1. If Type(value) is Object, then
  219. if (value.is_object()) {
  220. // a. If IsCallable(value) is false, throw a TypeError exception.
  221. if (!value.is_function())
  222. return vm.throw_completion<TypeError>(global_object, ErrorType::ShadowRealmWrappedValueNonFunctionObject, value);
  223. // b. Return ? WrappedFunctionCreate(callerRealm, value).
  224. return TRY(WrappedFunction::create(global_object, caller_realm, value.as_function()));
  225. }
  226. // 2. Return value.
  227. return value;
  228. }
  229. }