mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-16 03:51:16 +00:00
JavaScript: bind converts the target's length to an integer
A host function has no own length, so a script can define one with a fraction, and the bound function's length kept it. Function.prototype.bind now converts the target's length to an integer before it subtracts the bound arguments, as later editions specify.
This commit is contained in:
@@ -448,11 +448,15 @@ fn function_bind(interp: &mut Interp, this: Value, args: &[Value], _: bool) -> J
|
||||
let Some(target) = this.as_object() else { return Err(interp.type_error("the value bind was called on is not a function")) };
|
||||
let bound_this = arg(args, 0);
|
||||
let bound_args: Rc<[Value]> = args.get(1..).unwrap_or_default().into();
|
||||
// A host function's `length` is an ordinary property a script can set, so it is converted
|
||||
// to an integer first, as later editions specify.
|
||||
let target_length = match interp.get_from(target, &key("length"), &this)? {
|
||||
Value::Number(n) => n,
|
||||
Value::Number(n) if n.is_nan() => 0.0,
|
||||
Value::Number(n) => n.trunc(),
|
||||
_ => 0.0,
|
||||
};
|
||||
let length = (target_length - bound_args.len() as f64).max(0.0);
|
||||
// Adding 0 turns a negative zero into 0.
|
||||
let length = (target_length - bound_args.len() as f64).max(0.0) + 0.0;
|
||||
interp.reserve_heap(OBJECT_BYTES + 4 * PROP_BYTES + BOUND_ARG_BYTES * bound_args.len())?;
|
||||
let proto = interp.intrinsics.function_proto;
|
||||
let class = Class::Function(Func::Bound { target, this: bound_this, args: bound_args.clone() });
|
||||
|
||||
@@ -134,6 +134,14 @@ fn bind_fixes_this_and_leading_arguments() {
|
||||
throws("'use strict'; function f() {} f.bind(null).caller", "TypeError");
|
||||
truth("function f() { return arguments.length; } f.bind(null, 1).bind(null, 2)(3) === 3");
|
||||
truth("Object.prototype.toString.call(function () {}.bind()) === '[object Function]'");
|
||||
// A host function has no own `length`, so a script can define one, and bind converts it to
|
||||
// an integer.
|
||||
let mut realm = Realm::new();
|
||||
realm.define_function("host", |_| Ok(JsValue::Undefined));
|
||||
let src = "function len(v) { Object.defineProperty(host, 'length', {value: v, configurable: true}); return host; } \
|
||||
var a = len(2.9).bind(null).length; var b = 1 / len(-0.5).bind(null).length; var c = len(NaN).bind(null).length; \
|
||||
[a, b, c, len(Infinity).bind(null, 1).length].join()";
|
||||
assert_eq!(realm.run(src), Ok(JsValue::String("2,Infinity,0,Infinity".into())));
|
||||
}
|
||||
|
||||
// ---- Array ----
|
||||
|
||||
Reference in New Issue
Block a user