diff --git a/src/Fetch.js b/src/Fetch.js index c70f235d62464..e34d9574f9b7d 100644 --- a/src/Fetch.js +++ b/src/Fetch.js @@ -82,7 +82,7 @@ function fetchDeleteCachedData(db, fetch, onsuccess, onerror) { var fetch_attr = fetch + {{{ C_STRUCTS.emscripten_fetch_t.__attributes }}}; var path = HEAPU32[fetch_attr + {{{ C_STRUCTS.emscripten_fetch_attr_t.destinationPath }}} >> 2]; - if (!path) path = HEAPU32[fetch + {{{ C_STRUCTS.emscripten_fetch_t.url }}} >> 2]; + path ||= HEAPU32[fetch + {{{ C_STRUCTS.emscripten_fetch_t.url }}} >> 2]; var pathStr = UTF8ToString(path); try { @@ -131,7 +131,7 @@ function fetchLoadCachedData(db, fetch, onsuccess, onerror) { var fetch_attr = fetch + {{{ C_STRUCTS.emscripten_fetch_t.__attributes }}}; var path = HEAPU32[fetch_attr + {{{ C_STRUCTS.emscripten_fetch_attr_t.destinationPath }}} >> 2]; - if (!path) path = HEAPU32[fetch + {{{ C_STRUCTS.emscripten_fetch_t.url }}} >> 2]; + path ||= HEAPU32[fetch + {{{ C_STRUCTS.emscripten_fetch_t.url }}} >> 2]; var pathStr = UTF8ToString(path); try { @@ -196,7 +196,7 @@ function fetchCacheData(/** @type {IDBDatabase} */ db, fetch, data, onsuccess, o var fetch_attr = fetch + {{{ C_STRUCTS.emscripten_fetch_t.__attributes }}}; var destinationPath = HEAPU32[fetch_attr + {{{ C_STRUCTS.emscripten_fetch_attr_t.destinationPath }}} >> 2]; - if (!destinationPath) destinationPath = HEAPU32[fetch + {{{ C_STRUCTS.emscripten_fetch_t.url }}} >> 2]; + destinationPath ||= HEAPU32[fetch + {{{ C_STRUCTS.emscripten_fetch_t.url }}} >> 2]; var destinationPathStr = UTF8ToString(destinationPath); try { @@ -246,7 +246,7 @@ function fetchXHR(fetch, onsuccess, onerror, onprogress, onreadystatechange) { var fetch_attr = fetch + {{{ C_STRUCTS.emscripten_fetch_t.__attributes }}}; var requestMethod = UTF8ToString(fetch_attr + {{{ C_STRUCTS.emscripten_fetch_attr_t.requestMethod }}}); - if (!requestMethod) requestMethod = 'GET'; + requestMethod ||= 'GET'; var timeoutMsecs = {{{ makeGetValue('fetch_attr', C_STRUCTS.emscripten_fetch_attr_t.timeoutMSecs, 'u32') }}}; var userName = {{{ makeGetValue('fetch_attr', C_STRUCTS.emscripten_fetch_attr_t.userName, '*') }}}; var password = {{{ makeGetValue('fetch_attr', C_STRUCTS.emscripten_fetch_attr_t.password, '*') }}}; @@ -352,12 +352,12 @@ function fetchXHR(fetch, onsuccess, onerror, onprogress, onreadystatechange) { #if FETCH_DEBUG dbg(`fetch: xhr of URL "${xhr.url_}" / responseURL "${xhr.responseURL}" succeeded with status ${xhr.status}`); #endif - if (onsuccess) onsuccess(fetch, xhr, e); + onsuccess?.(fetch, xhr, e); } else { #if FETCH_DEBUG dbg(`fetch: xhr of URL "${xhr.url_}" / responseURL "${xhr.responseURL}" failed with status ${xhr.status}`); #endif - if (onerror) onerror(fetch, xhr, e); + onerror?.(fetch, xhr, e); } }; xhr.onerror = (e) => { @@ -369,7 +369,7 @@ function fetchXHR(fetch, onsuccess, onerror, onprogress, onreadystatechange) { dbg(`fetch: xhr of URL "${xhr.url_}" / responseURL "${xhr.responseURL}" finished with error, readyState ${xhr.readyState} and status ${xhr.status}`); #endif saveResponseAndStatus(); - if (onerror) onerror(fetch, xhr, e); + onerror?.(fetch, xhr, e); }; xhr.ontimeout = (e) => { // check if xhr was aborted by user and don't try to call back @@ -379,7 +379,7 @@ function fetchXHR(fetch, onsuccess, onerror, onprogress, onreadystatechange) { #if FETCH_DEBUG dbg(`fetch: xhr of URL "${xhr.url_}" / responseURL "${xhr.responseURL}" timed out, readyState ${xhr.readyState} and status ${xhr.status}`); #endif - if (onerror) onerror(fetch, xhr, e); + onerror?.(fetch, xhr, e); }; xhr.onprogress = (e) => { // check if xhr was aborted by user and don't try to call back @@ -408,7 +408,7 @@ function fetchXHR(fetch, onsuccess, onerror, onprogress, onreadystatechange) { if (xhr.readyState >= 3 && xhr.status === 0 && e.loaded > 0) xhr.status = 200; HEAPU16[fetch + {{{ C_STRUCTS.emscripten_fetch_t.status }}} >> 1] = xhr.status; if (xhr.statusText) stringToUTF8(xhr.statusText, fetch + {{{ C_STRUCTS.emscripten_fetch_t.statusText }}}, 64); - if (onprogress) onprogress(fetch, xhr, e); + onprogress?.(fetch, xhr, e); if (ptr) { _free(ptr); } @@ -423,7 +423,7 @@ function fetchXHR(fetch, onsuccess, onerror, onprogress, onreadystatechange) { if (xhr.readyState >= 2) { HEAPU16[fetch + {{{ C_STRUCTS.emscripten_fetch_t.status }}} >> 1] = xhr.status; } - if (onreadystatechange) onreadystatechange(fetch, xhr, e); + onreadystatechange?.(fetch, xhr, e); }; #if FETCH_DEBUG dbg(`fetch: xhr.send(data=${data})`); @@ -434,7 +434,7 @@ function fetchXHR(fetch, onsuccess, onerror, onprogress, onreadystatechange) { #if FETCH_DEBUG dbg(`fetch: xhr failed with exception: ${e}`); #endif - if (onerror) onerror(fetch, xhr, e); + onerror?.(fetch, xhr, e); } } @@ -466,14 +466,14 @@ function startFetch(fetch, successcb, errorcb, progresscb, readystatechangecb) { {{{ runtimeKeepalivePop() }}} doCallback(() => { if (onsuccess) {{{ makeDynCall('vp', 'onsuccess') }}}(fetch); - else if (successcb) successcb(fetch); + else successcb?.(fetch); }); }; var reportProgress = (fetch, xhr, e) => { doCallback(() => { if (onprogress) {{{ makeDynCall('vp', 'onprogress') }}}(fetch); - else if (progresscb) progresscb(fetch); + else progresscb?.(fetch); }); }; @@ -484,7 +484,7 @@ function startFetch(fetch, successcb, errorcb, progresscb, readystatechangecb) { {{{ runtimeKeepalivePop() }}} doCallback(() => { if (onerror) {{{ makeDynCall('vp', 'onerror') }}}(fetch); - else if (errorcb) errorcb(fetch); + else errorcb?.(fetch); }); }; @@ -494,7 +494,7 @@ function startFetch(fetch, successcb, errorcb, progresscb, readystatechangecb) { #endif doCallback(() => { if (onreadystatechange) {{{ makeDynCall('vp', 'onreadystatechange') }}}(fetch); - else if (readystatechangecb) readystatechangecb(fetch); + else readystatechangecb?.(fetch); }); }; @@ -517,7 +517,7 @@ function startFetch(fetch, successcb, errorcb, progresscb, readystatechangecb) { {{{ runtimeKeepalivePop() }}} doCallback(() => { if (onsuccess) {{{ makeDynCall('vp', 'onsuccess') }}}(fetch); - else if (successcb) successcb(fetch); + else successcb?.(fetch); }); }; var storeError = (fetch, xhr, e) => { @@ -527,7 +527,7 @@ function startFetch(fetch, successcb, errorcb, progresscb, readystatechangecb) { {{{ runtimeKeepalivePop() }}} doCallback(() => { if (onsuccess) {{{ makeDynCall('vp', 'onsuccess') }}}(fetch); - else if (successcb) successcb(fetch); + else successcb?.(fetch); }); }; fetchCacheData(Fetch.dbInstance, fetch, xhr.response, storeSuccess, storeError); diff --git a/src/cpuprofiler.js b/src/cpuprofiler.js index 8929f6e07ded0..79d06b37c244c 100644 --- a/src/cpuprofiler.js +++ b/src/cpuprofiler.js @@ -148,37 +148,35 @@ var emscriptenCpuProfiler = { createSection: function createSection(number, name, drawColor, traceable) { while (this.sections.length <= number) this.sections.push(null); // Keep an array structure. var sect = this.sections[number]; - if (!sect) { - sect = { - count: 0, - name, - startTick: 0, - accumulatedTimeInsideMainLoop: 0, - accumulatedTimeOutsideMainLoop: 0, - frametimesInsideMainLoop: [], - frametimesOutsideMainLoop: [], - drawColor, - traceable, - accumulatedFrameTimeInsideMainLoop: function(startX, numSamples) { - var total = 0; - numSamples = Math.min(numSamples, this.frametimesInsideMainLoop.length); - for (var i = 0; i < numSamples; ++i) { - var x = (startX + i) % this.frametimesInsideMainLoop.length; - if (this.frametimesInsideMainLoop[x]) total += this.frametimesInsideMainLoop[x]; - } - return total; - }, - accumulatedFrameTimeOutsideMainLoop: function(startX, numSamples) { - var total = 0; - numSamples = Math.min(numSamples, this.frametimesInsideMainLoop.length); - for (var i = 0; i < numSamples; ++i) { - var x = (startX + i) % this.frametimesInsideMainLoop.length; - if (this.frametimesOutsideMainLoop[x]) total += this.frametimesOutsideMainLoop[x]; - } - return total; + sect ||= { + count: 0, + name, + startTick: 0, + accumulatedTimeInsideMainLoop: 0, + accumulatedTimeOutsideMainLoop: 0, + frametimesInsideMainLoop: [], + frametimesOutsideMainLoop: [], + drawColor, + traceable, + accumulatedFrameTimeInsideMainLoop: function(startX, numSamples) { + var total = 0; + numSamples = Math.min(numSamples, this.frametimesInsideMainLoop.length); + for (var i = 0; i < numSamples; ++i) { + var x = (startX + i) % this.frametimesInsideMainLoop.length; + if (this.frametimesInsideMainLoop[x]) total += this.frametimesInsideMainLoop[x]; } - }; - } + return total; + }, + accumulatedFrameTimeOutsideMainLoop: function(startX, numSamples) { + var total = 0; + numSamples = Math.min(numSamples, this.frametimesInsideMainLoop.length); + for (var i = 0; i < numSamples; ++i) { + var x = (startX + i) % this.frametimesInsideMainLoop.length; + if (this.frametimesOutsideMainLoop[x]) total += this.frametimesOutsideMainLoop[x]; + } + return total; + } + }; sect.name = name; this.sections[number] = sect; }, @@ -532,14 +530,14 @@ var emscriptenCpuProfiler = { }, detectWebGLContext: function() { - if (Module['canvas'] && Module['canvas'].GLctxObject && Module['canvas'].GLctxObject.GLctx) return Module['canvas'].GLctxObject.GLctx; + if (Module['canvas']?.GLctxObject?.GLctx) return Module['canvas'].GLctxObject.GLctx; else if (typeof GLctx != 'undefined') return GLctx; else if (Module.ctx) return Module.ctx; return null; }, toggleHookWebGL: function(glCtx) { - if (!glCtx) glCtx = this.detectWebGLContext(); + glCtx ||= this.detectWebGLContext(); if (this.hookedWebGLContexts.includes(glCtx)) this.unhookWebGL(glCtx); else this.hookWebGL(glCtx); }, @@ -563,7 +561,7 @@ var emscriptenCpuProfiler = { }, unhookWebGL: function(glCtx) { - if (!glCtx) glCtx = this.detectWebGLContext(); + glCtx ||= this.detectWebGLContext(); if (!glCtx.cpuprofilerAlreadyHooked) return; glCtx.cpuprofilerAlreadyHooked = false; this.hookedWebGLContexts.splice(this.hookedWebGLContexts.indexOf(glCtx), 1); @@ -601,7 +599,7 @@ var emscriptenCpuProfiler = { }, hookWebGL: function(glCtx) { - if (!glCtx) glCtx = this.detectWebGLContext(); + glCtx ||= this.detectWebGLContext(); if (!glCtx) return; if (!((typeof WebGLRenderingContext != 'undefined' && glCtx instanceof WebGLRenderingContext) || (typeof WebGL2RenderingContext != 'undefined' && glCtx instanceof WebGL2RenderingContext))) { diff --git a/src/embind/embind.js b/src/embind/embind.js index e1d999a3f15d8..629b853d7611e 100644 --- a/src/embind/embind.js +++ b/src/embind/embind.js @@ -1370,9 +1370,7 @@ var LibraryEmbind = { return ptr; }, destructor(ptr) { - if (this.rawDestructor) { - this.rawDestructor(ptr); - } + this.rawDestructor?.(ptr); }, 'argPackAdvance': GenericWireTypeSize, 'readValueFromPointer': readPointer, @@ -1806,12 +1804,8 @@ var LibraryEmbind = { rawDestructor) => { name = readLatin1String(name); getActualType = embind__requireFunction(getActualTypeSignature, getActualType); - if (upcast) { - upcast = embind__requireFunction(upcastSignature, upcast); - } - if (downcast) { - downcast = embind__requireFunction(downcastSignature, downcast); - } + upcast &&= embind__requireFunction(upcastSignature, upcast); + downcast &&= embind__requireFunction(downcastSignature, downcast); rawDestructor = embind__requireFunction(destructorSignature, rawDestructor); var legalFunctionName = makeLegalFunctionName(name); @@ -1866,9 +1860,7 @@ var LibraryEmbind = { if (registeredClass.baseClass) { // Keep track of class hierarchy. Used to allow sub-classes to inherit class functions. - if (registeredClass.baseClass.__derivedClasses === undefined) { - registeredClass.baseClass.__derivedClasses = []; - } + registeredClass.baseClass.__derivedClasses ??= []; registeredClass.baseClass.__derivedClasses.push(registeredClass); } diff --git a/src/embind/emval.js b/src/embind/emval.js index 7dc47fb2e5c9a..cea116ca4ded3 100644 --- a/src/embind/emval.js +++ b/src/embind/emval.js @@ -336,9 +336,7 @@ var LibraryEmVal = { } var rv = kind === /* CONSTRUCTOR */ 1 ? reflectConstruct(func, argN) : func.apply(obj, argN); for (var i = 0; i < argCount; ++i) { - if (types[i].deleteObject) { - types[i].deleteObject(argN[i]); - } + types[i].deleteObject?.(argN[i]); } return emval_returnValue(retType, destructorsRef, rv); }; diff --git a/src/gl-matrix.js b/src/gl-matrix.js index 6dd0f80c787bc..99e8c069bcb30 100644 --- a/src/gl-matrix.js +++ b/src/gl-matrix.js @@ -180,7 +180,7 @@ vec3.multiply = function (vec, vec2, dest) { * _returns {vec3} dest if specified, vec otherwise */ vec3.negate = function (vec, dest) { - if (!dest) { dest = vec; } + dest ||= vec; dest[0] = -vec[0]; dest[1] = -vec[1]; @@ -221,7 +221,7 @@ vec3.scale = function (vec, val, dest) { * _returns {vec3} dest if specified, vec otherwise */ vec3.normalize = function (vec, dest) { - if (!dest) { dest = vec; } + dest ||= vec; var x = vec[0], y = vec[1], z = vec[2], len = Math.sqrt(x * x + y * y + z * z); @@ -255,7 +255,7 @@ vec3.normalize = function (vec, dest) { * _returns {vec3} dest if specified, vec otherwise */ vec3.cross = function (vec, vec2, dest) { - if (!dest) { dest = vec; } + dest ||= vec; var x = vec[0], y = vec[1], z = vec[2], x2 = vec2[0], y2 = vec2[1], z2 = vec2[2]; @@ -300,7 +300,7 @@ vec3.dot = function (vec, vec2) { * _returns {vec3} dest if specified, vec otherwise */ vec3.direction = function (vec, vec2, dest) { - if (!dest) { dest = vec; } + dest ||= vec; var x = vec[0] - vec2[0], y = vec[1] - vec2[1], @@ -332,7 +332,7 @@ vec3.direction = function (vec, vec2, dest) { * _returns {vec3} dest if specified, vec otherwise */ vec3.lerp = function (vec, vec2, lerp, dest) { - if (!dest) { dest = vec; } + dest ||= vec; dest[0] = vec[0] + lerp * (vec2[0] - vec[0]); dest[1] = vec[1] + lerp * (vec2[1] - vec[1]); @@ -371,7 +371,7 @@ vec3.dist = function (vec, vec2) { * _returns {vec3} dest if specified, vec otherwise */ vec3.unproject = function (vec, view, proj, viewport, dest) { - if (!dest) { dest = vec; } + dest ||= vec; var m = mat4.create(); var v = new MatrixArray(4); @@ -466,7 +466,7 @@ mat3.set = function (mat, dest) { * _returns dest if specified, otherwise a new mat3 */ mat3.identity = function (dest) { - if (!dest) { dest = mat3.create(); } + dest ||= mat3.create(); dest[0] = 1; dest[1] = 0; dest[2] = 0; @@ -522,7 +522,7 @@ mat3.transpose = function (mat, dest) { * _returns {mat4} dest if specified, a new mat4 otherwise */ mat3.toMat4 = function (mat, dest) { - if (!dest) { dest = mat4.create(); } + dest ||= mat4.create(); dest[15] = 1; dest[14] = 0; @@ -635,7 +635,7 @@ mat4.set = function (mat, dest) { * _returns {mat4} dest */ mat4.identity = function (dest) { - if (!dest) { dest = mat4.create(); } + dest ||= mat4.create(); dest[0] = 1; dest[1] = 0; dest[2] = 0; @@ -733,7 +733,7 @@ mat4.determinant = function (mat) { * @param {Object=} dest */ mat4.inverse = function (mat, dest) { - if (!dest) { dest = mat; } + dest ||= mat; // Cache the matrix values (makes for huge speed increases!) var a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3], @@ -790,7 +790,7 @@ mat4.inverse = function (mat, dest) { * _returns {mat4} dest is specified, a new mat4 otherwise */ mat4.toRotationMat = function (mat, dest) { - if (!dest) { dest = mat4.create(); } + dest ||= mat4.create(); dest[0] = mat[0]; dest[1] = mat[1]; @@ -821,7 +821,7 @@ mat4.toRotationMat = function (mat, dest) { * _returns {mat3} dest is specified, a new mat3 otherwise */ mat4.toMat3 = function (mat, dest) { - if (!dest) { dest = mat3.create(); } + dest ||= mat3.create(); dest[0] = mat[0]; dest[1] = mat[1]; @@ -862,7 +862,7 @@ mat4.toInverseMat3 = function (mat, dest) { if (!d) { return null; } id = 1 / d; - if (!dest) { dest = mat3.create(); } + dest ||= mat3.create(); dest[0] = b01 * id; dest[1] = (-a22 * a01 + a02 * a21) * id; @@ -885,7 +885,7 @@ mat4.toInverseMat3 = function (mat, dest) { * _param {mat4} [dest] mat4 receiving operation result. If not specified result is written to mat */ mat4.multiply = function (mat, mat2, dest) { - if (!dest) { dest = mat; } + dest ||= mat; // Cache the matrix values (makes for huge speed increases!) var a00 = mat[0], a01 = mat[1], a02 = mat[2], a03 = mat[3], @@ -929,7 +929,7 @@ mat4.multiply = function (mat, mat2, dest) { * _returns {vec3} dest if specified, vec otherwise */ mat4.multiplyVec3 = function (mat, vec, dest) { - if (!dest) { dest = vec; } + dest ||= vec; var x = vec[0], y = vec[1], z = vec[2]; @@ -952,7 +952,7 @@ mat4.multiplyVec3 = function (mat, vec, dest) { * @param {Object=} dest */ mat4.multiplyVec4 = function (mat, vec, dest) { - if (!dest) { dest = vec; } + dest ||= vec; var x = vec[0], y = vec[1], z = vec[2], w = vec[3]; @@ -1266,7 +1266,7 @@ mat4.rotateZ = function (mat, angle, dest) { * _returns {mat4} dest if specified, a new mat4 otherwise */ mat4.frustum = function (left, right, bottom, top, near, far, dest) { - if (!dest) { dest = mat4.create(); } + dest ||= mat4.create(); var rl = (right - left), tb = (top - bottom), fn = (far - near); @@ -1320,7 +1320,7 @@ mat4.perspective = function (fovy, aspect, near, far, dest) { * _returns {mat4} dest if specified, a new mat4 otherwise */ mat4.ortho = function (left, right, bottom, top, near, far, dest) { - if (!dest) { dest = mat4.create(); } + dest ||= mat4.create(); var rl = (right - left), tb = (top - bottom), fn = (far - near); @@ -1354,7 +1354,7 @@ mat4.ortho = function (left, right, bottom, top, near, far, dest) { * _returns {mat4} dest if specified, a new mat4 otherwise */ mat4.lookAt = function (eye, center, up, dest) { - if (!dest) { dest = mat4.create(); } + dest ||= mat4.create(); var x0, x1, x2, y0, y1, y2, z0, z1, z2, len, eyex = eye[0], @@ -1452,7 +1452,7 @@ mat4.lookAt = function (eye, center, up, dest) { * _returns {mat4} dest if specified, a new mat4 otherwise */ mat4.fromRotationTranslation = function (quat, vec, dest) { - if (!dest) { dest = mat4.create(); } + dest ||= mat4.create(); // Quaternion math var x = quat[0], y = quat[1], z = quat[2], w = quat[3], @@ -1658,7 +1658,7 @@ quat4.length = function (quat) { * _returns {quat4} dest if specified, quat otherwise */ quat4.normalize = function (quat, dest) { - if (!dest) { dest = quat; } + dest ||= quat; var x = quat[0], y = quat[1], z = quat[2], w = quat[3], len = Math.sqrt(x * x + y * y + z * z + w * w); @@ -1712,7 +1712,7 @@ quat4.add = function (quat, quat2, dest) { * _returns {quat4} dest if specified, quat otherwise */ quat4.multiply = function (quat, quat2, dest) { - if (!dest) { dest = quat; } + dest ||= quat; var qax = quat[0], qay = quat[1], qaz = quat[2], qaw = quat[3], qbx = quat2[0], qby = quat2[1], qbz = quat2[2], qbw = quat2[3]; @@ -1735,7 +1735,7 @@ quat4.multiply = function (quat, quat2, dest) { * _returns dest if specified, vec otherwise */ quat4.multiplyVec3 = function (quat, vec, dest) { - if (!dest) { dest = vec; } + dest ||= vec; var x = vec[0], y = vec[1], z = vec[2], qx = quat[0], qy = quat[1], qz = quat[2], qw = quat[3], @@ -1787,7 +1787,7 @@ quat4.scale = function (quat, val, dest) { * _returns {mat3} dest if specified, a new mat3 otherwise */ quat4.toMat3 = function (quat, dest) { - if (!dest) { dest = mat3.create(); } + dest ||= mat3.create(); var x = quat[0], y = quat[1], z = quat[2], w = quat[3], x2 = x + x, @@ -1828,7 +1828,7 @@ quat4.toMat3 = function (quat, dest) { * _returns {mat4} dest if specified, a new mat4 otherwise */ quat4.toMat4 = function (quat, dest) { - if (!dest) { dest = mat4.create(); } + dest ||= mat4.create(); var x = quat[0], y = quat[1], z = quat[2], w = quat[3], x2 = x + x, @@ -1879,7 +1879,7 @@ quat4.toMat4 = function (quat, dest) { * _returns {quat4} dest if specified, quat otherwise */ quat4.slerp = function (quat, quat2, slerp, dest) { - if (!dest) { dest = quat; } + dest ||= quat; var cosHalfTheta = quat[0] * quat2[0] + quat[1] * quat2[1] + quat[2] * quat2[2] + quat[3] * quat2[3], halfTheta, diff --git a/src/headless.js b/src/headless.js index 72baac8aa8284..18f8fa339addc 100644 --- a/src/headless.js +++ b/src/headless.js @@ -83,9 +83,7 @@ var window = { eventListeners: {}, addEventListener(id, func) { var listeners = this.eventListeners[id]; - if (!listeners) { - listeners = this.eventListeners[id] = []; - } + listeners ||= this.eventListeners[id] = []; listeners.push(func); }, removeEventListener(id, func) { @@ -161,17 +159,15 @@ var document = { }, elements: {}, querySelector(id) { - if (!document.elements[id]) { - document.elements[id] = { - classList: { - add() {}, - remove() {}, - }, - eventListeners: {}, - addEventListener: document.addEventListener, - removeEventListener: document.removeEventListener, - callEventListeners: document.callEventListeners, - }; + document.elements[id] ||= { + classList: { + add() {}, + remove() {}, + }, + eventListeners: {}, + addEventListener: document.addEventListener, + removeEventListener: document.removeEventListener, + callEventListeners: document.callEventListeners, }; return document.elements[id]; }, @@ -214,7 +210,7 @@ var XMLHttpRequest = function() { } else { window.setTimeout(() => { this.doSend(); - if (this.onload) this.onload(); + this.onload?.(); }, 0); } }, @@ -239,7 +235,7 @@ var Image = () => { this.complete = true; this.width = 64; this.height = 64; - if (this.onload) this.onload(); + this.onload?.(); }); }; var Worker = (workerPath) => { @@ -252,7 +248,7 @@ var Worker = (workerPath) => { function duplicateJSON(json) { function handleTypedArrays(key, value) { - if (value && value.toString && value.toString().substring(0, 8) == '[object ' && value.length && value.byteLength) { + if (value?.toString && value.toString().substring(0, 8) == '[object ' && value.length && value.byteLength) { return Array.prototype.slice.call(value); } return value; @@ -293,6 +289,4 @@ if (typeof console == 'undefined') { } // additional setup -if (!Module['canvas']) { - Module['canvas'] = document.getElementById('canvas'); -} +Module['canvas'] ||= document.getElementById('canvas'); diff --git a/src/library.js b/src/library.js index e9fbd9b8180a8..c5d607c042af5 100644 --- a/src/library.js +++ b/src/library.js @@ -2394,7 +2394,7 @@ addToLibrary({ _emscripten_get_now_is_monotonic: () => nowIsMonotonic, $warnOnce: (text) => { - if (!warnOnce.shown) warnOnce.shown = {}; + warnOnce.shown ||= {}; if (!warnOnce.shown[text]) { warnOnce.shown[text] = 1; #if ENVIRONMENT_MAY_BE_NODE @@ -2474,7 +2474,7 @@ addToLibrary({ if (flags & {{{ cDefs.EM_LOG_C_STACK }}}) { var orig = emscripten_source_map.originalPositionFor({line: lineno, column: column}); - haveSourceMap = (orig && orig.source); + haveSourceMap = orig?.source; if (haveSourceMap) { if (flags & {{{ cDefs.EM_LOG_NO_PATHS }}}) { orig.source = orig.source.substring(orig.source.replace(/\\/g, "/").lastIndexOf('/')+1); diff --git a/src/library_browser.js b/src/library_browser.js index aaf20d7c5dd74..1f92242521ff4 100644 --- a/src/library_browser.js +++ b/src/library_browser.js @@ -95,7 +95,7 @@ var LibraryBrowser = { } } callUserCallback(func); - if (Module['postMainLoop']) Module['postMainLoop'](); + Module['postMainLoop']?.(); } }, isFullscreen: false, @@ -140,11 +140,11 @@ var LibraryBrowser = { ctx.drawImage(img, 0, 0); preloadedImages[name] = canvas; URL.revokeObjectURL(url); - if (onload) onload(byteArray); + onload?.(byteArray); }; img.onerror = (event) => { err(`Image ${url} could not be decoded`); - if (onerror) onerror(); + onerror?.(); }; img.src = url; }; @@ -160,13 +160,13 @@ var LibraryBrowser = { if (done) return; done = true; preloadedAudios[name] = audio; - if (onload) onload(byteArray); + onload?.(byteArray); } function fail() { if (done) return; done = true; preloadedAudios[name] = new Audio(); // empty shim - if (onerror) onerror(); + onerror?.(); } var b = new Blob([byteArray], { type: Browser.getMimetype(name) }); var url = URL.createObjectURL(b); // XXX we never revoke this! @@ -344,8 +344,8 @@ var LibraryBrowser = { Browser.updateCanvasDimensions(canvas); } } - if (Module['onFullScreen']) Module['onFullScreen'](Browser.isFullscreen); - if (Module['onFullscreen']) Module['onFullscreen'](Browser.isFullscreen); + Module['onFullScreen']?.(Browser.isFullscreen); + Module['onFullscreen']?.(Browser.isFullscreen); } if (!Browser.fullscreenHandlersInstalled) { @@ -459,10 +459,8 @@ var LibraryBrowser = { }, getUserMedia(func) { - if (!window.getUserMedia) { - window.getUserMedia = navigator['getUserMedia'] || + window.getUserMedia ||= navigator['getUserMedia'] || navigator['mozGetUserMedia']; - } window.getUserMedia(func); }, @@ -593,7 +591,7 @@ var LibraryBrowser = { Browser.touches[touch.identifier] = coords; } else if (event.type === 'touchend' || event.type === 'touchmove') { var last = Browser.touches[touch.identifier]; - if (!last) last = coords; + last ||= coords; Browser.lastTouches[touch.identifier] = last; Browser.touches[touch.identifier] = coords; } @@ -733,7 +731,7 @@ var LibraryBrowser = { {{{ runtimeKeepalivePush() }}} var _suffix = UTF8ToString(suffix); - if (!Browser.asyncPrepareDataCounter) Browser.asyncPrepareDataCounter = 0; + Browser.asyncPrepareDataCounter ||= 0; var name = 'prepare_data_' + (Browser.asyncPrepareDataCounter++) + '.' + _suffix; var cname = stringToNewUTF8(name); FS.createPreloadedFile( @@ -790,7 +788,7 @@ var LibraryBrowser = { var loadError = () => { {{{ runtimeKeepalivePop() }}} - if (onerror) onerror(); + onerror?.(); }; #if ENVIRONMENT_MAY_BE_NODE && DYNAMIC_EXECUTION diff --git a/src/library_ccall.js b/src/library_ccall.js index 05d96fb73bea4..0c73ff7ecaaaa 100644 --- a/src/library_ccall.js +++ b/src/library_ccall.js @@ -86,7 +86,7 @@ addToLibrary({ return convertReturnValue(ret); } #if ASYNCIFY - var asyncMode = opts && opts.async; + var asyncMode = opts?.async; #endif #if ASYNCIFY == 1 diff --git a/src/library_dylink.js b/src/library_dylink.js index 6ff94267606f6..d58a5ce866d3b 100644 --- a/src/library_dylink.js +++ b/src/library_dylink.js @@ -218,9 +218,7 @@ var LibraryDylink = { } #endif - if (!GOT[symName]) { - GOT[symName] = new WebAssembly.Global({'value': '{{{ POINTER_WASM_TYPE }}}', 'mutable': true}); - } + GOT[symName] ||= new WebAssembly.Global({'value': '{{{ POINTER_WASM_TYPE }}}', 'mutable': true}); if (replace || GOT[symName].value == 0) { #if DYLINK_DEBUG == 2 dbg(`updateGOT: before: ${symName} : ${GOT[symName].value}`); @@ -713,7 +711,7 @@ var LibraryDylink = { if (!(prop in stubs)) { var resolved; stubs[prop] = function() { - if (!resolved) resolved = resolveSymbol(prop); + resolved ||= resolveSymbol(prop); return resolved.apply(null, arguments); }; } @@ -898,9 +896,7 @@ var LibraryDylink = { dbg(`setDylinkStackLimits for '${name}'`); #endif var lib = LDSO.loadedLibsByName[name]; - if (lib.exports['__set_stack_limits']) { - lib.exports['__set_stack_limits']({{{ to64("stackTop") }}}, {{{ to64("stackMax") }}}); - } + lib.exports['__set_stack_limits']?.({{{ to64("stackTop") }}}, {{{ to64("stackMax") }}}); } }, #endif diff --git a/src/library_eventloop.js b/src/library_eventloop.js index b6a71bd07d7ff..8bbc0883074cf 100644 --- a/src/library_eventloop.js +++ b/src/library_eventloop.js @@ -24,7 +24,7 @@ LibraryJSEventLoop = { // Just like setImmediate but returns an i32 that can be passed back // to wasm rather than a JS object. $setImmediateWrapped: (func) => { - if (!setImmediateWrapped.mapping) setImmediateWrapped.mapping = []; + setImmediateWrapped.mapping ||= []; var id = setImmediateWrapped.mapping.length; setImmediateWrapped.mapping[id] = setImmediate(() => { setImmediateWrapped.mapping[id] = undefined; diff --git a/src/library_exceptions.js b/src/library_exceptions.js index d97e704149efd..bfe919e890fe5 100644 --- a/src/library_exceptions.js +++ b/src/library_exceptions.js @@ -228,7 +228,7 @@ var LibraryExceptions = { $findMatchingCatch: (args) => { var thrown = #if EXCEPTION_STACK_TRACES - exceptionLast && exceptionLast.excPtr; + exceptionLast?.excPtr; #else exceptionLast; #endif diff --git a/src/library_exports.js b/src/library_exports.js index 3bf963c490a00..385d3c684e4fb 100644 --- a/src/library_exports.js +++ b/src/library_exports.js @@ -16,7 +16,7 @@ addToLibrary({ // Record the created function pointer to each function object, // so that if the same function pointer is obtained several times, // the same address will be returned. - if (!exportedFunc.ptr) exportedFunc.ptr = addFunction(exportedFunc); + exportedFunc.ptr ||= addFunction(exportedFunc); return exportedFunc.ptr; } #if ASSERTIONS diff --git a/src/library_fs.js b/src/library_fs.js index b8df41f3683e2..aa917a19ce7fd 100644 --- a/src/library_fs.js +++ b/src/library_fs.js @@ -459,9 +459,7 @@ FS.staticInit();` + // override node's stream ops with the device's stream.stream_ops = device.stream_ops; // forward the open call - if (stream.stream_ops.open) { - stream.stream_ops.open(stream); - } + stream.stream_ops.open?.(stream); }, llseek() { throw new FS.ErrnoError({{{ cDefs.ESPIPE }}}); diff --git a/src/library_fs_shared.js b/src/library_fs_shared.js index 0e9426cc9f46f..cdc9d9ef5df11 100644 --- a/src/library_fs_shared.js +++ b/src/library_fs_shared.js @@ -57,16 +57,16 @@ addToLibrary({ var dep = getUniqueRunDependency(`cp ${fullname}`); // might have several active requests for the same fullname function processData(byteArray) { function finish(byteArray) { - if (preFinish) preFinish(); + preFinish?.(); if (!dontCreateFile) { FS_createDataFile(parent, name, byteArray, canRead, canWrite, canOwn); } - if (onload) onload(); + onload?.(); removeRunDependency(dep); } #if !MINIMAL_RUNTIME if (FS_handledByPreloadPlugin(byteArray, fullname, finish, () => { - if (onerror) onerror(); + onerror?.(); removeRunDependency(dep); })) { return; diff --git a/src/library_glemu.js b/src/library_glemu.js index 190f01b262490..79fea2fd87f88 100644 --- a/src/library_glemu.js +++ b/src/library_glemu.js @@ -559,7 +559,7 @@ var LibraryGLEmulation = { GL.programShaders = {}; var glAttachShader = _glAttachShader; _glAttachShader = _emscripten_glAttachShader = (program, shader) => { - if (!GL.programShaders[program]) GL.programShaders[program] = []; + GL.programShaders[program] ||= []; GL.programShaders[program].push(shader); glAttachShader(program, shader); }; @@ -1998,16 +1998,14 @@ var LibraryGLEmulation = { var attrib = GLImmediate.clientAttributes[name]; if (!attrib) { for (var i = 0; i <= name; i++) { // keep flat - if (!GLImmediate.clientAttributes[i]) { - GLImmediate.clientAttributes[i] = { - name, - size, - type, - stride, - pointer, - offset: 0 - }; - } + GLImmediate.clientAttributes[i] ||= { + name, + size, + type, + stride, + pointer, + offset: 0 + }; } } else { attrib.name = name; @@ -2925,7 +2923,7 @@ var LibraryGLEmulation = { #if GL_ASSERTIONS warnOnce('Rendering from planar client-side vertex arrays. This is a very slow emulation path! Use interleaved vertex arrays for best performance.'); #endif - if (!GLImmediate.restrideBuffer) GLImmediate.restrideBuffer = _malloc(GL.MAX_TEMP_BUFFER_SIZE); + GLImmediate.restrideBuffer ||= _malloc(GL.MAX_TEMP_BUFFER_SIZE); var start = GLImmediate.restrideBuffer; bytes = 0; // calculate restrided offsets and total size diff --git a/src/library_glew.js b/src/library_glew.js index bac564de9e8d8..14e907ee72b9e 100644 --- a/src/library_glew.js +++ b/src/library_glew.js @@ -99,9 +99,7 @@ var LibraryGLEW = { }, extensionIsSupported(name) { - if (!GLEW.extensions) { - GLEW.extensions = UTF8ToString(_glGetString(0x1F03)).split(' '); - } + GLEW.extensions ||= UTF8ToString(_glGetString(0x1F03)).split(' '); if (GLEW.extensions.includes(name)) return 1; diff --git a/src/library_glfw.js b/src/library_glfw.js index 6201cf8955a6c..6bb35a497bb96 100644 --- a/src/library_glfw.js +++ b/src/library_glfw.js @@ -653,7 +653,7 @@ var LibraryGLFW = { refreshJoysticks: () => { // Produce a new Gamepad API sample if we are ticking a new game frame, or if not using emscripten_set_main_loop() at all to drive animation. if (Browser.mainLoop.currentFrameNumber !== GLFW.lastGamepadStateFrame || !Browser.mainLoop.currentFrameNumber) { - GLFW.lastGamepadState = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads : []); + GLFW.lastGamepadState = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads || []); GLFW.lastGamepadStateFrame = Browser.mainLoop.currentFrameNumber; for (var joy = 0; joy < GLFW.lastGamepadState.length; ++joy) { @@ -1219,9 +1219,7 @@ var LibraryGLFW = { glfwExtensionSupported__deps: ['glGetString'], glfwExtensionSupported: (extension) => { - if (!GLFW.extensions) { - GLFW.extensions = UTF8ToString(_glGetString(0x1F03)).split(' '); - } + GLFW.extensions ||= UTF8ToString(_glGetString(0x1F03)).split(' '); if (GLFW.extensions.includes(extension)) return 1; @@ -1239,9 +1237,7 @@ var LibraryGLFW = { #if USE_GLFW == 3 glfwGetVersionString: () => { - if (!GLFW.versionString) { - GLFW.versionString = stringToNewUTF8("3.2.1 JS WebGL Emscripten"); - } + GLFW.versionString ||= stringToNewUTF8("3.2.1 JS WebGL Emscripten"); return GLFW.versionString; }, @@ -1295,9 +1291,7 @@ var LibraryGLFW = { }, glfwGetMonitorName: (mon) => { - if (!GLFW.monitorString) { - GLFW.monitorString = stringToNewUTF8("HTML5 WebGL Canvas"); - } + GLFW.monitorString ||= stringToNewUTF8("HTML5 WebGL Canvas"); return GLFW.monitorString; }, diff --git a/src/library_html5.js b/src/library_html5.js index 50f7a220f96e6..abbf7a458619b 100644 --- a/src/library_html5.js +++ b/src/library_html5.js @@ -234,7 +234,7 @@ var LibraryHTML5 = { if (!target) return ''; if (target == window) return '#window'; if (target == screen) return '#screen'; - return (target && target.nodeName) ? target.nodeName : ''; + return target?.nodeName || ''; }, fullscreenEnabled() { @@ -1070,7 +1070,7 @@ var LibraryHTML5 = { // If transitioning to windowed mode, report info about the element that just was fullscreen. var reportedElement = isFullscreen ? fullscreenElement : JSEvents.previousFullscreenElement; var nodeName = JSEvents.getNodeNameForTarget(reportedElement); - var id = (reportedElement && reportedElement.id) ? reportedElement.id : ''; + var id = reportedElement?.id || ''; stringToUTF8(nodeName, eventStruct + {{{ C_STRUCTS.EmscriptenFullscreenChangeEvent.nodeName }}}, {{{ cDefs.EM_HTML5_LONG_STRING_LEN_BYTES }}}); stringToUTF8(id, eventStruct + {{{ C_STRUCTS.EmscriptenFullscreenChangeEvent.id }}}, {{{ cDefs.EM_HTML5_LONG_STRING_LEN_BYTES }}}); {{{ makeSetValue('eventStruct', C_STRUCTS.EmscriptenFullscreenChangeEvent.elementWidth, 'reportedElement ? reportedElement.clientWidth : 0', 'i32') }}}; @@ -1550,7 +1550,7 @@ var LibraryHTML5 = { emscripten_enter_soft_fullscreen__proxy: 'sync', emscripten_enter_soft_fullscreen: (target, fullscreenStrategy) => { #if !DISABLE_DEPRECATED_FIND_EVENT_TARGET_BEHAVIOR - if (!target) target = '#canvas'; + target ||= '#canvas'; #endif target = findEventTarget(target); if (!target) return {{{ cDefs.EMSCRIPTEN_RESULT_UNKNOWN_TARGET }}}; @@ -1608,7 +1608,7 @@ var LibraryHTML5 = { emscripten_exit_soft_fullscreen__deps: ['$restoreOldWindowedStyle'], emscripten_exit_soft_fullscreen__proxy: 'sync', emscripten_exit_soft_fullscreen: () => { - if (restoreOldWindowedStyle) restoreOldWindowedStyle(); + restoreOldWindowedStyle?.(); restoreOldWindowedStyle = null; return {{{ cDefs.EMSCRIPTEN_RESULT_SUCCESS }}}; @@ -1655,7 +1655,7 @@ var LibraryHTML5 = { #endif {{{ makeSetValue('eventStruct', C_STRUCTS.EmscriptenPointerlockChangeEvent.isActive, 'isPointerlocked', 'i32') }}}; var nodeName = JSEvents.getNodeNameForTarget(pointerLockElement); - var id = (pointerLockElement && pointerLockElement.id) ? pointerLockElement.id : ''; + var id = pointerLockElement?.id || ''; stringToUTF8(nodeName, eventStruct + {{{ C_STRUCTS.EmscriptenPointerlockChangeEvent.nodeName }}}, {{{ cDefs.EM_HTML5_LONG_STRING_LEN_BYTES }}}); stringToUTF8(id, eventStruct + {{{ C_STRUCTS.EmscriptenPointerlockChangeEvent.id }}}, {{{ cDefs.EM_HTML5_LONG_STRING_LEN_BYTES }}}); }, @@ -2323,7 +2323,7 @@ var LibraryHTML5 = { if (!canvas.controlTransferredOffscreen) { #endif var autoResizeViewport = false; - if (canvas.GLctxObject && canvas.GLctxObject.GLctx) { + if (canvas.GLctxObject?.GLctx) { var prevViewport = canvas.GLctxObject.GLctx.getParameter(0xBA2 /* GL_VIEWPORT */); // TODO: Perhaps autoResizeViewport should only be true if FBO 0 is currently active? autoResizeViewport = (prevViewport[0] === 0 && prevViewport[1] === 0 && prevViewport[2] === canvas.width && prevViewport[3] === canvas.height); diff --git a/src/library_memfs.js b/src/library_memfs.js index 78bb247733348..7eac15d236ef8 100644 --- a/src/library_memfs.js +++ b/src/library_memfs.js @@ -16,55 +16,53 @@ addToLibrary({ // no supported throw new FS.ErrnoError({{{ cDefs.EPERM }}}); } - if (!MEMFS.ops_table) { - MEMFS.ops_table = { - dir: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - lookup: MEMFS.node_ops.lookup, - mknod: MEMFS.node_ops.mknod, - rename: MEMFS.node_ops.rename, - unlink: MEMFS.node_ops.unlink, - rmdir: MEMFS.node_ops.rmdir, - readdir: MEMFS.node_ops.readdir, - symlink: MEMFS.node_ops.symlink - }, - stream: { - llseek: MEMFS.stream_ops.llseek - } - }, - file: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr - }, - stream: { - llseek: MEMFS.stream_ops.llseek, - read: MEMFS.stream_ops.read, - write: MEMFS.stream_ops.write, - allocate: MEMFS.stream_ops.allocate, - mmap: MEMFS.stream_ops.mmap, - msync: MEMFS.stream_ops.msync - } + MEMFS.ops_table ||= { + dir: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr, + lookup: MEMFS.node_ops.lookup, + mknod: MEMFS.node_ops.mknod, + rename: MEMFS.node_ops.rename, + unlink: MEMFS.node_ops.unlink, + rmdir: MEMFS.node_ops.rmdir, + readdir: MEMFS.node_ops.readdir, + symlink: MEMFS.node_ops.symlink }, - link: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr, - readlink: MEMFS.node_ops.readlink - }, - stream: {} + stream: { + llseek: MEMFS.stream_ops.llseek + } + }, + file: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr }, - chrdev: { - node: { - getattr: MEMFS.node_ops.getattr, - setattr: MEMFS.node_ops.setattr - }, - stream: FS.chrdev_stream_ops + stream: { + llseek: MEMFS.stream_ops.llseek, + read: MEMFS.stream_ops.read, + write: MEMFS.stream_ops.write, + allocate: MEMFS.stream_ops.allocate, + mmap: MEMFS.stream_ops.mmap, + msync: MEMFS.stream_ops.msync } - }; - } + }, + link: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr, + readlink: MEMFS.node_ops.readlink + }, + stream: {} + }, + chrdev: { + node: { + getattr: MEMFS.node_ops.getattr, + setattr: MEMFS.node_ops.setattr + }, + stream: FS.chrdev_stream_ops + } + }; var node = FS.createNode(parent, name, mode, dev); if (FS.isDir(node.mode)) { node.node_ops = MEMFS.ops_table.dir.node; diff --git a/src/library_pthread.js b/src/library_pthread.js index b3d4d27199e4c..e39bdb989d71f 100644 --- a/src/library_pthread.js +++ b/src/library_pthread.js @@ -767,8 +767,8 @@ var LibraryPThread = { if (transferredCanvasNames == (-1 >>> 0)) transferredCanvasNames = '{{{ OFFSCREENCANVASES_TO_PTHREAD }}}'; else #endif - if (transferredCanvasNames) transferredCanvasNames = UTF8ToString(transferredCanvasNames).trim(); - if (transferredCanvasNames) transferredCanvasNames = transferredCanvasNames.split(','); + transferredCanvasNames &&= UTF8ToString(transferredCanvasNames).trim(); + transferredCanvasNames &&= transferredCanvasNames.split(','); #if GL_DEBUG dbg(`pthread_create: transferredCanvasNames="${transferredCanvasNames}"`); #endif diff --git a/src/library_sdl.js b/src/library_sdl.js index 9fd29009630b9..c0ef45cff3b04 100644 --- a/src/library_sdl.js +++ b/src/library_sdl.js @@ -1726,7 +1726,7 @@ var LibrarySDL = { if (title) { _emscripten_set_window_title(title); } - icon = icon && UTF8ToString(icon); + icon &&= UTF8ToString(icon); }, // TODO @@ -1747,9 +1747,7 @@ var LibrarySDL = { SDL_GetKeyName__proxy: 'sync', SDL_GetKeyName__deps: ['$stringToNewUTF8'], SDL_GetKeyName: (key) => { - if (!SDL.keyName) { - SDL.keyName = stringToNewUTF8('unknown key'); - } + SDL.keyName ||= stringToNewUTF8('unknown key'); return SDL.keyName; }, @@ -1800,9 +1798,7 @@ var LibrarySDL = { SDL_GetError__proxy: 'sync', SDL_GetError__deps: ['$stringToNewUTF8'], SDL_GetError: () => { - if (!SDL.errorMessage) { - SDL.errorMessage = stringToNewUTF8("unknown SDL-emscripten error"); - } + SDL.errorMessage ||= stringToNewUTF8("unknown SDL-emscripten error"); return SDL.errorMessage; }, @@ -2982,7 +2978,7 @@ var LibrarySDL = { return count; } var info = SDL.channels[channel]; - if (info && info.audio && !info.audio.paused) { + if (info?.audio && !info.audio.paused) { return 1; } return 0; @@ -2998,7 +2994,7 @@ var LibrarySDL = { } /** @type {{ audio: HTMLMediaElement }} */ var info = SDL.channels[channel]; - if (info && info.audio) { + if (info?.audio) { info.audio.pause(); } else { //err(`Mix_Pause: no sound found for channel: ${channel}`); @@ -3016,14 +3012,14 @@ var LibrarySDL = { return pausedCount; } var info = SDL.channels[channel]; - if (info && info.audio && info.audio.paused) { + if (info?.audio?.paused) { return 1; } return 0; }, Mix_PausedMusic__proxy: 'sync', - Mix_PausedMusic: () => (SDL.music.audio && SDL.music.audio.paused) ? 1 : 0, + Mix_PausedMusic: () => SDL.music.audio?.paused ? 1 : 0, // http://www.libsdl.org/projects/SDL_mixer/docs/SDL_mixer_33.html#SEC33 Mix_Resume__proxy: 'sync', @@ -3035,7 +3031,7 @@ var LibrarySDL = { return; } var info = SDL.channels[channel]; - if (info && info.audio) info.audio.play(); + if (info?.audio) info.audio.play(); }, // SDL TTF @@ -3294,7 +3290,7 @@ var LibrarySDL = { SDL_GL_SwapBuffers__proxy: 'sync', SDL_GL_SwapBuffers: () => { - if (Browser.doSwapBuffers) Browser.doSwapBuffers(); // in workers, this is used to send out a buffered frame + Browser.doSwapBuffers?.(); // in workers, this is used to send out a buffered frame }, // SDL 2 diff --git a/src/library_strings.js b/src/library_strings.js index 3e84803d258d5..d211460230d77 100644 --- a/src/library_strings.js +++ b/src/library_strings.js @@ -364,9 +364,7 @@ addToLibrary({ assert(typeof maxBytesToWrite == 'number', 'stringToUTF16(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); #endif // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. - if (maxBytesToWrite === undefined) { - maxBytesToWrite = 0x7FFFFFFF; - } + maxBytesToWrite ??= 0x7FFFFFFF; if (maxBytesToWrite < 2) return 0; maxBytesToWrite -= 2; // Null terminator. var startPtr = outPtr; @@ -439,9 +437,7 @@ addToLibrary({ assert(typeof maxBytesToWrite == 'number', 'stringToUTF32(str, outPtr, maxBytesToWrite) is missing the third parameter that specifies the length of the output buffer!'); #endif // Backwards compatibility: if max bytes is not specified, assume unsafe unbounded write is allowed. - if (maxBytesToWrite === undefined) { - maxBytesToWrite = 0x7FFFFFFF; - } + maxBytesToWrite ??= 0x7FFFFFFF; if (maxBytesToWrite < 4) return 0; var startPtr = outPtr; var endPtr = startPtr + maxBytesToWrite - 4; diff --git a/src/library_syscall.js b/src/library_syscall.js index d6744c804739d..2caa081a88efa 100644 --- a/src/library_syscall.js +++ b/src/library_syscall.js @@ -710,9 +710,7 @@ var SyscallsLibrary = { __syscall_getdents64__deps: ['$stringToUTF8'], __syscall_getdents64: (fd, dirp, count) => { var stream = SYSCALLS.getStreamFromFD(fd) - if (!stream.getdents) { - stream.getdents = FS.readdir(stream.path); - } + stream.getdents ||= FS.readdir(stream.path); var struct_size = {{{ C_STRUCTS.dirent.__size__ }}}; var pos = 0; diff --git a/src/library_wasi.js b/src/library_wasi.js index 860439fced02d..9551f69dcc1d7 100644 --- a/src/library_wasi.js +++ b/src/library_wasi.js @@ -29,7 +29,7 @@ var WasiLibrary = { PThread.terminateAllThreads(); #endif #if expectToReceiveOnModule('onExit') - if (Module['onExit']) Module['onExit'](code); + Module['onExit']?.(code); #endif ABORT = true; } @@ -551,7 +551,7 @@ var WasiLibrary = { }); }); #else - if (stream.stream_ops && stream.stream_ops.fsync) { + if (stream.stream_ops?.fsync) { return stream.stream_ops.fsync(stream); } return 0; // we can't do anything synchronously; the in-memory FS is already synced to diff --git a/src/library_wasmfs.js b/src/library_wasmfs.js index 34fcaf703ef3d..e2ca6ed4d2f9e 100644 --- a/src/library_wasmfs.js +++ b/src/library_wasmfs.js @@ -514,7 +514,7 @@ FS.init(); $FS_create__deps: ['$FS_mknod'], $FS_create: (path, mode) => { // Default settings copied from the legacy JS FS API. - mode = mode !== undefined ? mode : 438 /* 0666 */; + mode = mode ?? 438 /* 0666 */; mode &= {{{ cDefs.S_IALLUGO }}}; mode |= {{{ cDefs.S_IFREG }}}; return FS_mknod(path, mode, 0); @@ -542,7 +542,7 @@ FS.init(); $FS_mkdir__deps: ['_wasmfs_mkdir'], $FS_mkdir: (path, mode) => FS.handleError(withStackSave(() => { - mode = mode !== undefined ? mode : 511 /* 0777 */; + mode = mode ?? 511 /* 0777 */; var buffer = stringToUTF8OnStack(path); return __wasmfs_mkdir(buffer, mode); })), diff --git a/src/library_webgl.js b/src/library_webgl.js index 311fba64bd734..d3839045b0012 100644 --- a/src/library_webgl.js +++ b/src/library_webgl.js @@ -227,9 +227,7 @@ var LibraryGL = { // is remembered, and subsequent errors are discarded until the user has cleared the stored error by a call to glGetError(). recordError: function recordError(errorCode) { #if GL_TRACK_ERRORS - if (!GL.lastError) { - GL.lastError = errorCode; - } + GL.lastError ||= errorCode; #endif }, // Get a new ID for a texture/buffer/etc., while keeping the table dense and fast. Creation is fairly rare so it is worth optimizing lookups later. @@ -1047,7 +1045,7 @@ var LibraryGL = { #endif GL.currentContext = GL.contexts[contextHandle]; // Active Emscripten GL layer context object. - Module.ctx = GLctx = GL.currentContext && GL.currentContext.GLctx; // Active WebGL context object. + Module.ctx = GLctx = GL.currentContext?.GLctx; // Active WebGL context object. return !(contextHandle && !GLctx); }, @@ -1071,7 +1069,7 @@ var LibraryGL = { // code here, so that GLES2 code can operate without changing behavior. initExtensions: (context) => { // If this function is called without a specific context object, init the extensions of the currently active context. - if (!context) context = GL.currentContext; + context ||= GL.currentContext; if (context.initExtensionsDone) return; context.initExtensionsDone = true; diff --git a/src/library_websocket.js b/src/library_websocket.js index 25349b65f1a4b..4ea12baaa66e1 100644 --- a/src/library_websocket.js +++ b/src/library_websocket.js @@ -137,7 +137,7 @@ var LibraryWebSocket = { // if (thread == {{{ cDefs.EM_CALLBACK_THREAD_CONTEXT_CALLING_THREAD }}} || // (thread == _pthread_self()) return emscripten_websocket_set_onopen_callback_on_calling_thread(socketId, userData, callbackFunc); - if (!WS.socketEvent) WS.socketEvent = _malloc(1024); // TODO: sizeof(EmscriptenWebSocketCloseEvent), which is the largest event struct + WS.socketEvent ||= _malloc(1024); // TODO: sizeof(EmscriptenWebSocketCloseEvent), which is the largest event struct var socket = WS.sockets[socketId]; if (!socket) { @@ -163,7 +163,7 @@ var LibraryWebSocket = { emscripten_websocket_set_onerror_callback_on_thread__deps: ['$WS'], emscripten_websocket_set_onerror_callback_on_thread__proxy: 'sync', emscripten_websocket_set_onerror_callback_on_thread: (socketId, userData, callbackFunc, thread) => { - if (!WS.socketEvent) WS.socketEvent = _malloc(1024); // TODO: sizeof(EmscriptenWebSocketCloseEvent), which is the largest event struct + WS.socketEvent ||= _malloc(1024); // TODO: sizeof(EmscriptenWebSocketCloseEvent), which is the largest event struct var socket = WS.sockets[socketId]; if (!socket) { @@ -189,7 +189,7 @@ var LibraryWebSocket = { emscripten_websocket_set_onclose_callback_on_thread__deps: ['$WS', '$stringToUTF8'], emscripten_websocket_set_onclose_callback_on_thread__proxy: 'sync', emscripten_websocket_set_onclose_callback_on_thread: (socketId, userData, callbackFunc, thread) => { - if (!WS.socketEvent) WS.socketEvent = _malloc(1024); // TODO: sizeof(EmscriptenWebSocketCloseEvent), which is the largest event struct + WS.socketEvent ||= _malloc(1024); // TODO: sizeof(EmscriptenWebSocketCloseEvent), which is the largest event struct var socket = WS.sockets[socketId]; if (!socket) { @@ -218,7 +218,7 @@ var LibraryWebSocket = { emscripten_websocket_set_onmessage_callback_on_thread__deps: ['$WS', '$stringToNewUTF8', 'malloc', 'free'], emscripten_websocket_set_onmessage_callback_on_thread__proxy: 'sync', emscripten_websocket_set_onmessage_callback_on_thread: (socketId, userData, callbackFunc, thread) => { - if (!WS.socketEvent) WS.socketEvent = _malloc(1024); // TODO: sizeof(EmscriptenWebSocketCloseEvent), which is the largest event struct + WS.socketEvent ||= _malloc(1024); // TODO: sizeof(EmscriptenWebSocketCloseEvent), which is the largest event struct var socket = WS.sockets[socketId]; if (!socket) { diff --git a/src/library_workerfs.js b/src/library_workerfs.js index 2db3e9aa4cdbd..6e5ab3cf853d9 100644 --- a/src/library_workerfs.js +++ b/src/library_workerfs.js @@ -28,9 +28,7 @@ addToLibrary({ // are just their corresponding parts within their given path, // rather than incremental aggregates which include their parent's // directories. - if (!createdParents[curr]) { - createdParents[curr] = WORKERFS.createNode(parent, parts[i], WORKERFS.DIR_MODE, 0); - } + createdParents[curr] ||= WORKERFS.createNode(parent, parts[i], WORKERFS.DIR_MODE, 0); parent = createdParents[curr]; } return parent; diff --git a/src/memoryprofiler.js b/src/memoryprofiler.js index 7008abae839bc..d42cbeaabbc08 100644 --- a/src/memoryprofiler.js +++ b/src/memoryprofiler.js @@ -190,7 +190,7 @@ var emscriptenMemoryProfiler = { if (!self.pagePreRunIsFinished) self.sizeOfPreRunAllocatedPtr[ptr] = size; var loc = new Error().stack.toString(); - if (!self.allocationsAtLoc[loc]) self.allocationsAtLoc[loc] = [0, 0, self.filterCallstackForMalloc(loc)]; + self.allocationsAtLoc[loc] ||= [0, 0, self.filterCallstackForMalloc(loc)]; self.allocationsAtLoc[loc][0] += 1; self.allocationsAtLoc[loc][1] += size; self.allocationSitePtrs[ptr] = loc; @@ -247,7 +247,7 @@ var emscriptenMemoryProfiler = { emscriptenMemoryProfiler.recordStackWatermark(); // Add a tracking mechanism to detect when VFS loading is complete. - if (!Module['preRun']) Module['preRun'] = []; + Module['preRun'] ||= []; Module['preRun'].push(emscriptenMemoryProfiler.onPreloadComplete); if (emscriptenMemoryProfiler.hookStackAlloc && typeof stackAlloc == 'function') { @@ -563,9 +563,7 @@ var emscriptenMemoryProfiler = { stack = self.filterCallstackAfterFunctionName(stack, s); } sbrk.filteredStack = stack; - if (!uniqueSources[stack]) { - uniqueSources[stack] = self.hsvToRgb(Object.keys(uniqueSources).length * 0.618033988749895 % 1, 0.5, 0.95); - } + uniqueSources[stack] ||= self.hsvToRgb(Object.keys(uniqueSources).length * 0.618033988749895 % 1, 0.5, 0.95); self.drawContext.fillStyle = sbrk.color = uniqueSources[stack]; self.fillRect(sbrk.begin, sbrk.end, 0.25); } diff --git a/src/parseTools.js b/src/parseTools.js index 053d5d7d0b64c..2252a59fa95c3 100644 --- a/src/parseTools.js +++ b/src/parseTools.js @@ -766,7 +766,7 @@ function isSymbolNeeded(symName) { function makeRemovedModuleAPIAssert(moduleName, localName) { if (!ASSERTIONS) return ''; - if (!localName) localName = moduleName; + localName ||= moduleName; return `legacyModuleProp('${moduleName}', '${localName}');`; } @@ -778,7 +778,7 @@ function checkReceiving(name) { // Make code to receive a value on the incoming Module object. function makeModuleReceive(localName, moduleName) { - if (!moduleName) moduleName = localName; + moduleName ||= localName; checkReceiving(moduleName); let ret = ''; if (expectToReceiveOnModule(moduleName)) { @@ -800,7 +800,7 @@ function makeModuleReceiveExpr(name, defaultValue) { } function makeModuleReceiveWithVar(localName, moduleName, defaultValue, noAssert) { - if (!moduleName) moduleName = localName; + moduleName ||= localName; checkReceiving(moduleName); let ret = `var ${localName}`; if (!expectToReceiveOnModule(moduleName)) { diff --git a/src/polyfill/bigint64array.js b/src/polyfill/bigint64array.js index 5828b609bad9d..e237e19d2224c 100644 --- a/src/polyfill/bigint64array.js +++ b/src/polyfill/bigint64array.js @@ -39,9 +39,7 @@ if (typeof globalThis.BigInt64Array === "undefined") { var proxy = new Proxy( { slice(min, max) { - if (max === undefined) { - max = array.length; - } + max ??= array.length; var new_buf = array.slice(min * 2, max * 2); return createBigInt64Array(new_buf); }, @@ -64,9 +62,7 @@ if (typeof globalThis.BigInt64Array === "undefined") { return proxy; }, set(source, targetOffset) { - if (targetOffset === undefined) { - targetOffset = 0; - } + targetOffset ??= 0; if (2 * (source.length + targetOffset) > array.length) { // This is the Chrome error message // Firefox: "invalid or out-of-range index" diff --git a/src/preamble.js b/src/preamble.js index a368db2c43615..4a3cc26c0f66d 100644 --- a/src/preamble.js +++ b/src/preamble.js @@ -361,9 +361,7 @@ function addRunDependency(id) { runDependencies++; #if expectToReceiveOnModule('monitorRunDependencies') - if (Module['monitorRunDependencies']) { - Module['monitorRunDependencies'](runDependencies); - } + Module['monitorRunDependencies']?.(runDependencies); #endif #if ASSERTIONS @@ -401,9 +399,7 @@ function removeRunDependency(id) { runDependencies--; #if expectToReceiveOnModule('monitorRunDependencies') - if (Module['monitorRunDependencies']) { - Module['monitorRunDependencies'](runDependencies); - } + Module['monitorRunDependencies']?.(runDependencies); #endif #if ASSERTIONS @@ -430,9 +426,7 @@ function removeRunDependency(id) { /** @param {string|number=} what */ function abort(what) { #if expectToReceiveOnModule('onAbort') - if (Module['onAbort']) { - Module['onAbort'](what); - } + Module['onAbort']?.(what); #endif what = 'Aborted(' + what + ')'; @@ -762,9 +756,7 @@ function instantiateSync(file, info) { } } } - if (!module) { - module = new WebAssembly.Module(binary); - } + module ||= new WebAssembly.Module(binary); if (ENVIRONMENT_IS_NODE && !hasCached) { #if RUNTIME_DEBUG dbg('NODE_CODE_CACHING: saving module'); diff --git a/src/proxyClient.js b/src/proxyClient.js index 80c7a3392e126..49c3f1c9eab81 100644 --- a/src/proxyClient.js +++ b/src/proxyClient.js @@ -134,9 +134,7 @@ var SUPPORT_BASE64_EMBEDDING; // Worker var filename; -if (!filename) { - filename = '<<< filename >>>'; -} +filename ||= '<<< filename >>>'; var workerURL = filename; if (SUPPORT_BASE64_EMBEDDING) { @@ -174,7 +172,7 @@ worker.onmessage = (event) => { //dump('\nclient got ' + JSON.stringify(event.data).substr(0, 150) + '\n'); if (!workerResponded) { workerResponded = true; - if (Module.setStatus) Module.setStatus(''); + Module.setStatus?.(''); if (SUPPORT_BASE64_EMBEDDING && workerURL !== filename) URL.revokeObjectURL(workerURL); } @@ -205,7 +203,7 @@ worker.onmessage = (event) => { case 'resize': { Module.canvas.width = data.width; Module.canvas.height = data.height; - if (Module.ctx && Module.ctx.getImageData) Module.canvasData = Module.ctx.getImageData(0, 0, data.width, data.height); + if (Module.ctx?.getImageData) Module.canvasData = Module.ctx.getImageData(0, 0, data.width, data.height); worker.postMessage({ target: 'canvas', boundingClientRect: cloneObject(Module.canvas.getBoundingClientRect()) }); break; } diff --git a/src/proxyWorker.js b/src/proxyWorker.js index 341d85e26aa67..c48f5af7d15a5 100644 --- a/src/proxyWorker.js +++ b/src/proxyWorker.js @@ -65,7 +65,7 @@ function EventListener() { this.listeners = {}; this.addEventListener = function addEventListener(event, func) { - if (!this.listeners[event]) this.listeners[event] = []; + this.listeners[event] ||= []; this.listeners[event].push(func); }; @@ -211,8 +211,8 @@ document.createElement = (what) => { canvas.style = new PropertyBag(); canvas.exitPointerLock = () => {}; - canvas.width_ = canvas.width_ || 0; - canvas.height_ = canvas.height_ || 0; + canvas.width_ ||= 0; + canvas.height_ ||= 0; Object.defineProperty(canvas, 'width', { set: (value) => { canvas.width_ = value; @@ -344,7 +344,7 @@ var clientFrameId = 0; var postMainLoop = Module['postMainLoop']; Module['postMainLoop'] = () => { - if (postMainLoop) postMainLoop(); + postMainLoop?.(); // frame complete, send a frame id postMessage({ target: 'tick', id: frameId++ }); commandBuffer = []; @@ -372,7 +372,7 @@ var messageResenderTimeout = null; var calledMain = false; // Set calledMain to true during postRun which happens onces main returns -if (!Module['postRun']) Module['postRun'] = []; +Module['postRun'] ||= []; if (typeof Module['postRun'] == 'function') Module['postRun'] = [Module['postRun']]; Module['postRun'].push(() => { calledMain = true; }); diff --git a/src/runtime_math.js b/src/runtime_math.js index 9a14fd5afe5c9..6bc3658001682 100644 --- a/src/runtime_math.js +++ b/src/runtime_math.js @@ -27,7 +27,7 @@ if (!Math.fround) { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/clz32 #if POLYFILL_OLD_MATH_FUNCTIONS || MIN_CHROME_VERSION < 38 || MIN_EDGE_VERSION < 12 || MIN_FIREFOX_VERSION < 31 || MIN_IE_VERSION != TARGET_NOT_SUPPORTED // || MIN_NODE_VERSION < 0.12 -if (!Math.clz32) Math.clz32 = (x) => { +Math.clz32 ||= (x) => { var n = 32; var y = x >> 16; if (y) { n -= 16; x = y; } y = x >> 8; if (y) { n -= 8; x = y; } @@ -40,7 +40,7 @@ if (!Math.clz32) Math.clz32 = (x) => { // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/trunc #if POLYFILL_OLD_MATH_FUNCTIONS || MIN_CHROME_VERSION < 38 || MIN_EDGE_VERSION < 12 || MIN_FIREFOX_VERSION < 25 || MIN_IE_VERSION != TARGET_NOT_SUPPORTED || MIN_SAFARI_VERSION < 80000 // || MIN_NODE_VERSION < 0.12 -if (!Math.trunc) Math.trunc = (x) => { +Math.trunc ||= (x) => { return x < 0 ? Math.ceil(x) : Math.floor(x); }; #endif diff --git a/src/settings.js b/src/settings.js index 4109dcfbd80c6..5764f26d97f8c 100644 --- a/src/settings.js +++ b/src/settings.js @@ -1768,10 +1768,10 @@ var AUTO_NATIVE_LIBRARIES = true; // versions >= MIN_FIREFOX_VERSION // are desired to work. Pass -sMIN_FIREFOX_VERSION=majorVersion to drop support // for Firefox versions older than < majorVersion. -// Firefox ESR 68 was released on July 9, 2019. +// Firefox 79 was released on 2020-07-28. // MAX_INT (0x7FFFFFFF, or -1) specifies that target is not supported. // [link] -var MIN_FIREFOX_VERSION = 68; +var MIN_FIREFOX_VERSION = 79; // Specifies the oldest version of desktop Safari to target. Version is encoded // in MMmmVV, e.g. 70101 denotes Safari 7.1.1. @@ -1810,10 +1810,10 @@ var MIN_EDGE_VERSION = 0x7FFFFFFF; // Specifies the oldest version of Chrome. E.g. pass -sMIN_CHROME_VERSION=58 to // drop support for Chrome 57 and older. -// Chrome 75.0.3770 was released on 2019-06-04 +// Chrome 85 was released on 2020-08-25. // MAX_INT (0x7FFFFFFF, or -1) specifies that target is not supported. // [link] -var MIN_CHROME_VERSION = 75; +var MIN_CHROME_VERSION = 85; // Specifies minimum node version to target for the generated code. This is // distinct from the minimum version required run the emscripten compiler. diff --git a/src/utility.js b/src/utility.js index 062559ce37f46..b0919790b9de6 100644 --- a/src/utility.js +++ b/src/utility.js @@ -67,7 +67,7 @@ function warnOnce(a, msg) { a = false; } if (!a) { - if (!warnOnce.msgs) warnOnce.msgs = {}; + warnOnce.msgs ||= {}; if (msg in warnOnce.msgs) return; warnOnce.msgs[msg] = true; warn(msg); @@ -247,7 +247,7 @@ function Benchmarker() { } lastTime = now; ids.push(id); - totals[id] = totals[id] || 0; + totals[id] ||= 0; }; this.stop = function(id) { const now = Date.now(); diff --git a/src/worker.js b/src/worker.js index 2fbadcfa61991..3a863ffaf0ef2 100644 --- a/src/worker.js +++ b/src/worker.js @@ -271,11 +271,9 @@ function handleMessage(e) { } catch(ex) { #if ASSERTIONS err(`worker.js onmessage() captured an uncaught exception: ${ex}`); - if (ex && ex.stack) err(ex.stack); + if (ex?.stack) err(ex.stack); #endif - if (Module['__emscripten_thread_crashed']) { - Module['__emscripten_thread_crashed'](); - } + Module['__emscripten_thread_crashed']?.(); throw ex; } }; diff --git a/test/code_size/hello_webgl2_wasm.json b/test/code_size/hello_webgl2_wasm.json index ec49d4dc16710..d2a834be28519 100644 --- a/test/code_size/hello_webgl2_wasm.json +++ b/test/code_size/hello_webgl2_wasm.json @@ -1,10 +1,10 @@ { "a.html": 569, "a.html.gz": 379, - "a.js": 4700, + "a.js": 4698, "a.js.gz": 2417, "a.wasm": 10467, "a.wasm.gz": 6706, - "total": 15736, + "total": 15734, "total_gz": 9502 } diff --git a/test/code_size/hello_webgl2_wasm2js.json b/test/code_size/hello_webgl2_wasm2js.json index 4122c5c210f7f..e1392aadbf5e6 100644 --- a/test/code_size/hello_webgl2_wasm2js.json +++ b/test/code_size/hello_webgl2_wasm2js.json @@ -1,10 +1,10 @@ { "a.html": 567, "a.html.gz": 379, - "a.js": 17913, - "a.js.gz": 8063, + "a.js": 17910, + "a.js.gz": 8064, "a.mem": 3171, "a.mem.gz": 2713, - "total": 21651, - "total_gz": 11155 + "total": 21648, + "total_gz": 11156 } diff --git a/test/code_size/hello_webgl_wasm.json b/test/code_size/hello_webgl_wasm.json index c8b509c537ba2..a0db530fedb04 100644 --- a/test/code_size/hello_webgl_wasm.json +++ b/test/code_size/hello_webgl_wasm.json @@ -1,10 +1,10 @@ { "a.html": 569, "a.html.gz": 379, - "a.js": 4186, - "a.js.gz": 2244, + "a.js": 4184, + "a.js.gz": 2242, "a.wasm": 10467, "a.wasm.gz": 6706, - "total": 15222, - "total_gz": 9329 + "total": 15220, + "total_gz": 9327 } diff --git a/test/code_size/hello_webgl_wasm2js.json b/test/code_size/hello_webgl_wasm2js.json index fda6e750793f0..133af5e84692a 100644 --- a/test/code_size/hello_webgl_wasm2js.json +++ b/test/code_size/hello_webgl_wasm2js.json @@ -1,10 +1,10 @@ { "a.html": 567, "a.html.gz": 379, - "a.js": 17391, - "a.js.gz": 7890, + "a.js": 17388, + "a.js.gz": 7887, "a.mem": 3171, "a.mem.gz": 2713, - "total": 21129, - "total_gz": 10982 + "total": 21126, + "total_gz": 10979 } diff --git a/test/other/test_unoptimized_code_size.js.size b/test/other/test_unoptimized_code_size.js.size index 59516e21ec507..70bb62401f9ad 100644 --- a/test/other/test_unoptimized_code_size.js.size +++ b/test/other/test_unoptimized_code_size.js.size @@ -1 +1 @@ -58305 +59815 diff --git a/test/other/test_unoptimized_code_size_no_asserts.js.size b/test/other/test_unoptimized_code_size_no_asserts.js.size index f90fb8fd192b6..442711b3ea4c7 100644 --- a/test/other/test_unoptimized_code_size_no_asserts.js.size +++ b/test/other/test_unoptimized_code_size_no_asserts.js.size @@ -1 +1 @@ -31702 +32503 diff --git a/test/other/test_unoptimized_code_size_strict.js.size b/test/other/test_unoptimized_code_size_strict.js.size index f7b4552c30211..1e88428ebf643 100644 --- a/test/other/test_unoptimized_code_size_strict.js.size +++ b/test/other/test_unoptimized_code_size_strict.js.size @@ -1 +1 @@ -57018 +58622 diff --git a/tools/acorn-optimizer.js b/tools/acorn-optimizer.js index 8260ec601112b..2d97919f7959c 100755 --- a/tools/acorn-optimizer.js +++ b/tools/acorn-optimizer.js @@ -1044,7 +1044,7 @@ function applyDCEGraphRemovals(ast) { // Need a parser to pass to acorn.Node constructor. // Create it once and reuse it. -const stubParser = new acorn.Parser({ecmaVersion: 2020}); +const stubParser = new acorn.Parser({ecmaVersion: 2021}); function createNode(props) { const node = new acorn.Node(stubParser); @@ -2008,7 +2008,7 @@ let ast; try { ast = acorn.parse(input, { // Keep in sync with --language_in that we pass to closure in building.py - ecmaVersion: 2020, + ecmaVersion: 2021, preserveParens: closureFriendly, onComment: closureFriendly ? sourceComments : undefined, sourceType: exportES6 ? 'module' : 'script', diff --git a/tools/building.py b/tools/building.py index 7f063bffb07c1..c24f1c41c6fdf 100644 --- a/tools/building.py +++ b/tools/building.py @@ -567,7 +567,7 @@ def closure_compiler(filename, advanced=True, extra_closure_args=None): args = ['--compilation_level', 'ADVANCED_OPTIMIZATIONS' if advanced else 'SIMPLE_OPTIMIZATIONS'] # Keep in sync with ecmaVersion in tools/acorn-optimizer.js - args += ['--language_in', 'ECMASCRIPT_2020'] + args += ['--language_in', 'ECMASCRIPT_2021'] # Tell closure not to do any transpiling or inject any polyfills. # At some point we may want to look into using this as way to convert to ES5 but # babel is perhaps a better tool for that. diff --git a/tools/unsafe_optimizations.js b/tools/unsafe_optimizations.js index 41641f93499d3..45e8d01c3545b 100644 --- a/tools/unsafe_optimizations.js +++ b/tools/unsafe_optimizations.js @@ -223,7 +223,7 @@ function optPassMergeVarInitializationAssignments(ast) { } function runOnJsText(js, pretty = false) { - const ast = acorn.parse(js, {ecmaVersion: 2020}); + const ast = acorn.parse(js, {ecmaVersion: 2021}); optPassSimplifyModuleInitialization(ast); optPassRemoveRedundantOperatorNews(ast);