Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lib: add bound apply variants of varargs primordials #37005

Merged
merged 2 commits into from
Jan 28, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
67 changes: 59 additions & 8 deletions lib/internal/per_context/primordials.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,36 @@ const {
// `uncurryThis` is equivalent to `func => Function.prototype.call.bind(func)`.
// It is using `bind.bind(call)` to avoid using `Function.prototype.bind`
// and `Function.prototype.call` after it may have been mutated by users.
const { bind, call } = Function.prototype;
const { apply, bind, call } = Function.prototype;
const uncurryThis = bind.bind(call);
primordials.uncurryThis = uncurryThis;

// `applyBind` is equivalent to `func => Function.prototype.apply.bind(func)`.
// It is using `bind.bind(apply)` to avoid using `Function.prototype.bind`
// and `Function.prototype.apply` after it may have been mutated by users.
const applyBind = bind.bind(apply);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could you please add a comment like the uncurryThis one which explains this is equivalent to

const applyBind = (func) => (thisArg, args) => ReflectApply(func, thisArg, args);

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actually, it’s closer to:

const applyBind = (func, ...rest) => {
	if (args.length > 0) {
		const thisArg = rest[0];
		return (args = []) => ReflectApply(func, thisArg, args);
	} else {
		return (thisArg, args = []) => ReflectApply(func, thisArg, args);
	}
}

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

BTW, shouldn't we prefer using Reflect.apply instead of Function.prototype.apply? I think if someone calls those methods without a argument array, it's almost certainly a bug, and using Reflect.apply would help spot that. Or is there a performance reason to use one or the other?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Well, Reflect.apply isn’t very optimised in comparison to bound Function.prototype.call and Function.prototype.apply calls.

Also, engines are able to generate better code for native bound functions compared to arrow functions that replicate the behaviour of a bound function.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I meant to use const { apply } = Reflect compared to const { apply } = Function.prototype.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That wouldn’t work, since then applyBind(foo) would create a function that roughly does: (...args) => Reflect.apply.call(foo, ...args), instead of (...args) => Reflect.apply(foo, ...args).

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Gotcha, the equivalent would have to be:

Suggested change
const applyBind = bind.bind(apply);
const applyBind = bind.bind(Reflect.apply, null);

Reflect.apply isn’t very optimised in comparison to bound Function.prototype.call and Function.prototype.apply calls.

Is that generally true statement or is it specific to V8? When reading the spec, Reflect.apply seems to be doing less things than Function.prototype.apply, that's a bit counter-intuitive.

Copy link
Contributor Author

@ExE-Boss ExE-Boss Jan 21, 2021

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Reflect.apply isn’t very optimised in comparison to bound Function.prototype.call and Function.prototype.apply calls.

Is that generally true statement or is it specific to V8?

That’s mostly specific to V8, but I assume that it also applies to other C++-based engines, since V8 hasn’t put as much effort into optimising Reflect as into optimising Object and Function methods.

Refs: #36740 (comment)

primordials.applyBind = applyBind;

// Methods that accept a variable number of arguments, and thus it's useful to
// also create `${prefix}${key}Apply`, which uses `Function.prototype.apply`,
// instead of `Function.prototype.call`, and thus doesn't require iterator
// destructuring.
const varargsMethods = [
// 'ArrayPrototypeConcat' is omitted, because it performs the spread
// on its own for arrays and array-likes with a truthy
// @@isConcatSpreadable symbol property.
'ArrayOf',
'ArrayPrototypePush',
'ArrayPrototypeUnshift',
// 'FunctionPrototypeCall' is omitted, since there's 'ReflectApply'
// and 'FunctionPrototypeApply'.
'MathHypot',
'MathMax',
'MathMin',
'StringPrototypeConcat',
'TypedArrayOf',
];

function getNewKey(key) {
return typeof key === 'symbol' ?
`Symbol${key.description[7].toUpperCase()}${key.description.slice(8)}` :
Expand All @@ -51,7 +77,16 @@ function copyPropsRenamed(src, dest, prefix) {
if ('get' in desc) {
copyAccessor(dest, prefix, newKey, desc);
} else {
ReflectDefineProperty(dest, `${prefix}${newKey}`, desc);
const name = `${prefix}${newKey}`;
ReflectDefineProperty(dest, name, desc);
if (varargsMethods.includes(name)) {
ReflectDefineProperty(dest, `${name}Apply`, {
// `src` is bound as the `this` so that the static `this` points
// to the object it was defined on,
// e.g.: `ArrayOfApply` gets a `this` of `Array`:
value: applyBind(desc.value, src),
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
});
}
}
}
}
Expand All @@ -63,10 +98,18 @@ function copyPropsRenamedBound(src, dest, prefix) {
if ('get' in desc) {
copyAccessor(dest, prefix, newKey, desc);
} else {
if (typeof desc.value === 'function') {
desc.value = desc.value.bind(src);
const { value } = desc;
if (typeof value === 'function') {
desc.value = value.bind(src);
ExE-Boss marked this conversation as resolved.
Show resolved Hide resolved
}

const name = `${prefix}${newKey}`;
ReflectDefineProperty(dest, name, desc);
if (varargsMethods.includes(name)) {
ReflectDefineProperty(dest, `${name}Apply`, {
value: applyBind(value, src),
aduh95 marked this conversation as resolved.
Show resolved Hide resolved
});
}
ReflectDefineProperty(dest, `${prefix}${newKey}`, desc);
}
}
}
Expand All @@ -78,10 +121,18 @@ function copyPrototype(src, dest, prefix) {
if ('get' in desc) {
copyAccessor(dest, prefix, newKey, desc);
} else {
if (typeof desc.value === 'function') {
desc.value = uncurryThis(desc.value);
const { value } = desc;
if (typeof value === 'function') {
desc.value = uncurryThis(value);
ExE-Boss marked this conversation as resolved.
Show resolved Hide resolved
}

const name = `${prefix}${newKey}`;
ReflectDefineProperty(dest, name, desc);
if (varargsMethods.includes(name)) {
ReflectDefineProperty(dest, `${name}Apply`, {
value: applyBind(value),
});
}
ReflectDefineProperty(dest, `${prefix}${newKey}`, desc);
}
}
}
Expand Down
5 changes: 3 additions & 2 deletions lib/internal/util/inspect.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ const {
ArrayPrototypeFilter,
ArrayPrototypeForEach,
ArrayPrototypePush,
ArrayPrototypePushApply,
ArrayPrototypeSort,
ArrayPrototypeUnshift,
BigIntPrototypeValueOf,
Expand Down Expand Up @@ -665,7 +666,7 @@ function getKeys(value, showHidden) {
if (showHidden) {
keys = ObjectGetOwnPropertyNames(value);
if (symbols.length !== 0)
ArrayPrototypePush(keys, ...symbols);
ArrayPrototypePushApply(keys, symbols);
} else {
// This might throw if `value` is a Module Namespace Object from an
// unevaluated module, but we don't want to perform the actual type
Expand All @@ -681,7 +682,7 @@ function getKeys(value, showHidden) {
}
if (symbols.length !== 0) {
const filter = (key) => ObjectPrototypePropertyIsEnumerable(value, key);
ArrayPrototypePush(keys, ...ArrayPrototypeFilter(symbols, filter));
ArrayPrototypePushApply(keys, ArrayPrototypeFilter(symbols, filter));
}
}
return keys;
Expand Down
3 changes: 2 additions & 1 deletion lib/readline.js
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ const {
MathCeil,
MathFloor,
MathMax,
MathMaxApply,
NumberIsFinite,
NumberIsNaN,
ObjectDefineProperty,
Expand Down Expand Up @@ -634,7 +635,7 @@ Interface.prototype._tabComplete = function(lastKeypressWasTab) {
// Apply/show completions.
const completionsWidth = ArrayPrototypeMap(completions,
(e) => getStringWidth(e));
const width = MathMax(...completionsWidth) + 2; // 2 space padding
const width = MathMaxApply(completionsWidth) + 2; // 2 space padding
let maxColumns = MathFloor(this.columns / width) || 1;
if (maxColumns === Infinity) {
maxColumns = 1;
Expand Down
1 change: 1 addition & 0 deletions lib/repl.js
Original file line number Diff line number Diff line change
Expand Up @@ -1313,6 +1313,7 @@ function complete(line, callback) {
if (!this.useGlobal) {
// When the context is not `global`, builtins are not own
// properties of it.
// `globalBuiltins` is a `SafeSet`, not an Array-like.
ArrayPrototypePush(contextOwnNames, ...globalBuiltins);
}
ArrayPrototypePush(completionGroups, contextOwnNames);
Expand Down
4 changes: 2 additions & 2 deletions lib/zlib.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ const {
ArrayPrototypePush,
Error,
FunctionPrototypeBind,
MathMax,
MathMaxApply,
NumberIsFinite,
NumberIsNaN,
ObjectDefineProperties,
Expand Down Expand Up @@ -788,7 +788,7 @@ function createConvenienceMethod(ctor, sync) {
};
}

const kMaxBrotliParam = MathMax(...ArrayPrototypeMap(
const kMaxBrotliParam = MathMaxApply(ArrayPrototypeMap(
ObjectKeys(constants),
(key) => (StringPrototypeStartsWith(key, 'BROTLI_PARAM_') ?
constants[key] :
Expand Down
74 changes: 74 additions & 0 deletions test/parallel/test-primordials-apply.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Flags: --expose-internals
'use strict';

require('../common');

const assert = require('assert');
const {
ArrayOfApply,
ArrayPrototypePushApply,
ArrayPrototypeUnshiftApply,
MathMaxApply,
MathMinApply,
StringPrototypeConcatApply,
TypedArrayOfApply,
} = require('internal/test/binding').primordials;

{
const arr1 = [1, 2, 3];
const arr2 = ArrayOfApply(arr1);

assert.deepStrictEqual(arr2, arr1);
assert.notStrictEqual(arr2, arr1);
}

{
const array = [1, 2, 3];
const i32Array = TypedArrayOfApply(Int32Array, array);

assert(i32Array instanceof Int32Array);
assert.strictEqual(i32Array.length, array.length);
for (let i = 0, { length } = array; i < length; i++) {
assert.strictEqual(i32Array[i], array[i], `i32Array[${i}] === array[${i}]`);
}
}

{
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const expected = [...arr1, ...arr2];

assert.strictEqual(ArrayPrototypePushApply(arr1, arr2), expected.length);
assert.deepStrictEqual(arr1, expected);
}

{
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const expected = [...arr2, ...arr1];

assert.strictEqual(ArrayPrototypeUnshiftApply(arr1, arr2), expected.length);
assert.deepStrictEqual(arr1, expected);
}

{
const array = [1, 2, 3];
assert.strictEqual(MathMaxApply(array), 3);
assert.strictEqual(MathMinApply(array), 1);
}

{
let hint;
const obj = { [Symbol.toPrimitive](h) {
hint = h;
return '[object Object]';
} };

const args = ['foo ', obj, ' bar'];
const result = StringPrototypeConcatApply('', args);

assert.strictEqual(hint, 'string');
assert.strictEqual(result, 'foo [object Object] bar');
}