dymokomi/luce-browser-engine
Source of release 0.6.1
0.6.1 / src / web / web_idl / abstract_operations.lucb
#==============================================================================================
#
# abstract_operations - WebIDL abstract operations: conversions, callbacks, buffer copies
#
# DESCRIPTION:
# Port of Libraries/LibWeb/WebIDL/AbstractOperations.cpp (lines 1-580) and
# AbstractOperations.h (lines 1-91). IntegerPart and ConvertToInt are ported in full
# (ConvertToInt's ToNumber handles the primitive values; strings and objects are JS cells,
# phase 3). Calling a user object's operation, invoking callback functions, constructing
# through a callback, the string conversions of JS values, buffer source copies and
# set_prototype_from_new_target operate on JS objects and come with luce-js (phase 3).
#
# Copyright (c) 2021-2023, Luke Wilde <lukew@serenityos.org>
# Copyright (c) 2021-2022, Linus Groh <linusg@serenityos.org>
# Copyright (c) 2023, Shannon Booth <shannon@serenityos.org>
# SPDX-License-Identifier: BSD-2-Clause
#
#==============================================================================================
# mark: Buffer sources ==========================================================================
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:29 Web::WebIDL::is_buffer_source_type:
## whether the value is a TypedArray, a DataView or an ArrayBuffer (JS objects, phase 3).
pub func idl_is_buffer_source_type(value: JsValue) -> bool:
if not js_value_is_object(value):
return false
# is<JS::TypedArrayBase>(object) || is<JS::DataView>(object) || is<JS::ArrayBuffer>(object): phase 3.
trap("unported (P3): Web::WebIDL::is_buffer_source_type of a JS object")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.h:25 Web::WebIDL::underlying_buffer_source.
pub func idl_underlying_buffer_source(buffer_source: JsObject*) -> JsArrayBuffer*?:
trap("unported (P3): Web::WebIDL::underlying_buffer_source (JS buffer objects)")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:39 Web::WebIDL::get_buffer_source_copy.
## https://webidl.spec.whatwg.org/#dfn-get-buffer-source-copy
pub func idl_get_buffer_source_copy(buffer_source: JsObject*) -> ak.ByteBuffer!:
trap("unported (P3): Web::WebIDL::get_buffer_source_copy (JS buffer objects)")
# mark: Callbacks ===============================================================================
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:117 Web::WebIDL::clean_up_on_return.
## https://webidl.spec.whatwg.org/#call-user-object-operation-return
pub func idl_clean_up_on_return(stored_settings: HtmlEnvironmentSettingsObject*, relevant_settings: HtmlEnvironmentSettingsObject*, completion: JsCompletion*, operation_returns_promise: IdlOperationReturnsPromise) -> JsCompletion:
# Return: at this point completion will be set to an ECMAScript completion value.
# 1. Clean up after running a callback with stored settings.
html_clean_up_after_running_callback(stored_settings)
# 2. Clean up after running script with relevant settings.
html_clean_up_after_running_script(relevant_settings)
# 3. If completion is a normal completion, return completion.
if js_completion_type(completion) == JsCompletionType.normal:
return *completion
# 4. If completion is an abrupt completion and the operation has a return type that is not a promise type, return completion.
if js_completion_is_abrupt(completion) and operation_returns_promise == IdlOperationReturnsPromise.no:
return *completion
# 5. Let rejectedPromise be ! Call(%Promise.reject%, %Promise%, «completion.[[Value]]»).
let rejected_promise = idl_create_rejected_promise(html_environment_settings_object_realm(relevant_settings), js_completion_value(completion))
# 6. Return the result of converting rejectedPromise to the operation’s return type.
# Note: The operation must return a promise, so no conversion is necessary
_ = rejected_promise
trap("unported (P3): Web::WebIDL::clean_up_on_return of a promise operation (JS::Value of the promise)")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:144 Web::WebIDL::call_user_object_operation.
## https://webidl.spec.whatwg.org/#call-a-user-objects-operation
## Region r19 ported the steps that call a callable object (a native function before phase 3);
## getting the operation from a callback interface object is phase 3.
pub func idl_call_user_object_operation(callback: IdlCallbackType*, operation_name: ak.Utf16FlyString, this_argument: JsValue?, args: const JsValue[]) -> JsCompletion:
# 1. Let completion be an uninitialized variable.
var completion: JsCompletion
# 2. If thisArg was not given, let thisArg be undefined.
var this_value = this_argument else js_undefined()
# 3. Let O be the ECMAScript object corresponding to value.
let object = callback.callback
# 4. Let realm be O’s associated realm.
let realm = js_object_shape_realm(object)
# 5. Let relevant settings be realm’s settings object.
let relevant_settings = html_principal_realm_settings_object(realm)
# 6. Let stored settings be value’s callback context.
let stored_settings = callback.callback_context
# 7. Prepare to run script with relevant settings.
html_prepare_to_run_script(relevant_settings)
# 8. Prepare to run a callback with stored settings.
html_prepare_to_run_callback(stored_settings)
# 9. Let X be O.
let actual_function_object = object
# 10. If ! IsCallable(O) is false, then:
if not js_object_is_function(object):
# 1. Let getResult be Get(O, opName).
# 2. If getResult is an abrupt completion, set completion to getResult and jump to the step labeled return.
# 4. If ! IsCallable(X) is false, then set completion to a new Completion{[[Type]]: throw, [[Value]]: a newly created TypeError object, [[Target]]: empty}, and jump to the step labeled return.
# 3. Set X to getResult.[[Value]].
# 5. Set thisArg to O (overriding the provided value).
# (Get(O, opName) on a callback interface object is a JS property access: phase 3.)
_ = operation_name
trap("unported (P3): Web::WebIDL::call_user_object_operation on a callback interface object (Get(O, opName))")
# FIXME: 11. Let esArgs be the result of converting args to an ECMAScript arguments list. If this throws an exception, set completion to the completion value representing the thrown exception and jump to the step labeled return.
# For simplicity, we currently make the caller do this. However, this means we can't throw exceptions at this point like the spec wants us to.
# 12. Let callResult be Call(X, thisArg, esArgs).
let vm = realm_vm(realm)
let call_result = js_call(vm, (JsFunctionObject*)actual_function_object, this_value, args) catch:
# 13. If callResult is an abrupt completion, set completion to callResult and jump to the step labeled return.
completion = vm_take_throw_completion(vm)
return idl_clean_up_on_return(stored_settings, relevant_settings, &completion, callback.operation_returns_promise)
# 14. Set completion to the result of converting callResult.[[Value]] to an IDL value of the same type as the operation’s return type.
# FIXME: This does no conversion.
completion = js_completion_from_value(call_result)
return idl_clean_up_on_return(stored_settings, relevant_settings, &completion, callback.operation_returns_promise)
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:219 Web::WebIDL::to_byte_string.
## https://webidl.spec.whatwg.org/#ref-for-idl-ByteString%E2%91%A7
pub func idl_to_byte_string(vm: Vm*, value: JsValue) -> ak.String!:
trap("unported (P3): Web::WebIDL::to_byte_string (JS ToString)")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:235 Web::WebIDL::to_string.
pub func idl_to_string(vm: Vm*, value: JsValue) -> ak.String!:
trap("unported (P3): Web::WebIDL::to_string (JS ToString)")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:240 Web::WebIDL::to_utf16_string.
pub func idl_to_utf16_string(vm: Vm*, value: JsValue) -> ak.Utf16String!:
trap("unported (P3): Web::WebIDL::to_utf16_string (JS ToString)")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:245 Web::WebIDL::to_usv_string.
pub func idl_to_usv_string(vm: Vm*, value: JsValue) -> ak.String!:
trap("unported (P3): Web::WebIDL::to_usv_string (JS ToString)")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:250 Web::WebIDL::to_utf16_usv_string.
pub func idl_to_utf16_usv_string(vm: Vm*, value: JsValue) -> ak.Utf16String!:
trap("unported (P3): Web::WebIDL::to_utf16_usv_string (JS ToString)")
## `JS::call(...)` as the Completion a ThrowCompletionOr<Value> converts to: the value, or the
## exception the call stored.
func idl_call_as_completion(vm: Vm*, function: JsFunctionObject*, this_value: JsValue, args: const JsValue[]) -> JsCompletion:
let value = js_call(vm, function, this_value, args) catch:
return vm_take_throw_completion(vm)
return js_completion_from_value(value)
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:258 Web::WebIDL::invoke_callback_impl:
## the shared steps of invoking a callback function. The C++ template takes the return steps as
## a lambda; here the caller runs them on the realm and completion this answers.
## https://webidl.spec.whatwg.org/#invoke-a-callback-function
## https://whatpr.org/webidl/1437.html#invoke-a-callback-function
func idl_invoke_callback_impl(callback: IdlCallbackType*, this_argument: JsValue?, args: const JsValue[]) -> (Realm*, JsCompletion):
# 1. Let completion be an uninitialized variable.
# 2. If thisArg was not given, let thisArg be undefined.
let this_value = this_argument else js_undefined()
# 3. Let F be the ECMAScript object corresponding to callable.
let function_object = callback.callback
# 5. Let realm be F’s associated realm.
let realm = js_object_shape_realm(function_object)
# 6. Let relevant settings be realm’s settings object.
let relevant_settings = html_principal_realm_settings_object(realm)
# 4. If ! IsCallable(F) is false:
if not js_object_is_function(function_object):
# 1. Note: This is only possible when the callback function came from an attribute marked with [LegacyTreatNonObjectAsNull].
# 2. Return the result of converting undefined to the callback function’s return type.
return (realm, js_completion_from_value(js_undefined()))
# 7. Let stored settings be callable’s callback context.
let stored_settings = callback.callback_context
# 8. Prepare to run script with relevant realm.
html_prepare_to_run_script(relevant_settings)
# 9. Prepare to run a callback with stored realm.
html_prepare_to_run_callback(stored_settings)
# FIXME: 10. Let jsArgs be the result of converting args to a JavaScript arguments list.
# If this throws an exception, set completion to the completion value representing the thrown exception and jump to the step labeled return.
# 11. Let callResult be Call(F, thisArg, jsArgs).
let call_result = idl_call_as_completion(realm_vm(realm), (JsFunctionObject*)function_object, this_value, args)
# 12. If callResult is an abrupt completion, set completion to callResult and jump to the step labeled return.
# 13. Set completion to the result of converting callResult.[[Value]] to an IDL value of the same type as callable’s
# return type. If this throws an exception, set completion to the completion value representing the thrown exception.
# 14. Return: at this point completion will be set to an IDL value or an abrupt completion.
# 1. Clean up after running a callback with stored settings.
html_clean_up_after_running_callback(stored_settings)
# 2. Clean up after running script with relevant settings.
# FIXME: This method follows an older version of the spec, which takes a realm, so we use F's associated realm instead.
html_clean_up_after_running_script(relevant_settings)
return (realm, call_result)
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:314 Web::WebIDL::invoke_callback.
## https://webidl.spec.whatwg.org/#invoke-a-callback-function
pub func idl_invoke_callback_idl_exception_behavior(callback: IdlCallbackType*, this_argument: JsValue?, exception_behavior: IdlExceptionBehavior, args: const JsValue[]) -> JsCompletion:
# https://webidl.spec.whatwg.org/#js-invoking-callback-functions
# The exceptionBehavior argument must be supplied if, and only if, callable’s return type is not a promise type. If callable’s return type is neither undefined nor any, it must be "rethrow".
# NOTE: Until call sites are updated to respect this, specifications which fail to provide a value here when it would be mandatory should be understood as supplying "rethrow".
var behavior = exception_behavior
if behavior == IdlExceptionBehavior.not_specified and callback.operation_returns_promise == IdlOperationReturnsPromise.no:
behavior = IdlExceptionBehavior.rethrow
assert(behavior == IdlExceptionBehavior.not_specified or callback.operation_returns_promise == IdlOperationReturnsPromise.no)
let (relevant_realm, completion) = idl_invoke_callback_impl(callback, this_argument, args)
# 3. If completion is an IDL value, return completion.
if not js_completion_is_abrupt(&completion):
return completion
# 4. Assert: completion is an abrupt completion.
# 5. If exceptionBehavior is "rethrow", throw completion.[[Value]].
if behavior == IdlExceptionBehavior.rethrow:
return js_throw_completion(js_completion_value(&completion))
# 6. Otherwise, if exceptionBehavior is "report":
if behavior == IdlExceptionBehavior.report:
# FIXME: 1. Assert: callable’s return type is undefined or any.
# 2. Report an exception completion.[[Value]] for relevant realm’s global object.
let window_or_worker = as_if_window_or_worker_global_scope_mixin((gc.Cell*)realm_global_object(relevant_realm)) else trap("as<HTML::WindowOrWorkerGlobalScopeMixin> failed")
html_window_or_worker_global_scope_mixin_report_an_exception(window_or_worker, js_completion_value(&completion))
# 3. Return the unique undefined IDL value.
return js_completion_from_value(js_undefined())
# 7. Assert: callable’s return type is a promise type.
assert(callback.operation_returns_promise == IdlOperationReturnsPromise.yes)
# 8. Let rejectedPromise be ! Call(%Promise.reject%, %Promise%, «completion.[[Value]]»).
let rejected_promise = idl_create_rejected_promise(relevant_realm, js_completion_value(&completion))
# 9. Return the result of converting rejectedPromise to the callback function’s return type.
_ = rejected_promise
trap("unported (P3): Web::WebIDL::invoke_callback of a promise callback (JS::Value of the promise)")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:360 Web::WebIDL::invoke_callback.
pub func idl_invoke_callback_span_js_value(callback: IdlCallbackType*, this_argument: JsValue?, args: const JsValue[]) -> JsCompletion:
return idl_invoke_callback_idl_exception_behavior(callback, this_argument, IdlExceptionBehavior.not_specified, args)
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:367 Web::WebIDL::invoke_promise_callback.
pub func idl_invoke_promise_callback(callback: IdlCallbackType*, this_argument: JsValue?, args: const JsValue[]) -> JsPromiseCapability*:
trap("unported (P3): Web::WebIDL::invoke_promise_callback (a JS call)")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:389 Web::WebIDL::construct.
## https://webidl.spec.whatwg.org/#construct-a-callback-function
pub func idl_construct(callable: IdlCallbackType*, args: const JsValue[]) -> JsCompletion:
trap("unported (P3): Web::WebIDL::construct (a JS construct call)")
# mark: Integer conversions =====================================================================
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:451 Web::WebIDL::integer_part.
## https://webidl.spec.whatwg.org/#abstract-opdef-integerpart
pub func idl_integer_part(n: f64) -> f64:
# 1. Let r be floor(abs(n)).
let r = math.floor(math.abs(n))
# 2. If n < 0, then return -1 × r.
if n < 0.0:
return -r
# 3. Otherwise, return r.
return r
## The integer types ConvertToInt is instantiated with (AbstractOperations.cpp:550-557, the
## WebIDL::Types.h aliases): convert_to_int<T> takes the type as this argument.
pub enum IdlIntegerType:
byte # WebIDL::Byte, i8
octet # WebIDL::Octet, u8
short # WebIDL::Short, i16
unsigned_short # WebIDL::UnsignedShort, u16
long # WebIDL::Long, i32
unsigned_long # WebIDL::UnsignedLong, u32
long_long # WebIDL::LongLong, i64
unsigned_long_long # WebIDL::UnsignedLongLong, u64
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:466 Web::WebIDL::convert_to_int:
## 3.2.4.9 ConvertToInt(V, bitLength, signedness), https://webidl.spec.whatwg.org/#abstract-opdef-converttoint.
## C++ instantiates the template per integer type; here the type is `type_` and the result is
## the integer as an f64 (exact: at most 2^64, an integral double), which the caller converts
## to its type as C++'s return statement does.
pub func idl_convert_to_int(vm: Vm*, value: JsValue, type_: IdlIntegerType, enforce_range: IdlEnforceRange = IdlEnforceRange.no, clamp: IdlClamp = IdlClamp.no) -> f64!:
var upper_bound: f64 = 0.0
var lower_bound: f64 = 0.0
let is_signed = type_ == .byte or type_ == .short or type_ == .long or type_ == .long_long
# NumericLimits<MakeUnsigned<T>>::max() + 1.0
let two_pow_bitlength: f64 = match type_:
.byte, .octet => 256.0
.short, .unsigned_short => 65536.0
.long, .unsigned_long => 4294967296.0
.long_long, .unsigned_long_long => 18446744073709551616.0
# 1. If bitLength is 64, then:
if type_ == .long_long or type_ == .unsigned_long_long:
# 1. Let upperBound be 2^(53) − 1
upper_bound = js_max_array_like_index
# 2. If signedness is "unsigned", then let lowerBound be 0.
if not is_signed:
lower_bound = 0.0
# 3. Otherwise let lowerBound be −2^(53) + 1.
else:
lower_bound = -js_max_array_like_index
# Note: this ensures long long types associated with [EnforceRange] or [Clamp] extended attributes are representable in ECMAScript’s Number type as unambiguous integers.
else:
# 2. Otherwise, if signedness is "unsigned", then:
# 1. Let lowerBound be 0.
# 2. Let upperBound be 2^(bitLength) − 1.
# 3. Otherwise:
# 1. Let lowerBound be -2^(bitLength − 1).
# 2. Let upperBound be 2^(bitLength − 1) − 1.
if is_signed:
lower_bound = -(two_pow_bitlength / 2.0)
upper_bound = two_pow_bitlength / 2.0 - 1.0
else:
lower_bound = 0.0
upper_bound = two_pow_bitlength - 1.0
# 4. Let x be ? ToNumber(V).
var x = js_value_as_double(try js_value_to_number(vm, value))
# 5. If x is −0, then set x to +0.
if x == -0.0:
x = 0.0
# 6. If the conversion is to an IDL type associated with the [EnforceRange] extended attribute, then:
if enforce_range == IdlEnforceRange.yes:
# 1. If x is NaN, +∞, or −∞, then throw a TypeError.
if math.is_nan(x) or math.is_infinite(x):
return try vm_throw_completion(vm, IdlSimpleExceptionType.type_error, .string_view(ak.sv("Number must not be NaN or Infinity")))
# 2. Set x to IntegerPart(x).
x = idl_integer_part(x)
# 3. If x < lowerBound or x > upperBound, then throw a TypeError.
if x < lower_bound or x > upper_bound:
var builder = ak.string_builder_new()
ak.vformat_arguments(&builder, ak.sv("Number '{}' is outside of allowed range of {} to {}"), [ak.arg_f64(x), ak.arg_f64(lower_bound), ak.arg_f64(upper_bound)]) else trap("MUST: String::formatted")
let message = ak.string_builder_to_string(&builder) else trap("MUST: String::formatted")
return try vm_throw_completion(vm, IdlSimpleExceptionType.type_error, .string(message))
# 4. Return x.
return x
# 7. If x is not NaN and the conversion is to an IDL type associated with the [Clamp] extended attribute, then:
if clamp == IdlClamp.yes and not math.is_nan(x):
# 1. Set x to min(max(x, lowerBound), upperBound).
x = idl_min(idl_max(x, lower_bound), upper_bound)
# 2. Round x to the nearest integer, choosing the even integer if it lies halfway between two, and choosing +0 rather than −0.
# 3. Return x.
# AK::round_to<T>(x), to nearest even; x is within T's range (the 8- and 16-bit types
# round as i32, which gives the same value).
return match type_:
.byte, .octet, .short, .unsigned_short, .long => (f64)ak.rounding_round_to_f64_i32(x)
.unsigned_long => (f64)ak.rounding_round_to_f64_u32(x)
.long_long => (f64)ak.rounding_round_to_f64_i64(x)
.unsigned_long_long => (f64)ak.rounding_round_to_f64_u64(x)
# 8. If x is NaN, +0, +∞, or −∞, then return +0.
if math.is_nan(x) or x == 0.0 or math.is_infinite(x):
return 0.0
# 9. Set x to IntegerPart(x).
x = idl_integer_part(x)
# 10. Set x to x modulo 2^bitLength.
x = js_modulo(x, two_pow_bitlength)
# 11. If signedness is "signed" and x ≥ 2^(bitLength − 1), then return x − 2^(bitLength).
if is_signed and x > two_pow_bitlength / 2.0 - 1.0:
return x - two_pow_bitlength
# 12. Otherwise, return x.
return x
## AK::min(a, b) on doubles: `b < a ? b : a`.
func idl_min(a: f64, b: f64) -> f64:
return b if b < a else a
## AK::max(a, b) on doubles: `a < b ? b : a`.
func idl_max(a: f64, b: f64) -> f64:
return b if a < b else a
## JS::MAX_ARRAY_LIKE_INDEX (Libraries/LibJS/Runtime/Value.h:32): 2^53 - 1.
pub let js_max_array_like_index: f64 = 9007199254740991.0
## Ported from Libraries/LibJS/Runtime/AbstractOperations.h:306 JS::modulo (floating point):
## x modulo y, https://tc39.es/ecma262/#eqn-modulo
pub func js_modulo(x: f64, y: f64) -> f64:
# The notation “x modulo y” (y must be finite and non-zero) computes a value k of the same sign as y (or zero) such that abs(k) < abs(y) and x - k = q × y for some integer q.
assert(y != 0.0)
assert(math.is_finite(y))
let r = math.mod(x, y)
return r + y if r < 0.0 else r
# mark: Caches and prototypes ===================================================================
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.cpp:561 Web::WebIDL::lists_contain_same_elements.
## AD-HOC: For same-object caching purposes, this can be used to compare a cached JS array of
## DOM::Elements with another list. Either list can be null, in which case they are considered
## the same only if they are both null.
pub func idl_lists_contain_same_elements(array: JsArray*?, elements: ak.Vector[DomElement*]?) -> bool:
if array == none or elements == none:
return array == none and elements == none
# The cached array is a JS Array of the elements' wrappers (phase 3).
trap("unported (P3): Web::WebIDL::lists_contain_same_elements of a JS::Array")
## Ported from Libraries/LibWeb/WebIDL/AbstractOperations.h:70 Web::WebIDL::set_prototype_from_new_target.
## https://webidl.spec.whatwg.org/#internally-create-a-new-object-implementing-the-interface
## Steps from "internally create a new object implementing the interface".
pub func idl_set_prototype_from_new_target[TPrototypeType](vm: Vm*, new_target: JsFunctionObject*, interface_name: ak.FlyString, object: JsObject*) -> !:
# 3.2. Let prototype be ? Get(newTarget, "prototype"). ... 9. Set instance.[[Prototype]] to prototype.
trap("unported (P3): Web::WebIDL::set_prototype_from_new_target (JS prototypes)")