Skip to content

Commit

Permalink
Make use of JS rest and spread operators throughout the codebase. NFC
Browse files Browse the repository at this point in the history
Following up on emscripten-core#21270.  These operators were introduced way before
our current default set of browser versions.  Anyone targeting an
browser so old as to not support these will already be on the
transpilation path.
  • Loading branch information
sbc100 committed Feb 6, 2024
1 parent c47d060 commit 9629049
Show file tree
Hide file tree
Showing 37 changed files with 95 additions and 106 deletions.
2 changes: 1 addition & 1 deletion src/cpuprofiler.js
Original file line number Diff line number Diff line change
Expand Up @@ -580,7 +580,7 @@ var emscriptenCpuProfiler = {
var realf = 'real_' + f;
glCtx[realf] = glCtx[f];
var numArgs = this.webGLFunctionLength(f); // On Firefox & Chrome, could do "glCtx[realf].length", but that doesn't work on Edge, which always reports 0.
// Accessing 'arguments' is super slow, so to avoid overhead, statically reason the number of arguments.
// Accessing 'arguments'/'...' is super slow, so to avoid overhead, statically reason the number of arguments.
switch (numArgs) {
case 0: glCtx[f] = () => { this.enterSection(section); var ret = glCtx[realf](); this.endSection(section); return ret; }; break;
case 1: glCtx[f] = (a1) => { this.enterSection(section); var ret = glCtx[realf](a1); this.endSection(section); return ret; }; break;
Expand Down
34 changes: 16 additions & 18 deletions src/embind/embind.js
Original file line number Diff line number Diff line change
Expand Up @@ -98,12 +98,12 @@ var LibraryEmbind = {
if (undefined === proto[methodName].overloadTable) {
var prevFunc = proto[methodName];
// Inject an overload resolver function that routes to the appropriate overload based on the number of arguments.
proto[methodName] = function() {
proto[methodName] = function(...args) {
// TODO This check can be removed in -O3 level "unsafe" optimizations.
if (!proto[methodName].overloadTable.hasOwnProperty(arguments.length)) {
throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${arguments.length}) - expects one of (${proto[methodName].overloadTable})!`);
if (!proto[methodName].overloadTable.hasOwnProperty(args.length)) {
throwBindingError(`Function '${humanName}' called with an invalid number of arguments (${args.length}) - expects one of (${proto[methodName].overloadTable})!`);
}
return proto[methodName].overloadTable[arguments.length].apply(this, arguments);
return proto[methodName].overloadTable[args.length].apply(this, args);
};
// Move the previous function into the overload table.
proto[methodName].overloadTable = [];
Expand Down Expand Up @@ -818,9 +818,9 @@ var LibraryEmbind = {
var argsWired = new Array(expectedArgCount);
var invokerFuncArgs = [];
var destructors = [];
var invokerFn = function() {
if (arguments.length !== expectedArgCount) {
throwBindingError(`function ${humanName} called with ${arguments.length} arguments, expected ${expectedArgCount}`);
var invokerFn = function(...args) {
if (args.length !== expectedArgCount) {
throwBindingError(`function ${humanName} called with ${args.length} arguments, expected ${expectedArgCount}`);
}
#if EMSCRIPTEN_TRACING
Module.emscripten_trace_enter_context(`embind::${humanName}`);
Expand All @@ -834,7 +834,7 @@ var LibraryEmbind = {
invokerFuncArgs[1] = thisWired;
}
for (var i = 0; i < expectedArgCount; ++i) {
argsWired[i] = argTypes[i + 2]['toWireType'](destructors, arguments[i]);
argsWired[i] = argTypes[i + 2]['toWireType'](destructors, args[i]);
invokerFuncArgs.push(argsWired[i]);
}

Expand Down Expand Up @@ -1765,18 +1765,18 @@ var LibraryEmbind = {
basePrototype = ClassHandle.prototype;
}

var constructor = createNamedFunction(name, function() {
var constructor = createNamedFunction(name, function(...args) {
if (Object.getPrototypeOf(this) !== instancePrototype) {
throw new BindingError("Use 'new' to construct " + name);
}
if (undefined === registeredClass.constructor_body) {
throw new BindingError(name + " has no accessible constructor");
}
var body = registeredClass.constructor_body[arguments.length];
var body = registeredClass.constructor_body[args.length];
if (undefined === body) {
throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${arguments.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`);
throw new BindingError(`Tried to invoke ctor of ${name} with invalid number of parameters (${args.length}) - expected (${Object.keys(registeredClass.constructor_body).toString()}) parameters instead!`);
}
return body.apply(this, arguments);
return body.apply(this, args);
});

var instancePrototype = Object.create(basePrototype, {
Expand Down Expand Up @@ -2197,14 +2197,12 @@ var LibraryEmbind = {
wrapperType = requireRegisteredType(wrapperType, 'wrapper');
properties = Emval.toValue(properties);

var arraySlice = [].slice;

var registeredClass = wrapperType.registeredClass;
var wrapperPrototype = registeredClass.instancePrototype;
var baseClass = registeredClass.baseClass;
var baseClassPrototype = baseClass.instancePrototype;
var baseConstructor = registeredClass.baseClass.constructor;
var ctor = createNamedFunction(constructorName, function() {
var ctor = createNamedFunction(constructorName, function(...args) {
registeredClass.baseClass.pureVirtualFunctions.forEach(function(name) {
if (this[name] === baseClassPrototype[name]) {
throw new PureVirtualError(`Pure virtual function ${name} must be implemented in JavaScript`);
Expand All @@ -2214,19 +2212,19 @@ var LibraryEmbind = {
Object.defineProperty(this, '__parent', {
value: wrapperPrototype
});
this["__construct"].apply(this, arraySlice.call(arguments));
this["__construct"].apply(this, args);
});

// It's a little nasty that we're modifying the wrapper prototype here.

wrapperPrototype["__construct"] = function __construct() {
wrapperPrototype["__construct"] = function __construct(...args) {
if (this === wrapperPrototype) {
throwBindingError("Pass correct 'this' to __construct");
}

var inner = baseConstructor["implement"].apply(
undefined,
[this].concat(arraySlice.call(arguments)));
[this].concat(args));
detachFinalizer(inner);
var $$ = inner.$$;
inner["notifyOnDestruction"]();
Expand Down
4 changes: 2 additions & 2 deletions src/jsifier.js
Original file line number Diff line number Diff line change
Expand Up @@ -237,9 +237,9 @@ ${argConvertions}
if (LIBRARY_DEBUG && !isJsOnlySymbol(symbol)) {
snippet = modifyJSFunction(snippet, (args, body, async) => `\
function(${args}) {
var ret = (function() { if (runtimeDebug) err("[library call:${mangled}: " + Array.prototype.slice.call(arguments).map(prettyPrint) + "]");
var ret = (function(...args) { if (runtimeDebug) err("[library call:${mangled}: " + args.map(prettyPrint) + "]");
${body}
}).apply(this, arguments);
}).apply(this, ...args);
if (runtimeDebug && typeof ret != "undefined") err(" [ return:" + prettyPrint(ret));
return ret;
}`);
Expand Down
7 changes: 1 addition & 6 deletions src/library.js
Original file line number Diff line number Diff line change
Expand Up @@ -3113,12 +3113,7 @@ addToLibrary({
#if ASSERTIONS && !DYNCALLS
assert(sig.includes('j') || sig.includes('p'), 'getDynCaller should only be called with i64 sigs')
#endif
var argCache = [];
return function() {
argCache.length = 0;
Object.assign(argCache, arguments);
return dynCall(sig, ptr, argCache);
};
return (...args) => dynCall(sig, ptr, args);
},
$dynCall__docs: '/** @param {Object=} args */',
Expand Down
10 changes: 5 additions & 5 deletions src/library_async.js
Original file line number Diff line number Diff line change
Expand Up @@ -68,10 +68,10 @@ addToLibrary({
}
#endif
#if ASSERTIONS && ASYNCIFY != 2 // We cannot apply assertions with stack switching, as the imports must not be modified from suspender.suspendOnReturnedPromise TODO find a way
imports[x] = function() {
imports[x] = (...args) => {
var originalAsyncifyState = Asyncify.state;
try {
return original.apply(null, arguments);
return original.apply(null, args);
} finally {
// Only asyncify-declared imports are allowed to change the
// state.
Expand Down Expand Up @@ -130,7 +130,7 @@ addToLibrary({
original = Asyncify.makeAsyncFunction(original);
}
#endif
ret[x] = function() {
ret[x] = (...args) => {
#if ASYNCIFY_DEBUG >= 2
dbg(`ASYNCIFY: ${' '.repeat(Asyncify.exportCallStack.length} try ${x}`);
#endif
Expand All @@ -143,9 +143,9 @@ addToLibrary({
// can just call the function with no args at all since and the engine will produce zeros
// for all arguments. However, for i64 arguments we get `undefined cannot be converted to
// BigInt`.
return original.apply(null, Asyncify.saveOrRestoreRewindArguments(x, arguments));
return original.apply(null, Asyncify.saveOrRestoreRewindArguments(x, args));
#else
return original.apply(null, arguments);
return original.apply(null, args);
#endif
#if ASYNCIFY == 1
} finally {
Expand Down
4 changes: 2 additions & 2 deletions src/library_fs.js
Original file line number Diff line number Diff line change
Expand Up @@ -1784,9 +1784,9 @@ FS.staticInit();` +
var keys = Object.keys(node.stream_ops);
keys.forEach((key) => {
var fn = node.stream_ops[key];
stream_ops[key] = function forceLoadLazyFile() {
stream_ops[key] = (...args) => {
FS.forceLoadFile(node);
return fn.apply(null, arguments);
return fn.apply(null, ...args);
};
});
function writeChunks(stream, buffer, offset, length, position) {
Expand Down
6 changes: 2 additions & 4 deletions src/library_idbfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,10 +21,8 @@ addToLibrary({
},
DB_VERSION: 21,
DB_STORE_NAME: 'FILE_DATA',
mount: function(mount) {
// reuse all of the core MEMFS functionality
return MEMFS.mount.apply(null, arguments);
},
// reuse all of the core MEMFS functionality
mount: (...args) => MEMFS.mount.apply(null, ...args);
syncfs: (mount, populate, callback) => {
IDBFS.getLocalSet(mount, (err, local) => {
if (err) return callback(err);
Expand Down
7 changes: 2 additions & 5 deletions src/library_nodepath.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,15 @@ addToLibrary({
normalize: (path) => nodePath['normalize'](path),
dirname: (path) => nodePath['dirname'](path),
basename: (path) => nodePath['basename'](path),
join: function () {
return nodePath['join'].apply(null, arguments);
},
join: (...args) => nodePath['join'].apply(null, args),
join2: (l, r) => nodePath['join'](l, r),
},
// The FS-using parts are split out into a separate object, so simple path
// usage does not require the FS.
$PATH_FS__deps: ['$FS'],
$PATH_FS__docs: '/** @type{{resolve: function(...*)}} */',
$PATH_FS: {
resolve: function () {
var paths = Array.prototype.slice.call(arguments, 0);
resolve: (...paths) => {
paths.unshift(FS.cwd());
return nodePath['posix']['resolve'].apply(null, paths);
},
Expand Down
30 changes: 15 additions & 15 deletions src/library_noderawfs.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,9 @@ addToLibrary({
$NODERAWFS__postset: `
if (ENVIRONMENT_IS_NODE) {
var _wrapNodeError = function(func) {
return function() {
return function(...args) {
try {
return func.apply(this, arguments)
return func.apply(this, args)
} catch (e) {
if (e.code) {
throw new FS.ErrnoError(ERRNO_CODES[e.code]);
Expand Down Expand Up @@ -52,34 +52,34 @@ addToLibrary({
},
// generic function for all node creation
cwd() { return process.cwd(); },
chdir() { process.chdir.apply(void 0, arguments); },
chdir() { process.chdir.apply(void 0, args); },
mknod(path, mode) {
if (FS.isDir(path)) {
fs.mkdirSync(path, mode);
} else {
fs.writeFileSync(path, '', { mode: mode });
}
},
mkdir() { fs.mkdirSync.apply(void 0, arguments); },
symlink() { fs.symlinkSync.apply(void 0, arguments); },
rename() { fs.renameSync.apply(void 0, arguments); },
rmdir() { fs.rmdirSync.apply(void 0, arguments); },
readdir() { return ['.', '..'].concat(fs.readdirSync.apply(void 0, arguments)); },
unlink() { fs.unlinkSync.apply(void 0, arguments); },
readlink() { return fs.readlinkSync.apply(void 0, arguments); },
stat() { return fs.statSync.apply(void 0, arguments); },
lstat() { return fs.lstatSync.apply(void 0, arguments); },
chmod() { fs.chmodSync.apply(void 0, arguments); },
mkdir(...args) { fs.mkdirSync.apply(void 0, args); },
symlink(...args) { fs.symlinkSync.apply(void 0, args); },
rename(...args) { fs.renameSync.apply(void 0, args); },
rmdir(...args) { fs.rmdirSync.apply(void 0, args); },
readdir(...args) { return ['.', '..'].concat(fs.readdirSync.apply(void 0, args)); },
unlink(...args) { fs.unlinkSync.apply(void 0, args); },
readlink(...args) { return fs.readlinkSync.apply(void 0, args); },
stat(...args) { return fs.statSync.apply(void 0, args); },
lstat(...args) { return fs.lstatSync.apply(void 0, args); },
chmod(...args) { fs.chmodSync.apply(void 0, args); },
fchmod(fd, mode) {
var stream = FS.getStreamChecked(fd);
fs.fchmodSync(stream.nfd, mode);
},
chown() { fs.chownSync.apply(void 0, arguments); },
chown(...args) { fs.chownSync.apply(void 0, args); },
fchown(fd, owner, group) {
var stream = FS.getStreamChecked(fd);
fs.fchownSync(stream.nfd, owner, group);
},
truncate() { fs.truncateSync.apply(void 0, arguments); },
truncate(...args) { fs.truncateSync.apply(void 0, args); },
ftruncate(fd, len) {
// See https://github.com/nodejs/node/issues/35632
if (len < 0) {
Expand Down
11 changes: 4 additions & 7 deletions src/library_path.js
Original file line number Diff line number Diff line change
Expand Up @@ -72,10 +72,7 @@ addToLibrary({
if (lastSlash === -1) return path;
return path.substr(lastSlash+1);
},
join: function() {
var paths = Array.prototype.slice.call(arguments);
return PATH.normalize(paths.join('/'));
},
join: (...paths) => PATH.normalize(paths.join('/')),
join2: (l, r) => PATH.normalize(l + '/' + r),
},
// The FS-using parts are split out into a separate object, so simple path
Expand All @@ -90,11 +87,11 @@ addToLibrary({
#endif
],
$PATH_FS: {
resolve: function() {
resolve: (...args) => {
var resolvedPath = '',
resolvedAbsolute = false;
for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? arguments[i] : FS.cwd();
for (var i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) {
var path = (i >= 0) ? args[i] : FS.cwd();
// Skip empty and invalid entries
if (typeof path != 'string') {
throw new TypeError('Arguments to path.resolve must be strings');
Expand Down
14 changes: 7 additions & 7 deletions src/preamble.js
Original file line number Diff line number Diff line change
Expand Up @@ -513,14 +513,14 @@ Module['FS_createPreloadedFile'] = FS.createPreloadedFile;
#if ASSERTIONS
function createExportWrapper(name) {
return function() {
return (...args) => {
assert(runtimeInitialized, `native function \`${name}\` called before runtime initialization`);
#if EXIT_RUNTIME
assert(!runtimeExited, `native function \`${name}\` called after runtime exit (use NO_EXIT_RUNTIME to keep it alive after main() exits)`);
#endif
var f = wasmExports[name];
assert(f, `exported native function \`${name}\` not found`);
return f.apply(null, arguments);
return f.apply(null, args);
};
}
#endif
Expand All @@ -537,15 +537,15 @@ var abortWrapperDepth = 0;
// Creates a wrapper in a closure so that each wrapper gets it's own copy of 'original'
function makeAbortWrapper(original) {
return function() {
return (...args) => {
// Don't allow this function to be called if we're aborted!
if (ABORT) {
throw "program has already aborted!";
}
abortWrapperDepth += 1;
try {
return original.apply(null, arguments);
return original.apply(null, args);
} catch (e) {
if (
ABORT // rethrow exception if abort() was called in the original function call above
Expand Down Expand Up @@ -700,7 +700,7 @@ var wasmOffsetConverter;
{{{ makeModuleReceiveWithVar('loadSplitModule', undefined, 'instantiateSync', true) }}}
var splitModuleProxyHandler = {
get(target, prop, receiver) {
return function() {
return (...args) => {
#if ASYNCIFY == 2
throw new Error('Placeholder function "' + prop + '" should not be called when using JSPI.');
#else
Expand All @@ -714,9 +714,9 @@ var splitModuleProxyHandler = {
// When the table is dynamically laid out, the placeholder functions names
// are offsets from the table base. In the main module, the table base is
// always 1.
return wasmTable.get(1 + parseInt(prop)).apply(null, arguments);
return wasmTable.get(1 + parseInt(prop)).apply(null, args);
#else
return wasmTable.get(prop).apply(null, arguments);
return wasmTable.get(prop).apply(null, args);
#endif
#endif
}
Expand Down
6 changes: 3 additions & 3 deletions src/runtime_debug.js
Original file line number Diff line number Diff line change
Expand Up @@ -161,16 +161,16 @@ function prettyPrint(arg) {

#if ASSERTIONS || RUNTIME_DEBUG || AUTODEBUG
// Used by XXXXX_DEBUG settings to output debug messages.
function dbg(text) {
function dbg(...args) {
#if ENVIRONMENT_MAY_BE_NODE && PTHREADS
// Avoid using the console for debugging in multi-threaded node applications
// See https://github.com/emscripten-core/emscripten/issues/14804
if (ENVIRONMENT_IS_NODE) {
fs.writeSync(2, Array.from(arguments).join(' ') + '\n');
fs.writeSync(2, argss.join(' ') + '\n');
} else
#endif
// TODO(sbc): Make this configurable somehow. Its not always convenient for
// logging to show up as warnings.
console.warn.apply(console, arguments);
console.warn.apply(console, args);
}
#endif
4 changes: 2 additions & 2 deletions src/shell.html
Original file line number Diff line number Diff line change
Expand Up @@ -38,8 +38,8 @@
print: (function() {
var element = document.getElementById('output');
if (element) element.value = ''; // clear browser cache
return function(text) {
if (arguments.length > 1) text = Array.prototype.slice.call(arguments).join(' ');
return function(...args) => {
text = args.join(' ');
// These replacements are necessary if you render to raw HTML
//text = text.replace(/&/g, "&amp;");
//text = text.replace(/</g, "&lt;");
Expand Down
Loading

0 comments on commit 9629049

Please sign in to comment.